diff --git a/.gitignore b/.gitignore index f5bd1e41..70c69686 100644 --- a/.gitignore +++ b/.gitignore @@ -19,6 +19,8 @@ Thumbs.db ##################### *.gch *.out +Cmake-build-debug/ +Cmake-build-release/ ########################## # Jetbrains Ignore files # @@ -26,3 +28,5 @@ Thumbs.db *.iml .idea/ +old/ + diff --git a/0001-0500/0001-Two-Sum/cpp-0001/CMakeLists.txt b/0001-0500/0001-Two-Sum/cpp-0001/CMakeLists.txt new file mode 100644 index 00000000..3a29ec8c --- /dev/null +++ b/0001-0500/0001-Two-Sum/cpp-0001/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0001) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0001 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0001-Two-Sum/cpp-0001/main.cpp b/0001-0500/0001-Two-Sum/cpp-0001/main.cpp new file mode 100644 index 00000000..6119d8f8 --- /dev/null +++ b/0001-0500/0001-Two-Sum/cpp-0001/main.cpp @@ -0,0 +1,41 @@ +/// Source : https://leetcode.com/problems/two-sum/description/ +/// Author : liuyubobobo +/// Time : 2017-11-15 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n^2) +/// Space Complexity: O(1) +class Solution { +public: + vector twoSum(vector& nums, int target) { + + for(int i = 0 ; i < nums.size() ; i ++) + for(int j = i + 1 ; j < nums.size() ; j ++) + if(nums[i] + nums[j] == target) + return {i, j}; + + throw invalid_argument("the input has no solution"); + } +}; + + +void print_vec(const vector& vec){ + for(int e: vec) + cout << e << " "; + cout << endl; +} + +int main() { + + vector nums = {0,4,3,5}; + int target = 10; + print_vec(Solution().twoSum(nums, target)); + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0001-Two-Sum/cpp-0001/main2.cpp b/0001-0500/0001-Two-Sum/cpp-0001/main2.cpp new file mode 100644 index 00000000..36235dae --- /dev/null +++ b/0001-0500/0001-Two-Sum/cpp-0001/main2.cpp @@ -0,0 +1,55 @@ +/// Source : https://leetcode.com/problems/two-sum/description/ +/// Author : liuyubobobo +/// Time : 2017-11-15 + +#include +#include +#include +#include + +using namespace std; + + +/// Two-Pass Hash Table +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector twoSum(vector& nums, int target) { + + unordered_map record; + for(int i = 0 ; i < nums.size() ; i ++) + record[nums[i]] = i; + + for(int i = 0 ; i < nums.size() ; i ++){ + unordered_map::iterator iter = record.find(target - nums[i]); + if(iter != record.end() && iter->second != i) + return {i, iter->second}; + } + + throw invalid_argument("the input has no solution"); + } +}; + + +void print_vec(const vector& vec){ + for(int e: vec) + cout << e << " "; + cout << endl; +} + + +void print_vec(const vector& vec){ + for(int e: vec) + cout << e << " "; + cout << endl; +} + +int main() { + + vector nums = {0,4,3,0}; + int target = 0; + print_vec(Solution().twoSum(nums, target)); + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0001-Two-Sum/cpp-0001/main3.cpp b/0001-0500/0001-Two-Sum/cpp-0001/main3.cpp new file mode 100644 index 00000000..197a91e0 --- /dev/null +++ b/0001-0500/0001-Two-Sum/cpp-0001/main3.cpp @@ -0,0 +1,51 @@ +/// Source : https://leetcode.com/problems/two-sum/description/ +/// Author : liuyubobobo +/// Time : 2017-11-15 + +#include +#include +#include +#include + +using namespace std; + + +/// One-Pass Hash Table +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector twoSum(vector& nums, int target) { + + unordered_map record; + for(int i = 0 ; i < nums.size() ; i ++){ + + int complement = target - nums[i]; + if(record.find(complement) != record.end()){ + int res[] = {i, record[complement]}; + return vector(res, res + 2); + } + + record[nums[i]] = i; + } + + throw invalid_argument("the input has no solution"); + } +}; + + +void print_vec(const vector& vec){ + for(int e: vec) + cout << e << " "; + cout << endl; +} + +int main() { + + const int nums[] = {0,4,3,0}; + vector nums_vec( nums, nums + sizeof(nums)/sizeof(int) ); + int target = 0; + print_vec(Solution().twoSum(nums_vec, target)); + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0001-Two-Sum/java-0001/src/Solution1.java b/0001-0500/0001-Two-Sum/java-0001/src/Solution1.java new file mode 100644 index 00000000..d9ce20f2 --- /dev/null +++ b/0001-0500/0001-Two-Sum/java-0001/src/Solution1.java @@ -0,0 +1,36 @@ +/// Source : https://leetcode.com/problems/two-sum/description/ +/// Author : liuyubobobo +/// Time : 2017-11-15 + +import java.util.HashMap; + +/// Brute Force +/// Time Complexity: O(n^2) +/// Space Complexity: O(1) +public class Solution1 { + + public int[] twoSum(int[] nums, int target) { + + for(int i = 0 ; i < nums.length; i ++) + for(int j = i + 1 ; j < nums.length ; j ++) + if(nums[i] + nums[j] == target){ + int[] res = {i, j}; + return res; + } + + throw new IllegalStateException("the input has no solution"); + } + + private static void printArr(int[] nums){ + for(int num: nums) + System.out.print(num + " "); + System.out.println(); + } + + public static void main(String[] args) { + + int[] nums = {0, 4, 3, 0}; + int target = 0; + printArr((new Solution1()).twoSum(nums, target)); + } +} diff --git a/0001-0500/0001-Two-Sum/java-0001/src/Solution2.java b/0001-0500/0001-Two-Sum/java-0001/src/Solution2.java new file mode 100644 index 00000000..a8374941 --- /dev/null +++ b/0001-0500/0001-Two-Sum/java-0001/src/Solution2.java @@ -0,0 +1,43 @@ +/// Source : https://leetcode.com/problems/two-sum/description/ +/// Author : liuyubobobo +/// Time : 2017-11-15 +/// Updated: 2018-12-28 + +import java.util.HashMap; + +/// Two-Pass Hash Table +/// Time Complexity: O(n) +/// Space Complexity: O(n) +public class Solution2 { + + public int[] twoSum(int[] nums, int target) { + + HashMap record = new HashMap(); + for(int i = 0 ; i < nums.length ; i ++) + record.put(nums[i], i); + + for(int i = 0 ; i < nums.length; i ++){ + + Integer index = record.get(target - nums[i]); + if(index != null && index != i){ + int[] res = {i, index}; + return res; + } + } + + throw new IllegalStateException("the input has no solution"); + } + + private static void printArr(int[] nums){ + for(int num: nums) + System.out.print(num + " "); + System.out.println(); + } + + public static void main(String[] args) { + + int[] nums = {0, 4, 3, 0}; + int target = 0; + printArr((new Solution2()).twoSum(nums, target)); + } +} diff --git a/0001-Two-Sum/java-0001/src/Solution3.java b/0001-0500/0001-Two-Sum/java-0001/src/Solution3.java similarity index 100% rename from 0001-Two-Sum/java-0001/src/Solution3.java rename to 0001-0500/0001-Two-Sum/java-0001/src/Solution3.java diff --git a/0001-0500/0002-Add-Two-Numbers/cpp-0002/CMakeLists.txt b/0001-0500/0002-Add-Two-Numbers/cpp-0002/CMakeLists.txt new file mode 100644 index 00000000..3a14c42c --- /dev/null +++ b/0001-0500/0002-Add-Two-Numbers/cpp-0002/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0002) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main2.cpp) +add_executable(cpp_0002 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0002-Add-Two-Numbers/cpp-0002/main.cpp b/0001-0500/0002-Add-Two-Numbers/cpp-0002/main.cpp new file mode 100644 index 00000000..03fa1208 --- /dev/null +++ b/0001-0500/0002-Add-Two-Numbers/cpp-0002/main.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/add-two-numbers/description/ +/// Author : liuyubobobo +/// Time : 2018-08-09 + +#include + +using namespace std; + +/// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} +}; + + +/// Create new LinkedList for result +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { + + ListNode *p1 = l1, *p2 = l2; + ListNode *dummyHead = new ListNode(-1); + ListNode* cur = dummyHead; + int carried = 0; + while(p1 || p2 ){ + int a = p1 ? p1->val : 0; + int b = p2 ? p2->val : 0; + cur->next = new ListNode((a + b + carried) % 10); + carried = (a + b + carried) / 10; + + cur = cur->next; + p1 = p1 ? p1->next : NULL; + p2 = p2 ? p2->next : NULL; + } + + cur->next = carried ? new ListNode(1) : NULL; + ListNode* ret = dummyHead->next; + delete dummyHead; + return ret; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0002-Add-Two-Numbers/cpp-0002/main2.cpp b/0001-0500/0002-Add-Two-Numbers/cpp-0002/main2.cpp new file mode 100644 index 00000000..cdd669bd --- /dev/null +++ b/0001-0500/0002-Add-Two-Numbers/cpp-0002/main2.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/add-two-numbers/description/ +/// Author : liuyubobobo +/// Time : 2018-08-09 + +#include + +using namespace std; + +/// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} +}; + + +/// Using l1 as the result list +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +public: + ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { + + ListNode *p1 = l1, *p2 = l2; + ListNode* pre = NULL; + int carried = 0; + + while(p1 || p2){ + int a = p1 ? p1->val : 0; + int b = p2 ? p2->val : 0; + if(p1) + p1->val = (a + b + carried) % 10; + else{ + pre->next = new ListNode((a + b + carried) % 10); + p1 = pre->next; + } + carried = (a + b + carried) / 10; + + pre = p1; + p1 = p1->next; + if(p2) p2 = p2->next; + } + + pre->next = carried ? new ListNode(1) : NULL; + return l1; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0002-Add-Two-Numbers/cpp-0002/main3.cpp b/0001-0500/0002-Add-Two-Numbers/cpp-0002/main3.cpp new file mode 100644 index 00000000..116d4185 --- /dev/null +++ b/0001-0500/0002-Add-Two-Numbers/cpp-0002/main3.cpp @@ -0,0 +1,59 @@ +/// Source : https://leetcode.com/problems/add-two-numbers/description/ +/// Author : liuyubobobo +/// Time : 2018-08-09 + +#include + +using namespace std; + +/// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} +}; + + +/// Using the longest list in l1 and l2 as the result list +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { + +public: + ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { + + int len1 = getLen(l1), len2 = getLen(l2); + ListNode *p1 = len1 > len2 ? l1 : l2; + ListNode *p2 = len1 > len2 ? l2 : l1; + + ListNode* pre = NULL; + int carried = 0; + while(p1){ + int a = p1->val; + int b = p2 ? p2->val : 0; + p1->val = (a + b + carried) % 10; + carried = (a + b + carried) / 10; + + pre = p1; + p1 = p1->next; + p2 = p2 ? p2->next : NULL; + } + + pre->next = carried ? new ListNode(1) : NULL; + return len1 > len2 ? l1 : l2; + } + +private: + int getLen(ListNode* l){ + int res = 0; + while(l) + res ++, l = l -> next; + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0003-Longest-Substring-Without-Repeating-Characters/cpp-0003/CMakeLists.txt b/0001-0500/0003-Longest-Substring-Without-Repeating-Characters/cpp-0003/CMakeLists.txt similarity index 100% rename from 0003-Longest-Substring-Without-Repeating-Characters/cpp-0003/CMakeLists.txt rename to 0001-0500/0003-Longest-Substring-Without-Repeating-Characters/cpp-0003/CMakeLists.txt diff --git a/0003-Longest-Substring-Without-Repeating-Characters/cpp-0003/main.cpp b/0001-0500/0003-Longest-Substring-Without-Repeating-Characters/cpp-0003/main.cpp similarity index 100% rename from 0003-Longest-Substring-Without-Repeating-Characters/cpp-0003/main.cpp rename to 0001-0500/0003-Longest-Substring-Without-Repeating-Characters/cpp-0003/main.cpp diff --git a/0003-Longest-Substring-Without-Repeating-Characters/cpp-0003/main2.cpp b/0001-0500/0003-Longest-Substring-Without-Repeating-Characters/cpp-0003/main2.cpp similarity index 100% rename from 0003-Longest-Substring-Without-Repeating-Characters/cpp-0003/main2.cpp rename to 0001-0500/0003-Longest-Substring-Without-Repeating-Characters/cpp-0003/main2.cpp diff --git a/0003-Longest-Substring-Without-Repeating-Characters/cpp-0003/main3.cpp b/0001-0500/0003-Longest-Substring-Without-Repeating-Characters/cpp-0003/main3.cpp similarity index 100% rename from 0003-Longest-Substring-Without-Repeating-Characters/cpp-0003/main3.cpp rename to 0001-0500/0003-Longest-Substring-Without-Repeating-Characters/cpp-0003/main3.cpp diff --git a/0003-Longest-Substring-Without-Repeating-Characters/java-0003/src/Solution1.java b/0001-0500/0003-Longest-Substring-Without-Repeating-Characters/java-0003/src/Solution1.java similarity index 100% rename from 0003-Longest-Substring-Without-Repeating-Characters/java-0003/src/Solution1.java rename to 0001-0500/0003-Longest-Substring-Without-Repeating-Characters/java-0003/src/Solution1.java diff --git a/0003-Longest-Substring-Without-Repeating-Characters/java-0003/src/Solution2.java b/0001-0500/0003-Longest-Substring-Without-Repeating-Characters/java-0003/src/Solution2.java similarity index 100% rename from 0003-Longest-Substring-Without-Repeating-Characters/java-0003/src/Solution2.java rename to 0001-0500/0003-Longest-Substring-Without-Repeating-Characters/java-0003/src/Solution2.java diff --git a/0003-Longest-Substring-Without-Repeating-Characters/java-0003/src/Solution3.java b/0001-0500/0003-Longest-Substring-Without-Repeating-Characters/java-0003/src/Solution3.java similarity index 100% rename from 0003-Longest-Substring-Without-Repeating-Characters/java-0003/src/Solution3.java rename to 0001-0500/0003-Longest-Substring-Without-Repeating-Characters/java-0003/src/Solution3.java diff --git a/0001-0500/0004-Median-of-Two-Sorted-Arrays/cpp-0004/CMakeLists.txt b/0001-0500/0004-Median-of-Two-Sorted-Arrays/cpp-0004/CMakeLists.txt new file mode 100644 index 00000000..ca56e308 --- /dev/null +++ b/0001-0500/0004-Median-of-Two-Sorted-Arrays/cpp-0004/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(cpp_0004) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0004 main2.cpp) \ No newline at end of file diff --git a/0001-0500/0004-Median-of-Two-Sorted-Arrays/cpp-0004/main.cpp b/0001-0500/0004-Median-of-Two-Sorted-Arrays/cpp-0004/main.cpp new file mode 100644 index 00000000..0238984b --- /dev/null +++ b/0001-0500/0004-Median-of-Two-Sorted-Arrays/cpp-0004/main.cpp @@ -0,0 +1,80 @@ +/// Source : https://leetcode.com/problems/median-of-two-sorted-arrays/ +/// Author : liuyubobobo +/// Time : 2019-06-13 + +#include +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(log(min(n, m))) +/// Space Complexity: O(1) +class Solution { +public: + double findMedianSortedArrays(vector& nums1, vector& nums2) { + + if(nums1.size() > nums2.size()) swap(nums1, nums2); + + int n = nums1.size(), m = nums2.size(); + if(n == 0) return m % 2 ? nums2[m / 2] : (nums2[m / 2 - 1] + nums2[m / 2]) / 2.0; + int half = (n + m) / 2; + + int l = 0, r = n; + while(l <= r){ + int mid = (l + r) / 2; + + int i1 = mid, i2 = half - i1; + + int leftMax = i1 == 0 ? nums2[i2 - 1] : + i2 == 0 ? nums1[i1 - 1] : max(nums1[i1 - 1], nums2[i2 - 1]); + int rightMin = i1 == n ? nums2[i2] : + i2 == m ? nums1[i1] : min(nums1[i1], nums2[i2]); + + if(leftMax <= rightMin){ + if((n + m) % 2 == 1) + return rightMin; + else{ + int nums1Left = i1 == 0 ? INT_MIN : + i1 == 1 ? nums1[i1 - 1] : max(nums1[i1 - 1], nums1[i1 - 2]); + int nums1Right = i1 == n ? INT_MAX : + i1 == n - 1 ? nums1[i1] : min(nums1[i1], nums1[i1 + 1]); + int nums2Left = i2 == 0 ? INT_MIN : + i2 == 1 ? nums2[i2 - 1] : max(nums2[i2 - 1], nums2[i2 - 2]); + int nums2Right = i2 == m ? INT_MAX : + i2 == m - 1 ? nums2[i2] : min(nums2[i2], nums2[i2 + 1]); + return (max(nums1Left, nums2Left) + min(nums1Right, nums2Right)) / 2.0; + } + } + else if(nums1[i1] == rightMin) + l = mid + 1; + else + r = mid - 1; + } + assert(false); + return -1; + } +}; + + +int main() { + + vector nums11 = {1, 3}; + vector nums12 = {2}; + cout << Solution().findMedianSortedArrays(nums11, nums12) << endl; + // 2 + + vector nums21 = {1, 2}; + vector nums22 = {3, 4}; + cout << Solution().findMedianSortedArrays(nums21, nums22) << endl; + // 2.5 + + vector nums31 = {}; + vector nums32 = {1}; + cout << Solution().findMedianSortedArrays(nums31, nums32) << endl; + // 1 + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0004-Median-of-Two-Sorted-Arrays/cpp-0004/main2.cpp b/0001-0500/0004-Median-of-Two-Sorted-Arrays/cpp-0004/main2.cpp new file mode 100644 index 00000000..3bb76d83 --- /dev/null +++ b/0001-0500/0004-Median-of-Two-Sorted-Arrays/cpp-0004/main2.cpp @@ -0,0 +1,79 @@ +/// Source : https://leetcode.com/problems/median-of-two-sorted-arrays/ +/// Author : liuyubobobo +/// Time : 2021-03-02 + +#include +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(log(min(n, m))) +/// Space Complexity: O(1) +class Solution { +public: + double findMedianSortedArrays(vector& nums1, vector& nums2) { + + int len = nums1.size() + nums2.size(); + + int a = select(nums1, 0, (int)nums1.size() - 1, + nums2, 0, (int)nums2.size() - 1, len / 2); + if(len % 2) return a; + + int b = select(nums1, 0, (int)nums1.size() - 1, + nums2, 0, (int)nums2.size() - 1, len / 2 - 1); + return (a + b) / 2.0; + } + +private: + int select(const vector& nums1, int l1, int r1, + const vector& nums2, int l2, int r2, int k){ + + if(l1 > r1) return nums2[l2 + k]; + if(l2 > r2) return nums1[l1 + k]; + + int len1 = r1 - l1 + 1, len2 = r2 - l2 + 1; + int mid1 = len1 / 2, mid2 = len2 / 2; + int e1 = nums1[l1 + mid1], e2 = nums2[l2 + mid2]; + if(mid1 + mid2 < k){ + if(e1 > e2) + return select(nums1, l1, r1, nums2, l2 + mid2 + 1, r2, k - mid2 - 1); + else + return select(nums1, l1 + mid1 + 1, r1, nums2, l2, r2, k - mid1 - 1); + } + else{ + if(e1 > e2) + return select(nums1, l1, l1 + mid1 - 1, nums2, l2, r2, k); + else + return select(nums1, l1, r1, nums2, l2, l2 + mid2 - 1, k); + } + } +}; + + +int main() { + + vector nums11 = {1, 3}; + vector nums12 = {2}; + cout << Solution().findMedianSortedArrays(nums11, nums12) << endl; + // 2 + + vector nums21 = {1, 2}; + vector nums22 = {3, 4}; + cout << Solution().findMedianSortedArrays(nums21, nums22) << endl; + // 2.5 + + vector nums31 = {}; + vector nums32 = {1}; + cout << Solution().findMedianSortedArrays(nums31, nums32) << endl; + // 1 + + vector nums41 = {1, 2, 2}; + vector nums42 = {1, 2, 3}; + cout << Solution().findMedianSortedArrays(nums41, nums42) << endl; + // 2 + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0004-Median-of-Two-Sorted-Arrays/java-0004/src/Solution.java b/0001-0500/0004-Median-of-Two-Sorted-Arrays/java-0004/src/Solution.java new file mode 100644 index 00000000..d37a6ca3 --- /dev/null +++ b/0001-0500/0004-Median-of-Two-Sorted-Arrays/java-0004/src/Solution.java @@ -0,0 +1,45 @@ +/// Source : https://leetcode.com/problems/median-of-two-sorted-arrays/ +/// Author : liuyubobobo +/// Time : 2021-03-02 + +/// Binary Search +/// Time Complexity: O(log(min(n, m))) +/// Space Complexity: O(1) +public class Solution { + + public double findMedianSortedArrays(int[] nums1, int[] nums2) { + + int len = nums1.length + nums2.length; + + int a = select(nums1, 0, nums1.length - 1, + nums2, 0, nums2.length - 1, len / 2); + if(len % 2 == 1) return a; + + int b = select(nums1, 0, nums1.length - 1, + nums2, 0, nums2.length - 1, len / 2 - 1); + return (a + b) / 2.0; + } + + private int select(int[] nums1, int l1, int r1, + int[] nums2, int l2, int r2, int k){ + + if(l1 > r1) return nums2[l2 + k]; + if(l2 > r2) return nums1[l1 + k]; + + int len1 = r1 - l1 + 1, len2 = r2 - l2 + 1; + int mid1 = len1 / 2, mid2 = len2 / 2; + int e1 = nums1[l1 + mid1], e2 = nums2[l2 + mid2]; + if(mid1 + mid2 < k){ + if(e1 > e2) + return select(nums1, l1, r1, nums2, l2 + mid2 + 1, r2, k - mid2 - 1); + else + return select(nums1, l1 + mid1 + 1, r1, nums2, l2, r2, k - mid1 - 1); + } + else{ + if(e1 > e2) + return select(nums1, l1, l1 + mid1 - 1, nums2, l2, r2, k); + else + return select(nums1, l1, r1, nums2, l2, l2 + mid2 - 1, k); + } + } +} diff --git a/0001-0500/0005-Longest-Palindromic-Substring/cpp-0005/CMakeLists.txt b/0001-0500/0005-Longest-Palindromic-Substring/cpp-0005/CMakeLists.txt new file mode 100644 index 00000000..1fcc6634 --- /dev/null +++ b/0001-0500/0005-Longest-Palindromic-Substring/cpp-0005/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(cpp_0005) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(cpp_0005 main8.cpp) \ No newline at end of file diff --git a/0001-0500/0005-Longest-Palindromic-Substring/cpp-0005/main.cpp b/0001-0500/0005-Longest-Palindromic-Substring/cpp-0005/main.cpp new file mode 100644 index 00000000..7a22402e --- /dev/null +++ b/0001-0500/0005-Longest-Palindromic-Substring/cpp-0005/main.cpp @@ -0,0 +1,39 @@ +/// Source : https://leetcode.com/problems/longest-palindromic-substring/ +/// Author : liuyubobobo +/// Time : 2019-01-11 + +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n^3) +/// Space Complexity: O(1) +class Solution { +public: + string longestPalindrome(string s) { + + if(s == "") return s; + + int n = s.size(); + string res = s.substr(0, 1); + for(int i = 0; i < n; i ++) + for(int j = i + res.size(); j < n; j ++) + if(ok(s, i, j) && j - i + 1 > res.size()) + res = s.substr(i, j - i + 1); + return res; + } + +private: + bool ok(const string& s, int a, int b){ + for(; a < b && s[a] == s[b]; a ++, b --); + return a >= b; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0005-Longest-Palindromic-Substring/cpp-0005/main2.cpp b/0001-0500/0005-Longest-Palindromic-Substring/cpp-0005/main2.cpp new file mode 100644 index 00000000..a2e6b020 --- /dev/null +++ b/0001-0500/0005-Longest-Palindromic-Substring/cpp-0005/main2.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/longest-palindromic-substring/ +/// Author : liuyubobobo +/// Time : 2019-01-11 + +#include +#include +#include + +using namespace std; + + +/// Memory Search +/// State: is s[a...b] a palindrome? +/// +/// Time Complexity: O(n^2) +/// Space Complexity: O(n^2) +class Solution { +public: + string longestPalindrome(string s) { + + if(s == "") return s; + + int n = s.size(); + vector> dp(n, vector(n, -1)); // s[a...b] + for(int len = n; len >= 1; len --) + for(int start = 0; start + len - 1 < n; start ++) + if(dfs(s, start, start + len - 1, dp)) + return s.substr(start, len); + return ""; + } + +private: + int dfs(const string& s, int a, int b, + vector>& dp){ + + if(a > b) return dp[a][b] = 0; + if(a == b || (a + 1 == b && s[a] == s[b])) return dp[a][b] = 1; + if(dp[a][b] != -1) return dp[a][b]; + + if(s[a] != s[b]) return dp[a][b] = 0; +// assert(s[a] == s[b]); + return dp[a][b] = dfs(s, a + 1, b - 1, dp); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0005-Longest-Palindromic-Substring/cpp-0005/main3.cpp b/0001-0500/0005-Longest-Palindromic-Substring/cpp-0005/main3.cpp new file mode 100644 index 00000000..267f17d3 --- /dev/null +++ b/0001-0500/0005-Longest-Palindromic-Substring/cpp-0005/main3.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/longest-palindromic-substring/ +/// Author : liuyubobobo +/// Time : 2019-01-11 + +#include +#include +#include + +using namespace std; + + +/// Memory Search +/// State: is s.substr(start, len) a palindrome? +/// +/// Time Complexity: O(n^2) +/// Space Complexity: O(n^2) +class Solution { +public: + string longestPalindrome(string s) { + + if(s == "") return s; + + int n = s.size(); + vector> dp(n, vector(n + 1, -1)); // start, len + for(int len = n; len >= 1; len --) + for(int start = 0; start + len - 1 < n; start ++) + if(dfs(s, start, len, dp)) + return s.substr(start, len); + return ""; + } + +private: + int dfs(const string& s, int start, int len, vector>& dp){ + + if(len <= 1) return dp[start][len] = 1; + if(dp[start][len] >= 0) return dp[start][len]; + return dp[start][len] = + (s[start] == s[start + len - 1] && dfs(s, start + 1, len - 2, dp)); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0005-Longest-Palindromic-Substring/cpp-0005/main4.cpp b/0001-0500/0005-Longest-Palindromic-Substring/cpp-0005/main4.cpp new file mode 100644 index 00000000..929a2a78 --- /dev/null +++ b/0001-0500/0005-Longest-Palindromic-Substring/cpp-0005/main4.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/longest-palindromic-substring/ +/// Author : liuyubobobo +/// Time : 2019-01-11 + +#include +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// State: is s.substr(start, len) a palindrome? +/// +/// Time Complexity: O(n^2) +/// Space Complexity: O(n^2) +class Solution { +public: + string longestPalindrome(string s) { + + if(s == "") return s; + + int n = s.size(); + vector> dp(n, vector(n + 1, true)); // start, len + for(int len = 2; len <= n; len ++) + for(int start = 0; start + len - 1 < n; start ++) + dp[start][len] = (s[start] == s[start + len - 1] && dp[start + 1][len - 2]); + for(int len = n; len >= 1; len --) + for(int start = 0; start + len - 1 < n; start ++) + if(dp[start][len]) + return s.substr(start, len); + return ""; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0005-Longest-Palindromic-Substring/cpp-0005/main5.cpp b/0001-0500/0005-Longest-Palindromic-Substring/cpp-0005/main5.cpp new file mode 100644 index 00000000..5c35bebe --- /dev/null +++ b/0001-0500/0005-Longest-Palindromic-Substring/cpp-0005/main5.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/longest-palindromic-substring/ +/// Author : liuyubobobo +/// Time : 2019-01-11 + +#include +#include +#include + +using namespace std; + + +/// Expand from center +/// Time Complexity: O(n^2) +/// Space Complexity: O(1) +class Solution { +public: + string longestPalindrome(string s) { + + if(s == "") return s; + + int best = 0, n = s.size(); + string res = ""; + for(int center = 0; center < n; center ++){ + int len = 1, x; + for(x = 1; x <= min(center, n - (center + 1)) && s[center - x] == s[center + x]; x ++) + len += 2; + if(len > best) + best = len, res = s.substr(center - x + 1, len); + } + + for(int center = 0; center + 1 < n; center ++) + if(s[center] == s[center + 1]){ + int len = 2, x; + for(x = 1; x <= min(center, n - (center + 2)) && s[center - x] == s[center + 1 + x]; x ++) + len += 2; + if(len > best) + best = len, res = s.substr(center - x + 1, len); + } + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0005-Longest-Palindromic-Substring/cpp-0005/main6.cpp b/0001-0500/0005-Longest-Palindromic-Substring/cpp-0005/main6.cpp new file mode 100644 index 00000000..d7ceb109 --- /dev/null +++ b/0001-0500/0005-Longest-Palindromic-Substring/cpp-0005/main6.cpp @@ -0,0 +1,48 @@ +/// Source : https://leetcode.com/problems/longest-palindromic-substring/ +/// Author : liuyubobobo +/// Time : 2019-07-25 + +#include +#include +#include + +using namespace std; + + +/// LCS +/// Attention: Just get LCS between s and reverse(s) doesn't work +/// Some small fixes is needed +/// See here for details: https://leetcode.com/problems/longest-palindromic-substring/solution/ +/// +/// Time Complexity: O(n^2) +/// Space Complexity: O(n^2) +class Solution { +public: + string longestPalindrome(string s) { + + if(s == "") return s; + + string rs = s; + reverse(rs.begin(), rs.end()); + + // lcs + int n = s.size(); + vector> dp(n + 1, vector(n + 1, 0)); + string res = ""; + for(int i = 0; i < s.size(); i ++) + for(int j = 0; j < rs.size(); j ++) { + dp[i + 1][j + 1] = (s[i] == rs[j]) ? dp[i][j] + 1 : 0; + if(dp[i + 1][j + 1] > res.size() && i - dp[i + 1][j + 1] + 1 == n - 1 - j) + res = s.substr(i - dp[i + 1][j + 1] + 1, dp[i + 1][j + 1]); + } + return res; + } +}; + + +int main() { + + cout << Solution().longestPalindrome("babad") << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0005-Longest-Palindromic-Substring/cpp-0005/main7.cpp b/0001-0500/0005-Longest-Palindromic-Substring/cpp-0005/main7.cpp new file mode 100644 index 00000000..46abe072 --- /dev/null +++ b/0001-0500/0005-Longest-Palindromic-Substring/cpp-0005/main7.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/longest-palindromic-substring/ +/// Author : liuyubobobo +/// Time : 2019-07-25 + +#include +#include +#include + +using namespace std; + + +/// LCS +/// Attention: Just get LCS between s and reverse(s) doesn't work +/// Some small fixes is needed +/// See here for details: https://leetcode.com/problems/longest-palindromic-substring/solution/ +/// +/// Using only O(n) space +/// +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { +public: + string longestPalindrome(string s) { + + if(s == "") return s; + + string rs = s; + reverse(rs.begin(), rs.end()); + + // lcs + int n = s.size(); + vector> dp(2, vector(n + 1, 0)); + string res = ""; + for(int i = 0; i < s.size(); i ++) + for(int j = 0; j < rs.size(); j ++) { + dp[(i + 1) % 2][j + 1] = (s[i] == rs[j]) ? dp[i % 2][j] + 1 : 0; + if(dp[(i + 1) % 2][j + 1] > res.size() && i - dp[(i + 1) % 2][j + 1] + 1 == n - 1 - j) + res = s.substr(i - dp[(i + 1) % 2][j + 1] + 1, dp[(i + 1) % 2][j + 1]); + } + return res; + } +}; + + +int main() { + + cout << Solution().longestPalindrome("babad") << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0005-Longest-Palindromic-Substring/cpp-0005/main8.cpp b/0001-0500/0005-Longest-Palindromic-Substring/cpp-0005/main8.cpp new file mode 100644 index 00000000..7c44e1ef --- /dev/null +++ b/0001-0500/0005-Longest-Palindromic-Substring/cpp-0005/main8.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/longest-palindromic-substring/ +/// Author : liuyubobobo +/// Time : 2019-07-25 + +#include +#include +#include + +using namespace std; + + +/// Manacher's Algorithm +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + string longestPalindrome(string input) { + + string s = "#"; + for(char c: input) + s += c, s += '#'; + + int id = 0, maxright = 0; + int rescenter = 0, reslen = 0; + vector r(s.size(), 0); + for(int i = 1; i < s.size() - 1; i ++){ + r[i] = maxright > i ? min(r[2 * id - i], maxright - i) : 1; + while(i - r[i] >= 0 && i + r[i] < s.size() && s[i + r[i]] == s[i - r[i]]) r[i] ++; + r[i] --; + + if(i + r[i] > maxright) maxright = i + r[i], id = i; + + if(r[i] > reslen) reslen = r[i], rescenter = i; + } + + return input.substr((rescenter - reslen) / 2, reslen); + } +}; + + +int main() { + + cout << Solution().longestPalindrome("babad") << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0006-Zigzag-Conversion/cpp-0006/CMakeLists.txt b/0001-0500/0006-Zigzag-Conversion/cpp-0006/CMakeLists.txt new file mode 100644 index 00000000..f39e1e37 --- /dev/null +++ b/0001-0500/0006-Zigzag-Conversion/cpp-0006/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_0006) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0006 main.cpp) diff --git a/0001-0500/0006-Zigzag-Conversion/cpp-0006/main.cpp b/0001-0500/0006-Zigzag-Conversion/cpp-0006/main.cpp new file mode 100644 index 00000000..daf19aa8 --- /dev/null +++ b/0001-0500/0006-Zigzag-Conversion/cpp-0006/main.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/zigzag-conversion/ +/// Author : liuyubobobo +/// Time : 2022-02-28 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(|s|) +/// Space Complexity: O(numRows * |s|) +class Solution { +public: + string convert(string s, int numRows) { + + if(numRows == 1) return s; + + int n = s.size(); + + vector res(numRows, string(n, '-')); + int index = 0, cury = 0; + while(index < n){ + for(int k = 0; k < numRows && index < n; k ++) + res[k][cury] = s[index ++]; + if(index >= n) break; + + for(int k = numRows - 2, y = cury + 1; k > 0 && index < n; k --, y ++) + res[k][y] = s[index ++]; + if(index >= n) break; + + cury += (numRows - 1); + } + + string ret = ""; + for(int i = 0; i < numRows; i ++) + for(char c: res[i]) if(c != '-') ret += c; + return ret; + } +}; + + +int main() { + + cout << Solution().convert("PAYPALISHIRING", 3) << endl; + // "PAHNAPLSIIGYIR" + + return 0; +} diff --git a/0001-0500/0007-Reverse-Integer/cpp-0007/CMakeLists.txt b/0001-0500/0007-Reverse-Integer/cpp-0007/CMakeLists.txt new file mode 100644 index 00000000..511ef7ea --- /dev/null +++ b/0001-0500/0007-Reverse-Integer/cpp-0007/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0007) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main3.cpp) +add_executable(cpp_0007 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0007-Reverse-Integer/cpp-0007/main.cpp b/0001-0500/0007-Reverse-Integer/cpp-0007/main.cpp new file mode 100644 index 00000000..58d92ca0 --- /dev/null +++ b/0001-0500/0007-Reverse-Integer/cpp-0007/main.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/reverse-integer/description/ +/// Author : liuyubobobo +/// Time : 2018-07-08 + +#include + +using namespace std; + + +/// Using long long to solve the overflow problem +/// Time Complexity: O(logx) +/// Space Complexity: O(logx) +class Solution { +public: + int reverse(int x) { + + if(x == 0) + return x; + + int sign = x > 0 ? 1 : -1; + + long long num = abs((long long)x); + long long reverseNum = 0; + while(num){ + reverseNum = reverseNum * 10 + num % 10; + num /= 10; + } + + reverseNum *= sign; + if(reverseNum > INT_MAX || reverseNum < INT_MIN) + return 0; + return reverseNum; + } +}; + + +int main() { + + cout << Solution().reverse(123) << endl; + cout << Solution().reverse(-123) << endl; + cout << Solution().reverse(12) << endl; + cout << Solution().reverse(INT_MAX) << endl; + cout << Solution().reverse(INT_MIN) << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0007-Reverse-Integer/cpp-0007/main2.cpp b/0001-0500/0007-Reverse-Integer/cpp-0007/main2.cpp new file mode 100644 index 00000000..da60629e --- /dev/null +++ b/0001-0500/0007-Reverse-Integer/cpp-0007/main2.cpp @@ -0,0 +1,79 @@ +/// Source : https://leetcode.com/problems/reverse-integer/description/ +/// Author : liuyubobobo +/// Time : 2018-07-08 + +#include +#include +#include + +using namespace std; + + +/// Using digit vector to solve the overflow problem +/// Time Complexity: O(logx) +/// Space Complexity: O(logx) +class Solution { +public: + int reverse(int x) { + + if(x == 0) + return x; + + if(x == INT_MIN) + return 0; + + int sign = x > 0 ? 1 : -1; + + x = abs(x); + vector reverseDigits; + while(x){ + reverseDigits.push_back(x % 10); + x /= 10; + } + + if(sign > 0 && overflow(reverseDigits, {2, 1, 4, 7, 4, 8, 3, 6, 4, 7})) + return 0; + else if(sign < 0 && overflow(reverseDigits, {2, 1, 4, 7, 4, 8, 3, 6, 4, 8})) + return 0; + + return sign * getNumber(reverseDigits); + } + +private: + int getNumber(const vector& digits){ + int res = 0; + for(int digit: digits) + res = res * 10 + digit; + return res; + } + + bool overflow(const vector& digits, const vector& max){ + + if(digits.size() < max.size()) + return false; + + assert(digits.size() == max.size()); + for(int i = 0 ; i < digits.size() ; i ++) + if(digits[i] > max[i]) + return true; + else if(digits[i] < max[i]) + return false; + return false; + } +}; + + +int main() { + +// cout << INT_MAX << endl; // 2147483647 +// cout << INT_MIN << endl; // -2147483648 + + cout << Solution().reverse(123) << endl; // 321 + cout << Solution().reverse(-123) << endl; // -321 + cout << Solution().reverse(12) << endl; // 21 + cout << Solution().reverse(INT_MAX) << endl; // 0 + cout << Solution().reverse(INT_MIN) << endl; // 0 + cout << Solution().reverse(-2147483412) << endl; // -2143847412 + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0007-Reverse-Integer/cpp-0007/main3.cpp b/0001-0500/0007-Reverse-Integer/cpp-0007/main3.cpp new file mode 100644 index 00000000..d6953063 --- /dev/null +++ b/0001-0500/0007-Reverse-Integer/cpp-0007/main3.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/reverse-integer/description/ +/// Author : liuyubobobo +/// Time : 2018-07-08 + +#include +#include +#include + +using namespace std; + + +/// Poping digit one by one and check before overflow +/// Time Complexity: O(logx) +/// Space Complexity: O(1) +class Solution { +public: + int reverse(int x) { + + if(x == 0) + return x; + + if(x == INT_MIN) + return 0; + + int sign = x > 0 ? 1 : -1; + + x = abs(x); + int reverseNum = 0; + while(x){ + + if(reverseNum > INT_MAX / 10 || (reverseNum == INT_MAX / 10 && x % 10 > 7)) + return 0; + + reverseNum = reverseNum * 10 + x % 10; + x /= 10; + } + + return sign * reverseNum; + } +}; + + +int main() { + +// cout << INT_MAX << endl; // 2147483647 +// cout << INT_MIN << endl; // -2147483648 + + cout << Solution().reverse(123) << endl; // 321 + cout << Solution().reverse(-123) << endl; // -321 + cout << Solution().reverse(12) << endl; // 21 + cout << Solution().reverse(INT_MAX) << endl; // 0 + cout << Solution().reverse(INT_MIN) << endl; // 0 + cout << Solution().reverse(-2147483412) << endl; // -2143847412 + cout << Solution().reverse(-2147483418) << endl; // 0 + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0008-String-to-Integer/cpp-0008/CMakeLists.txt b/0001-0500/0008-String-to-Integer/cpp-0008/CMakeLists.txt new file mode 100644 index 00000000..a50225c0 --- /dev/null +++ b/0001-0500/0008-String-to-Integer/cpp-0008/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_0008) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0008 main.cpp) diff --git a/0001-0500/0008-String-to-Integer/cpp-0008/main.cpp b/0001-0500/0008-String-to-Integer/cpp-0008/main.cpp new file mode 100644 index 00000000..25943b94 --- /dev/null +++ b/0001-0500/0008-String-to-Integer/cpp-0008/main.cpp @@ -0,0 +1,62 @@ +/// Source : https://leetcode.com/problems/string-to-integer-atoi/ +/// Author : liuyubobobo +/// Time : 2022-01-13 + +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int myAtoi(string s) { + + int i; + for(i = 0; i < s.size() && s[i] == ' '; i ++); + + if(i == s.size()) return 0; + + bool pos = true; + if(s[i] == '-') pos = false, i ++; + else if(s[i] == '+') i ++; + + int j = i; + for(j = i; j < s.size() && isdigit(s[j]); j ++); + + long long num = get_num(s.substr(i, j - i)); + if(pos) return min(num, (long long)INT_MAX); + return max(-num, (long long)INT_MIN); + } + +private: + long long get_num(const string& s){ + + long long res = 0; + for(char c: s){ + res = res * 10 + (c - '0'); + if(res > INT_MAX) return res; + } + return res; + } +}; + + +int main() { + + cout << Solution().myAtoi("42") << endl; + // 42 + + cout << Solution().myAtoi(" -42") << endl; + // -42 + + cout << Solution().myAtoi("4193 with words") << endl; + // 4193 + + cout << Solution().myAtoi("+1") << endl; + // 1 + + return 0; +} diff --git a/0001-0500/0010-Regular-Expression-Matching/cpp-0010/CMakeLists.txt b/0001-0500/0010-Regular-Expression-Matching/cpp-0010/CMakeLists.txt new file mode 100644 index 00000000..3fc7fcca --- /dev/null +++ b/0001-0500/0010-Regular-Expression-Matching/cpp-0010/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(cpp_0010) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0010 main2.cpp) \ No newline at end of file diff --git a/0001-0500/0010-Regular-Expression-Matching/cpp-0010/main.cpp b/0001-0500/0010-Regular-Expression-Matching/cpp-0010/main.cpp new file mode 100644 index 00000000..e7db7bdf --- /dev/null +++ b/0001-0500/0010-Regular-Expression-Matching/cpp-0010/main.cpp @@ -0,0 +1,58 @@ +/// Source : https://leetcode.com/problems/regular-expression-matching/ +/// Author : liuyubobobo +/// Time : 2019-03-19 + +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O((s + p) * 2^(s + p)) +/// Space Complexity: O(s + p) +class Solution { +public: + bool isMatch(const string& s, const string& p) { + return match(s, 0, p, 0); + } + +private: + bool match(const string& s, int sl, const string& p, int pl){ + + if(sl == s.size()) return no_more_match(p, pl); + if(pl == p.size()) return false; + + if(pl + 1 < p.size() && p[pl + 1] == '*'){ + if(s[sl] == p[pl] || p[pl] == '.') + return match(s, sl + 1, p, pl) || match(s, sl, p, pl + 2); + else + return match(s, sl, p, pl + 2); + } + else if(s[sl] == p[pl] || p[pl] == '.') + return match(s, sl + 1, p, pl + 1); + return false; + } + + bool no_more_match(const string& p, int pl){ + int i; + for(i = pl; i < p.size(); i += 2) + if(i + 1 < p.size() && p[i + 1] != '*') return false; + return i == p.size(); + } +}; + + +int main() { + + cout << Solution().isMatch("aa", "a") << endl; // false + cout << Solution().isMatch("aa", "a*") << endl; // true + cout << Solution().isMatch("ab", ".*") << endl; // true + cout << Solution().isMatch("aab", "c*a*b") << endl; // true + cout << Solution().isMatch("mississippi", "mis*is*p*") << endl; // false + cout << Solution().isMatch("ab", ".*c") << endl; // false + cout << Solution().isMatch("a", ".*..a") << endl; // false + cout << Solution().isMatch("", ".*") << endl; // true + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0010-Regular-Expression-Matching/cpp-0010/main2.cpp b/0001-0500/0010-Regular-Expression-Matching/cpp-0010/main2.cpp new file mode 100644 index 00000000..71e2566b --- /dev/null +++ b/0001-0500/0010-Regular-Expression-Matching/cpp-0010/main2.cpp @@ -0,0 +1,63 @@ +/// Source : https://leetcode.com/problems/regular-expression-matching/ +/// Author : liuyubobobo +/// Time : 2019-03-19 + +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(s * p) +/// Space Complexity: O(s * p) +class Solution { +public: + bool isMatch(const string& s, const string& p) { + + vector> dp(s.size(), vector(p.size(), -1)); + return match(s, 0, p, 0, dp); + } + +private: + bool match(const string& s, int sl, const string& p, int pl, + vector>& dp){ + + if(sl == s.size()) return no_more_match(p, pl); + if(pl == p.size()) return false; + + if(dp[sl][pl] != -1) return dp[sl][pl]; + + if(pl + 1 < p.size() && p[pl + 1] == '*'){ + if(s[sl] == p[pl] || p[pl] == '.') + return dp[sl][pl] = (match(s, sl + 1, p, pl, dp) || match(s, sl, p, pl + 2, dp)); + else + return dp[sl][pl] = match(s, sl, p, pl + 2, dp); + } + else if(s[sl] == p[pl] || p[pl] == '.') + return dp[sl][pl] = match(s, sl + 1, p, pl + 1, dp); + return dp[sl][pl] = false; + } + + bool no_more_match(const string& p, int pl){ + int i; + for(i = pl; i < p.size(); i += 2) + if(i + 1 < p.size() && p[i + 1] != '*') return false; + return i == p.size(); + } +}; + + +int main() { + + cout << Solution().isMatch("aa", "a") << endl; // false + cout << Solution().isMatch("aa", "a*") << endl; // true + cout << Solution().isMatch("ab", ".*") << endl; // true + cout << Solution().isMatch("aab", "c*a*b") << endl; // true + cout << Solution().isMatch("mississippi", "mis*is*p*") << endl; // false + cout << Solution().isMatch("ab", ".*c") << endl; // false + cout << Solution().isMatch("a", ".*..a") << endl; // false + cout << Solution().isMatch("", ".*") << endl; // true + + return 0; +} \ No newline at end of file diff --git a/old/0011 Container With Most Water/cpp-Container-With-Most-Water/CMakeLists.txt b/0001-0500/0011-Container-With-Most-Water/cpp-0011/CMakeLists.txt similarity index 100% rename from old/0011 Container With Most Water/cpp-Container-With-Most-Water/CMakeLists.txt rename to 0001-0500/0011-Container-With-Most-Water/cpp-0011/CMakeLists.txt diff --git a/0001-0500/0011-Container-With-Most-Water/cpp-0011/main.cpp b/0001-0500/0011-Container-With-Most-Water/cpp-0011/main.cpp new file mode 100644 index 00000000..634a673d --- /dev/null +++ b/0001-0500/0011-Container-With-Most-Water/cpp-0011/main.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/container-with-most-water/ +/// Author : liuyubobobo +/// Time : 2018-08-13 + +#include +#include +#include + +using namespace std; + +/// Brute Force +/// Time Complexity: O(n^2) +/// Space Complexity: O(1) +class Solution { +public: + int maxArea(vector& height) { + + assert(height.size() >= 2); + + int area = 0; + for(int i = 0 ; i < height.size() ; i ++) + for(int j = i + 1; j < height.size() ; j ++) + area = max(area , min(height[i], height[j]) * (j - i)); + return area; + } +}; + + +int main() { + + vector nums1 = {1, 1}; + cout << Solution().maxArea(nums1) << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0011-Container-With-Most-Water/cpp-0011/main2.cpp b/0001-0500/0011-Container-With-Most-Water/cpp-0011/main2.cpp new file mode 100644 index 00000000..e527b48d --- /dev/null +++ b/0001-0500/0011-Container-With-Most-Water/cpp-0011/main2.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/container-with-most-water/ +/// Author : liuyubobobo +/// Time : 2016-12-26 + +#include +#include +#include + +using namespace std; + +/// Two Pointers +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int maxArea(vector& height) { + + assert(height.size() >= 2); + + int l = 0, r = height.size() - 1; + int area = 0; + while(l < r){ + area = max(area , min(height[l], height[r]) * (r - l)); + if(height[l] < height[r]) + l ++; + else + r --; + } + return area; + } +}; + + +int main() { + + vector nums1 = {1, 1}; + cout << Solution().maxArea(nums1) << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0012-Integer-to-Roman/cpp-0012/CMakeLists.txt b/0001-0500/0012-Integer-to-Roman/cpp-0012/CMakeLists.txt new file mode 100644 index 00000000..ddccea68 --- /dev/null +++ b/0001-0500/0012-Integer-to-Roman/cpp-0012/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0012) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0012 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0012-Integer-to-Roman/cpp-0012/main.cpp b/0001-0500/0012-Integer-to-Roman/cpp-0012/main.cpp new file mode 100644 index 00000000..efebc3a3 --- /dev/null +++ b/0001-0500/0012-Integer-to-Roman/cpp-0012/main.cpp @@ -0,0 +1,48 @@ +/// Source : https://leetcode.com/problems/integer-to-roman/description/ +/// Author : liuyubobobo +/// Time : 2018-09-16 + +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(1) +/// Space Complexity: O(1) +class Solution { +public: + string intToRoman(int num) { + + string res = ""; + string one[] = {"I", "X", "C", "M", ""}, five[] = {"V", "L", "D", ""}; + for(int k = 3; k >= 0; k --){ + int b = (int)pow(10, k); + if(num >= b){ + int x = num / b; + res += rome(x, one[k], five[k], one[k + 1]); + num %= b; + } + } + return res; + } + +private: + string rome(int x, string one, string five, string ten){ + if(x <= 3) + return string(x, one[0]); + else if(x == 4) + return one + five; + else if(x <= 8) + return five + string(x - 5, one[0]); + // x == 9 + return one + ten; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0013-Roman-to-Integer/cpp-0013/CMakeLists.txt b/0001-0500/0013-Roman-to-Integer/cpp-0013/CMakeLists.txt new file mode 100644 index 00000000..b4005238 --- /dev/null +++ b/0001-0500/0013-Roman-to-Integer/cpp-0013/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0013) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0013 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0013-Roman-to-Integer/cpp-0013/main.cpp b/0001-0500/0013-Roman-to-Integer/cpp-0013/main.cpp new file mode 100644 index 00000000..d8994b9e --- /dev/null +++ b/0001-0500/0013-Roman-to-Integer/cpp-0013/main.cpp @@ -0,0 +1,38 @@ +/// Source : https://leetcode.com/problems/roman-to-integer/description/ +/// Author : liuyubobobo +/// Time : 2018-09-17 + +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int romanToInt(string s) { + + unordered_map map = { + {'I', 1}, {'V', 5}, {'X', 10}, {'L', 50}, {'C', 100}, {'D', 500}, {'M', 1000}}; + + int res = 0; + for(int i = 0; i < s.size(); i ++) + if(i + 1 < s.size() && map[s[i]] < map[s[i + 1]]){ + res += map[s[i + 1]] - map[s[i]]; + i ++; + } + else + res += map[s[i]]; + + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0014-Longest-Common-Prefix/cpp-0014/CMakeLists.txt b/0001-0500/0014-Longest-Common-Prefix/cpp-0014/CMakeLists.txt new file mode 100644 index 00000000..d0745d75 --- /dev/null +++ b/0001-0500/0014-Longest-Common-Prefix/cpp-0014/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0014) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main3.cpp) +add_executable(cpp_0014 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0014-Longest-Common-Prefix/cpp-0014/main.cpp b/0001-0500/0014-Longest-Common-Prefix/cpp-0014/main.cpp new file mode 100644 index 00000000..68a33797 --- /dev/null +++ b/0001-0500/0014-Longest-Common-Prefix/cpp-0014/main.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/longest-common-prefix/description/ +/// Author : liuyubobobo +/// Time : 2018-06-03 + +#include +#include +#include + +using namespace std; + + +/// Vertical Scan +/// Time Complexity: O(len(strs) * max len of string) +/// Space Complexity: O(1) +class Solution { +public: + string longestCommonPrefix(vector& strs) { + + string res = ""; + if(strs.size() == 0) + return res; + + for(int i = 0 ; i < strs[0].size() ; i ++){ + + char c = strs[0][i]; + for(int j = 1 ; j < strs.size() ; j ++) + if(i >= strs[j].size() || strs[j][i] != c) + return res; + + res += c; + } + + return res; + } +}; + + +int main() { + + vector strs1 = {"flower","flow","flight"}; + cout << Solution().longestCommonPrefix(strs1) << endl; + + vector strs2 = {"dog","racecar","car"}; + cout << Solution().longestCommonPrefix(strs2) << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0014-Longest-Common-Prefix/cpp-0014/main2.cpp b/0001-0500/0014-Longest-Common-Prefix/cpp-0014/main2.cpp new file mode 100644 index 00000000..ce5a65c1 --- /dev/null +++ b/0001-0500/0014-Longest-Common-Prefix/cpp-0014/main2.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/longest-common-prefix/description/ +/// Author : liuyubobobo +/// Time : 2018-06-03 + +#include +#include +#include + +using namespace std; + + +/// Horizonal Scan +/// Time Complexity: O(len(strs) * max len of string) +/// Space Complexity: O(1) +class Solution { +public: + string longestCommonPrefix(vector& strs) { + + if(strs.size() == 0) + return ""; + + string res = strs[0]; + + for(int i = 1 ; i < strs.size() ; i ++){ + for(int j = 0 ; j < res.size() ; j ++) + if(j >= strs[i].size() || res[j] != strs[i][j]){ + res = res.substr(0, j); + break; + } + } + + return res; + } +}; + + +int main() { + + vector strs1 = {"flower","flow","flight"}; + cout << Solution().longestCommonPrefix(strs1) << endl; + + vector strs2 = {"dog","racecar","car"}; + cout << Solution().longestCommonPrefix(strs2) << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0014-Longest-Common-Prefix/cpp-0014/main3.cpp b/0001-0500/0014-Longest-Common-Prefix/cpp-0014/main3.cpp new file mode 100644 index 00000000..757153d2 --- /dev/null +++ b/0001-0500/0014-Longest-Common-Prefix/cpp-0014/main3.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/longest-common-prefix/description/ +/// Author : liuyubobobo +/// Time : 2018-06-03 + +#include +#include +#include + +using namespace std; + + +/// Divide and Conquer +/// Time Complexity: O(len(strs) * max len of string) +/// Space Complexity: O(log(len(strs))) +class Solution { +public: + string longestCommonPrefix(vector& strs) { + + if(strs.size() == 0) + return ""; + + return solve(strs, 0, strs.size() - 1); + } + +private: + string solve(const vector& strs, int start, int end){ + + if(start == end) + return strs[start]; + + int mid = (start + end) / 2; + string res1 = solve(strs, start, mid); + string res2 = solve(strs, mid + 1, end); + + int i = 0; + for( ; i < res1.size() && i < res2.size(); i ++) + if(res1[i] != res2[i]) + break; + + return res1.substr(0, i); + } +}; + + +int main() { + + vector strs1 = {"flower","flow","flight"}; + cout << Solution().longestCommonPrefix(strs1) << endl; + + vector strs2 = {"dog","racecar","car"}; + cout << Solution().longestCommonPrefix(strs2) << endl; + + return 0; +} \ No newline at end of file diff --git a/0015 3Sum/cpp-3Sum/CMakeLists.txt b/0001-0500/0015-3Sum/cpp-0015/CMakeLists.txt similarity index 100% rename from 0015 3Sum/cpp-3Sum/CMakeLists.txt rename to 0001-0500/0015-3Sum/cpp-0015/CMakeLists.txt diff --git a/0015 3Sum/cpp-3Sum/main1.cpp b/0001-0500/0015-3Sum/cpp-0015/main1.cpp similarity index 100% rename from 0015 3Sum/cpp-3Sum/main1.cpp rename to 0001-0500/0015-3Sum/cpp-0015/main1.cpp diff --git a/0015 3Sum/cpp-3Sum/main2.cpp b/0001-0500/0015-3Sum/cpp-0015/main2.cpp similarity index 100% rename from 0015 3Sum/cpp-3Sum/main2.cpp rename to 0001-0500/0015-3Sum/cpp-0015/main2.cpp diff --git a/old/0016 3Sum Closest/cpp-3Sum-Closest/CMakeLists.txt b/0001-0500/0016-3Sum-Closest/cpp-0016/CMakeLists.txt similarity index 100% rename from old/0016 3Sum Closest/cpp-3Sum-Closest/CMakeLists.txt rename to 0001-0500/0016-3Sum-Closest/cpp-0016/CMakeLists.txt diff --git a/0001-0500/0016-3Sum-Closest/cpp-0016/main.cpp b/0001-0500/0016-3Sum-Closest/cpp-0016/main.cpp new file mode 100644 index 00000000..44e18e72 --- /dev/null +++ b/0001-0500/0016-3Sum-Closest/cpp-0016/main.cpp @@ -0,0 +1,61 @@ +/// Source : https://leetcode.com/problems/3sum-closest/ +/// Author : liuyubobobo +/// Time : 2016-12-03 + +#include +#include +#include +#include + +using namespace std; + + +/// Sorting + Two Pointers +/// Time Complexity: O(nlogn) + O(n^2) +/// Space Complexity: O(1) +class Solution { +public: + int threeSumClosest(vector& nums, int target) { + + assert(nums.size() >= 3); + + sort(nums.begin(), nums.end()); + + int diff = abs(nums[0] + nums[1] + nums[2] - target); + int res = nums[0] + nums[1] + nums[2]; + + for(int i = 0 ; i < nums.size() ; i ++){ + + int l = i + 1, r = nums.size() - 1; + int t = target - nums[i]; + while(l < r){ + if(nums[l] + nums[r] == t) + return nums[i] + nums[l] + nums[r]; + else{ + + if(abs(nums[l] + nums[r] - t) < diff){ + diff = abs(nums[l] + nums[r] - t); + res = nums[i] + nums[l] + nums[r]; + } + + if( nums[l] + nums[r] < t ) + l ++; + else // nums[l] + nums[r] > t + r --; + } + } + } + + return res; + } +}; + + +int main() { + + vector nums1 = {0, 0, 0}; + int target1 = 1; + cout << Solution().threeSumClosest(nums1, target ) << endl; + + return 0; +} \ No newline at end of file diff --git a/0017-Letter-Combinations-of-a-Phone-Number/cpp-0017/CMakeLists.txt b/0001-0500/0017-Letter-Combinations-of-a-Phone-Number/cpp-0017/CMakeLists.txt similarity index 100% rename from 0017-Letter-Combinations-of-a-Phone-Number/cpp-0017/CMakeLists.txt rename to 0001-0500/0017-Letter-Combinations-of-a-Phone-Number/cpp-0017/CMakeLists.txt diff --git a/0017-Letter-Combinations-of-a-Phone-Number/cpp-0017/main.cpp b/0001-0500/0017-Letter-Combinations-of-a-Phone-Number/cpp-0017/main.cpp similarity index 100% rename from 0017-Letter-Combinations-of-a-Phone-Number/cpp-0017/main.cpp rename to 0001-0500/0017-Letter-Combinations-of-a-Phone-Number/cpp-0017/main.cpp diff --git a/0017-Letter-Combinations-of-a-Phone-Number/java-0017/src/Solution.java b/0001-0500/0017-Letter-Combinations-of-a-Phone-Number/java-0017/src/Solution.java similarity index 100% rename from 0017-Letter-Combinations-of-a-Phone-Number/java-0017/src/Solution.java rename to 0001-0500/0017-Letter-Combinations-of-a-Phone-Number/java-0017/src/Solution.java diff --git a/0001-0500/0018-4Sum/cpp-0018/CMakeLists.txt b/0001-0500/0018-4Sum/cpp-0018/CMakeLists.txt new file mode 100644 index 00000000..d83463ca --- /dev/null +++ b/0001-0500/0018-4Sum/cpp-0018/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_4Sum) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main2.cpp) +add_executable(cpp_4Sum ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0018-4Sum/cpp-0018/main.cpp b/0001-0500/0018-4Sum/cpp-0018/main.cpp new file mode 100644 index 00000000..450ed79e --- /dev/null +++ b/0001-0500/0018-4Sum/cpp-0018/main.cpp @@ -0,0 +1,94 @@ +/// Source : https://leetcode.com/problems/4sum/ +/// Author : liuyubobobo +/// Time : 2016-12-06 +/// Updated: 2023-07-14 + +#include +#include +#include +#include + +using namespace std; + + +/// Two pointers +/// Sort the array first. +/// For every different number a and b, try to find a pair (c, d), which a + b + c + d == 0 +/// Using this way, we don't need to see whether the triplet is a repeated one +/// +/// Time Complexity: O(nlogn) + O(n^3) +/// Space Complexity: O(1) +class Solution { +public: + vector> fourSum(vector& nums, int target) { + + int n = nums.size(); + + vector> res; + if(n < 4) + return res; + + sort(nums.begin(), nums.end()); + for(int i = 0 ; i <= n - 4 ; i = nextNumberIndex(nums, i)) + for (int j = i + 1; j <= n - 3; j = nextNumberIndex(nums, j)) { + + long long t = 0ll + target - nums[i] - nums[j]; + + if(nums[j+1] + nums[j+2] > t || nums[n-1] + nums[n-2] < t) + continue; + + int p1 = j + 1; + int p2 = nums.size() - 1; + if (p1 >= p2) + break; + + while (p1 < p2) { + if (nums[p1] + nums[p2] == t) { + res.push_back({nums[i], nums[j], nums[p1], nums[p2]}); + + p1 = nextNumberIndex(nums, p1); + p2 = preNumberIndex(nums, p2); + } + else if (nums[p1] + nums[p2] < t) + p1 = nextNumberIndex(nums, p1); + else // nums[p1] + nums[p2] > t + p2 = preNumberIndex(nums, p2); + } + } + + return res; + } + +private: + int nextNumberIndex( const vector &nums , int index ){ + for( int i = index + 1 ; i < nums.size() ; i ++ ) + if( nums[i] != nums[index] ) + return i; + return nums.size(); + } + + int preNumberIndex( const vector &nums , int index ){ + for( int i = index-1 ; i >= 0 ; i -- ) + if( nums[i] != nums[index] ) + return i; + return -1; + } +}; + + +void print_vec(const vector>& vec){ + for(const vector& v: vec){ + for(int e: v) + cout << e << " "; + cout << endl; + } +} + +int main() { + + vector nums1 = {1, 0, -1, 0, -2, 2}; + int target1 = 0; + print_vec(Solution().fourSum(nums1, target1)); + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0018-4Sum/cpp-0018/main2.cpp b/0001-0500/0018-4Sum/cpp-0018/main2.cpp new file mode 100644 index 00000000..b509627c --- /dev/null +++ b/0001-0500/0018-4Sum/cpp-0018/main2.cpp @@ -0,0 +1,91 @@ +/// Source : https://leetcode.com/problems/4sum/ +/// Author : liuyubobobo +/// Time : 2017-09-27 +/// Updated: 2023-07-14 + +#include +#include +#include +#include +#include +#include + +using namespace std; + + +/// Using hash table +/// Sort the array first. +/// Store every different c + d == t first +/// For every different number a and b, try to find a pair (c, d), which a + b + c + d == 0 +/// +/// Time Complexity: O(nlogn) + O(n^2) + O(n^3) +/// Space Complexity: O(n^2) +class Solution { +public: + vector> fourSum(vector& nums, int target) { + + int n = nums.size(); + + vector> res; + if(n < 4) + return res; + + sort(nums.begin() , nums.end()); + + unordered_map>> hashtable; + for(int i = 0 ; i < n - 1 ; i = nextNumberIndex(nums, i)) + for(int j = i + 1 ; j < n ; j = nextNumberIndex(nums, j)) + hashtable[nums[i]+nums[j]].push_back(make_pair(nums[i], nums[j])); + + for( int i = 0 ; i <= n - 4 ; i = nextNumberIndex(nums, i) ) + for (int j = i + 1; j <= n - 3; j = nextNumberIndex(nums, j)) { + + long long t = 0ll + target - nums[i] - nums[j]; + if( nums[j+1] + nums[j+2] > t || nums[n-1] + nums[n-2] < t) + continue; + + if(hashtable.find(t) == hashtable.end()) + continue; + + vector>::iterator iter = + lower_bound(hashtable[t].begin(), hashtable[t].end(), make_pair(nums[j+1], nums[j+1])); + for(; iter != hashtable[t].end() ; iter ++) + res.push_back({nums[i], nums[j], iter->first, iter->second}); + } + + return res; + } + +private: + int nextNumberIndex( const vector &nums , int index ){ + for( int i = index + 1 ; i < nums.size() ; i ++ ) + if( nums[i] != nums[index] ) + return i; + return nums.size(); + } + + int preNumberIndex( const vector &nums , int index ){ + for( int i = index-1 ; i >= 0 ; i -- ) + if( nums[i] != nums[index] ) + return i; + return -1; + } +}; + + +void print_vec(const vector>& vec){ + for(const vector& v: vec){ + for(int e: v) + cout << e << " "; + cout << endl; + } +} + +int main() { + + vector nums1 = {1, 0, -1, 0, -2, 2}; + int target1 = 0; + print_vec(Solution().fourSum(nums1, target1)); + + return 0; +} \ No newline at end of file diff --git a/0019-Remove-Nth-Node-From-End-of-List/cpp-0019/CMakeLists.txt b/0001-0500/0019-Remove-Nth-Node-From-End-of-List/cpp-0019/CMakeLists.txt similarity index 100% rename from 0019-Remove-Nth-Node-From-End-of-List/cpp-0019/CMakeLists.txt rename to 0001-0500/0019-Remove-Nth-Node-From-End-of-List/cpp-0019/CMakeLists.txt diff --git a/0001-0500/0019-Remove-Nth-Node-From-End-of-List/cpp-0019/main.cpp b/0001-0500/0019-Remove-Nth-Node-From-End-of-List/cpp-0019/main.cpp new file mode 100644 index 00000000..743df3fd --- /dev/null +++ b/0001-0500/0019-Remove-Nth-Node-From-End-of-List/cpp-0019/main.cpp @@ -0,0 +1,111 @@ +/// Source : https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/ +/// Author : liuyubobobo +/// Time : 2017-11-15 + +#include +#include + +using namespace std; + +///Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} +}; + +/// LinkedList Test Helper Functions +ListNode* createLinkedList(int arr[], int n){ + + if(n == 0) + return NULL; + + ListNode* head = new ListNode(arr[0]); + ListNode* curNode = head; + for(int i = 1 ; i < n ; i ++){ + curNode->next = new ListNode(arr[i]); + curNode = curNode->next; + } + + return head; +} + +void printLinkedList(ListNode* head){ + + if(head == NULL){ + cout<<"NULL"<val; + if(curNode->next != NULL) + cout << " -> "; + curNode = curNode->next; + } + + cout << endl; + + return; +} + +void deleteLinkedList(ListNode* head){ + + ListNode* curNode = head; + while(curNode != NULL){ + ListNode* delNode = curNode; + curNode = curNode->next; + delete delNode; + } + + return; +} + +/// Get the total length and remove the nth node +/// Two Pass Algorithm +/// +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + ListNode* removeNthFromEnd(ListNode* head, int n) { + + ListNode* dummyHead = new ListNode(0); + dummyHead->next = head; + + int length = 0; + for(ListNode* cur = dummyHead->next ; cur != NULL ; cur = cur->next) + length ++; + + int k = length - n; + assert(k >= 0); + ListNode* cur = dummyHead; + for(int i = 0 ; i < k ; i ++) + cur = cur->next; + + ListNode* delNode = cur->next; + cur->next = delNode->next; + delete delNode; + + ListNode* retNode = dummyHead->next; + delete dummyHead; + return retNode; + } +}; + +int main() { + + int arr[] = {1, 2, 3, 4, 5}; + int n = sizeof(arr)/sizeof(int); + + ListNode* head = createLinkedList(arr, n); + printLinkedList(head); + + head = Solution().removeNthFromEnd(head, 2); + printLinkedList(head); + + deleteLinkedList(head); + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0019-Remove-Nth-Node-From-End-of-List/cpp-0019/main2.cpp b/0001-0500/0019-Remove-Nth-Node-From-End-of-List/cpp-0019/main2.cpp new file mode 100644 index 00000000..3be9d091 --- /dev/null +++ b/0001-0500/0019-Remove-Nth-Node-From-End-of-List/cpp-0019/main2.cpp @@ -0,0 +1,112 @@ +/// Source : https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/ +/// Author : liuyubobobo +/// Time : 2017-11-15 + +#include +#include + +using namespace std; + +///Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} +}; + +/// LinkedList Test Helper Functions +ListNode* createLinkedList(int arr[], int n){ + + if(n == 0) + return NULL; + + ListNode* head = new ListNode(arr[0]); + ListNode* curNode = head; + for(int i = 1 ; i < n ; i ++){ + curNode->next = new ListNode(arr[i]); + curNode = curNode->next; + } + + return head; +} + +void printLinkedList(ListNode* head){ + + if( head == NULL ){ + cout << "NULL" << endl; + return; + } + + ListNode* curNode = head; + while(curNode != NULL){ + cout << curNode->val; + if( curNode->next != NULL ) + cout << " -> "; + curNode = curNode->next; + } + + cout << endl; + + return; +} + +void deleteLinkedList(ListNode* head){ + + ListNode* curNode = head; + while(curNode != NULL){ + ListNode* delNode = curNode; + curNode = curNode->next; + delete delNode; + } + + return; +} + +/// Two Pointers - One Pass Algorithm +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + ListNode* removeNthFromEnd(ListNode* head, int n) { + + ListNode* dummyHead = new ListNode(0); + dummyHead->next = head; + + ListNode* p = dummyHead; + ListNode* q = dummyHead; + for(int i = 0 ; i < n + 1 ; i ++){ + assert(q); + q = q->next; + } + + while(q){ + p = p->next; + q = q->next; + } + + ListNode* delNode = p->next; + p->next = delNode->next; + delete delNode; + + ListNode* retNode = dummyHead->next; + delete dummyHead; + + return retNode; + } +}; + +int main() { + + int arr[] = {1, 2, 3, 4, 5}; + int n = sizeof(arr)/sizeof(int); + + ListNode* head = createLinkedList(arr, n); + printLinkedList(head); + + head = Solution().removeNthFromEnd(head, 2); + printLinkedList(head); + + deleteLinkedList(head); + + return 0; +} \ No newline at end of file diff --git a/0019-Remove-Nth-Node-From-End-of-List/java-0019/src/ListNode.java b/0001-0500/0019-Remove-Nth-Node-From-End-of-List/java-0019/src/ListNode.java similarity index 100% rename from 0019-Remove-Nth-Node-From-End-of-List/java-0019/src/ListNode.java rename to 0001-0500/0019-Remove-Nth-Node-From-End-of-List/java-0019/src/ListNode.java diff --git a/0019-Remove-Nth-Node-From-End-of-List/java-0019/src/Solution1.java b/0001-0500/0019-Remove-Nth-Node-From-End-of-List/java-0019/src/Solution1.java similarity index 100% rename from 0019-Remove-Nth-Node-From-End-of-List/java-0019/src/Solution1.java rename to 0001-0500/0019-Remove-Nth-Node-From-End-of-List/java-0019/src/Solution1.java diff --git a/0019-Remove-Nth-Node-From-End-of-List/java-0019/src/Solution2.java b/0001-0500/0019-Remove-Nth-Node-From-End-of-List/java-0019/src/Solution2.java similarity index 100% rename from 0019-Remove-Nth-Node-From-End-of-List/java-0019/src/Solution2.java rename to 0001-0500/0019-Remove-Nth-Node-From-End-of-List/java-0019/src/Solution2.java diff --git a/0020-Valid-Parentheses/cpp-0020/CMakeLists.txt b/0001-0500/0020-Valid-Parentheses/cpp-0020/CMakeLists.txt similarity index 100% rename from 0020-Valid-Parentheses/cpp-0020/CMakeLists.txt rename to 0001-0500/0020-Valid-Parentheses/cpp-0020/CMakeLists.txt diff --git a/0020-Valid-Parentheses/cpp-0020/main.cpp b/0001-0500/0020-Valid-Parentheses/cpp-0020/main.cpp similarity index 100% rename from 0020-Valid-Parentheses/cpp-0020/main.cpp rename to 0001-0500/0020-Valid-Parentheses/cpp-0020/main.cpp diff --git a/0020-Valid-Parentheses/java-0020/src/Main.java b/0001-0500/0020-Valid-Parentheses/java-0020/src/Main.java similarity index 100% rename from 0020-Valid-Parentheses/java-0020/src/Main.java rename to 0001-0500/0020-Valid-Parentheses/java-0020/src/Main.java diff --git a/0020-Valid-Parentheses/java-0020/src/Solution.java b/0001-0500/0020-Valid-Parentheses/java-0020/src/Solution.java similarity index 100% rename from 0020-Valid-Parentheses/java-0020/src/Solution.java rename to 0001-0500/0020-Valid-Parentheses/java-0020/src/Solution.java diff --git a/0021-Merge-Two-Sorted-Lists/cpp-0021/CMakeLists.txt b/0001-0500/0021-Merge-Two-Sorted-Lists/cpp-0021/CMakeLists.txt similarity index 100% rename from 0021-Merge-Two-Sorted-Lists/cpp-0021/CMakeLists.txt rename to 0001-0500/0021-Merge-Two-Sorted-Lists/cpp-0021/CMakeLists.txt diff --git a/0021-Merge-Two-Sorted-Lists/cpp-0021/main.cpp b/0001-0500/0021-Merge-Two-Sorted-Lists/cpp-0021/main.cpp similarity index 100% rename from 0021-Merge-Two-Sorted-Lists/cpp-0021/main.cpp rename to 0001-0500/0021-Merge-Two-Sorted-Lists/cpp-0021/main.cpp diff --git a/0021-Merge-Two-Sorted-Lists/cpp-0021/main2.cpp b/0001-0500/0021-Merge-Two-Sorted-Lists/cpp-0021/main2.cpp similarity index 100% rename from 0021-Merge-Two-Sorted-Lists/cpp-0021/main2.cpp rename to 0001-0500/0021-Merge-Two-Sorted-Lists/cpp-0021/main2.cpp diff --git a/0001-0500/0022-Generate-Parentheses/cpp-0022/CMakeLists.txt b/0001-0500/0022-Generate-Parentheses/cpp-0022/CMakeLists.txt new file mode 100644 index 00000000..d1051047 --- /dev/null +++ b/0001-0500/0022-Generate-Parentheses/cpp-0022/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0022) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main5.cpp) +add_executable(cpp_0022 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0022-Generate-Parentheses/cpp-0022/main.cpp b/0001-0500/0022-Generate-Parentheses/cpp-0022/main.cpp new file mode 100644 index 00000000..01dee84b --- /dev/null +++ b/0001-0500/0022-Generate-Parentheses/cpp-0022/main.cpp @@ -0,0 +1,49 @@ +/// Source : https://leetcode.com/problems/generate-parentheses/description/ +/// Author : liuyubobobo +/// Time : 2018-09-23 + +#include +#include +#include +#include + +using namespace std; + + +/// Generate all permutation and check validation +/// Time Complexity: O(n*2^n) +/// Space Complexity: O(n) +class Solution { + +public: + vector generateParenthesis(int n) { + + string s = string(n, '(') + string(n, ')'); + vector res; + do{ + if(valid(s)) + res.push_back(s); + }while(next_permutation(s.begin(), s.end())); + return res; + } + +private: + bool valid(const string& s){ + + stack stack; + for(char c: s) + if(c == '(') + stack.push(c); + else if(stack.empty()) + return false; + else + stack.pop(); + return true; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0022-Generate-Parentheses/cpp-0022/main2.cpp b/0001-0500/0022-Generate-Parentheses/cpp-0022/main2.cpp new file mode 100644 index 00000000..ce2e6050 --- /dev/null +++ b/0001-0500/0022-Generate-Parentheses/cpp-0022/main2.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/generate-parentheses/description/ +/// Author : liuyubobobo +/// Time : 2018-09-23 + +#include +#include +#include +#include + +using namespace std; + + +/// Generate all valid permutation directly +/// Time Complexity: O(2^n) +/// Space Complexity: O(n) +class Solution { + +public: + vector generateParenthesis(int n) { + + vector res; + generate(n, n, "", res); + return res; + } + +private: + void generate(int left, int right, const string& cur, vector& res){ + + if(left == 0 && right == 0){ + res.push_back(cur); + return; + } + + if(left) + generate(left - 1, right, cur + '(', res); + + if(right && left < right) + generate(left, right - 1, cur + ')', res); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0022-Generate-Parentheses/cpp-0022/main3.cpp b/0001-0500/0022-Generate-Parentheses/cpp-0022/main3.cpp new file mode 100644 index 00000000..8d191d4a --- /dev/null +++ b/0001-0500/0022-Generate-Parentheses/cpp-0022/main3.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/generate-parentheses/description/ +/// Author : liuyubobobo +/// Time : 2018-09-23 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// Recursively call generateParenthesis for smaller n +/// Time Complexity: O(2^n) +/// Space Complexity: O(2^n) +class Solution { + +public: + vector generateParenthesis(int n) { + + if(n == 0) + return {}; + + vector res; + for(int i = 0; i <= n - 1; i ++){ + vector left = generateParenthesis(i); + if(left.size() == 0) left.push_back(""); + vector right = generateParenthesis(n - i - 1); + if(right.size() == 0) right.push_back(""); + for(const string& l: left) + for(const string& r: right) + res.push_back("(" + l + ")" + r); + } + return res; + } +}; + + +void print_vec(const vector& vec){ + for(const string& s: vec) + cout << s << " "; + cout << endl; +} + +int main() { + + print_vec(Solution().generateParenthesis(1)); + print_vec(Solution().generateParenthesis(2)); + print_vec(Solution().generateParenthesis(3)); + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0022-Generate-Parentheses/cpp-0022/main4.cpp b/0001-0500/0022-Generate-Parentheses/cpp-0022/main4.cpp new file mode 100644 index 00000000..e04c15ff --- /dev/null +++ b/0001-0500/0022-Generate-Parentheses/cpp-0022/main4.cpp @@ -0,0 +1,67 @@ +/// Source : https://leetcode.com/problems/generate-parentheses/description/ +/// Author : liuyubobobo +/// Time : 2018-09-23 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(2^n) +/// Space Complexity: O(2^n) +class Solution { + +private: + vector> res; + +public: + vector generateParenthesis(int n){ + + res.clear(); + for(int i = 0; i <= n; i ++) + res.push_back(vector()); + return generate(n); + } + +private: + vector generate(int n) { + + if(n == 0) + return {}; + + if(res[n].size() != 0) + return res[n]; + + for(int i = 0; i <= n - 1; i ++){ + vector left = generate(i); + if(left.size() == 0) left.push_back(""); + vector right = generate(n - i - 1); + if(right.size() == 0) right.push_back(""); + for(const string& l: left) + for(const string& r: right) + res[n].push_back("(" + l + ")" + r); + } + return res[n]; + } +}; + + +void print_vec(const vector& vec){ + for(const string& s: vec) + cout << s << " "; + cout << endl; +} + +int main() { + + print_vec(Solution().generateParenthesis(1)); + print_vec(Solution().generateParenthesis(2)); + print_vec(Solution().generateParenthesis(3)); + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0022-Generate-Parentheses/cpp-0022/main5.cpp b/0001-0500/0022-Generate-Parentheses/cpp-0022/main5.cpp new file mode 100644 index 00000000..8b9e354b --- /dev/null +++ b/0001-0500/0022-Generate-Parentheses/cpp-0022/main5.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/generate-parentheses/description/ +/// Author : liuyubobobo +/// Time : 2018-09-23 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(2^n) +/// Space Complexity: O(2^n) +class Solution { + +public: + vector generateParenthesis(int n){ + + if(n == 0) + return {}; + + vector> res(n + 1); + res[0].push_back(""); + for(int i = 1; i <= n; i ++) + for(int j = 0; j <= i - 1; j ++) + for(const string& l: res[j]) + for(const string& r: res[i - j - 1]) + res[i].push_back("(" + l + ")" + r); + return res[n]; + } +}; + + +void print_vec(const vector& vec){ + for(const string& s: vec) + cout << s << " "; + cout << endl; +} + +int main() { + + print_vec(Solution().generateParenthesis(1)); + print_vec(Solution().generateParenthesis(2)); + print_vec(Solution().generateParenthesis(3)); + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0022-Generate-Parentheses/java-0022/src/Solution1.java b/0001-0500/0022-Generate-Parentheses/java-0022/src/Solution1.java new file mode 100644 index 00000000..93500f2e --- /dev/null +++ b/0001-0500/0022-Generate-Parentheses/java-0022/src/Solution1.java @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/generate-parentheses/ +/// Author : penpenps +/// Time : 2019-05-28 + +import java.util.*; + +/// Recursive with "(" and ")" separately and guarantee open and close num is equal +/// Time Complexity: O(2^n) +/// Space Complexity: O(n) + +public class Solution1 { + public void helper(List ans, String str, int open, int close, int max) { + if(str.length() == 2*max){ + ans.add(str); + return; + } + + if(open < max) + helper(ans, str+"(", open+1, close, max); + if(close < open) + helper(ans, str+")", open, close+1, max); + } + public List generateParenthesis(int n) { + List ans = new ArrayList<>(); + helper(ans, "", 0, 0, n); + return ans; + } + + private static void printList(List list){ + for(String e: list) + System.out.print(e + " "); + System.out.println(); + } + + public static void main(String[] args) { + int n = 3; + List res = (new Solution1()).generateParenthesis(n); + printList(res); + } +} diff --git a/0001-0500/0022-Generate-Parentheses/py-0022/Solution1.py b/0001-0500/0022-Generate-Parentheses/py-0022/Solution1.py new file mode 100644 index 00000000..9c0046e9 --- /dev/null +++ b/0001-0500/0022-Generate-Parentheses/py-0022/Solution1.py @@ -0,0 +1,29 @@ +# Source : https://leetcode.com/problems/generate-parentheses/ +# Author : penpenps +# Time : 2019-05-28 + +from typing import List + +# Recursive with "(" and ")" separately and guarantee open and close num is equal +# Time Complexity: O(2^n) +# Space Complexity: O(n) + +class Solution: + def generateParenthesis(self, n: int) -> List[str]: + def helper(current, openNum, closeNum, n, ans): + if len(current) == 2*n: + ans.append(current) + return + if openNum < n: + helper(current+"(", openNum + 1, closeNum, n, ans) + if closeNum < openNum: + helper(current+")", openNum, closeNum + 1, n, ans) + + ans = [] + helper("", 0, 0, n, ans) + return ans + +if __name__ == '__main__': + solution = Solution() + n = 3 + print(solution.generateParenthesis(n)) \ No newline at end of file diff --git a/0001-0500/0022-Generate-Parentheses/py-0022/Solution2.py b/0001-0500/0022-Generate-Parentheses/py-0022/Solution2.py new file mode 100644 index 00000000..0b32fa02 --- /dev/null +++ b/0001-0500/0022-Generate-Parentheses/py-0022/Solution2.py @@ -0,0 +1,29 @@ +# Source : https://leetcode.com/problems/generate-parentheses/ +# Author : penpenps +# Time : 2019-05-28 + +from typing import List + +# Traversal all combinations with left part length as i and right part as n-1-i +# Time Complexity: O(2^n) +# Space Complexity: O(n) + +class Solution: + def generateParenthesis(self, n: int) -> List[str]: + ans = [] + for i in range(n): + left = self.generateParenthesis(i) + if not left: + left = [""] + right = self.generateParenthesis(n-1-i) + if not right: + right = [""] + for l in left: + for r in right: + ans.append("("+l+")"+r) + return ans + +if __name__ == '__main__': + solution = Solution() + n = 3 + print(solution.generateParenthesis(n)) \ No newline at end of file diff --git a/0001-0500/0022-Generate-Parentheses/py-0022/Solution3.py b/0001-0500/0022-Generate-Parentheses/py-0022/Solution3.py new file mode 100644 index 00000000..9d511ec6 --- /dev/null +++ b/0001-0500/0022-Generate-Parentheses/py-0022/Solution3.py @@ -0,0 +1,25 @@ +# Source : https://leetcode.com/problems/generate-parentheses/ +# Author : penpenps +# Time : 2019-05-28 + +from typing import List + +# Traversal all combinations with left part length as i and right part as n-1-i +# Time Complexity: O(2^n) +# Space Complexity: O(n) + +class Solution: + def generateParenthesis(self, n: int) -> List[str]: + dp = [[] for _ in range(n+1)] + dp[0] = [""] + for i in range(1, n+1): + for j in range(i): + for l in dp[j]: + for r in dp[i-j-1]: + dp[i].append("("+l+")"+r) + return dp[n] + +if __name__ == '__main__': + solution = Solution() + n = 3 + print(solution.generateParenthesis(n)) \ No newline at end of file diff --git a/0001-0500/0023-Merge-k-Sorted-Lists/cpp-0023/CMakeLists.txt b/0001-0500/0023-Merge-k-Sorted-Lists/cpp-0023/CMakeLists.txt new file mode 100644 index 00000000..cf5ccf09 --- /dev/null +++ b/0001-0500/0023-Merge-k-Sorted-Lists/cpp-0023/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0023) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main2.cpp) +add_executable(cpp_0023 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0023-Merge-k-Sorted-Lists/cpp-0023/main.cpp b/0001-0500/0023-Merge-k-Sorted-Lists/cpp-0023/main.cpp new file mode 100644 index 00000000..cd047840 --- /dev/null +++ b/0001-0500/0023-Merge-k-Sorted-Lists/cpp-0023/main.cpp @@ -0,0 +1,68 @@ +/// Source : https://leetcode.com/problems/merge-k-sorted-lists/description/ +/// Author : liuyubobobo +/// Time : 2018-07-02 + +#include +#include +#include + +using namespace std; + +/// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} +}; + +/// Linear Compare each ListNode +/// Time Complexity: O(k*n) where k is len(lists) and n is the nodes number +/// Space Complexity: O(1) +class Solution { +public: + ListNode* mergeKLists(vector& lists) { + + if(lists.size() == 0) + return NULL; + + ListNode* dummyHead = new ListNode(-1); + ListNode* curNode = dummyHead; + + int finished = 0; + for(ListNode* node: lists) + if(node == NULL) + finished ++; + + while(finished < lists.size()){ + + ListNode* nextNode = NULL; + int nextIndex = -1; + for(int i = 0 ; i < lists.size() ; i ++) + if(lists[i] != NULL){ + if(nextIndex == -1 || lists[i]->val < nextNode->val){ + nextNode = lists[i]; + nextIndex = i; + } + } + assert(nextIndex != -1 && nextNode != NULL); + + lists[nextIndex] = lists[nextIndex]->next; + if(lists[nextIndex] == NULL) + finished ++; + + curNode->next = nextNode; + nextNode->next = NULL; + curNode = curNode->next; + } + + ListNode* ret = dummyHead->next; + delete dummyHead; + return ret; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0023-Merge-k-Sorted-Lists/cpp-0023/main2.cpp b/0001-0500/0023-Merge-k-Sorted-Lists/cpp-0023/main2.cpp new file mode 100644 index 00000000..a793ab17 --- /dev/null +++ b/0001-0500/0023-Merge-k-Sorted-Lists/cpp-0023/main2.cpp @@ -0,0 +1,68 @@ +/// Source : https://leetcode.com/problems/merge-k-sorted-lists/description/ +/// Author : liuyubobobo +/// Time : 2018-07-02 + +#include +#include +#include +#include + +using namespace std; + +/// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} +}; + +class CompareListNode{ +public: + bool operator()(ListNode* node1, ListNode* node2){ + return node1->val > node2->val; + } +}; + +/// Using Priority Queue to compare each ListNode +/// Time Complexity: O(nlogk) where k is len(lists) and n is the nodes number +/// Space Complexity: O(1) +class Solution { +public: + ListNode* mergeKLists(vector& lists) { + + if(lists.size() == 0) + return NULL; + + ListNode* dummyHead = new ListNode(-1); + ListNode* curNode = dummyHead; + + priority_queue, CompareListNode> q; + for(ListNode* node: lists) + if(node != NULL) + q.push(node); + + while(!q.empty()){ + + ListNode* nextNode = q.top(); + q.pop(); + + + curNode->next = nextNode; + if(nextNode->next != NULL) + q.push(nextNode->next); + + nextNode->next = NULL; + curNode = curNode->next; + } + + ListNode* ret = dummyHead->next; + delete dummyHead; + return ret; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0023-Merge-k-Sorted-Lists/cpp-0023/main3.cpp b/0001-0500/0023-Merge-k-Sorted-Lists/cpp-0023/main3.cpp new file mode 100644 index 00000000..ee740012 --- /dev/null +++ b/0001-0500/0023-Merge-k-Sorted-Lists/cpp-0023/main3.cpp @@ -0,0 +1,69 @@ +/// Source : https://leetcode.com/problems/merge-k-sorted-lists/description/ +/// Author : liuyubobobo +/// Time : 2018-07-02 + +#include +#include +#include +#include + +using namespace std; + +/// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} +}; + +/// Merge List One by One +/// Time Complexity: O(k*n), where k is len(lists) and n is the nodes number +/// Space Complexity: O(1) +class Solution { +public: + ListNode* mergeKLists(vector& lists) { + + if(lists.size() == 0) + return NULL; + + ListNode* ret = NULL; + for(ListNode* list: lists) + ret = merge(ret, list); + return ret; + } + +private: + ListNode* merge(ListNode* list1, ListNode* list2){ + + ListNode* dummyHead = new ListNode(-1); + ListNode* curNode = dummyHead; + while(list1 != NULL && list2 != NULL){ + if(list1->val < list2->val){ + curNode->next = list1; + list1 = list1->next; + } + else{ + curNode->next = list2; + list2 = list2->next; + } + + curNode = curNode->next; + curNode->next = NULL; + } + + if(list1) + curNode->next = list1; + if(list2) + curNode->next = list2; + + ListNode* ret = dummyHead->next; + delete dummyHead; + return ret; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0023-Merge-k-Sorted-Lists/cpp-0023/main4.cpp b/0001-0500/0023-Merge-k-Sorted-Lists/cpp-0023/main4.cpp new file mode 100644 index 00000000..bc304265 --- /dev/null +++ b/0001-0500/0023-Merge-k-Sorted-Lists/cpp-0023/main4.cpp @@ -0,0 +1,82 @@ +/// Source : https://leetcode.com/problems/merge-k-sorted-lists/description/ +/// Author : liuyubobobo +/// Time : 2018-07-02 + +#include +#include +#include +#include + +using namespace std; + +/// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} +}; + +/// Merge List with Divide and Conquer +/// Using the Bottom-Up Merge +/// Since Top-Down Merge will lead to TLE :-( +/// +/// Time Complexity: O(nlogk), where k is len(lists) and n is the nodes number +/// Space Complexity: O(logk) +class Solution { +public: + ListNode* mergeKLists(vector& lists) { + + if(lists.size() == 0) + return NULL; + + while(lists.size() > 1){ + int index = 0; + for(int i = 0; i < lists.size() ; i += 2){ + if(i + 1 == lists.size()) + lists[index] = lists[i]; + else + lists[index] = merge(lists[i], lists[i + 1]); + index ++; + } + + while(lists.size() > index) + lists.pop_back(); + } + return lists[0]; + } + +private: + ListNode* merge(ListNode* list1, ListNode* list2){ + + ListNode* dummyHead = new ListNode(-1); + ListNode* curNode = dummyHead; + while(list1 != NULL && list2 != NULL){ + if(list1->val < list2->val){ + curNode->next = list1; + list1 = list1->next; + } + else{ + curNode->next = list2; + list2 = list2->next; + } + + curNode = curNode->next; + curNode->next = NULL; + } + + if(list1) + curNode->next = list1; + if(list2) + curNode->next = list2; + + ListNode* ret = dummyHead->next; + delete dummyHead; + return ret; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0024-Swap-Nodes-in-Pairs/cpp-0024/CMakeLists.txt b/0001-0500/0024-Swap-Nodes-in-Pairs/cpp-0024/CMakeLists.txt similarity index 100% rename from 0024-Swap-Nodes-in-Pairs/cpp-0024/CMakeLists.txt rename to 0001-0500/0024-Swap-Nodes-in-Pairs/cpp-0024/CMakeLists.txt diff --git a/0024-Swap-Nodes-in-Pairs/cpp-0024/main.cpp b/0001-0500/0024-Swap-Nodes-in-Pairs/cpp-0024/main.cpp similarity index 100% rename from 0024-Swap-Nodes-in-Pairs/cpp-0024/main.cpp rename to 0001-0500/0024-Swap-Nodes-in-Pairs/cpp-0024/main.cpp diff --git a/0024-Swap-Nodes-in-Pairs/java-0024/src/ListNode.java b/0001-0500/0024-Swap-Nodes-in-Pairs/java-0024/src/ListNode.java similarity index 100% rename from 0024-Swap-Nodes-in-Pairs/java-0024/src/ListNode.java rename to 0001-0500/0024-Swap-Nodes-in-Pairs/java-0024/src/ListNode.java diff --git a/0024-Swap-Nodes-in-Pairs/java-0024/src/Solution.java b/0001-0500/0024-Swap-Nodes-in-Pairs/java-0024/src/Solution.java similarity index 100% rename from 0024-Swap-Nodes-in-Pairs/java-0024/src/Solution.java rename to 0001-0500/0024-Swap-Nodes-in-Pairs/java-0024/src/Solution.java diff --git a/0001-0500/0025-Reverse-Nodes-in-k-Group/cpp-0025/CMakeLists.txt b/0001-0500/0025-Reverse-Nodes-in-k-Group/cpp-0025/CMakeLists.txt new file mode 100644 index 00000000..4115eed5 --- /dev/null +++ b/0001-0500/0025-Reverse-Nodes-in-k-Group/cpp-0025/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0025) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0025 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0025-Reverse-Nodes-in-k-Group/cpp-0025/main.cpp b/0001-0500/0025-Reverse-Nodes-in-k-Group/cpp-0025/main.cpp new file mode 100644 index 00000000..c38ef3f6 --- /dev/null +++ b/0001-0500/0025-Reverse-Nodes-in-k-Group/cpp-0025/main.cpp @@ -0,0 +1,121 @@ +/// Source : https://leetcode.com/problems/reverse-nodes-in-k-group/description/ +/// Author : liuyubobobo +/// Time : 2019-08-09 + +#include +#include + +using namespace std; + + +/// Linear Scan and Recursive Reverse +/// Time Complexity: O(n) +/// Space Complexity: O(k) + +/// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} +}; + +class Solution { +public: + ListNode* reverseKGroup(ListNode* head, int k) { + + ListNode* dummyHead = new ListNode(-1); + dummyHead->next = head; + + ListNode* pre = dummyHead; + while(pre && pre->next){ + + ListNode* end = pre; + int i; + for(i = 0; i < k && end->next; i ++) + end = end->next; + + if(i != k) break; + + ListNode* next = end->next; + + // reverse from pre->next to end + ListNode* rhead = reverse(pre->next, end); + + ListNode* tail = pre->next; + pre->next = rhead; + tail->next = next; + pre = tail; + } + + ListNode* ret = dummyHead->next; + delete dummyHead; + return ret; + } + +private: + ListNode* reverse(ListNode* head, ListNode* end){ + + if(head == end) return head; + + ListNode* rhead = reverse(head->next, end); + head->next->next = head; + return rhead; + } +}; + + +/// LinkedList 测试辅助函数 + +// 根据n个元素的数组arr创建一个链表, 并返回链表的头 +ListNode* createLinkedList(const vector& arr){ + + if(arr.size() == 0) + return NULL; + + ListNode* head = new ListNode(arr[0]); + ListNode* curNode = head; + for(int i = 1 ; i < arr.size() ; i ++){ + curNode->next = new ListNode(arr[i]); + curNode = curNode->next; + } + + return head; +} + +// 打印以head为头结点的链表信息内容 +void printLinkedList(ListNode* head){ + + ListNode* curNode = head; + while(curNode != NULL){ + cout << curNode->val << " -> "; + curNode = curNode->next; + } + + cout << "NULL" << endl; + + return; +} + +// 释放以head为头结点的链表空间 +void deleteLinkedList(ListNode* head){ + + ListNode* curNode = head; + while(curNode != NULL){ + ListNode* delNode = curNode; + curNode = curNode->next; + delete delNode; + } + + return; +} + + +int main() { + + vector arr1 = {1, 2, 3, 4, 5}; + ListNode* res1 = Solution().reverseKGroup(createLinkedList(arr1), 3); + printLinkedList(res1); + deleteLinkedList(res1); + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0025-Reverse-Nodes-in-k-Group/cpp-0025/main2.cpp b/0001-0500/0025-Reverse-Nodes-in-k-Group/cpp-0025/main2.cpp new file mode 100644 index 00000000..7832b7d0 --- /dev/null +++ b/0001-0500/0025-Reverse-Nodes-in-k-Group/cpp-0025/main2.cpp @@ -0,0 +1,124 @@ +/// Source : https://leetcode.com/problems/reverse-nodes-in-k-group/description/ +/// Author : liuyubobobo +/// Time : 2018-10-02 + +#include +#include + +using namespace std; + + +/// Linear Scan and Recursive Reverse +/// Time Complexity: O(n) +/// Space Complexity: O(k) + +/// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} +}; + +class Solution { +public: + ListNode* reverseKGroup(ListNode* head, int k) { + + ListNode* dummyHead = new ListNode(-1); + dummyHead->next = head; + + ListNode* cur = dummyHead; + while(cur && cur->next){ + ListNode* tail = cur->next; + + ListNode* left; + bool ok = false; + cur->next = reverse(cur->next, k - 1, left, ok); + tail->next = left; + + if(ok) + cur = tail; + else { + tail = cur->next; + cur->next = reverse(cur->next, k - 1, left, ok); + tail->next = NULL; + break; + } + } + + ListNode* ret = dummyHead->next; + delete dummyHead; + return ret; + } + +private: + ListNode* reverse(ListNode* head, int index, ListNode* &left, bool& ok){ + + if(index == 0 || !head->next){ + ok = index == 0; + left = head->next; + return head; + } + + ListNode* tail = head->next; + ListNode* ret = reverse(head->next, index - 1, left, ok); + tail->next = head; + return ret; + } +}; + + +/// LinkedList 测试辅助函数 + +// 根据n个元素的数组arr创建一个链表, 并返回链表的头 +ListNode* createLinkedList(const vector& arr){ + + if(arr.size() == 0) + return NULL; + + ListNode* head = new ListNode(arr[0]); + ListNode* curNode = head; + for(int i = 1 ; i < arr.size() ; i ++){ + curNode->next = new ListNode(arr[i]); + curNode = curNode->next; + } + + return head; +} + +// 打印以head为头结点的链表信息内容 +void printLinkedList(ListNode* head){ + + ListNode* curNode = head; + while(curNode != NULL){ + cout << curNode->val << " -> "; + curNode = curNode->next; + } + + cout << "NULL" << endl; + + return; +} + +// 释放以head为头结点的链表空间 +void deleteLinkedList(ListNode* head){ + + ListNode* curNode = head; + while(curNode != NULL){ + ListNode* delNode = curNode; + curNode = curNode->next; + delete delNode; + } + + return; +} + + +int main() { + + vector arr1 = {1, 2, 3, 4, 5}; + ListNode* res1 = Solution().reverseKGroup(createLinkedList(arr1), 3); + printLinkedList(res1); + deleteLinkedList(res1); + + return 0; +} \ No newline at end of file diff --git a/old/0026 Remove Duplicates from Sorted Array/cpp-Remove-Duplicates-from-Sorted-Array/CMakeLists.txt b/0001-0500/0026-Remove-Duplicates-from-Sorted-Array/cpp-0026/CMakeLists.txt similarity index 100% rename from old/0026 Remove Duplicates from Sorted Array/cpp-Remove-Duplicates-from-Sorted-Array/CMakeLists.txt rename to 0001-0500/0026-Remove-Duplicates-from-Sorted-Array/cpp-0026/CMakeLists.txt diff --git a/0001-0500/0026-Remove-Duplicates-from-Sorted-Array/cpp-0026/main.cpp b/0001-0500/0026-Remove-Duplicates-from-Sorted-Array/cpp-0026/main.cpp new file mode 100644 index 00000000..358ee43a --- /dev/null +++ b/0001-0500/0026-Remove-Duplicates-from-Sorted-Array/cpp-0026/main.cpp @@ -0,0 +1,51 @@ +/// Source : https://leetcode.com/problems/remove-duplicates-from-sorted-array/ +/// Author : liuyubobobo +/// Time : 2016-12-06 + + +#include +#include +#include +#include + +using namespace std; + +/// Two pointers +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int removeDuplicates(vector& nums) { + + if(nums.size() == 0) + return 0; + + int res = 1; + int index = nextDifferentCharacterIndex(nums, 1); + int i = 1; + while(index < nums.size()){ + res ++; + nums[i++] = nums[index]; + index = nextDifferentCharacterIndex(nums, index + 1); + } + + return res; + } + +private: + int nextDifferentCharacterIndex(const vector &nums, int p){ + for( ; p < nums.size() ; p ++ ) + if( nums[p] != nums[p - 1] ) + break; + return p; + } +}; + + +int main() { + + vector nums1 = {1, 1, 2}; + cout << Solution().removeDuplicates(nums1) << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0027-Remove-Element/cpp-0027/CMakeLists.txt b/0001-0500/0027-Remove-Element/cpp-0027/CMakeLists.txt new file mode 100644 index 00000000..cedc2e3c --- /dev/null +++ b/0001-0500/0027-Remove-Element/cpp-0027/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_Remove_Element) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main1.cpp) +add_executable(cpp_Remove_Element ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0027-Remove-Element/cpp-0027/main1.cpp b/0001-0500/0027-Remove-Element/cpp-0027/main1.cpp new file mode 100644 index 00000000..5344ba31 --- /dev/null +++ b/0001-0500/0027-Remove-Element/cpp-0027/main1.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/remove-element/ +/// Author : liuyubobobo +/// Time : 2016-12-05 + + +#include +#include +#include +#include + +using namespace std; + + +/// Two Pointers +///Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { + +public: + int removeElement(vector& nums, int val) { + + int newl = 0; + for( int i = 0 ; i < nums.size() ; i ++ ) + if( nums[i] != val ) + nums[newl++] = nums[i]; + + return newl; + } +}; + + +int main() { + + vector nums = {3, 2, 2, 3}; + int val = 3; + + cout << Solution().removeElement(nums, val) << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0027-Remove-Element/cpp-0027/main2.cpp b/0001-0500/0027-Remove-Element/cpp-0027/main2.cpp new file mode 100644 index 00000000..6f2bed9f --- /dev/null +++ b/0001-0500/0027-Remove-Element/cpp-0027/main2.cpp @@ -0,0 +1,44 @@ +/// Source : https://leetcode.com/problems/remove-element/ +/// Author : liuyubobobo +/// Time : 2016-12-05 + +#include +#include +#include +#include + +using namespace std; + +/// Two Pointers +/// Move the deleted element to the last +/// This method would be save the unnecessary copy when the removed element is rare. +/// +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { + +public: + int removeElement(vector& nums, int val) { + + int newl = nums.size(); + int i = 0; + while( i < newl ) + if( nums[i] == val ) + nums[i] = nums[--newl]; + else + i ++; + + return newl; + } +}; + + +int main() { + + vector nums = {3, 2, 2, 3}; + int val = 3; + + cout << Solution().removeElement(nums, val) << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0028-Implement-strStr/cpp-0028/CMakeLists.txt b/0001-0500/0028-Implement-strStr/cpp-0028/CMakeLists.txt new file mode 100644 index 00000000..1a235f53 --- /dev/null +++ b/0001-0500/0028-Implement-strStr/cpp-0028/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0028) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main4.cpp) +add_executable(cpp_0028 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0028-Implement-strStr/cpp-0028/main.cpp b/0001-0500/0028-Implement-strStr/cpp-0028/main.cpp new file mode 100644 index 00000000..523a9968 --- /dev/null +++ b/0001-0500/0028-Implement-strStr/cpp-0028/main.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/implement-strstr/ +/// Author : liuyubobobo +/// Time : 2018-03-06 + +#include + +using namespace std; + + +/// Naive implementation +/// Time Complexity: O(n * m) +/// Sapce Complexity: O(1) +class Solution { +public: + int strStr(string haystack, string needle) { + + int n = haystack.size(), m = needle.size(); + for(int i = 0 ; i <= n - m ; i ++){ + int j = 0; + for(j = 0 ; j < needle.size() ; j ++) + if(needle[j] != haystack[j + i]) + break; + if(j == needle.size()) + return i; + } + return -1; + } +}; + + +int main() { + + cout << Solution().strStr("hello", "ll") << endl; + cout << Solution().strStr("aaaaa", "bba") << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0028-Implement-strStr/cpp-0028/main2.cpp b/0001-0500/0028-Implement-strStr/cpp-0028/main2.cpp new file mode 100644 index 00000000..b36c43d6 --- /dev/null +++ b/0001-0500/0028-Implement-strStr/cpp-0028/main2.cpp @@ -0,0 +1,67 @@ +/// Source : https://leetcode.com/problems/implement-strstr/ +/// Author : liuyubobobo +/// Time : 2019-03-12 + +#include +#include +#include + +using namespace std; + + +/// Rabin-Karp +/// Time Complexity: O(n * m) +/// Sapce Complexity: O(m) +class Solution { + +private: + const int MOD = 1e9 + 7; + const int base = 256; + +public: + int strStr(string haystack, string needle) { + + if(needle == "") return 0; + if(haystack == "") return -1; + + int n = haystack.size(), m = needle.size(); + if(n < m) return -1; + + int h = 1, txthash = 0, patternhash = 0; + for(int i = 0; i < m - 1; i ++){ + h = h * 256ll % MOD; + txthash = (txthash * 256ll + haystack[i]) % MOD; + patternhash = (patternhash * 256ll + needle[i]) % MOD; + } + patternhash = (patternhash * 256ll + needle[m - 1]) % MOD; + + for(int i = m - 1; i < n; i ++){ + txthash = (txthash * 256ll + haystack[i]) % MOD; + if(txthash == patternhash && same(haystack, i - m + 1, i, needle)) + return i - m + 1; + + txthash -= haystack[i - m + 1] * (long long)h % MOD; + if(txthash < 0) txthash += MOD; + } + return -1; + } + +private: + bool same(const string& s, int start, int end, const string& t){ +// assert(end - start + 1 == t.size()); + for(int i = start; i <= end; i ++) + if(s[i] != t[i - start]) + return false; + return true; + } +}; + + +int main() { + +// cout << Solution().strStr("hello", "ll") << endl; // 2 + cout << Solution().strStr("aaaaa", "bba") << endl; // -1 +// cout << Solution().strStr("mississippi", "issip") << endl; // 4 + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0028-Implement-strStr/cpp-0028/main3.cpp b/0001-0500/0028-Implement-strStr/cpp-0028/main3.cpp new file mode 100644 index 00000000..7b9c1ba3 --- /dev/null +++ b/0001-0500/0028-Implement-strStr/cpp-0028/main3.cpp @@ -0,0 +1,69 @@ +/// Source : https://leetcode.com/problems/implement-strstr/ +/// Author : liuyubobobo +/// Time : 2019-03-11 + +#include +#include + +using namespace std; + + +/// KMP based on lps +/// Time Complexity: O(n + m) +/// Sapce Complexity: O(m) +class Solution { +public: + int strStr(string haystack, string needle) { + + if(haystack == "") return needle == "" ? 0 : -1; + if(needle == "") return 0; + + int n = haystack.size(), m = needle.size(); + vector lps = getLPS(needle, m); // longest proper prefix which is also suffix + + int i = 0, j = 0; + while(i < n){ + + if(haystack[i] == needle[j]) { + i++, j++; + + if (j == needle.size()) + return i - needle.size(); + } + + else if(j) j = lps[j - 1] ; + else i ++; + } + return -1; + } + +private: + vector getLPS(const string& pattern, int m){ + + vector lps(m, 0); + // lps[0] = 0; + + int len = 0; + int i = 1; + while(i < m) + if(pattern[i] == pattern[len]) + lps[i ++] = ++ len; + + // trick part + // a great explanation: + // https://leetcode.com/problems/implement-strstr/discuss/13160/detailed-explanation-on-building-up-lps-for-kmp-algorithm + else if(len) len = lps[len - 1]; // len -- + else i ++; + return lps; + } +}; + + +int main() { + + cout << Solution().strStr("hello", "ll") << endl; // 2 + cout << Solution().strStr("aaaaa", "bba") << endl; // -1 + cout << Solution().strStr("mississippi", "issip") << endl; // 4 + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0028-Implement-strStr/cpp-0028/main4.cpp b/0001-0500/0028-Implement-strStr/cpp-0028/main4.cpp new file mode 100644 index 00000000..836e5914 --- /dev/null +++ b/0001-0500/0028-Implement-strStr/cpp-0028/main4.cpp @@ -0,0 +1,70 @@ +/// Source : https://leetcode.com/problems/implement-strstr/ +/// Author : liuyubobobo +/// Time : 2019-03-12 + +#include +#include + +using namespace std; + + +/// KMP based on lps +/// Another way to compute lps, maybe more intuitive :-) +/// See here for details: +/// https://www.coursera.org/lecture/algorithms-on-strings/computing-prefix-function-5lDsK +/// +/// Time Complexity: O(n + m) +/// Sapce Complexity: O(m) +class Solution { +public: + int strStr(string haystack, string needle) { + + if(haystack == "") return needle == "" ? 0 : -1; + if(needle == "") return 0; + + int n = haystack.size(), m = needle.size(); + vector lps = getLPS(needle, m); // longest proper prefix which is also suffix + + int i = 0, j = 0; + while(i < n){ + + if(haystack[i] == needle[j]) { + i++, j++; + + if (j == needle.size()) + return i - needle.size(); + } + + else if(j) j = lps[j - 1] ; + else i ++; + } + return -1; + } + +private: + vector getLPS(const string& pattern, int m){ + + vector lps(m, 0); + // lps[0] = 0; + + int len = 0; + for(int i = 1; i < m; i ++){ + while(len && pattern[i] != pattern[len]) + len = lps[len - 1]; + + if(pattern[i] == pattern[len]) + lps[i] = ++ len; + } + return lps; + } +}; + + +int main() { + + cout << Solution().strStr("hello", "ll") << endl; // 2 + cout << Solution().strStr("aaaaa", "bba") << endl; // -1 + cout << Solution().strStr("mississippi", "issip") << endl; // 4 + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0028-Implement-strStr/cpp-0028/main5.cpp b/0001-0500/0028-Implement-strStr/cpp-0028/main5.cpp new file mode 100644 index 00000000..cb4559e0 --- /dev/null +++ b/0001-0500/0028-Implement-strStr/cpp-0028/main5.cpp @@ -0,0 +1,55 @@ +/// Source : https://leetcode.com/problems/implement-strstr/ +/// Author : liuyubobobo +/// Time : 2019-03-12 + +#include +#include + +using namespace std; + + +/// KMP based on DFA +/// +/// Time Complexity: O(m * all_characters + n) +/// Sapce Complexity: O(m * all_characters) +class Solution { +public: + int strStr(string haystack, string needle) { + + if(needle == "") return 0; + if(haystack == "") return -1; + + int n = haystack.size(), m = needle.size(); + vector> dfa(256, vector(m + 1, 0)); + + // dfa construction + dfa[needle[0]][0] = 1; + int lps = 0; + for(int state = 1; state < m; state ++){ + for(int c = 0; c < 256; c ++) + dfa[c][state] = dfa[c][lps]; + + dfa[needle[state]][state] = state + 1; + + lps = dfa[needle[state]][lps]; + } + + int state = 0; + for(int i = 0; i < n; i ++){ + state = dfa[haystack[i]][state]; + if(state == m) return i - m + 1; + + } + return -1; + } +}; + + +int main() { + + cout << Solution().strStr("hello", "ll") << endl; // 2 + cout << Solution().strStr("aaaaa", "bba") << endl; // -1 + cout << Solution().strStr("mississippi", "issip") << endl; // 4 + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0028-Implement-strStr/cpp-0028/main6.cpp b/0001-0500/0028-Implement-strStr/cpp-0028/main6.cpp new file mode 100644 index 00000000..eb3e3c31 --- /dev/null +++ b/0001-0500/0028-Implement-strStr/cpp-0028/main6.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/implement-strstr/ +/// Author : liuyubobobo +/// Time : 2019-03-12 + +#include +#include + +using namespace std; + + +/// BM Algorithm +/// Only bad character heuristic is used +/// +/// Time Complexity: O(m * all_characters + n) +/// Sapce Complexity: O(m * all_characters) +class Solution { +public: + int strStr(string haystack, string needle) { + + if(needle == "") return 0; + if(haystack == "") return -1; + + int n = haystack.size(), m = needle.size(); + vector bad(256, -1); // last occurrence of every character + for(int i = 0; i < m; i ++) + bad[needle[i]] = i; + + int i = 0; + while(i <= n - m){ + + int j = m - 1; + for(; j >= 0; j --) + if(needle[j] != haystack[i + j]) + break; + + if(j < 0) return i; + if(bad[haystack[i + j]] < 0) + i += j + 1; + else + i += max(1, j - bad[haystack[i + j]]); + } + return -1; + } +}; + + +int main() { + + cout << Solution().strStr("hello", "ll") << endl; // 2 + cout << Solution().strStr("aaaaa", "bba") << endl; // -1 + cout << Solution().strStr("mississippi", "issip") << endl; // 4 + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0029-Divide-Two-Integers/cpp-0029/CMakeLists.txt b/0001-0500/0029-Divide-Two-Integers/cpp-0029/CMakeLists.txt new file mode 100644 index 00000000..66e825fe --- /dev/null +++ b/0001-0500/0029-Divide-Two-Integers/cpp-0029/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0029) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0029 main.cpp) \ No newline at end of file diff --git a/0001-0500/0029-Divide-Two-Integers/cpp-0029/main.cpp b/0001-0500/0029-Divide-Two-Integers/cpp-0029/main.cpp new file mode 100644 index 00000000..0b87d3de --- /dev/null +++ b/0001-0500/0029-Divide-Two-Integers/cpp-0029/main.cpp @@ -0,0 +1,26 @@ +/// Source : https://leetcode.com/problems/divide-two-integers/ +/// Author : liuyubobobo +/// Time : 2021-02-27 + +#include + +using namespace std; + + +/// Division +/// Time Complexity: O(1) +/// Space Complexity: O(1) +class Solution { +public: + int divide(int dividend, int divisor) { + + long long res = (long long)dividend / divisor; + return (res > INT_MAX || res < INT_MIN) ? INT_MAX : res; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0030-Substring-with-Concatenation-of-All-Words/cpp-0030/CMakeLists.txt b/0001-0500/0030-Substring-with-Concatenation-of-All-Words/cpp-0030/CMakeLists.txt new file mode 100644 index 00000000..fafca30b --- /dev/null +++ b/0001-0500/0030-Substring-with-Concatenation-of-All-Words/cpp-0030/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_0030) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0030 main.cpp) diff --git a/0001-0500/0030-Substring-with-Concatenation-of-All-Words/cpp-0030/main.cpp b/0001-0500/0030-Substring-with-Concatenation-of-All-Words/cpp-0030/main.cpp new file mode 100644 index 00000000..3ac701b4 --- /dev/null +++ b/0001-0500/0030-Substring-with-Concatenation-of-All-Words/cpp-0030/main.cpp @@ -0,0 +1,81 @@ +/// Source : https://leetcode.com/problems/substring-with-concatenation-of-all-words/ +/// Author : liuyubobobo +/// Time : 2022-06-22 + +#include +#include +#include + +using namespace std; + + +/// Sliding Window +/// Time Complexity: O(word_len * |s|) +/// Space Complexity: O(|s|) +class Solution { +public: + vector findSubstring(string s, vector& words) { + + int word_len = words[0].size(); + + map words_f; + for(int i = 0; i < words.size(); i ++) words_f[words[i]] ++; + + vector res; + for(int start = 0; start < word_len; start ++){ + + vector data; + for(int i = start; i < s.size(); i += word_len) + data.push_back(s.substr(i, word_len)); + + int ok_cnt = 0, l = 0, r = -1; + map cur_f; + while(l < (int)data.size()){ + if(r + 1 < (int)data.size() && words_f.count(data[r + 1]) && cur_f[data[r + 1]] + 1 <= words_f[data[r + 1]]){ + cur_f[data[r + 1]] ++; + + if(cur_f[data[r + 1]] == words_f[data[r + 1]]){ + ok_cnt ++; + if(ok_cnt == words_f.size()) + res.push_back(start + l * word_len); + } + + r ++; + } + else{ + + if(words_f.count(data[l])){ + cur_f[data[l]] --; + if(cur_f[data[l]] + 1 == words_f[data[l]]) ok_cnt --; + } + l ++; + r = max(r, l - 1); + } + } + } + + return res; + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << ' '; cout << '\n'; +} + +int main() { + + vector words1 = {"foo", "bar"}; + print_vec(Solution().findSubstring("barfoothefoobarman", words1)); + // 0 9 + + vector words2 = {"word","good","best","word"}; + print_vec(Solution().findSubstring("wordgoodgoodgoodbestword", words2)); + // empty + + vector words3 = {"bar","foo","the"}; + print_vec(Solution().findSubstring("barfoofoobarthefoobarman", words3)); + // 6 9 12 + + return 0; +} diff --git a/0001-0500/0031-Next-Permutation/cpp-0031/CMakeLists.txt b/0001-0500/0031-Next-Permutation/cpp-0031/CMakeLists.txt new file mode 100644 index 00000000..b44070d1 --- /dev/null +++ b/0001-0500/0031-Next-Permutation/cpp-0031/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_0031) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0031 main.cpp) \ No newline at end of file diff --git a/0001-0500/0031-Next-Permutation/cpp-0031/main.cpp b/0001-0500/0031-Next-Permutation/cpp-0031/main.cpp new file mode 100644 index 00000000..587b2eca --- /dev/null +++ b/0001-0500/0031-Next-Permutation/cpp-0031/main.cpp @@ -0,0 +1,61 @@ +/// Source : https://leetcode.com/problems/next-permutation/ +/// Author : liuyubobobo +/// Time : 2021-05-04 + +#include +#include + +using namespace std; + + +/// next permutation +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + void nextPermutation(vector& nums) { + + int i; + for(i = nums.size() - 1; i >= 1; i --) + if(nums[i - 1] < nums[i]) break; + + if(i == 0){ + reverse(nums.begin(), nums.end()); + return; + } + + int j; + for(j = nums.size() - 1; j > i; j --) + if(nums[j] > nums[i - 1]) break; + + swap(nums[i - 1], nums[j]); + reverse(nums.begin() + i, nums.end()); + } +}; + + +bool is_sorted(const vector& v){ + for(int i = 1; i < v.size(); i ++) + if(v[i - 1] > v[i]) return false; + return true; +} + +void print_vec(const vector& v){ + for(int e: v) cout << e << " "; cout << endl; +} + +int main() { + + vector nums1 = {1, 2, 3}; + Solution().nextPermutation(nums1); + print_vec(nums1); + // 1 3 2 + + vector nums2 = {1, 2, 2}; + do{ + Solution().nextPermutation(nums2); + print_vec(nums2); + }while(!is_sorted(nums2)); + + return 0; +} diff --git a/0001-0500/0033-Search-in-Rotated-Sorted-Array/cpp-0033/CMakeLists.txt b/0001-0500/0033-Search-in-Rotated-Sorted-Array/cpp-0033/CMakeLists.txt new file mode 100644 index 00000000..04734f7f --- /dev/null +++ b/0001-0500/0033-Search-in-Rotated-Sorted-Array/cpp-0033/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0033) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main2.cpp) +add_executable(cpp_0033 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0033-Search-in-Rotated-Sorted-Array/cpp-0033/main.cpp b/0001-0500/0033-Search-in-Rotated-Sorted-Array/cpp-0033/main.cpp new file mode 100644 index 00000000..5401194c --- /dev/null +++ b/0001-0500/0033-Search-in-Rotated-Sorted-Array/cpp-0033/main.cpp @@ -0,0 +1,76 @@ +/// Source : https://leetcode.com/problems/search-in-rotated-sorted-array/description/ +/// Author : liuyubobobo +/// Time : 2018-06-22 + +#include +#include + +using namespace std; + +/// Binary Search +/// Time Complexity: O(logn) +/// Space Complexity: O(1) +class Solution { +public: + int search(vector& nums, int target) { + + int l = 0, r = nums.size() - 1; + while(l <= r){ + //cout << "l : " << l << " r : " << r << endl; + int mid = l + (r - l) / 2; + if(nums[mid] == target) + return mid; + //cout << "mid : " << mid << endl; + + if(target < nums[mid]){ + if(nums[l] <= nums[r] || nums[mid] < nums[l]) + r = mid - 1; + else if(target >= nums[l]) + r = mid - 1; + else + l = mid + 1; + } + else{ // target > nums[mid] + if(nums[l] <= nums[r] || nums[mid] > nums[r]) + l = mid + 1; + else if(target >= nums[l]) + r = mid - 1; + else + l = mid + 1; + } + } + + return -1; + } +}; + + +int main() { + + vector nums1 = {4, 5, 6, 7, 0, 1, 2}; + int target1 = 0; + cout << Solution().search(nums1, target1) << endl; + // 4 + + vector nums2 = {4, 5, 6, 7, 0, 1, 2}; + int target2 = 3; + cout << Solution().search(nums2, target2) << endl; + // -1 + + vector nums3 = {1, 3}; + int target3 = 3; + cout << Solution().search(nums3, target3) << endl; + // 1 + + vector nums4 = {5, 1, 3}; + int target4 = 5; + cout << Solution().search(nums4, target4) << endl; + // 0 + + vector nums5 = {4, 5, 6, 7, 8, 1, 2, 3}; + int target5 = 8; + cout << Solution().search(nums5, target5) << endl; + // 4 + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0033-Search-in-Rotated-Sorted-Array/cpp-0033/main2.cpp b/0001-0500/0033-Search-in-Rotated-Sorted-Array/cpp-0033/main2.cpp new file mode 100644 index 00000000..df6cc64b --- /dev/null +++ b/0001-0500/0033-Search-in-Rotated-Sorted-Array/cpp-0033/main2.cpp @@ -0,0 +1,69 @@ +/// Source : https://leetcode.com/problems/search-in-rotated-sorted-array/description/ +/// Author : liuyubobobo +/// Time : 2020-10-14 + +#include +#include + +using namespace std; + +/// Find max value and do Binary Search +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int search(vector& nums, int target) { + + if(nums.size() == 0) return -1; + int max_index = max_element(nums.begin(), nums.end()) - nums.begin(); + + int l = 0, r = max_index; + while(l <= r){ + int mid = l + (r - l) / 2; + if(nums[mid] == target) return mid; + if(target < nums[mid]) r = mid - 1; + else l = mid + 1; + } + + l = max_index + 1, r = nums.size() - 1; + while(l <= r){ + int mid = l + (r - l) / 2; + if(nums[mid] == target) return mid; + if(target < nums[mid]) r = mid - 1; + else l = mid + 1; + } + + return -1; + } +}; + + +int main() { + + vector nums1 = {4, 5, 6, 7, 0, 1, 2}; + int target1 = 0; + cout << Solution().search(nums1, target1) << endl; + // 4 + + vector nums2 = {4, 5, 6, 7, 0, 1, 2}; + int target2 = 3; + cout << Solution().search(nums2, target2) << endl; + // -1 + + vector nums3 = {1, 3}; + int target3 = 3; + cout << Solution().search(nums3, target3) << endl; + // 1 + + vector nums4 = {5, 1, 3}; + int target4 = 5; + cout << Solution().search(nums4, target4) << endl; + // 0 + + vector nums5 = {4, 5, 6, 7, 8, 1, 2, 3}; + int target5 = 8; + cout << Solution().search(nums5, target5) << endl; + // 4 + + return 0; +} \ No newline at end of file diff --git a/0034-Search-for-a-Range/cpp-0034/CMakeLists.txt b/0001-0500/0034-Search-for-a-Range/cpp-0034/CMakeLists.txt similarity index 100% rename from 0034-Search-for-a-Range/cpp-0034/CMakeLists.txt rename to 0001-0500/0034-Search-for-a-Range/cpp-0034/CMakeLists.txt diff --git a/0001-0500/0034-Search-for-a-Range/cpp-0034/main.cpp b/0001-0500/0034-Search-for-a-Range/cpp-0034/main.cpp new file mode 100644 index 00000000..ebbc30ec --- /dev/null +++ b/0001-0500/0034-Search-for-a-Range/cpp-0034/main.cpp @@ -0,0 +1,49 @@ +/// Source : https://leetcode.com/problems/search-for-a-range/description/ +/// Author : liuyubobobo +/// Time : 2017-11-16 +/// Updated: 2021-04-29 + +#include +#include +#include + +using namespace std; + +/// Linear Scan +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + vector searchRange(vector& nums, int target) { + + bool ok = false; + int first = nums.size(), last = -1; + for(int i = 0 ; i < nums.size() ; i ++) + if(nums[i] == target){ + first = min(first, i); + last = max(last, i); + ok = true; + } + + if(ok) return {first, last}; + return {-1, -1}; + } +}; + + +void printVec(const vector& vec){ + for(int e: vec) + cout << e << " "; + cout << endl; +} + +int main() { + + int nums[6] = {5, 7, 7, 8, 8, 10}; + int target = 8; + vector vec(nums, nums + sizeof(nums) / sizeof(int)); + + printVec(Solution().searchRange(vec, target)); + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0034-Search-for-a-Range/cpp-0034/main2.cpp b/0001-0500/0034-Search-for-a-Range/cpp-0034/main2.cpp new file mode 100644 index 00000000..0aa63d4b --- /dev/null +++ b/0001-0500/0034-Search-for-a-Range/cpp-0034/main2.cpp @@ -0,0 +1,78 @@ +/// Source : https://leetcode.com/problems/search-for-a-range/description/ +/// Author : liuyubobobo +/// Time : 2017-11-16 +/// Updated: 2021-04-29 + +#include +#include +#include +#include + +using namespace std; + +/// Using STL lower_bounf and upper_bound +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + vector searchRange(vector& nums, int target) { + + vector::iterator lowerIter = lower_bound(nums.begin(), nums.end(), target); + int first = -1; + if(lowerIter != nums.end() && *lowerIter == target) + first = lowerIter - nums.begin(); + else return {-1, -1}; + + vector::iterator upperIter = upper_bound(nums.begin(), nums.end(), target); + int last = -1; + if(upperIter != nums.begin()){ + upperIter --; + last = upperIter - nums.begin(); + } + else return {-1, -1}; + + return {first, last}; + } +}; + + +void printVec(const vector& vec){ + for(int e: vec) + cout << e << " "; + cout << endl; +} + +int main() { + + int nums1[6] = {5, 7, 7, 8, 8, 10}; + int target1 = 8; + vector vec1(nums1, nums1 + sizeof(nums1) / sizeof(int)); + + printVec(Solution().searchRange(vec1, target1)); + // 3, 4 + + // --- + + int nums2[1] = {1}; + int target2 = 0; + vector vec2(nums2, nums2 + sizeof(nums2) / sizeof(int)); + + printVec(Solution().searchRange(vec2, target2)); + // -1, -1 + + // --- + + int nums3[1] = {1}; + int target3 = 1; + vector vec3(nums3, nums3 + sizeof(nums3) / sizeof(int)); + + printVec(Solution().searchRange(vec3, target3)); + // 0, 0 + + // --- + vector vec4; + printVec(Solution().searchRange(vec4, 0)); + // -1, -1 + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0034-Search-for-a-Range/cpp-0034/main3.cpp b/0001-0500/0034-Search-for-a-Range/cpp-0034/main3.cpp new file mode 100644 index 00000000..29a0209e --- /dev/null +++ b/0001-0500/0034-Search-for-a-Range/cpp-0034/main3.cpp @@ -0,0 +1,108 @@ +/// Source : https://leetcode.com/problems/search-for-a-range/description/ +/// Author : liuyubobobo +/// Time : 2017-11-16 +/// Updated: 2021-04-29 + +#include +#include +#include + +using namespace std; + +/// Binary Search +/// Time Complexity: O(logn) +/// Space Complexity: O(1) +class Solution { + +public: + vector searchRange(vector& nums, int target) { + + int lowerIndex = firstOccurance(nums, target); + int first = -1; + if(lowerIndex != nums.size() && nums[lowerIndex] == target) + first = lowerIndex; + else return {-1, -1}; + // cout << "first = " << first << endl; + + int upperIndex = lastOccurance(nums, target); + int last = -1; + if(upperIndex != 0){ + upperIndex --; + last = upperIndex; + } + else return {-1, -1}; + + return {first, last}; + } + +private: + // same to lower_bound + int firstOccurance(const vector& nums, int target){ + + int l = 0, r = nums.size(); + while(l != r){ + int mid = l + (r - l) / 2; + if(nums[mid] < target) + l = mid + 1; + else // nums[mid] >= target + r = mid; + } + return l; + } + + // same to upper_bound + int lastOccurance(const vector& nums, int target){ + + int l = 0, r = nums.size(); + while(l != r){ + int mid = l + (r - l) / 2; + if(nums[mid] <= target) + l = mid + 1; + else // nums[mid] > target + r = mid; + } + return l; + } +}; + + +void printVec(const vector& vec){ + for(int e: vec) + cout << e << " "; + cout << endl; +} + +int main() { + + int nums1[6] = {5, 7, 7, 8, 8, 10}; + int target1 = 8; + vector vec1(nums1, nums1 + sizeof(nums1) / sizeof(int)); + + printVec(Solution().searchRange(vec1, target1)); + // 3, 4 + + // --- + + int nums2[1] = {1}; + int target2 = 0; + vector vec2(nums2, nums2 + sizeof(nums2) / sizeof(int)); + + printVec(Solution().searchRange(vec2, target2)); + // -1, -1 + + // --- + + int nums3[1] = {1}; + int target3 = 1; + vector vec3(nums3, nums3 + sizeof(nums3) / sizeof(int)); + + printVec(Solution().searchRange(vec3, target3)); + // 0, 0 + + // --- + vector vec4; + printVec(Solution().searchRange(vec4, 0)); + // -1, -1 + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0035-Search-Insert-Position/cpp-0035/CMakeLists.txt b/0001-0500/0035-Search-Insert-Position/cpp-0035/CMakeLists.txt new file mode 100644 index 00000000..4d4d38f9 --- /dev/null +++ b/0001-0500/0035-Search-Insert-Position/cpp-0035/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_0035) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0035 main.cpp) \ No newline at end of file diff --git a/0001-0500/0035-Search-Insert-Position/cpp-0035/main.cpp b/0001-0500/0035-Search-Insert-Position/cpp-0035/main.cpp new file mode 100644 index 00000000..eff859aa --- /dev/null +++ b/0001-0500/0035-Search-Insert-Position/cpp-0035/main.cpp @@ -0,0 +1,25 @@ +/// Source : https://leetcode.com/problems/search-insert-position/ +/// Author : liuyubobobo +/// Time : 2021-07-02 + +#include +#include + +using namespace std; + + +/// lower bound +/// Time Complexity: O(logn) +/// Space Complexity: O(1) +class Solution { +public: + int searchInsert(vector& nums, int target) { + return lower_bound(nums.begin(), nums.end(), target) - nums.begin(); + } +}; + + +int main() { + + return 0; +} diff --git a/old/0036 Valid Sudoku/cpp-Valid-Sudoku/CMakeLists.txt b/0001-0500/0036-Valid-Sudoku/cpp-0036/CMakeLists.txt similarity index 100% rename from old/0036 Valid Sudoku/cpp-Valid-Sudoku/CMakeLists.txt rename to 0001-0500/0036-Valid-Sudoku/cpp-0036/CMakeLists.txt diff --git a/0001-0500/0036-Valid-Sudoku/cpp-0036/main.cpp b/0001-0500/0036-Valid-Sudoku/cpp-0036/main.cpp new file mode 100644 index 00000000..8712f035 --- /dev/null +++ b/0001-0500/0036-Valid-Sudoku/cpp-0036/main.cpp @@ -0,0 +1,91 @@ +/// Source : https://leetcode.com/problems/valid-sudoku/ +/// Author : liuyubobobo +/// Time : 2016-12-05 + +#include +#include +#include +#include + +using namespace std; + + +/// Using hashtable to check every row, column and block. +/// Time Complexity: O(9*9) +/// Space Complexity: O(1) +class Solution { +public: + bool isValidSudoku(vector>& board) { + + bool hashtable[9][9]; + + // check for every row + memset(hashtable, 0, sizeof(hashtable)); + for(int i = 0 ; i < 9 ; i ++) + for(int j = 0 ; j < 9 ; j ++) + if(board[i][j] != '.'){ + int num = board[i][j] - '0' - 1; + if(hashtable[i][num] == 1) + return false; + hashtable[i][num] = 1; + } + + // check for every col + memset(hashtable, 0, sizeof(hashtable)); + for(int i = 0 ; i < 9 ; i ++) + for(int j = 0 ; j < 9 ; j ++) + if(board[j][i] != '.'){ + int num = board[j][i] - '0' - 1; + if( hashtable[i][num] == 1 ) + return false; + hashtable[i][num] = 1; + } + + // check for every block + memset(hashtable, 0, sizeof(hashtable)); + for(int i = 0 ; i < 9 ; i ++){ + int br = i/3; + int bc = i%3; + for(int ii = 0 ; ii < 3 ; ii ++) + for(int jj = 0 ; jj < 3 ; jj ++){ + int r = br*3 + ii; + int c = bc*3 + jj; + if(board[r][c] != '.'){ + int num = board[r][c] - '0' - 1; + if (hashtable[i][num] == 1) + return false; + hashtable[i][num] = 1; + } + } + } + return true; + } +}; + + +int main() { + + vector input = { + "53..7....", + "6..195...", + ".98....6.", + "8...6...3", + "4..8.3..1", + "7...2...6", + ".6....28.", + "...419..5", + "....8..79" + }; + + vector> board; + for(const string& row: input){ + vector r; + for(char c: row) + r.push_back(c); + board.push_back(r); + } + + cout << Solution().isValidSudoku(board) << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0037-Sudoku-Solver/cpp-0037/CMakeLists.txt b/0001-0500/0037-Sudoku-Solver/cpp-0037/CMakeLists.txt new file mode 100644 index 00000000..119d2146 --- /dev/null +++ b/0001-0500/0037-Sudoku-Solver/cpp-0037/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0037) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0037 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0037-Sudoku-Solver/cpp-0037/main.cpp b/0001-0500/0037-Sudoku-Solver/cpp-0037/main.cpp new file mode 100644 index 00000000..775fc6ea --- /dev/null +++ b/0001-0500/0037-Sudoku-Solver/cpp-0037/main.cpp @@ -0,0 +1,74 @@ +/// Source : https://leetcode.com/problems/sudoku-solver/description/ +/// Author : liuyubobobo +/// Time : 2018-10-03 + +#include +#include +#include + +using namespace std; + + +/// Backtracking +/// Time Complexity: O(n^{need to fill}) +/// Space Complexity: O(9*9) +class Solution { +public: + void solveSudoku(vector>& board) { + + vector> row(9, vector(10, false)); + vector> col(9, vector(10, false)); + vector> block(9, vector(10, false)); + for(int i = 0; i < 9; i ++) + for(int j = 0; j < 9; j ++) + if(board[i][j] != '.'){ + row[i][board[i][j] - '0'] = true; + col[j][board[i][j] - '0'] = true; + block[i / 3 * 3 + j / 3][board[i][j] - '0'] = true; + } + + for(int i = 0; i < 81; i ++) + if(board[i / 9][i % 9] == '.'){ + assert(dfs(board, i, row, col, block)); + return; + } + } + +private: + bool dfs(vector>& board, int pos, + vector>& row, vector>& col, + vector>& block){ + + if(pos == 81) + return true; + + int next = pos + 1; + for(; next < 81; next ++) + if(board[next / 9][next % 9] == '.') + break; + + int x = pos / 9, y = pos % 9; + for(int i = 1; i <= 9; i ++) + if(!row[x][i] && !col[y][i] && !block[x / 3 * 3 + y / 3][i]){ + row[x][i] = true; + col[y][i] = true; + block[x / 3 * 3 + y / 3][i] = true; + board[x][y] = '0' + i; + + if(dfs(board, next, row, col, block)) + return true; + + row[x][i] = false; + col[y][i] = false; + block[x / 3 * 3 + y / 3][i] = false; + board[x][y] = '.'; + } + return false; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0037-Sudoku-Solver/java-0037/src/Solution.java b/0001-0500/0037-Sudoku-Solver/java-0037/src/Solution.java new file mode 100644 index 00000000..3eed3fe8 --- /dev/null +++ b/0001-0500/0037-Sudoku-Solver/java-0037/src/Solution.java @@ -0,0 +1,56 @@ +/// Source : https://leetcode.com/problems/sudoku-solver/description/ +/// Author : liuyubobobo +/// Time : 2018-10-03 + +class Solution { + public void solveSudoku(char[][] board) { + + boolean[][] row = new boolean[9][10]; + boolean[][] col = new boolean[9][10]; + boolean[][] block = new boolean[9][10]; + for(int i = 0; i < 9; i ++) + for(int j = 0; j < 9; j ++) + if(board[i][j] != '.'){ + row[i][board[i][j] - '0'] = true; + col[j][board[i][j] - '0'] = true; + block[i / 3 * 3 + j / 3][board[i][j] - '0'] = true; + } + + for(int i = 0; i < 81; i ++) + if(board[i / 9][i % 9] == '.'){ + assert(dfs(board, i, row, col, block)); + return; + } + } + + + private boolean dfs(char[][] board, int pos, + boolean[][] row, boolean[][] col, boolean[][] block){ + + if(pos == 81) + return true; + + int next = pos + 1; + for(; next < 81; next ++) + if(board[next / 9][next % 9] == '.') + break; + + int x = pos / 9, y = pos % 9; + for(int i = 1; i <= 9; i ++) + if(!row[x][i] && !col[y][i] && !block[x / 3 * 3 + y / 3][i]){ + row[x][i] = true; + col[y][i] = true; + block[x / 3 * 3 + y / 3][i] = true; + board[x][y] = (char)('0' + i); + + if(dfs(board, next, row, col, block)) + return true; + + row[x][i] = false; + col[y][i] = false; + block[x / 3 * 3 + y / 3][i] = false; + board[x][y] = '.'; + } + return false; + } +} \ No newline at end of file diff --git a/0001-0500/0038-Count-and-Say/cpp-0038/CMakeLists.txt b/0001-0500/0038-Count-and-Say/cpp-0038/CMakeLists.txt new file mode 100644 index 00000000..485c45de --- /dev/null +++ b/0001-0500/0038-Count-and-Say/cpp-0038/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0038) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0038 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0038-Count-and-Say/cpp-0038/main.cpp b/0001-0500/0038-Count-and-Say/cpp-0038/main.cpp new file mode 100644 index 00000000..5159174d --- /dev/null +++ b/0001-0500/0038-Count-and-Say/cpp-0038/main.cpp @@ -0,0 +1,51 @@ +/// Source : https://leetcode.com/problems/count-and-say/description/ +/// Author : liuyubobobo +/// Time : 2018-10-03 + +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n * 2^n) +/// Space Complexity: O(2^n) +class Solution { +public: + string countAndSay(int n) { + + string s = "1"; + if(n == 1) + return s; + + for(int i = 2; i <= n; i ++) + s = next(s); + return s; + } + +private: + string next(const string& s){ + + string ret = ""; + int start = 0; + for(int i = start + 1; i <= s.size(); i ++) + if(i == s.size() || s[i] != s[start]){ + ret += to_string(i - start) + s[start]; + start = i; + } + return ret; + } +}; + + +int main() { + + cout << Solution().countAndSay(1) << endl; + cout << Solution().countAndSay(2) << endl; + cout << Solution().countAndSay(3) << endl; + cout << Solution().countAndSay(4) << endl; + cout << Solution().countAndSay(5) << endl; + cout << Solution().countAndSay(30) << endl; + + return 0; +} \ No newline at end of file diff --git a/0039-Combination-Sum/cpp-0039/CMakeLists.txt b/0001-0500/0039-Combination-Sum/cpp-0039/CMakeLists.txt similarity index 100% rename from 0039-Combination-Sum/cpp-0039/CMakeLists.txt rename to 0001-0500/0039-Combination-Sum/cpp-0039/CMakeLists.txt diff --git a/0039-Combination-Sum/cpp-0039/main.cpp b/0001-0500/0039-Combination-Sum/cpp-0039/main.cpp similarity index 100% rename from 0039-Combination-Sum/cpp-0039/main.cpp rename to 0001-0500/0039-Combination-Sum/cpp-0039/main.cpp diff --git a/0040-Combination-Sum-II/cpp-0040/CMakeLists.txt b/0001-0500/0040-Combination-Sum-II/cpp-0040/CMakeLists.txt similarity index 100% rename from 0040-Combination-Sum-II/cpp-0040/CMakeLists.txt rename to 0001-0500/0040-Combination-Sum-II/cpp-0040/CMakeLists.txt diff --git a/0040-Combination-Sum-II/cpp-0040/main.cpp b/0001-0500/0040-Combination-Sum-II/cpp-0040/main.cpp similarity index 100% rename from 0040-Combination-Sum-II/cpp-0040/main.cpp rename to 0001-0500/0040-Combination-Sum-II/cpp-0040/main.cpp diff --git a/0001-0500/0041-First-Missing-Positive/cpp-0041/CMakeLists.txt b/0001-0500/0041-First-Missing-Positive/cpp-0041/CMakeLists.txt new file mode 100644 index 00000000..46ad0de2 --- /dev/null +++ b/0001-0500/0041-First-Missing-Positive/cpp-0041/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(cpp_0041) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(cpp_0041 main.cpp) \ No newline at end of file diff --git a/0001-0500/0041-First-Missing-Positive/cpp-0041/main.cpp b/0001-0500/0041-First-Missing-Positive/cpp-0041/main.cpp new file mode 100644 index 00000000..e4e87539 --- /dev/null +++ b/0001-0500/0041-First-Missing-Positive/cpp-0041/main.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/first-missing-positive/ +/// Author : liuyubobobo +/// Time : 2019-02-07 + +#include +#include + +using namespace std; + + +/// Index as a hash key +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int firstMissingPositive(vector& nums) { + + int n = nums.size(), cur = 0; + for(int i = 0; i < n; i ++) + if(nums[i] <= 0) + swap(nums[i--], nums[--n]); + + //nums[0...n) are all positives +// for(int e: nums) +// cout << e << " "; +// cout << endl; +// cout << "size = " << n << endl; + + for(int i = 0; i < n; i ++) + if(abs(nums[i]) - 1 < n && nums[abs(nums[i]) - 1] > 0) + nums[abs(nums[i]) - 1] *= -1; + // nums[i] < 0 means there exists i + 1 +// for(int e: nums) +// cout << e << " "; +// cout << endl; + + for(int i = 0; i < n; i ++) + if(nums[i] > 0) + return i + 1; + return n + 1; + } +}; + + +int main() { + + vector nums = {3, 4, -1, 1}; + cout << Solution().firstMissingPositive(nums) << endl; + // 2 + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0042-Trapping-Rain-Water/cpp-0042/CMakeLists.txt b/0001-0500/0042-Trapping-Rain-Water/cpp-0042/CMakeLists.txt new file mode 100644 index 00000000..869e3771 --- /dev/null +++ b/0001-0500/0042-Trapping-Rain-Water/cpp-0042/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0042) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main5.cpp) +add_executable(cpp_0042 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0042-Trapping-Rain-Water/cpp-0042/main.cpp b/0001-0500/0042-Trapping-Rain-Water/cpp-0042/main.cpp new file mode 100644 index 00000000..adac8231 --- /dev/null +++ b/0001-0500/0042-Trapping-Rain-Water/cpp-0042/main.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/trapping-rain-water/description/ +/// Author : liuyubobobo +/// Time : 2018-09-16 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n^2) +/// Space Complexity: O(1) +class Solution { +public: + int trap(vector& height) { + + if(height.size() <= 2) + return 0; + + int res = 0; + for(int i = 1; i < height.size() - 1; i ++) { + int lmax = height[i], rmax = height[i]; + for (int l = i - 1; l >= 0; l --) + lmax = max(lmax, height[l]); + for(int r = i + 1; r < height.size(); r ++) + rmax = max(rmax, height[r]); + res += min(lmax, rmax) - height[i]; + } + return res; + } +}; + + +int main() { + + vector height1 = {0,1,0,2,1,0,1,3,2,1,2,1}; + cout << Solution().trap(height1) << endl; + // 6 + + vector height2 = {4,2,3}; + cout << Solution().trap(height2) << endl; + // 1 + + vector height3 = {4, 2, 0, 3, 2, 5}; + cout << Solution().trap(height3) << endl; + // 9 + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0042-Trapping-Rain-Water/cpp-0042/main2.cpp b/0001-0500/0042-Trapping-Rain-Water/cpp-0042/main2.cpp new file mode 100644 index 00000000..4a8ac762 --- /dev/null +++ b/0001-0500/0042-Trapping-Rain-Water/cpp-0042/main2.cpp @@ -0,0 +1,67 @@ +/// Source : https://leetcode.com/problems/trapping-rain-water/description/ +/// Author : liuyubobobo +/// Time : 2018-09-16 + +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int trap(vector& height) { + + if(height.size() <= 2) + return 0; + + vector rdp(height.size(), -1); + getR(0, height, rdp); + + vector ldp(height.size(), -1); + getL(height.size() - 1, height, ldp); + + int res = 0; + for(int i = 0; i < height.size(); i ++) + res += min(ldp[i], rdp[i]) - height[i]; + return res; + } + +private: + int getR(int index, const vector& height, vector& rdp){ + + if(index == height.size() - 1) + return rdp[index] = height[index]; + + return rdp[index] = max(height[index], getR(index + 1, height, rdp)); + } + + int getL(int index, const vector& height, vector& ldp){ + + if(index == 0) + return ldp[index] = height[index]; + + return ldp[index] = max(height[index], getL(index - 1, height, ldp)); + } +}; + + +int main() { + + vector height1 = {0,1,0,2,1,0,1,3,2,1,2,1}; + cout << Solution().trap(height1) << endl; + // 6 + + vector height2 = {4,2,3}; + cout << Solution().trap(height2) << endl; + // 1 + + vector height3 = {4, 2, 0, 3, 2, 5}; + cout << Solution().trap(height3) << endl; + // 9 + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0042-Trapping-Rain-Water/cpp-0042/main3.cpp b/0001-0500/0042-Trapping-Rain-Water/cpp-0042/main3.cpp new file mode 100644 index 00000000..ddadb693 --- /dev/null +++ b/0001-0500/0042-Trapping-Rain-Water/cpp-0042/main3.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/trapping-rain-water/description/ +/// Author : liuyubobobo +/// Time : 2018-09-16 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int trap(vector& height) { + + if(height.size() <= 2) + return 0; + + vector rdp(height.size(), height.back()); + for(int i = height.size() - 2; i >= 0; i --) + rdp[i] = max(height[i], rdp[i + 1]); + + vector ldp(height.size(), height[0]); + for(int i = 1; i < height.size(); i ++) + ldp[i] = max(height[i], ldp[i - 1]); + + int res = 0; + for(int i = 0; i < height.size(); i ++) + res += min(ldp[i], rdp[i]) - height[i]; + return res; + } +}; + + +int main() { + + vector height1 = {0,1,0,2,1,0,1,3,2,1,2,1}; + cout << Solution().trap(height1) << endl; + // 6 + + vector height2 = {4,2,3}; + cout << Solution().trap(height2) << endl; + // 1 + + vector height3 = {4, 2, 0, 3, 2, 5}; + cout << Solution().trap(height3) << endl; + // 9 + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0042-Trapping-Rain-Water/cpp-0042/main4.cpp b/0001-0500/0042-Trapping-Rain-Water/cpp-0042/main4.cpp new file mode 100644 index 00000000..981435b7 --- /dev/null +++ b/0001-0500/0042-Trapping-Rain-Water/cpp-0042/main4.cpp @@ -0,0 +1,56 @@ +/// Source : https://leetcode.com/problems/trapping-rain-water/description/ +/// Author : liuyubobobo +/// Time : 2018-09-16 + +#include +#include + +using namespace std; + + +/// Using Stack +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int trap(vector& height) { + + if(height.size() <= 2) + return 0; + + vector stack; + int res = 0; + for(int i = 0; i < height.size(); i ++){ + while(!stack.empty() && height[i] > height[stack.back()]){ + int cur = stack.back(); + stack.pop_back(); + if(stack.empty()) + break; + + int dis = i - stack.back() - 1; + int h = min(height[stack.back()], height[i]) - height[cur]; + res += h * dis; + } + stack.push_back(i); + } + return res; + } +}; + + +int main() { + + vector height1 = {0,1,0,2,1,0,1,3,2,1,2,1}; + cout << Solution().trap(height1) << endl; + // 6 + + vector height2 = {4,2,3}; + cout << Solution().trap(height2) << endl; + // 1 + + vector height3 = {4, 2, 0, 3, 2, 5}; + cout << Solution().trap(height3) << endl; + // 9 + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0042-Trapping-Rain-Water/cpp-0042/main5.cpp b/0001-0500/0042-Trapping-Rain-Water/cpp-0042/main5.cpp new file mode 100644 index 00000000..e773a3a2 --- /dev/null +++ b/0001-0500/0042-Trapping-Rain-Water/cpp-0042/main5.cpp @@ -0,0 +1,59 @@ +/// Source : https://leetcode.com/problems/trapping-rain-water/description/ +/// Author : liuyubobobo +/// Time : 2018-09-16 + +#include +#include + +using namespace std; + + +/// Two Pointers +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int trap(vector& height) { + + if(height.size() <= 2) + return 0; + + int res = 0; + int l = 0, r = height.size() - 1, lmax_i = l, rmax_i = r; + while(l < r){ + if(height[l] < height[r]){ + l ++; + if(height[l] < height[lmax_i]) + res += min(height[lmax_i], height[rmax_i]) - height[l]; + else + lmax_i = l; + } + else{ + r --; + if(height[r] < height[rmax_i]) + res += min(height[lmax_i], height[rmax_i]) - height[r]; + else + rmax_i = r; + } + } + return res; + } +}; + + +int main() { + + vector height1 = {0,1,0,2,1,0,1,3,2,1,2,1}; + cout << Solution().trap(height1) << endl; + // 6 + + vector height2 = {4,2,3}; + cout << Solution().trap(height2) << endl; + // 1 + + vector height3 = {4, 2, 0, 3, 2, 5}; + cout << Solution().trap(height3) << endl; + // 9 + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0043-Multiply-Strings/cpp-0043/CMakeLists.txt b/0001-0500/0043-Multiply-Strings/cpp-0043/CMakeLists.txt new file mode 100644 index 00000000..3f795255 --- /dev/null +++ b/0001-0500/0043-Multiply-Strings/cpp-0043/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0043) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0043 main.cpp) diff --git a/0001-0500/0043-Multiply-Strings/cpp-0043/main.cpp b/0001-0500/0043-Multiply-Strings/cpp-0043/main.cpp new file mode 100644 index 00000000..8ac8d3b2 --- /dev/null +++ b/0001-0500/0043-Multiply-Strings/cpp-0043/main.cpp @@ -0,0 +1,79 @@ +/// Source : https://leetcode.com/problems/multiply-strings/ +/// Author : liuyubobobo +/// Time : 2021-11-07 + +#include +#include + +using namespace std; + + +/// Simulation +class Solution { +public: + string multiply(string num1, string num2) { + + if(num1 == "0" || num2 == "0") return "0"; + + vector v1, v2; + for(int i = num1.size() - 1; i >= 0; i --) v1.push_back(num1[i] - '0'); + for(int i = num2.size() - 1; i >= 0; i --) v2.push_back(num2[i] - '0'); + + vector res = {0}; + for(int i = 0; i < v1.size(); i ++){ + vector tres = mul(v2, v1[i]); + reverse(tres.begin(), tres.end()); + for(int j = 0; j < i; j ++) tres.push_back(0); + reverse(tres.begin(), tres.end()); + + add(res, tres); + } + + while(res.back() == 0) res.pop_back(); + assert(res.size()); + + string s = ""; + for(int i = res.size() - 1; i >= 0; i --) s += string(1, '0' + res[i]); + return s; + } + +private: + void add(vector& res, vector& tres){ + + while(res.size() < tres.size()) res.push_back(0); + while(tres.size() < res.size()) tres.push_back(0); + + int carry = 0; + for(int i = 0; i < tres.size(); i ++){ + int t = res[i] + tres[i] + carry; + res[i] = t % 10; + carry = t >= 10; + } + if(carry) res.push_back(1); + } + + vector mul(const vector& v, int m){ + assert(0 <= m && m < 10); + + vector res; + int carry = 0; + for(int i = 0; i < v.size(); i ++){ + res.push_back((v[i] * m + carry) % 10); + carry = (v[i] * m + carry) / 10; + } + if(carry) res.push_back(carry); + return res; + } +}; + + +int main() { + + cout << Solution().multiply("2", "3") << endl; + // 6 + + cout << Solution().multiply("123", "456") << endl; + // 56088 + + return 0; +} diff --git a/0001-0500/0045-Jump-Game-II/cpp-0045/CMakeLists.txt b/0001-0500/0045-Jump-Game-II/cpp-0045/CMakeLists.txt new file mode 100644 index 00000000..57c45c1c --- /dev/null +++ b/0001-0500/0045-Jump-Game-II/cpp-0045/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_0045) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0045 main2.cpp) \ No newline at end of file diff --git a/0001-0500/0045-Jump-Game-II/cpp-0045/main.cpp b/0001-0500/0045-Jump-Game-II/cpp-0045/main.cpp new file mode 100644 index 00000000..bc5eaecb --- /dev/null +++ b/0001-0500/0045-Jump-Game-II/cpp-0045/main.cpp @@ -0,0 +1,38 @@ +/// Source : https://leetcode.com/problems/jump-game-ii/ +/// Author : liuyubobobo +/// Time : 2021-05-05 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// TLE +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { +public: + int jump(vector& nums) { + + int n = nums.size(); + vector dp(n, INT_MAX); + dp[0] = 0; + for(int i = 1; i < n; i ++) + for(int j = i - 1; j >= 0; j --) + if(dp[j] != INT_MAX && j + nums[j] >= i) + dp[i] = min(dp[i], 1 + dp[j]); + return dp.back(); + } +}; + + +int main() { + + vector nums1 = {2, 3, 1, 1, 4}; + cout << Solution().jump(nums1) << endl; + // 2 + + return 0; +} diff --git a/0001-0500/0045-Jump-Game-II/cpp-0045/main2.cpp b/0001-0500/0045-Jump-Game-II/cpp-0045/main2.cpp new file mode 100644 index 00000000..d5dd43a8 --- /dev/null +++ b/0001-0500/0045-Jump-Game-II/cpp-0045/main2.cpp @@ -0,0 +1,48 @@ +/// Source : https://leetcode.com/problems/jump-game-ii/ +/// Author : liuyubobobo +/// Time : 2021-07-27 + +#include +#include +#include + +using namespace std; + + +/// BFS +/// Time Complexity: O(n + E) +/// Space Complexity: O(n) +class Solution { +public: + int jump(vector& nums) { + + int n = nums.size(); + int s = 0, t = n - 1; + vector dis(n, -1); + + queue q; + q.push(0); + dis[0] = 0; + while(!q.empty()){ + int u = q.front(); q.pop(); + if(u == t) break; + + for(int i = 1; i <= nums[u] && u + i < n; i ++) + if(dis[u + i] == -1){ + dis[u + i] = dis[u] + 1; + q.push(u + i); + } + } + return dis.back(); + } +}; + + +int main() { + + vector nums1 = {2, 3, 1, 1, 4}; + cout << Solution().jump(nums1) << endl; + // 2 + + return 0; +} diff --git a/0046-Permutations/cpp-0046/CMakeLists.txt b/0001-0500/0046-Permutations/cpp-0046/CMakeLists.txt similarity index 100% rename from 0046-Permutations/cpp-0046/CMakeLists.txt rename to 0001-0500/0046-Permutations/cpp-0046/CMakeLists.txt diff --git a/0046-Permutations/cpp-0046/main.cpp b/0001-0500/0046-Permutations/cpp-0046/main.cpp similarity index 100% rename from 0046-Permutations/cpp-0046/main.cpp rename to 0001-0500/0046-Permutations/cpp-0046/main.cpp diff --git a/0046-Permutations/cpp-0046/main2.cpp b/0001-0500/0046-Permutations/cpp-0046/main2.cpp similarity index 100% rename from 0046-Permutations/cpp-0046/main2.cpp rename to 0001-0500/0046-Permutations/cpp-0046/main2.cpp diff --git a/0046-Permutations/java-0046/src/Solution1.java b/0001-0500/0046-Permutations/java-0046/src/Solution1.java similarity index 100% rename from 0046-Permutations/java-0046/src/Solution1.java rename to 0001-0500/0046-Permutations/java-0046/src/Solution1.java diff --git a/0001-0500/0046-Permutations/java-0046/src/Solution2.java b/0001-0500/0046-Permutations/java-0046/src/Solution2.java new file mode 100644 index 00000000..4c5d53a6 --- /dev/null +++ b/0001-0500/0046-Permutations/java-0046/src/Solution2.java @@ -0,0 +1,65 @@ +/// Source : https://leetcode.com/problems/permutations/description/ +/// Author : liuyubobobo +/// Time : 2017-11-18 + +import java.util.Arrays; +import java.util.List; +import java.util.ArrayList; + +/// Recursive get all the permutations in place +/// Time Complexity: O(n!) +/// Space Complexity: O(n) +public class Solution2 { + + private ArrayList> res; + + public List> permute(int[] nums) { + + res = new ArrayList>(); + if(nums == null || nums.length == 0) + return res; + + generatePermutation(nums, 0); + + return res; + } + + private void generatePermutation(int[] nums, int index){ + + if(index == nums.length){ + List list = new ArrayList(); + for(int i : nums) + list.add(i); + res.add(list); + return; + } + + for(int i = index ; i < nums.length ; i ++){ + swap(nums, i, index); + generatePermutation(nums, index + 1); + swap(nums, i, index); + } + + return; + } + + private void swap(int[] nums, int i, int j){ + int t = nums[i]; + nums[i] = nums[j]; + nums[j] = t; + } + + private static void printList(List list){ + for(Integer e: list) + System.out.print(e + " "); + System.out.println(); + } + + public static void main(String[] args) { + + int[] nums = {1, 2, 3}; + List> res = (new Solution1()).permute(nums); + for(List list: res) + printList(list); + } +} diff --git a/0047-Permutations-II/cpp-0047/CMakeLists.txt b/0001-0500/0047-Permutations-II/cpp-0047/CMakeLists.txt similarity index 100% rename from 0047-Permutations-II/cpp-0047/CMakeLists.txt rename to 0001-0500/0047-Permutations-II/cpp-0047/CMakeLists.txt diff --git a/0047-Permutations-II/cpp-0047/main.cpp b/0001-0500/0047-Permutations-II/cpp-0047/main.cpp similarity index 100% rename from 0047-Permutations-II/cpp-0047/main.cpp rename to 0001-0500/0047-Permutations-II/cpp-0047/main.cpp diff --git a/0001-0500/0048-Rotate-Image/cpp-0048/CMakeLists.txt b/0001-0500/0048-Rotate-Image/cpp-0048/CMakeLists.txt new file mode 100644 index 00000000..14977dce --- /dev/null +++ b/0001-0500/0048-Rotate-Image/cpp-0048/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0048) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main2.cpp) +add_executable(cpp_0048 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0048-Rotate-Image/cpp-0048/main.cpp b/0001-0500/0048-Rotate-Image/cpp-0048/main.cpp new file mode 100644 index 00000000..77e7ceab --- /dev/null +++ b/0001-0500/0048-Rotate-Image/cpp-0048/main.cpp @@ -0,0 +1,61 @@ +/// Source : https://leetcode.com/problems/rotate-image/description/ +/// Author : liuyubobobo +/// Time : 2018-09-13 + +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(n^2) +/// Space Complexity: O(1) +class Solution { +public: + void rotate(vector>& matrix) { + + int n = matrix.size(); + for(int i = 0; i <= n / 2; i ++) + for(int j = i; j < n - 1 - i; j ++){ + int t = matrix[i][j]; + matrix[i][j] = matrix[n - 1 - j][i]; + matrix[n - 1 - j][i] = matrix[n - 1 - i][n - 1 - j]; + matrix[n - 1 - i][n - 1 - j] = matrix[j][n - 1 - i]; + matrix[j][n - 1 - i] = t; + Solution::print_matrix(matrix); + } + } + + static void print_matrix(const vector>& m){ + for(int i = 0; i < m.size(); i ++){ + for(int j = 0; j < m[i].size(); j ++) + cout << m[i][j] << " "; + cout << endl; + } + cout << endl; + } +}; + + +int main() { + + vector> matrix1 = { + {1, 2, 3}, + {4, 5, 6}, + {7, 8, 9} + }; + Solution().rotate(matrix1); + Solution::print_matrix(matrix1); + + vector> matrix2 = { + {1, 2, 3, 4}, + {5, 6, 7, 8}, + {9, 10, 11, 12}, + {13, 14, 15, 16} + }; + Solution().rotate(matrix2); + Solution::print_matrix(matrix2); + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0048-Rotate-Image/cpp-0048/main2.cpp b/0001-0500/0048-Rotate-Image/cpp-0048/main2.cpp new file mode 100644 index 00000000..9b200068 --- /dev/null +++ b/0001-0500/0048-Rotate-Image/cpp-0048/main2.cpp @@ -0,0 +1,59 @@ +/// Source : https://leetcode.com/problems/rotate-image/description/ +/// Author : liuyubobobo +/// Time : 2018-12-16 + +#include +#include + +using namespace std; + + +/// Reverse diagonally and then reverse row +/// Time Complexity: O(n^2) +/// Space Complexity: O(1) +class Solution { +public: + void rotate(vector>& matrix) { + + int n = matrix.size(); + for(int i = 0; i < n; i ++) + for(int j = 0; j < n - i; j ++) + swap(matrix[i][j], matrix[n - j - 1][n - i - 1]); + + for(int i = 0; i < n / 2; i ++) + for(int j = 0; j < n; j ++) + swap(matrix[i][j], matrix[n - i - 1][j]); + } +}; + + +void print_matrix(const vector>& m){ + for(int i = 0; i < m.size(); i ++){ + for(int j = 0; j < m[i].size(); j ++) + cout << m[i][j] << " "; + cout << endl; + } + cout << endl; +} + +int main() { + + vector> matrix1 = { + {1, 2, 3}, + {4, 5, 6}, + {7, 8, 9} + }; + Solution().rotate(matrix1); + print_matrix(matrix1); + + vector> matrix2 = { + {1, 2, 3, 4}, + {5, 6, 7, 8}, + {9, 10, 11, 12}, + {13, 14, 15, 16} + }; + Solution().rotate(matrix2); + print_matrix(matrix2); + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0049-Group-Anagrams/cpp-0049/CMakeLists.txt b/0001-0500/0049-Group-Anagrams/cpp-0049/CMakeLists.txt new file mode 100644 index 00000000..2d9ea917 --- /dev/null +++ b/0001-0500/0049-Group-Anagrams/cpp-0049/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0049) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main2.cpp) +add_executable(cpp_0049 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0049-Group-Anagrams/cpp-0049/main.cpp b/0001-0500/0049-Group-Anagrams/cpp-0049/main.cpp new file mode 100644 index 00000000..730936d3 --- /dev/null +++ b/0001-0500/0049-Group-Anagrams/cpp-0049/main.cpp @@ -0,0 +1,39 @@ +/// Source : https://leetcode.com/problems/group-anagrams/description/ +/// Author : liuyubobobo +/// Time : 2018-09-12 + +#include +#include +#include + +using namespace std; + + +/// Using HashMap +/// Using sorted string as key +/// +/// Time Complexity: O(n*klogk) where k is the max length of string in strs +/// Space Complexity: O(n*k) +class Solution { +public: + vector> groupAnagrams(vector& strs) { + + unordered_map> map; + for(const string& s: strs){ + string key = s; + sort(key.begin(), key.end()); + map[key].push_back(s); + } + + vector> res; + for(const auto& p: map) + res.push_back(p.second); + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0049-Group-Anagrams/cpp-0049/main2.cpp b/0001-0500/0049-Group-Anagrams/cpp-0049/main2.cpp new file mode 100644 index 00000000..06bf9bda --- /dev/null +++ b/0001-0500/0049-Group-Anagrams/cpp-0049/main2.cpp @@ -0,0 +1,49 @@ +/// Source : https://leetcode.com/problems/group-anagrams/description/ +/// Author : liuyubobobo +/// Time : 2018-09-12 + +#include +#include +#include + +using namespace std; + + +/// Using HashMap +/// Using characters frequency as key +/// +/// Time Complexity: O(n*k) where k is the max length of string in strs +/// Space Complexity: O(n*k) +class Solution { +public: + vector> groupAnagrams(vector& strs) { + + unordered_map> map; + for(const string& s: strs){ + string key = getKey(s); + map[key].push_back(s); + } + + vector> res; + for(const auto& p: map) + res.push_back(p.second); + return res; + } + +private: + string getKey(const string& s){ + vector freq(26, 0); + for(char c: s) + freq[c - 'a'] ++; + string key = ""; + for(int num: freq) + key += to_string(num) + "#"; + return key; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0050-Pow-x-n/cpp-0050/CMakeLists.txt b/0001-0500/0050-Pow-x-n/cpp-0050/CMakeLists.txt new file mode 100644 index 00000000..f8b136d7 --- /dev/null +++ b/0001-0500/0050-Pow-x-n/cpp-0050/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(cpp_0050) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(cpp_0050 main.cpp) \ No newline at end of file diff --git a/0001-0500/0050-Pow-x-n/cpp-0050/main.cpp b/0001-0500/0050-Pow-x-n/cpp-0050/main.cpp new file mode 100644 index 00000000..ba55a25a --- /dev/null +++ b/0001-0500/0050-Pow-x-n/cpp-0050/main.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/powx-n/ +/// Author : liuyubobobo +/// Time : 2018-12-20 + +#include +#include +#include + +using namespace std; + + +/// Classic Divide and Conquer to get power +/// Only deal with positive n +/// +/// Time Complexity: O(logn) +/// Space Complexity: O(logn) +class Solution { +public: + double myPow(double x, int n) { + + if(n == 0) return 1.0; + + double res = myPositivePow(x, abs((long long)n)); + if(n < 0) res = 1.0 / res; + return res; + } + +private: + double myPositivePow(double x, long long n){ + + assert(n >= 0); + if(!n) return 1.0; + + double t = myPositivePow(x, n / 2); + double res = t * t; + if(n % 2) res *= x; + return res; + } +}; + + +int main() { + + cout << Solution().myPow(2.0, -2) << endl; + // 0.25 + + cout << Solution().myPow(-2.0, 2) << endl; + // 4.0 + + cout << Solution().myPow(34.00515, -3) << endl; + // 3e-05 + + cout << Solution().myPow(1.0, -2147483648) << endl; + // 3e-05 + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0050-Pow-x-n/cpp-0050/main2.cpp b/0001-0500/0050-Pow-x-n/cpp-0050/main2.cpp new file mode 100644 index 00000000..7a44d38b --- /dev/null +++ b/0001-0500/0050-Pow-x-n/cpp-0050/main2.cpp @@ -0,0 +1,44 @@ +/// Source : https://leetcode.com/problems/powx-n/ +/// Author : liuyubobobo +/// Time : 2018-12-20 + +#include +#include + +using namespace std; + + +/// Classic Divide and Conquer to get power +/// Deal with both positive and negative n correctly +/// +/// Time Complexity: O(logn) +/// Space Complexity: O(logn) +class Solution { +public: + double myPow(double x, int n) { + + if(n == 0) return 1.0; + + double t = myPow(x, n / 2); + if(n % 2 == 0) + return t * t; + else if( n > 0) + return t * t * x; + return t * t / x; + } +}; + + +int main() { + + cout << Solution().myPow(2.0, -2) << endl; + // 0.25 + + cout << Solution().myPow(-2.0, 2) << endl; + // 4.0 + + cout << Solution().myPow(34.00515, -3) << endl; + // 3e-05 + + return 0; +} \ No newline at end of file diff --git a/0051-N-Queens/cpp-0051/CMakeLists.txt b/0001-0500/0051-N-Queens/cpp-0051/CMakeLists.txt similarity index 100% rename from 0051-N-Queens/cpp-0051/CMakeLists.txt rename to 0001-0500/0051-N-Queens/cpp-0051/CMakeLists.txt diff --git a/0051-N-Queens/cpp-0051/main.cpp b/0001-0500/0051-N-Queens/cpp-0051/main.cpp similarity index 100% rename from 0051-N-Queens/cpp-0051/main.cpp rename to 0001-0500/0051-N-Queens/cpp-0051/main.cpp diff --git a/0051-N-Queens/java-0051/src/Solution.java b/0001-0500/0051-N-Queens/java-0051/src/Solution.java similarity index 100% rename from 0051-N-Queens/java-0051/src/Solution.java rename to 0001-0500/0051-N-Queens/java-0051/src/Solution.java diff --git a/0001-0500/0052-N-Queens-II/cpp-0052/CMakeLists.txt b/0001-0500/0052-N-Queens-II/cpp-0052/CMakeLists.txt new file mode 100644 index 00000000..981b6b7d --- /dev/null +++ b/0001-0500/0052-N-Queens-II/cpp-0052/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(cpp_0052) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(cpp_0052 main.cpp) \ No newline at end of file diff --git a/0001-0500/0052-N-Queens-II/cpp-0052/main.cpp b/0001-0500/0052-N-Queens-II/cpp-0052/main.cpp new file mode 100644 index 00000000..9f73cbdc --- /dev/null +++ b/0001-0500/0052-N-Queens-II/cpp-0052/main.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/n-queens-ii/ +/// Author : liuyubobobo +/// Time : 2018-01-07 + +#include +#include + +using namespace std; + + +/// Basic Recursive +/// Time Complexity: O(n^n) +/// Space Complexity: O(n) +class Solution { +public: + int totalNQueens(int n) { + + vector row; + vector col(n, false), dia1(2 * n - 1, false), dia2(2 * n - 1, false); + + return dfs(n, 0, row, col, dia1, dia2); + } + +private: + int dfs(int n, int index, vector& row, + vector& col, vector& dia1, vector& dia2){ + + if(index == n) + return 1; + + int res = 0; + for(int i = 0; i < n; i ++) + if(!col[i] && !dia1[index + i] && !dia2[index - i + n - 1]){ + row.push_back(i); + col[i] = true; + dia1[index + i] = true; + dia2[index - i + n - 1] = true; + + res += dfs(n, index + 1, row, col, dia1, dia2); + + col[i] = false; + dia1[index + i] = false; + dia2[index - i + n - 1] = false; + row.pop_back(); + } + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0053-Maximum-Subarray/cpp-0053/CMakeLists.txt b/0001-0500/0053-Maximum-Subarray/cpp-0053/CMakeLists.txt new file mode 100644 index 00000000..43ca050f --- /dev/null +++ b/0001-0500/0053-Maximum-Subarray/cpp-0053/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(cpp_0053) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0053 main3.cpp) \ No newline at end of file diff --git a/0001-0500/0053-Maximum-Subarray/cpp-0053/main.cpp b/0001-0500/0053-Maximum-Subarray/cpp-0053/main.cpp new file mode 100644 index 00000000..c165fd66 --- /dev/null +++ b/0001-0500/0053-Maximum-Subarray/cpp-0053/main.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/maximum-subarray/ +/// Author : liuyubobobo +/// Time : 2020-04-03 + +#include +#include + +using namespace std; + + +/// Classical DP: Kadane's algorithm +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int maxSubArray(vector& nums) { + + int res = *max_element(nums.begin(), nums.end()); + if(res < 0) return res; + + int sum = 0; + for(int e: nums){ + if(sum + e < 0) sum = 0; + else{res = max(res, sum + e); sum += e;} + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0053-Maximum-Subarray/cpp-0053/main2.cpp b/0001-0500/0053-Maximum-Subarray/cpp-0053/main2.cpp new file mode 100644 index 00000000..2860eb9f --- /dev/null +++ b/0001-0500/0053-Maximum-Subarray/cpp-0053/main2.cpp @@ -0,0 +1,32 @@ +/// Source : https://leetcode.com/problems/maximum-subarray/ +/// Author : liuyubobobo +/// Time : 2020-04-03 + +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int maxSubArray(vector& nums) { + + int res = nums[0], sum = nums[0]; + for(int i = 1; i < nums.size(); i ++){ + if(sum + nums[i] < nums[i]) sum = nums[i]; + else sum += nums[i]; + res = max(res, sum); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0053-Maximum-Subarray/cpp-0053/main3.cpp b/0001-0500/0053-Maximum-Subarray/cpp-0053/main3.cpp new file mode 100644 index 00000000..d6629943 --- /dev/null +++ b/0001-0500/0053-Maximum-Subarray/cpp-0053/main3.cpp @@ -0,0 +1,62 @@ +/// Source : https://leetcode.com/problems/maximum-subarray/ +/// Author : liuyubobobo +/// Time : 2020-04-03 + +#include +#include +#include + +using namespace std; + + +/// Divide and Conqure +/// Time Complexity: O(nlogn) +/// Space Complexity: O(logn) +class Solution { +public: + int maxSubArray(vector& nums) { + + assert(nums.size()); + return maxSubArray(nums, 0, nums.size() - 1); + } + +private: + int maxSubArray(const vector& nums, int l, int r){ + + if(l == r) return nums[l]; + + int mid = (l + r) / 2; + int res = max(maxSubArray(nums, l, mid), + maxSubArray(nums, mid + 1, r)); + return max(res, crossSum(nums, l, mid, r)); + } + + int crossSum(const vector& nums, int l, int mid, int r){ + + int lres = nums[mid]; + int sum = lres; + for(int i = mid - 1; i >= l; i --){ + sum += nums[i]; + lres = max(lres, sum); + } + + int rres = nums[mid + 1]; + sum = rres; + for(int i = mid + 2; i <= r; i ++){ + sum += nums[i]; + rres = max(rres, sum); + } + + return lres + rres; + } +}; + + +int main() { + + vector nums = {-2,1,-3,4,-1,2,1,-5,4}; + cout << Solution().maxSubArray(nums) << endl; + // 6 + + return 0; +} diff --git a/0001-0500/0054-Spiral-Matrix/cpp-0054/CMakeLists.txt b/0001-0500/0054-Spiral-Matrix/cpp-0054/CMakeLists.txt new file mode 100644 index 00000000..73cd7e36 --- /dev/null +++ b/0001-0500/0054-Spiral-Matrix/cpp-0054/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0054) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0054 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0054-Spiral-Matrix/cpp-0054/main.cpp b/0001-0500/0054-Spiral-Matrix/cpp-0054/main.cpp new file mode 100644 index 00000000..598cc4ba --- /dev/null +++ b/0001-0500/0054-Spiral-Matrix/cpp-0054/main.cpp @@ -0,0 +1,76 @@ +/// Source : https://leetcode.com/problems/spiral-matrix/description/ +/// Author : liuyubobobo +/// Time : 2018-04-24 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n^2) +/// Space Complexity: O(n^2) +class Solution { + +private: + int d[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + int N, M; + +public: + vector spiralOrder(vector>& matrix) { + + N = matrix.size(); + if(N == 0) + return {}; + + M = matrix[0].size(); + if(M == 0) + return {}; + + vector> visited(N, vector(M, false)); + int curd = 0, curx = 0, cury = 0; + vector res; + while(res.size() < N * M){ + + if(!visited[curx][cury]) { + res.push_back(matrix[curx][cury]); + visited[curx][cury] = true; + } + + int nextx = curx + d[curd][0]; + int nexty = cury + d[curd][1]; + if(inArea(nextx, nexty) && !visited[nextx][nexty]){ + curx = nextx; + cury = nexty; + } + else + curd = (curd + 1) % 4; + } + return res; + } + +private: + bool inArea(int x, int y){ + return x >= 0 && x < N && y >= 0 && y < M; + } +}; + + +void print_vec(const vector& vec){ + for(int e: vec) + cout << e << " "; + cout << endl; +} + +int main() { + + vector> matrix1 = { + {1, 2, 3}, + {4, 5, 6}, + {7, 8, 9} + }; + print_vec(Solution().spiralOrder(matrix1)); + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0055-Jump-Game/cpp-0055/CMakeLists.txt b/0001-0500/0055-Jump-Game/cpp-0055/CMakeLists.txt new file mode 100644 index 00000000..bc886a80 --- /dev/null +++ b/0001-0500/0055-Jump-Game/cpp-0055/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_0055) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0055 main.cpp) \ No newline at end of file diff --git a/0001-0500/0055-Jump-Game/cpp-0055/main.cpp b/0001-0500/0055-Jump-Game/cpp-0055/main.cpp new file mode 100644 index 00000000..ec625e77 --- /dev/null +++ b/0001-0500/0055-Jump-Game/cpp-0055/main.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/jump-game/ +/// Author : liuyubobobo +/// Time : 2021-05-05 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { +public: + bool canJump(vector& nums) { + + int n = nums.size(); + vector dp(n, false); + dp[0] = true; + for(int i = 1; i < n; i ++) + for(int j = i - 1; j >= 0; j --) + if(dp[j] && j + nums[j] >= i){ + dp[i] = true; + break; + } + return dp.back(); + } +}; + + +int main() { + + return 0; +} diff --git a/0056-Merge-Intervals/cpp-0056/CMakeLists.txt b/0001-0500/0056-Merge-Intervals/cpp-0056/CMakeLists.txt similarity index 100% rename from 0056-Merge-Intervals/cpp-0056/CMakeLists.txt rename to 0001-0500/0056-Merge-Intervals/cpp-0056/CMakeLists.txt diff --git a/0001-0500/0056-Merge-Intervals/cpp-0056/main.cpp b/0001-0500/0056-Merge-Intervals/cpp-0056/main.cpp new file mode 100644 index 00000000..a4d6745e --- /dev/null +++ b/0001-0500/0056-Merge-Intervals/cpp-0056/main.cpp @@ -0,0 +1,73 @@ +/// Source : https://leetcode.com/problems/merge-intervals/description/ +/// Author : liuyubobobo +/// Time : 2017-11-15 +/// Updated: 2019-05-23 + +#include +#include + +using namespace std; + + +/// Sorting +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + vector> merge(vector>& intervals) { + + if(intervals.size() <= 1) + return intervals; + + sort(intervals.begin(), intervals.end(), [](const vector& a, const vector& b){ + if(a[0] != b[0]) + return a[0] < b[0]; + return a[1] < b[1]; + }); + + vector> res; + res.push_back(intervals[0]); + for(int i = 1 ; i < intervals.size() ; i ++){ + if(cross(res.back(), intervals[i])){ + vector newInterval = mergeInterval(res.back(), intervals[i]); + res.pop_back(); + res.push_back(newInterval); + } + else + res.push_back(intervals[i]); + } + + return res; + } + +private: + bool cross(const vector& interval1, const vector& interval2){ + return interval2[0] <= interval1[1]; + } + + vector mergeInterval(const vector& interval1, const vector& interval2){ + return {min(interval1[0], interval2[0]), max(interval1[1], interval2[1])}; + } +}; + + +void printIntervals(const vector>& vec){ + for(const vector& interval: vec) + cout << interval[0] << " " << interval[1] << endl; + cout << endl; +} + +int main() { + + vector> vec1 = {{1, 3}, {2, 6}, {8, 10}, {15, 18}}; + printIntervals(Solution().merge(vec1)); + // [1,6] [8,10] [15,18] + + // --- + + vector> vec2 = {{1, 4}, {0, 0}}; + printIntervals(Solution().merge(vec2)); + // [0,0] [1,4] + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0057-Insert-Interval/cpp-0057/CMakeLists.txt b/0001-0500/0057-Insert-Interval/cpp-0057/CMakeLists.txt new file mode 100644 index 00000000..15527718 --- /dev/null +++ b/0001-0500/0057-Insert-Interval/cpp-0057/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_0057) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_0057 main.cpp) diff --git a/0001-0500/0057-Insert-Interval/cpp-0057/main.cpp b/0001-0500/0057-Insert-Interval/cpp-0057/main.cpp new file mode 100644 index 00000000..23304fb3 --- /dev/null +++ b/0001-0500/0057-Insert-Interval/cpp-0057/main.cpp @@ -0,0 +1,49 @@ +/// Source : https://leetcode.com/problems/insert-interval/ +/// Author : liuyubobobo +/// Time : 2023-01-15 + +#include +#include + +using namespace std; + + +/// Stack +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector> insert(vector>& intervals, vector& newInterval) { + + intervals.push_back(newInterval); + sort(intervals.begin(), intervals.end()); + + vector> res; + for(const vector& v: intervals){ + if(!res.empty() && is_intersect(res.back(), v)){ + vector x = res.back(); + res.pop_back(); + res.push_back(intersect(x, v)); + } + else res.push_back(v); + } + return res; + } + +private: + bool is_intersect(const vector& a, const vector& b){ + if(a[0] <= b[0] && b[0] <= a[1]) return true; + if(b[0] <= a[0] && a[0] <= b[1]) return true; + return false; + } + + vector intersect(const vector& a, const vector& b){ + return {min(a[0], b[0]), max(a[1], b[1])}; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0058-Length-of-Last-Word/cpp-0058/CMakeLists.txt b/0001-0500/0058-Length-of-Last-Word/cpp-0058/CMakeLists.txt new file mode 100644 index 00000000..8d6c0d17 --- /dev/null +++ b/0001-0500/0058-Length-of-Last-Word/cpp-0058/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0058) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0058 main.cpp) diff --git a/0001-0500/0058-Length-of-Last-Word/cpp-0058/main.cpp b/0001-0500/0058-Length-of-Last-Word/cpp-0058/main.cpp new file mode 100644 index 00000000..bb4ebc7f --- /dev/null +++ b/0001-0500/0058-Length-of-Last-Word/cpp-0058/main.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/length-of-last-word/ +/// Author : liuyubobobo +/// Time : 2021-09-20 + +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int lengthOfLastWord(string s) { + + int res = 0; + for(int start = next_letter(s, 0), i = start + 1; i <= s.size(); i ++){ + if(i == s.size() || s[i] == ' '){ + res = i - start; + start = next_letter(s, i); + i = start; + } + } + return res; + } + +private: + int next_letter(const string& s, int start){ + for(int i = start; i < s.size(); i ++) + if(s[i] != ' ') return i; + return INT_MAX / 2; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0059-Spiral-Matrix-II/cpp-0059/CMakeLists.txt b/0001-0500/0059-Spiral-Matrix-II/cpp-0059/CMakeLists.txt new file mode 100644 index 00000000..fffad2c4 --- /dev/null +++ b/0001-0500/0059-Spiral-Matrix-II/cpp-0059/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0059) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0059 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0059-Spiral-Matrix-II/cpp-0059/main.cpp b/0001-0500/0059-Spiral-Matrix-II/cpp-0059/main.cpp new file mode 100644 index 00000000..a8001fe7 --- /dev/null +++ b/0001-0500/0059-Spiral-Matrix-II/cpp-0059/main.cpp @@ -0,0 +1,72 @@ +/// Source : https://leetcode.com/problems/spiral-matrix-ii/description/ +/// Author : liuyubobobo +/// Time : 2018-04-24 + +#include +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n^2) +/// Space Complexity: O(1) +class Solution { + +private: + int d[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + int N; + +public: + vector> generateMatrix(int n) { + + if(n == 0) + return {}; + + N = n; + int maxnum = n * n; + + vector> res(N, vector(N, 0)); + int curx = 0, cury = 0, curd = 0, num = 1; + while(num <= maxnum){ + if(res[curx][cury] == 0){ + res[curx][cury] = num; + num ++; + } + + int nextx = curx + d[curd][0]; + int nexty = cury + d[curd][1]; + if(inArea(nextx, nexty) && res[nextx][nexty] == 0){ + curx = nextx; + cury = nexty; + } + else + curd = (curd + 1) % 4; + } + + return res; + } + +private: + bool inArea(int x, int y){ + return x >= 0 && x < N && y >= 0 && y < N; + } +}; + + +void print_matrix(const vector>& matrix){ + for(const vector& vec: matrix){ + for(int e: vec) + cout << e << " "; + cout << endl; + } +} + +int main() { + + vector> res = Solution().generateMatrix(3); + print_matrix(res); + + return 0; +} \ No newline at end of file diff --git a/0061-Rotate-List/cpp-0061/CMakeLists.txt b/0001-0500/0061-Rotate-List/cpp-0061/CMakeLists.txt similarity index 100% rename from 0061-Rotate-List/cpp-0061/CMakeLists.txt rename to 0001-0500/0061-Rotate-List/cpp-0061/CMakeLists.txt diff --git a/0061-Rotate-List/cpp-0061/main.cpp b/0001-0500/0061-Rotate-List/cpp-0061/main.cpp similarity index 100% rename from 0061-Rotate-List/cpp-0061/main.cpp rename to 0001-0500/0061-Rotate-List/cpp-0061/main.cpp diff --git a/0001-0500/0062-Unique-Paths/cpp-0062/CMakeLists.txt b/0001-0500/0062-Unique-Paths/cpp-0062/CMakeLists.txt new file mode 100644 index 00000000..836dad8d --- /dev/null +++ b/0001-0500/0062-Unique-Paths/cpp-0062/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(cpp_0062) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0062 main2.cpp) \ No newline at end of file diff --git a/0001-0500/0062-Unique-Paths/cpp-0062/main.cpp b/0001-0500/0062-Unique-Paths/cpp-0062/main.cpp new file mode 100644 index 00000000..3893eb98 --- /dev/null +++ b/0001-0500/0062-Unique-Paths/cpp-0062/main.cpp @@ -0,0 +1,38 @@ +/// Source : https://leetcode.com/problems/unique-paths/ +/// Author : liuyubobobo +/// Time : 2019-04-02 + +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(m * n) +/// Space Complexity: O(m * n) +class Solution { + +public: + int uniquePaths(int m, int n) { + + vector> dp(m, vector(n, 0)); + return dfs(m - 1, n - 1, dp); + } + +private: + int dfs(int x, int y, vector>& dp){ + + if(x == 0 || y == 0) return 1; + if(dp[x][y]) return dp[x][y]; + + int res = dfs(x - 1, y, dp) + dfs(x, y - 1, dp); + return dp[x][y] = res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0062-Unique-Paths/cpp-0062/main2.cpp b/0001-0500/0062-Unique-Paths/cpp-0062/main2.cpp new file mode 100644 index 00000000..8dae5d87 --- /dev/null +++ b/0001-0500/0062-Unique-Paths/cpp-0062/main2.cpp @@ -0,0 +1,30 @@ +/// Source : https://leetcode.com/problems/unique-paths/ +/// Author : liuyubobobo +/// Time : 2019-04-02 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(m * n) +/// Space Complexity: O(m * n) +class Solution { +public: + int uniquePaths(int m, int n) { + + vector> dp(m, vector(n, 1)); + for(int i = 1; i < m; i ++) + for(int j = 1; j < n; j ++) + dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; + return dp[m - 1][n - 1]; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0063-Unique-Paths-II/cpp-0063/CMakeLists.txt b/0001-0500/0063-Unique-Paths-II/cpp-0063/CMakeLists.txt new file mode 100644 index 00000000..d87d1750 --- /dev/null +++ b/0001-0500/0063-Unique-Paths-II/cpp-0063/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0063) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0063 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0063-Unique-Paths-II/cpp-0063/main.cpp b/0001-0500/0063-Unique-Paths-II/cpp-0063/main.cpp new file mode 100644 index 00000000..622c1718 --- /dev/null +++ b/0001-0500/0063-Unique-Paths-II/cpp-0063/main.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/unique-paths-ii/ +/// Author : liuyubobobo +/// Time : 2018-10-25 +/// Updated: 2019-09-24 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(m*n) +/// Space Complexity: O(m*n) +class Solution { +public: + int uniquePathsWithObstacles(vector>& obstacleGrid) { + + int m = obstacleGrid.size(); + if(!m) return 0; + + int n = obstacleGrid[0].size(); + if(!n || obstacleGrid[0][0]) + return 0; + + vector> dp(m, vector(n, 1ll)); + dp[0][0] = 1; + for(int j = 1; j < n; j ++) + if(obstacleGrid[0][j]) + dp[0][j] = 0; + else + dp[0][j] = dp[0][j - 1]; + + for(int i = 1; i < m; i ++) + if(obstacleGrid[i][0]) + dp[i][0] = 0; + else + dp[i][0] = dp[i - 1][0]; + + for(int i = 1; i < m; i ++) + for(int j = 1; j < n; j ++) + if(obstacleGrid[i][j]) + dp[i][j] = 0; + else + dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; + return dp[m - 1][n - 1]; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0064-Minimum-Path-Sum/cpp-0064/CMakeLists.txt b/0001-0500/0064-Minimum-Path-Sum/cpp-0064/CMakeLists.txt similarity index 100% rename from 0064-Minimum-Path-Sum/cpp-0064/CMakeLists.txt rename to 0001-0500/0064-Minimum-Path-Sum/cpp-0064/CMakeLists.txt diff --git a/0064-Minimum-Path-Sum/cpp-0064/main.cpp b/0001-0500/0064-Minimum-Path-Sum/cpp-0064/main.cpp similarity index 100% rename from 0064-Minimum-Path-Sum/cpp-0064/main.cpp rename to 0001-0500/0064-Minimum-Path-Sum/cpp-0064/main.cpp diff --git a/0001-0500/0064-Minimum-Path-Sum/cpp-0064/main2.cpp b/0001-0500/0064-Minimum-Path-Sum/cpp-0064/main2.cpp new file mode 100644 index 00000000..208910c8 --- /dev/null +++ b/0001-0500/0064-Minimum-Path-Sum/cpp-0064/main2.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/minimum-path-sum/description/ +/// Author : liuyubobobo +/// Time : 2017-11-21 + +#include +#include +#include + +using namespace std; + +/// Dynamic Programming +/// with O(n) space, actually 2*n space +/// +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { +public: + int minPathSum(vector>& grid) { + + int n = grid.size(); + assert(n > 0); + + int m = grid[0].size(); + assert(m > 0); + + vector> res(2, vector(m, 0)); + res[0][0] = grid[0][0]; + + for(int j = 1 ; j < m ; j ++) + res[0][j] = grid[0][j] + res[0][j-1]; + + for(int i = 1 ; i < n ; i ++){ + res[i%2][0] = grid[i][0] + res[(i-1)%2][0]; + for(int j = 1 ; j < m ; j ++) + res[i%2][j] = grid[i][j] + min(res[(i-1)%2][j], res[i%2][j-1]); + } + + return res[(n-1)%2][m-1]; + } +}; + +int main() { + + vector> grid = {{1, 3, 1}, + {1, 5, 1}, + {4, 2, 1}}; + cout << Solution().minPathSum(grid) << endl; + + return 0; +} \ No newline at end of file diff --git a/0064-Minimum-Path-Sum/cpp-0064/main3.cpp b/0001-0500/0064-Minimum-Path-Sum/cpp-0064/main3.cpp similarity index 100% rename from 0064-Minimum-Path-Sum/cpp-0064/main3.cpp rename to 0001-0500/0064-Minimum-Path-Sum/cpp-0064/main3.cpp diff --git a/0064-Minimum-Path-Sum/cpp-0064/main4.cpp b/0001-0500/0064-Minimum-Path-Sum/cpp-0064/main4.cpp similarity index 100% rename from 0064-Minimum-Path-Sum/cpp-0064/main4.cpp rename to 0001-0500/0064-Minimum-Path-Sum/cpp-0064/main4.cpp diff --git a/0001-0500/0064-Minimum-Path-Sum/py-0064/Solution1.py b/0001-0500/0064-Minimum-Path-Sum/py-0064/Solution1.py new file mode 100644 index 00000000..e7c59126 --- /dev/null +++ b/0001-0500/0064-Minimum-Path-Sum/py-0064/Solution1.py @@ -0,0 +1,37 @@ +# Source : https://leetcode.com/problems/minimum-path-sum/ +# Author : penpenps +# Time : 2019-07-10 + +from typing import List + +# Straght-forward dp solution, dp[i][j] means the min distance from position [0][0] to [i][j] +# Time Complexity: O(n*m) +# Space Complexity: O(n*m) + +class Solution: + def minPathSum(self, grid: List[List[int]]) -> int: + if not grid or not grid[0]: + return 0 + n = len(grid) + m = len(grid[0]) + dp = [[0]*m for _ in range(n)] + dp[0][0] = grid[0][0] + for i in range(1, m): + dp[0][i] = dp[0][i-1] + grid[0][i] + for j in range(1, n): + dp[j][0] = dp[j-1][0] + grid[j][0] + + for i in range(1, n): + for j in range(1, m): + dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + grid[i][j] + + return dp[n-1][m-1] + +if __name__ == '__main__': + solution = Solution() + grid = [ + [1,3,1], + [1,5,1], + [4,2,1] + ] + print(solution.minPathSum(grid)) \ No newline at end of file diff --git a/0001-0500/0064-Minimum-Path-Sum/py-0064/Solution2.py b/0001-0500/0064-Minimum-Path-Sum/py-0064/Solution2.py new file mode 100644 index 00000000..3093aa49 --- /dev/null +++ b/0001-0500/0064-Minimum-Path-Sum/py-0064/Solution2.py @@ -0,0 +1,35 @@ +# Source : https://leetcode.com/problems/minimum-path-sum/ +# Author : penpenps +# Time : 2019-07-10 + +from typing import List + +# Use two m-length list to keep last iteration and current iteration result +# Time Complexity: O(n*m) +# Space Complexity: O(2*n) +class Solution: + def minPathSum(self, grid: List[List[int]]) -> int: + if not grid or not grid[0]: + return 0 + n = len(grid) + m = len(grid[0]) + dp = [[0]*m for _ in range(2)] + dp[0][0] = grid[0][0] + for i in range(1, m): + dp[0][i] = dp[0][i-1] + grid[0][i] + + for i in range(1, n): + dp[i%2][0] = dp[(i-1)%2][0] + grid[i][0] + for j in range(1, m): + dp[i%2][j] = min(dp[(i-1)%2][j], dp[i%2][j-1]) + grid[i][j] + + return dp[(n-1)%2][m-1] + +if __name__ == '__main__': + solution = Solution() + grid = [ + [1,3,1], + [1,5,1], + [4,2,1] + ] + print(solution.minPathSum(grid)) \ No newline at end of file diff --git a/0001-0500/0064-Minimum-Path-Sum/py-0064/Solution3.py b/0001-0500/0064-Minimum-Path-Sum/py-0064/Solution3.py new file mode 100644 index 00000000..5122494c --- /dev/null +++ b/0001-0500/0064-Minimum-Path-Sum/py-0064/Solution3.py @@ -0,0 +1,35 @@ +# Source : https://leetcode.com/problems/minimum-path-sum/ +# Author : penpenps +# Time : 2019-07-10 + +from typing import List + +# Use single list to keep accumulate dp result +# Time Complexity: O(n*m) +# Space Complexity: O(n) +class Solution: + def minPathSum(self, grid: List[List[int]]) -> int: + if not grid or not grid[0]: + return 0 + n = len(grid) + m = len(grid[0]) + dp = [0]*m + dp[0] = grid[0][0] + for i in range(1, m): + dp[i] = dp[i-1] + grid[0][i] + + for i in range(1, n): + dp[0] += grid[i][0] + for j in range(1, m): + dp[j] = min(dp[j-1], dp[j]) + grid[i][j] + + return dp[m-1] + +if __name__ == '__main__': + solution = Solution() + grid = [ + [1,3,1], + [1,5,1], + [4,2,1] + ] + print(solution.minPathSum(grid)) \ No newline at end of file diff --git a/0001-0500/0064-Minimum-Path-Sum/py-0064/Solution4.py b/0001-0500/0064-Minimum-Path-Sum/py-0064/Solution4.py new file mode 100644 index 00000000..c5aebe5f --- /dev/null +++ b/0001-0500/0064-Minimum-Path-Sum/py-0064/Solution4.py @@ -0,0 +1,33 @@ +# Source : https://leetcode.com/problems/minimum-path-sum/ +# Author : penpenps +# Time : 2019-07-10 + +from typing import List + +# Update min distance in-place +# Time Complexity: O(n*m) +# Space Complexity: O(1) +class Solution: + def minPathSum(self, grid: List[List[int]]) -> int: + if not grid or not grid[0]: + return 0 + n = len(grid) + m = len(grid[0]) + for i in range(1, m): + grid[0][i] += grid[0][i-1] + + for i in range(1, n): + grid[i][0] += grid[i-1][0] + for j in range(1, m): + grid[i][j] = min(grid[i][j-1], grid[i-1][j]) + grid[i][j] + + return grid[n-1][m-1] + +if __name__ == '__main__': + solution = Solution() + grid = [ + [1,3,1], + [1,5,1], + [4,2,1] + ] + print(solution.minPathSum(grid)) \ No newline at end of file diff --git a/0001-0500/0065-Valid-Number/cpp-0065/CMakeLists.txt b/0001-0500/0065-Valid-Number/cpp-0065/CMakeLists.txt new file mode 100644 index 00000000..48ae5767 --- /dev/null +++ b/0001-0500/0065-Valid-Number/cpp-0065/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_0065) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0065 main.cpp) \ No newline at end of file diff --git a/0001-0500/0065-Valid-Number/cpp-0065/main.cpp b/0001-0500/0065-Valid-Number/cpp-0065/main.cpp new file mode 100644 index 00000000..c2285a9f --- /dev/null +++ b/0001-0500/0065-Valid-Number/cpp-0065/main.cpp @@ -0,0 +1,86 @@ +/// Source : https://leetcode.com/problems/valid-number/ +/// Author : liuyubobobo +/// Time : 2021-05-15 + +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + bool isNumber(string s) { + + if(s.size() == 0) return false; + + if(isInteger(s)) + return true; + return isEDecimal(s); + } + +private: + bool isEDecimal(const string& s){ + + int epos = s.find('e'); + if(epos == string::npos) epos = s.find('E'); + if(epos != string::npos){ + string a = s.substr(0, epos), b = s.substr(epos + 1); + return isDecimal(a) && isInteger(b); + } + return isDecimal(s); + } + + bool isDecimal(const string& s){ + + if(s.size() == 0) return false; + + if(s[0] == '+' || s[0] == '-') + return isNonSignedDecimal(s.substr(1)); + return isNonSignedDecimal(s); + } + + bool isNonSignedDecimal(const string& s){ + + int dotpos = s.find('.'); + if(dotpos == string::npos) return isInteger(s); + + string a = s.substr(0, dotpos), b = s.substr(dotpos + 1); + if(a.size() == 0) return isNonSignedInteger(b); + else if(b.size() == 0) return isInteger(a); + return isInteger(a) && isNonSignedInteger(b); + } + + bool isInteger(const string& s){ + + if(s.size() == 0) return false; + if(s[0] == '+' || s[0] == '-') + return isNonSignedInteger(s.substr(1)); + return isNonSignedInteger(s); + } + + bool isNonSignedInteger(const string& s){ + + if(s.size() == 0) return false; + for(char c: s) + if(!isdigit(c)) return false; + return true; + } +}; + + +int main() { + + cout << Solution().isNumber(".1") << endl; + // 1 + + cout << Solution().isNumber("005047e+6") << endl; + // 1 + + cout << Solution().isNumber(".-4") << endl; + // 0 + + return 0; +} diff --git a/0001-0500/0066-Plus-One/cpp-0066/CMakeLists.txt b/0001-0500/0066-Plus-One/cpp-0066/CMakeLists.txt new file mode 100644 index 00000000..bf776bcf --- /dev/null +++ b/0001-0500/0066-Plus-One/cpp-0066/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0066) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0066 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0066-Plus-One/cpp-0066/main.cpp b/0001-0500/0066-Plus-One/cpp-0066/main.cpp new file mode 100644 index 00000000..e281345e --- /dev/null +++ b/0001-0500/0066-Plus-One/cpp-0066/main.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/plus-one/description/ +/// Author : liuyubobobo +/// Time : 2018-06-03 + +#include +#include + +using namespace std; + +/// Ad Hoc +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + vector plusOne(vector& digits) { + + digits[digits.size() - 1] ++; + for(int i = digits.size() - 1 ; i >= 1 ; i --) + if(digits[i] == 10){ + digits[i] = 0; + digits[i - 1] ++; + } + + if(digits[0] == 10){ + digits[0] = 0; + digits.insert(digits.begin(), 1); + } + + return digits; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0067-Add-Binary/cpp-0067/CMakeLists.txt b/0001-0500/0067-Add-Binary/cpp-0067/CMakeLists.txt new file mode 100644 index 00000000..b6bb77d2 --- /dev/null +++ b/0001-0500/0067-Add-Binary/cpp-0067/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0067) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0067 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0067-Add-Binary/cpp-0067/main.cpp b/0001-0500/0067-Add-Binary/cpp-0067/main.cpp new file mode 100644 index 00000000..877543d7 --- /dev/null +++ b/0001-0500/0067-Add-Binary/cpp-0067/main.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/add-binary/description/ +/// Author : liuyubobobo +/// Time : 2018-06-03 + +#include + +using namespace std; + +/// Simulation +/// Time Complexity: O(max(len(a), len(b))) +/// Space Complexity: O(1) +class Solution { +public: + string addBinary(string a, string b) { + + string res = a.size() > b.size() ? a : b; + string adder = a.size() > b.size() ? b : a; + + int index = res.size() - 1; + for(int i = adder.size() - 1 ; i >= 0 ; i --){ + res[index] += adder[i] - '0'; + index --; + } + + for(int i = res.size() - 1 ; i > 0 ; i --) + if(res[i] > '1'){ + res[i - 1] += 1; + res[i] = '0' + (res[i] - '0') % 2; + } + + if(res[0] > '1'){ + res[0] = '0' + (res[0] - '0') % 2; + res = '1' + res; + } + return res; + } +}; + + +int main() { + + cout << Solution().addBinary("11", "1") << endl; + cout << Solution().addBinary("1010", "1011") << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0068-Text-Justification/cpp-0068/CMakeLists.txt b/0001-0500/0068-Text-Justification/cpp-0068/CMakeLists.txt new file mode 100644 index 00000000..1d513984 --- /dev/null +++ b/0001-0500/0068-Text-Justification/cpp-0068/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0068) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0068 main.cpp) diff --git a/0001-0500/0068-Text-Justification/cpp-0068/main.cpp b/0001-0500/0068-Text-Justification/cpp-0068/main.cpp new file mode 100644 index 00000000..ee61ff5e --- /dev/null +++ b/0001-0500/0068-Text-Justification/cpp-0068/main.cpp @@ -0,0 +1,69 @@ +/// Source : https://leetcode.com/problems/text-justification/ +/// Author : liuyubobobo +/// Time : 2021-09-08 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector fullJustify(vector& words, int maxWidth) { + + vector res; + int index = 0; + while(index < words.size()){ + + vector linev = {words[index ++]}; + int cur = linev[0].size(); + while(index < words.size() && cur + 1 + words[index].size() <= maxWidth){ + linev.push_back(words[index]), + cur += (1 + words[index].size()), + index ++; + } + + string line = ""; + if(index < words.size()){ + int left = maxWidth - cur, space = linev.size() - 1; + + line = linev[0]; + for(int i = 1; i < linev.size(); i ++) + line += string(1 + left / space + (i- 1 < left % space), ' '), + line += linev[i]; + + line += string(maxWidth - line.size(), ' '); + } + else{ + line = linev[0]; + for(int i = 1; i < linev.size(); i ++) + line += " " + linev[i]; + line += string(maxWidth - line.size(), ' '); + } + + res.push_back(line); + } + return res; + } +}; + + +void print_text(const vector& text){ + for(const string& line: text) + cout << line << endl; +} + +int main() { + + vector words1 = {"This", "is", "an", "example", "of", "text", "justification."}; + print_text(Solution().fullJustify(words1, 16)); + + vector words2 = {"What","must","be","acknowledgment","shall","be"}; + print_text(Solution().fullJustify(words2, 16)); + + return 0; +} diff --git a/0001-0500/0069-Sqrt-x/cpp-0069/CMakeLists.txt b/0001-0500/0069-Sqrt-x/cpp-0069/CMakeLists.txt new file mode 100644 index 00000000..ea176d8e --- /dev/null +++ b/0001-0500/0069-Sqrt-x/cpp-0069/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0069) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main3.cpp) +add_executable(cpp_0069 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0069-Sqrt-x/cpp-0069/main.cpp b/0001-0500/0069-Sqrt-x/cpp-0069/main.cpp new file mode 100644 index 00000000..da817d18 --- /dev/null +++ b/0001-0500/0069-Sqrt-x/cpp-0069/main.cpp @@ -0,0 +1,36 @@ +/// Source : https://leetcode.com/problems/sqrtx/description/ +/// Author : liuyubobobo +/// Time : 2018-06-18 + +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(log(MAX_INT)) +/// Space Complexity: O(1) +class Solution { +public: + int mySqrt(int x) { + + int l = 0, r = x; + while(l < r){ + long long mid = l + ((long long)r - l + 1) / 2; + if(mid * mid <= (long long)x) + l = mid; + else + r = mid - 1; + } + return l; + } +}; + + +int main() { + + cout << Solution().mySqrt(4) << endl; + cout << Solution().mySqrt(8) << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0069-Sqrt-x/cpp-0069/main2.cpp b/0001-0500/0069-Sqrt-x/cpp-0069/main2.cpp new file mode 100644 index 00000000..c575d1a7 --- /dev/null +++ b/0001-0500/0069-Sqrt-x/cpp-0069/main2.cpp @@ -0,0 +1,42 @@ +/// Source : https://leetcode.com/problems/sqrtx/description/ +/// Author : liuyubobobo +/// Time : 2019-04-03 + +#include + +using namespace std; + + +/// Binary Search +/// Using double first +/// +/// Time Complexity: O(log(MAX_INT) * precision) +/// Space Complexity: O(1) +class Solution { + +private: + double e = 1e-6; + +public: + int mySqrt(int x) { + + double l = 0.0, r = INT_MAX; + while(r - l >= e){ + double mid = (l + r) / 2; + if(mid * mid <= x) + l = mid; + else + r = mid; + } + return (int)r; + } +}; + + +int main() { + + cout << Solution().mySqrt(4) << endl; + cout << Solution().mySqrt(8) << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0069-Sqrt-x/cpp-0069/main3.cpp b/0001-0500/0069-Sqrt-x/cpp-0069/main3.cpp new file mode 100644 index 00000000..0f341e12 --- /dev/null +++ b/0001-0500/0069-Sqrt-x/cpp-0069/main3.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/sqrtx/description/ +/// Author : liuyubobobo +/// Time : 2022-03-16 + +#include + +using namespace std; + + +/// Taylor Series Expansion +/// Time Complexity: iterative count +/// Space Complexity: O(1) +class Solution { + +private: + double e = 1e-5; + +public: + int mySqrt(int x) { + + if(!x) return x; + + double a = x / 2.0; + while(true){ + double next_a = a - (a * a - (double)x) / (2.0 * a); + if(abs(next_a - a) < e) break; + a = next_a; + } + return (int)a; + } +}; + + +int main() { + + cout << Solution().mySqrt(4) << endl; + cout << Solution().mySqrt(8) << endl; + + return 0; +} \ No newline at end of file diff --git a/0070-Climbing-Stairs/cpp-0070/CMakeLists.txt b/0001-0500/0070-Climbing-Stairs/cpp-0070/CMakeLists.txt similarity index 100% rename from 0070-Climbing-Stairs/cpp-0070/CMakeLists.txt rename to 0001-0500/0070-Climbing-Stairs/cpp-0070/CMakeLists.txt diff --git a/0070-Climbing-Stairs/cpp-0070/main.cpp b/0001-0500/0070-Climbing-Stairs/cpp-0070/main.cpp similarity index 100% rename from 0070-Climbing-Stairs/cpp-0070/main.cpp rename to 0001-0500/0070-Climbing-Stairs/cpp-0070/main.cpp diff --git a/0070-Climbing-Stairs/cpp-0070/main2.cpp b/0001-0500/0070-Climbing-Stairs/cpp-0070/main2.cpp similarity index 100% rename from 0070-Climbing-Stairs/cpp-0070/main2.cpp rename to 0001-0500/0070-Climbing-Stairs/cpp-0070/main2.cpp diff --git a/0070-Climbing-Stairs/cpp-0070/main3.cpp b/0001-0500/0070-Climbing-Stairs/cpp-0070/main3.cpp similarity index 100% rename from 0070-Climbing-Stairs/cpp-0070/main3.cpp rename to 0001-0500/0070-Climbing-Stairs/cpp-0070/main3.cpp diff --git a/0070-Climbing-Stairs/cpp-0070/main4.cpp b/0001-0500/0070-Climbing-Stairs/cpp-0070/main4.cpp similarity index 100% rename from 0070-Climbing-Stairs/cpp-0070/main4.cpp rename to 0001-0500/0070-Climbing-Stairs/cpp-0070/main4.cpp diff --git a/0070-Climbing-Stairs/cpp-0070/main5.cpp b/0001-0500/0070-Climbing-Stairs/cpp-0070/main5.cpp similarity index 100% rename from 0070-Climbing-Stairs/cpp-0070/main5.cpp rename to 0001-0500/0070-Climbing-Stairs/cpp-0070/main5.cpp diff --git a/0070-Climbing-Stairs/java-0070/src/Solution1.java b/0001-0500/0070-Climbing-Stairs/java-0070/src/Solution1.java similarity index 100% rename from 0070-Climbing-Stairs/java-0070/src/Solution1.java rename to 0001-0500/0070-Climbing-Stairs/java-0070/src/Solution1.java diff --git a/0070-Climbing-Stairs/java-0070/src/Solution2.java b/0001-0500/0070-Climbing-Stairs/java-0070/src/Solution2.java similarity index 100% rename from 0070-Climbing-Stairs/java-0070/src/Solution2.java rename to 0001-0500/0070-Climbing-Stairs/java-0070/src/Solution2.java diff --git a/0070-Climbing-Stairs/java-0070/src/Solution3.java b/0001-0500/0070-Climbing-Stairs/java-0070/src/Solution3.java similarity index 100% rename from 0070-Climbing-Stairs/java-0070/src/Solution3.java rename to 0001-0500/0070-Climbing-Stairs/java-0070/src/Solution3.java diff --git a/0070-Climbing-Stairs/java-0070/src/Solution4.java b/0001-0500/0070-Climbing-Stairs/java-0070/src/Solution4.java similarity index 100% rename from 0070-Climbing-Stairs/java-0070/src/Solution4.java rename to 0001-0500/0070-Climbing-Stairs/java-0070/src/Solution4.java diff --git a/0070-Climbing-Stairs/java-0070/src/Solution5.java b/0001-0500/0070-Climbing-Stairs/java-0070/src/Solution5.java similarity index 100% rename from 0070-Climbing-Stairs/java-0070/src/Solution5.java rename to 0001-0500/0070-Climbing-Stairs/java-0070/src/Solution5.java diff --git a/0001-0500/0071-Simplify-Path/cpp-0071/CMakeLists.txt b/0001-0500/0071-Simplify-Path/cpp-0071/CMakeLists.txt new file mode 100644 index 00000000..cad32029 --- /dev/null +++ b/0001-0500/0071-Simplify-Path/cpp-0071/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(cpp_0071) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0071 main.cpp) \ No newline at end of file diff --git a/0001-0500/0071-Simplify-Path/cpp-0071/main.cpp b/0001-0500/0071-Simplify-Path/cpp-0071/main.cpp new file mode 100644 index 00000000..74aca728 --- /dev/null +++ b/0001-0500/0071-Simplify-Path/cpp-0071/main.cpp @@ -0,0 +1,42 @@ +/// Source : https://leetcode.com/problems/simplify-path/ +/// Author : liuyubobobo +/// Time : 2019-02-10 + +#include +#include + +using namespace std; + + +/// Using Stack +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + string simplifyPath(string path) { + + vector stack; + for(int start = 1, i = 1; i <= path.size(); i ++) + if(i == path.size() || path[i] == '/'){ + string f = path.substr(start, i - start); + if(f.size()){ + if(f == ".."){ + if(stack.size()) stack.pop_back(); + } + else if(f != ".") stack.push_back(f); + } + start = i + 1; + } + + string res = ""; + for(string e: stack) + res += "/" + e; + return res == "" ? "/" : res; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0072-Edit-Distance/cpp-0072/CMakeLists.txt b/0001-0500/0072-Edit-Distance/cpp-0072/CMakeLists.txt new file mode 100644 index 00000000..4d1917e7 --- /dev/null +++ b/0001-0500/0072-Edit-Distance/cpp-0072/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.12) +project(cpp_0072) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(cpp_0072 main2.cpp) \ No newline at end of file diff --git a/0001-0500/0072-Edit-Distance/cpp-0072/main.cpp b/0001-0500/0072-Edit-Distance/cpp-0072/main.cpp new file mode 100644 index 00000000..418eb524 --- /dev/null +++ b/0001-0500/0072-Edit-Distance/cpp-0072/main.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/edit-distance/ +/// Author : liuyubobobo +/// Time : 2018-11-23 + +#include +#include +#include + +using namespace std; + + +/// Memory Serach +/// Time Complexity: O(len(word1) * len(word2)) +/// Space Complexity: O(len(word1) * len(word2)) +class Solution { + +private: + map, int> dp; + +public: + int minDistance(string word1, string word2) { + return dfs(word1, word2, 0, 0); + } + +private: + int dfs(const string& word1, const string& word2, int index1, int index2){ + + if(index1 == word1.size()) + return word2.size() - index2; + + if(index2 == word2.size()) + return word1.size() - index1; + + pair hash = make_pair(index1, index2); + if(dp.count(hash)) + return dp[hash]; + + int res = INT_MAX; + if(word1[index1] == word2[index2]) + res = min(res, dfs(word1, word2, index1 + 1, index2 + 1)); + + res = min(res, 1 + dfs(word1, word2, index1, index2 + 1)); + res = min(res, 1 + dfs(word1, word2, index1 + 1, index2)); + res = min(res, 1 + dfs(word1, word2, index1 + 1, index2 + 1)); + return dp[hash] = res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0072-Edit-Distance/cpp-0072/main2.cpp b/0001-0500/0072-Edit-Distance/cpp-0072/main2.cpp new file mode 100644 index 00000000..77ce3851 --- /dev/null +++ b/0001-0500/0072-Edit-Distance/cpp-0072/main2.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/edit-distance/ +/// Author : liuyubobobo +/// Time : 2018-11-23 + +#include +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(len(word1) * len(word2)) +/// Space Complexity: O(len(word1) * len(word2)) +class Solution { + +public: + int minDistance(string word1, string word2) { + + int m = word1.size(), n = word2.size(); + vector> dp(m + 1, vector(n + 1, INT_MAX)); + + for(int i = 0; i <= m; i ++) + dp[i][0] = i; + for(int j = 0; j <= n; j ++) + dp[0][j] = j; + + // get dp[i][j], check word[i - 1], word[j - 1] + for(int i = 1; i <= m; i ++) + for(int j = 1; j <= n; j ++){ + if(word1[i - 1] == word2[j - 1]) + dp[i][j] = dp[i - 1][j - 1]; + dp[i][j] = min(dp[i][j], 1 + dp[i - 1][j - 1]); + dp[i][j] = min(dp[i][j], 1 + dp[i - 1][j]); + dp[i][j] = min(dp[i][j], 1 + dp[i][j - 1]); + } + + return dp[m][n]; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0073-Set-Matrix-Zeroes/cpp-0073/CMakeLists.txt b/0001-0500/0073-Set-Matrix-Zeroes/cpp-0073/CMakeLists.txt new file mode 100644 index 00000000..c942613d --- /dev/null +++ b/0001-0500/0073-Set-Matrix-Zeroes/cpp-0073/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0073) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main4.cpp) +add_executable(cpp_0073 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0073-Set-Matrix-Zeroes/cpp-0073/main.cpp b/0001-0500/0073-Set-Matrix-Zeroes/cpp-0073/main.cpp new file mode 100644 index 00000000..1f44d97d --- /dev/null +++ b/0001-0500/0073-Set-Matrix-Zeroes/cpp-0073/main.cpp @@ -0,0 +1,45 @@ +/// Source : https://leetcode.com/problems/set-matrix-zeroes/description/ +/// Author : liuyubobobo +/// Time : 2018-10-05 + +#include +#include + +using namespace std; + + +/// Using another matrix to record zero place +/// Time Complexity: O(m * n * (m + n)) +/// Space Complexity: O(m * n) +class Solution { +public: + void setZeroes(vector>& matrix) { + + int m = matrix.size(); + if(!m) return; + + int n = matrix[0].size(); + if(!n) return; + + vector> isZero(m, vector(n, false)); + for(int i = 0; i < m; i ++) + for(int j = 0; j < n; j ++) + if(!matrix[i][j]){ + for(int k = 0; k < n; k ++) + isZero[i][k] = true; + for(int k = 0; k < m; k ++) + isZero[k][j] = true; + } + + for(int i = 0; i < m; i ++) + for(int j = 0; j < n; j ++) + if(isZero[i][j]) + matrix[i][j] = 0; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0073-Set-Matrix-Zeroes/cpp-0073/main2.cpp b/0001-0500/0073-Set-Matrix-Zeroes/cpp-0073/main2.cpp new file mode 100644 index 00000000..1ca5fa18 --- /dev/null +++ b/0001-0500/0073-Set-Matrix-Zeroes/cpp-0073/main2.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/set-matrix-zeroes/description/ +/// Author : liuyubobobo +/// Time : 2018-10-05 + +#include +#include + +using namespace std; + + +/// Only record the zero row index and col index +/// Time Complexity: O(m * n) +/// Space Complexity: O(m + n) +class Solution { +public: + void setZeroes(vector>& matrix) { + + int m = matrix.size(); + if(!m) return; + + int n = matrix[0].size(); + if(!n) return; + + vector zeroRows, zeroCols; + for(int i = 0; i < m; i ++) + for(int j = 0; j < n; j ++) + if(!matrix[i][j]){ + zeroRows.push_back(i); + zeroCols.push_back(j); + } + + for(int r: zeroRows) + for(int j = 0; j < n; j ++) + matrix[r][j] = 0; + + for(int c: zeroCols) + for(int i = 0; i < m; i ++) + matrix[i][c] = 0; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0073-Set-Matrix-Zeroes/cpp-0073/main3.cpp b/0001-0500/0073-Set-Matrix-Zeroes/cpp-0073/main3.cpp new file mode 100644 index 00000000..0f3edc3f --- /dev/null +++ b/0001-0500/0073-Set-Matrix-Zeroes/cpp-0073/main3.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/set-matrix-zeroes/description/ +/// Author : liuyubobobo +/// Time : 2018-10-05 + +#include +#include + +using namespace std; + + +/// Using an sentinel value to mark zero in place +/// Attention: this method is actually wrong since we can not guarantee that +/// the sentinel value can not occur in the matrix +/// +/// Time Complexity: O(m * n * (m + n)) +/// Space Complexity: O(1) +class Solution { +public: + void setZeroes(vector>& matrix) { + + int m = matrix.size(); + if(!m) return; + + int n = matrix[0].size(); + if(!n) return; + + int sentinel = 2e9; + for(int i = 0; i < m; i ++) + for(int j = 0; j < n; j ++) + if(matrix[i][j] == 0){ + for(int k = 0; k < n; k ++) + if(matrix[i][k] != 0) + matrix[i][k] = sentinel; + for(int k = 0; k < m; k ++) + if(matrix[k][j] != 0) + matrix[k][j] = sentinel; + } + + for(int i = 0; i < m; i ++) + for(int j = 0; j < n; j ++) + if(matrix[i][j] == sentinel) + matrix[i][j] = 0; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0073-Set-Matrix-Zeroes/cpp-0073/main4.cpp b/0001-0500/0073-Set-Matrix-Zeroes/cpp-0073/main4.cpp new file mode 100644 index 00000000..5e062b33 --- /dev/null +++ b/0001-0500/0073-Set-Matrix-Zeroes/cpp-0073/main4.cpp @@ -0,0 +1,81 @@ +/// Source : https://leetcode.com/problems/set-matrix-zeroes/description/ +/// Author : liuyubobobo +/// Time : 2018-10-05 + +#include +#include + +using namespace std; + + +/// Make a marker in the first element of every row and column +/// Time Complexity: O(m * n) +/// Space Complexity: O(1) +class Solution { +public: + void setZeroes(vector>& matrix) { + + int m = matrix.size(); + if(!m) return; + + int n = matrix[0].size(); + if(!n) return; + + bool zeroIndexColZero = false; + for(int i = 0; i < m; i ++) + for(int j = 0; j < n; j ++) + if(!matrix[i][j]){ + matrix[i][0] = 0; + if(j == 0) + zeroIndexColZero = true; + else + matrix[0][j] = 0; + } + + for(int i = 1; i < m; i ++) + if(!matrix[i][0]) + for(int j = 0; j < n; j ++) + matrix[i][j] = 0; + + for(int j = 1; j < n; j ++) + if(!matrix[0][j]) + for(int i = 0; i < m; i ++) + matrix[i][j] = 0; + + if(!matrix[0][0]) + for(int j = 0; j < n; j ++) + matrix[0][j] = 0; + + if(zeroIndexColZero) + for(int i = 0; i < m; i ++) + matrix[i][0] = 0; + } +}; + + +void print_matrix(const vector>& matrix){ + + for(const vector& row: matrix){ + for(int e: row) + cout << e << " "; + cout << endl; + } + cout << endl; +} + +int main() { + + vector> matrix1 = { + {1,1,1},{1,0,1},{1,1,1} + }; + Solution().setZeroes(matrix1); + print_matrix(matrix1); + + vector> matrix2 = { + {0,1,2,0},{3,4,5,2},{1,3,1,5} + }; + Solution().setZeroes(matrix2); + print_matrix(matrix2); + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0074-Search-a-2D-Matrix/cpp-0074/CMakeLists.txt b/0001-0500/0074-Search-a-2D-Matrix/cpp-0074/CMakeLists.txt new file mode 100644 index 00000000..320d7386 --- /dev/null +++ b/0001-0500/0074-Search-a-2D-Matrix/cpp-0074/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(cpp_0074) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0074 main2.cpp) \ No newline at end of file diff --git a/0001-0500/0074-Search-a-2D-Matrix/cpp-0074/main.cpp b/0001-0500/0074-Search-a-2D-Matrix/cpp-0074/main.cpp new file mode 100644 index 00000000..e54aa021 --- /dev/null +++ b/0001-0500/0074-Search-a-2D-Matrix/cpp-0074/main.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/search-a-2d-matrix/ +/// Author : liuyubobobo +/// Time : 2019-05-02 + +#include +#include +#include + +using namespace std; + + +/// Two steps Binary Search +/// Time Complexity: O(logn + logm) +/// Space Complexity: O(m) +class Solution { +public: + bool searchMatrix(vector>& matrix, int target) { + + if(!matrix.size() || !matrix[0].size()) return false; + if(target < matrix[0][0]) return false; + + vector row; + for(int i = 0; i < matrix.size(); i ++) + row.push_back(matrix[i][0]); + + int row_index = lower_bound(row.begin(), row.end(), target) - row.begin(); + if(row_index == matrix.size() || matrix[row_index][0] != target) + row_index --; +// cout << row_index << endl; + + vector::iterator iter = lower_bound(matrix[row_index].begin(), matrix[row_index].end(), target); + return iter != matrix[row_index].end() && *iter == target; + } +}; + + +int main() { + + vector> matrix1 = { + {1, 3, 5, 7}, + {10, 11, 16, 20}, + {23, 30, 34, 50} + }; + cout << Solution().searchMatrix(matrix1, 3) << endl; + // true + + vector> matrix2 = { + {1} + }; + cout << Solution().searchMatrix(matrix2, 2) << endl; + // false + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0074-Search-a-2D-Matrix/cpp-0074/main2.cpp b/0001-0500/0074-Search-a-2D-Matrix/cpp-0074/main2.cpp new file mode 100644 index 00000000..e8f73b2c --- /dev/null +++ b/0001-0500/0074-Search-a-2D-Matrix/cpp-0074/main2.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/search-a-2d-matrix/ +/// Author : liuyubobobo +/// Time : 2019-05-02 + +#include +#include +#include + +using namespace std; + + +/// Think the whole 2d matrix as a 1d array and Binary Search +/// +/// Time Complexity: O(log(m*n)) +/// Space Complexity: O(1) +class Solution { +public: + bool searchMatrix(vector>& matrix, int target) { + + if(!matrix.size() || !matrix[0].size()) return false; + + int m = matrix.size(), n = matrix[0].size(); + int l = 0, r = m * n - 1; + while(l <= r){ + int mid = (l + r) / 2; + int x = matrix[mid / n][mid % n]; + if(target == x) return true; + else if(target < x) r = mid - 1; + else l = mid + 1; + } + return false; + } +}; + + +int main() { + + vector> matrix1 = { + {1, 3, 5, 7}, + {10, 11, 16, 20}, + {23, 30, 34, 50} + }; + cout << Solution().searchMatrix(matrix1, 3) << endl; + // true + + vector> matrix2 = { + {1} + }; + cout << Solution().searchMatrix(matrix2, 2) << endl; + // false + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0075-Sort-Colors/cpp-0075/CMakeLists.txt b/0001-0500/0075-Sort-Colors/cpp-0075/CMakeLists.txt new file mode 100644 index 00000000..facaa011 --- /dev/null +++ b/0001-0500/0075-Sort-Colors/cpp-0075/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0075) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main3.cpp) +add_executable(cpp_0075 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0075-Sort-Colors/cpp-0075/main.cpp b/0001-0500/0075-Sort-Colors/cpp-0075/main.cpp new file mode 100644 index 00000000..6b731c72 --- /dev/null +++ b/0001-0500/0075-Sort-Colors/cpp-0075/main.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/sort-colors/description/ +/// Author : liuyubobobo +/// Time : 2017-11-13 + +#include +#include +#include + +using namespace std; + +// Counting +// Time Complexity: O(n) +// Space Complexity: O(3) +class Solution { +public: + void sortColors(vector &nums) { + + int count[3] = {0}; + for(int i = 0 ; i < nums.size() ; i ++){ + assert(nums[i] >= 0 && nums[i] <= 2); + count[nums[i]] ++; + } + + int index = 0; + for(int i = 0 ; i < count[0] ; i ++) + nums[index++] = 0; + for(int i = 0 ; i < count[1] ; i ++) + nums[index++] = 1; + for(int i = 0 ; i < count[2] ; i ++) + nums[index++] = 2; + } +}; + + +void print_arr(const vector& vec){ + for(int e: vec) + cout << e << " "; + cout << endl; +} + +int main() { + + vector vec1 = {2, 2, 2, 1, 1, 0}; + Solution().sortColors(vec1); + print_arr(vec1); + + vector vec2 = {2}; + Solution().sortColors(vec2); + print_arr(vec2); + + return 0; +} diff --git a/0001-0500/0075-Sort-Colors/cpp-0075/main2.cpp b/0001-0500/0075-Sort-Colors/cpp-0075/main2.cpp new file mode 100644 index 00000000..58c41509 --- /dev/null +++ b/0001-0500/0075-Sort-Colors/cpp-0075/main2.cpp @@ -0,0 +1,51 @@ +/// Source : https://leetcode.com/problems/sort-colors/description/ +/// Author : liuyubobobo +/// Time : 2017-11-13 + +#include +#include +#include + +using namespace std; + +// Three Way Quick Sort +// Time Complexity: O(n) +// Space Complexity: O(1) +class Solution { +public: + void sortColors(vector &nums) { + + int zero = -1; // [0...zero] == 0 + int two = nums.size(); // [two...n-1] == 2 + for(int i = 0 ; i < two ; ){ + if(nums[i] == 1) + i ++; + else if (nums[i] == 2) + swap( nums[i] , nums[--two]); + else{ // nums[i] == 0 + assert(nums[i] == 0); + swap(nums[++zero] , nums[i++]); + } + } + } +}; + + +void print_arr(const vector& vec){ + for(int e: vec) + cout << e << " "; + cout << endl; +} + +int main() { + + vector vec1 = {2, 2, 2, 1, 1, 0}; + Solution().sortColors(vec1); + print_arr(vec1); + + vector vec2 = {2}; + Solution().sortColors(vec2); + print_arr(vec2); + + return 0; +} diff --git a/0001-0500/0075-Sort-Colors/cpp-0075/main3.cpp b/0001-0500/0075-Sort-Colors/cpp-0075/main3.cpp new file mode 100644 index 00000000..bae93e7a --- /dev/null +++ b/0001-0500/0075-Sort-Colors/cpp-0075/main3.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/sort-colors/description/ +/// Author : liuyubobobo +/// Time : 2021-08-08 + +#include +#include +#include + +using namespace std; + +// Counting +// Time Complexity: O(n) +// Space Complexity: O(3) +class Solution { +public: + void sortColors(vector &nums) { + + const int MAX = 3; + vector count(MAX, 0); + for(int i = 0 ; i < nums.size() ; i ++){ + assert(nums[i] >= 0 && nums[i] <= MAX); + count[nums[i]] ++; + } + + int index = 0; + for(int i = 0 ; i < MAX ; i ++) + for(int j = 0; j < count[i]; j ++) + nums[index++] = i; + } +}; + + +void print_arr(const vector& vec){ + for(int e: vec) + cout << e << " "; + cout << endl; +} + +int main() { + + vector vec1 = {2, 2, 2, 1, 1, 0}; + Solution().sortColors(vec1); + print_arr(vec1); + + vector vec2 = {2}; + Solution().sortColors(vec2); + print_arr(vec2); + + return 0; +} diff --git a/0075-Sort-Colors/java-0075/src/Solution1.java b/0001-0500/0075-Sort-Colors/java-0075/src/Solution1.java similarity index 100% rename from 0075-Sort-Colors/java-0075/src/Solution1.java rename to 0001-0500/0075-Sort-Colors/java-0075/src/Solution1.java diff --git a/0075-Sort-Colors/java-0075/src/Solution2.java b/0001-0500/0075-Sort-Colors/java-0075/src/Solution2.java similarity index 100% rename from 0075-Sort-Colors/java-0075/src/Solution2.java rename to 0001-0500/0075-Sort-Colors/java-0075/src/Solution2.java diff --git a/0001-0500/0075-Sort-Colors/py-0075/Solution1.py b/0001-0500/0075-Sort-Colors/py-0075/Solution1.py new file mode 100644 index 00000000..345f7e86 --- /dev/null +++ b/0001-0500/0075-Sort-Colors/py-0075/Solution1.py @@ -0,0 +1,33 @@ +# Source : https://leetcode.com/problems/sort-colors/ +# Author : penpenps +# Time : 2019-05-31 + +from typing import List + +# Counting and reset nums in order +# Time Complexity: O(2*n) +# Space Complexity: O(3) + +class Solution: + def sortColors(self, nums: List[int]) -> None: + """ + Do not return anything, modify nums in-place instead. + """ + m = [0]*3 + for x in nums: + m[x] += 1 + + for i in range(len(nums)): + if i < m[0]: + nums[i] = 0 + if m[0] <= i < m[1] + m[0]: + nums[i] = 1 + if i >= m[0] + m[1]: + nums[i] = 2 + + +if __name__ == '__main__': + s = Solution() + nums = [2,0,2,1,1,0] + s.sortColors(nums) + print(nums) diff --git a/0001-0500/0075-Sort-Colors/py-0075/Solution2.py b/0001-0500/0075-Sort-Colors/py-0075/Solution2.py new file mode 100644 index 00000000..8cc2b940 --- /dev/null +++ b/0001-0500/0075-Sort-Colors/py-0075/Solution2.py @@ -0,0 +1,35 @@ +# Source : https://leetcode.com/problems/sort-colors/ +# Author : penpenps +# Time : 2019-05-31 + +from typing import List + +# Quick sort for 3 numbers +# Time Complexity: O(n) +# Space Complexity: O(3) + +class Solution: + def sortColors(self, nums: List[int]) -> None: + """ + Do not return anything, modify nums in-place instead. + """ + zero = 0 + two = len(nums) - 1 + i = 0 + while i <= two: + if nums[i] == 0: + nums[i], nums[zero] = nums[zero], nums[i] + zero += 1 + i += 1 + elif nums[i] == 2: + nums[i], nums[two] = nums[two], nums[i] + two -= 1 + else: + i += 1 + + +if __name__ == '__main__': + s = Solution() + nums = [2,0,2,1,1,0] + s.sortColors(nums) + print(nums) diff --git a/0001-0500/0075-Sort-Colors/py-0075/Solution3.py b/0001-0500/0075-Sort-Colors/py-0075/Solution3.py new file mode 100644 index 00000000..01fefdb7 --- /dev/null +++ b/0001-0500/0075-Sort-Colors/py-0075/Solution3.py @@ -0,0 +1,32 @@ +# Source : https://leetcode.com/problems/sort-colors/ +# Author : penpenps +# Time : 2019-05-31 + +from typing import List + +# use [i, j) to keep 0, [j, k) keeps 1 and [k, ] keeps 2 +# Time Complexity: O(n) +# Space Complexity: O(4) + +class Solution: + def sortColors(self, nums: List[int]) -> None: + """ + Do not return anything, modify nums in-place instead. + """ + i, j, k = 0, 0, 0 + for k in range(len(nums)): + v = nums[k] + nums[k] = 2 + if v < 2: + nums[j] = 1 + j += 1 + if v < 1: + nums[i] = 0 + i += 1 + + +if __name__ == '__main__': + s = Solution() + nums = [2,0,2,1,1,0] + s.sortColors(nums) + print(nums) diff --git a/0001-0500/0076-Minimum-Window-Substring/cpp-0076/CMakeLists.txt b/0001-0500/0076-Minimum-Window-Substring/cpp-0076/CMakeLists.txt new file mode 100644 index 00000000..6459f393 --- /dev/null +++ b/0001-0500/0076-Minimum-Window-Substring/cpp-0076/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_Minimum_Window_Substring) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main2.cpp) +add_executable(cpp_Minimum_Window_Substring ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0076-Minimum-Window-Substring/cpp-0076/main.cpp b/0001-0500/0076-Minimum-Window-Substring/cpp-0076/main.cpp new file mode 100644 index 00000000..7996d0bf --- /dev/null +++ b/0001-0500/0076-Minimum-Window-Substring/cpp-0076/main.cpp @@ -0,0 +1,73 @@ +/// Source : https://leetcode.com/problems/minimum-window-substring/ +/// Author : liuyubobobo +/// Time : 2017-01-17 + +#include +#include + +using namespace std; + +/// Sliding Window +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + string minWindow(string s, string t) { + + int tFreq[256] = {0}; + for(int i = 0 ; i < t.size() ; i ++) + tFreq[t[i]] ++; + + int sFreq[256] = {0}; + int sCnt = 0; + + int minLength = s.size() + 1; + int startIndex = -1; + + int l = 0, r = -1; + while(l < s.size()){ + + if(r + 1 < s.size() && sCnt < t.size()){ + + sFreq[s[r+1]] ++; + if(sFreq[s[r+1]] <= tFreq[s[r+1]]) + sCnt ++; + r ++; + } + else{ + assert(sCnt <= t.size()); + if(sCnt == t.size() && r - l + 1 < minLength){ + minLength = r - l + 1; + startIndex = l; + } + + sFreq[s[l]] --; + if(sFreq[s[l]] < tFreq[s[l]]) + sCnt --; + l ++; + } + } + + if( startIndex != -1 ) + return s.substr(startIndex, minLength); + + return ""; + } +}; + +int main() { + + cout << Solution().minWindow("ADOBECODEBANC", "ABC") << endl; + // BANC + + cout << Solution().minWindow("a", "aa") << endl; + // empty + + cout << Solution().minWindow("aa", "aa") << endl; + // aa + + cout << Solution().minWindow("bba", "ab") << endl; + // ba + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0076-Minimum-Window-Substring/cpp-0076/main2.cpp b/0001-0500/0076-Minimum-Window-Substring/cpp-0076/main2.cpp new file mode 100644 index 00000000..0f755b39 --- /dev/null +++ b/0001-0500/0076-Minimum-Window-Substring/cpp-0076/main2.cpp @@ -0,0 +1,91 @@ +/// Source : https://leetcode.com/problems/minimum-window-substring/ +/// Author : liuyubobobo +/// Time : 2018-08-28 + +#include +#include +#include +#include + +using namespace std; + +/// Sliding Window +/// Using filtered s, which remove all characters not in T +/// will be a good improvement when T is small and lots of character are not in S:) +/// +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + string minWindow(string s, string t) { + + unordered_set t_set; + int tFreq[256] = {0}; + for(char c: t){ + t_set.insert(c); + tFreq[c] ++; + } + + string filtered_s = ""; + vector pos; + for(int i = 0; i < s.size() ; i ++) + if(t_set.find(s[i]) != t_set.end()){ + filtered_s += s[i]; + pos.push_back(i); + } + + + int sFreq[256] = {0}; + int sCnt = 0; + + int minLength = s.size() + 1; + int startIndex = -1; + + int l = 0, r = -1; + while(l < filtered_s.size()){ + + if(r + 1 < filtered_s.size() && sCnt < t.size()){ + + sFreq[filtered_s[r+1]] ++; + if(sFreq[filtered_s[r+1]] <= tFreq[filtered_s[r+1]]) + sCnt ++; + r ++; + } + else{ + assert(sCnt <= t.size()); + if(sCnt == t.size() && pos[r] - pos[l] + 1 < minLength){ + minLength = pos[r] - pos[l] + 1; + startIndex = pos[l]; + } + + sFreq[filtered_s[l]] --; + if(sFreq[filtered_s[l]] < tFreq[filtered_s[l]]) + sCnt --; + l ++; + } + } + + if( startIndex != -1 ) + return s.substr(startIndex, minLength); + + return ""; + } +}; + + +int main() { + + cout << Solution().minWindow("ADOBECODEBANC", "ABC") << endl; + // BANC + + cout << Solution().minWindow("a", "aa") << endl; + // empty + + cout << Solution().minWindow("aa", "aa") << endl; + // aa + + cout << Solution().minWindow("bba", "ab") << endl; + // ba + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0077-Combinations/cpp-0077/CMakeLists.txt b/0001-0500/0077-Combinations/cpp-0077/CMakeLists.txt new file mode 100644 index 00000000..5fd3fabe --- /dev/null +++ b/0001-0500/0077-Combinations/cpp-0077/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(cpp_0077) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0077 main5.cpp) \ No newline at end of file diff --git a/0001-0500/0077-Combinations/cpp-0077/main.cpp b/0001-0500/0077-Combinations/cpp-0077/main.cpp new file mode 100644 index 00000000..92c8c11c --- /dev/null +++ b/0001-0500/0077-Combinations/cpp-0077/main.cpp @@ -0,0 +1,63 @@ +/// Source : https://leetcode.com/problems/combinations/description/ +/// Author : liuyubobobo +/// Time : 2017-11-18 + +#include +#include + +using namespace std; + + +/// Naive Recursive +/// Time Complexity: O(k * C(n, k)) +/// Space Complexity: O(k) +class Solution { + +private: + vector> res; + + void generateCombinations(int n, int k, int start, vector &c){ + + if(c.size() == k){ + res.push_back(c); + return; + } + + for(int i = start ; i <= n ; i ++){ + c.push_back( i ); + generateCombinations(n, k, i + 1, c); + c.pop_back(); + } + + return; + } + +public: + vector> combine(int n, int k) { + + res.clear(); + if( n <= 0 || k <= 0 || k > n ) + return res; + + vector c; + generateCombinations(n, k, 1, c); + + return res; + } +}; + + +void print_vec(const vector& vec){ + + for(int e: vec) + cout << e << " "; + cout << endl; +} + +int main() { + + vector> res = Solution().combine(4,2); + for( int i = 0 ; i < res.size() ; i ++ ) + print_vec(res[i]); + return 0; +} \ No newline at end of file diff --git a/0001-0500/0077-Combinations/cpp-0077/main2.cpp b/0001-0500/0077-Combinations/cpp-0077/main2.cpp new file mode 100644 index 00000000..d24f087d --- /dev/null +++ b/0001-0500/0077-Combinations/cpp-0077/main2.cpp @@ -0,0 +1,64 @@ +/// Source : https://leetcode.com/problems/combinations/description/ +/// Author : liuyubobobo +/// Time : 2017-11-18 + +#include +#include + +using namespace std; + + +/// Naive Recursive Optimized +/// Time Complexity: O(k * C(n, k)) +/// Space Complexity: O(k) +class Solution { + +private: + vector> res; + + void generateCombinations(int n, int k, int start, vector &c){ + + if(c.size() == k){ + res.push_back(c); + return; + } + + // i will at most be n - (k - c.size()) + 1 + for(int i = start; i <= n - (k - c.size()) + 1 ; i ++){ + c.push_back(i); + generateCombinations(n, k, i + 1 ,c); + c.pop_back(); + } + + return; + } + +public: + vector> combine(int n, int k) { + + res.clear(); + if(n <= 0 || k <= 0 || k > n) + return res; + + vector c; + generateCombinations(n, k, 1, c); + + return res; + } +}; + + +void print_vec(const vector& vec){ + + for(int e: vec) + cout << e << " "; + cout << endl; +} + +int main() { + + vector> res = Solution().combine(4,2); + for( int i = 0 ; i < res.size() ; i ++ ) + print_vec(res[i]); + return 0; +} \ No newline at end of file diff --git a/0001-0500/0077-Combinations/cpp-0077/main3.cpp b/0001-0500/0077-Combinations/cpp-0077/main3.cpp new file mode 100644 index 00000000..c2e7fc62 --- /dev/null +++ b/0001-0500/0077-Combinations/cpp-0077/main3.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/combinations/description/ +/// Author : liuyubobobo +/// Time : 2019-03-29 + +#include +#include + +using namespace std; + + +/// Using bit mask +/// Time Complexity: O(2^n * n) +/// Space Complexity: O(1) +class Solution { + +public: + vector> combine(int n, int k) { + + vector> res; + + int LIMIT = (1 << n); + for(int i = 0; i < LIMIT; i ++){ + + vector tres = get_vector(i); + if(tres.size() == k) res.push_back(tres); + } + return res; + } + +private: + vector get_vector(int num){ + + vector res; + int i = 1; + while(num){ + if(num % 2) res.push_back(i); + i ++, num /= 2; + } + return res; + } +}; + + +void print_vec(const vector& vec){ + + for(int e: vec) + cout << e << " "; + cout << endl; +} + +int main() { + + vector> res = Solution().combine(4,2); + for( int i = 0 ; i < res.size() ; i ++ ) + print_vec(res[i]); + return 0; +} \ No newline at end of file diff --git a/0001-0500/0077-Combinations/cpp-0077/main4.cpp b/0001-0500/0077-Combinations/cpp-0077/main4.cpp new file mode 100644 index 00000000..58800000 --- /dev/null +++ b/0001-0500/0077-Combinations/cpp-0077/main4.cpp @@ -0,0 +1,64 @@ +/// Source : https://leetcode.com/problems/combinations/description/ +/// Author : liuyubobobo +/// Time : 2019-03-29 + +#include +#include + +using namespace std; + + +/// Get all the combinations in place +/// Find the first non-saturated element and increase it +/// +/// Time Complexity: O(k * C(n, k)) +/// Space Complexity: O(1) +class Solution { + +public: + vector> combine(int n, int k) { + + vector> res; + + vector c; + for(int i = 1; i <= k; i ++) + c.push_back(i); +// Solution::print_vec(c); + res.push_back(c); + + while(c[0] != n - k + 1){ + + if(c.back() != n) c.back() ++; + else{ + int i; + for(i = k - 1; i >= 0; i --) + if(c[i] != i + n - k + 1){ + c[i] ++; + for(int j = i + 1; j < k; j ++) + c[j] = c[j - 1] + 1; + break; + } + } +// Solution::print_vec(c); + res.push_back(vector(c.begin(), c.begin() + k)); + } + return res; + } + + static void print_vec(const vector& vec){ + + for(int e: vec) + cout << e << " "; + cout << endl; + } +}; + + +int main() { + + vector> res = Solution().combine(4,3); + for( int i = 0 ; i < res.size() ; i ++ ) + Solution::print_vec(res[i]); + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0077-Combinations/cpp-0077/main5.cpp b/0001-0500/0077-Combinations/cpp-0077/main5.cpp new file mode 100644 index 00000000..5420c74b --- /dev/null +++ b/0001-0500/0077-Combinations/cpp-0077/main5.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/combinations/description/ +/// Author : liuyubobobo +/// Time : 2019-03-29 + +#include +#include + +using namespace std; + + +/// Get all the combinations in place +/// find the first j which nums[j] + 1 != nums[j + 1] and increase nums[j] +/// See here for details: https://leetcode.com/problems/combinations/solution/ +/// +/// Time Complexity: O(k * C(n, k)) +/// Space Complexity: O(1) +class Solution { + +public: + vector> combine(int n, int k) { + + vector> res; + + vector c; + for(int i = 1; i <= k; i ++) + c.push_back(i); + c.push_back(n + 1); + + int j = 0; + while(j < k){ + + res.push_back(vector(c.begin(), c.begin() + k)); + + for(j = 0; j < k && c[j] + 1 == c[j + 1]; j ++) + c[j] = j + 1; + + c[j] ++; + } + return res; + } +}; + + +void print_vec(const vector& vec){ + + for(int e: vec) + cout << e << " "; + cout << endl; +} + +int main() { + + vector> res = Solution().combine(4,3); + for( int i = 0 ; i < res.size() ; i ++ ) + print_vec(res[i]); + return 0; +} \ No newline at end of file diff --git a/0077-Combinations/java-0077/src/Solution1.java b/0001-0500/0077-Combinations/java-0077/src/Solution1.java similarity index 100% rename from 0077-Combinations/java-0077/src/Solution1.java rename to 0001-0500/0077-Combinations/java-0077/src/Solution1.java diff --git a/0001-0500/0077-Combinations/java-0077/src/Solution2.java b/0001-0500/0077-Combinations/java-0077/src/Solution2.java new file mode 100644 index 00000000..99c2311d --- /dev/null +++ b/0001-0500/0077-Combinations/java-0077/src/Solution2.java @@ -0,0 +1,58 @@ +/// Source : https://leetcode.com/problems/combinations/description/ +/// Author : liuyubobobo +/// Time : 2017-11-18 + +import java.util.List; +import java.util.ArrayList; +import java.util.LinkedList; + + +/// Naive Recursive Optimized +/// Time Complexity: O(n^k) +/// Space Complexity: O(k) +public class Solution2 { + + private ArrayList> res; + + public List> combine(int n, int k) { + + res = new ArrayList>(); + if(n <= 0 || k <= 0 || k > n) + return res; + + LinkedList c = new LinkedList(); + generateCombinations(n, k, 1, c); + + return res; + } + + private void generateCombinations(int n, int k, int start, LinkedList c){ + + if(c.size() == k){ + res.add((List)c.clone()); + return; + } + + // i will at most be n - (k - c.size()) + 1 + for(int i = start ; i <= n - (k - c.size()) + 1 ; i ++){ + c.addLast(i); + generateCombinations(n, k, i + 1, c); + c.removeLast(); + } + + return; + } + + private static void printList(List list){ + for(Integer e: list) + System.out.print(e + " "); + System.out.println(); + } + + public static void main(String[] args) { + + List> res = (new Solution2()).combine(4, 2); + for(List list: res) + printList(list); + } +} diff --git a/0001-0500/0077-Combinations/java-0077/src/Solution3.java b/0001-0500/0077-Combinations/java-0077/src/Solution3.java new file mode 100644 index 00000000..d7758b8d --- /dev/null +++ b/0001-0500/0077-Combinations/java-0077/src/Solution3.java @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/combinations/description/ +/// Author : liuyubobobo +/// Time : 2019-04-08 + +import java.util.List; +import java.util.ArrayList; + + +/// Using bit mask +/// Time Complexity: O(2^n * n) +/// Space Complexity: O(1) +public class Solution3 { + + public List> combine(int n, int k) { + + List> res = new ArrayList<>(); + + int LIMIT = (1 << n); + for(int i = 0; i < LIMIT; i ++){ + List lst = getCombination(i); + if(lst.size() == k) res.add(lst); + } + return res; + } + + private List getCombination(int num){ + + ArrayList res = new ArrayList<>(); + int i = 1; + while (num != 0){ + if(num % 2 == 1) res.add(i); + i ++; + num /= 2; + } + return res; + } +} diff --git a/0001-0500/0077-Combinations/java-0077/src/Solution4.java b/0001-0500/0077-Combinations/java-0077/src/Solution4.java new file mode 100644 index 00000000..df0eb07d --- /dev/null +++ b/0001-0500/0077-Combinations/java-0077/src/Solution4.java @@ -0,0 +1,48 @@ +/// Source : https://leetcode.com/problems/combinations/description/ +/// Author : liuyubobobo +/// Time : 2019-04-08 + +import java.util.List; +import java.util.ArrayList; + + +/// Get all the combinations in place +/// Find the first non-saturated element and increase it +/// +/// Time Complexity: O(k * C(n, k)) +/// Space Complexity: O(1) +public class Solution4 { + + public List> combine(int n, int k) { + + List> res = new ArrayList<>(); + + int[] c = new int[k]; + for(int i = 1; i <= k; i ++) + c[i - 1] = i; + res.add(getList(c)); + + while(c[0] != n - k + 1){ + + if(c[k - 1] != n) c[k - 1] ++; + else{ + for(int i = k - 1; i >= 0; i --) + if(c[i] != i + n - k + 1){ + c[i] ++; + for(int j = i + 1; j < k; j ++) + c[j] = c[j - 1] + 1; + break; + } + } + res.add(getList(c)); + } + return res; + } + + private List getList(int[] arr){ + ArrayList res = new ArrayList<>(); + for(int e: arr) + res.add(e); + return res; + } +} diff --git a/0001-0500/0077-Combinations/java-0077/src/Solution5.java b/0001-0500/0077-Combinations/java-0077/src/Solution5.java new file mode 100644 index 00000000..1c676e22 --- /dev/null +++ b/0001-0500/0077-Combinations/java-0077/src/Solution5.java @@ -0,0 +1,43 @@ +/// Source : https://leetcode.com/problems/combinations/description/ +/// Author : liuyubobobo +/// Time : 2019-04-08 + +import java.util.List; +import java.util.ArrayList; + + +/// Get all the combinations in place +/// find the first j which nums[j] + 1 != nums[j + 1] and increase nums[j] +/// See here for details: https://leetcode.com/problems/combinations/solution/ +/// +/// Time Complexity: O(k * C(n, k)) +/// Space Complexity: O(1) +public class Solution5 { + + public List> combine(int n, int k) { + + List> res = new ArrayList<>(); + + int[] c = new int[k + 1]; + for(int i = 1; i <= k; i ++) + c[i - 1] = i; + c[k] = n + 1; + + int j = 0; + while(j < k){ + res.add(getList(c)); + + for(j = 0; j < k && c[j] + 1 == c[j + 1]; j ++) + c[j] = j + 1; + c[j] ++; + } + return res; + } + + private List getList(int[] arr){ + ArrayList res = new ArrayList<>(); + for(int i = 0; i < arr.length - 1; i ++) + res.add(arr[i]); + return res; + } +} diff --git a/0001-0500/0078-Subsets/cpp-0078/CMakeLists.txt b/0001-0500/0078-Subsets/cpp-0078/CMakeLists.txt new file mode 100644 index 00000000..604f8036 --- /dev/null +++ b/0001-0500/0078-Subsets/cpp-0078/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_0078) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0078 main.cpp) \ No newline at end of file diff --git a/0001-0500/0078-Subsets/cpp-0078/main.cpp b/0001-0500/0078-Subsets/cpp-0078/main.cpp new file mode 100644 index 00000000..f30b47f9 --- /dev/null +++ b/0001-0500/0078-Subsets/cpp-0078/main.cpp @@ -0,0 +1,43 @@ +/// Source : https://leetcode.com/problems/subsets/ +/// Author : liuyubobobo +/// Time : 2021-07-24 + +#include +#include + +using namespace std; + + +/// Subsets traversal +/// Time Compelexity: O(2^n) +/// Space Complexity: O(2^n) +class Solution { +public: + vector> subsets(vector& nums) { + + vector> res; + + int n = nums.size(); + for(int state = 0; state < (1 << n); state ++) + res.push_back(get_subsets(state, nums)); + return res; + } + +private: + vector get_subsets(int state, const vector& nums){ + + vector res; + int k = 0; + while(state){ + if(state & 1) res.push_back(nums[k]); + state >>= 1, k ++; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/0079-Word-Search/cpp-0079/CMakeLists.txt b/0001-0500/0079-Word-Search/cpp-0079/CMakeLists.txt similarity index 100% rename from 0079-Word-Search/cpp-0079/CMakeLists.txt rename to 0001-0500/0079-Word-Search/cpp-0079/CMakeLists.txt diff --git a/0079-Word-Search/cpp-0079/main.cpp b/0001-0500/0079-Word-Search/cpp-0079/main.cpp similarity index 100% rename from 0079-Word-Search/cpp-0079/main.cpp rename to 0001-0500/0079-Word-Search/cpp-0079/main.cpp diff --git a/0079-Word-Search/java-0079/src/Solution.java b/0001-0500/0079-Word-Search/java-0079/src/Solution.java similarity index 100% rename from 0079-Word-Search/java-0079/src/Solution.java rename to 0001-0500/0079-Word-Search/java-0079/src/Solution.java diff --git a/old/0080 Remove Duplicates from Sorted Array II/cpp-Remove-Duplicates-from-Sorted-Array-II/CMakeLists.txt b/0001-0500/0080-Remove-Duplicates-from-Sorted-Array-II/cpp-0080/CMakeLists.txt similarity index 100% rename from old/0080 Remove Duplicates from Sorted Array II/cpp-Remove-Duplicates-from-Sorted-Array-II/CMakeLists.txt rename to 0001-0500/0080-Remove-Duplicates-from-Sorted-Array-II/cpp-0080/CMakeLists.txt diff --git a/0001-0500/0080-Remove-Duplicates-from-Sorted-Array-II/cpp-0080/main.cpp b/0001-0500/0080-Remove-Duplicates-from-Sorted-Array-II/cpp-0080/main.cpp new file mode 100644 index 00000000..723ad5e1 --- /dev/null +++ b/0001-0500/0080-Remove-Duplicates-from-Sorted-Array-II/cpp-0080/main.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/description/ +/// Author : liuyubobobo +/// Time : 2016-12-26 +#include +#include + +using namespace std; + +/// Ad-Hoc +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int removeDuplicates(vector& nums) { + + int i = 0; + int j = 0; + while(j < nums.size()){ + int k = nextIndex(nums, j); + int len = min( 2, k-j); + for(int ii = 0 ; ii < len ; ii ++) + nums[i+ii] = nums[j]; + i += len; + j = k; + } + + return i; + } + +private: + int nextIndex(const vector& nums, int index){ + for(int i = index ; i < nums.size() ; i ++) + if(nums[i] != nums[index]) + return i; + return nums.size(); + } +}; + + +int main() { + + vector nums1 = {1, 1, 1, 2, 2, 3}; + cout << Solution().removeDuplicates(nums1) << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0081-Search-in-Rotated-Sorted-Array-II/cpp-0081/CMakeLists.txt b/0001-0500/0081-Search-in-Rotated-Sorted-Array-II/cpp-0081/CMakeLists.txt new file mode 100644 index 00000000..2a77bdf1 --- /dev/null +++ b/0001-0500/0081-Search-in-Rotated-Sorted-Array-II/cpp-0081/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0081) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0081 main.cpp) \ No newline at end of file diff --git a/0001-0500/0081-Search-in-Rotated-Sorted-Array-II/cpp-0081/main.cpp b/0001-0500/0081-Search-in-Rotated-Sorted-Array-II/cpp-0081/main.cpp new file mode 100644 index 00000000..d98a78d7 --- /dev/null +++ b/0001-0500/0081-Search-in-Rotated-Sorted-Array-II/cpp-0081/main.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/search-in-rotated-sorted-array-ii/ +/// Author : liuyubobobo +/// Time : 2020-10-14 + +#include +#include + +using namespace std; + + +/// Finding break point and binary search +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + bool search(vector& nums, int target) { + + if(nums.size() == 0) return false; + + int p = 0; + for(p = 0; p + 1 < nums.size(); p ++) + if(nums[p] > nums[p + 1]) break; + + int l = 0, r = p; + while(l <= r){ + int mid = l + (r - l) / 2; + if(nums[mid] == target) return true; + if(target < nums[mid]) r = mid - 1; + else l = mid + 1; + } + + l = p + 1, r = nums.size() - 1; + while(l <= r){ + int mid = l + (r - l) / 2; + if(nums[mid] == target) return true; + if(target < nums[mid]) r = mid - 1; + else l = mid + 1; + } + + return false; + } +}; + + +int main() { + + vector nums1 = {4,5,6,7,0,1,2}; + cout << Solution().search(nums1, 0) << endl; + + vector nums2 = {4,5,6,7,8,1,2,3}; + cout << Solution().search(nums2, 8) << endl; + + return 0; +} diff --git a/0001-0500/0082-Remove-Duplicates-from-Sorted-List-II/cpp-0082/CMakeLists.txt b/0001-0500/0082-Remove-Duplicates-from-Sorted-List-II/cpp-0082/CMakeLists.txt new file mode 100644 index 00000000..c85ee3be --- /dev/null +++ b/0001-0500/0082-Remove-Duplicates-from-Sorted-List-II/cpp-0082/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(cpp_0082) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(cpp_0082 main.cpp) \ No newline at end of file diff --git a/0001-0500/0082-Remove-Duplicates-from-Sorted-List-II/cpp-0082/main.cpp b/0001-0500/0082-Remove-Duplicates-from-Sorted-List-II/cpp-0082/main.cpp new file mode 100644 index 00000000..687bd57b --- /dev/null +++ b/0001-0500/0082-Remove-Duplicates-from-Sorted-List-II/cpp-0082/main.cpp @@ -0,0 +1,56 @@ +/// Source : https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/ +/// Author : liuyubobobo +/// Time : 2019-02-11 + +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(n) +/// Space Complexity: O(1) + +/// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} +}; + +class Solution { +public: + ListNode* deleteDuplicates(ListNode* head) { + + ListNode* dummyHead = new ListNode(-1); + dummyHead->next = head; + + ListNode* prev = dummyHead; + ListNode* cur = prev->next; + while(cur){ + + int num = 0; + ListNode* p = cur; + while(p && p->val == cur->val){ + num ++; + p = p->next; + } + + if(num > 1) + prev->next = p; + else + prev = cur; + cur = p; + } + + ListNode* ret = dummyHead->next; + delete dummyHead; + return ret; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0083-Remove-Duplicates-from-Sorted-List/cpp-0083/CMakeLists.txt b/0001-0500/0083-Remove-Duplicates-from-Sorted-List/cpp-0083/CMakeLists.txt new file mode 100644 index 00000000..752ffb47 --- /dev/null +++ b/0001-0500/0083-Remove-Duplicates-from-Sorted-List/cpp-0083/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(cpp_0083) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0083 main.cpp) \ No newline at end of file diff --git a/0001-0500/0083-Remove-Duplicates-from-Sorted-List/cpp-0083/main.cpp b/0001-0500/0083-Remove-Duplicates-from-Sorted-List/cpp-0083/main.cpp new file mode 100644 index 00000000..691dcfb7 --- /dev/null +++ b/0001-0500/0083-Remove-Duplicates-from-Sorted-List/cpp-0083/main.cpp @@ -0,0 +1,38 @@ +/// Source : https://leetcode.com/problems/remove-duplicates-from-sorted-list/ +/// Author : liuyubobobo +/// Time : 2020-04-02 + +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(n) +/// Space Complexity: O(1) + +/// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} +}; + +class Solution { +public: + ListNode* deleteDuplicates(ListNode* head) { + + ListNode* cur = head; + while(cur && cur->next){ + if(cur->val == cur->next->val) cur->next = cur->next->next; + else cur = cur->next; + } + return head; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0084-Largest-Rectangle-in-Histogram/cpp-0084/CMakeLists.txt b/0001-0500/0084-Largest-Rectangle-in-Histogram/cpp-0084/CMakeLists.txt new file mode 100644 index 00000000..68c0afe5 --- /dev/null +++ b/0001-0500/0084-Largest-Rectangle-in-Histogram/cpp-0084/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(cpp_0084) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0084 main4.cpp) \ No newline at end of file diff --git a/0001-0500/0084-Largest-Rectangle-in-Histogram/cpp-0084/main.cpp b/0001-0500/0084-Largest-Rectangle-in-Histogram/cpp-0084/main.cpp new file mode 100644 index 00000000..bd3bb336 --- /dev/null +++ b/0001-0500/0084-Largest-Rectangle-in-Histogram/cpp-0084/main.cpp @@ -0,0 +1,96 @@ +/// Source : https://leetcode.com/problems/largest-rectangle-in-histogram/ +/// Author : liuyubobobo +/// Time : 2020-05-13 + +#include +#include + +using namespace std; + + +/// Divide and Conquer + Segment Tree +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class SegmentTree{ + +private: + int n; + vector data, tree; + +public: + SegmentTree(const vector& data): data(data.begin(), data.end()), n(data.size()), tree(4*n, 0){ + buildSegTree(0, 0, n - 1); + } + + int query(int l, int r){ + return query(0, 0, n - 1, l, r); + } + +private: + void buildSegTree(int treeID, int l, int r){ + + if(l == r){ + tree[treeID] = l; + return; + } + + int mid = (l + r) / 2; + buildSegTree(treeID * 2 + 1, l, mid); + buildSegTree(treeID * 2 + 2, mid + 1, r); + tree[treeID] = data[tree[treeID * 2 + 1]] < data[tree[treeID * 2 + 2]] ? tree[treeID * 2 + 1] : tree[treeID * 2 + 2]; + return; + } + + int query(int treeID, int l, int r, int ql, int qr){ + + if(ql == l && qr == r) + return tree[treeID]; + + int mid = (l + r) / 2; + if(qr <= mid) return query(treeID * 2 + 1, l, mid, ql, qr); + else if(ql > mid) return query(treeID * 2 + 2, mid + 1, r, ql, qr); + + int resl = query(treeID * 2 + 1, l, mid, ql, mid); + int resr = query(treeID * 2 + 2, mid + 1, r, mid + 1, qr); + return data[resl] < data[resr] ? resl : resr; + } +}; + +class Solution { + +private: + int n; + +public: + int largestRectangleArea(vector& heights) { + + n = heights.size(); + if(!n) return 0; + + SegmentTree tree(heights); + return largest(heights, 0, n - 1, tree); + } + +private: + int largest(const vector& heights, int l, int r, SegmentTree& tree){ + + if(l > r) return 0; + if(l == r) return heights[l]; + + int min_index = tree.query(l, r); + int res = largest(heights, l, min_index - 1, tree); + res = max(res, largest(heights, min_index + 1, r, tree)); + res = max(res, heights[min_index] * (r - l + 1)); + return res; + } +}; + + +int main() { + + vector heights = {2,1,5,6,2,3}; + cout << Solution().largestRectangleArea(heights) << endl; + // 10 + + return 0; +} diff --git a/0001-0500/0084-Largest-Rectangle-in-Histogram/cpp-0084/main2.cpp b/0001-0500/0084-Largest-Rectangle-in-Histogram/cpp-0084/main2.cpp new file mode 100644 index 00000000..8b624e5a --- /dev/null +++ b/0001-0500/0084-Largest-Rectangle-in-Histogram/cpp-0084/main2.cpp @@ -0,0 +1,79 @@ +/// Source : https://leetcode.com/problems/largest-rectangle-in-histogram/ +/// Author : liuyubobobo +/// Time : 2020-05-13 + +#include +#include +#include + +using namespace std; + + +/// Monotone Stack +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +public: + int largestRectangleArea(vector& heights) { + + int n = heights.size(); + if(!n) return 0; + + stack stack; + int res = 0; + for(int i = 0; i < n; i ++){ + while(!stack.empty() && heights[i] < heights[stack.top()]){ + int x = stack.top(); + res = max(res, heights[x]); + stack.pop(); + if(!stack.empty()) res = max(res, heights[x] * (i - 1 - (stack.top() + 1) + 1)); + else res = max(res, heights[x] * i); + } + stack.push(i); + } + + if(!stack.empty()){ + int r = stack.top(); + while(!stack.empty()){ + int x = stack.top(); + stack.pop(); + res = max(res, heights[x]); + + if(!stack.empty()) res = max(res, heights[x] * (r - (stack.top() + 1) + 1)); + else res = max(res, heights[x] * n); + } + } + return res; + } +}; + + +int main() { + + vector heights1 = {2,1,5,6,2,3}; + cout << Solution().largestRectangleArea(heights1) << endl; + // 10 + + vector heights2 = {2,1,2}; + cout << Solution().largestRectangleArea(heights2) << endl; + // 3 + + vector heights3 = {0, 9}; + cout << Solution().largestRectangleArea(heights3) << endl; + // 9 + + vector heights4 = {5, 4, 1, 2}; + cout << Solution().largestRectangleArea(heights4) << endl; + // 8 + + vector heights5 = {1, 2, 3, 4, 5}; + cout << Solution().largestRectangleArea(heights5) << endl; + // 9 + + vector heights6 = {4, 2, 0, 3, 2, 5}; + cout << Solution().largestRectangleArea(heights6) << endl; + // 6 + + return 0; +} diff --git a/0001-0500/0084-Largest-Rectangle-in-Histogram/cpp-0084/main3.cpp b/0001-0500/0084-Largest-Rectangle-in-Histogram/cpp-0084/main3.cpp new file mode 100644 index 00000000..ab35a85c --- /dev/null +++ b/0001-0500/0084-Largest-Rectangle-in-Histogram/cpp-0084/main3.cpp @@ -0,0 +1,69 @@ +/// Source : https://leetcode.com/problems/largest-rectangle-in-histogram/ +/// Author : liuyubobobo +/// Time : 2020-05-14 + +#include +#include +#include + +using namespace std; + + +/// Monotone Stack with sentinel to simplify the code +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +public: + int largestRectangleArea(vector& heights) { + + if(!heights.size()) return 0; + + heights.insert(heights.begin(), 0); + heights.push_back(0); + + stack stack; + int res = 0; + for(int i = 0; i < heights.size(); i ++){ + while(!stack.empty() && heights[i] < heights[stack.top()]){ + int x = stack.top(); + res = max(res, heights[x]); + stack.pop(); + if(!stack.empty()) res = max(res, heights[x] * (i - 1 - (stack.top() + 1) + 1)); + else res = max(res, heights[x] * i); + } + stack.push(i); + } + return res; + } +}; + + +int main() { + + vector heights1 = {2,1,5,6,2,3}; + cout << Solution().largestRectangleArea(heights1) << endl; + // 10 + + vector heights2 = {2,1,2}; + cout << Solution().largestRectangleArea(heights2) << endl; + // 3 + + vector heights3 = {0, 9}; + cout << Solution().largestRectangleArea(heights3) << endl; + // 9 + + vector heights4 = {5, 4, 1, 2}; + cout << Solution().largestRectangleArea(heights4) << endl; + // 8 + + vector heights5 = {1, 2, 3, 4, 5}; + cout << Solution().largestRectangleArea(heights5) << endl; + // 9 + + vector heights6 = {4, 2, 0, 3, 2, 5}; + cout << Solution().largestRectangleArea(heights6) << endl; + // 6 + + return 0; +} diff --git a/0001-0500/0084-Largest-Rectangle-in-Histogram/cpp-0084/main4.cpp b/0001-0500/0084-Largest-Rectangle-in-Histogram/cpp-0084/main4.cpp new file mode 100644 index 00000000..a055304b --- /dev/null +++ b/0001-0500/0084-Largest-Rectangle-in-Histogram/cpp-0084/main4.cpp @@ -0,0 +1,81 @@ +/// Source : https://leetcode.com/problems/largest-rectangle-in-histogram/ +/// Author : liuyubobobo +/// Time : 2020-05-20 + +#include +#include +#include + +using namespace std; + + +/// A very cool idea, using a dp-like thoughts +/// See here for details: https://leetcode.com/problems/largest-rectangle-in-histogram/discuss/28902/5ms-O(n)-Java-solution-explained-(beats-96) +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +public: + int largestRectangleArea(vector& heights) { + + int n = heights.size(); + if(!n) return 0; + + heights.insert(heights.begin(), INT_MAX); + heights.push_back(INT_MAX); + + vector left(n + 2), right(n + 2); + left[0] = 0; + for(int i = 1; i <= n; i ++){ + int p = i - 1; + while(p > 0 && heights[i] <= heights[p]) + p = left[p]; + left[i] = p; + } +// for(int e: left) cout << e << " "; cout << endl; + + right[n + 1] = n + 1; + for(int i = n; i >= 1; i --){ + int p = i + 1; + while(p < n + 1 && heights[i] <= heights[p]) + p = right[p]; + right[i] = p; + } +// for(int e: right) cout << e << " "; cout << endl; + + int res = 0; + for(int i = 1; i <= n; i ++) + res = max(res, heights[i] * (right[i] - left[i] - 1)); + return res; + } +}; + + +int main() { + + vector heights1 = {2,1,5,6,2,3}; + cout << Solution().largestRectangleArea(heights1) << endl; + // 10 + + vector heights2 = {2,1,2}; + cout << Solution().largestRectangleArea(heights2) << endl; + // 3 + + vector heights3 = {0, 9}; + cout << Solution().largestRectangleArea(heights3) << endl; + // 9 + + vector heights4 = {5, 4, 1, 2}; + cout << Solution().largestRectangleArea(heights4) << endl; + // 8 + + vector heights5 = {1, 2, 3, 4, 5}; + cout << Solution().largestRectangleArea(heights5) << endl; + // 9 + + vector heights6 = {4, 2, 0, 3, 2, 5}; + cout << Solution().largestRectangleArea(heights6) << endl; + // 6 + + return 0; +} diff --git a/0001-0500/0085-Maximal-Rectangle/cpp-0085/CMakeLists.txt b/0001-0500/0085-Maximal-Rectangle/cpp-0085/CMakeLists.txt new file mode 100644 index 00000000..6df69af5 --- /dev/null +++ b/0001-0500/0085-Maximal-Rectangle/cpp-0085/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0085) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0085 main2.cpp) \ No newline at end of file diff --git a/0001-0500/0085-Maximal-Rectangle/cpp-0085/main.cpp b/0001-0500/0085-Maximal-Rectangle/cpp-0085/main.cpp new file mode 100644 index 00000000..71d67a92 --- /dev/null +++ b/0001-0500/0085-Maximal-Rectangle/cpp-0085/main.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/maximal-rectangle/ +/// Author : liuyubobobo +/// Time : 2020-12-26 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(R * C * R) +/// Space Complexity: O(R * C) +class Solution { +public: + int maximalRectangle(vector>& matrix) { + + if(!matrix.size() || !matrix[0].size()) return 0; + + int R = matrix.size(), C = matrix[0].size(); + vector> dp(R, vector(C, 0)); + for(int i = 0; i < matrix.size(); i ++){ + dp[i][0] = matrix[i][0] - '0'; + for(int j = 1; j < C; j ++) + if(matrix[i][j] == '1') + dp[i][j] = dp[i][j - 1] + 1; + } + + int res = *max_element(dp[0].begin(), dp[0].end()); + + for(int i = 1; i < R; i ++) + for(int j = 0; j < C; j ++){ + int w = dp[i][j]; + for(int k = i; k >= 0 && w; k --){ + w = min(w, dp[k][j]); + res = max(res, w * (i - k + 1)); + } + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0085-Maximal-Rectangle/cpp-0085/main2.cpp b/0001-0500/0085-Maximal-Rectangle/cpp-0085/main2.cpp new file mode 100644 index 00000000..4e3b03e4 --- /dev/null +++ b/0001-0500/0085-Maximal-Rectangle/cpp-0085/main2.cpp @@ -0,0 +1,58 @@ +/// Source : https://leetcode.com/problems/maximal-rectangle/ +/// Author : liuyubobobo +/// Time : 2020-12-26 + +#include +#include + +using namespace std; + + +/// Dynamic Programming and Mono Stack +/// Time Complexity: O(R * C) +/// Space Complexity: O(R * C) +class Solution { +public: + int maximalRectangle(vector>& matrix) { + + if(!matrix.size() || !matrix[0].size()) return 0; + + int R = matrix.size(), C = matrix[0].size(); + vector> dp(R, vector(C, 0)); + for(int i = 0; i < matrix.size(); i ++){ + dp[i][0] = matrix[i][0] - '0'; + for(int j = 1; j < C; j ++) + if(matrix[i][j] == '1') + dp[i][j] = dp[i][j - 1] + 1; + } + + int res = 0; + for(int j = 0; j < C; j ++){ + vector stack; + stack.push_back(0); + for(int i = 1; i < R; i ++){ + while(!stack.empty() && dp[i][j] < dp[stack.back()][j]){ + int h = dp[stack.back()][j]; + stack.pop_back(); + int l = stack.empty() ? 0 : stack.back() + 1; + res = max(res, h * (i - l)); + } + stack.push_back(i); + } + + while(!stack.empty()){ + int h = dp[stack.back()][j]; + stack.pop_back(); + int l = stack.empty() ? 0 : stack.back() + 1; + res = max(res, h * (R - l)); + } + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0086-Partition-List/cpp-0086/CMakeLists.txt b/0001-0500/0086-Partition-List/cpp-0086/CMakeLists.txt new file mode 100644 index 00000000..b5ba07cd --- /dev/null +++ b/0001-0500/0086-Partition-List/cpp-0086/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0086) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0086 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0086-Partition-List/cpp-0086/main.cpp b/0001-0500/0086-Partition-List/cpp-0086/main.cpp new file mode 100644 index 00000000..ce8e3fad --- /dev/null +++ b/0001-0500/0086-Partition-List/cpp-0086/main.cpp @@ -0,0 +1,56 @@ +/// Source : https://leetcode.com/problems/partition-list/description/ +/// Author : liuyubobobo +/// Time : 2018-07-07 + +#include + +using namespace std; + +/// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} +}; + +/// Linear Scan +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + ListNode* partition(ListNode* head, int x) { + + ListNode* dummyHead1 = new ListNode(-1); + ListNode* dummyHead2 = new ListNode(-1); + ListNode* prev1 = dummyHead1; + ListNode* prev2 = dummyHead2; + + for(ListNode* cur = head ; cur != NULL ;){ + if(cur->val < x){ + prev1->next = cur; + cur = cur->next; + prev1 = prev1->next; + prev1->next = NULL; + } + else{ + prev2->next = cur; + cur = cur->next; + prev2 = prev2->next; + prev2->next = NULL; + } + } + + prev1->next = dummyHead2->next; + ListNode* ret = dummyHead1->next; + + delete dummyHead1; + delete dummyHead2; + return ret; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0087-Scramble-String/cpp-0087/CMakeLists.txt b/0001-0500/0087-Scramble-String/cpp-0087/CMakeLists.txt new file mode 100644 index 00000000..8e2494be --- /dev/null +++ b/0001-0500/0087-Scramble-String/cpp-0087/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0087) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main4.cpp) +add_executable(cpp_0087 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0087-Scramble-String/cpp-0087/main.cpp b/0001-0500/0087-Scramble-String/cpp-0087/main.cpp new file mode 100644 index 00000000..5e2876dd --- /dev/null +++ b/0001-0500/0087-Scramble-String/cpp-0087/main.cpp @@ -0,0 +1,62 @@ +/// Source : https://leetcode.com/problems/scramble-string/description/ +/// Author : liuyubobobo +/// Time : 2018-04-23 + +#include +#include +#include + +using namespace std; + +/// Recursive +/// Time Complexity: O(n^n) +/// Space Complexity: O(n^2) +class Solution { +public: + bool isScramble(string s1, string s2) { + + if(s1.size() != s2.size()) + return false; + + if(s1 == s2) + return true; + + unordered_map freq; + for(char c: s1) + freq[c] += 1; + for(char c: s2) + if(freq.find(c) == freq.end()) + return false; + else{ + freq[c] -= 1; + if(freq[c] == 0) + freq.erase(c); + } + + + for(int i = 1 ; i <= s1.size() - 1 ; i ++){ + if(isScramble(s1.substr(0, i), s2.substr(0, i)) + && isScramble(s1.substr(i), s2.substr(i))) + return true; + if(isScramble(s1.substr(0, i), s2.substr(s2.size() - i)) + && isScramble(s1.substr(i), s2.substr(0, s2.size() - i))) + return true; + } + + return false; + } +}; + + +void print_bool(bool res){ + cout << (res ? "true" : "false") << endl; +} + +int main() { + + print_bool(Solution().isScramble("great", "rgeat")); + print_bool(Solution().isScramble("abcde", "caebd")); + print_bool(Solution().isScramble("abcdefghijklmn", "efghijklmncadb")); + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0087-Scramble-String/cpp-0087/main2.cpp b/0001-0500/0087-Scramble-String/cpp-0087/main2.cpp new file mode 100644 index 00000000..4c186b3a --- /dev/null +++ b/0001-0500/0087-Scramble-String/cpp-0087/main2.cpp @@ -0,0 +1,73 @@ +/// Source : https://leetcode.com/problems/scramble-string/description/ +/// Author : liuyubobobo +/// Time : 2018-04-23 + +#include +#include +#include + +using namespace std; + +/// Memory Search +/// Time Complexity: O(26^n) +/// Space Complexity: O(n^2) +class Solution { + +public: + bool isScramble(string s1, string s2) { + + if(s1.size() != s2.size()) + return false; + + unordered_map memo; + return isScramble(s1, s2, memo); + } + +private: + bool isScramble(string s1, string s2, unordered_map& memo) { + + string key = s1 + s2; + if(memo.find(key) != memo.end()) + return memo[key]; + + if(s1 == s2) + return memo[key] = true; + + unordered_map freq; + for(char c: s1) + freq[c] += 1; + for(char c: s2) + if(freq.find(c) == freq.end()) + return memo[key] = false; + else{ + freq[c] -= 1; + if(freq[c] == 0) + freq.erase(c); + } + + for(int i = 1 ; i <= s1.size() - 1 ; i ++){ + if(isScramble(s1.substr(0, i), s2.substr(0, i)) + && isScramble(s1.substr(i), s2.substr(i))) + return memo[key] = true; + if(isScramble(s1.substr(0, i), s2.substr(s2.size() - i)) + && isScramble(s1.substr(i), s2.substr(0, s2.size() - i))) + return memo[key] = true; + } + + return memo[key] = false; + } +}; + + +void print_bool(bool res){ + cout << (res ? "true" : "false") << endl; +} + +int main() { + + print_bool(Solution().isScramble("great", "rgeat")); + print_bool(Solution().isScramble("abcde", "caebd")); + print_bool(Solution().isScramble("abcdefghijklmn", "efghijklmncadb")); + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0087-Scramble-String/cpp-0087/main3.cpp b/0001-0500/0087-Scramble-String/cpp-0087/main3.cpp new file mode 100644 index 00000000..46e1c473 --- /dev/null +++ b/0001-0500/0087-Scramble-String/cpp-0087/main3.cpp @@ -0,0 +1,78 @@ +/// Source : https://leetcode.com/problems/scramble-string/description/ +/// Author : liuyubobobo +/// Time : 2018-04-23 + +#include +#include +#include +#include + +using namespace std; + +/// Memory Search +/// Time Complexity: O(n^4) +/// Space Complexity: O(n^4) +class Solution { + +public: + bool isScramble(string s1, string s2) { + + if(s1.size() != s2.size()) + return false; + + vector>> memo(s1.size() + 1, + vector>(s1.size(), vector(s2.size(), -1)) + ); + return isScramble(s1, s2, s1.size(), 0, 0, memo); + } + +private: + bool isScramble(string s1, string s2, int len, int i1, int i2, + vector>>& memo) { + + if(memo[len][i1][i2] != -1) + return memo[len][i1][i2]; + + string a = s1.substr(i1, len); + string b = s2.substr(i2, len); + if(a == b) + return memo[len][i1][i2] = true; + + unordered_map freq; + for(char c: a) + freq[c] += 1; + for(char c: b) + if(freq.find(c) == freq.end()) + return memo[len][i1][i2] = false; + else{ + freq[c] -= 1; + if(freq[c] == 0) + freq.erase(c); + } + + for(int i = 1 ; i <= len - 1 ; i ++){ + if(isScramble(s1, s2, i, i1, i2, memo) + && isScramble(s1, s2, len - i, i1 + i, i2 + i, memo)) + return memo[len][i1][i2] = true; + if(isScramble(s1, s2, i, i1, i2 + len - i, memo) + && isScramble(s1, s2, len - i, i1 + i, i2, memo)) + return memo[len][i1][i2] = true; + } + + return memo[len][i1][i2] = false; + } +}; + + +void print_bool(bool res){ + cout << (res ? "true" : "false") << endl; +} + +int main() { + + print_bool(Solution().isScramble("great", "rgeat")); + print_bool(Solution().isScramble("abcde", "caebd")); + print_bool(Solution().isScramble("abcdefghijklmn", "efghijklmncadb")); + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0087-Scramble-String/cpp-0087/main4.cpp b/0001-0500/0087-Scramble-String/cpp-0087/main4.cpp new file mode 100644 index 00000000..f43dfa02 --- /dev/null +++ b/0001-0500/0087-Scramble-String/cpp-0087/main4.cpp @@ -0,0 +1,65 @@ +/// Source : https://leetcode.com/problems/scramble-string/description/ +/// Author : liuyubobobo +/// Time : 2018-04-23 + +#include +#include +#include +#include + +using namespace std; + +/// Dynamic Programming +/// Time Complexity: O(n^4) +/// Space Complexity: O(n^3) +class Solution { + +public: + bool isScramble(string s1, string s2) { + + if(s1.size() != s2.size()) + return false; + + vector>> memo(s1.size() + 1, + vector>(s1.size(), vector(s2.size(), false)) + ); + for(int i = 0 ; i < s1.size() ; i ++) + for(int j = 0 ; j < s2.size() ; j ++) + if(s1[i] == s2[j]) + memo[1][i][j] = true; + + for(int len = 2 ; len <= s1.size() ; len ++) + for(int i1 = 0 ; i1 <= s1.size() - len ; i1 ++) + for(int i2 = 0 ; i2 <= s2.size() - len ; i2 ++){ + + for(int i = 1 ; i <= len - 1 ; i ++){ + if(memo[i][i1][i2] && memo[len - i][i1 + i][i2 + i]){ + memo[len][i1][i2] = true; + break; + } + else if(memo[i][i1][i2 + len - i] && memo[len - i][i1 + i][i2]){ + memo[len][i1][i2] = true; + break; + } + } + } + + return memo[s1.size()][0][0]; + } + +}; + + +void print_bool(bool res){ + cout << (res ? "true" : "false") << endl; +} + +int main() { + + print_bool(Solution().isScramble("great", "rgeat")); + print_bool(Solution().isScramble("abcde", "caebd")); + print_bool(Solution().isScramble("abcdefghijklmn", "efghijklmncadb")); + print_bool(Solution().isScramble("abc", "bca")); + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0088-Merge-Sorted-Array/cpp-0088/CMakeLists.txt b/0001-0500/0088-Merge-Sorted-Array/cpp-0088/CMakeLists.txt new file mode 100644 index 00000000..f6ebee07 --- /dev/null +++ b/0001-0500/0088-Merge-Sorted-Array/cpp-0088/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(cpp_0088) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(cpp_0088 main2.cpp) \ No newline at end of file diff --git a/0001-0500/0088-Merge-Sorted-Array/cpp-0088/main.cpp b/0001-0500/0088-Merge-Sorted-Array/cpp-0088/main.cpp new file mode 100644 index 00000000..b59c36e8 --- /dev/null +++ b/0001-0500/0088-Merge-Sorted-Array/cpp-0088/main.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/merge-sorted-array/ +/// Author : liuyubobobo +/// Time : 2019-02-07 + +#include +#include +#include + +using namespace std; + + +/// Sorting +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + void merge(vector& nums1, int m, vector& nums2, int n) { + + assert(nums1.size() == m + n && nums2.size() == n); + + for(int i = 0; i < n ; i ++ ) + nums1[m + i] = nums2[i]; + + sort(nums1.begin(), nums1.end()); + } +}; + + +void print_vec(const vector& vec){ + for(int e: vec) + cout << e << " "; + cout << endl; +} + +int main() { + + vector nums1 = {1, 3, 5, 7}; + int m = nums1.size(); + + vector nums2 = {2, 4, 6}; + int n = nums2.size(); + + for( int i = 0 ; i < nums2.size() ; i ++ ) + nums1.push_back(0); + + Solution().merge(nums1, m, nums2, n); + print_vec(nums1); + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0088-Merge-Sorted-Array/cpp-0088/main2.cpp b/0001-0500/0088-Merge-Sorted-Array/cpp-0088/main2.cpp new file mode 100644 index 00000000..43661d2b --- /dev/null +++ b/0001-0500/0088-Merge-Sorted-Array/cpp-0088/main2.cpp @@ -0,0 +1,62 @@ +/// Source : https://leetcode.com/problems/merge-sorted-array/ +/// Author : liuyubobobo +/// Time : 2016-12-06 + +#include +#include +#include + +using namespace std; + + +/// Standard merge process in merge sort +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + void merge(vector& nums1, int m, vector& nums2, int n) { + + assert(nums1.size() == m + n && nums2.size() == n); + + for(int i = n + m - 1 ; i >= n ; i -- ) + nums1[i] = nums1[i - n]; + + int i = n; // pointer for nums1 [n, n+m) + int j = 0; // pointer for nums2 [0, n) + int k = 0; // pointer merged nums1 [0, n+m) + while( k < n + m ){ + if( i >= n+m ) + nums1[k++] = nums2[j++]; + else if( j >= n ) + nums1[k++] = nums1[i++]; + else if( nums1[i] < nums2[j] ) + nums1[k++] = nums1[i++]; + else + nums1[k++] = nums2[j++]; + } + } +}; + + +void print_vec(const vector& vec){ + for(int e: vec) + cout << e << " "; + cout << endl; +} + +int main() { + + vector nums1 = {1, 3, 5, 7}; + int m = nums1.size(); + + vector nums2 = {2, 4, 6}; + int n = nums2.size(); + + for( int i = 0 ; i < nums2.size() ; i ++ ) + nums1.push_back(0); + + Solution().merge(nums1, m, nums2, n); + print_vec(nums1); + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0088-Merge-Sorted-Array/java-0088/src/Solution1.java b/0001-0500/0088-Merge-Sorted-Array/java-0088/src/Solution1.java new file mode 100644 index 00000000..1a791bbf --- /dev/null +++ b/0001-0500/0088-Merge-Sorted-Array/java-0088/src/Solution1.java @@ -0,0 +1,35 @@ +/** + * @author: qiaoyi + * @edit: + * @created:2019/09/10 + * Time Complexity:O(n) + * Space Complexity:O(n) + */ +public class Solution1 { + + //using auxilliary array + public static void merge(int[] nums1, int m, int[] nums2, int n) { + if (n <= 0) { + return; + } + int[] result = new int[m + n]; + int point1 = 0; + int point2 = 0; + for (int i = 0; i < m + n; i++) { + if (point1 < m && point2 < n && nums1[point1] < nums2[point2]) { + result[i] = nums1[point1++]; + } else if (point2 < n) { + result[i] = nums2[point2++]; + } else { + result[i] = nums1[point1++]; + } + } + System.arraycopy(result, 0, nums1, 0, nums1.length); + } + + public static void main(String[] args) { + int[] num1 = {1, 2, 3, 0, 0, 0}; + int[] num2 = {2, 5, 6}; + merge(num1, 0, num2, 1); + } +} diff --git a/0001-0500/0088-Merge-Sorted-Array/java-0088/src/Solution2.java b/0001-0500/0088-Merge-Sorted-Array/java-0088/src/Solution2.java new file mode 100644 index 00000000..edbd150d --- /dev/null +++ b/0001-0500/0088-Merge-Sorted-Array/java-0088/src/Solution2.java @@ -0,0 +1,37 @@ +/** + * @author: qiaoyi + * @edit: + * @created:2019/09/10 + * Time Complexity:O(n) + * Space Complexity:O(1) + */ +public class Solution2 { + + //do not use auxilliary array, tranverse num1 from back to front + public static void merge2(int[] nums1, int m, int[] nums2, int n) { + if (n <= 0) { + return; + } + int point1 = m - 1; + int point2 = n - 1; + for (int i = m + n - 1; i >= 0; i--) { + + if (point1 >= 0 && point2 >= 0 && nums1[point1] > nums2[point2]) { + nums1[i] = nums1[point1]; + point1--; + } else if (point2 >= 0) { + nums1[i] = nums2[point2]; + point2--; + } else { + nums1[i] = nums1[point1]; + point1--; + } + } + } + + public static void main(String[] args) { + int[] num1 = {1, 2, 3, 0, 0, 0}; + int[] num2 = {2, 5, 6}; + merge(num1, 0, num2, 1); + } +} diff --git a/0001-0500/0089-Gray-Code/cpp-0089/CMakeLists.txt b/0001-0500/0089-Gray-Code/cpp-0089/CMakeLists.txt new file mode 100644 index 00000000..2bdf3e7d --- /dev/null +++ b/0001-0500/0089-Gray-Code/cpp-0089/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(cpp_0089) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0089 main3.cpp) \ No newline at end of file diff --git a/0001-0500/0089-Gray-Code/cpp-0089/main.cpp b/0001-0500/0089-Gray-Code/cpp-0089/main.cpp new file mode 100644 index 00000000..8f03a3d7 --- /dev/null +++ b/0001-0500/0089-Gray-Code/cpp-0089/main.cpp @@ -0,0 +1,31 @@ +/// Source : https://leetcode.com/problems/gray-code/ +/// Author : liuyubobobo +/// Time : 2019-11-05 + +#include +#include + +using namespace std; + + +/// Recursion +/// Time Complexity: O(2^n) +/// Space Complexity: O(n) +class Solution { +public: + vector grayCode(int n) { + + if(n == 0) return {0}; + + vector res = grayCode(n - 1); + for(int i = res.size() - 1; i >= 0; i --) + res.push_back((1 << (n - 1)) + res[i]); + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0089-Gray-Code/cpp-0089/main2.cpp b/0001-0500/0089-Gray-Code/cpp-0089/main2.cpp new file mode 100644 index 00000000..91ef24b0 --- /dev/null +++ b/0001-0500/0089-Gray-Code/cpp-0089/main2.cpp @@ -0,0 +1,31 @@ +/// Source : https://leetcode.com/problems/gray-code/ +/// Author : liuyubobobo +/// Time : 2019-11-05 + +#include +#include + +using namespace std; + + +/// Recurrence +/// Time Complexity: O(2^n) +/// Space Complexity: O(1) +class Solution { +public: + vector grayCode(int n) { + + vector res = {0}; + for(int i = 0; i < n; i ++){ + for(int j = res.size() - 1; j >= 0; j --) + res.push_back((1 << i) + res[j]); + } + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0089-Gray-Code/cpp-0089/main3.cpp b/0001-0500/0089-Gray-Code/cpp-0089/main3.cpp new file mode 100644 index 00000000..77d08837 --- /dev/null +++ b/0001-0500/0089-Gray-Code/cpp-0089/main3.cpp @@ -0,0 +1,29 @@ +/// Source : https://leetcode.com/problems/gray-code/ +/// Author : liuyubobobo +/// Time : 2019-11-06 + +#include +#include + +using namespace std; + + +/// Gray Code Xor Formula +/// Time Complexity: O(2^n) +/// Space Complexity: O(1) +class Solution { +public: + vector grayCode(int n) { + + vector res; + for(int i = 0; i < (1 << n); i ++) + res.push_back(i ^ (i >> 1)); + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0090-Subsets-II/CMakeLists.txt b/0001-0500/0090-Subsets-II/CMakeLists.txt new file mode 100644 index 00000000..7bdd48b7 --- /dev/null +++ b/0001-0500/0090-Subsets-II/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(0090_Subsets_II) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(0090_Subsets_II main.cpp) \ No newline at end of file diff --git a/0001-0500/0090-Subsets-II/main.cpp b/0001-0500/0090-Subsets-II/main.cpp new file mode 100644 index 00000000..9699d2ca --- /dev/null +++ b/0001-0500/0090-Subsets-II/main.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/subsets-ii/ +/// Author : liuyubobobo +/// Time : 2021-03-21 + +#include +#include +#include + +using namespace std; + + +/// Soting and Using set +/// Time Complexity: O(n * 2^n) +/// Space Complexity: O(n) +class Solution { +public: + vector> subsetsWithDup(vector& nums) { + + sort(nums.begin(), nums.end()); + + int n = nums.size(); + set> s; + for(int state = 0; state < (1 << n); state ++){ + vector t; + for(int i = 0; i < n; i ++) + if(state & (1 << i)) t.push_back(nums[i]); + s.insert(t); + } + return vector>(s.begin(), s.end()); + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0091-Decode-Ways/cpp-0091/CMakeLists.txt b/0001-0500/0091-Decode-Ways/cpp-0091/CMakeLists.txt new file mode 100644 index 00000000..3d5069b2 --- /dev/null +++ b/0001-0500/0091-Decode-Ways/cpp-0091/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(cpp_0091) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0091 main2.cpp) \ No newline at end of file diff --git a/0001-0500/0091-Decode-Ways/cpp-0091/main.cpp b/0001-0500/0091-Decode-Ways/cpp-0091/main.cpp new file mode 100644 index 00000000..91f7db14 --- /dev/null +++ b/0001-0500/0091-Decode-Ways/cpp-0091/main.cpp @@ -0,0 +1,49 @@ +/// Source : https://leetcode.com/problems/decode-ways/ +/// Author : liuyubobobo +/// Time : 2019-09-03 + +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +private: + int n; + vector dp; + +public: + int numDecodings(string s) { + + n = s.size(); + dp.resize(n, -1); + return dfs(s, 0); + } + +private: + int dfs(const string& s, int start){ + + if(start >= s.size()) return 1; + if(s[start] == '0') return 0; + if(dp[start] != -1) return dp[start]; + + int res = dfs(s, start + 1); + if(start + 1 < n && s.substr(start, 2) <= "26") + res += dfs(s, start + 2); + return dp[start] = res; + } +}; + + +int main() { + + cout << Solution().numDecodings("12") << endl; + cout << Solution().numDecodings("226") << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0091-Decode-Ways/cpp-0091/main2.cpp b/0001-0500/0091-Decode-Ways/cpp-0091/main2.cpp new file mode 100644 index 00000000..8fc9dd57 --- /dev/null +++ b/0001-0500/0091-Decode-Ways/cpp-0091/main2.cpp @@ -0,0 +1,43 @@ +/// Source : https://leetcode.com/problems/decode-ways/ +/// Author : liuyubobobo +/// Time : 2019-09-03 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +public: + int numDecodings(string s) { + + int n = s.size(); + if(n == 1 || s[0] == '0') return s[0] != '0'; + + vector dp(n + 1, 0); + dp[n] = 1; + for(int i = n - 1; i >= 0; i --) + if(s[i] != '0'){ + dp[i] = dp[i + 1]; + if(i + 1 < n && s.substr(i, 2) <= "26") dp[i] += dp[i + 2]; + } + + return dp[0]; + } +}; + + +int main() { + + cout << Solution().numDecodings("12") << endl; // 2 + cout << Solution().numDecodings("226") << endl; // 3 + cout << Solution().numDecodings("101") << endl; // 1 + cout << Solution().numDecodings("301") << endl; // 0 + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0092-Reverse-Linked-List-II/cpp-0092/CMakeLists.txt b/0001-0500/0092-Reverse-Linked-List-II/cpp-0092/CMakeLists.txt new file mode 100644 index 00000000..b584d4c7 --- /dev/null +++ b/0001-0500/0092-Reverse-Linked-List-II/cpp-0092/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0092) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main2.cpp) +add_executable(cpp_0092 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0092-Reverse-Linked-List-II/cpp-0092/main.cpp b/0001-0500/0092-Reverse-Linked-List-II/cpp-0092/main.cpp new file mode 100644 index 00000000..fe499f7c --- /dev/null +++ b/0001-0500/0092-Reverse-Linked-List-II/cpp-0092/main.cpp @@ -0,0 +1,60 @@ +/// Source : https://leetcode.com/problems/reverse-linked-list-ii/description/ +/// Author : liuyubobobo +/// Time : 2018-10-02 + +#include + +using namespace std; + + +/// Recursive +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} +}; + +class Solution { +public: + ListNode* reverseBetween(ListNode* head, int m, int n) { + + ListNode* dummyHead = new ListNode(-1); + dummyHead->next = head; + + ListNode* pre = dummyHead; + for(int i = 0; i < m - 1; i ++, pre = pre->next); + + ListNode* tail = pre->next; + ListNode* left; + pre->next = reverse(pre->next, n - m, left); + tail->next = left; + + ListNode* ret = dummyHead->next; + delete dummyHead; + return ret; + } + +private: + ListNode* reverse(ListNode* head, int index, ListNode* &left){ + + if(index == 0){ + left = head->next; + return head; + } + + ListNode* tail = head->next; + ListNode* ret = reverse(head->next, index - 1, left); + tail->next = head; + return ret; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0092-Reverse-Linked-List-II/cpp-0092/main2.cpp b/0001-0500/0092-Reverse-Linked-List-II/cpp-0092/main2.cpp new file mode 100644 index 00000000..35096c5d --- /dev/null +++ b/0001-0500/0092-Reverse-Linked-List-II/cpp-0092/main2.cpp @@ -0,0 +1,63 @@ +/// Source : https://leetcode.com/problems/reverse-linked-list-ii/description/ +/// Author : liuyubobobo +/// Time : 2019-01-10 + +#include + +using namespace std; + + +/// Non-Recursive +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} +}; + +class Solution { +public: + ListNode* reverseBetween(ListNode* head, int m, int n) { + + ListNode* dummyHead = new ListNode(-1); + dummyHead->next = head; + + ListNode* pre = dummyHead; + for(int i = 0; i < m - 1; i ++, pre = pre->next); + + ListNode* tail = pre->next; + ListNode* left = tail; + pre->next = reverse(pre->next, n - m, left); + if(left != tail) tail->next = left; + + ListNode* ret = dummyHead->next; + delete dummyHead; + return ret; + } + +private: + ListNode* reverse(ListNode* head, int n, ListNode* &left){ + + if(!head || !head->next || !n) + return head; + + ListNode* pre = head, *cur = head->next; + while(n -- ){ + ListNode* next = cur->next; + cur->next = pre; + pre = cur; + cur = next; + }; + left = cur; + return pre; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0093-Restore-IP-Addresses/cpp-0093/CMakeLists.txt b/0001-0500/0093-Restore-IP-Addresses/cpp-0093/CMakeLists.txt new file mode 100644 index 00000000..a1ac2acd --- /dev/null +++ b/0001-0500/0093-Restore-IP-Addresses/cpp-0093/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(cpp_0093) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(cpp_0093 main.cpp) \ No newline at end of file diff --git a/0001-0500/0093-Restore-IP-Addresses/cpp-0093/main.cpp b/0001-0500/0093-Restore-IP-Addresses/cpp-0093/main.cpp new file mode 100644 index 00000000..80f8ae70 --- /dev/null +++ b/0001-0500/0093-Restore-IP-Addresses/cpp-0093/main.cpp @@ -0,0 +1,83 @@ +/// Source : https://leetcode.com/problems/restore-ip-addresses/ +/// Author : liuyubobobo +/// Time : 2019-01-18 + +#include +#include + +using namespace std; + + +/// Backtrack +/// Time Complexity: O(2^n) +/// Space Complexity: O(n) +class Solution { +public: + vector restoreIpAddresses(string s) { + + vector res; + vector ip; + dfs(s, 0, ip, res); + return res; + } + +private: + void dfs(const string& s, int index, vector& ip, vector& res){ + + if(index == s.size()){ + if(ip.size() == 4) + res.push_back(get_string(ip)); + return; + } + + if(index == 0){ + ip.push_back(s[0] - '0'); + dfs(s, index + 1, ip, res); + } + else{ + int next = ip.back() * 10 + (s[index] - '0'); + if(next <= 255 && ip.back() != 0){ + ip.back() = next; + dfs(s, index + 1, ip, res); + ip.back() /= 10; + } + if(ip.size() < 4){ + ip.push_back(s[index] - '0'); + dfs(s, index + 1, ip, res); + ip.pop_back(); + } + } + } + + string get_string(const vector& ip){ + string res = to_string(ip[0]); + for(int i = 1; i < ip.size(); i ++) + res += "." + to_string(ip[i]); + return res; + } +}; + + +void print_vec(const vector& vec){ + + for(const string& e: vec) + cout << e << " "; + cout << endl; +} + +int main() { + + string s1 = "25525511135"; + print_vec(Solution().restoreIpAddresses(s1)); + // 255.255.111.35 255.255.11.135 + + string s2 = "1"; + print_vec(Solution().restoreIpAddresses(s2)); + // empty + + string s3 = "010010"; + print_vec(Solution().restoreIpAddresses(s3)); + // 0.10.0.10 0.100.1.0 + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0094-Binary-Tree-Inorder-Traversal/cpp-0094/CMakeLists.txt b/0001-0500/0094-Binary-Tree-Inorder-Traversal/cpp-0094/CMakeLists.txt new file mode 100644 index 00000000..783977e9 --- /dev/null +++ b/0001-0500/0094-Binary-Tree-Inorder-Traversal/cpp-0094/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0094) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main3.cpp) +add_executable(cpp_0094 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0094-Binary-Tree-Inorder-Traversal/cpp-0094/main.cpp b/0001-0500/0094-Binary-Tree-Inorder-Traversal/cpp-0094/main.cpp new file mode 100644 index 00000000..0265badf --- /dev/null +++ b/0001-0500/0094-Binary-Tree-Inorder-Traversal/cpp-0094/main.cpp @@ -0,0 +1,45 @@ +/// Source : https://leetcode.com/problems/binary-tree-inorder-traversal/ +/// Author : liuyubobobo +/// Time : 2017-11-17 + +#include +#include + +using namespace std; + + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +// Recursive +// Time Complexity: O(n), n is the node number in the tree +// Space Complexity: O(h), h is the height of the tree +class Solution { +public: + vector inorderTraversal(TreeNode* root) { + + vector res; + __inorderTraversal(root, res); + return res; + } + +private: + void __inorderTraversal(TreeNode* node, vector &res){ + + if( node ){ + __inorderTraversal(node->left, res); + res.push_back( node->val ); + __inorderTraversal(node->right, res); + } + } +}; + +int main() { + + return 0; +} diff --git a/0001-0500/0094-Binary-Tree-Inorder-Traversal/cpp-0094/main2.cpp b/0001-0500/0094-Binary-Tree-Inorder-Traversal/cpp-0094/main2.cpp new file mode 100644 index 00000000..043483f2 --- /dev/null +++ b/0001-0500/0094-Binary-Tree-Inorder-Traversal/cpp-0094/main2.cpp @@ -0,0 +1,64 @@ +/// Source : https://leetcode.com/problems/binary-tree-inorder-traversal/ +/// Author : liuyubobobo +/// Time : 2017-11-17 + +#include +#include +#include + +using namespace std; + + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + + +// My Non-Recursive +// Time Complexity: O(n), n is the node number in the tree +// Space Complexity: O(h), h is the height of the tree +class Solution { + +private: + struct Command{ + string s; // go, print + TreeNode* node; + Command(string s, TreeNode* node): s(s), node(node){} + }; + +public: + vector inorderTraversal(TreeNode* root) { + + vector res; + if( root == NULL ) + return res; + + stack stack; + stack.push(Command("go", root)); + while( !stack.empty() ){ + Command command = stack.top(); + stack.pop(); + + if(command.s == "print") + res.push_back(command.node->val); + else{ + assert(command.s == "go"); + if(command.node->right) + stack.push(Command("go",command.node->right)); + stack.push(Command("print", command.node)); + if(command.node->left) + stack.push(Command("go",command.node->left)); + } + } + return res; + } +}; + +int main() { + + return 0; +} diff --git a/0001-0500/0094-Binary-Tree-Inorder-Traversal/cpp-0094/main3.cpp b/0001-0500/0094-Binary-Tree-Inorder-Traversal/cpp-0094/main3.cpp new file mode 100644 index 00000000..c10758e0 --- /dev/null +++ b/0001-0500/0094-Binary-Tree-Inorder-Traversal/cpp-0094/main3.cpp @@ -0,0 +1,55 @@ +/// Source : https://leetcode.com/problems/binary-tree-inorder-traversal/ +/// Author : liuyubobobo +/// Time : 2017-05-30 + +#include +#include +#include + +using namespace std; + + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + + +// Classic Non-Recursive algorithm for inorder traversal +// Time Complexity: O(n), n is the node number in the tree +// Space Complexity: O(h), h is the height of the tree +class Solution { + +public: + vector inorderTraversal(TreeNode* root) { + + vector res; + if( root == NULL ) + return res; + + stack stack; + TreeNode* cur = root; + while(cur != NULL || !stack.empty()){ + + while(cur != NULL){ + stack.push(cur); + cur = cur->left; + } + + cur = stack.top(); + stack.pop(); + res.push_back(cur->val); + cur = cur->right; + + } + return res; + } +}; + +int main() { + + return 0; +} diff --git a/0001-0500/0094-Binary-Tree-Inorder-Traversal/cpp-0094/main4.cpp b/0001-0500/0094-Binary-Tree-Inorder-Traversal/cpp-0094/main4.cpp new file mode 100644 index 00000000..2c950952 --- /dev/null +++ b/0001-0500/0094-Binary-Tree-Inorder-Traversal/cpp-0094/main4.cpp @@ -0,0 +1,55 @@ +/// Source : https://leetcode.com/problems/binary-tree-inorder-traversal/ +/// Author : liuyubobobo +/// Time : 2017-05-30 + +#include +#include +#include + +using namespace std; + + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + + +// Another Classic Non-Recursive algorithm for inorder traversal +// Time Complexity: O(n), n is the node number in the tree +// Space Complexity: O(h), h is the height of the tree +class Solution { + +public: + vector inorderTraversal(TreeNode* root) { + + vector res; + if( root == NULL ) + return res; + + stack stack; + TreeNode* cur = root; + while(cur != NULL || !stack.empty()){ + + if(cur != NULL){ + stack.push(cur); + cur = cur->left; + } + else { + cur = stack.top(); + stack.pop(); + res.push_back(cur->val); + cur = cur->right; + } + } + return res; + } +}; + +int main() { + + return 0; +} diff --git a/0001-0500/0094-Binary-Tree-Inorder-Traversal/cpp-0094/main5.cpp b/0001-0500/0094-Binary-Tree-Inorder-Traversal/cpp-0094/main5.cpp new file mode 100644 index 00000000..d5de25a4 --- /dev/null +++ b/0001-0500/0094-Binary-Tree-Inorder-Traversal/cpp-0094/main5.cpp @@ -0,0 +1,64 @@ +/// Source : https://leetcode.com/problems/binary-tree-inorder-traversal/ +/// Author : liuyubobobo +/// Time : 2018-05-30 + +#include +#include +#include + +using namespace std; + + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + + +// InOrder Morris Traversal +// Time Complexity: O(n), n is the node number in the tree +// Space Complexity: O(1) +class Solution { + +public: + vector inorderTraversal(TreeNode* root) { + + vector res; + if( root == NULL ) + return res; + + TreeNode* cur = root; + while(cur != NULL){ + + if(cur->left == NULL){ + res.push_back(cur->val); + cur = cur->right; + } + else{ + TreeNode* prev = cur->left; + while(prev->right != NULL && prev->right != cur) + prev = prev->right; + + if(prev->right == NULL){ + prev->right = cur; + cur = cur->left; + } + else{ + prev->right = NULL; + res.push_back(cur->val); + cur = cur->right; + } + } + } + + return res; + } +}; + +int main() { + + return 0; +} diff --git a/0001-0500/0094-Binary-Tree-Inorder-Traversal/java-0094/src/Solution1.java b/0001-0500/0094-Binary-Tree-Inorder-Traversal/java-0094/src/Solution1.java new file mode 100644 index 00000000..1cf54d2a --- /dev/null +++ b/0001-0500/0094-Binary-Tree-Inorder-Traversal/java-0094/src/Solution1.java @@ -0,0 +1,27 @@ +/// Source : https://leetcode.com/problems/binary-tree-inorder-traversal/ +/// Author : liuyubobobo +/// Time : 2017-11-17 + +import java.util.ArrayList; +import java.util.List; + +// Recursive +// Time Complexity: O(n), n is the node number in the tree +// Space Complexity: O(h), h is the height of the tree +public class Solution1 { + + public List inorderTraversal(TreeNode root) { + + ArrayList res = new ArrayList(); + inorderTraversal(root, res); + return res; + } + + private void inorderTraversal(TreeNode node, List list){ + if(node != null){ + inorderTraversal(node.left, list); + list.add(node.val); + inorderTraversal(node.right, list); + } + } +} diff --git a/0001-0500/0094-Binary-Tree-Inorder-Traversal/java-0094/src/Solution2.java b/0001-0500/0094-Binary-Tree-Inorder-Traversal/java-0094/src/Solution2.java new file mode 100644 index 00000000..c2f9507f --- /dev/null +++ b/0001-0500/0094-Binary-Tree-Inorder-Traversal/java-0094/src/Solution2.java @@ -0,0 +1,48 @@ +/// Source : https://leetcode.com/problems/binary-tree-inorder-traversal/ +/// Author : liuyubobobo +/// Time : 2017-11-17 + +import java.util.ArrayList; +import java.util.List; +import java.util.Stack; + +// My Non-Recursive +// Time Complexity: O(n), n is the node number in the tree +// Space Complexity: O(h), h is the height of the tree +public class Solution2 { + + private class Command{ + String s; // go, print + TreeNode node; + Command(String s, TreeNode node){ + this.s = s; + this.node = node; + } + }; + + public List inorderTraversal(TreeNode root) { + + ArrayList res = new ArrayList(); + if(root == null) + return res; + + Stack stack = new Stack(); + stack.push(new Command("go", root)); + while(!stack.empty()){ + Command command = stack.pop(); + + if(command.s.equals("print")) + res.add(command.node.val); + else{ + assert command.s.equals("go"); + if(command.node.right != null) + stack.push(new Command("go",command.node.right)); + stack.push(new Command("print", command.node)); + if(command.node.left != null) + stack.push(new Command("go",command.node.left)); + } + } + return res; + } + +} diff --git a/0001-0500/0094-Binary-Tree-Inorder-Traversal/java-0094/src/Solution3.java b/0001-0500/0094-Binary-Tree-Inorder-Traversal/java-0094/src/Solution3.java new file mode 100644 index 00000000..bce6a201 --- /dev/null +++ b/0001-0500/0094-Binary-Tree-Inorder-Traversal/java-0094/src/Solution3.java @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/binary-tree-inorder-traversal/ +/// Author : liuyubobobo +/// Time : 2018-05-30 + +import java.util.ArrayList; +import java.util.List; +import java.util.Stack; + +// Classic Non-Recursive algorithm for inorder traversal +// Time Complexity: O(n), n is the node number in the tree +// Space Complexity: O(h), h is the height of the tree +public class Solution3 { + + public List inorderTraversal(TreeNode root) { + + ArrayList res = new ArrayList(); + if(root == null) + return res; + + Stack stack = new Stack<>(); + TreeNode cur = root; + while(cur != null || !stack.empty()){ + + while(cur != null){ + stack.push(cur); + cur = cur.left; + } + + cur = stack.pop(); + res.add(cur.val); + cur = cur.right; + } + return res; + } +} diff --git a/0001-0500/0094-Binary-Tree-Inorder-Traversal/java-0094/src/Solution4.java b/0001-0500/0094-Binary-Tree-Inorder-Traversal/java-0094/src/Solution4.java new file mode 100644 index 00000000..1d76d12c --- /dev/null +++ b/0001-0500/0094-Binary-Tree-Inorder-Traversal/java-0094/src/Solution4.java @@ -0,0 +1,36 @@ +/// Source : https://leetcode.com/problems/binary-tree-inorder-traversal/ +/// Author : liuyubobobo +/// Time : 2018-05-30 + +import java.util.ArrayList; +import java.util.List; +import java.util.Stack; + +// Another Classic Non-Recursive algorithm for inorder traversal +// Time Complexity: O(n), n is the node number in the tree +// Space Complexity: O(h), h is the height of the tree +public class Solution4 { + + public List inorderTraversal(TreeNode root) { + + ArrayList res = new ArrayList(); + if(root == null) + return res; + + Stack stack = new Stack<>(); + TreeNode cur = root; + while(cur != null || !stack.empty()){ + + if(cur != null){ + stack.push(cur); + cur = cur.left; + } + else{ + cur = stack.pop(); + res.add(cur.val); + cur = cur.right; + } + } + return res; + } +} diff --git a/0001-0500/0094-Binary-Tree-Inorder-Traversal/java-0094/src/Solution5.java b/0001-0500/0094-Binary-Tree-Inorder-Traversal/java-0094/src/Solution5.java new file mode 100644 index 00000000..41ec5fae --- /dev/null +++ b/0001-0500/0094-Binary-Tree-Inorder-Traversal/java-0094/src/Solution5.java @@ -0,0 +1,45 @@ +/// Source : https://leetcode.com/problems/binary-tree-inorder-traversal/ +/// Author : liuyubobobo +/// Time : 2018-05-30 + +import java.util.ArrayList; +import java.util.List; +import java.util.Stack; + +// Inorder Morris Traversal +// Time Complexity: O(n), n is the node number in the tree +// Space Complexity: O(1) +public class Solution5 { + + public List inorderTraversal(TreeNode root) { + + ArrayList res = new ArrayList(); + if(root == null) + return res; + + TreeNode cur = root; + while(cur != null){ + + if(cur.left == null){ + res.add(cur.val); + cur = cur.right; + } + else{ + TreeNode prev = cur.left; + while(prev.right != null && prev.right != cur) + prev = prev.right; + + if(prev.right == null){ + prev.right = cur; + cur = cur.left; + } + else{ + prev.right = null; + res.add(cur.val); + cur = cur.right; + } + } + } + return res; + } +} diff --git a/0001-0500/0094-Binary-Tree-Inorder-Traversal/java-0094/src/TreeNode.java b/0001-0500/0094-Binary-Tree-Inorder-Traversal/java-0094/src/TreeNode.java new file mode 100644 index 00000000..f408f764 --- /dev/null +++ b/0001-0500/0094-Binary-Tree-Inorder-Traversal/java-0094/src/TreeNode.java @@ -0,0 +1,7 @@ +// Definition for a binary tree node. +public class TreeNode { + int val; + TreeNode left; + TreeNode right; + TreeNode(int x) { val = x; } +} \ No newline at end of file diff --git a/0001-0500/0095-Unique-Binary-Search-Trees-II/cpp-0095/CMakeLists.txt b/0001-0500/0095-Unique-Binary-Search-Trees-II/cpp-0095/CMakeLists.txt new file mode 100644 index 00000000..349f4e16 --- /dev/null +++ b/0001-0500/0095-Unique-Binary-Search-Trees-II/cpp-0095/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0095) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0095 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0095-Unique-Binary-Search-Trees-II/cpp-0095/main.cpp b/0001-0500/0095-Unique-Binary-Search-Trees-II/cpp-0095/main.cpp new file mode 100644 index 00000000..8faf9d64 --- /dev/null +++ b/0001-0500/0095-Unique-Binary-Search-Trees-II/cpp-0095/main.cpp @@ -0,0 +1,66 @@ +/// Source : https://leetcode.com/problems/unique-binary-search-trees-ii/description/ +/// Author : liuyubobobo +/// Time : 2018-09-10 + +#include +#include + +using namespace std; + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +/// Backtracking +/// Time Complexity: O(n^n) +/// Space Complexity: O(n^n) +class Solution { +public: + vector generateTrees(int n) { + + vector vals; + for(int i = 1; i <= n; i ++) + vals.push_back(i); + return generateTrees(vals); + } + +private: + vector generateTrees(const vector& vec){ + + if(vec.size() == 0) + return {}; + + if(vec.size() == 1) + return {new TreeNode(vec[0])}; + + vector ret; + for(int i = 0; i < vec.size(); i ++){ + vector left = generateTrees(vector(vec.begin(), vec.begin() + i)); + vector right = generateTrees(vector(vec.begin() + i + 1, vec.end())); + if(left.empty()) left.push_back(NULL); + if(right.empty()) right.push_back(NULL); + + for(TreeNode* ltree: left) + for(TreeNode* rtree: right){ + TreeNode* root = new TreeNode(vec[i]); + root->left = ltree; + root->right = rtree; + ret.push_back(root); + } + } + return ret; + } +}; + + +int main() { + + cout << Solution().generateTrees(0).size() << endl; + cout << Solution().generateTrees(3).size() << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0096-Unique-Binary-Search-Trees/cpp-0096/CMakeLists.txt b/0001-0500/0096-Unique-Binary-Search-Trees/cpp-0096/CMakeLists.txt new file mode 100644 index 00000000..fe81bbb0 --- /dev/null +++ b/0001-0500/0096-Unique-Binary-Search-Trees/cpp-0096/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0096) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main3.cpp) +add_executable(cpp_0096 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0096-Unique-Binary-Search-Trees/cpp-0096/main.cpp b/0001-0500/0096-Unique-Binary-Search-Trees/cpp-0096/main.cpp new file mode 100644 index 00000000..0311f80d --- /dev/null +++ b/0001-0500/0096-Unique-Binary-Search-Trees/cpp-0096/main.cpp @@ -0,0 +1,45 @@ +/// Source : https://leetcode.com/problems/unique-binary-search-trees/description/ +/// Author : liuyubobobo +/// Time : 2018-09-10 + +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +public: + int numTrees(int n) { + + vector dp(n + 1, -1); + return numTrees(n, dp); + } + +private: + int numTrees(int n, vector& dp){ + + if(n <= 1) + return 1; + + if(dp[n] != -1) + return dp[n]; + + int res = 0; + for(int i = 1; i <= n; i ++) + res += numTrees(i - 1, dp) * numTrees(n - i, dp); + return dp[n] = res; + } +}; + + +int main() { + + cout << Solution().numTrees(3) << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0096-Unique-Binary-Search-Trees/cpp-0096/main2.cpp b/0001-0500/0096-Unique-Binary-Search-Trees/cpp-0096/main2.cpp new file mode 100644 index 00000000..9ec27e3e --- /dev/null +++ b/0001-0500/0096-Unique-Binary-Search-Trees/cpp-0096/main2.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/unique-binary-search-trees/description/ +/// Author : liuyubobobo +/// Time : 2018-09-10 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +public: + int numTrees(int n) { + + vector dp(n + 1, 0); + dp[0] = dp[1] = 1; + for(int i = 2; i <= n; i ++) + for(int j = 1; j <= i; j ++) + dp[i] += dp[j - 1] * dp[i - j]; + return dp[n]; + } +}; + + +int main() { + + cout << Solution().numTrees(3) << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0096-Unique-Binary-Search-Trees/cpp-0096/main3.cpp b/0001-0500/0096-Unique-Binary-Search-Trees/cpp-0096/main3.cpp new file mode 100644 index 00000000..66326d84 --- /dev/null +++ b/0001-0500/0096-Unique-Binary-Search-Trees/cpp-0096/main3.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/unique-binary-search-trees/description/ +/// Author : liuyubobobo +/// Time : 2018-09-10 + +#include +#include + +using namespace std; + + +/// Mathematics +/// It's Catalan Number! +/// See more about Catalan number here: +/// https://en.wikipedia.org/wiki/Catalan_number +/// +/// Time Complexity: O(n) +/// Space Complexity: O(1) + +class Solution { + +public: + int numTrees(int n) { + + long long C = 1ll; + for(int i = 0; i < n; i ++) + C = C * 2 * (2 * i + 1) / (i + 2); + return C; + } +}; + + +int main() { + + cout << Solution().numTrees(3) << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0097-Interleaving-String/cpp-0097/CMakeLists.txt b/0001-0500/0097-Interleaving-String/cpp-0097/CMakeLists.txt new file mode 100644 index 00000000..74c97bb2 --- /dev/null +++ b/0001-0500/0097-Interleaving-String/cpp-0097/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_0097) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0097 main.cpp) \ No newline at end of file diff --git a/0001-0500/0097-Interleaving-String/cpp-0097/main.cpp b/0001-0500/0097-Interleaving-String/cpp-0097/main.cpp new file mode 100644 index 00000000..8ac9361b --- /dev/null +++ b/0001-0500/0097-Interleaving-String/cpp-0097/main.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/interleaving-string/ +/// Author : liuyubobobo +/// Time : 2021-06-03 + +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(|s1| * |s2|) +/// Space Complexity: O(|s1| * |s2|) +class Solution { +public: + bool isInterleave(string s1, string s2, string s3) { + + int n1 = s1.size(), n2 = s2.size(); + if(s3.size() != n1 + n2) return false; + + vector> dp(n1 + 1, vector(n2 + 1, -1)); + return dfs(s1, s2, s3, 0, 0, dp); + } + +private: + int dfs(const string& s1, const string& s2, const string& s3, int i, int j, + vector>& dp){ + + if(i == s1.size() && j == s2.size()) return 1; + if(dp[i][j] != -1) return dp[i][j]; + + if(i == s1.size()) + return dp[i][j] = (s2[j] == s3[i + j] ? dfs(s1, s2, s3, i, j + 1, dp) : 0); + + if(j == s2.size()) + return dp[i][j] = (s1[i] == s3[i + j] ? dfs(s1, s2, s3, i + 1, j, dp) : 0); + + if(s1[i] == s3[i + j] && dfs(s1, s2, s3, i + 1, j, dp) == 1) + return dp[i][j] = 1; + + if(s2[j] == s3[i + j] && dfs(s1, s2, s3, i, j + 1, dp) == 1) + return dp[i][j] = 1; + + return dp[i][j] = 0; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0098-Validate-Binary-Search-Tree/cpp-0098/CMakeLists.txt b/0001-0500/0098-Validate-Binary-Search-Tree/cpp-0098/CMakeLists.txt new file mode 100644 index 00000000..b35c9dbe --- /dev/null +++ b/0001-0500/0098-Validate-Binary-Search-Tree/cpp-0098/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0098) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main5.cpp) +add_executable(cpp_0098 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0098-Validate-Binary-Search-Tree/cpp-0098/main.cpp b/0001-0500/0098-Validate-Binary-Search-Tree/cpp-0098/main.cpp new file mode 100644 index 00000000..eae0a0a5 --- /dev/null +++ b/0001-0500/0098-Validate-Binary-Search-Tree/cpp-0098/main.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/validate-binary-search-tree/description/ +/// Author : liuyubobobo +/// Time : 2018-05-09 + +#include +#include + +using namespace std; + + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + + +/// Using inOrder traverse +/// Store all elements in an vector +/// +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + bool isValidBST(TreeNode* root) { + + vector vec; + inOrder(root, vec); + for(int i = 1 ; i < vec.size() ; i ++) + if(vec[i-1] >= vec[i]) + return false; + return true; + } + +private: + void inOrder(TreeNode* node, vector& vec){ + + if(node == NULL) + return; + + inOrder(node->left, vec); + vec.push_back(node->val); + inOrder(node->right, vec); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0098-Validate-Binary-Search-Tree/cpp-0098/main2.cpp b/0001-0500/0098-Validate-Binary-Search-Tree/cpp-0098/main2.cpp new file mode 100644 index 00000000..da64d5c5 --- /dev/null +++ b/0001-0500/0098-Validate-Binary-Search-Tree/cpp-0098/main2.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/validate-binary-search-tree/description/ +/// Author : liuyubobobo +/// Time : 2018-05-09 + +#include +#include + +using namespace std; + + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +/// Recursive test +/// Time Complexity: O(n) +/// Space Complexity: O(h) +class Solution { +public: + bool isValidBST(TreeNode* root) { + + return isValidBST(root, INT_MIN, INT_MAX); + } + +private: + bool isValidBST(TreeNode* node, int min, int max){ + + if(node == NULL) + return true; + + if(node->val < min || node->val > max) + return false; + + if(node->left != NULL && node->left->val >= node->val) + return false; + + if(node->right != NULL && node->right->val <= node->val) + return false; + + return isValidBST(node->left, min, node->val - 1) && isValidBST(node->right, node->val + 1, max); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0098-Validate-Binary-Search-Tree/cpp-0098/main3.cpp b/0001-0500/0098-Validate-Binary-Search-Tree/cpp-0098/main3.cpp new file mode 100644 index 00000000..70ee9ab0 --- /dev/null +++ b/0001-0500/0098-Validate-Binary-Search-Tree/cpp-0098/main3.cpp @@ -0,0 +1,71 @@ +/// Source : https://leetcode.com/problems/validate-binary-search-tree/description/ +/// Author : liuyubobobo +/// Time : 2018-12-16 + +#include +#include + +using namespace std; + + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + + +/// Non-Recursion Solution for Recursion thinking +/// Time Complexity: O(n) +/// Space Complexity: O(h) +class Solution { + +public: + bool isValidBST(TreeNode* root) { + + if(!root) return true; + + stack st; + stack upper, lower; + + st.push(root); + upper.push(INT_MAX); + lower.push(INT_MIN); + while(!st.empty()){ + TreeNode* cur = st.top(); + st.pop(); + + int left = lower.top(); + lower.pop(); + + int right = upper.top(); + upper.pop(); + + if(cur->val > right || cur->val < left) + return false; + + if(cur->right){ + if(cur->right->val <= cur->val) return false; + st.push(cur->right); + lower.push(cur->val + 1); + upper.push(right); + } + + if(cur->left){ + if(cur->left->val >= cur->val) return false; + st.push(cur->left); + lower.push(left); + upper.push(cur->val - 1); + } + } + return true; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0098-Validate-Binary-Search-Tree/cpp-0098/main4.cpp b/0001-0500/0098-Validate-Binary-Search-Tree/cpp-0098/main4.cpp new file mode 100644 index 00000000..e5b08478 --- /dev/null +++ b/0001-0500/0098-Validate-Binary-Search-Tree/cpp-0098/main4.cpp @@ -0,0 +1,63 @@ +/// Source : https://leetcode.com/problems/validate-binary-search-tree/description/ +/// Author : liuyubobobo +/// Time : 2018-05-22 + +#include + +using namespace std; + + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + + +/// InOrder traverse +/// validate during the traversing +/// +/// Time Complexity: O(n) +/// Space Complexity: O(h) +class Solution { + +private: + int pre = -1; + bool isPre = false; + +public: + bool isValidBST(TreeNode* root) { + + isPre = false; + pre = -1; + return inOrder(root); + } + +private: + bool inOrder(TreeNode* node){ + + if(node == NULL) + return true; + + if(!inOrder(node->left)) + return false; + + if(isPre && pre >= node->val) + return false; + isPre = true; + pre = node->val; + + if(!inOrder(node->right)) + return false; + + return true; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0098-Validate-Binary-Search-Tree/cpp-0098/main5.cpp b/0001-0500/0098-Validate-Binary-Search-Tree/cpp-0098/main5.cpp new file mode 100644 index 00000000..f14ddbd6 --- /dev/null +++ b/0001-0500/0098-Validate-Binary-Search-Tree/cpp-0098/main5.cpp @@ -0,0 +1,93 @@ +/// Source : https://leetcode.com/problems/validate-binary-search-tree/description/ +/// Author : liuyubobobo +/// Time : 2018-05-28 + +#include + +using namespace std; + + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + + +/// Morris InOrder traversal +/// Attention: you can not change the give Tree structure in Leetcode, +/// So try to return result early will lead to RE :-) +/// +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { + +private: + bool flag; + int pre; + +public: + bool isValidBST(TreeNode* root) { + + flag = false; + pre = -1; + TreeNode* cur = root; + + bool res = true; + while(cur != NULL){ + if(cur->left == NULL){ + if(!process(cur)) + res = false; + cur = cur->right; + } + else{ + TreeNode* prev = cur->left; + while(prev->right != NULL && prev->right != cur) + prev = prev->right; + + if(prev->right == NULL){ + prev->right = cur; + cur = cur->left; + } + else{ + prev->right = NULL; + if(!process(cur)) + res = false; + cur = cur->right; + } + } + } + + return res; + } + +private: + bool process(TreeNode* node){ + + if(flag && pre >= node->val) + return false; + flag = true; + pre = node->val; + return true; + } +}; + + +void print_bool(bool res){ + cout << (res ? "True" : "False") << endl; +} + +int main() { + + TreeNode* root = new TreeNode(5); + root->left = new TreeNode(1); + root->right = new TreeNode(4); + root->right->left = new TreeNode(3); + root->right->right = new TreeNode(6); + + print_bool(Solution().isValidBST(root)); + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0098-Validate-Binary-Search-Tree/java-0098/src/Solution.java b/0001-0500/0098-Validate-Binary-Search-Tree/java-0098/src/Solution.java new file mode 100644 index 00000000..ad2d5777 --- /dev/null +++ b/0001-0500/0098-Validate-Binary-Search-Tree/java-0098/src/Solution.java @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/validate-binary-search-tree/description/ +/// Author : liuyubobobo +/// Time : 2018-05-22 + +import java.util.ArrayList; + +/// Using inOrder traverse +/// Store all elements in an ArrayList +/// +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + + public boolean isValidBST(TreeNode root) { + + ArrayList list = new ArrayList<>(); + inOrder(root, list); + for(int i = 1 ; i < list.size() ; i ++) + if(list.get(i - 1) >= list.get(i)) + return false; + return true; + } + + private void inOrder(TreeNode node, ArrayList list){ + + if(node == null) + return; + + inOrder(node.left, list); + list.add(node.val); + inOrder(node.right, list); + } +} diff --git a/0001-0500/0098-Validate-Binary-Search-Tree/java-0098/src/Solution2.java b/0001-0500/0098-Validate-Binary-Search-Tree/java-0098/src/Solution2.java new file mode 100644 index 00000000..7779b8a3 --- /dev/null +++ b/0001-0500/0098-Validate-Binary-Search-Tree/java-0098/src/Solution2.java @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/validate-binary-search-tree/description/ +/// Author : liuyubobobo +/// Time : 2018-05-22 + +/// Recursive test +/// Time Complexity: O(n) +/// Space Complexity: O(h) +class Solution2 { + + public boolean isValidBST(TreeNode root) { + + return isValidBST(root, Integer.MIN_VALUE, Integer.MAX_VALUE); + } + + private boolean isValidBST(TreeNode node, int min, int max){ + + if(node == null) + return true; + + if(node.val < min || node.val > max) + return false; + + if(node.left != null && node.left.val >= node.val) + return false; + + if(node.right != null && node.right.val <= node.val) + return false; + + return isValidBST(node.left, min, node.val - 1) && + isValidBST(node.right, node.val + 1, max); + } + + public static void main(String[] args){ + + TreeNode root = new TreeNode(-2147483648); + root.left = new TreeNode(-2147483648); + + System.out.println((new Solution2()).isValidBST(root)); + } +} diff --git a/0001-0500/0098-Validate-Binary-Search-Tree/java-0098/src/Solution3.java b/0001-0500/0098-Validate-Binary-Search-Tree/java-0098/src/Solution3.java new file mode 100644 index 00000000..ff8e5ed0 --- /dev/null +++ b/0001-0500/0098-Validate-Binary-Search-Tree/java-0098/src/Solution3.java @@ -0,0 +1,49 @@ +/// Source : https://leetcode.com/problems/validate-binary-search-tree/description/ +/// Author : liuyubobobo +/// Time : 2018-12-16 + + +import java.util.Stack; + +/// Non-Recursion Solution for Recursion thinking +/// Time Complexity: O(n) +/// Space Complexity: O(h) +public class Solution3 { + + + public boolean isValidBST(TreeNode root) { + + if(root == null) return true; + + Stack stack = new Stack<>(); + Stack lower = new Stack<>(); + Stack upper = new Stack<>(); + + stack.push(root); + lower.push(Integer.MIN_VALUE); + upper.push(Integer.MAX_VALUE); + while(!stack.empty()){ + TreeNode cur = stack.pop(); + int left = lower.pop(); + int right = upper.pop(); + + if(cur.val < left || cur.val > right) + return false; + + if(cur.right != null){ + if(cur.right.val <= cur.val) return false; + stack.push(cur.right); + lower.push(cur.val + 1); + upper.push(right); + } + + if(cur.left != null){ + if(cur.left.val >= cur.val) return false; + stack.push(cur.left); + lower.push(left); + upper.push(cur.val - 1); + } + } + return true; + } +} diff --git a/0001-0500/0098-Validate-Binary-Search-Tree/java-0098/src/Solution4.java b/0001-0500/0098-Validate-Binary-Search-Tree/java-0098/src/Solution4.java new file mode 100644 index 00000000..35093111 --- /dev/null +++ b/0001-0500/0098-Validate-Binary-Search-Tree/java-0098/src/Solution4.java @@ -0,0 +1,36 @@ +/// Source : https://leetcode.com/problems/validate-binary-search-tree/description/ +/// Author : liuyubobobo +/// Time : 2018-05-22 + +/// InOrder traverse +/// validate during the traversing +/// +/// Time Complexity: O(n) +/// Space Complexity: O(h) +public class Solution4 { + + private Integer pre = null; + + public boolean isValidBST(TreeNode root) { + + return inOrder(root); + } + + private boolean inOrder(TreeNode node){ + + if(node == null) + return true; + + if(!inOrder(node.left)) + return false; + + if(pre != null && node.val <= pre) + return false; + pre = node.val; + + if(!inOrder(node.right)) + return false; + + return true; + } +} diff --git a/0001-0500/0098-Validate-Binary-Search-Tree/java-0098/src/Solution5.java b/0001-0500/0098-Validate-Binary-Search-Tree/java-0098/src/Solution5.java new file mode 100644 index 00000000..891fc392 --- /dev/null +++ b/0001-0500/0098-Validate-Binary-Search-Tree/java-0098/src/Solution5.java @@ -0,0 +1,58 @@ +/// Source : https://leetcode.com/problems/validate-binary-search-tree/description/ +/// Author : liuyubobobo +/// Time : 2018-12-16 + +/// Morris InOrder traversal +/// Attention: you can not change the give Tree structure in Leetcode, +/// So try to return result early will lead to RE :-) +/// +/// Time Complexity: O(n) +/// Space Complexity: O(1) +public class Solution5 { + + private boolean flag; + private int pre; + + public boolean isValidBST(TreeNode root) { + + flag = false; + pre = -1; + + TreeNode cur = root; + boolean res = true; + while(cur != null){ + + if(cur.left == null){ + if(!process(cur.val)) return false; + cur = cur.right; + } + else{ + TreeNode prev = cur.left; + while(prev.right != null && prev.right != cur) + prev = prev.right; + + if(prev.right == null){ + prev.right = cur; + cur = cur.left; + } + else{ + prev.right = null; + if(!process(cur.val)) + return false; + cur = cur.right; + } + } + } + return true; + } + + private boolean process(int v){ + + if(flag && pre >= v) + return false; + + flag = true; + pre = v; + return true; + } +} diff --git a/0001-0500/0098-Validate-Binary-Search-Tree/java-0098/src/TreeNode.java b/0001-0500/0098-Validate-Binary-Search-Tree/java-0098/src/TreeNode.java new file mode 100644 index 00000000..b7dbcf2e --- /dev/null +++ b/0001-0500/0098-Validate-Binary-Search-Tree/java-0098/src/TreeNode.java @@ -0,0 +1,7 @@ +/// Definition for a binary tree node. +public class TreeNode { + int val; + TreeNode left; + TreeNode right; + TreeNode(int x) { val = x; } +} diff --git a/0001-0500/0099-Recover-Binary-Search-Tree/java-0099/src/Solution.java b/0001-0500/0099-Recover-Binary-Search-Tree/java-0099/src/Solution.java new file mode 100644 index 00000000..6c14cbe6 --- /dev/null +++ b/0001-0500/0099-Recover-Binary-Search-Tree/java-0099/src/Solution.java @@ -0,0 +1,58 @@ +/// Source : https://leetcode.com/problems/validate-binary-search-tree/description/ +/// Author : liuyubobobo +/// Time : 2018-05-22 + +import java.util.ArrayList; + +/// Using inOrder traverse +/// Store all Nodes in an ArrayList and find the mistaked swapped nodes +/// +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + + public void recoverTree(TreeNode root) { + + ArrayList list = new ArrayList<>(); + inOrder(root, list); + + TreeNode a = null; + TreeNode b = null; + for(int i = 1 ; i < list.size() ; i ++) { + if (list.get(i - 1).val > list.get(i).val) { + if (a == null){ + a = list.get(i - 1); + b = list.get(i); + } + else { + b = list.get(i); + break; + } + } + } + + int t = a.val; + a.val = b.val; + b.val = t; + } + + private void inOrder(TreeNode node, ArrayList list){ + + if(node == null) + return; + + inOrder(node.left, list); + list.add(node); + inOrder(node.right, list); + } + + public static void main(String[] args){ + + TreeNode root = new TreeNode(3); + root.left = new TreeNode(1); + root.right = new TreeNode(4); + root.right.left = new TreeNode(2); + + (new Solution()).recoverTree(root); + } +} \ No newline at end of file diff --git a/0001-0500/0099-Recover-Binary-Search-Tree/java-0099/src/Solution2.java b/0001-0500/0099-Recover-Binary-Search-Tree/java-0099/src/Solution2.java new file mode 100644 index 00000000..d2bd8917 --- /dev/null +++ b/0001-0500/0099-Recover-Binary-Search-Tree/java-0099/src/Solution2.java @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/validate-binary-search-tree/description/ +/// Author : liuyubobobo +/// Time : 2018-05-22 + +/// Using inOrder traverse +/// Find the mistaked swapped nodes during the traversing +/// +/// Time Complexity: O(n) +/// Space Complexity: O(h) +class Solution2 { + + private TreeNode pre; + private TreeNode a, b; + + public void recoverTree(TreeNode root) { + + pre = null; + a = null; + b = null; + inOrder(root); + + int t = a.val; + a.val = b.val; + b.val = t; + } + + private void inOrder(TreeNode node){ + + if(node == null) + return; + + inOrder(node.left); + + if(pre != null && pre.val > node.val){ + if (a == null){ + a = pre; + b = node; + } + else + b = node; + } + pre = node; + + inOrder(node.right); + } +} \ No newline at end of file diff --git a/0001-0500/0099-Recover-Binary-Search-Tree/java-0099/src/Solution3.java b/0001-0500/0099-Recover-Binary-Search-Tree/java-0099/src/Solution3.java new file mode 100644 index 00000000..70d193c9 --- /dev/null +++ b/0001-0500/0099-Recover-Binary-Search-Tree/java-0099/src/Solution3.java @@ -0,0 +1,58 @@ +/// Source : https://leetcode.com/problems/validate-binary-search-tree/description/ +/// Author : liuyubobobo +/// Time : 2018-05-29 + +/// Using Morris inOrder traversal +/// Find the mistaked swapped nodes during the traversing +/// +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution3 { + + private TreeNode pre; + private TreeNode a, b; + + public void recoverTree(TreeNode root) { + + TreeNode cur = root; + while(cur != null){ + if(cur.left == null){ + process(cur); + cur = cur.right; + } + else{ + TreeNode prev = cur.left; + while(prev.right != null && prev.right != cur) + prev = prev.right; + + if(prev.right == null){ + prev.right = cur; + cur = cur.left; + } + else{ + prev.right = null; + process(cur); + cur = cur.right; + } + } + } + + int t = a.val; + a.val = b.val; + b.val = t; + } + + private void process(TreeNode node){ + + if(pre != null && pre.val > node.val){ + if(a == null){ + a = pre; + b = node; + } + else + b = node; + } + + pre = node; + } +} \ No newline at end of file diff --git a/0001-0500/0099-Recover-Binary-Search-Tree/java-0099/src/TreeNode.java b/0001-0500/0099-Recover-Binary-Search-Tree/java-0099/src/TreeNode.java new file mode 100644 index 00000000..c500bfff --- /dev/null +++ b/0001-0500/0099-Recover-Binary-Search-Tree/java-0099/src/TreeNode.java @@ -0,0 +1,8 @@ +/// Definition for a binary tree node. +public class TreeNode { + int val; + TreeNode left; + TreeNode right; + TreeNode(int x) { val = x; } +} + diff --git a/0001-0500/0100-Same-Tree/cpp-0100/CMakeLists.txt b/0001-0500/0100-Same-Tree/cpp-0100/CMakeLists.txt new file mode 100644 index 00000000..76fd5d63 --- /dev/null +++ b/0001-0500/0100-Same-Tree/cpp-0100/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0100) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main3.cpp) +add_executable(cpp_0100 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0100-Same-Tree/cpp-0100/main.cpp b/0001-0500/0100-Same-Tree/cpp-0100/main.cpp new file mode 100644 index 00000000..95306e78 --- /dev/null +++ b/0001-0500/0100-Same-Tree/cpp-0100/main.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/same-tree/description/ +/// Author : liuyubobobo +/// Time : 2018-10-16 + +#include + +using namespace std; + + +/// Using a string to represent a Binary Tree in preorder +/// Time Complexity: O(n) +/// Space Complexity: O(h) + +/// 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: + bool isSameTree(TreeNode* p, TreeNode* q) { + + string ps = "#"; + getTreeString(p, ps); + + string qs = "#"; + getTreeString(q, qs); + + return ps == qs; + } + +private: + void getTreeString(TreeNode* node, string& s){ + + if(!node){ + s += "NULL#"; + return; + } + + s += to_string(node->val) + "#"; + getTreeString(node->left, s); + getTreeString(node->right, s); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0100-Same-Tree/cpp-0100/main2.cpp b/0001-0500/0100-Same-Tree/cpp-0100/main2.cpp new file mode 100644 index 00000000..90405850 --- /dev/null +++ b/0001-0500/0100-Same-Tree/cpp-0100/main2.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/same-tree/description/ +/// Author : liuyubobobo +/// Time : 2018-10-16 + +#include + +using namespace std; + + +/// Recursion +/// Time Complexity: O(n) +/// Space Complexity: O(h) + +/// 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: + bool isSameTree(TreeNode* p, TreeNode* q) { + + if(!p && !q) return true; + if(!p || !q) return false; + if(p->val != q->val) return false; + return isSameTree(p->left, q->left) && isSameTree(p->right, q->right); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0100-Same-Tree/cpp-0100/main3.cpp b/0001-0500/0100-Same-Tree/cpp-0100/main3.cpp new file mode 100644 index 00000000..34ed9b52 --- /dev/null +++ b/0001-0500/0100-Same-Tree/cpp-0100/main3.cpp @@ -0,0 +1,55 @@ +/// Source : https://leetcode.com/problems/same-tree/description/ +/// Author : liuyubobobo +/// Time : 2019-03-11 + +#include +#include + +using namespace std; + + +/// Iterative +/// Time Complexity: O(n) +/// Space Complexity: O(h) + +/// 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: + bool isSameTree(TreeNode* p, TreeNode* q) { + + stack stack1, stack2; + stack1.push(p), stack2.push(q); + while(!stack1.empty() || !stack2.empty()){ + TreeNode* cur1 = stack1.top(); + stack1.pop(); + + TreeNode* cur2 = stack2.top(); + stack2.pop(); + + if(cur1 && !cur2) return false; + if(!cur1 && cur2) return false; + if(!cur1 && !cur2) continue; + + if(cur1->val != cur2->val) return false; + stack1.push(cur1->right); + stack1.push(cur1->left); + stack2.push(cur2->right); + stack2.push(cur2->left); + } + + return stack1.empty() && stack2.empty(); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0101-Symmetric-Tree/cpp-0101/CMakeLists.txt b/0001-0500/0101-Symmetric-Tree/cpp-0101/CMakeLists.txt new file mode 100644 index 00000000..4fb18793 --- /dev/null +++ b/0001-0500/0101-Symmetric-Tree/cpp-0101/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0101) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0101 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0101-Symmetric-Tree/cpp-0101/main.cpp b/0001-0500/0101-Symmetric-Tree/cpp-0101/main.cpp new file mode 100644 index 00000000..1da4c446 --- /dev/null +++ b/0001-0500/0101-Symmetric-Tree/cpp-0101/main.cpp @@ -0,0 +1,67 @@ +/// Source : https://leetcode.com/problems/symmetric-tree/description/ +/// Author : liuyubobobo +/// Time : 2018-06-02 + +#include + +using namespace std; + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +/// Recursive +/// Revert one child tree and see if the two child trees of the root are identical +/// +/// Time Complexity: O(n) +/// Space Complexity: O(h) +class Solution { +public: + bool isSymmetric(TreeNode* root) { + + if(root == NULL) + return true; + + TreeNode* left = root->left; + TreeNode* right = root->right; + right = revert(right); + + return is_identical(left, right); + } + +private: + TreeNode* revert(TreeNode* root){ + if(root == NULL) + return NULL; + + swap(root->left, root->right); + revert(root->left); + revert(root->right); + return root; + } + + bool is_identical(TreeNode* root1, TreeNode* root2){ + + if(root1 == NULL && root2 == NULL) + return true; + + if(root1 == NULL || root2 == NULL) + return false; + + if(root1->val != root2->val) + return false; + + return is_identical(root1->left, root2->left) && + is_identical(root1->right, root2->right); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0101-Symmetric-Tree/cpp-0101/main2.cpp b/0001-0500/0101-Symmetric-Tree/cpp-0101/main2.cpp new file mode 100644 index 00000000..6ffa603b --- /dev/null +++ b/0001-0500/0101-Symmetric-Tree/cpp-0101/main2.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/symmetric-tree/description/ +/// Author : liuyubobobo +/// Time : 2018-06-02 + +#include + +using namespace std; + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +/// Recursive +/// No need to revert one child tree +/// See if the two child trees of the root are mirror directly +/// +/// Time Complexity: O(n) +/// Space Complexity: O(h) +class Solution { +public: + bool isSymmetric(TreeNode* root) { + + if(root == NULL) + return true; + + return is_mirror(root, root); + } + +private: + bool is_mirror(TreeNode* root1, TreeNode* root2){ + + if(root1 == NULL && root2 == NULL) + return true; + + if(root1 == NULL || root2 == NULL) + return false; + + if(root1->val != root2->val) + return false; + + return is_mirror(root1->left, root2->right) && + is_mirror(root1->right, root2->left); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0101-Symmetric-Tree/cpp-0101/main3.cpp b/0001-0500/0101-Symmetric-Tree/cpp-0101/main3.cpp new file mode 100644 index 00000000..a6de98a0 --- /dev/null +++ b/0001-0500/0101-Symmetric-Tree/cpp-0101/main3.cpp @@ -0,0 +1,64 @@ +/// Source : https://leetcode.com/problems/symmetric-tree/description/ +/// Author : liuyubobobo +/// Time : 2018-06-02 + +#include +#include + +using namespace std; + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +/// Non-Recursive +/// Using two queues to level traverse the root in different directions +/// +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + bool isSymmetric(TreeNode* root) { + + if(root == NULL) + return true; + + queue q1, q2; + q1.push(root); + q2.push(root); + while(!q1.empty() && !q2.empty()){ + TreeNode* node1 = q1.front(); + q1.pop(); + + TreeNode* node2 = q2.front(); + q2.pop(); + + if(node1 == NULL && node2 == NULL) + continue; + + if(node1 == NULL || node2 == NULL) + return false; + + if(node1->val != node2->val) + return false; + + q1.push(node1->left); + q1.push(node1->right); + + q2.push(node2->right); + q2.push(node2->left); + } + + return q1.empty() && q2.empty(); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0101-Symmetric-Tree/cpp-0101/main4.cpp b/0001-0500/0101-Symmetric-Tree/cpp-0101/main4.cpp new file mode 100644 index 00000000..92f563f9 --- /dev/null +++ b/0001-0500/0101-Symmetric-Tree/cpp-0101/main4.cpp @@ -0,0 +1,63 @@ +/// Source : https://leetcode.com/problems/symmetric-tree/description/ +/// Author : liuyubobobo +/// Time : 2018-06-02 + +#include +#include + +using namespace std; + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +/// Non-Recursive +/// Using one queues to level traverse the root in different directions +/// +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + bool isSymmetric(TreeNode* root) { + + if(root == NULL) + return true; + + queue q; + q.push(root); + q.push(root); + while(!q.empty()){ + TreeNode* node1 = q.front(); + q.pop(); + + TreeNode* node2 = q.front(); + q.pop(); + + if(node1 == NULL && node2 == NULL) + continue; + + if(node1 == NULL || node2 == NULL) + return false; + + if(node1->val != node2->val) + return false; + + q.push(node1->left); + q.push(node2->right); + q.push(node1->right); + q.push(node2->left); + } + + return true; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0101-Symmetric-Tree/py-0101/Solution1.py b/0001-0500/0101-Symmetric-Tree/py-0101/Solution1.py new file mode 100644 index 00000000..33c8c0d6 --- /dev/null +++ b/0001-0500/0101-Symmetric-Tree/py-0101/Solution1.py @@ -0,0 +1,35 @@ +# Source : https://leetcode.com/problems/symmetric-tree/ +# Author : penpenps +# Time : 2019-07-09 + +# Revert right node firstly, then compare with left node +# Time Complexity: O(n) +# Space Complexity: O(n) + +# Definition for a binary tree node. +class TreeNode: + def __init__(self, x): + self.val = x + self.left = None + self.right = None + +class Solution: + def isSymmetric(self, root: TreeNode) -> bool: + # Revert TreeNode + def revert(node): + if not node: return + node.left, node.right = node.right, node.left + revert(node.left) + revert(node.right) + + def isEqual(left, right): + if not left and not right: return True + if not left or not right: return False + if left.val != right.val: + return False + return isEqual(left.left, right.left) and isEqual(left.right, right.right) + + if not root: + return True + revert(root.right) + return isEqual(root.left, root.right) diff --git a/0001-0500/0101-Symmetric-Tree/py-0101/Solution2.py b/0001-0500/0101-Symmetric-Tree/py-0101/Solution2.py new file mode 100644 index 00000000..82382c8c --- /dev/null +++ b/0001-0500/0101-Symmetric-Tree/py-0101/Solution2.py @@ -0,0 +1,32 @@ +# Source : https://leetcode.com/problems/symmetric-tree/ +# Author : penpenps +# Time : 2019-07-09 + +# Recursively check whether the child node is symmetric or not +# Time Complexity: O(n) +# Space Complexity: O(n) + +# Definition for a binary tree node. +class TreeNode: + def __init__(self, x): + self.val = x + self.left = None + self.right = None + +class Solution: + def isSymmetric(self, root: TreeNode) -> bool: + # Check whether left and right child are symmetic + def symmetricEqual(left, right): + # left and right child are both None, return True + if not left and not right: return True + # one of left and right is None, return False + if not left or not right: return False + # the value of left and right are not equal, return False + if left.val != right.val: + return False + return symmetricEqual(left.left, right.right) and symmetricEqual(left.right, right.left) + + if not root: + return True + + return symmetricEqual(root.left, root.right) \ No newline at end of file diff --git a/0001-0500/0101-Symmetric-Tree/py-0101/Solution3.py b/0001-0500/0101-Symmetric-Tree/py-0101/Solution3.py new file mode 100644 index 00000000..f54233e1 --- /dev/null +++ b/0001-0500/0101-Symmetric-Tree/py-0101/Solution3.py @@ -0,0 +1,33 @@ +# Source : https://leetcode.com/problems/symmetric-tree/ +# Author : penpenps +# Time : 2019-07-09 + +# Level traversal using two queues to keep left and right sub-tree +# Time Complexity: O(n) +# Space Complexity: O(n) + +# Definition for a binary tree node. +class TreeNode: + def __init__(self, x): + self.val = x + self.left = None + self.right = None + +class Solution: + def isSymmetric(self, root: TreeNode) -> bool: + if not root: + return True + q1, q2 = [root], [root] + while q1 and q2: + n1, n2 = q1.pop(), q2.pop() + if not n1 and not n2: + continue + if not n1 or not n2: + return False + if n1.val != n2.val: + return False + q1.append(n1.left) + q1.append(n1.right) + q2.append(n2.right) + q2.append(n2.left) + return not q1 and not q2 \ No newline at end of file diff --git a/0001-0500/0101-Symmetric-Tree/py-0101/Solution4.py b/0001-0500/0101-Symmetric-Tree/py-0101/Solution4.py new file mode 100644 index 00000000..abbb862a --- /dev/null +++ b/0001-0500/0101-Symmetric-Tree/py-0101/Solution4.py @@ -0,0 +1,33 @@ +# Source : https://leetcode.com/problems/symmetric-tree/ +# Author : penpenps +# Time : 2019-07-09 + +# Use single queue to store left and right subtree elements in different directions +# Time Complexity: O(n) +# Space Complexity: O(n) + +# Definition for a binary tree node. +class TreeNode: + def __init__(self, x): + self.val = x + self.left = None + self.right = None + +class Solution: + def isSymmetric(self, root: TreeNode) -> bool: + if not root: + return True + q = [root, root] + while q: + n1, n2 = q.pop(), q.pop() + if not n1 and not n2: + continue + if not n1 or not n2: + return False + if n1.val != n2.val: + return False + q.append(n1.left) + q.append(n2.right) + q.append(n1.right) + q.append(n2.left) + return True \ No newline at end of file diff --git a/0001-0500/0102-Binary-Tree-Level-Order-Traversal/cpp-0102/CMakeLists.txt b/0001-0500/0102-Binary-Tree-Level-Order-Traversal/cpp-0102/CMakeLists.txt new file mode 100644 index 00000000..f6643a5f --- /dev/null +++ b/0001-0500/0102-Binary-Tree-Level-Order-Traversal/cpp-0102/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0102) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main2.cpp) +add_executable(cpp_0102 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0102-Binary-Tree-Level-Order-Traversal/cpp-0102/main.cpp b/0001-0500/0102-Binary-Tree-Level-Order-Traversal/cpp-0102/main.cpp new file mode 100644 index 00000000..12313dd9 --- /dev/null +++ b/0001-0500/0102-Binary-Tree-Level-Order-Traversal/cpp-0102/main.cpp @@ -0,0 +1,59 @@ +/// Source : https://leetcode.com/problems/binary-tree-level-order-traversal/description/ +/// Author : liuyubobobo +/// Time : 2017-11-17 + +#include +#include +#include +#include + +using namespace std; + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +/// BFS +/// Time Complexity: O(n), where n is the number of nodes in the tree +/// Space Complexity: O(n) +class Solution { +public: + vector> levelOrder(TreeNode* root) { + + vector> res; + if(root == NULL) + return res; + + queue> q; + q.push(make_pair(root, 0)); + + while(!q.empty()){ + + TreeNode* node = q.front().first; + int level = q.front().second; + q.pop(); + + if(level == res.size()) + res.push_back(vector()); + assert( level < res.size() ); + + res[level].push_back(node->val); + if(node->left) + q.push(make_pair(node->left, level + 1 )); + if(node->right) + q.push(make_pair(node->right, level + 1 )); + } + + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0102-Binary-Tree-Level-Order-Traversal/cpp-0102/main2.cpp b/0001-0500/0102-Binary-Tree-Level-Order-Traversal/cpp-0102/main2.cpp new file mode 100644 index 00000000..b1494a4f --- /dev/null +++ b/0001-0500/0102-Binary-Tree-Level-Order-Traversal/cpp-0102/main2.cpp @@ -0,0 +1,68 @@ +/// Source : https://leetcode.com/problems/binary-tree-level-order-traversal/description/ +/// Author : liuyubobobo +/// Time : 2018-10-16 + +#include +#include +#include +#include + +using namespace std; + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +/// BFS +/// No need to store level information in the queue :-) +/// +/// Time Complexity: O(n), where n is the number of nodes in the tree +/// Space Complexity: O(n) +class Solution { +public: + vector> levelOrder(TreeNode* root) { + + vector> res; + if(root == NULL) + return res; + + queue q; + q.push(root); + int level_num = 1; + + while(!q.empty()){ + + int new_level_num = 0; + vector level; + for(int i = 0; i < level_num; i ++){ + TreeNode* node = q.front(); + q.pop(); + level.push_back(node->val); + + if(node->left){ + q.push(node->left); + new_level_num ++; + } + if(node->right){ + q.push(node->right); + new_level_num ++; + } + } + + res.push_back(level); + level_num = new_level_num; + } + + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0102-Binary-Tree-Level-Order-Traversal/java-0102/src/Solution.java b/0001-0500/0102-Binary-Tree-Level-Order-Traversal/java-0102/src/Solution.java new file mode 100644 index 00000000..d654fd95 --- /dev/null +++ b/0001-0500/0102-Binary-Tree-Level-Order-Traversal/java-0102/src/Solution.java @@ -0,0 +1,43 @@ +/// Source : https://leetcode.com/problems/binary-tree-level-order-traversal/description/ +/// Author : liuyubobobo +/// Time : 2017-11-17 + +import java.util.ArrayList; +import java.util.List; +import java.util.LinkedList; +import javafx.util.Pair; + +/// BFS +/// Time Complexity: O(n), where n is the number of nodes in the tree +/// Space Complexity: O(n) +class Solution { + + public List> levelOrder(TreeNode root) { + + ArrayList> res = new ArrayList<>(); + if(root == null) + return res; + + LinkedList> queue = new LinkedList<>(); + queue.addLast(new Pair<>(root, 0)); + + while(!queue.isEmpty()){ + + Pair front = queue.removeFirst(); + TreeNode node = front.getKey(); + int level = front.getValue(); + + if(level == res.size()) + res.add(new ArrayList<>()); + assert level < res.size(); + + res.get(level).add(node.val); + if(node.left != null) + queue.addLast(new Pair<>(node.left, level + 1)); + if(node.right != null) + queue.addLast(new Pair<>(node.right, level + 1)); + } + + return res; + } +} diff --git a/0001-0500/0102-Binary-Tree-Level-Order-Traversal/java-0102/src/Solution2.java b/0001-0500/0102-Binary-Tree-Level-Order-Traversal/java-0102/src/Solution2.java new file mode 100644 index 00000000..269d9366 --- /dev/null +++ b/0001-0500/0102-Binary-Tree-Level-Order-Traversal/java-0102/src/Solution2.java @@ -0,0 +1,51 @@ +/// Source : https://leetcode.com/problems/binary-tree-level-order-traversal/description/ +/// Author : liuyubobobo +/// Time : 2018-10-16 + +import java.util.ArrayList; +import java.util.List; +import java.util.LinkedList; +import java.util.Queue; + +/// BFS +/// No need to store level information in the queue :-) +/// +/// Time Complexity: O(n), where n is the number of nodes in the tree +/// Space Complexity: O(n) +class Solution2 { + + public List> levelOrder(TreeNode root) { + + ArrayList> res = new ArrayList<>(); + if(root == null) + return res; + + Queue queue = new LinkedList<>(); + queue.add(root); + int levelNum = 1; + + while(!queue.isEmpty()){ + + int newLevelNum = 0; + ArrayList level = new ArrayList<>(); + for(int i = 0; i < levelNum; i ++){ + TreeNode node = queue.remove(); + level.add(node.val); + + if(node.left != null){ + queue.add(node.left); + newLevelNum ++; + } + if(node.right != null){ + queue.add(node.right); + newLevelNum ++; + } + } + + res.add(level); + levelNum = newLevelNum; + } + + return res; + } +} diff --git a/0001-0500/0102-Binary-Tree-Level-Order-Traversal/java-0102/src/TreeNode.java b/0001-0500/0102-Binary-Tree-Level-Order-Traversal/java-0102/src/TreeNode.java new file mode 100644 index 00000000..f408f764 --- /dev/null +++ b/0001-0500/0102-Binary-Tree-Level-Order-Traversal/java-0102/src/TreeNode.java @@ -0,0 +1,7 @@ +// Definition for a binary tree node. +public class TreeNode { + int val; + TreeNode left; + TreeNode right; + TreeNode(int x) { val = x; } +} \ No newline at end of file diff --git a/0001-0500/0103-Binary-Tree-Zigzag-Level-Order-Traversal/cpp-0103/CMakeLists.txt b/0001-0500/0103-Binary-Tree-Zigzag-Level-Order-Traversal/cpp-0103/CMakeLists.txt new file mode 100644 index 00000000..5007c0dd --- /dev/null +++ b/0001-0500/0103-Binary-Tree-Zigzag-Level-Order-Traversal/cpp-0103/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(cpp_0103) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0103 main2.cpp) \ No newline at end of file diff --git a/0001-0500/0103-Binary-Tree-Zigzag-Level-Order-Traversal/cpp-0103/main.cpp b/0001-0500/0103-Binary-Tree-Zigzag-Level-Order-Traversal/cpp-0103/main.cpp new file mode 100644 index 00000000..ac8a1c21 --- /dev/null +++ b/0001-0500/0103-Binary-Tree-Zigzag-Level-Order-Traversal/cpp-0103/main.cpp @@ -0,0 +1,59 @@ +/// Source : https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/ +/// Author : liuyubobobo +/// Time : 2019-09-26 + +#include +#include + +using namespace std; + + +/// BFS +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// 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: + vector> zigzagLevelOrder(TreeNode* root) { + + vector> res; + if(!root) return res; + + vector cur; + cur.push_back(root); + int index = 0; + while(cur.size()){ + + vector next; + vector tres; + + for(TreeNode* node: cur){ + tres.push_back(node->val); + if(node->left) next.push_back(node->left); + if(node->right) next.push_back(node->right); + } + + if(index % 2) reverse(tres.begin(), tres.end()); + res.push_back(tres); + + cur = next; + index ++; + } + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0103-Binary-Tree-Zigzag-Level-Order-Traversal/cpp-0103/main2.cpp b/0001-0500/0103-Binary-Tree-Zigzag-Level-Order-Traversal/cpp-0103/main2.cpp new file mode 100644 index 00000000..3aa0d6ab --- /dev/null +++ b/0001-0500/0103-Binary-Tree-Zigzag-Level-Order-Traversal/cpp-0103/main2.cpp @@ -0,0 +1,56 @@ +/// Source : https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/ +/// Author : liuyubobobo +/// Time : 2019-09-26 + +#include +#include +#include + +using namespace std; + + +/// BFS +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// 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: + vector> zigzagLevelOrder(TreeNode* root) { + + vector> res; + if(!root) return res; + + queue> q; + q.push(make_pair(root, 0)); + while(!q.empty()){ + + TreeNode* node = q.front().first; + int level = q.front().second; + if(level >= res.size()) res.push_back({}); + res[level].push_back(node->val); + q.pop(); + + if(node->left) q.push(make_pair(node->left, level + 1)); + if(node->right) q.push(make_pair(node->right, level + 1)); + } + + for(int i = 1; i < res.size(); i += 2) + reverse(res[i].begin(), res[i].end()); + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0104-Maximum-Depth-of-Binary-Tree/cpp-0104/CMakeLists.txt b/0001-0500/0104-Maximum-Depth-of-Binary-Tree/cpp-0104/CMakeLists.txt similarity index 100% rename from 0104-Maximum-Depth-of-Binary-Tree/cpp-0104/CMakeLists.txt rename to 0001-0500/0104-Maximum-Depth-of-Binary-Tree/cpp-0104/CMakeLists.txt diff --git a/0104-Maximum-Depth-of-Binary-Tree/cpp-0104/main.cpp b/0001-0500/0104-Maximum-Depth-of-Binary-Tree/cpp-0104/main.cpp similarity index 100% rename from 0104-Maximum-Depth-of-Binary-Tree/cpp-0104/main.cpp rename to 0001-0500/0104-Maximum-Depth-of-Binary-Tree/cpp-0104/main.cpp diff --git a/0104-Maximum-Depth-of-Binary-Tree/cpp-0104/main2.cpp b/0001-0500/0104-Maximum-Depth-of-Binary-Tree/cpp-0104/main2.cpp similarity index 100% rename from 0104-Maximum-Depth-of-Binary-Tree/cpp-0104/main2.cpp rename to 0001-0500/0104-Maximum-Depth-of-Binary-Tree/cpp-0104/main2.cpp diff --git a/0104-Maximum-Depth-of-Binary-Tree/java-0104/src/Solution1.java b/0001-0500/0104-Maximum-Depth-of-Binary-Tree/java-0104/src/Solution1.java similarity index 100% rename from 0104-Maximum-Depth-of-Binary-Tree/java-0104/src/Solution1.java rename to 0001-0500/0104-Maximum-Depth-of-Binary-Tree/java-0104/src/Solution1.java diff --git a/0104-Maximum-Depth-of-Binary-Tree/java-0104/src/Solution2.java b/0001-0500/0104-Maximum-Depth-of-Binary-Tree/java-0104/src/Solution2.java similarity index 100% rename from 0104-Maximum-Depth-of-Binary-Tree/java-0104/src/Solution2.java rename to 0001-0500/0104-Maximum-Depth-of-Binary-Tree/java-0104/src/Solution2.java diff --git a/0001-0500/0105-Construct-Binary-Tree-from-Preorder-and-Inorder Traversal/cpp-0105/CMakeLists.txt b/0001-0500/0105-Construct-Binary-Tree-from-Preorder-and-Inorder Traversal/cpp-0105/CMakeLists.txt new file mode 100644 index 00000000..92c0fadf --- /dev/null +++ b/0001-0500/0105-Construct-Binary-Tree-from-Preorder-and-Inorder Traversal/cpp-0105/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0105) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0105 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0105-Construct-Binary-Tree-from-Preorder-and-Inorder Traversal/cpp-0105/main.cpp b/0001-0500/0105-Construct-Binary-Tree-from-Preorder-and-Inorder Traversal/cpp-0105/main.cpp new file mode 100644 index 00000000..5f18469c --- /dev/null +++ b/0001-0500/0105-Construct-Binary-Tree-from-Preorder-and-Inorder Traversal/cpp-0105/main.cpp @@ -0,0 +1,59 @@ +/// Source : https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/description/ +/// Author : liuyubobobo +/// Time : 2018-06-03 + +#include +#include +#include + +using namespace std; + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +/// Recursive +/// Time Complexity: O(n*h) where n is the num of node in th tree +/// and h is the height of the tree +/// Space Complexity: O(h) +class Solution { +public: + TreeNode* buildTree(vector& preorder, vector& inorder) { + return buildTree(preorder, 0, preorder.size(), inorder, 0, inorder.size()); + } + +private: + TreeNode* buildTree(const vector& preorder, int preorderL, int preorderR, + const vector& inorder, int inorderL, int inorderR){ + + if(inorderL >= inorderR){ + assert(preorderL >= preorderR); + return NULL; + } + + if(inorderL + 1 == inorderR){ + assert(preorderL + 1 == preorderR); + return new TreeNode(inorder[inorderL]); + } + + TreeNode* root = new TreeNode(preorder[preorderL]); + int rootPos = find(inorder.begin() + inorderL, inorder.begin() + inorderR, root->val) - inorder.begin(); + assert(rootPos >= inorderL && rootPos < inorderR); + + int lsize = rootPos - inorderL; + int rsize = inorderR - (rootPos + 1); + root->left = buildTree(preorder, preorderL + 1, preorderL + 1 + lsize, inorder, inorderL, rootPos); + root->right = buildTree(preorder, preorderL + 1 + lsize, preorderR, inorder, rootPos + 1, inorderR); + return root; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0106-Construct-Binary-Tree-from-Inorder-and-Postorder Traversal/cpp-0106/CMakeLists.txt b/0001-0500/0106-Construct-Binary-Tree-from-Inorder-and-Postorder Traversal/cpp-0106/CMakeLists.txt new file mode 100644 index 00000000..c06cccf1 --- /dev/null +++ b/0001-0500/0106-Construct-Binary-Tree-from-Inorder-and-Postorder Traversal/cpp-0106/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0106) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0106 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0106-Construct-Binary-Tree-from-Inorder-and-Postorder Traversal/cpp-0106/main.cpp b/0001-0500/0106-Construct-Binary-Tree-from-Inorder-and-Postorder Traversal/cpp-0106/main.cpp new file mode 100644 index 00000000..81cbb713 --- /dev/null +++ b/0001-0500/0106-Construct-Binary-Tree-from-Inorder-and-Postorder Traversal/cpp-0106/main.cpp @@ -0,0 +1,64 @@ +/// Source : https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/description/ +/// Author : liuyubobobo +/// Time : 2018-06-03 + +#include +#include +#include + +using namespace std; + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + + +/// Recursive +/// Time Complexity: O(n*h) where n is the num of node in th tree +/// and h is the height of the tree +/// Space Complexity: O(h) +class Solution { +public: + TreeNode* buildTree(vector& inorder, vector& postorder) { + return buildTree(inorder, 0, inorder.size(), postorder, 0, postorder.size()); + } + +private: + TreeNode* buildTree(vector& inorder, int inorderL, int inorderR, + vector& postorder, int postorderL, int postorderR){ + + if(inorderL >= inorderR){ + assert(postorderL >= postorderR); + return NULL; + } + + if(inorderL + 1 == inorderR){ + assert(postorderL + 1 == postorderR); + return new TreeNode(inorder[inorderL]); + } + + TreeNode* root = new TreeNode(postorder[postorderR - 1]); + int rootPos = find(inorder.begin() + inorderL, inorder.begin() + inorderR, root->val) - inorder.begin(); + assert(inorderL <= rootPos && rootPos < inorderR); + + int lsize = rootPos - inorderL; + int rsize = inorderR - (rootPos + 1); + root->left = buildTree(inorder, inorderL, inorderL + lsize, postorder, postorderL, postorderL + lsize); + root->right = buildTree(inorder, rootPos + 1, inorderR, postorder, postorderL + lsize, postorderR - 1); + return root; + } +}; + + +int main() { + + vector inorder = {9,3,15,20,7}; + vector postorder = {9,15,7,20,3}; + TreeNode* root = Solution().buildTree(inorder, postorder); + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0107-Binary-Tree-Level-Order-Traversal-II/cpp-0107/CMakeLists.txt b/0001-0500/0107-Binary-Tree-Level-Order-Traversal-II/cpp-0107/CMakeLists.txt new file mode 100644 index 00000000..03bbb208 --- /dev/null +++ b/0001-0500/0107-Binary-Tree-Level-Order-Traversal-II/cpp-0107/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0107) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main2.cpp) +add_executable(cpp_0107 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0107-Binary-Tree-Level-Order-Traversal-II/cpp-0107/main.cpp b/0001-0500/0107-Binary-Tree-Level-Order-Traversal-II/cpp-0107/main.cpp new file mode 100644 index 00000000..3303e981 --- /dev/null +++ b/0001-0500/0107-Binary-Tree-Level-Order-Traversal-II/cpp-0107/main.cpp @@ -0,0 +1,65 @@ +/// Source : https://leetcode.com/problems/binary-tree-level-order-traversal-ii/description/ +/// Author : liuyubobobo +/// Time : 2018-10-16 + +#include + +using namespace std; + +#include +#include +#include +#include + +using namespace std; + + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +/// BFS +/// Time Complexity: O(n), where n is the number of nodes in the tree +/// Space Complexity: O(n) +class Solution { +public: + vector> levelOrderBottom(TreeNode* root) { + + vector> res; + if(root == NULL) + return res; + + queue> q; + q.push(make_pair(root, 0)); + + while(!q.empty()){ + + TreeNode* node = q.front().first; + int level = q.front().second; + q.pop(); + + if(level == res.size()) + res.push_back(vector()); + assert( level < res.size() ); + + res[level].push_back(node->val); + if(node->left) + q.push(make_pair(node->left, level + 1 )); + if(node->right) + q.push(make_pair(node->right, level + 1 )); + } + + reverse(res.begin(), res.end()); + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0107-Binary-Tree-Level-Order-Traversal-II/cpp-0107/main2.cpp b/0001-0500/0107-Binary-Tree-Level-Order-Traversal-II/cpp-0107/main2.cpp new file mode 100644 index 00000000..f475da7c --- /dev/null +++ b/0001-0500/0107-Binary-Tree-Level-Order-Traversal-II/cpp-0107/main2.cpp @@ -0,0 +1,74 @@ +/// Source : https://leetcode.com/problems/binary-tree-level-order-traversal-ii/description/ +/// Author : liuyubobobo +/// Time : 2018-10-16 + +#include + +using namespace std; + +#include +#include +#include +#include + +using namespace std; + + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +/// BFS +/// No need to store level information in the queue :-) +/// +/// Time Complexity: O(n), where n is the number of nodes in the tree +/// Space Complexity: O(n) +class Solution { +public: + vector> levelOrderBottom(TreeNode* root) { + + vector> res; + if(root == NULL) + return res; + + queue q; + q.push(root); + int level_num = 1; + + while(!q.empty()){ + + int new_level_num = 0; + vector level; + for(int i = 0; i < level_num; i ++){ + TreeNode* node = q.front(); + q.pop(); + level.push_back(node->val); + + if(node->left){ + q.push(node->left); + new_level_num ++; + } + if(node->right){ + q.push(node->right); + new_level_num ++; + } + } + + res.push_back(level); + level_num = new_level_num; + } + + reverse(res.begin(), res.end()); + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0108-Convert-Sorted-Array-to-Binary-Search-Tree/cpp-0108/CMakeLists.txt b/0001-0500/0108-Convert-Sorted-Array-to-Binary-Search-Tree/cpp-0108/CMakeLists.txt new file mode 100644 index 00000000..cdc6e358 --- /dev/null +++ b/0001-0500/0108-Convert-Sorted-Array-to-Binary-Search-Tree/cpp-0108/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0108) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0108 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0108-Convert-Sorted-Array-to-Binary-Search-Tree/cpp-0108/main.cpp b/0001-0500/0108-Convert-Sorted-Array-to-Binary-Search-Tree/cpp-0108/main.cpp new file mode 100644 index 00000000..faf007d1 --- /dev/null +++ b/0001-0500/0108-Convert-Sorted-Array-to-Binary-Search-Tree/cpp-0108/main.cpp @@ -0,0 +1,49 @@ +/// Source : https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/description/ +/// Author : liuyubobobo +/// Time : 2018-10-30 + +#include +#include + +using namespace std; + + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +/// Recursion +/// Time Complexity: O(n) +/// Space Complexity: O(logn) +class Solution { +public: + TreeNode* sortedArrayToBST(vector& nums) { + + if(nums.size() == 0) + return NULL; + return buildTree(nums, 0, nums.size() - 1); + } + +private: + TreeNode* buildTree(const vector& nums, int l, int r){ + + if(l > r) return NULL; + if(l == r) return new TreeNode(nums[l]); + + int mid = (l + r) / 2; + TreeNode* root = new TreeNode(nums[mid]); + root->left = buildTree(nums, l, mid - 1); + root->right = buildTree(nums, mid + 1, r); + return root; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0109-Convert-Sorted-List-to-Binary-Search-Tree/cpp-0109/CMakeLists.txt b/0001-0500/0109-Convert-Sorted-List-to-Binary-Search-Tree/cpp-0109/CMakeLists.txt new file mode 100644 index 00000000..8256de52 --- /dev/null +++ b/0001-0500/0109-Convert-Sorted-List-to-Binary-Search-Tree/cpp-0109/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0109) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main2.cpp) +add_executable(cpp_0109 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0109-Convert-Sorted-List-to-Binary-Search-Tree/cpp-0109/main.cpp b/0001-0500/0109-Convert-Sorted-List-to-Binary-Search-Tree/cpp-0109/main.cpp new file mode 100644 index 00000000..68a51fd5 --- /dev/null +++ b/0001-0500/0109-Convert-Sorted-List-to-Binary-Search-Tree/cpp-0109/main.cpp @@ -0,0 +1,112 @@ +/// Source : https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/description/ +/// Author : liuyubobobo +/// Time : 2018-04-22 + +#include + +using namespace std; + + +/// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} +}; + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + + +/// Recursive +/// Time Complexity: O(nlogn) +/// Space Complexity: O(logn) +class Solution { + +public: + TreeNode* sortedListToBST(ListNode* head) { + + if(head == NULL) + return NULL; + + int len = getLen(head); + return buildBST(head, 0, len - 1); + } + +private: + TreeNode* buildBST(ListNode* head, int l, int r){ + + if(l > r) + return NULL; + + if(l == r) + return new TreeNode(head->val); + + int mid = l + (r - l + 1) / 2; + ListNode* cur = head; + for(int i = l ; i < mid - 1 ; i ++) + cur = cur->next; + + ListNode* node = cur->next; + cur->next = NULL; + + TreeNode* root = new TreeNode(node->val); + root->left = buildBST(head, l, mid - 1); + root->right = buildBST(node->next, mid + 1, r); + return root; + } + + int getLen(ListNode* head){ + + ListNode* cur = head; + int res = 0; + while(cur != NULL){ + res ++; + cur = cur->next; + } + return res; + } +}; + + +/// Test Helper +ListNode* createLinkedList(int arr[], int n){ + + if(n == 0) + return NULL; + + ListNode* head = new ListNode(arr[0]); + ListNode* curNode = head; + for(int i = 1 ; i < n ; i ++){ + curNode->next = new ListNode(arr[i]); + curNode = curNode->next; + } + + return head; +} + +void inOrder(TreeNode* node){ + + if(node == NULL) + return; + + inOrder(node->left); + cout << node->val << " "; + inOrder(node->right); +} + + +int main() { + + int arr1[] = {-10, -3, 0, 5, 9}; + ListNode* head1 = createLinkedList(arr1, 5); + inOrder(Solution().sortedListToBST(head1)); + cout << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0109-Convert-Sorted-List-to-Binary-Search-Tree/cpp-0109/main2.cpp b/0001-0500/0109-Convert-Sorted-List-to-Binary-Search-Tree/cpp-0109/main2.cpp new file mode 100644 index 00000000..3bfeb1cb --- /dev/null +++ b/0001-0500/0109-Convert-Sorted-List-to-Binary-Search-Tree/cpp-0109/main2.cpp @@ -0,0 +1,112 @@ +/// Source : https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/description/ +/// Author : liuyubobobo +/// Time : 2018-11-17 + +#include + +using namespace std; + + +/// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} +}; + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + + +/// Recursive and do the inorder simulation +/// Time Complexity: O(n) +/// Space Complexity: O(logn) +class Solution { + +private: + ListNode* cur; + +public: + TreeNode* sortedListToBST(ListNode* head) { + + if(head == NULL) + return NULL; + + int len = getLen(head); + cur = head; + return buildBST(0, len - 1); + } + +private: + TreeNode* buildBST(int l, int r){ + + if(l > r) + return NULL; + + int mid = l + (r - l + 1) / 2; + TreeNode* left = buildBST(l, mid - 1); + + TreeNode* root = new TreeNode(cur->val); + cur = cur->next; + + TreeNode* right = buildBST(mid + 1, r); + + root->left = left; + root->right = right; + return root; + } + + int getLen(ListNode* head){ + + ListNode* cur = head; + int res = 0; + while(cur != NULL){ + res ++; + cur = cur->next; + } + return res; + } +}; + + +/// Test Helper +ListNode* createLinkedList(int arr[], int n){ + + if(n == 0) + return NULL; + + ListNode* head = new ListNode(arr[0]); + ListNode* curNode = head; + for(int i = 1 ; i < n ; i ++){ + curNode->next = new ListNode(arr[i]); + curNode = curNode->next; + } + + return head; +} + +void inOrder(TreeNode* node){ + + if(node == NULL) + return; + + inOrder(node->left); + cout << node->val << " "; + inOrder(node->right); +} + + +int main() { + + int arr1[] = {-10, -3, 0, 5, 9}; + ListNode* head1 = createLinkedList(arr1, 5); + inOrder(Solution().sortedListToBST(head1)); + cout << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0110-Balanced-Binary-Tree/cpp-0100/CMakeLists.txt b/0001-0500/0110-Balanced-Binary-Tree/cpp-0100/CMakeLists.txt new file mode 100644 index 00000000..744f6d97 --- /dev/null +++ b/0001-0500/0110-Balanced-Binary-Tree/cpp-0100/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0100) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0100 main.cpp) \ No newline at end of file diff --git a/0001-0500/0110-Balanced-Binary-Tree/cpp-0100/main.cpp b/0001-0500/0110-Balanced-Binary-Tree/cpp-0100/main.cpp new file mode 100644 index 00000000..ac2196c4 --- /dev/null +++ b/0001-0500/0110-Balanced-Binary-Tree/cpp-0100/main.cpp @@ -0,0 +1,55 @@ +/// Source : https://leetcode.com/problems/balanced-binary-tree/ +/// Author : liuyubobobo +/// Time : 2020-12-23 + +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// 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 { + +private: + unordered_map height; + +public: + bool isBalanced(TreeNode* root) { + + if(!root) return true; + + int left_height = get_height(root->left); + int right_height = get_height(root->right); + + return isBalanced(root->left) && isBalanced(root->right) && abs(left_height - right_height) <= 1; + } + +private: + int get_height(TreeNode* node){ + + if(!node) return 0; + if(height.count(node)) return height[node]; + + return height[node] = max(get_height(node->left), get_height(node->right)) + 1; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0111-Minimum-Depth-of-Binary-Tree/cpp-0111/CMakeLists.txt b/0001-0500/0111-Minimum-Depth-of-Binary-Tree/cpp-0111/CMakeLists.txt new file mode 100644 index 00000000..e8cd9b67 --- /dev/null +++ b/0001-0500/0111-Minimum-Depth-of-Binary-Tree/cpp-0111/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0111) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main3.cpp) +add_executable(cpp_0111 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0111-Minimum-Depth-of-Binary-Tree/cpp-0111/main.cpp b/0001-0500/0111-Minimum-Depth-of-Binary-Tree/cpp-0111/main.cpp new file mode 100644 index 00000000..73649ccd --- /dev/null +++ b/0001-0500/0111-Minimum-Depth-of-Binary-Tree/cpp-0111/main.cpp @@ -0,0 +1,44 @@ +/// Source : https://leetcode.com/problems/minimum-depth-of-binary-tree/ +/// Author : liuyubobobo +/// Time : 2018-06-02 + +#include + +using namespace std; + + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +/// Recursive +/// Time Complexity: O(n) +/// Space Complexity: O(h) +class Solution { +public: + int minDepth(TreeNode* root) { + + if(root == NULL) + return 0; + + if(root->left == NULL && root->right == NULL) + return 1; + + int ret = INT_MAX; + if(root->left != NULL) + ret = min(ret, 1 + minDepth(root->left)); + if(root->right != NULL) + ret = min(ret, 1 + minDepth(root->right)); + return ret; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0111-Minimum-Depth-of-Binary-Tree/cpp-0111/main2.cpp b/0001-0500/0111-Minimum-Depth-of-Binary-Tree/cpp-0111/main2.cpp new file mode 100644 index 00000000..b683de00 --- /dev/null +++ b/0001-0500/0111-Minimum-Depth-of-Binary-Tree/cpp-0111/main2.cpp @@ -0,0 +1,56 @@ +/// Source : https://leetcode.com/problems/minimum-depth-of-binary-tree/ +/// Author : liuyubobobo +/// Time : 2018-10-29 + +#include +#include + +using namespace std; + + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +/// Non-Recursive +/// Using stack +/// +/// Time Complexity: O(n) +/// Space Complexity: O(h) +class Solution { +public: + int minDepth(TreeNode* root) { + + if(root == NULL) + return 0; + + stack> stack; + stack.push(make_pair(root, 1)); + int res = INT_MAX; + while(!stack.empty()){ + TreeNode* cur = stack.top().first; + int step = stack.top().second; + stack.pop(); + + if(!cur->left && !cur->right) + res = min(res, step); + else{ + if(cur->left) + stack.push(make_pair(cur->left, step + 1)); + if(cur->right) + stack.push(make_pair(cur->right, step + 1)); + } + } + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0111-Minimum-Depth-of-Binary-Tree/cpp-0111/main3.cpp b/0001-0500/0111-Minimum-Depth-of-Binary-Tree/cpp-0111/main3.cpp new file mode 100644 index 00000000..8c46bfdd --- /dev/null +++ b/0001-0500/0111-Minimum-Depth-of-Binary-Tree/cpp-0111/main3.cpp @@ -0,0 +1,58 @@ +/// Source : https://leetcode.com/problems/minimum-depth-of-binary-tree/ +/// Author : liuyubobobo +/// Time : 2018-10-29 + +#include +#include +#include + +using namespace std; + + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +/// Non-Recursive +/// Using BFS may not visit all the nodes :-) +/// +/// Time Complexity: O(n) +/// Space Complexity: O(h) +class Solution { +public: + int minDepth(TreeNode* root) { + + if(root == NULL) + return 0; + + queue> queue; + queue.push(make_pair(root, 1)); + while(!queue.empty()){ + TreeNode* cur = queue.front().first; + int step = queue.front().second; + queue.pop(); + + if(!cur->left && !cur->right) + return step; + else{ + if(cur->left) + queue.push(make_pair(cur->left, step + 1)); + if(cur->right) + queue.push(make_pair(cur->right, step + 1)); + } + } + + assert(false); + return -1; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0112-Path-Sum/cpp-0112/CMakeLists.txt b/0001-0500/0112-Path-Sum/cpp-0112/CMakeLists.txt new file mode 100644 index 00000000..cc05927c --- /dev/null +++ b/0001-0500/0112-Path-Sum/cpp-0112/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0112) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main2.cpp) +add_executable(cpp_0112 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0112-Path-Sum/cpp-0112/main.cpp b/0001-0500/0112-Path-Sum/cpp-0112/main.cpp new file mode 100644 index 00000000..d71ddcbf --- /dev/null +++ b/0001-0500/0112-Path-Sum/cpp-0112/main.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/path-sum/description/ +/// Author : liuyubobobo +/// Time : 2017-11-17 + +#include + +using namespace std; + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + + +/// Recursive +/// Time Complexity: O(n), where n is the nodes' number of the tree +/// Space Complexity: O(h), where h is the height of the tree +class Solution { +public: + bool hasPathSum(TreeNode* root, int sum) { + + if(!root) + return false; + + if(!root->left && !root->right) + return sum == root->val; + + return hasPathSum(root->left, sum - root->val) + || hasPathSum(root->right, sum - root->val); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0112-Path-Sum/cpp-0112/main2.cpp b/0001-0500/0112-Path-Sum/cpp-0112/main2.cpp new file mode 100644 index 00000000..185366e7 --- /dev/null +++ b/0001-0500/0112-Path-Sum/cpp-0112/main2.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/path-sum/description/ +/// Author : liuyubobobo +/// Time : 2018-11-17 + +#include +#include + +using namespace std; + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + + +/// Non-Recursive +/// Using Stack +/// +/// Time Complexity: O(n), where n is the nodes' number of the tree +/// Space Complexity: O(h), where h is the height of the tree +class Solution { +public: + bool hasPathSum(TreeNode* root, int sum) { + + if(!root) + return false; + + stack> stack; + stack.push(make_pair(root, sum)); + while(!stack.empty()){ + TreeNode* cur = stack.top().first; + int num = stack.top().second; + stack.pop(); + + if(num == cur->val && !cur->left && !cur->right) + return true; + + if (cur->left) + stack.push(make_pair(cur->left, num - cur->val)); + if (cur->right) + stack.push(make_pair(cur->right, num - cur->val)); + } + return false; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0112-Path-Sum/java-0112/src/Solution.java b/0001-0500/0112-Path-Sum/java-0112/src/Solution.java new file mode 100644 index 00000000..06c7d2a6 --- /dev/null +++ b/0001-0500/0112-Path-Sum/java-0112/src/Solution.java @@ -0,0 +1,21 @@ +/// Source : https://leetcode.com/problems/path-sum/description/ +/// Author : liuyubobobo +/// Time : 2017-11-17 + +/// Recursive +/// Time Complexity: O(n), where n is the nodes' number of the tree +/// Space Complexity: O(h), where h is the height of the tree +class Solution { + + public boolean hasPathSum(TreeNode root, int sum) { + + if(root == null) + return false; + + if(root.left == null && root.right == null) + return sum == root.val; + + return hasPathSum(root.left, sum - root.val) + || hasPathSum(root.right, sum - root.val); + } +} \ No newline at end of file diff --git a/0001-0500/0112-Path-Sum/java-0112/src/Solution2.java b/0001-0500/0112-Path-Sum/java-0112/src/Solution2.java new file mode 100644 index 00000000..9459682d --- /dev/null +++ b/0001-0500/0112-Path-Sum/java-0112/src/Solution2.java @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/path-sum/description/ +/// Author : liuyubobobo +/// Time : 2018-11-17 + +import java.util.Stack; +import javafx.util.Pair; + +/// Non-Recursive +/// Using Stack +/// +/// Time Complexity: O(n), where n is the nodes' number of the tree +/// Space Complexity: O(h), where h is the height of the tree +public class Solution2 { + + public boolean hasPathSum(TreeNode root, int sum) { + + if(root == null) + return false; + + Stack> stack = new Stack<>(); + stack.push(new Pair<>(root, sum)); + while(!stack.empty()){ + TreeNode cur = stack.peek().getKey(); + int num = stack.peek().getValue(); + stack.pop(); + + if(num == cur.val && cur.left == null && cur.right == null) + return true; + + if(cur.left != null) + stack.push(new Pair<>(cur.left, num - cur.val)); + if(cur.right != null) + stack.push(new Pair<>(cur.right, num - cur.val)); + } + return false; + } +} diff --git a/0001-0500/0112-Path-Sum/java-0112/src/TreeNode.java b/0001-0500/0112-Path-Sum/java-0112/src/TreeNode.java new file mode 100644 index 00000000..f408f764 --- /dev/null +++ b/0001-0500/0112-Path-Sum/java-0112/src/TreeNode.java @@ -0,0 +1,7 @@ +// Definition for a binary tree node. +public class TreeNode { + int val; + TreeNode left; + TreeNode right; + TreeNode(int x) { val = x; } +} \ No newline at end of file diff --git a/0001-0500/0113-Path-Sum-II/cpp-0113/CMakeLists.txt b/0001-0500/0113-Path-Sum-II/cpp-0113/CMakeLists.txt new file mode 100644 index 00000000..e5399828 --- /dev/null +++ b/0001-0500/0113-Path-Sum-II/cpp-0113/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0113) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0113 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0113-Path-Sum-II/cpp-0113/main.cpp b/0001-0500/0113-Path-Sum-II/cpp-0113/main.cpp new file mode 100644 index 00000000..fc85d5d7 --- /dev/null +++ b/0001-0500/0113-Path-Sum-II/cpp-0113/main.cpp @@ -0,0 +1,65 @@ +/// Source : https://leetcode.com/problems/path-sum-ii/description/ +/// Author : liuyubobobo +/// Time : 2018-10-16 + +#include +#include + +using namespace std; + + +/// Recursion +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// 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: + vector> pathSum(TreeNode* root, int sum) { + + vector> res; + if(!root) + return res; + + vector tres; + dfs(root, tres, 0, sum, res); + return res; + } + +private: + void dfs(TreeNode* node, vector& tres, int tsum, + int sum, vector>& res){ + + tres.push_back(node->val); + tsum += node->val; + + if(!node->left && !node->right){ + if(tsum == sum) + res.push_back(tres); + } + else { + if (node->left) + dfs(node->left, tres, tsum, sum, res); + + if (node->right) + dfs(node->right, tres, tsum, sum, res); + } + + tres.pop_back(); + return; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0114-Flatten-Binary-Tree-to-Linked-List/cpp-0114/CMakeLists.txt b/0001-0500/0114-Flatten-Binary-Tree-to-Linked-List/cpp-0114/CMakeLists.txt new file mode 100644 index 00000000..e0e7d3b7 --- /dev/null +++ b/0001-0500/0114-Flatten-Binary-Tree-to-Linked-List/cpp-0114/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_0114) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0114 main.cpp) \ No newline at end of file diff --git a/0001-0500/0114-Flatten-Binary-Tree-to-Linked-List/cpp-0114/main.cpp b/0001-0500/0114-Flatten-Binary-Tree-to-Linked-List/cpp-0114/main.cpp new file mode 100644 index 00000000..95860e64 --- /dev/null +++ b/0001-0500/0114-Flatten-Binary-Tree-to-Linked-List/cpp-0114/main.cpp @@ -0,0 +1,55 @@ +/// Source : https://leetcode.com/problems/flatten-binary-tree-to-linked-list/ +/// Author : liuyubobobo +/// Time : 2021-05-14 + +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// 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: + void flatten(TreeNode* root) { + + if(!root) return; + + vector v; + dfs(root, v); + + for(int i = 0; i + 1 < v.size(); i ++) + v[i]->left = nullptr, v[i]->right = v[i + 1]; + + v.back()->right = nullptr; + root = v[0]; + } + +private: + void dfs(TreeNode* node, vector& v){ + + if(!node) return; + v.push_back(node); + dfs(node->left, v); + dfs(node->right, v); + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0115-Distinct-Subsequences/cpp-0115/CMakeLists.txt b/0001-0500/0115-Distinct-Subsequences/cpp-0115/CMakeLists.txt new file mode 100644 index 00000000..0a7b68dc --- /dev/null +++ b/0001-0500/0115-Distinct-Subsequences/cpp-0115/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0115) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main2.cpp) +add_executable(cpp_0115 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0115-Distinct-Subsequences/cpp-0115/main.cpp b/0001-0500/0115-Distinct-Subsequences/cpp-0115/main.cpp new file mode 100644 index 00000000..c8d82c69 --- /dev/null +++ b/0001-0500/0115-Distinct-Subsequences/cpp-0115/main.cpp @@ -0,0 +1,55 @@ +/// Source : https://leetcode.com/problems/distinct-subsequences/description/ +/// Author : liuyubobobo +/// Time : 2018-04-23 +/// Updated: 2021-09-19 + +#include +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(s * t) +/// Space Complexity: O(s * t) +class Solution { + +private: + const long long MOD = (long long)INT_MAX + 1; + +public: + int numDistinct(string s, string t) { + + vector> dp(s.size() + 1, vector(t.size() + 1, 0)); + for(int i = 0 ; i <= s.size() ; i ++) + dp[i][0] = 1; + + for(int i = 1 ; i <= s.size() ; i ++) + for(int j = 1 ; j <= t.size() ; j ++){ + dp[i][j] = dp[i - 1][j]; + if(s[i - 1] == t[j - 1]) + dp[i][j] = (dp[i][j] + dp[i - 1][j - 1]) % MOD; + } + + return dp[s.size()][t.size()]; + } +}; + + +int main() { + + string S1 = "rabbbit"; + string T1 = "rabbit"; + cout << Solution().numDistinct(S1, T1) << endl; + // 3 + + // --- + + string S2 = "babgbag"; + string T2 = "bag"; + cout << Solution().numDistinct(S2, T2) << endl; + // 5 + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0115-Distinct-Subsequences/cpp-0115/main2.cpp b/0001-0500/0115-Distinct-Subsequences/cpp-0115/main2.cpp new file mode 100644 index 00000000..5464c6fe --- /dev/null +++ b/0001-0500/0115-Distinct-Subsequences/cpp-0115/main2.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/distinct-subsequences/description/ +/// Author : liuyubobobo +/// Time : 2018-04-23 +/// Updated: 2021-09-19 + +#include +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(s * t) +/// Space Complexity: O(t) +class Solution { + +private: + const long long MOD = (long long)INT_MAX + 1; + +public: + int numDistinct(string s, string t) { + + vector dp(t.size() + 1, 0); + dp[0] = 1; + + for(int i = 1 ; i <= s.size() ; i ++) + for(int j = t.size() ; j >= 1 ; j --) + if(s[i - 1] == t[j - 1]) + dp[j] = (dp[j] + dp[j - 1]) % MOD; + + + return dp[t.size()]; + } +}; + + +int main() { + + string S1 = "rabbbit"; + string T1 = "rabbit"; + cout << Solution().numDistinct(S1, T1) << endl; + // 3 + + // --- + + string S2 = "babgbag"; + string T2 = "bag"; + cout << Solution().numDistinct(S2, T2) << endl; + // 5 + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0115-Distinct-Subsequences/java-0115/src/Solution.java b/0001-0500/0115-Distinct-Subsequences/java-0115/src/Solution.java new file mode 100644 index 00000000..f2d7c3bf --- /dev/null +++ b/0001-0500/0115-Distinct-Subsequences/java-0115/src/Solution.java @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/distinct-subsequences/description/ +/// Author : liuyubobobo +/// Time : 2018-04-23 + +/// Dynamic Programming +/// Time Complexity: O(s * t) +/// Space Complexity: O(s * t) +public class Solution { + public int numDistinct(String s, String t) { + + int[][] dp = new int[s.length() + 1][t.length() + 1]; + for(int i = 0 ; i <= s.length() ; i ++) + dp[i][0] = 1; + + for(int i = 1 ; i <= s.length() ; i ++) + for(int j = 1 ; j <= t.length() ; j ++){ + dp[i][j] = dp[i - 1][j]; + if(s.charAt(i - 1) == t.charAt(j - 1)) + dp[i][j] += dp[i - 1][j - 1]; + } + + return dp[s.length()][t.length()]; + } + + public static void main(String[] args) { + + String s1 = "rabbbit", t1 = "rabbit"; + System.out.println((new Solution()).numDistinct(s1, t1)); + // 3 + + String s2 = "babgbag", t2 = "bag"; + System.out.println((new Solution()).numDistinct(s2, t2)); + // 5 + } +} diff --git a/0001-0500/0115-Distinct-Subsequences/java-0115/src/Solution2.java b/0001-0500/0115-Distinct-Subsequences/java-0115/src/Solution2.java new file mode 100644 index 00000000..2948427d --- /dev/null +++ b/0001-0500/0115-Distinct-Subsequences/java-0115/src/Solution2.java @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/distinct-subsequences/description/ +/// Author : liuyubobobo +/// Time : 2018-04-23 + +/// Dynamic Programming +/// Time Complexity: O(s * t) +/// Space Complexity: O(t) +public class Solution2 { + + public int numDistinct(String s, String t) { + + int[] dp = new int[t.length() + 1]; + dp[0] = 1; + + for(int i = 1 ; i <= s.length() ; i ++) + for(int j = t.length() ; j >= 1 ; j --) + if(s.charAt(i - 1) == t.charAt(j - 1)) + dp[j] += dp[j - 1]; + + + return dp[t.length()]; + } + + public static void main(String[] args) { + + String s1 = "rabbbit", t1 = "rabbit"; + System.out.println((new Solution()).numDistinct(s1, t1)); + // 3 + + String s2 = "babgbag", t2 = "bag"; + System.out.println((new Solution()).numDistinct(s2, t2)); + // 5 + } +} diff --git a/0001-0500/0116-Populating-Next-Right-Pointers-in-Each-Node/cpp-0116/CMakeLists.txt b/0001-0500/0116-Populating-Next-Right-Pointers-in-Each-Node/cpp-0116/CMakeLists.txt new file mode 100644 index 00000000..26f3bbcb --- /dev/null +++ b/0001-0500/0116-Populating-Next-Right-Pointers-in-Each-Node/cpp-0116/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0116) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main3.cpp) +add_executable(cpp_0116 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0116-Populating-Next-Right-Pointers-in-Each-Node/cpp-0116/main.cpp b/0001-0500/0116-Populating-Next-Right-Pointers-in-Each-Node/cpp-0116/main.cpp new file mode 100644 index 00000000..37d1b187 --- /dev/null +++ b/0001-0500/0116-Populating-Next-Right-Pointers-in-Each-Node/cpp-0116/main.cpp @@ -0,0 +1,65 @@ +/// Source : https://leetcode.com/problems/populating-next-right-pointers-in-each-node/description/ +/// Author : liuyubobobo +/// Time : 2018-10-08 +/// Updated: 2021-07-09 + +#include +#include +#include + +using namespace std; + + +/// Using queue for BFS +/// Time Complexity: O(n) +/// Space Compelxity: O(n) + +/// Definition for binary tree with next pointer. +class Node { +public: + int val; + Node* left; + Node* right; + Node* next; + + Node() : val(0), left(NULL), right(NULL), next(NULL) {} + + Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {} + + Node(int _val, Node* _left, Node* _right, Node* _next) + : val(_val), left(_left), right(_right), next(_next) {} +}; + +class Solution { +public: + Node* connect(Node *root) { + + if(!root) return root; + + queue q; + q.push(root); + int level = 0; + while(!q.empty()){ + int n = (1 << level); + while(n --){ + Node* cur = q.front(); + q.pop(); + if(n) + cur->next = q.front(); + if(cur->left){ + q.push(cur->left); + assert(cur->right); + q.push(cur->right); + } + } + level ++; + } + return root; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0116-Populating-Next-Right-Pointers-in-Each-Node/cpp-0116/main2.cpp b/0001-0500/0116-Populating-Next-Right-Pointers-in-Each-Node/cpp-0116/main2.cpp new file mode 100644 index 00000000..0f74d136 --- /dev/null +++ b/0001-0500/0116-Populating-Next-Right-Pointers-in-Each-Node/cpp-0116/main2.cpp @@ -0,0 +1,60 @@ +/// Source : https://leetcode.com/problems/populating-next-right-pointers-in-each-node/description/ +/// Author : liuyubobobo +/// Time : 2018-10-08 +/// Updated: 2021-07-09 + +#include +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Compelxity: O(logn) + +/// Definition for binary tree with next pointer. +class Node { +public: + int val; + Node* left; + Node* right; + Node* next; + + Node() : val(0), left(NULL), right(NULL), next(NULL) {} + + Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {} + + Node(int _val, Node* _left, Node* _right, Node* _next) + : val(_val), left(_left), right(_right), next(_next) {} +}; + +class Solution { + +public: + Node* connect(Node *root) { + + if(!root) return nullptr; + dfs(root->left, root->right); + + connect(root->left); + connect(root->right); + return root; + } + +private: + void dfs(Node* l, Node* r){ + + if(l){ + l->next = r; + dfs(l->right, r->left); + } + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0116-Populating-Next-Right-Pointers-in-Each-Node/cpp-0116/main3.cpp b/0001-0500/0116-Populating-Next-Right-Pointers-in-Each-Node/cpp-0116/main3.cpp new file mode 100644 index 00000000..f5e247aa --- /dev/null +++ b/0001-0500/0116-Populating-Next-Right-Pointers-in-Each-Node/cpp-0116/main3.cpp @@ -0,0 +1,70 @@ +/// Source : https://leetcode.com/problems/populating-next-right-pointers-in-each-node/description/ +/// Author : liuyubobobo +/// Time : 2018-10-19 +/// Updated: 2021-07-09 + +#include +#include +#include + +using namespace std; + + +/// BFS without queue +/// Since the upper level have already been a linked list +/// We can traverse the upper level in a linked list way to connect the lower level +/// Actually, the upper linked list is our queue :-) +/// +/// Time Complexity: O(n) +/// Space Compelxity: O(1) + +/// Definition for binary tree with next pointer. +class Node { +public: + int val; + Node* left; + Node* right; + Node* next; + + Node() : val(0), left(NULL), right(NULL), next(NULL) {} + + Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {} + + Node(int _val, Node* _left, Node* _right, Node* _next) + : val(_val), left(_left), right(_right), next(_next) {} +}; + +class Solution { + +public: + Node* connect(Node *root) { + + if(!root) return nullptr; + + Node* node = root; + while(node->left){ + Node* p = node; + Node* dummyHead = new Node(-1); + Node* cur = dummyHead; + while(p){ + cur->next = p->left; + cur = cur->next; + + cur->next = p->right; + cur = cur->next; + + p = p->next; + } + + delete dummyHead; + node = node->left; + } + return root; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0117-Populating-Next-Right-Pointers-in-Each-Node-II/cpp-0117/CMakeLists.txt b/0001-0500/0117-Populating-Next-Right-Pointers-in-Each-Node-II/cpp-0117/CMakeLists.txt new file mode 100644 index 00000000..8c12b221 --- /dev/null +++ b/0001-0500/0117-Populating-Next-Right-Pointers-in-Each-Node-II/cpp-0117/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0117) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main2.cpp) +add_executable(cpp_0117 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0117-Populating-Next-Right-Pointers-in-Each-Node-II/cpp-0117/main.cpp b/0001-0500/0117-Populating-Next-Right-Pointers-in-Each-Node-II/cpp-0117/main.cpp new file mode 100644 index 00000000..e27a4d9b --- /dev/null +++ b/0001-0500/0117-Populating-Next-Right-Pointers-in-Each-Node-II/cpp-0117/main.cpp @@ -0,0 +1,59 @@ +/// Source : https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/description/ +/// Author : liuyubobobo +/// Time : 2018-10-16 + +#include +#include + +using namespace std; + + +/// Using BFS +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// Definition for binary tree with next pointer. +struct TreeLinkNode { + int val; + TreeLinkNode *left, *right, *next; + TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {} +}; + +class Solution { +public: + void connect(TreeLinkNode *root) { + + if(!root) + return; + + queue q; + q.push(root); + int level_num = 1; + while(!q.empty()){ + + int new_level_num = 0; + for(int i = 0; i < level_num; i ++){ + TreeLinkNode* node = q.front(); + q.pop(); + node->next = (i == level_num - 1 ? NULL : q.front()); + + if(node->left){ + q.push(node->left); + new_level_num ++; + } + + if(node->right){ + q.push(node->right); + new_level_num ++; + } + } + + level_num = new_level_num; + } + } +}; + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0117-Populating-Next-Right-Pointers-in-Each-Node-II/cpp-0117/main2.cpp b/0001-0500/0117-Populating-Next-Right-Pointers-in-Each-Node-II/cpp-0117/main2.cpp new file mode 100644 index 00000000..3c016bd8 --- /dev/null +++ b/0001-0500/0117-Populating-Next-Right-Pointers-in-Each-Node-II/cpp-0117/main2.cpp @@ -0,0 +1,56 @@ +/// Source : https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/description/ +/// Author : liuyubobobo +/// Time : 2018-10-18 + +#include +#include + +using namespace std; + + +/// Since the upper level have already been a linked list +/// We can traverse the upper level in a linked list way to connect the lower level +/// +/// Time Complexity: O(n) +/// Space Complexity: O(1) + +/// Definition for binary tree with next pointer. +struct TreeLinkNode { + int val; + TreeLinkNode *left, *right, *next; + TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {} +}; + +class Solution { +public: + void connect(TreeLinkNode *root) { + + if(!root) + return; + + TreeLinkNode* first = root; + while(first){ + + TreeLinkNode* p = first; + TreeLinkNode* cur = NULL; + first =NULL; + while(p){ + if(p->left){ + if(cur) cur->next = p->left, cur = cur->next; + else cur = first = p->left; + } + if(p->right){ + if(cur) cur->next = p->right, cur = cur->next; + else cur = first = p->right; + } + p = p->next; + } + } + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0118-Pascals-Triangle/cpp-0118/CMakeLists.txt b/0001-0500/0118-Pascals-Triangle/cpp-0118/CMakeLists.txt new file mode 100644 index 00000000..7081f5e9 --- /dev/null +++ b/0001-0500/0118-Pascals-Triangle/cpp-0118/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0118) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0118 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0118-Pascals-Triangle/cpp-0118/main.cpp b/0001-0500/0118-Pascals-Triangle/cpp-0118/main.cpp new file mode 100644 index 00000000..873700f1 --- /dev/null +++ b/0001-0500/0118-Pascals-Triangle/cpp-0118/main.cpp @@ -0,0 +1,38 @@ +/// Source : https://leetcode.com/problems/pascals-triangle/description/ +/// Author : liuyubobobo +/// Time : 2018-06-03 + +#include +#include + +using namespace std; + + +/// Simulation (Dynamic Programming) +/// Time Complexity: O(n^2) +/// Space Complexity: O(1) +class Solution { +public: + vector> generate(int numRows) { + + vector> res; + if(numRows <= 0) + return res; + + res.push_back({1}); + for(int i = 1 ; i < numRows ; i ++){ + vector row; + row.push_back(1); + for(int j = 1 ; j < i ; j ++) + row.push_back(res[i-1][j-1] + res[i-1][j]); + row.push_back(1); + res.push_back(row); + } + return res; + } +}; + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0119-Pascals-Triangle-II/cpp-0119/CMakeLists.txt b/0001-0500/0119-Pascals-Triangle-II/cpp-0119/CMakeLists.txt new file mode 100644 index 00000000..27969a12 --- /dev/null +++ b/0001-0500/0119-Pascals-Triangle-II/cpp-0119/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0119) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main3.cpp) +add_executable(cpp_0119 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0119-Pascals-Triangle-II/cpp-0119/main.cpp b/0001-0500/0119-Pascals-Triangle-II/cpp-0119/main.cpp new file mode 100644 index 00000000..c47258ca --- /dev/null +++ b/0001-0500/0119-Pascals-Triangle-II/cpp-0119/main.cpp @@ -0,0 +1,39 @@ +/// Source : https://leetcode.com/problems/pascals-triangle-ii/description/ +/// Author : liuyubobobo +/// Time : 2018-08-10 + +#include +#include + +using namespace std; + + +/// Simulate Pascal Triangle +/// +/// Time Complexity: O(rowIndex^2) +/// Space Complexity: O(rowIndex^2) +class Solution { +public: + vector getRow(int rowIndex) { + vector> res(rowIndex + 1, vector(rowIndex + 1, 1)); + for(int i = 2; i <= rowIndex ; i ++) + for(int j = 1; j < i; j ++ ) + res[i][j] = res[i-1][j-1] + res[i-1][j]; + return res[rowIndex]; + } +}; + + +void print_vec(const vector& vec){ + for(int e: vec) + cout << e << " "; + cout << endl; +} + +int main() { + + for(int i = 0 ; i < 10 ; i ++) + print_vec(Solution().getRow(i)); + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0119-Pascals-Triangle-II/cpp-0119/main2.cpp b/0001-0500/0119-Pascals-Triangle-II/cpp-0119/main2.cpp new file mode 100644 index 00000000..e00424d0 --- /dev/null +++ b/0001-0500/0119-Pascals-Triangle-II/cpp-0119/main2.cpp @@ -0,0 +1,39 @@ +/// Source : https://leetcode.com/problems/pascals-triangle-ii/description/ +/// Author : liuyubobobo +/// Time : 2018-08-10 + +#include +#include + +using namespace std; + + +/// Simulate Pascal Triangle with only O(n) space +/// +/// Time Complexity: O(rowIndex^2) +/// Space Complexity: O(rowIndex) +class Solution { +public: + vector getRow(int rowIndex) { + vector> res(2, vector(rowIndex + 1, 1)); + for(int i = 2; i <= rowIndex ; i ++) + for(int j = 1; j < i; j ++ ) + res[i&1][j] = res[(i-1)&1][j-1] + res[(i-1)&1][j]; + return res[rowIndex&1]; + } +}; + + +void print_vec(const vector& vec){ + for(int e: vec) + cout << e << " "; + cout << endl; +} + +int main() { + + for(int i = 0 ; i < 10 ; i ++) + print_vec(Solution().getRow(i)); + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0119-Pascals-Triangle-II/cpp-0119/main3.cpp b/0001-0500/0119-Pascals-Triangle-II/cpp-0119/main3.cpp new file mode 100644 index 00000000..d9993a7f --- /dev/null +++ b/0001-0500/0119-Pascals-Triangle-II/cpp-0119/main3.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/pascals-triangle-ii/description/ +/// Author : liuyubobobo +/// Time : 2018-08-10 + +#include +#include + +using namespace std; + + +/// Using Binomial Coefficients +/// +/// Time Complexity: O(rowIndex^2) +/// Space Complexity: O(rowIndex) +class Solution { +public: + vector getRow(int rowIndex) { + vector res(rowIndex + 1, 1); + for(int i = 1; i <= (rowIndex + 1) / 2; i ++) + res[i] = res[rowIndex - i] = C(rowIndex, i); + return res; + } + +private: + int C(int m, int n){ + long long up = 1ll; + int down1 = n, down2 = m - n; + for(int i = m; i > 0; i --){ + up *= i; + if(down1 && up % down1 == 0ll) up /= down1, down1 --; + if(down2 && up % down2 == 0ll) up /= down2, down2 --; + } + return up; + } +}; + + +void print_vec(const vector& vec){ + for(int e: vec) + cout << e << " "; + cout << endl; +} + +int main() { + + for(int i = 0 ; i < 10 ; i ++) + print_vec(Solution().getRow(i)); + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0119-Pascals-Triangle-II/cpp-0119/main4.cpp b/0001-0500/0119-Pascals-Triangle-II/cpp-0119/main4.cpp new file mode 100644 index 00000000..64f7bb9d --- /dev/null +++ b/0001-0500/0119-Pascals-Triangle-II/cpp-0119/main4.cpp @@ -0,0 +1,39 @@ +/// Source : https://leetcode.com/problems/pascals-triangle-ii/description/ +/// Author : liuyubobobo +/// Time : 2018-08-10 + +#include +#include + +using namespace std; + + +/// Using Binomial Coefficients Recurrence Relationship +/// Using C(m, n) = (m - n + 1) / n * C(m, n - 1) +/// +/// Time Complexity: O(rowIndex) +/// Space Complexity: O(rowIndex) +class Solution { +public: + vector getRow(int rowIndex) { + vector res(rowIndex + 1, 1); + for(int i = 1; i <= (rowIndex + 1) / 2; i ++) + res[i] = res[rowIndex - i] = (long long)(rowIndex - i + 1) * res[i - 1] / i; + return res; + } +}; + + +void print_vec(const vector& vec){ + for(int e: vec) + cout << e << " "; + cout << endl; +} + +int main() { + + for(int i = 0 ; i < 10 ; i ++) + print_vec(Solution().getRow(i)); + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0120-Triangle/cpp-0120/CMakeLists.txt b/0001-0500/0120-Triangle/cpp-0120/CMakeLists.txt new file mode 100644 index 00000000..be4d0a64 --- /dev/null +++ b/0001-0500/0120-Triangle/cpp-0120/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0120) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main2.cpp) +add_executable(cpp_0120 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0120-Triangle/cpp-0120/main.cpp b/0001-0500/0120-Triangle/cpp-0120/main.cpp new file mode 100644 index 00000000..f94c5394 --- /dev/null +++ b/0001-0500/0120-Triangle/cpp-0120/main.cpp @@ -0,0 +1,41 @@ +/// Source : https://leetcode.com/problems/triangle/description/ +/// Author : liuyubobobo +/// Time : 2018-03-26 + +#include +#include + +using namespace std; + +/// Dynamic Programming +/// Time Complexity: O(n^2) +/// Space Complexity: O(1) +class Solution { +public: + int minimumTotal(vector>& triangle) { + + int n = triangle.size(); + for(int i = 1 ; i < n ; i ++){ + + triangle[i][0] += triangle[i-1][0]; + triangle[i][i] += triangle[i-1][i-1]; + for(int j = 1 ; j < i ; j ++) + triangle[i][j] += min(triangle[i-1][j-1], triangle[i-1][j]); + } + + return *min_element(triangle[n-1].begin(), triangle[n-1].end()); + } +}; + + +int main() { + + vector> triangle = { {2}, + {3, 4}, + {6,5,7}, + {4,1,8,3}}; + cout << Solution().minimumTotal(triangle) << endl; + // 11 + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0120-Triangle/cpp-0120/main2.cpp b/0001-0500/0120-Triangle/cpp-0120/main2.cpp new file mode 100644 index 00000000..cc97bfd3 --- /dev/null +++ b/0001-0500/0120-Triangle/cpp-0120/main2.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/triangle/description/ +/// Author : liuyubobobo +/// Time : 2018-12-19 + +#include +#include + +using namespace std; + +/// Memory Search +/// Time Complexity: O(n^2) +/// Space Complexity: O(1) +class Solution { +public: + int minimumTotal(vector>& triangle) { + + int n = triangle.size(); + vector> dp(n, vector(n, -1)); + for(int i = 0 ; i < n ; i ++) + go(triangle, n - 1, i, dp); + + return *min_element(dp[n-1].begin(), dp[n-1].end()); + } + +private: + int go(const vector>& triangle, int i, int j, + vector>& dp){ + + if(dp[i][j] != -1) + return dp[i][j]; + + if(i == 0) + return dp[i][j] = triangle[i][j]; + + if(j == 0) + return dp[i][j] = triangle[i][j] + go(triangle, i - 1, 0, dp); + + if(j == i) + return dp[i][j] = triangle[i][j] + go(triangle, i - 1, i - 1, dp); + + return dp[i][j] = triangle[i][j] + min(go(triangle, i - 1, j - 1, dp), + go(triangle, i - 1, j, dp)); + } +}; + + +int main() { + + vector> triangle = { {2}, + {3, 4}, + {6,5,7}, + {4,1,8,3}}; + cout << Solution().minimumTotal(triangle) << endl; + // 11 + + return 0; +} \ No newline at end of file diff --git a/0121-Best-Time-to-Buy-and-Sell-Stock/cpp-0121/CMakeLists.txt b/0001-0500/0121-Best-Time-to-Buy-and-Sell-Stock/cpp-0121/CMakeLists.txt similarity index 100% rename from 0121-Best-Time-to-Buy-and-Sell-Stock/cpp-0121/CMakeLists.txt rename to 0001-0500/0121-Best-Time-to-Buy-and-Sell-Stock/cpp-0121/CMakeLists.txt diff --git a/0121-Best-Time-to-Buy-and-Sell-Stock/cpp-0121/main.cpp b/0001-0500/0121-Best-Time-to-Buy-and-Sell-Stock/cpp-0121/main.cpp similarity index 100% rename from 0121-Best-Time-to-Buy-and-Sell-Stock/cpp-0121/main.cpp rename to 0001-0500/0121-Best-Time-to-Buy-and-Sell-Stock/cpp-0121/main.cpp diff --git a/0122-Best-Time-to-Buy-and-Sell-Stock-II/cpp-0122/CMakeLists.txt b/0001-0500/0122-Best-Time-to-Buy-and-Sell-Stock-II/cpp-0122/CMakeLists.txt similarity index 100% rename from 0122-Best-Time-to-Buy-and-Sell-Stock-II/cpp-0122/CMakeLists.txt rename to 0001-0500/0122-Best-Time-to-Buy-and-Sell-Stock-II/cpp-0122/CMakeLists.txt diff --git a/0122-Best-Time-to-Buy-and-Sell-Stock-II/cpp-0122/main.cpp b/0001-0500/0122-Best-Time-to-Buy-and-Sell-Stock-II/cpp-0122/main.cpp similarity index 100% rename from 0122-Best-Time-to-Buy-and-Sell-Stock-II/cpp-0122/main.cpp rename to 0001-0500/0122-Best-Time-to-Buy-and-Sell-Stock-II/cpp-0122/main.cpp diff --git a/0122-Best-Time-to-Buy-and-Sell-Stock-II/cpp-0122/main2.cpp b/0001-0500/0122-Best-Time-to-Buy-and-Sell-Stock-II/cpp-0122/main2.cpp similarity index 100% rename from 0122-Best-Time-to-Buy-and-Sell-Stock-II/cpp-0122/main2.cpp rename to 0001-0500/0122-Best-Time-to-Buy-and-Sell-Stock-II/cpp-0122/main2.cpp diff --git a/0123-Best-Time-to-Buy-and-Sell-Stock-III/cpp-0123/CMakeLists.txt b/0001-0500/0123-Best-Time-to-Buy-and-Sell-Stock-III/cpp-0123/CMakeLists.txt similarity index 100% rename from 0123-Best-Time-to-Buy-and-Sell-Stock-III/cpp-0123/CMakeLists.txt rename to 0001-0500/0123-Best-Time-to-Buy-and-Sell-Stock-III/cpp-0123/CMakeLists.txt diff --git a/0123-Best-Time-to-Buy-and-Sell-Stock-III/cpp-0123/main.cpp b/0001-0500/0123-Best-Time-to-Buy-and-Sell-Stock-III/cpp-0123/main.cpp similarity index 100% rename from 0123-Best-Time-to-Buy-and-Sell-Stock-III/cpp-0123/main.cpp rename to 0001-0500/0123-Best-Time-to-Buy-and-Sell-Stock-III/cpp-0123/main.cpp diff --git a/0123-Best-Time-to-Buy-and-Sell-Stock-III/cpp-0123/main2.cpp b/0001-0500/0123-Best-Time-to-Buy-and-Sell-Stock-III/cpp-0123/main2.cpp similarity index 100% rename from 0123-Best-Time-to-Buy-and-Sell-Stock-III/cpp-0123/main2.cpp rename to 0001-0500/0123-Best-Time-to-Buy-and-Sell-Stock-III/cpp-0123/main2.cpp diff --git a/0001-0500/0124-Binary-Tree-Maximum-Path-Sum/cpp-0124/CMakeLists.txt b/0001-0500/0124-Binary-Tree-Maximum-Path-Sum/cpp-0124/CMakeLists.txt new file mode 100644 index 00000000..a3d81545 --- /dev/null +++ b/0001-0500/0124-Binary-Tree-Maximum-Path-Sum/cpp-0124/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(cpp_0124) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(cpp_0124 main2.cpp) \ No newline at end of file diff --git a/0001-0500/0124-Binary-Tree-Maximum-Path-Sum/cpp-0124/main.cpp b/0001-0500/0124-Binary-Tree-Maximum-Path-Sum/cpp-0124/main.cpp new file mode 100644 index 00000000..3a45f8a6 --- /dev/null +++ b/0001-0500/0124-Binary-Tree-Maximum-Path-Sum/cpp-0124/main.cpp @@ -0,0 +1,58 @@ +/// Source : https://leetcode.com/problems/binary-tree-maximum-path-sum/ +/// Author : liuyubobobo +/// Time : 2019-08-09 + +#include +#include + +using namespace std; + + +/// Two Pass DFS +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// 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 { + +private: + unordered_map map; + int res = INT_MIN; + +public: + int maxPathSum(TreeNode* root) { + + dfs1(root); + dfs2(root); + return res; + } + +private: + void dfs2(TreeNode* node){ + + if(!node) return; + res = max(res, node->val + max(0, map[node->left]) + max(0, map[node->right])); + dfs2(node->left); + dfs2(node->right); + } + + int dfs1(TreeNode* node){ + + int left = node->left ? dfs1(node->left) : 0; + int right = node->right ? dfs1(node->right) : 0; + return map[node] = node->val + max(0, max(left, right)); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0124-Binary-Tree-Maximum-Path-Sum/cpp-0124/main2.cpp b/0001-0500/0124-Binary-Tree-Maximum-Path-Sum/cpp-0124/main2.cpp new file mode 100644 index 00000000..6e4e0b79 --- /dev/null +++ b/0001-0500/0124-Binary-Tree-Maximum-Path-Sum/cpp-0124/main2.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/binary-tree-maximum-path-sum/ +/// Author : liuyubobobo +/// Time : 2019-08-09 + +#include +#include + +using namespace std; + + +/// One Pass DFS +/// Time Complexity: O(n) +/// Space Complexity: O(h) + +/// 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 { + +private: + int res = INT_MIN; + +public: + int maxPathSum(TreeNode* root) { + dfs(root); + return res; + } + +private: + int dfs(TreeNode* node){ + + int left = node->left ? dfs(node->left) : 0; + int right = node->right ? dfs(node->right) : 0; + + res = max(res, node->val + max(0, left) + max(0, right)); + + return node->val + max(0, max(left, right)); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0125-Valid-Palindrome/cpp-0125/CMakeLists.txt b/0001-0500/0125-Valid-Palindrome/cpp-0125/CMakeLists.txt new file mode 100644 index 00000000..46e7762d --- /dev/null +++ b/0001-0500/0125-Valid-Palindrome/cpp-0125/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0125) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0125 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0125-Valid-Palindrome/cpp-0125/main.cpp b/0001-0500/0125-Valid-Palindrome/cpp-0125/main.cpp new file mode 100644 index 00000000..f49651f2 --- /dev/null +++ b/0001-0500/0125-Valid-Palindrome/cpp-0125/main.cpp @@ -0,0 +1,59 @@ +/// Source : https://leetcode.com/problems/valid-palindrome/description/ +/// Author : liuyubobobo +/// Time : 2018-05-27 + +#include + +using namespace std; + + +/// Two Pointers +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { + +public: + bool isPalindrome(string s) { + + int i = next_alpha_numeric(s, 0); + int j = prev_alpha_numeric(s, s.size() - 1); + while(i <= j){ + if(tolower(s[i]) != tolower(s[j])) + return false; + i = next_alpha_numeric(s, i + 1); + j = prev_alpha_numeric(s, j - 1); + } + return true; + } + +private: + int next_alpha_numeric(const string& s, int index){ + for(int i = index ; i < s.size() ; i ++) + if(isalnum(s[i])) + return i; + return s.size(); + } + + int prev_alpha_numeric(const string& s, int index){ + for(int i = index ; i >= 0 ; i --) + if(isalnum(s[i])) + return i; + return -1; + } +}; + + +void print_bool(bool res){ + cout << (res ? "True" : "False") << endl; +} + +int main() { + + string s1 = "A man, a plan, a canal: Panama"; + print_bool(Solution().isPalindrome(s1)); + + string s2 = "race a car"; + print_bool(Solution().isPalindrome(s2)); + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0126-Word-Ladder-II/cpp-0126/CMakeLists.txt b/0001-0500/0126-Word-Ladder-II/cpp-0126/CMakeLists.txt new file mode 100644 index 00000000..1735ca9a --- /dev/null +++ b/0001-0500/0126-Word-Ladder-II/cpp-0126/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0127) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0127 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0126-Word-Ladder-II/cpp-0126/main.cpp b/0001-0500/0126-Word-Ladder-II/cpp-0126/main.cpp new file mode 100644 index 00000000..84ea4303 --- /dev/null +++ b/0001-0500/0126-Word-Ladder-II/cpp-0126/main.cpp @@ -0,0 +1,137 @@ +/// Source : https://leetcode.com/problems/word-ladder-ii/description/ +/// Author : liuyubobobo +/// Time : 2018-04-23 +/// Updated: 2022-08-10 + +#include +#include +#include +#include + +using namespace std; + + +/// BFS + Backtrack +/// Attention: backtrack from begin to end will get TLE +/// The following solution will backtrack result in reverse (from end to begin) +/// +/// Time Complexity: O(?) +/// Space Complexity: O(?) +class Solution { + +public: + vector> findLadders(string beginWord, string endWord, vector& wordList) { + + int end = find(wordList.begin(), wordList.end(), endWord) - wordList.begin(); + if(end == wordList.size()) + return {}; + + int begin = find(wordList.begin(), wordList.end(), beginWord) - wordList.begin(); + if(begin == wordList.size()) + wordList.push_back(beginWord); + + int n = wordList.size(); + + // Create Graph + vector> g(n); + for(int i = 0 ; i < wordList.size() ; i ++) + for(int j = i + 1 ; j < wordList.size() ; j ++) + if(similar(wordList[i], wordList[j])){ + g[i].push_back(j); + g[j].push_back(i); + } + + vector distance = bfs(n, g, begin); + if(distance[end] == -1) return {}; + + vector> res; + vector tres = {wordList[end]}; + get_res(g, end, begin, distance, wordList, tres, res); + + return res; + } + +private: + vector bfs(int n, const vector>& g, int begin){ + + vector distance(n, -1); + + queue q; + q.push(begin); + distance[begin] = 0; + + while(!q.empty()){ + int cur = q.front(); q.pop(); + + for(int j: g[cur]) + if(distance[j] == -1){ + distance[j] = distance[cur] + 1; + q.push(j); + } + } + + return distance; + } + + void get_res(vector>& g, int cur, int end, + const vector& distance, + const vector& wordList, + vector& tres, vector>& res){ + + if(tres.size() > 0 && tres[tres.size() - 1] == wordList[end]){ + res.push_back(tres); + reverse(res.back().begin(), res.back().end()); + return; + } + + for(int i: g[cur]) + if(distance[i] == distance[cur] - 1){ + tres.push_back(wordList[i]); + get_res(g, i, end, distance, wordList, tres, res); + tres.pop_back(); + } + + return; + } + + bool similar(const string& word1, const string& word2){ + + // assert(word1 != "" && word1.size() == word2.size() && word1 != word2); + + int diff = 0; + for(int i = 0 ; i < word1.size() ; i ++) + if(word1[i] != word2[i]){ + diff ++; + if(diff > 1) + return false; + } + return true; + } +}; + + +void print_vector(const vector>& res){ + for(const vector& v: res){ + for(const string& e: v) + cout << e << " "; + cout << endl; + } + cout << endl; +} + +int main() { + + vector vec1 = {"hot","dot","dog","lot","log","cog"}; + string beginWord1 = "hit"; + string endWord1 = "cog"; + vector> res1 = Solution().findLadders(beginWord1, endWord1, vec1); + print_vector(res1); + + vector vec2 = {"a","b","c"}; + string beginWord2 = "a"; + string endWord2 = "c"; + vector> res2 = Solution().findLadders(beginWord2, endWord2, vec2); + print_vector(res2); + + return 0; +} \ No newline at end of file diff --git a/0127-Word-Ladder/cpp-0127/CMakeLists.txt b/0001-0500/0127-Word-Ladder/cpp-0127/CMakeLists.txt similarity index 100% rename from 0127-Word-Ladder/cpp-0127/CMakeLists.txt rename to 0001-0500/0127-Word-Ladder/cpp-0127/CMakeLists.txt diff --git a/0127-Word-Ladder/cpp-0127/main.cpp b/0001-0500/0127-Word-Ladder/cpp-0127/main.cpp similarity index 100% rename from 0127-Word-Ladder/cpp-0127/main.cpp rename to 0001-0500/0127-Word-Ladder/cpp-0127/main.cpp diff --git a/0127-Word-Ladder/cpp-0127/main2.cpp b/0001-0500/0127-Word-Ladder/cpp-0127/main2.cpp similarity index 100% rename from 0127-Word-Ladder/cpp-0127/main2.cpp rename to 0001-0500/0127-Word-Ladder/cpp-0127/main2.cpp diff --git a/0127-Word-Ladder/cpp-0127/main3.cpp b/0001-0500/0127-Word-Ladder/cpp-0127/main3.cpp similarity index 100% rename from 0127-Word-Ladder/cpp-0127/main3.cpp rename to 0001-0500/0127-Word-Ladder/cpp-0127/main3.cpp diff --git a/0127-Word-Ladder/cpp-0127/main4.cpp b/0001-0500/0127-Word-Ladder/cpp-0127/main4.cpp similarity index 100% rename from 0127-Word-Ladder/cpp-0127/main4.cpp rename to 0001-0500/0127-Word-Ladder/cpp-0127/main4.cpp diff --git a/0127-Word-Ladder/java-0127/src/Solution.java b/0001-0500/0127-Word-Ladder/java-0127/src/Solution.java similarity index 100% rename from 0127-Word-Ladder/java-0127/src/Solution.java rename to 0001-0500/0127-Word-Ladder/java-0127/src/Solution.java diff --git a/0127-Word-Ladder/java-0127/src/Solution2.java b/0001-0500/0127-Word-Ladder/java-0127/src/Solution2.java similarity index 100% rename from 0127-Word-Ladder/java-0127/src/Solution2.java rename to 0001-0500/0127-Word-Ladder/java-0127/src/Solution2.java diff --git a/0127-Word-Ladder/java-0127/src/Solution3.java b/0001-0500/0127-Word-Ladder/java-0127/src/Solution3.java similarity index 100% rename from 0127-Word-Ladder/java-0127/src/Solution3.java rename to 0001-0500/0127-Word-Ladder/java-0127/src/Solution3.java diff --git a/0127-Word-Ladder/java-0127/src/Solution4.java b/0001-0500/0127-Word-Ladder/java-0127/src/Solution4.java similarity index 100% rename from 0127-Word-Ladder/java-0127/src/Solution4.java rename to 0001-0500/0127-Word-Ladder/java-0127/src/Solution4.java diff --git a/0128-Longest-Consecutive-Sequence/cpp-0128/CMakeLists.txt b/0001-0500/0128-Longest-Consecutive-Sequence/cpp-0128/CMakeLists.txt similarity index 100% rename from 0128-Longest-Consecutive-Sequence/cpp-0128/CMakeLists.txt rename to 0001-0500/0128-Longest-Consecutive-Sequence/cpp-0128/CMakeLists.txt diff --git a/0128-Longest-Consecutive-Sequence/cpp-0128/main.cpp b/0001-0500/0128-Longest-Consecutive-Sequence/cpp-0128/main.cpp similarity index 100% rename from 0128-Longest-Consecutive-Sequence/cpp-0128/main.cpp rename to 0001-0500/0128-Longest-Consecutive-Sequence/cpp-0128/main.cpp diff --git a/0128-Longest-Consecutive-Sequence/cpp-0128/main2.cpp b/0001-0500/0128-Longest-Consecutive-Sequence/cpp-0128/main2.cpp similarity index 100% rename from 0128-Longest-Consecutive-Sequence/cpp-0128/main2.cpp rename to 0001-0500/0128-Longest-Consecutive-Sequence/cpp-0128/main2.cpp diff --git a/0128-Longest-Consecutive-Sequence/cpp-0128/main3.cpp b/0001-0500/0128-Longest-Consecutive-Sequence/cpp-0128/main3.cpp similarity index 100% rename from 0128-Longest-Consecutive-Sequence/cpp-0128/main3.cpp rename to 0001-0500/0128-Longest-Consecutive-Sequence/cpp-0128/main3.cpp diff --git a/0001-0500/0129-Sum-Root-to-Leaf-Numbers/cpp-0129/CMakeLists.txt b/0001-0500/0129-Sum-Root-to-Leaf-Numbers/cpp-0129/CMakeLists.txt new file mode 100644 index 00000000..e49c5884 --- /dev/null +++ b/0001-0500/0129-Sum-Root-to-Leaf-Numbers/cpp-0129/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0129) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0129 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0129-Sum-Root-to-Leaf-Numbers/cpp-0129/main.cpp b/0001-0500/0129-Sum-Root-to-Leaf-Numbers/cpp-0129/main.cpp new file mode 100644 index 00000000..59081a97 --- /dev/null +++ b/0001-0500/0129-Sum-Root-to-Leaf-Numbers/cpp-0129/main.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/sum-root-to-leaf-numbers/description/ +/// Author : liuyubobobo +/// Time : 2018-10-16 + +#include + +using namespace std; + + +/// Recursion +/// Time Complexity: O(n) +/// Space Complexity: O(logn) + +/// 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: + int sumNumbers(TreeNode* root) { + + if(!root) return 0; + + int res = 0; + dfs(root, 0, res); + return res; + } + +private: + void dfs(TreeNode* node, int tnum, int& sum){ + + tnum = tnum * 10 + node->val; + + if(!node->left && !node->right) + sum += tnum; + else{ + if(node->left) + dfs(node->left, tnum, sum); + if(node->right) + dfs(node->right, tnum, sum); + } + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0130-Surrounded-Regions/cpp-0130/CMakeLists.txt b/0001-0500/0130-Surrounded-Regions/cpp-0130/CMakeLists.txt new file mode 100644 index 00000000..a5f1bbd5 --- /dev/null +++ b/0001-0500/0130-Surrounded-Regions/cpp-0130/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_Surrounded_Regions) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_Surrounded_Regions ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0130-Surrounded-Regions/cpp-0130/main.cpp b/0001-0500/0130-Surrounded-Regions/cpp-0130/main.cpp new file mode 100644 index 00000000..221e8d94 --- /dev/null +++ b/0001-0500/0130-Surrounded-Regions/cpp-0130/main.cpp @@ -0,0 +1,132 @@ +/// Source : https://leetcode.com/problems/two-sum/description/ +/// Author : liuyubobobo +/// Time : 2017-07-13 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// BFS +/// Time Complexity: O(m*n) +/// Space Complexity: O(m*n) +/// +/// This problem is amazing! Because using DFS will lead to Runtime Error, +/// Because in some specific cases, the recursive depth might be too high +/// The following is an example: +/// OOOOOOOOO +/// XXXXXXXXO +/// OOOOOOOXO +/// OXXXXXOXO +/// OXOOOXOXO +/// OXOXOXOXO +/// OXOXXXOXO +/// OXOOOOOXO +/// OXXXXXXXO +/// OOOOOOOOO +/// +/// We can see, in above test case, the complexity of recursive depth is O(n*m), +/// where n and m describe the size of board. +/// Obviously, it's too high! +class Solution { +private: + int m, n; + int d[4][2] = {{0,1}, {1,0}, {0,-1}, {-1,0}}; + +private: + bool inArea(int x, int y){ + return x >= 0 && y >= 0 && x < m && y < n; + } + + bool bfs(const vector> &board, int x, int y, + vector>& visited, vector>& record){ + + queue> q; + + // return true if we can only get to 'X' during BFS, + // otherwise, return false + bool ret = true; + + visited[x][y] = true; + q.push(pair(x, y)); + while( !q.empty()){ + pair cur = q.front(); + q.pop(); + record.push_back(pair(cur.first, cur.second)); + + for(int i = 0 ; i < 4 ;i ++){ + int newX = cur.first + d[i][0]; + int newY = cur.second + d[i][1]; + + if(!inArea(newX, newY)) + // If newX, newY is not in the area, + // it means we get out of the board in this BFS, + // we need to return false in this case + ret = false; + else if(board[newX][newY] == 'O' && !visited[newX][newY]){ + visited[newX][newY] = true; + q.push(pair(newX, newY)); + } + } + } + + return ret; + } + +public: + void solve(vector>& board) { + m = board.size(); + if(m == 0) + return; + n = board[0].size(); + if(n == 0) + return; + + vector> visited(m, vector(n, false)); + vector> record; + for (int i = 0; i < m; i++) + for (int j = 0; j < n; j++) + if (board[i][j] == 'O' && !visited[i][j]){ + // clear record before each time we run BFS + record.clear(); + if(bfs(board, i, j, visited, record)) + // If BFS return true, + // means from this position, + // we will not get out of the board. + // As a result, we can make every position we visited in this BFS from 'O' to 'X' + for(int k = 0 ; k < record.size() ; k ++) + board[record[k].first][record[k].second] = 'X'; + } + + return; + } +}; + + +int main(){ + + int n = 4, m = 4; + string board_array[] = { + "XXXX", + "XOOX", + "XXOX", + "XOXX"}; + vector> board = vector>(n, vector(m, ' ')); + for(int i = 0 ; i < n ; i ++) + for(int j = 0 ; j < m ; j ++) + board[i][j] = board_array[i][j]; + + Solution().solve(board); + + for(int i = 0 ; i < n ; i ++){ + for(int j = 0 ; j < m ; j ++) + cout << board[i][j]; + cout << endl; + } + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0131-Palindrome-Partitioning/cpp-0131/CMakeLists.txt b/0001-0500/0131-Palindrome-Partitioning/cpp-0131/CMakeLists.txt new file mode 100644 index 00000000..8586a053 --- /dev/null +++ b/0001-0500/0131-Palindrome-Partitioning/cpp-0131/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0131) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0131 main.cpp) \ No newline at end of file diff --git a/0001-0500/0131-Palindrome-Partitioning/cpp-0131/main.cpp b/0001-0500/0131-Palindrome-Partitioning/cpp-0131/main.cpp new file mode 100644 index 00000000..b98dae38 --- /dev/null +++ b/0001-0500/0131-Palindrome-Partitioning/cpp-0131/main.cpp @@ -0,0 +1,49 @@ +#include +#include + +using namespace std; + + +class Solution { +public: + vector> partition(string s) { + + vector> res; + vector cur; + dfs(s, 0, cur, res); + return res; + } + +private: + void dfs(const string& s, int l, vector& cur, + vector>& res){ + + if(l == s.size()){ + res.push_back(cur); + return; + } + + for(int r = l; r < s.size(); r ++) + if(ispalindrome(s, l, r)){ + cur.push_back(s.substr(l, r + 1 - l)); + dfs(s, r + 1, cur, res); + cur.pop_back(); + } + } + + bool ispalindrome(const string& s, int l, int r){ + + while(l <= r){ + if(s[l] != s[r]) return false; + l ++, r --; + } + return true; + } +}; + + +int main() { + + Solution().partition("efe"); + return 0; +} diff --git a/0001-0500/0132-Palindrome-Partitioning-II/cpp-0132/CMakeLists.txt b/0001-0500/0132-Palindrome-Partitioning-II/cpp-0132/CMakeLists.txt new file mode 100644 index 00000000..324cb07e --- /dev/null +++ b/0001-0500/0132-Palindrome-Partitioning-II/cpp-0132/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0132) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0132 main.cpp) \ No newline at end of file diff --git a/0001-0500/0132-Palindrome-Partitioning-II/cpp-0132/main.cpp b/0001-0500/0132-Palindrome-Partitioning-II/cpp-0132/main.cpp new file mode 100644 index 00000000..a96dba50 --- /dev/null +++ b/0001-0500/0132-Palindrome-Partitioning-II/cpp-0132/main.cpp @@ -0,0 +1,55 @@ +/// Source : https://leetcode.com/problems/palindrome-partitioning-ii/ +/// Author : liuyubobobo +/// Time : 2021-01-30 + +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(n^2) +/// Space Complexity: O(n^2) +class Solution { +public: + int minCut(string s) { + + int n = s.size(); + + vector> dp(n + 1); + dp[1] = vector(n, true); + for(int i = 0; i + 1 < n; i ++) + dp[2].push_back(s[i] == s[i + 1]); + + for(int sz = 3; sz <= n; sz ++) + for(int i = 0; i + sz <= n; i ++) + dp[sz].push_back((s[i] == s[i + sz - 1]) && dp[sz - 2][i + 1]); + + vector res(n + 1, INT_MAX); + res[n] = 0; + for(int i = n - 1; i >= 0; i --){ + for(int sz = 1; i + sz <= n; sz ++) + if(dp[sz][i]) res[i] = min(res[i], 1 + res[i + sz]); + } + return res[0] - 1; + } +}; + + +int main() { + + cout << Solution().minCut("aab") << endl; + // 1 + + cout << Solution().minCut("a") << endl; + // 0 + + cout << Solution().minCut("ab") << endl; + // 1 + + cout << Solution().minCut("aaabaa") << endl; + // 1 + + return 0; +} diff --git a/0001-0500/0133-Clone-Graph/cpp-0133/CMakeLists.txt b/0001-0500/0133-Clone-Graph/cpp-0133/CMakeLists.txt new file mode 100644 index 00000000..06e51fa4 --- /dev/null +++ b/0001-0500/0133-Clone-Graph/cpp-0133/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0133) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main3.cpp) +add_executable(cpp_0133 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0133-Clone-Graph/cpp-0133/main.cpp b/0001-0500/0133-Clone-Graph/cpp-0133/main.cpp new file mode 100644 index 00000000..fe1febcf --- /dev/null +++ b/0001-0500/0133-Clone-Graph/cpp-0133/main.cpp @@ -0,0 +1,76 @@ +/// Source : https://leetcode.com/problems/clone-graph/description/ +/// Author : liuyubobobo +/// Time : 2018-08-30 +/// Updated: 2022-02-22 + +#include +#include +#include +#include + +using namespace std; + +/// Definition for undirected graph. +class Node { +public: + int val; + vector neighbors; + Node() { + val = 0; + neighbors = vector(); + } + Node(int _val) { + val = _val; + neighbors = vector(); + } + Node(int _val, vector _neighbors) { + val = _val; + neighbors = _neighbors; + } +}; + +/// Using Two Stacks and HashMap from label to Node +/// Time Complexity: O(V+E) +/// Space Complexity: O(V) +class Solution { +public: + Node *cloneGraph(Node *node) { + + if(node == NULL) + return NULL; + + Node* ret = new Node(node->val); + + stack stack1; + stack1.push(node); + unordered_map visited; + visited[ret->val] = ret; + + stack stack2; + stack2.push(ret); + + while(!stack1.empty()){ + Node* old_cur = stack1.top(); + stack1.pop(); + + Node* new_cur = stack2.top(); + stack2.pop(); + + for(Node *next: old_cur->neighbors) { + if (visited.find(next->val) == visited.end()) { + visited[next->val] = new Node(next->val); + stack1.push(next); + stack2.push(visited[next->val]); + } + new_cur->neighbors.push_back(visited[next->val]); + } + } + return ret; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0133-Clone-Graph/cpp-0133/main2.cpp b/0001-0500/0133-Clone-Graph/cpp-0133/main2.cpp new file mode 100644 index 00000000..79e81058 --- /dev/null +++ b/0001-0500/0133-Clone-Graph/cpp-0133/main2.cpp @@ -0,0 +1,66 @@ +/// Source : https://leetcode.com/problems/clone-graph/description/ +/// Author : liuyubobobo +/// Time : 2018-09-14 +/// Updated: 2022-02-22 + +#include +#include +#include +#include + +using namespace std; + +/// Definition for undirected graph. +class Node { +public: + int val; + vector neighbors; + Node() { + val = 0; + neighbors = vector(); + } + Node(int _val) { + val = _val; + neighbors = vector(); + } + Node(int _val, vector _neighbors) { + val = _val; + neighbors = _neighbors; + } +}; + +/// Using Only One Stacks and HashMap from Node to Node +/// Time Complexity: O(V+E) +/// Space Complexity: O(V) +class Solution { +public: + Node *cloneGraph(Node *node) { + + if(node == NULL) + return NULL; + + Node* ret = new Node(node->val); + stack stack; + stack.push(node); + unordered_map nodeMap; + nodeMap[node] = ret; + while(!stack.empty()){ + Node* cur = stack.top(); + stack.pop(); + for(Node *next: cur->neighbors) { + if (!nodeMap.count(next)) { + nodeMap[next] = new Node(next->val); + stack.push(next); + } + nodeMap[cur]->neighbors.push_back(nodeMap[next]); + } + } + return ret; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0133-Clone-Graph/cpp-0133/main3.cpp b/0001-0500/0133-Clone-Graph/cpp-0133/main3.cpp new file mode 100644 index 00000000..4b953d0c --- /dev/null +++ b/0001-0500/0133-Clone-Graph/cpp-0133/main3.cpp @@ -0,0 +1,63 @@ +/// Source : https://leetcode.com/problems/clone-graph/description/ +/// Author : liuyubobobo +/// Time : 2018-09-14 +/// Updated: 2022-02-22 + +#include +#include +#include + +using namespace std; + +/// Definition for undirected graph. +class Node { +public: + int val; + vector neighbors; + Node() { + val = 0; + neighbors = vector(); + } + Node(int _val) { + val = _val; + neighbors = vector(); + } + Node(int _val, vector _neighbors) { + val = _val; + neighbors = _neighbors; + } +}; + +/// DFS +/// Time Complexity: O(V+E) +/// Space Complexity: O(V) +class Solution { + +public: + Node *cloneGraph(Node *node) { + + if(node == NULL) + return NULL; + + unordered_map nodeMap; + return dfs(node, nodeMap); + } + +private: + Node *dfs(Node *node, unordered_map& nodeMap){ + + if(nodeMap.count(node)) + return nodeMap[node]; + + nodeMap[node] = new Node(node->val); + for(Node* next: node->neighbors) + nodeMap[node]->neighbors.push_back(dfs(next, nodeMap)); + return nodeMap[node]; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0134-Gas-Station/cpp-0134/CMakeLists.txt b/0001-0500/0134-Gas-Station/cpp-0134/CMakeLists.txt new file mode 100644 index 00000000..6653f898 --- /dev/null +++ b/0001-0500/0134-Gas-Station/cpp-0134/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(cpp_0134) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0134 main2.cpp) \ No newline at end of file diff --git a/0001-0500/0134-Gas-Station/cpp-0134/main.cpp b/0001-0500/0134-Gas-Station/cpp-0134/main.cpp new file mode 100644 index 00000000..5b14d19b --- /dev/null +++ b/0001-0500/0134-Gas-Station/cpp-0134/main.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/gas-station/ +/// Author : liuyubobobo +/// Time : 2019-03-16 + +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int canCompleteCircuit(vector& gas, vector& cost) { + + int n = gas.size(); + + int minv = INT_MAX, res = -1, cur = 0; + for(int i = 0; i < n; i ++){ + cur += gas[i] - cost[i]; + if(cur < minv) minv = cur, res = i; + } + if(cur < 0) return -1; + return (res + 1) % n; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0134-Gas-Station/cpp-0134/main2.cpp b/0001-0500/0134-Gas-Station/cpp-0134/main2.cpp new file mode 100644 index 00000000..3b2a60cd --- /dev/null +++ b/0001-0500/0134-Gas-Station/cpp-0134/main2.cpp @@ -0,0 +1,38 @@ +/// Source : https://leetcode.com/problems/gas-station/ +/// Author : liuyubobobo +/// Time : 2019-03-16 + +#include +#include + +using namespace std; + + +/// Simulation +/// This solution is more intuitive, see Leetcode Official Solution for details: +/// https://leetcode.com/problems/gas-station/solution/ +/// +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int canCompleteCircuit(vector& gas, vector& cost) { + + int n = gas.size(); + + int res = 0, total = 0, cur = 0; + for(int i = 0; i < n; i ++){ + cur += gas[i] - cost[i]; + total += gas[i] - cost[i]; + if(total <= 0) res = (i + 1) % n, total = 0; + } + if(cur < 0) return -1; + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0135-Candy/cpp-0135/CMakeLists.txt b/0001-0500/0135-Candy/cpp-0135/CMakeLists.txt new file mode 100644 index 00000000..3f584f9b --- /dev/null +++ b/0001-0500/0135-Candy/cpp-0135/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(cpp_0135) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(cpp_0135 main.cpp) \ No newline at end of file diff --git a/0001-0500/0135-Candy/cpp-0135/main.cpp b/0001-0500/0135-Candy/cpp-0135/main.cpp new file mode 100644 index 00000000..7d5f1e03 --- /dev/null +++ b/0001-0500/0135-Candy/cpp-0135/main.cpp @@ -0,0 +1,41 @@ +/// Source : https://leetcode.com/problems/candy/ +/// Author : liuyubobobo +/// Time : 2018-12-10 + +#include +#include + +using namespace std; + + +/// Two arrays +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int candy(vector& ratings) { + + int n = ratings.size(); + + vector left(n, 1); + for(int i = 1; i < n; i ++) + if(ratings[i] > ratings[i - 1]) + left[i] = left[i - 1] + 1; + + vector right(n, 1); + for(int i = n - 2; i >= 0; i --) + if(ratings[i] > ratings[i + 1]) + right[i] = right[i + 1] + 1; + + int res = 0; + for(int i = 0; i < n; i ++) + res += max(left[i], right[i]); + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0135-Candy/cpp-0135/main2.cpp b/0001-0500/0135-Candy/cpp-0135/main2.cpp new file mode 100644 index 00000000..8cbae5c8 --- /dev/null +++ b/0001-0500/0135-Candy/cpp-0135/main2.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/candy/ +/// Author : liuyubobobo +/// Time : 2018-12-10 + +#include +#include +#include + +using namespace std; + + +/// Two arrays's thinking +/// But only use one array :-) +/// +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int candy(vector& ratings) { + + int n = ratings.size(); + + vector res(n, 1); + for(int i = 1; i < n; i ++) + if(ratings[i] > ratings[i - 1]) + res[i] = res[i - 1] + 1; + + for(int i = n - 2; i >= 0; i --) + if(ratings[i] > ratings[i + 1] && res[i] <= res[i + 1]) + res[i] = res[i + 1] + 1; + + return accumulate(res.begin(), res.end(), 0); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/old/0136 Single Number/cpp-Single-Number/CMakeLists.txt b/0001-0500/0136-Single-Number/cpp-0136/CMakeLists.txt similarity index 100% rename from old/0136 Single Number/cpp-Single-Number/CMakeLists.txt rename to 0001-0500/0136-Single-Number/cpp-0136/CMakeLists.txt diff --git a/0001-0500/0136-Single-Number/cpp-0136/main1.cpp b/0001-0500/0136-Single-Number/cpp-0136/main1.cpp new file mode 100644 index 00000000..489038e9 --- /dev/null +++ b/0001-0500/0136-Single-Number/cpp-0136/main1.cpp @@ -0,0 +1,41 @@ +/// Source : https://leetcode.com/problems/single-number/ +/// Author : liuyubobobo +/// Time : 2016-12-05 + +#include +#include +#include +#include + +using namespace std; + + +/// Using hashtable to find the one +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int singleNumber(vector& nums) { + + assert(nums.size()%2 == 1); + + unordered_set hashtable; + for(int i = 0 ; i < nums.size() ; i ++) + if(hashtable.find(nums[i]) == hashtable.end()) + hashtable.insert(nums[i]); + else + hashtable.erase(nums[i]); + + assert(hashtable.size() == 1); + return *hashtable.begin(); + } +}; + + +int main() { + + vector nums = {0, 0, 1, 1, 2}; + cout << Solution().singleNumber(nums) << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0136-Single-Number/cpp-0136/main2.cpp b/0001-0500/0136-Single-Number/cpp-0136/main2.cpp new file mode 100644 index 00000000..1fc8a82f --- /dev/null +++ b/0001-0500/0136-Single-Number/cpp-0136/main2.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/single-number/ +/// Author : liuyubobobo +/// Time : 2018-06-11 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// Using the sum of vector and the sum of set +/// mathematically get the result +/// +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int singleNumber(vector& nums) { + + assert(nums.size()%2 == 1); + + unordered_set set; + for(int num: nums) + set.insert(num); + + return 2 * accumulate(set.begin(), set.end(), 0) - accumulate(nums.begin(), nums.end(), 0); + } +}; + + +int main() { + + vector nums = {0, 0, 1, 1, 2}; + cout << Solution().singleNumber(nums) << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0136-Single-Number/cpp-0136/main3.cpp b/0001-0500/0136-Single-Number/cpp-0136/main3.cpp new file mode 100644 index 00000000..4721b061 --- /dev/null +++ b/0001-0500/0136-Single-Number/cpp-0136/main3.cpp @@ -0,0 +1,41 @@ +/// Source : https://leetcode.com/problems/single-number/ +/// Author : liuyubobobo +/// Time : 2016-12-05 + + +#include +#include +#include +#include +#include + +using namespace std; + + +/// Using the attribution of xor operation: +/// a ^ 0 = a +/// a ^ a = 0 +/// +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int singleNumber(vector& nums) { + + assert(nums.size()%2 == 1); + + int res = 0; + for(int i = 0 ; i < nums.size() ; i ++) + res ^= nums[i]; + return res; + } +}; + + +int main() { + + vector nums = {0, 0, 1, 1, 2}; + cout << Solution().singleNumber(nums) << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0137-Single-Number-II/cpp-0137/CMakeLists.txt b/0001-0500/0137-Single-Number-II/cpp-0137/CMakeLists.txt new file mode 100644 index 00000000..0a0d93b1 --- /dev/null +++ b/0001-0500/0137-Single-Number-II/cpp-0137/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_0137) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0137 main.cpp) \ No newline at end of file diff --git a/0001-0500/0137-Single-Number-II/cpp-0137/main.cpp b/0001-0500/0137-Single-Number-II/cpp-0137/main.cpp new file mode 100644 index 00000000..8c45a71b --- /dev/null +++ b/0001-0500/0137-Single-Number-II/cpp-0137/main.cpp @@ -0,0 +1,32 @@ +/// Source : https://leetcode.com/problems/single-number-ii/ +/// Author : liuyubobobo +/// Time : 2021-04-30 + +#include +#include +#include + +using namespace std; + + +/// Using HashMap +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int singleNumber(vector& nums) { + + unordered_map f; + for(int e: nums) f[e] ++; + + for(const pair& p: f) + if(p.second == 1) return p.first; + return -1; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0138-Copy-List-with-Random-Pointer/cpp-0138/CMakeLists.txt b/0001-0500/0138-Copy-List-with-Random-Pointer/cpp-0138/CMakeLists.txt new file mode 100644 index 00000000..4091b45f --- /dev/null +++ b/0001-0500/0138-Copy-List-with-Random-Pointer/cpp-0138/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0138) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main4.cpp) +add_executable(cpp_0138 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0138-Copy-List-with-Random-Pointer/cpp-0138/main.cpp b/0001-0500/0138-Copy-List-with-Random-Pointer/cpp-0138/main.cpp new file mode 100644 index 00000000..f2b88ce6 --- /dev/null +++ b/0001-0500/0138-Copy-List-with-Random-Pointer/cpp-0138/main.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/copy-list-with-random-pointer/description/ +/// Author : liuyubobobo +/// Time : 2018-09-14 + +#include +#include + +using namespace std; + + +/// Using HashMap +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// Definition for singly-linked list with a random pointer. +struct RandomListNode { + int label; + RandomListNode *next, *random; + RandomListNode(int x) : label(x), next(NULL), random(NULL) {} +}; + +class Solution { +public: + RandomListNode *copyRandomList(RandomListNode *head) { + + // oldNode -> newNode + unordered_map nodeMap; + + RandomListNode* dummyHead = new RandomListNode(-1); + RandomListNode* pre = dummyHead; + RandomListNode* node = head; + while(node){ + if(!nodeMap.count(node)) + nodeMap[node] = new RandomListNode(node->label); + pre->next = nodeMap[node]; + pre = pre->next; + + if(node->random){ + if(!nodeMap.count(node->random)) + nodeMap[node->random] = new RandomListNode(node->random->label); + pre->random = nodeMap[node->random]; + } + + node = node->next; + } + + RandomListNode* ret = dummyHead->next; + delete dummyHead; + return ret; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0138-Copy-List-with-Random-Pointer/cpp-0138/main2.cpp b/0001-0500/0138-Copy-List-with-Random-Pointer/cpp-0138/main2.cpp new file mode 100644 index 00000000..37cd6b1e --- /dev/null +++ b/0001-0500/0138-Copy-List-with-Random-Pointer/cpp-0138/main2.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/copy-list-with-random-pointer/description/ +/// Author : liuyubobobo +/// Time : 2018-09-14 + +#include +#include + +using namespace std; + + +/// Using HashMap +/// Treat the RandomList as a Graph and using DFS +/// +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// Definition for singly-linked list with a random pointer. +struct RandomListNode { + int label; + RandomListNode *next, *random; + RandomListNode(int x) : label(x), next(NULL), random(NULL) {} +}; + +class Solution { +public: + RandomListNode *copyRandomList(RandomListNode *head) { + + if(!head) return NULL; + + // oldNode -> newNode + unordered_map nodeMap; + return dfs(head, nodeMap); + } + +private: + RandomListNode* dfs(RandomListNode* oldNode, + unordered_map& nodeMap){ + + if(nodeMap.count(oldNode)) + return nodeMap[oldNode]; + + nodeMap[oldNode] = new RandomListNode(oldNode->label); + if(oldNode->next) + nodeMap[oldNode]->next = dfs(oldNode->next, nodeMap); + + if(oldNode->random) + nodeMap[oldNode]->random = dfs(oldNode->random, nodeMap); + + return nodeMap[oldNode]; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0138-Copy-List-with-Random-Pointer/cpp-0138/main3.cpp b/0001-0500/0138-Copy-List-with-Random-Pointer/cpp-0138/main3.cpp new file mode 100644 index 00000000..a9ce13fe --- /dev/null +++ b/0001-0500/0138-Copy-List-with-Random-Pointer/cpp-0138/main3.cpp @@ -0,0 +1,67 @@ +/// Source : https://leetcode.com/problems/copy-list-with-random-pointer/description/ +/// Author : liuyubobobo +/// Time : 2018-09-14 + +#include +#include +#include + +using namespace std; + + +/// Using HashMap +/// Treat the RandomList as a Graph and using Stack +/// +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// Definition for singly-linked list with a random pointer. +struct RandomListNode { + int label; + RandomListNode *next, *random; + RandomListNode(int x) : label(x), next(NULL), random(NULL) {} +}; + +class Solution { +public: + RandomListNode *copyRandomList(RandomListNode *head) { + + if(!head) return NULL; + + // oldNode -> newNode + unordered_map nodeMap; + + RandomListNode* ret = new RandomListNode(head->label); + stack stack; + stack.push(head); + nodeMap[head] = ret; + while(!stack.empty()){ + RandomListNode* cur = stack.top(); + stack.pop(); + + if(cur->next) { + if (!nodeMap.count(cur->next)) { + nodeMap[cur->next] = new RandomListNode(cur->next->label); + stack.push(cur->next); + } + nodeMap[cur]->next = nodeMap[cur->next]; + } + + if(cur->random){ + if(!nodeMap.count(cur->random)){ + nodeMap[cur->random] = new RandomListNode(cur->random->label); + stack.push(cur->random); + } + nodeMap[cur]->random = nodeMap[cur->random]; + } + } + + return ret; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0138-Copy-List-with-Random-Pointer/cpp-0138/main4.cpp b/0001-0500/0138-Copy-List-with-Random-Pointer/cpp-0138/main4.cpp new file mode 100644 index 00000000..dcd06c6f --- /dev/null +++ b/0001-0500/0138-Copy-List-with-Random-Pointer/cpp-0138/main4.cpp @@ -0,0 +1,63 @@ +/// Source : https://leetcode.com/problems/copy-list-with-random-pointer/description/ +/// Author : liuyubobobo +/// Time : 2018-09-14 + +#include + +using namespace std; + + +/// Link all the new nodes after every old node +/// Very fancy solution:) +/// +/// Time Complexity: O(n) +/// Space Complexity: O(1) + +/// Definition for singly-linked list with a random pointer. +struct RandomListNode { + int label; + RandomListNode *next, *random; + RandomListNode(int x) : label(x), next(NULL), random(NULL) {} +}; + +class Solution { +public: + RandomListNode *copyRandomList(RandomListNode *head) { + + if(!head) + return NULL; + + RandomListNode* cur = head; + while(cur){ + RandomListNode* next = cur->next; + cur->next = new RandomListNode(cur->label); + cur->next->next = next; + cur = next; + } + + cur = head; + while(cur){ + if(cur->random) + cur->next->random = cur->random->next; + cur = cur->next->next; + } + + cur = head; + RandomListNode* ret = cur->next; + while(cur->next->next){ + RandomListNode* next = cur->next->next; + cur->next->next = next->next; + cur->next = next; + cur = next; + } + cur->next = NULL; + + return ret; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0139-Word-Break/cpp-0139/CMakeLists.txt b/0001-0500/0139-Word-Break/cpp-0139/CMakeLists.txt new file mode 100644 index 00000000..213e6763 --- /dev/null +++ b/0001-0500/0139-Word-Break/cpp-0139/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0139) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0139 main2.cpp) \ No newline at end of file diff --git a/0001-0500/0139-Word-Break/cpp-0139/main.cpp b/0001-0500/0139-Word-Break/cpp-0139/main.cpp new file mode 100644 index 00000000..93ea9561 --- /dev/null +++ b/0001-0500/0139-Word-Break/cpp-0139/main.cpp @@ -0,0 +1,41 @@ +/// Source : https://leetcode.com/problems/word-break/ +/// Author : liuyubobobo +/// Time : 2021-02-25 + +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(|s| * |wordDict|) +/// Space Complexity: O(|s|) +class Solution { +public: + bool wordBreak(string s, vector& wordDict) { + + vector dp(s.size(), -1); + return dfs(s, 0, wordDict, dp); + } + +private: + bool dfs(const string& s, int index, const vector& wordDict, + vector& dp){ + + if(index == s.size()) return true; + if(dp[index] != -1) return dp[index]; + + int left = s.size() - index; + for(const string& word: wordDict) + if(left >= word.size() && s.substr(index, word.size()) == word && + dfs(s, index + word.size(), wordDict, dp)) return dp[index] = true; + return dp[index] = false; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0139-Word-Break/cpp-0139/main2.cpp b/0001-0500/0139-Word-Break/cpp-0139/main2.cpp new file mode 100644 index 00000000..69057eb5 --- /dev/null +++ b/0001-0500/0139-Word-Break/cpp-0139/main2.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/word-break/ +/// Author : liuyubobobo +/// Time : 2021-02-25 + +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(|s| * |wordDict|) +/// Space Complexity: O(|s|) +class Solution { +public: + bool wordBreak(string s, vector& wordDict) { + + vector dp(s.size() + 1, false); + dp[s.size()] = true; + for(int i = dp.size() - 1; i >= 0; i --){ + int left = s.size() - i; + for(const string& word: wordDict) + if(left >= word.size() && s.substr(i, word.size()) == word && + dp[i + word.size()]){ + dp[i] = true; + break; + } + } + return dp[0]; + } +}; + + +int main() { + + return 0; +} diff --git a/0141-Linked-List-Cycle/cpp-0141/CMakeLists.txt b/0001-0500/0141-Linked-List-Cycle/cpp-0141/CMakeLists.txt similarity index 100% rename from 0141-Linked-List-Cycle/cpp-0141/CMakeLists.txt rename to 0001-0500/0141-Linked-List-Cycle/cpp-0141/CMakeLists.txt diff --git a/0141-Linked-List-Cycle/cpp-0141/main.cpp b/0001-0500/0141-Linked-List-Cycle/cpp-0141/main.cpp similarity index 100% rename from 0141-Linked-List-Cycle/cpp-0141/main.cpp rename to 0001-0500/0141-Linked-List-Cycle/cpp-0141/main.cpp diff --git a/0141-Linked-List-Cycle/cpp-0141/main2.cpp b/0001-0500/0141-Linked-List-Cycle/cpp-0141/main2.cpp similarity index 100% rename from 0141-Linked-List-Cycle/cpp-0141/main2.cpp rename to 0001-0500/0141-Linked-List-Cycle/cpp-0141/main2.cpp diff --git a/0142-Linked-List-Cycle-II/cpp-0142/CMakeLists.txt b/0001-0500/0142-Linked-List-Cycle-II/cpp-0142/CMakeLists.txt similarity index 100% rename from 0142-Linked-List-Cycle-II/cpp-0142/CMakeLists.txt rename to 0001-0500/0142-Linked-List-Cycle-II/cpp-0142/CMakeLists.txt diff --git a/0142-Linked-List-Cycle-II/cpp-0142/main.cpp b/0001-0500/0142-Linked-List-Cycle-II/cpp-0142/main.cpp similarity index 100% rename from 0142-Linked-List-Cycle-II/cpp-0142/main.cpp rename to 0001-0500/0142-Linked-List-Cycle-II/cpp-0142/main.cpp diff --git a/0142-Linked-List-Cycle-II/cpp-0142/main2.cpp b/0001-0500/0142-Linked-List-Cycle-II/cpp-0142/main2.cpp similarity index 100% rename from 0142-Linked-List-Cycle-II/cpp-0142/main2.cpp rename to 0001-0500/0142-Linked-List-Cycle-II/cpp-0142/main2.cpp diff --git a/0001-0500/0143-Reorder-List/cpp-0143/CMakeLists.txt b/0001-0500/0143-Reorder-List/cpp-0143/CMakeLists.txt new file mode 100644 index 00000000..9f03bc75 --- /dev/null +++ b/0001-0500/0143-Reorder-List/cpp-0143/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(cpp_0143) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0143 main.cpp) \ No newline at end of file diff --git a/0001-0500/0143-Reorder-List/cpp-0143/main.cpp b/0001-0500/0143-Reorder-List/cpp-0143/main.cpp new file mode 100644 index 00000000..4d8be91d --- /dev/null +++ b/0001-0500/0143-Reorder-List/cpp-0143/main.cpp @@ -0,0 +1,60 @@ +/// Source : https://leetcode.com/problems/reorder-list/ +/// Author : liuyubobobo +/// Time : 2019-08-30 + +#include + +using namespace std; + + +/// Simulations +/// Time Complexity: O(n) +/// Space Complexity: O(1) + + +/// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} +}; + + +class Solution { +public: + void reorderList(ListNode* head) { + + if(!head || !head->next) return; + + ListNode* slow = head, *fast = head; + while(fast->next && fast->next->next) + slow = slow->next, fast = fast->next, fast = fast->next; + + ListNode* head1 = head, *head2 = slow->next; + slow->next = NULL; + head2 = reverse(head2); + + ListNode* dummyHead = new ListNode(-1); + ListNode* cur= dummyHead, *cur1 = head1, *cur2 = head2; + for(int i = 0; cur1 || cur2; i ++) + if(i % 2 == 0) cur->next = cur1, cur = cur->next, cur1 = cur1->next; + else cur->next = cur2, cur = cur->next, cur2 = cur2->next; + head = dummyHead->next; + } + +private: + ListNode* reverse(ListNode* node){ + + if(!node->next) return node; + ListNode* ret = reverse(node->next); + node->next->next = node; + node->next = NULL; + return ret; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0144-Binary-Tree-Preorder-Traversal/cpp-0144/CMakeLists.txt b/0001-0500/0144-Binary-Tree-Preorder-Traversal/cpp-0144/CMakeLists.txt new file mode 100644 index 00000000..28d00385 --- /dev/null +++ b/0001-0500/0144-Binary-Tree-Preorder-Traversal/cpp-0144/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0144) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main5.cpp) +add_executable(cpp_0144 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0144-Binary-Tree-Preorder-Traversal/cpp-0144/main.cpp b/0001-0500/0144-Binary-Tree-Preorder-Traversal/cpp-0144/main.cpp similarity index 100% rename from 0144-Binary-Tree-Preorder-Traversal/cpp-0144/main.cpp rename to 0001-0500/0144-Binary-Tree-Preorder-Traversal/cpp-0144/main.cpp diff --git a/0144-Binary-Tree-Preorder-Traversal/cpp-0144/main2.cpp b/0001-0500/0144-Binary-Tree-Preorder-Traversal/cpp-0144/main2.cpp similarity index 100% rename from 0144-Binary-Tree-Preorder-Traversal/cpp-0144/main2.cpp rename to 0001-0500/0144-Binary-Tree-Preorder-Traversal/cpp-0144/main2.cpp diff --git a/0144-Binary-Tree-Preorder-Traversal/cpp-0144/main3.cpp b/0001-0500/0144-Binary-Tree-Preorder-Traversal/cpp-0144/main3.cpp similarity index 100% rename from 0144-Binary-Tree-Preorder-Traversal/cpp-0144/main3.cpp rename to 0001-0500/0144-Binary-Tree-Preorder-Traversal/cpp-0144/main3.cpp diff --git a/0001-0500/0144-Binary-Tree-Preorder-Traversal/cpp-0144/main4.cpp b/0001-0500/0144-Binary-Tree-Preorder-Traversal/cpp-0144/main4.cpp new file mode 100644 index 00000000..62985356 --- /dev/null +++ b/0001-0500/0144-Binary-Tree-Preorder-Traversal/cpp-0144/main4.cpp @@ -0,0 +1,65 @@ +/// Source : https://leetcode.com/problems/binary-tree-preorder-traversal/description/ +/// Author : liuyubobobo +/// Time : 2018-05-30 + +#include +#include +#include +#include + +using namespace std; + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +// Another Classic Non-Recursive algorithm for preorder traversal +// Time Complexity: O(n), n is the node number in the tree +// Space Complexity: O(h), h is the height of the tree +class Solution { + +public: + vector preorderTraversal(TreeNode* root) { + + vector res; + if(root == NULL) + return res; + + stack stack; + TreeNode* cur = root; + while(cur != NULL || !stack.empty()){ + while(cur != NULL){ + res.push_back(cur->val); + stack.push(cur); + cur = cur->left; + } + + cur = stack.top(); + stack.pop(); + cur = cur->right; + } + return res; + } +}; + + +void print_vec(const vector& vec){ + for(int e: vec) + cout << e << " "; + cout << endl; +} + +int main() { + + TreeNode* root = new TreeNode(1); + root->right = new TreeNode(2); + root->right->left = new TreeNode(3); + vector res = Solution().preorderTraversal(root); + print_vec(res); + + return 0; +} diff --git a/0001-0500/0144-Binary-Tree-Preorder-Traversal/cpp-0144/main5.cpp b/0001-0500/0144-Binary-Tree-Preorder-Traversal/cpp-0144/main5.cpp new file mode 100644 index 00000000..47f44151 --- /dev/null +++ b/0001-0500/0144-Binary-Tree-Preorder-Traversal/cpp-0144/main5.cpp @@ -0,0 +1,66 @@ +/// Source : https://leetcode.com/problems/binary-tree-preorder-traversal/description/ +/// Author : liuyubobobo +/// Time : 2018-05-30 + +#include +#include +#include +#include + +using namespace std; + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +// Another Classic Non-Recursive algorithm for preorder traversal +// Time Complexity: O(n), n is the node number in the tree +// Space Complexity: O(h), h is the height of the tree +class Solution { + +public: + vector preorderTraversal(TreeNode* root) { + + vector res; + if(root == NULL) + return res; + + stack stack; + TreeNode* cur = root; + while(cur != NULL || !stack.empty()){ + if(cur != NULL){ + res.push_back(cur->val); + stack.push(cur); + cur = cur->left; + } + else{ + cur = stack.top(); + stack.pop(); + cur = cur->right; + } + } + return res; + } +}; + + +void print_vec(const vector& vec){ + for(int e: vec) + cout << e << " "; + cout << endl; +} + +int main() { + + TreeNode* root = new TreeNode(1); + root->right = new TreeNode(2); + root->right->left = new TreeNode(3); + vector res = Solution().preorderTraversal(root); + print_vec(res); + + return 0; +} diff --git a/0001-0500/0144-Binary-Tree-Preorder-Traversal/cpp-0144/main6.cpp b/0001-0500/0144-Binary-Tree-Preorder-Traversal/cpp-0144/main6.cpp new file mode 100644 index 00000000..0aa0dcaa --- /dev/null +++ b/0001-0500/0144-Binary-Tree-Preorder-Traversal/cpp-0144/main6.cpp @@ -0,0 +1,62 @@ +/// Source : https://leetcode.com/problems/binary-tree-preorder-traversal/description/ +/// Author : liuyubobobo +/// Time : 2018-05-29 + +#include +#include +#include +#include + +using namespace std; + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +// PreOrder Morris Traversal +// Time Complexity: O(n), n is the node number in the tree +// Space Complexity: O(1) +class Solution { + +public: + vector preorderTraversal(TreeNode* root) { + + vector res; + if(root == NULL) + return res; + + TreeNode* cur = root; + while(cur != NULL){ + if(cur->left == NULL){ + res.push_back(cur->val); + cur = cur->right; + } + else{ + TreeNode* prev = cur->left; + while(prev->right != NULL && prev->right != cur) + prev = prev->right; + + if(prev->right == NULL){ + res.push_back(cur->val); + prev->right = cur; + cur = cur->left; + } + else{ + prev->right = NULL; + cur = cur->right; + } + } + } + + return res; + } +}; + +int main() { + + return 0; +} diff --git a/0001-0500/0144-Binary-Tree-Preorder-Traversal/java-0144/src/Solution1.java b/0001-0500/0144-Binary-Tree-Preorder-Traversal/java-0144/src/Solution1.java new file mode 100644 index 00000000..ba66bee9 --- /dev/null +++ b/0001-0500/0144-Binary-Tree-Preorder-Traversal/java-0144/src/Solution1.java @@ -0,0 +1,26 @@ +/// Source : https://leetcode.com/problems/binary-tree-preorder-traversal/description/ +/// Author : liuyubobobo +/// Time : 2017-11-17 +import java.util.ArrayList; +import java.util.List; + +// Recursive +// Time Complexity: O(n), n is the node number in the tree +// Space Complexity: O(h), h is the height of the tree +public class Solution1 { + + public List preorderTraversal(TreeNode root) { + + ArrayList res = new ArrayList(); + preorderTraversal(root, res); + return res; + } + + private void preorderTraversal(TreeNode node, List list){ + if(node != null){ + list.add(node.val); + preorderTraversal(node.left, list); + preorderTraversal(node.right, list); + } + } +} diff --git a/0001-0500/0144-Binary-Tree-Preorder-Traversal/java-0144/src/Solution2.java b/0001-0500/0144-Binary-Tree-Preorder-Traversal/java-0144/src/Solution2.java new file mode 100644 index 00000000..28bb5173 --- /dev/null +++ b/0001-0500/0144-Binary-Tree-Preorder-Traversal/java-0144/src/Solution2.java @@ -0,0 +1,48 @@ +/// Source : https://leetcode.com/problems/binary-tree-preorder-traversal/description/ +/// Author : liuyubobobo +/// Time : 2017-11-17 + +import java.util.ArrayList; +import java.util.List; +import java.util.Stack; + +// My Non-Recursive +// Time Complexity: O(n), n is the node number in the tree +// Space Complexity: O(h), h is the height of the tree +public class Solution2 { + + private class Command{ + String s; // go, print + TreeNode node; + Command(String s, TreeNode node){ + this.s = s; + this.node = node; + } + }; + + public List preorderTraversal(TreeNode root) { + + ArrayList res = new ArrayList(); + if(root == null) + return res; + + Stack stack = new Stack(); + stack.push(new Command("go", root)); + while(!stack.empty()){ + Command command = stack.pop(); + + if(command.s.equals("print")) + res.add(command.node.val); + else{ + assert command.s.equals("go"); + if(command.node.right != null) + stack.push(new Command("go",command.node.right)); + if(command.node.left != null) + stack.push(new Command("go",command.node.left)); + stack.push(new Command("print", command.node)); + } + } + return res; + } + +} diff --git a/0001-0500/0144-Binary-Tree-Preorder-Traversal/java-0144/src/Solution3.java b/0001-0500/0144-Binary-Tree-Preorder-Traversal/java-0144/src/Solution3.java new file mode 100644 index 00000000..09ebc934 --- /dev/null +++ b/0001-0500/0144-Binary-Tree-Preorder-Traversal/java-0144/src/Solution3.java @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/binary-tree-preorder-traversal/description/ +/// Author : liuyubobobo +/// Time : 2017-11-17 + +import java.util.ArrayList; +import java.util.List; +import java.util.Stack; + +// Classic Non-Recursive algorithm for preorder traversal +// Time Complexity: O(n), n is the node number in the tree +// Space Complexity: O(h), h is the height of the tree +public class Solution3 { + + public List preorderTraversal(TreeNode root) { + + ArrayList res = new ArrayList(); + if(root == null) + return res; + + Stack stack = new Stack(); + stack.push(root); + while(!stack.empty()){ + TreeNode curNode = stack.pop(); + res.add(curNode.val); + + if(curNode.right != null) + stack.push(curNode.right); + if(curNode.left != null) + stack.push(curNode.left); + } + return res; + } + +} diff --git a/0001-0500/0144-Binary-Tree-Preorder-Traversal/java-0144/src/Solution4.java b/0001-0500/0144-Binary-Tree-Preorder-Traversal/java-0144/src/Solution4.java new file mode 100644 index 00000000..290717ab --- /dev/null +++ b/0001-0500/0144-Binary-Tree-Preorder-Traversal/java-0144/src/Solution4.java @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/binary-tree-preorder-traversal/description/ +/// Author : liuyubobobo +/// Time : 2018-05-30 + +import java.util.ArrayList; +import java.util.List; +import java.util.Stack; + +// Another Classic Non-Recursive algorithm for preorder traversal +// Time Complexity: O(n), n is the node number in the tree +// Space Complexity: O(h), h is the height of the tree +public class Solution4 { + + public List preorderTraversal(TreeNode root) { + + ArrayList res = new ArrayList(); + if(root == null) + return res; + + Stack stack = new Stack(); + TreeNode cur = root; + while(cur != null || !stack.isEmpty()){ + while(cur != null){ + res.add(cur.val); + stack.push(cur); + cur = cur.left; + } + + cur = stack.pop(); + cur = cur.right; + } + return res; + } +} diff --git a/0001-0500/0144-Binary-Tree-Preorder-Traversal/java-0144/src/Solution5.java b/0001-0500/0144-Binary-Tree-Preorder-Traversal/java-0144/src/Solution5.java new file mode 100644 index 00000000..68d12ec3 --- /dev/null +++ b/0001-0500/0144-Binary-Tree-Preorder-Traversal/java-0144/src/Solution5.java @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/binary-tree-preorder-traversal/description/ +/// Author : liuyubobobo +/// Time : 2018-05-30 + +import java.util.ArrayList; +import java.util.List; +import java.util.Stack; + +// Another Classic Non-Recursive algorithm for preorder traversal +// Time Complexity: O(n), n is the node number in the tree +// Space Complexity: O(h), h is the height of the tree +public class Solution5 { + + public List preorderTraversal(TreeNode root) { + + ArrayList res = new ArrayList(); + if(root == null) + return res; + + Stack stack = new Stack(); + TreeNode cur = root; + while(cur != null || !stack.isEmpty()){ + if(cur != null){ + res.add(cur.val); + stack.push(cur); + cur = cur.left; + } + else{ + cur = stack.pop(); + cur = cur.right; + } + } + return res; + } +} diff --git a/0001-0500/0144-Binary-Tree-Preorder-Traversal/java-0144/src/Solution6.java b/0001-0500/0144-Binary-Tree-Preorder-Traversal/java-0144/src/Solution6.java new file mode 100644 index 00000000..9dbb2008 --- /dev/null +++ b/0001-0500/0144-Binary-Tree-Preorder-Traversal/java-0144/src/Solution6.java @@ -0,0 +1,45 @@ +/// Source : https://leetcode.com/problems/binary-tree-preorder-traversal/description/ +/// Author : liuyubobobo +/// Time : 2018-05-29 + +import java.util.ArrayList; +import java.util.List; +import java.util.Stack; + +// PreOrder Morris Traversal +// Time Complexity: O(n), n is the node number in the tree +// Space Complexity: O(1) +public class Solution6 { + + public List preorderTraversal(TreeNode root) { + + ArrayList res = new ArrayList(); + if(root == null) + return res; + + TreeNode cur = root; + while(cur != null){ + if(cur.left == null){ + res.add(cur.val); + cur = cur.right; + } + else{ + TreeNode prev = cur.left; + while(prev.right != null && prev.right != cur) + prev = prev.right; + + if(prev.right == null){ + res.add(cur.val); + prev.right = cur; + cur = cur.left; + } + else{ + prev.right = null; + cur = cur.right; + } + } + } + + return res; + } +} diff --git a/0001-0500/0144-Binary-Tree-Preorder-Traversal/java-0144/src/TreeNode.java b/0001-0500/0144-Binary-Tree-Preorder-Traversal/java-0144/src/TreeNode.java new file mode 100644 index 00000000..f408f764 --- /dev/null +++ b/0001-0500/0144-Binary-Tree-Preorder-Traversal/java-0144/src/TreeNode.java @@ -0,0 +1,7 @@ +// Definition for a binary tree node. +public class TreeNode { + int val; + TreeNode left; + TreeNode right; + TreeNode(int x) { val = x; } +} \ No newline at end of file diff --git a/0001-0500/0145-Binary-Tree-Postorder-Traversal/cpp-0145/CMakeLists.txt b/0001-0500/0145-Binary-Tree-Postorder-Traversal/cpp-0145/CMakeLists.txt new file mode 100644 index 00000000..9407f7ea --- /dev/null +++ b/0001-0500/0145-Binary-Tree-Postorder-Traversal/cpp-0145/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0145) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main8.cpp) +add_executable(cpp_0145 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0145-Binary-Tree-Postorder-Traversal/cpp-0145/main.cpp b/0001-0500/0145-Binary-Tree-Postorder-Traversal/cpp-0145/main.cpp similarity index 100% rename from 0145-Binary-Tree-Postorder-Traversal/cpp-0145/main.cpp rename to 0001-0500/0145-Binary-Tree-Postorder-Traversal/cpp-0145/main.cpp diff --git a/0001-0500/0145-Binary-Tree-Postorder-Traversal/cpp-0145/main2.cpp b/0001-0500/0145-Binary-Tree-Postorder-Traversal/cpp-0145/main2.cpp new file mode 100644 index 00000000..152e5ff0 --- /dev/null +++ b/0001-0500/0145-Binary-Tree-Postorder-Traversal/cpp-0145/main2.cpp @@ -0,0 +1,63 @@ +/// Source : https://leetcode.com/problems/binary-tree-postorder-traversal/description/ +/// Author : liuyubobobo +/// Time : 2017-11-17 + +#include +#include + +using namespace std; + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + + +// My Non-Recursive +// Time Complexity: O(n), n is the node number in the tree +// Space Complexity: O(h), h is the height of the tree +class Solution { + +private: + struct Command{ + string s; // go, print + TreeNode* node; + Command(string s, TreeNode* node): s(s), node(node){} + }; + +public: + vector postorderTraversal(TreeNode* root) { + + vector res; + if(root == NULL) + return res; + + stack stack; + stack.push(Command("go", root) ); + while(!stack.empty()){ + Command command = stack.top(); + stack.pop(); + + if(command.s == "print") + res.push_back(command.node->val); + else{ + assert(command.s == "go"); + stack.push(Command("print", command.node)); + if(command.node->right) + stack.push(Command("go",command.node->right)); + if(command.node->left) + stack.push(Command("go",command.node->left)); + } + } + return res; + } +}; + +int main() { + + return 0; +} + diff --git a/0001-0500/0145-Binary-Tree-Postorder-Traversal/cpp-0145/main3.cpp b/0001-0500/0145-Binary-Tree-Postorder-Traversal/cpp-0145/main3.cpp new file mode 100644 index 00000000..08c7b0ab --- /dev/null +++ b/0001-0500/0145-Binary-Tree-Postorder-Traversal/cpp-0145/main3.cpp @@ -0,0 +1,71 @@ +/// Source : https://leetcode.com/problems/binary-tree-postorder-traversal/description/ +/// Author : liuyubobobo +/// Time : 2018-05-30 + +#include +#include +#include + +using namespace std; + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + + +// Non-Recursive +// Using a tag to record whether the node has been visited +// +// Time Complexity: O(n), n is the node number in the tree +// Space Complexity: O(h), h is the height of the tree +class Solution { + +private: + struct TagNode{ + TreeNode* node; + bool isFirst; + TagNode(TreeNode* node): node(node), isFirst(false){} + }; + +public: + vector postorderTraversal(TreeNode* root) { + + vector res; + if(root == NULL) + return res; + + stack stack; + TreeNode* cur = root; + while(cur != NULL || !stack.empty()){ + + while(cur != NULL){ + stack.push(TagNode(cur)); + cur = cur->left; + } + + TagNode tagNode = stack.top(); + stack.pop(); + cur = tagNode.node; + if(tagNode.isFirst == false){ + tagNode.isFirst = true; + stack.push(tagNode); + cur = cur->right; + } + else{ + res.push_back(cur->val); + cur = NULL; + }; + } + return res; + } +}; + +int main() { + + return 0; +} + diff --git a/0001-0500/0145-Binary-Tree-Postorder-Traversal/cpp-0145/main4.cpp b/0001-0500/0145-Binary-Tree-Postorder-Traversal/cpp-0145/main4.cpp new file mode 100644 index 00000000..4ca66408 --- /dev/null +++ b/0001-0500/0145-Binary-Tree-Postorder-Traversal/cpp-0145/main4.cpp @@ -0,0 +1,62 @@ +/// Source : https://leetcode.com/problems/binary-tree-postorder-traversal/description/ +/// Author : liuyubobobo +/// Time : 2018-05-30 + +#include +#include +#include + +using namespace std; + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + + +// Non-Recursive +// Using two stacks, Reverse the Preorder Traversal! +// +// Time Complexity: O(n) +// Space Complexity: O(n) +class Solution { + +public: + vector postorderTraversal(TreeNode* root) { + + vector res; + if(root == NULL) + return res; + + stack stack, output; + + stack.push(root); + while(!stack.empty()){ + + TreeNode* node = stack.top(); + stack.pop(); + output.push(node); + + if(node->left != NULL) + stack.push(node->left); + if(node->right != NULL) + stack.push(node->right); + } + + while(!output.empty()){ + res.push_back((output.top())->val); + output.pop(); + } + + return res; + } +}; + +int main() { + + return 0; +} + diff --git a/0001-0500/0145-Binary-Tree-Postorder-Traversal/cpp-0145/main5.cpp b/0001-0500/0145-Binary-Tree-Postorder-Traversal/cpp-0145/main5.cpp new file mode 100644 index 00000000..fa5926c4 --- /dev/null +++ b/0001-0500/0145-Binary-Tree-Postorder-Traversal/cpp-0145/main5.cpp @@ -0,0 +1,63 @@ +/// Source : https://leetcode.com/problems/binary-tree-postorder-traversal/description/ +/// Author : liuyubobobo +/// Time : 2018-05-30 + +#include +#include +#include + +using namespace std; + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + + +// Non-Recursive +// Using two stacks, Reverse the Preorder Traversal! +// +// Time Complexity: O(n) +// Space Complexity: O(n) +class Solution { + +public: + vector postorderTraversal(TreeNode* root) { + + vector res; + if(root == NULL) + return res; + + stack stack, output; + + TreeNode* p = root; + while(p != NULL || !stack.empty()){ + if(p != NULL){ + stack.push(p); + output.push(p); + p = p->right; + } + else{ + p = stack.top(); + stack.pop(); + p = p->left; + } + } + + while(!output.empty()){ + res.push_back((output.top())->val); + output.pop(); + } + + return res; + } +}; + +int main() { + + return 0; +} + diff --git a/0001-0500/0145-Binary-Tree-Postorder-Traversal/cpp-0145/main6.cpp b/0001-0500/0145-Binary-Tree-Postorder-Traversal/cpp-0145/main6.cpp new file mode 100644 index 00000000..63f0a18d --- /dev/null +++ b/0001-0500/0145-Binary-Tree-Postorder-Traversal/cpp-0145/main6.cpp @@ -0,0 +1,78 @@ +/// Source : https://leetcode.com/problems/binary-tree-postorder-traversal/description/ +/// Author : liuyubobobo +/// Time : 2018-05-31 + +#include +#include +#include + +using namespace std; + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + + +// Non-Recursive +// Using a pre pointer to record the last visted node +// +// Time Complexity: O(n) +// Space Complexity: O(h) +class Solution { + +public: + vector postorderTraversal(TreeNode* root) { + + vector res; + if(root == NULL) + return res; + + stack stack; + TreeNode* pre = NULL; + + stack.push(root); + while(!stack.empty()){ + + TreeNode* node = stack.top(); + stack.pop(); + if((node->left == NULL && node->right == NULL) || + (pre != NULL && pre == node->left && node->right == NULL) || + (pre != NULL && pre == node->right)){ + res.push_back(node->val); + pre = node; + } + else{ + stack.push(node); + + if(node->right != NULL) + stack.push(node->right); + if(node->left != NULL) + stack.push(node->left); + } + } + + return res; + } +}; + + +void print_vec(const vector& vec){ + for(int e: vec) + cout << e << " "; + cout << endl; +} + +int main() { + + TreeNode* root = new TreeNode(1); + root->right = new TreeNode(2); + root->right->left = new TreeNode(3); + print_vec(Solution().postorderTraversal(root)); + + return 0; +} + diff --git a/0001-0500/0145-Binary-Tree-Postorder-Traversal/cpp-0145/main7.cpp b/0001-0500/0145-Binary-Tree-Postorder-Traversal/cpp-0145/main7.cpp new file mode 100644 index 00000000..d3b436ec --- /dev/null +++ b/0001-0500/0145-Binary-Tree-Postorder-Traversal/cpp-0145/main7.cpp @@ -0,0 +1,79 @@ +/// Source : https://leetcode.com/problems/binary-tree-postorder-traversal/description/ +/// Author : liuyubobobo +/// Time : 2018-05-31 + +#include +#include +#include + +using namespace std; + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + + +// Classic Non-Recursive +// Using a pre pointer to record the last visted node +// +// Time Complexity: O(n) +// Space Complexity: O(h) +class Solution { + +public: + vector postorderTraversal(TreeNode* root) { + + vector res; + if(root == NULL) + return res; + + stack stack; + TreeNode* pre = NULL; + TreeNode* cur = root; + + while(cur != NULL || !stack.empty()){ + + while(cur != NULL){ + stack.push(cur); + cur = cur->left; + } + + cur = stack.top(); + stack.pop(); + + if(cur->right == NULL || pre == cur->right){ + res.push_back(cur->val); + pre = cur; + cur = NULL; + } + else{ + stack.push(cur); + cur = cur->right; + } + } + + return res; + } +}; + + +void print_vec(const vector& vec){ + for(int e: vec) + cout << e << " "; + cout << endl; +} + +int main() { + + TreeNode* root = new TreeNode(1); + root->right = new TreeNode(2); + root->right->left = new TreeNode(3); + print_vec(Solution().postorderTraversal(root)); + + return 0; +} + diff --git a/0001-0500/0145-Binary-Tree-Postorder-Traversal/cpp-0145/main8.cpp b/0001-0500/0145-Binary-Tree-Postorder-Traversal/cpp-0145/main8.cpp new file mode 100644 index 00000000..c122f894 --- /dev/null +++ b/0001-0500/0145-Binary-Tree-Postorder-Traversal/cpp-0145/main8.cpp @@ -0,0 +1,79 @@ +/// Source : https://leetcode.com/problems/binary-tree-postorder-traversal/description/ +/// Author : liuyubobobo +/// Time : 2018-05-31 + +#include +#include +#include + +using namespace std; + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + + +// Classic Non-Recursive +// Using a pre pointer to record the last visted node +// +// Time Complexity: O(n) +// Space Complexity: O(h) +class Solution { + +public: + vector postorderTraversal(TreeNode* root) { + + vector res; + if(root == NULL) + return res; + + stack stack; + TreeNode* pre = NULL; + TreeNode* cur = root; + + while(cur != NULL || !stack.empty()){ + if(cur != NULL){ + stack.push(cur); + cur = cur->left; + } + else{ + cur = stack.top(); + stack.pop(); + + if(cur->right == NULL || pre == cur->right){ + res.push_back(cur->val); + pre = cur; + cur = NULL; + } + else{ + stack.push(cur); + cur = cur->right; + } + } + } + + return res; + } +}; + + +void print_vec(const vector& vec){ + for(int e: vec) + cout << e << " "; + cout << endl; +} + +int main() { + + TreeNode* root = new TreeNode(1); + root->right = new TreeNode(2); + root->right->left = new TreeNode(3); + print_vec(Solution().postorderTraversal(root)); + + return 0; +} + diff --git a/0001-0500/0145-Binary-Tree-Postorder-Traversal/cpp-0145/main9.cpp b/0001-0500/0145-Binary-Tree-Postorder-Traversal/cpp-0145/main9.cpp new file mode 100644 index 00000000..e898fec0 --- /dev/null +++ b/0001-0500/0145-Binary-Tree-Postorder-Traversal/cpp-0145/main9.cpp @@ -0,0 +1,89 @@ +/// Source : https://leetcode.com/problems/binary-tree-postorder-traversal/description/ +/// Author : liuyubobobo +/// Time : 2018-05-31 + +#include +#include +#include + +using namespace std; + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + + +// Morris PostOrder Traversal +// +// Time Complexity: O(n) +// Space Complexity: O(1) +class Solution { + +public: + vector postorderTraversal(TreeNode* root) { + + vector res; + if(root == NULL) + return res; + + TreeNode* dummyRoot = new TreeNode(-1); + dummyRoot->left = root; + + TreeNode* cur = dummyRoot; + while(cur != NULL){ + if(cur->left == NULL) + cur = cur->right; + else{ + TreeNode* prev = cur->left; + while(prev->right != NULL && prev->right != cur) + prev = prev->right; + + if(prev->right == NULL){ + prev->right = cur; + cur = cur->left; + } + else{ + prev->right = NULL; + reverseTraversal(cur->left, res); + cur = cur->right; + } + } + } + delete dummyRoot; + + return res; + } + +private: + void reverseTraversal(TreeNode* node, vector& res){ + + int start = res.size(); + while(node != NULL){ + res.push_back(node->val); + node = node->right; + } + reverse(res.begin() + start, res.end()); + } +}; + + +void print_vec(const vector& vec){ + for(int e: vec) + cout << e << " "; + cout << endl; +} + +int main() { + + TreeNode* root = new TreeNode(1); + root->right = new TreeNode(2); + root->right->left = new TreeNode(3); + print_vec(Solution().postorderTraversal(root)); + + return 0; +} + diff --git a/0001-0500/0145-Binary-Tree-Postorder-Traversal/java-0145/src/Solution1.java b/0001-0500/0145-Binary-Tree-Postorder-Traversal/java-0145/src/Solution1.java new file mode 100644 index 00000000..ee2f01b2 --- /dev/null +++ b/0001-0500/0145-Binary-Tree-Postorder-Traversal/java-0145/src/Solution1.java @@ -0,0 +1,27 @@ +/// Source : https://leetcode.com/problems/binary-tree-postorder-traversal/description/ +/// Author : liuyubobobo +/// Time : 2017-11-17 + +import java.util.ArrayList; +import java.util.List; + +// Recursive +// Time Complexity: O(n), n is the node number in the tree +// Space Complexity: O(h), h is the height of the tree +public class Solution1 { + + public List postorderTraversal(TreeNode root) { + + ArrayList res = new ArrayList(); + postorderTraversal(root, res); + return res; + } + + private void postorderTraversal(TreeNode node, List list){ + if(node != null){ + postorderTraversal(node.left, list); + postorderTraversal(node.right, list); + list.add(node.val); + } + } +} diff --git a/0001-0500/0145-Binary-Tree-Postorder-Traversal/java-0145/src/Solution2.java b/0001-0500/0145-Binary-Tree-Postorder-Traversal/java-0145/src/Solution2.java new file mode 100644 index 00000000..b6fb9ed5 --- /dev/null +++ b/0001-0500/0145-Binary-Tree-Postorder-Traversal/java-0145/src/Solution2.java @@ -0,0 +1,48 @@ +/// Source : https://leetcode.com/problems/binary-tree-postorder-traversal/description/ +/// Author : liuyubobobo +/// Time : 2017-11-17 + +import java.util.ArrayList; +import java.util.List; +import java.util.Stack; + +// My Non-Recursive +// Time Complexity: O(n), n is the node number in the tree +// Space Complexity: O(h), h is the height of the tree +public class Solution2 { + + private class Command{ + String s; // go, print + TreeNode node; + Command(String s, TreeNode node){ + this.s = s; + this.node = node; + } + }; + + public List postorderTraversal(TreeNode root) { + + ArrayList res = new ArrayList(); + if(root == null) + return res; + + Stack stack = new Stack(); + stack.push(new Command("go", root)); + while(!stack.empty()){ + Command command = stack.pop(); + + if(command.s.equals("print")) + res.add(command.node.val); + else{ + assert command.s.equals("go"); + stack.push(new Command("print", command.node)); + if(command.node.right != null) + stack.push(new Command("go",command.node.right)); + if(command.node.left != null) + stack.push(new Command("go",command.node.left)); + } + } + return res; + } + +} diff --git a/0001-0500/0145-Binary-Tree-Postorder-Traversal/java-0145/src/Solution3.java b/0001-0500/0145-Binary-Tree-Postorder-Traversal/java-0145/src/Solution3.java new file mode 100644 index 00000000..892f59a3 --- /dev/null +++ b/0001-0500/0145-Binary-Tree-Postorder-Traversal/java-0145/src/Solution3.java @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/binary-tree-postorder-traversal/description/ +/// Author : liuyubobobo +/// Time : 2018-05-30 + +import java.util.ArrayList; +import java.util.List; +import java.util.Stack; + +// Non-Recursive +// Using a tag to record whether the node has been visited +// +// Time Complexity: O(n), n is the node number in the tree +// Space Complexity: O(h), h is the height of the tree +public class Solution3 { + + private class TagNode{ + TreeNode node; + boolean isFirst; + TagNode(TreeNode node){ + this.node = node; + this.isFirst = false; + } + }; + + public List postorderTraversal(TreeNode root) { + + ArrayList res = new ArrayList(); + if(root == null) + return res; + + Stack stack = new Stack<>(); + TreeNode cur = root; + while(cur != null || !stack.empty()){ + + while(cur != null){ + stack.push(new TagNode(cur)); + cur = cur.left; + } + + TagNode tagNode = stack.pop(); + cur = tagNode.node; + if(tagNode.isFirst == false){ + tagNode.isFirst = true; + stack.push(tagNode); + cur = cur.right; + } + else{ + res.add(cur.val); + cur = null; + } + } + return res; + } +} diff --git a/0001-0500/0145-Binary-Tree-Postorder-Traversal/java-0145/src/Solution4.java b/0001-0500/0145-Binary-Tree-Postorder-Traversal/java-0145/src/Solution4.java new file mode 100644 index 00000000..18a950d2 --- /dev/null +++ b/0001-0500/0145-Binary-Tree-Postorder-Traversal/java-0145/src/Solution4.java @@ -0,0 +1,41 @@ +/// Source : https://leetcode.com/problems/binary-tree-postorder-traversal/description/ +/// Author : liuyubobobo +/// Time : 2018-05-30 + +import java.util.ArrayList; +import java.util.List; +import java.util.Stack; + +// Non-Recursive +// Using two stacks, Reverse the Preorder Traversal! +// +// Time Complexity: O(n) +// Space Complexity: O(n) +public class Solution4 { + + public List postorderTraversal(TreeNode root) { + + ArrayList res = new ArrayList(); + if(root == null) + return res; + + Stack stack = new Stack<>(); + Stack output = new Stack<>(); + + stack.push(root); + while(!stack.empty()){ + + TreeNode cur = stack.pop(); + output.push(cur.val); + + if(cur.left != null) + stack.push(cur.left); + if(cur.right != null) + stack.push(cur.right); + } + + while(!output.empty()) + res.add(output.pop()); + return res; + } +} diff --git a/0001-0500/0145-Binary-Tree-Postorder-Traversal/java-0145/src/Solution5.java b/0001-0500/0145-Binary-Tree-Postorder-Traversal/java-0145/src/Solution5.java new file mode 100644 index 00000000..5d05befa --- /dev/null +++ b/0001-0500/0145-Binary-Tree-Postorder-Traversal/java-0145/src/Solution5.java @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/binary-tree-postorder-traversal/description/ +/// Author : liuyubobobo +/// Time : 2018-05-30 + +import java.util.ArrayList; +import java.util.List; +import java.util.Stack; +import java.util.LinkedList; + +// Non-Recursive +// Using two stacks, Reverse the Preorder Traversal! +// +// Time Complexity: O(n) +// Space Complexity: O(n) +public class Solution5 { + + public List postorderTraversal(TreeNode root){ + + Stack stack = new Stack<>(); + LinkedList output = new LinkedList<>(); + + TreeNode p = root; + while(p != null || !stack.isEmpty()){ + if(p != null){ + stack.push(p); + output.push(p); + p = p.right; + } + else{ + p = stack.pop(); + p = p.left; + } + } + + List res = new ArrayList<>(); + while(!output.isEmpty()) + res.add(output.pop().val); + return res; + } +} diff --git a/0001-0500/0145-Binary-Tree-Postorder-Traversal/java-0145/src/Solution6.java b/0001-0500/0145-Binary-Tree-Postorder-Traversal/java-0145/src/Solution6.java new file mode 100644 index 00000000..ae187962 --- /dev/null +++ b/0001-0500/0145-Binary-Tree-Postorder-Traversal/java-0145/src/Solution6.java @@ -0,0 +1,45 @@ +/// Source : https://leetcode.com/problems/binary-tree-postorder-traversal/description/ +/// Author : liuyubobobo +/// Time : 2018-05-31 + +import java.util.ArrayList; +import java.util.List; +import java.util.Stack; + +// Non-Recursive +// Using a pre pointer to record the last visted node +// +// Time Complexity: O(n) +// Space Complexity: O(h) +public class Solution6 { + + public List postorderTraversal(TreeNode root) { + + ArrayList res = new ArrayList(); + if(root == null) + return res; + + Stack stack = new Stack<>(); + TreeNode pre = null; + + stack.push(root); + while(!stack.empty()){ + + TreeNode cur = stack.pop(); + if((cur.left == null && cur.right == null) || + (pre != null && pre == cur.left && cur.right == null) || + (pre != null && pre == cur.right)){ + res.add(cur.val); + pre = cur; + } + else{ + stack.push(cur); + if(cur.right != null) + stack.push(cur.right); + if(cur.left != null) + stack.push(cur.left); + } + } + return res; + } +} diff --git a/0001-0500/0145-Binary-Tree-Postorder-Traversal/java-0145/src/Solution7.java b/0001-0500/0145-Binary-Tree-Postorder-Traversal/java-0145/src/Solution7.java new file mode 100644 index 00000000..f945dfa5 --- /dev/null +++ b/0001-0500/0145-Binary-Tree-Postorder-Traversal/java-0145/src/Solution7.java @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/binary-tree-postorder-traversal/description/ +/// Author : liuyubobobo +/// Time : 2018-05-31 + +import java.util.ArrayList; +import java.util.List; +import java.util.Stack; + +// Classic Non-Recursive +// Using a pre pointer to record the last visted node +// +// Time Complexity: O(n) +// Space Complexity: O(h) +public class Solution7 { + + public List postorderTraversal(TreeNode root) { + + ArrayList res = new ArrayList(); + if(root == null) + return res; + + Stack stack = new Stack<>(); + TreeNode pre = null; + TreeNode cur = root; + + while(cur != null || !stack.empty()){ + + while(cur != null){ + stack.push(cur); + cur = cur.left; + } + + cur = stack.pop(); + if(cur.right == null || pre == cur.right){ + res.add(cur.val); + pre = cur; + cur = null; + } + else{ + stack.push(cur); + cur = cur.right; + } + } + return res; + } +} diff --git a/0001-0500/0145-Binary-Tree-Postorder-Traversal/java-0145/src/Solution8.java b/0001-0500/0145-Binary-Tree-Postorder-Traversal/java-0145/src/Solution8.java new file mode 100644 index 00000000..d0c3d68d --- /dev/null +++ b/0001-0500/0145-Binary-Tree-Postorder-Traversal/java-0145/src/Solution8.java @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/binary-tree-postorder-traversal/description/ +/// Author : liuyubobobo +/// Time : 2018-05-31 + +import java.util.ArrayList; +import java.util.List; +import java.util.Stack; + +// Classic Non-Recursive +// Using a pre pointer to record the last visted node +// +// Time Complexity: O(n) +// Space Complexity: O(h) +public class Solution8 { + + public List postorderTraversal(TreeNode root) { + + ArrayList res = new ArrayList(); + if(root == null) + return res; + + Stack stack = new Stack<>(); + TreeNode pre = null; + TreeNode cur = root; + + while(cur != null || !stack.empty()){ + + if(cur != null){ + stack.push(cur); + cur = cur.left; + } + else{ + cur = stack.pop(); + if(cur.right == null || pre == cur.right){ + res.add(cur.val); + pre = cur; + cur = null; + } + else{ + stack.push(cur); + cur = cur.right; + } + } + } + return res; + } +} diff --git a/0001-0500/0145-Binary-Tree-Postorder-Traversal/java-0145/src/Solution9.java b/0001-0500/0145-Binary-Tree-Postorder-Traversal/java-0145/src/Solution9.java new file mode 100644 index 00000000..2862c0cc --- /dev/null +++ b/0001-0500/0145-Binary-Tree-Postorder-Traversal/java-0145/src/Solution9.java @@ -0,0 +1,65 @@ +/// Source : https://leetcode.com/problems/binary-tree-postorder-traversal/description/ +/// Author : liuyubobobo +/// Time : 2018-05-31 + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Stack; + +// Morris PostOrder Traversal +// +// Time Complexity: O(n) +// Space Complexity: O(1) +public class Solution9 { + + public List postorderTraversal(TreeNode root) { + + ArrayList res = new ArrayList(); + if(root == null) + return res; + + TreeNode dummyRoot = new TreeNode(-1); + dummyRoot.left = root; + + TreeNode cur = dummyRoot; + while(cur != null){ + if(cur.left == null) + cur = cur.right; + else{ + TreeNode pre = cur.left; + while(pre.right != null && pre.right != cur) + pre = pre.right; + + if(pre.right == null){ + pre.right = cur; + cur = cur.left; + } + else{ + pre.right = null; + reverseTraversal(cur.left, res); + cur = cur.right; + } + } + } + return res; + } + + private void reverseTraversal(TreeNode node, ArrayList res){ + int start = res.size(); + while(node != null){ + res.add(node.val); + node = node.right; + } + + int i = start, j = res.size() - 1; + while(i < j){ + Integer t = res.get(i); + res.set(i, res.get(j)); + res.set(j, t); + + i ++; + j --; + } + } +} diff --git a/0001-0500/0145-Binary-Tree-Postorder-Traversal/java-0145/src/TreeNode.java b/0001-0500/0145-Binary-Tree-Postorder-Traversal/java-0145/src/TreeNode.java new file mode 100644 index 00000000..f408f764 --- /dev/null +++ b/0001-0500/0145-Binary-Tree-Postorder-Traversal/java-0145/src/TreeNode.java @@ -0,0 +1,7 @@ +// Definition for a binary tree node. +public class TreeNode { + int val; + TreeNode left; + TreeNode right; + TreeNode(int x) { val = x; } +} \ No newline at end of file diff --git a/0001-0500/0146-LRU-Cache/cpp-0146/CMakeLists.txt b/0001-0500/0146-LRU-Cache/cpp-0146/CMakeLists.txt new file mode 100644 index 00000000..2a3ce052 --- /dev/null +++ b/0001-0500/0146-LRU-Cache/cpp-0146/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(cpp_0146) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0146 main.cpp) \ No newline at end of file diff --git a/0001-0500/0146-LRU-Cache/cpp-0146/main.cpp b/0001-0500/0146-LRU-Cache/cpp-0146/main.cpp new file mode 100644 index 00000000..4d10a127 --- /dev/null +++ b/0001-0500/0146-LRU-Cache/cpp-0146/main.cpp @@ -0,0 +1,148 @@ +/// Source : https://leetcode.com/problems/lru-cache/ +/// Author : liuyubobobo +/// Time : 2019-03-02 + +#include +#include +#include + +using namespace std; + + +/// HashMap + Double Linked List +/// Time Complexity: init: O(1) +/// get: O(1) +/// put: O(1) +/// Space Complexity: O(n) +class LRUCache { + +private: + class Node{ + + public: + int key, value; + Node *prev, *next; + + Node(int k, int v): key(k), value(v), prev(NULL), next(NULL){} + }; + + int capacity; + unordered_map data; + + Node* dummyHead; + Node* tail; + +public: + LRUCache(int capacity): capacity(capacity){ + dummyHead = new Node(-1, -1); + tail = new Node(-1, -1); + + dummyHead->next = tail; + tail->prev = dummyHead; + } + + ~LRUCache(){ + // TODO memory + } + + int get(int key) { +// cout << "get " << key << endl; + if(data.count(key)){ + moveToHead(data[key]); + assert(dummyHead->next); +// debug(); + return dummyHead->next->value; + } + return -1; + } + + void put(int key, int value) { +// cout << "put " << key << " " << value << endl; + if(data.count(key)){ + data[key]->value = value; + moveToHead(data[key]); + return; + } + + data[key] = new Node(key, value); + addFirst(data[key]); +// debug(); + if(data.size() > capacity){ + assert(data.size() == capacity + 1); + int delKey = removeLast(); + assert(data.count(delKey)); + data.erase(delKey); +// debug(); + } + } + +private: + void moveToHead(Node* node){ + node->prev->next = node->next; + node->next->prev = node->prev; + + node->prev = node->next = NULL; + addFirst(node); + } + + void addFirst(Node* node){ + + node->next = dummyHead->next; + node->next->prev= node; + + node->prev = dummyHead; + dummyHead->next = node; + } + + int removeLast(){ + + assert(tail->prev != dummyHead); + Node* delNode = tail->prev; + + tail->prev = tail->prev->prev; + tail->prev->next = tail; + + // TODO: delete delNode + return delNode->key; + } + + void debug(){ + + cout << "Hash Map : sz = " << data.size() << endl; + for(const pair& p: data) + cout << p.first << " : ( " << p.second->key << " , " << p.second->value << " )" << endl; + + cout << "Double Linked List : " << endl; + Node* cur = dummyHead; + while(cur) + cout << "(" << cur->key << "," << cur->value << ") -> ", cur = cur->next; + cout << "NULL" << endl << endl; + } +}; + + +int main() { + + LRUCache cache1(2); + cache1.put(1, 1); + cache1.put(2, 2); + cout << cache1.get(1) << endl; // 1 + cache1.put(3, 3); + cout << cache1.get(2) << endl; // -1 + cache1.put(4, 4); + cout << cache1.get(1) << endl; // -1 + cout << cache1.get(3) << endl; // 3 + cout << cache1.get(4) << endl; // 4 + + cout << endl; + + LRUCache cache2(2); + cache2.put(2, 1); + cache2.put(1, 1); + cache2.put(2, 3); + cache2.put(4, 1); + cout << cache2.get(1) << endl; // -1 + cout << cache2.get(2) << endl; // 3 + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0146-LRU-Cache/java-0146/src/LRUCache.java b/0001-0500/0146-LRU-Cache/java-0146/src/LRUCache.java new file mode 100644 index 00000000..0da00d4a --- /dev/null +++ b/0001-0500/0146-LRU-Cache/java-0146/src/LRUCache.java @@ -0,0 +1,79 @@ +/// Source : https://leetcode.com/problems/lru-cache/ +/// Author : liuyubobobo +/// Time : 2021-11-24 + +import java.util.*; + + +/// Using Time Stamp +/// Time Complexity: init: O(1) +/// get: O(logn) +/// put: O(logn) +/// Space Complexity: O(n) +public class LRUCache { + + private int timestamp; + private int cap; + + private HashMap data; + private HashMap key2timestamp; + private TreeMap timestamp2key; + + public LRUCache(int capacity) { + + timestamp = 0; + cap = capacity; + + data = new HashMap<>(); + key2timestamp = new HashMap<>(); + timestamp2key = new TreeMap<>(); + } + + public int get(int key) { + + if(data.containsKey(key)){ + int oldTimestamp = key2timestamp.get(key); + timestamp2key.remove(oldTimestamp); + + key2timestamp.put(key, timestamp); + timestamp2key.put(timestamp, key); + timestamp ++; + + return data.get(key); + } + return -1; + } + + public void put(int key, int value) { + + if(data.containsKey(key)){ + int oldTimestamp = key2timestamp.get(key); + timestamp2key.remove(oldTimestamp); + } + + data.put(key, value); + + key2timestamp.put(key, timestamp); + timestamp2key.put(timestamp, key); + timestamp ++; + + if(data.size() > cap){ + int removeTimestamp = timestamp2key.firstKey(); + int removeKey = timestamp2key.get(removeTimestamp); + + data.remove(removeKey); + key2timestamp.remove(removeKey); + timestamp2key.remove(removeTimestamp); + } + } + + public static void main(String[] args) { + + LRUCache lru = new LRUCache(2); + lru.put(1, 1); + lru.put(2, 2); + System.out.println(lru.get(1)); // 1 + lru.put(3, 3); + System.out.println(lru.get(2)); // -1 + } +} diff --git a/0001-0500/0147-Insertion-Sort-List/cpp-0147/CMakeLists.txt b/0001-0500/0147-Insertion-Sort-List/cpp-0147/CMakeLists.txt new file mode 100644 index 00000000..5ad5bc50 --- /dev/null +++ b/0001-0500/0147-Insertion-Sort-List/cpp-0147/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(cpp_0147) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(cpp_0147 main.cpp) \ No newline at end of file diff --git a/0001-0500/0147-Insertion-Sort-List/cpp-0147/main.cpp b/0001-0500/0147-Insertion-Sort-List/cpp-0147/main.cpp new file mode 100644 index 00000000..b712abc5 --- /dev/null +++ b/0001-0500/0147-Insertion-Sort-List/cpp-0147/main.cpp @@ -0,0 +1,111 @@ +/// Source : https://leetcode.com/problems/insertion-sort-list/ +/// Author : liuyubobobo +/// Time : 2019-02-13 + +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(n^2) +/// Space Compelxity: O(1) + +/// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} +}; + + +ListNode* createLinkedList(int arr[], int n){ + + if(n == 0) + return NULL; + + ListNode* head = new ListNode(arr[0]); + ListNode* curNode = head; + for(int i = 1 ; i < n ; i ++){ + curNode->next = new ListNode(arr[i]); + curNode = curNode->next; + } + + return head; +} + +void printLinkedList(ListNode* head){ + + ListNode* curNode = head; + while(curNode != NULL){ + cout << curNode->val << " -> "; + curNode = curNode->next; + } + + cout << "NULL" << endl; + + return; +} + +void deleteLinkedList(ListNode* head){ + + ListNode* curNode = head; + while(curNode != NULL){ + ListNode* delNode = curNode; + curNode = curNode->next; + delete delNode; + } + + return; +} + +class Solution { +public: + ListNode* insertionSortList(ListNode* head) { + + if(!head || !head->next) return head; + + ListNode* dummyHead = new ListNode(-1); + dummyHead->next = head; + + ListNode* pre = dummyHead->next; + while(pre->next){ + int val = pre->next->val; + ListNode* next = pre->next->next; + ListNode* pi = dummyHead; + for(; pi != pre; pi = pi->next) + if(pi->next->val > val){ + ListNode* pj = pi->next; + ListNode* swapNode = pre->next; + + pi->next = swapNode; + swapNode->next = pj; + pre->next = next; + + break; + } + + if(pi == pre) pre = pre->next; +// printLinkedList(dummyHead); + } + return dummyHead->next; + } +}; + + +int main() { + + int arr1[4] = {4, 2, 1, 3}; + ListNode* head1 = createLinkedList(arr1, 4); + ListNode* res1 = Solution().insertionSortList(head1); + printLinkedList(res1); + deleteLinkedList(res1); + + int arr2[5] = {-1, 5, 3, 4, 0}; + ListNode* head2 = createLinkedList(arr2, 5); + ListNode* res2 = Solution().insertionSortList(head2); + printLinkedList(res2); + deleteLinkedList(res2); + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0148-Sort-List/cpp-0148/CMakeLists.txt b/0001-0500/0148-Sort-List/cpp-0148/CMakeLists.txt new file mode 100644 index 00000000..1bc533c1 --- /dev/null +++ b/0001-0500/0148-Sort-List/cpp-0148/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0148) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main2.cpp) +add_executable(cpp_0148 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0148-Sort-List/cpp-0148/main.cpp b/0001-0500/0148-Sort-List/cpp-0148/main.cpp new file mode 100644 index 00000000..15c45ed5 --- /dev/null +++ b/0001-0500/0148-Sort-List/cpp-0148/main.cpp @@ -0,0 +1,119 @@ +/// Source : https://leetcode.com/problems/two-sum/description/ +/// Author : liuyubobobo +/// Time : 2018-08-21 + +#include +#include + +using namespace std; + +/// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} +}; + +class ListOp{ + +public: + // 根据n个元素的数组arr创建一个链表, 并返回链表的头 + static ListNode* createLinkedList(const vector& arr){ + + if(arr.size() == 0) + return NULL; + + ListNode* head = new ListNode(arr[0]); + ListNode* curNode = head; + for(int i = 1 ; i < arr.size() ; i ++){ + curNode->next = new ListNode(arr[i]); + curNode = curNode->next; + } + return head; + } + + // 打印以head为头结点的链表信息内容 + static void printLinkedList(ListNode* head){ + + ListNode* curNode = head; + while(curNode){ + cout << curNode->val << " -> "; + curNode = curNode->next; + } + cout << "NULL" << endl; + } + + // 释放以head为头结点的链表空间 + static void deleteLinkedList(ListNode* head){ + + ListNode* curNode = head; + while(curNode){ + ListNode* delNode = curNode; + curNode = curNode->next; + delete delNode; + } + } +}; + + +/// Merge Sort Top Down +/// Time Complexity: O(nlogn) +/// Space Complexity: O(logn) +class Solution { +public: + ListNode* sortList(ListNode* head) { + + if(head == NULL || head->next == NULL) + return head; + + ListNode* slow = head; + ListNode* fast = head->next; + while(fast && fast->next){ + slow = slow->next; + fast = fast->next->next; + } + + ListNode* head2 = slow->next; + slow->next = NULL; + head = sortList(head); + head2 = sortList(head2); + return merge(head, head2); + } + +private: + ListNode* merge(ListNode* a, ListNode* b){ + + ListNode* dummyHead = new ListNode(-1); + ListNode *p1 = a, *p2 = b, *p = dummyHead; + while(p1 && p2) + if(p1->val < p2->val){ + p->next = p1; + p1 = p1->next; + p = p->next; + p->next = NULL; + } + else{ + p->next = p2; + p2 = p2->next; + p = p->next; + p->next = NULL; + } + if(p1) p->next = p1; + if(p2) p->next = p2; + + ListNode* ret = dummyHead->next; + delete dummyHead; + return ret; + } +}; + + +int main() { + + vector arr = {4, 2, 1, 3}; + ListNode* head = Solution().sortList(ListOp::createLinkedList(arr)); + ListOp::printLinkedList(head); + ListOp::deleteLinkedList(head); + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0148-Sort-List/cpp-0148/main2.cpp b/0001-0500/0148-Sort-List/cpp-0148/main2.cpp new file mode 100644 index 00000000..030155dc --- /dev/null +++ b/0001-0500/0148-Sort-List/cpp-0148/main2.cpp @@ -0,0 +1,145 @@ +/// Source : https://leetcode.com/problems/two-sum/description/ +/// Author : liuyubobobo +/// Time : 2018-08-21 + +#include +#include + +using namespace std; + +/// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} +}; + +class ListOp{ + +public: + // 根据n个元素的数组arr创建一个链表, 并返回链表的头 + static ListNode* createLinkedList(const vector& arr){ + + if(arr.size() == 0) + return NULL; + + ListNode* head = new ListNode(arr[0]); + ListNode* curNode = head; + for(int i = 1 ; i < arr.size() ; i ++){ + curNode->next = new ListNode(arr[i]); + curNode = curNode->next; + } + return head; + } + + // 打印以head为头结点的链表信息内容 + static void printLinkedList(ListNode* head){ + + ListNode* curNode = head; + while(curNode){ + cout << curNode->val << " -> "; + curNode = curNode->next; + } + cout << "NULL" << endl; + } + + // 释放以head为头结点的链表空间 + static void deleteLinkedList(ListNode* head){ + + ListNode* curNode = head; + while(curNode){ + ListNode* delNode = curNode; + curNode = curNode->next; + delete delNode; + } + } +}; + + +/// Merge Sort Bottom Up +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + ListNode* sortList(ListNode* head) { + + if(head == NULL || head->next == NULL) + return head; + + ListNode* dummyHead = new ListNode(-1); + dummyHead->next = head; + int sz = 1; + while(true){ + ListNode *pre = dummyHead, *cur = pre; + + while(cur->next){ + cur = pre; + for(int i = 0; i < sz && cur->next; i ++, cur = cur->next); + + if(cur->next){ + ListNode* pre2 = cur; + for(int i = 0; i < sz && cur->next; i ++, cur = cur->next); + ListNode* next = cur->next, *head2 = pre2->next; + pre2->next = NULL, cur->next = NULL; + + ListNode* tail; + pre->next = merge(pre->next, head2, tail); + + pre = tail; + pre->next = next; + } + else if(pre == dummyHead){ + sz = 0; + break; + } + } + + if(sz == 0) break; + else sz *= 2; + } + + ListNode* ret = dummyHead->next; + delete dummyHead; + return ret; + } + +private: + ListNode* merge(ListNode* a, ListNode* b, ListNode* &tail){ + + ListNode* dummyHead = new ListNode(-1); + ListNode *p1 = a, *p2 = b, *p = dummyHead; + while(p1 && p2) + if(p1->val < p2->val){ + p->next = p1; + p1 = p1->next; + p = p->next; + p->next = NULL; + } + else{ + p->next = p2; + p2 = p2->next; + p = p->next; + p->next = NULL; + } + if(p1) p->next = p1; + if(p2) p->next = p2; + + tail = p; + while(tail->next) tail = tail->next; + + ListNode* ret = dummyHead->next; + delete dummyHead; + return ret; + } +}; + + +int main() { + + vector arr = {4, 2, 1, 3}; + ListNode* head = Solution().sortList(ListOp::createLinkedList(arr)); + ListOp::printLinkedList(head); + ListOp::deleteLinkedList(head); + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0149-Max-Points-on-a-Line/cpp-0149/CMakeLists.txt b/0001-0500/0149-Max-Points-on-a-Line/cpp-0149/CMakeLists.txt new file mode 100644 index 00000000..b1a6a464 --- /dev/null +++ b/0001-0500/0149-Max-Points-on-a-Line/cpp-0149/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_Max_Points_on_a_Line) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_Max_Points_on_a_Line ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0149-Max-Points-on-a-Line/cpp-0149/main.cpp b/0001-0500/0149-Max-Points-on-a-Line/cpp-0149/main.cpp new file mode 100644 index 00000000..836c31f1 --- /dev/null +++ b/0001-0500/0149-Max-Points-on-a-Line/cpp-0149/main.cpp @@ -0,0 +1,83 @@ +/// Source : https://leetcode.com/problems/max-points-on-a-line/ +/// Author : liuyubobobo +/// Time : 2017-07-17 +/// Updated: 2021-06-23 + +#include +#include +#include + +using namespace std; + + +/// Using Hash Map +/// Using pair directly to record the slopes +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { +public: + int maxPoints(vector>& points) { + + if(points.size() <= 1) + return points.size(); + + int res = 1; + for( int i = 0 ; i < points.size() ; i ++ ){ + + map, int> record; + int samePoint = 0; + for( int j = 0 ; j < points.size() ; j ++ ){ + if( points[i][0] == points[j][0] && points[i][1] == points[j][1]) + samePoint ++; + else + record[slope(points[j], points[i])]++; + } + + res = max(res, samePoint); // In case the record is empty and all the points are in the same point. + for(map,int>::iterator iter = record.begin() ; iter != record.end() ; iter ++) + res = max(res, iter->second + samePoint); + } + + return res; + } + +private: + pair slope(const vector& pa, const vector& pb){ + + int dy = pa[1] - pb[1]; + int dx = pa[0] - pb[0]; + if(dx == 0) + return make_pair(1,0); + if(dy == 0) + return make_pair(0,1); + + int g = gcd(abs(dy), abs(dx)); + dy /= g; + dx /= g; + if(dx < 0){ + dy = -dy; + dx = -dx; + } + return make_pair(dy, dx); + } + + int gcd(int a, int b){ + + if(a < b) + swap(a, b); + + if(a % b == 0) + return b; + + return gcd(b, a%b ); + } +}; + + +int main() { + + vector> pvec1 = {{1, 1}, {1, 1}}; + cout< +#include +#include + +using namespace std; + + +/// Using Stacks +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int evalRPN(vector& tokens) { + + stack nums; + for(const string& s: tokens){ + if(s == "+" || s == "-" || s == "*" || s == "/"){ + int a = nums.top(); + nums.pop(); + int b = nums.top(); + nums.pop(); + + if(s == "+") + nums.push(b + a); + else if(s == "-") + nums.push(b - a); + else if(s == "*") + nums.push(b * a); + else if(s == "/") + nums.push(b / a); + } + else + nums.push(atoi(s.c_str())); + } + return nums.top(); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0151-Reverse-Words-in-a-String/cpp-0151/CMakeLists.txt b/0001-0500/0151-Reverse-Words-in-a-String/cpp-0151/CMakeLists.txt new file mode 100644 index 00000000..83b7754e --- /dev/null +++ b/0001-0500/0151-Reverse-Words-in-a-String/cpp-0151/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0151) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main3.cpp) +add_executable(cpp_0151 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0151-Reverse-Words-in-a-String/cpp-0151/main.cpp b/0001-0500/0151-Reverse-Words-in-a-String/cpp-0151/main.cpp new file mode 100644 index 00000000..deea1e9b --- /dev/null +++ b/0001-0500/0151-Reverse-Words-in-a-String/cpp-0151/main.cpp @@ -0,0 +1,71 @@ +/// Source : https://leetcode.com/problems/reverse-words-in-a-string/description/ +/// Author : liuyubobobo +/// Time : 2018-08-10 +/// Updated: 2021-07-02 + +#include +#include + +using namespace std; + + +/// Split and Reverse +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +public: + string reverseWords(string &s) { + + vector vec = split(s); + if(vec.size() == 0){ + s = ""; + return s; + } + + reverse(vec.begin(), vec.end()); + s = vec[0]; + for(int i = 1; i < vec.size() ; i ++) + s += " " + vec[i]; + + return s; + } + +private: + vector split(const string& s){ + + vector res; + + int start = nextNonSpace(s, 0); + for(int i = start + 1; i <= s.size() ;) + if(i == s.size() || s[i] == ' ') { + res.push_back(s.substr(start, i - start)); + start = nextNonSpace(s, i); + i = start + 1; + } + else + i ++; + + return res; + } + + int nextNonSpace(const string& s, int start){ + int i = start; + for(; i < s.size() ; i ++) + if(s[i] != ' ') + return i; + return i; + } +}; + + +int main() { + + string s1 = "the sky is blue"; + cout << Solution().reverseWords(s1) << endl; + + string s2 = ""; + cout << Solution().reverseWords(s2) << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0151-Reverse-Words-in-a-String/cpp-0151/main2.cpp b/0001-0500/0151-Reverse-Words-in-a-String/cpp-0151/main2.cpp new file mode 100644 index 00000000..f33301d9 --- /dev/null +++ b/0001-0500/0151-Reverse-Words-in-a-String/cpp-0151/main2.cpp @@ -0,0 +1,86 @@ +/// Source : https://leetcode.com/problems/reverse-words-in-a-string/description/ +/// Author : liuyubobobo +/// Time : 2018-08-12 +/// Updated: 2021-07-02 + +#include +#include + +using namespace std; + + +/// Reverse then reverse:) +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { + +public: + string reverseWords(string &s) { + + int start = nextNonSpace(s, 0); + s = s.substr(start); + + start = 0; + for(int i = start + 1; i <= s.size() ; ) + if(i == s.size() || s[i] == ' '){ + start = nextNonSpace(s, i); + if(start != s.size()) + s = s.substr(0, i) + " " + s.substr(start); + else{ + s = s.substr(0, i); + break; + } + + start = i + 1; + i = start + 1; + } + else + i ++; + + reverse(s, 0, s.size() - 1); + start = 0; + for(int i = start + 1; i <= s.size() ; ) + if(i == s.size() || s[i] == ' '){ + reverse(s, start, i - 1); + start = i + 1; + i = start + 1; + } + else + i ++; + + return s; + } + +private: + int nextNonSpace(const string& s, int start){ + int i = start; + for(; i < s.size() ; i ++) + if(s[i] != ' ') + return i; + return i; + } + + void reverse(string& s, int start, int end){ + int i = start, j = end; + while(i < j) + swap(s[i++], s[j--]); + } +}; + + +int main() { + + string s1 = "the sky is blue"; + cout << Solution().reverseWords(s1) << endl; + + string s2 = ""; + cout << Solution().reverseWords(s2) << endl; + + string s3 = " 1 "; + cout << Solution().reverseWords(s3) << endl; + + string s4 = " a b "; + cout << Solution().reverseWords(s4) << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0151-Reverse-Words-in-a-String/cpp-0151/main3.cpp b/0001-0500/0151-Reverse-Words-in-a-String/cpp-0151/main3.cpp new file mode 100644 index 00000000..2b6eb889 --- /dev/null +++ b/0001-0500/0151-Reverse-Words-in-a-String/cpp-0151/main3.cpp @@ -0,0 +1,94 @@ +/// Source : https://leetcode.com/problems/reverse-words-in-a-string/description/ +/// Author : liuyubobobo +/// Time : 2018-08-12 +/// Updated: 2021-07-02 + +#include +#include + +using namespace std; + + +/// Reverse then reverse +/// really do all the things in place:) +/// +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { + +public: + string reverseWords(string &s) { + + int search_start = nextNonSpace(s, 0); + if(search_start == s.size()){ + s = ""; + return s; + } + + int start = 0; + for(int i = search_start + 1; i <= s.size() ; ) + if(i == s.size() || s[i] == ' '){ + + for(int j = search_start; j < i ; j ++) + s[start++] = s[j]; + + search_start = nextNonSpace(s, i); + if(search_start == s.size()){ + s = s.substr(0, start); + break; + } + else + s[start++] = ' '; + + i = search_start + 1; + } + else + i ++; + + reverse(s, 0, s.size() - 1); + start = 0; + for(int i = start + 1; i <= s.size() ; ) + if(i == s.size() || s[i] == ' '){ + reverse(s, start, i - 1); + start = i + 1; + i = start + 1; + } + else + i ++; + + return s; + } + +private: + int nextNonSpace(const string& s, int start){ + int i = start; + for(; i < s.size() ; i ++) + if(s[i] != ' ') + return i; + return i; + } + + void reverse(string& s, int start, int end){ + int i = start, j = end; + while(i < j) + swap(s[i++], s[j--]); + } +}; + + +int main() { + + string s1 = "the sky is blue"; + cout << Solution().reverseWords(s1) << endl; + + string s2 = ""; + cout << Solution().reverseWords(s2) << endl; + + string s3 = " 1 "; + cout << Solution().reverseWords(s3) << endl; + + string s4 = " a b "; + cout << Solution().reverseWords(s4) << s4 << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0152-Maximum-Product-Subarray/cpp-0152/CMakeLists.txt b/0001-0500/0152-Maximum-Product-Subarray/cpp-0152/CMakeLists.txt new file mode 100644 index 00000000..be43ed49 --- /dev/null +++ b/0001-0500/0152-Maximum-Product-Subarray/cpp-0152/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0152) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0152 main.cpp) \ No newline at end of file diff --git a/0001-0500/0152-Maximum-Product-Subarray/cpp-0152/main.cpp b/0001-0500/0152-Maximum-Product-Subarray/cpp-0152/main.cpp new file mode 100644 index 00000000..0d321471 --- /dev/null +++ b/0001-0500/0152-Maximum-Product-Subarray/cpp-0152/main.cpp @@ -0,0 +1,66 @@ +/// Source : https://leetcode.com/problems/maximum-product-subarray/ +/// Author : liuyubobobo +/// Time : 2021-02-25 + +#include +#include + +using namespace std; + + +/// Split and Linear Scan +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int maxProduct(vector& nums) { + + int res = nums[0] == 0 ? 0 : INT_MIN; + bool has_zero = false; + for(int start = next_non_zero(nums, 0), i = start + 1; i <= nums.size(); i ++) + if(i == nums.size() || nums[i] == 0){ + if(i < nums.size() && nums[i] == 0) has_zero = true; + res = max(res, solve(nums, start, i - 1)); + start = next_non_zero(nums, i); + i = start; + } + + if(has_zero) res = max(res, 0); + return res; + } + +private: + int solve(const vector& nums, int l, int r){ + + int res = nums[l], cur = nums[l]; + for(int i = l + 1; i <= r; i ++){ + cur *= nums[i]; + res = max(res, cur); + } + + res = max(res, nums[r]); + cur = nums[r]; + for(int i = r - 1; i >= l; i --){ + cur *= nums[i]; + res = max(res, cur); + } + return res; + } + + int next_non_zero(const vector& nums, int start){ + + for(int i = start; i < nums.size(); i ++) + if(nums[i] != 0) return i; + return nums.size(); + } +}; + + +int main() { + + vector nums1 = {-3, 0, 1, -2}; + cout << Solution().maxProduct(nums1) << endl; + // 1 + + return 0; +} diff --git a/0001-0500/0152-Maximum-Product-Subarray/py-0152/Solution1.py b/0001-0500/0152-Maximum-Product-Subarray/py-0152/Solution1.py new file mode 100644 index 00000000..641ff8a9 --- /dev/null +++ b/0001-0500/0152-Maximum-Product-Subarray/py-0152/Solution1.py @@ -0,0 +1,31 @@ +# Source : https://leetcode.com/problems/maximum-product-subarray/ +# Author : penpenps +# Time : 2019-07-21 + +from typing import List + +# Travesal nums, use maxVal and minVal to keep max and min product end with current element +# Time Complexity: O(n) +# Space Complexity: O(1) + +class Solution: + def maxProduct(self, nums: List[int]) -> int: + n = len(nums) + minVal, maxVal = nums[0], nums[0] + ans = nums[0] + for i in range(1, n): + # If negative number, it should swap min and max for sign switching + if nums[i] < 0: + minVal, maxVal = maxVal, minVal + maxVal = max(nums[i]*maxVal, nums[i]) + minVal = min(nums[i]*minVal, nums[i]) + ans = max(maxVal, ans) + + return ans + + +if __name__ == '__main__': + s = Solution() + nums = [2,3,-2,4] + answer = s.maxProduct(nums) + print(answer) diff --git a/0001-0500/0152-Maximum-Product-Subarray/py-0152/Solution2.py b/0001-0500/0152-Maximum-Product-Subarray/py-0152/Solution2.py new file mode 100644 index 00000000..a5935d13 --- /dev/null +++ b/0001-0500/0152-Maximum-Product-Subarray/py-0152/Solution2.py @@ -0,0 +1,27 @@ +# Source : https://leetcode.com/problems/maximum-product-subarray/ +# Author : penpenps +# Time : 2019-07-21 + +from typing import List + +# If even number of elements, the max product is multiple all nums together +# If odd number, it should be divided into to part from one of the negative numbers and the answer is one of two seperated parts to multiple together +# Time Complexity: O(n) +# Space Complexity: O(1) + +class Solution: + def maxProduct(self, nums: List[int]) -> int: + n = len(nums) + rnums = nums[::-1] + for i in range(1, n): + nums[i] *= nums[i-1] or 1 + rnums[i] *= rnums[i-1] or 1 + + return max(nums + rnums) + + +if __name__ == '__main__': + s = Solution() + nums = [2,3,-2,4] + answer = s.maxProduct(nums) + print(answer) diff --git a/0001-0500/0153-Find-Minimum-in-Rotated-Sorted-Array/cpp-0153/CMakeLists.txt b/0001-0500/0153-Find-Minimum-in-Rotated-Sorted-Array/cpp-0153/CMakeLists.txt new file mode 100644 index 00000000..b5d0a91a --- /dev/null +++ b/0001-0500/0153-Find-Minimum-in-Rotated-Sorted-Array/cpp-0153/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0153) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main2.cpp) +add_executable(cpp_0153 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0153-Find-Minimum-in-Rotated-Sorted-Array/cpp-0153/main.cpp b/0001-0500/0153-Find-Minimum-in-Rotated-Sorted-Array/cpp-0153/main.cpp new file mode 100644 index 00000000..b86b7170 --- /dev/null +++ b/0001-0500/0153-Find-Minimum-in-Rotated-Sorted-Array/cpp-0153/main.cpp @@ -0,0 +1,38 @@ +/// Source : https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/description/ +/// Author : liuyubobobo +/// Time : 2018-09-07 + +#include +#include +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int findMin(vector& nums) { + return *min_element(nums.begin(), nums.end()); + } +}; + + +int main() { + + vector nums1 = {3, 4, 5, 1, 2}; + cout << Solution().findMin(nums1) << endl; // 1 + + vector nums2 = {4, 5, 6, 7, 0, 1, 2}; + cout << Solution().findMin(nums2) << endl; // 0 + + vector nums3 = {3, 1, 2}; + cout << Solution().findMin(nums3) << endl; // 1 + + vector nums4 = {7, 1, 2, 3, 4, 5, 6}; + cout << Solution().findMin(nums4) << endl; // 1 + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0153-Find-Minimum-in-Rotated-Sorted-Array/cpp-0153/main2.cpp b/0001-0500/0153-Find-Minimum-in-Rotated-Sorted-Array/cpp-0153/main2.cpp new file mode 100644 index 00000000..bb197cef --- /dev/null +++ b/0001-0500/0153-Find-Minimum-in-Rotated-Sorted-Array/cpp-0153/main2.cpp @@ -0,0 +1,58 @@ +/// Source : https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/description/ +/// Author : liuyubobobo +/// Time : 2018-09-07 + +#include +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(logn) +/// Space Complexity: O(1) +class Solution { +public: + int findMin(vector& nums) { + + assert(nums.size() > 0); + if(nums.size() == 1) + return nums[0]; + if(nums.size() == 2) + return min(nums[0], nums[1]); + + int l = 0, r = nums.size() - 1; + while(l < r){ + int mid = l + (r - l) / 2; + if(nums[l] <= nums[mid] && nums[mid] <= nums[r]) + return nums[l]; + + if(nums[l] > nums[mid]) + l = l + 1, r = mid; + else if(nums[r] < nums[mid]) + l = mid + 1; + else + assert(false); + } + return nums[l]; + } +}; + + +int main() { + + vector nums1 = {3, 4, 5, 1, 2}; + cout << Solution().findMin(nums1) << endl; // 1 + + vector nums2 = {4, 5, 6, 7, 0, 1, 2}; + cout << Solution().findMin(nums2) << endl; // 0 + + vector nums3 = {3, 1, 2}; + cout << Solution().findMin(nums3) << endl; // 1 + + vector nums4 = {7, 1, 2, 3, 4, 5, 6}; + cout << Solution().findMin(nums4) << endl; // 1 + + return 0; +} \ No newline at end of file diff --git a/0155-Min-Stack/cpp-0155/CMakeLists.txt b/0001-0500/0155-Min-Stack/cpp-0155/CMakeLists.txt similarity index 100% rename from 0155-Min-Stack/cpp-0155/CMakeLists.txt rename to 0001-0500/0155-Min-Stack/cpp-0155/CMakeLists.txt diff --git a/0155-Min-Stack/cpp-0155/main.cpp b/0001-0500/0155-Min-Stack/cpp-0155/main.cpp similarity index 100% rename from 0155-Min-Stack/cpp-0155/main.cpp rename to 0001-0500/0155-Min-Stack/cpp-0155/main.cpp diff --git a/0155-Min-Stack/cpp-0155/main2.cpp b/0001-0500/0155-Min-Stack/cpp-0155/main2.cpp similarity index 100% rename from 0155-Min-Stack/cpp-0155/main2.cpp rename to 0001-0500/0155-Min-Stack/cpp-0155/main2.cpp diff --git a/0155-Min-Stack/cpp-0155/main3.cpp b/0001-0500/0155-Min-Stack/cpp-0155/main3.cpp similarity index 100% rename from 0155-Min-Stack/cpp-0155/main3.cpp rename to 0001-0500/0155-Min-Stack/cpp-0155/main3.cpp diff --git a/old/0159 Longest Substring with At Most Two Distinct Characters/cpp-Longest-Substring-with-At-Most-Two-Distinct-Characters/CMakeLists.txt b/0001-0500/0159-Longest-Substring-with-At-Most-Two-Distinct-Characters/cpp-0159/CMakeLists.txt similarity index 100% rename from old/0159 Longest Substring with At Most Two Distinct Characters/cpp-Longest-Substring-with-At-Most-Two-Distinct-Characters/CMakeLists.txt rename to 0001-0500/0159-Longest-Substring-with-At-Most-Two-Distinct-Characters/cpp-0159/CMakeLists.txt diff --git a/0001-0500/0159-Longest-Substring-with-At-Most-Two-Distinct-Characters/cpp-0159/main1.cpp b/0001-0500/0159-Longest-Substring-with-At-Most-Two-Distinct-Characters/cpp-0159/main1.cpp new file mode 100644 index 00000000..0e49697c --- /dev/null +++ b/0001-0500/0159-Longest-Substring-with-At-Most-Two-Distinct-Characters/cpp-0159/main1.cpp @@ -0,0 +1,60 @@ +/// Source : https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/description/ +/// Author : liuyubobobo +/// Time : 2016-12-30 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// Two Pointers + HashMap +/// Recording how many different characters in the current string by map. +/// +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int lengthOfLongestSubstringTwoDistinct(string s) { + + unordered_map map; + int l = 0, r = 0; + int res = 0; + while(r <= s.size()){ + if(r == s.size() || (map.size() == 2 && map.find(s[r]) == map.end())){ + res = max(res, r-l); + while(map.size() >= 2){ + if(map[s[l]] == 1) + map.erase(s[l]); + else + map[s[l]] --; + l ++; + } + + if( r == s.size() ) + break; + } + else{ + if(map.find(s[r]) == map.end()) + map[s[r]] = 1; + else + map[s[r]] += 1; + r ++; + } + } + + return res; + } +}; + + +int main() { + + cout << Solution().lengthOfLongestSubstringTwoDistinct("eceba") << endl; + cout << Solution().lengthOfLongestSubstringTwoDistinct("a") << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0159-Longest-Substring-with-At-Most-Two-Distinct-Characters/cpp-0159/main2.cpp b/0001-0500/0159-Longest-Substring-with-At-Most-Two-Distinct-Characters/cpp-0159/main2.cpp new file mode 100644 index 00000000..9cc011d5 --- /dev/null +++ b/0001-0500/0159-Longest-Substring-with-At-Most-Two-Distinct-Characters/cpp-0159/main2.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/description/ +/// Author : liuyubobobo +/// Time : 2017-03-01 +#include +#include +#include +#include +#include + +using namespace std; + + +/// Two Pointers + Static Array as HashMap +/// Using self-built hashtable to record how many different characters in the current string +/// +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int lengthOfLongestSubstringTwoDistinct(string s) { + + int hashtable[256] = {0}; + int l = 0, r = 0; + int res = 0; + int count = 0; + while(r <= s.size()){ + if(r == s.size() || (count == 2 && !hashtable[s[r]])){ + res = max(res, r-l); + while(count >= 2){ + hashtable[s[l]] --; + if(hashtable[s[l]] == 0) + count --; + l ++; + } + + if(r == s.size()) + break; + } + else{ + hashtable[s[r]] ++; + if(hashtable[s[r]] == 1) + count ++; + r ++; + } + } + + return res; + } +}; + +int main() { + + cout << Solution().lengthOfLongestSubstringTwoDistinct("eceba") << endl; + cout << Solution().lengthOfLongestSubstringTwoDistinct("a") << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0160-Intersection-of-Two-Linked-Lists/cpp-0160/CMakeLists.txt b/0001-0500/0160-Intersection-of-Two-Linked-Lists/cpp-0160/CMakeLists.txt new file mode 100644 index 00000000..d26bcccb --- /dev/null +++ b/0001-0500/0160-Intersection-of-Two-Linked-Lists/cpp-0160/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0160) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main3.cpp) +add_executable(cpp_0160 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0160-Intersection-of-Two-Linked-Lists/cpp-0160/main.cpp b/0001-0500/0160-Intersection-of-Two-Linked-Lists/cpp-0160/main.cpp new file mode 100644 index 00000000..61a4aea8 --- /dev/null +++ b/0001-0500/0160-Intersection-of-Two-Linked-Lists/cpp-0160/main.cpp @@ -0,0 +1,36 @@ +/// Source : https://leetcode.com/problems/intersection-of-two-linked-lists/description/ +/// Author : liuyubobobo +/// Time : 2018-10-01 + +#include + +using namespace std; + +/// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} +}; + + +/// Brute Force +/// Time Complexity: O(m*n) +/// Space Complexity: O(1) +class Solution { +public: + ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { + + for(ListNode* pA = headA; pA; pA = pA->next) + for(ListNode* pB = headB; pB; pB = pB->next) + if(pA == pB) + return pA; + return NULL; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0160-Intersection-of-Two-Linked-Lists/cpp-0160/main2.cpp b/0001-0500/0160-Intersection-of-Two-Linked-Lists/cpp-0160/main2.cpp new file mode 100644 index 00000000..4de2ff46 --- /dev/null +++ b/0001-0500/0160-Intersection-of-Two-Linked-Lists/cpp-0160/main2.cpp @@ -0,0 +1,41 @@ +/// Source : https://leetcode.com/problems/intersection-of-two-linked-lists/description/ +/// Author : liuyubobobo +/// Time : 2018-10-01 + +#include +#include + +using namespace std; + +/// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} +}; + + +/// Using HashSet +/// Time Complexity: O(m + n) +/// Space Complexity: O(m) +class Solution { +public: + ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { + + unordered_set set; + for(ListNode* pA = headA; pA; pA = pA->next) + set.insert(pA); + + for(ListNode* pB = headB; pB; pB = pB->next) + if(set.count(pB)) + return pB; + + return NULL; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0160-Intersection-of-Two-Linked-Lists/cpp-0160/main3.cpp b/0001-0500/0160-Intersection-of-Two-Linked-Lists/cpp-0160/main3.cpp new file mode 100644 index 00000000..819a4b9f --- /dev/null +++ b/0001-0500/0160-Intersection-of-Two-Linked-Lists/cpp-0160/main3.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/intersection-of-two-linked-lists/description/ +/// Author : liuyubobobo +/// Time : 2018-10-01 + +#include +#include + +using namespace std; + +/// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} +}; + + +/// Two Pointers +/// Time Complexity: O(m + n) +/// Space Complexity: O(1) +class Solution { +public: + ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { + + ListNode* pA = headA; + ListNode* pB = headB; + while(pA || pB){ + + if(pA == pB) + return pA; + + if(pA) pA = pA->next; + else pA = headB; + + if(pB) pB = pB->next; + else pB = headA; + } + + return NULL; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0161-One-Edit-Distance/cpp-0161/CMakeLists.txt b/0001-0500/0161-One-Edit-Distance/cpp-0161/CMakeLists.txt new file mode 100644 index 00000000..c64418bb --- /dev/null +++ b/0001-0500/0161-One-Edit-Distance/cpp-0161/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(cpp_0161) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(cpp_0161 main2.cpp) \ No newline at end of file diff --git a/0001-0500/0161-One-Edit-Distance/cpp-0161/main.cpp b/0001-0500/0161-One-Edit-Distance/cpp-0161/main.cpp new file mode 100644 index 00000000..dac2f31d --- /dev/null +++ b/0001-0500/0161-One-Edit-Distance/cpp-0161/main.cpp @@ -0,0 +1,70 @@ +/// Source : https://leetcode.com/problems/one-edit-distance/ +/// Author : liuyubobobo +/// Time : 2019-02-14 + +#include +#include + +using namespace std; + + +/// Three One Pass Algorithms +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { + +public: + bool isOneEditDistance(string s, string t) { + + if(s.size() == 0) return t.size() == 1; + if(t.size() == 0) return s.size() == 1; + + if(s.size() + 1 == t.size()) + return can_add_char(s, t); + else if(s.size() == t.size() + 1) + return can_delete_char(s, t); + else if(s.size() == t.size()) + return can_replace_char(s, t); + return false; + } + +private: + bool can_replace_char(const string& s, const string& t){ + + assert(s.size() == t.size()); + + int diff = 0; + for(int i = 0; i < s.size(); i ++) + diff += s[i] != t[i]; + return diff == 1; + } + + bool can_delete_char(const string& s, const string& t){ + return can_add_char(t, s); + } + + bool can_add_char(const string&s, const string& t){ + + int si = 0, ti = 0; + while(si < s.size() && ti < t.size() && s[si] == t[ti]) si ++, ti ++; + si --; + + int sj = s.size() - 1, tj = t.size() - 1; + while(sj > si && tj > ti && s[sj] == t[tj]) sj --, tj --; + +// cout << "si=" << si << " sj=" << sj << " ti=" << ti << " tj=" << tj << endl; + return si == sj; + } +}; + + +int main() { + + string s1 = "ab", t1 = "acb"; + cout << Solution().isOneEditDistance(s1, t1) << endl; + + string s2 = "cab", t2 = "ad"; + cout << Solution().isOneEditDistance(s2, t2) << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0161-One-Edit-Distance/cpp-0161/main2.cpp b/0001-0500/0161-One-Edit-Distance/cpp-0161/main2.cpp new file mode 100644 index 00000000..be83cc1e --- /dev/null +++ b/0001-0500/0161-One-Edit-Distance/cpp-0161/main2.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/one-edit-distance/ +/// Author : liuyubobobo +/// Time : 2019-02-14 + +#include +#include + +using namespace std; + + +/// One Pass Algorithms +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { + +public: + bool isOneEditDistance(string s, string t) { + + if(s.size() == 0) return t.size() == 1; + if(t.size() == 0) return s.size() == 1; + + int si = 0, ti = 0; + while(si < s.size() && ti < t.size() && s[si] == t[ti]) si ++, ti ++; + si --, ti --; + + int sj = s.size() - 1, tj = t.size() - 1; + while(sj > si && tj > ti && s[sj] == t[tj]) sj --, tj --; + + if(si + 1 == sj && ti == tj) return true; + if(ti + 1 == tj && si == sj) return true; + if(si + 1 == sj && ti + 1 == tj) return true; + return false; + } +}; + + +int main() { + + string s1 = "ab", t1 = "acb"; + cout << Solution().isOneEditDistance(s1, t1) << endl; + + string s2 = "cab", t2 = "ad"; + cout << Solution().isOneEditDistance(s2, t2) << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0162-Find-Peak-Element/cpp-0162/CMakeLists.txt b/0001-0500/0162-Find-Peak-Element/cpp-0162/CMakeLists.txt new file mode 100644 index 00000000..0ab637bd --- /dev/null +++ b/0001-0500/0162-Find-Peak-Element/cpp-0162/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_0162) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0162 main2.cpp) \ No newline at end of file diff --git a/0001-0500/0162-Find-Peak-Element/cpp-0162/main.cpp b/0001-0500/0162-Find-Peak-Element/cpp-0162/main.cpp new file mode 100644 index 00000000..bf156768 --- /dev/null +++ b/0001-0500/0162-Find-Peak-Element/cpp-0162/main.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/find-peak-element/ +/// Author : liuyubobobo +/// Time : 2021-06-15 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int findPeakElement(vector& nums) { + + if(nums.size() == 1) return 0; + + int n = nums.size(); + if(nums[0] > nums[1]) return 0; + if(nums[n - 1] > nums[n - 2]) return n - 1; + + for(int i = 1; i + 1 < n; i ++) + if(nums[i] > nums[i - 1] && nums[i] > nums[i + 1]) + return i; + return -1; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0162-Find-Peak-Element/cpp-0162/main2.cpp b/0001-0500/0162-Find-Peak-Element/cpp-0162/main2.cpp new file mode 100644 index 00000000..3f3a383d --- /dev/null +++ b/0001-0500/0162-Find-Peak-Element/cpp-0162/main2.cpp @@ -0,0 +1,39 @@ +/// Source : https://leetcode.com/problems/find-peak-element/ +/// Author : liuyubobobo +/// Time : 2021-06-15 + +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(logn) +/// Space Complexity: O(1) +class Solution { +public: + int findPeakElement(vector& nums) { + + if(nums.size() == 1) return 0; + + return binary_search(nums, 0, nums.size() - 1); + } + +private: + int binary_search(const vector& nums, int l, int r){ + + if(l == r) return l; + + int mid = (l + r) / 2; + if(mid + 1 <= r && nums[mid] > nums[mid + 1]) + return binary_search(nums, l, mid); + return binary_search(nums, mid + 1, r); + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0163-Missing-Ranges/cpp-0163/CMakeLists.txt b/0001-0500/0163-Missing-Ranges/cpp-0163/CMakeLists.txt new file mode 100644 index 00000000..04b67844 --- /dev/null +++ b/0001-0500/0163-Missing-Ranges/cpp-0163/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0163) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0163 main.cpp) \ No newline at end of file diff --git a/0001-0500/0163-Missing-Ranges/cpp-0163/main.cpp b/0001-0500/0163-Missing-Ranges/cpp-0163/main.cpp new file mode 100644 index 00000000..4f87bdf7 --- /dev/null +++ b/0001-0500/0163-Missing-Ranges/cpp-0163/main.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/missing-ranges/ +/// Author : liuyubobobo +/// Time : 2020-12-08 +/// Updated: 2022-06-16 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + vector> findMissingRanges(vector& nums, int lower, int upper) { + + nums.push_back(upper + 1); + + vector> res; + int l = lower; + for(int i = 0; i < nums.size(); i ++){ + if(nums[i] == l) l ++; + else{ + res.push_back({l, nums[i] - 1}); + l = nums[i] + 1; + } + } + return res; + } +}; + + +void print_vec(const vector>& v){ + for(const vector& seg: v) cout << '(' << seg[0] << ',' << seg[1] << ')'; + cout << '\n'; +} + +int main() { + + vector nums1 = {0, 1, 3, 50, 75}; + print_vec(Solution().findMissingRanges(nums1, 0, 99)); + + return 0; +} diff --git a/0001-0500/0164-Maximum-Gap/cpp-0164/CMakeLists.txt b/0001-0500/0164-Maximum-Gap/cpp-0164/CMakeLists.txt new file mode 100644 index 00000000..4930a530 --- /dev/null +++ b/0001-0500/0164-Maximum-Gap/cpp-0164/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0164) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0164 main.cpp) \ No newline at end of file diff --git a/0001-0500/0164-Maximum-Gap/cpp-0164/main.cpp b/0001-0500/0164-Maximum-Gap/cpp-0164/main.cpp new file mode 100644 index 00000000..fd50d713 --- /dev/null +++ b/0001-0500/0164-Maximum-Gap/cpp-0164/main.cpp @@ -0,0 +1,32 @@ +/// Source : https://leetcode.com/problems/maximum-gap/ +/// Author : liuyubobobo +/// Time : 2021-03-04 + +#include +#include + +using namespace std; + + +/// Sorting +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + int maximumGap(vector& nums) { + + if(nums.size() < 2) return 0; + + sort(nums.begin(), nums.end()); + int res = INT_MIN; + for(int i = 1; i < nums.size(); i ++) + res = max(res, nums[i] - nums[i - 1]); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0165-Compare-Version-Numbers/cpp-0165/CMakeLists.txt b/0001-0500/0165-Compare-Version-Numbers/cpp-0165/CMakeLists.txt new file mode 100644 index 00000000..cf012893 --- /dev/null +++ b/0001-0500/0165-Compare-Version-Numbers/cpp-0165/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0165) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0165 main.cpp) diff --git a/0001-0500/0165-Compare-Version-Numbers/cpp-0165/main.cpp b/0001-0500/0165-Compare-Version-Numbers/cpp-0165/main.cpp new file mode 100644 index 00000000..affde4b0 --- /dev/null +++ b/0001-0500/0165-Compare-Version-Numbers/cpp-0165/main.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/compare-version-numbers/ +/// Author : liuyubobobo +/// Time : 2021-08-31 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(|v1| + |v2|) +/// Space Complexity: O(|v1| + |v2|) +class Solution { +public: + int compareVersion(string version1, string version2) { + + vector v1 = get_ver(version1), v2 = get_ver(version2); + + while(v1.size() < v2.size()) v1.push_back(0); + while(v2.size() < v1.size()) v2.push_back(0); + return v1 == v2 ? 0 : (v1 < v2 ? -1 : 1); + } + +private: + vector get_ver(string s){ + + vector res; + while(true){ + int p = s.find('.'); + if(p == string::npos){ + res.push_back(atoi(s.c_str())); + break; + } + + res.push_back(atoi(s.substr(0, p).c_str())); + s = s.substr(p + 1); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0166-Fraction-to- Recurring-Decimal/cpp-0166/CMakeLists.txt b/0001-0500/0166-Fraction-to- Recurring-Decimal/cpp-0166/CMakeLists.txt new file mode 100644 index 00000000..213f7300 --- /dev/null +++ b/0001-0500/0166-Fraction-to- Recurring-Decimal/cpp-0166/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0166) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0166 main.cpp) diff --git a/0001-0500/0166-Fraction-to- Recurring-Decimal/cpp-0166/main.cpp b/0001-0500/0166-Fraction-to- Recurring-Decimal/cpp-0166/main.cpp new file mode 100644 index 00000000..a1119d7f --- /dev/null +++ b/0001-0500/0166-Fraction-to- Recurring-Decimal/cpp-0166/main.cpp @@ -0,0 +1,75 @@ +/// Source : https://leetcode.com/problems/fraction-to-recurring-decimal/ +/// Author : liuyubobobo +/// Time : 2021-10-02 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(denominator) +/// Space Complexity: O(denominator) +class Solution { +public: + string fractionToDecimal(long long numerator, long long denominator) { + + if(numerator == 0) return "0"; + + string res = ""; + if(sign(numerator) * sign(denominator) < 0) + res += "-"; + + numerator = abs(numerator); + denominator = abs(denominator); + + res += to_string(numerator / denominator); + numerator %= denominator; + + if(numerator == 0) return res; + + res += "."; + + map pos; + while(numerator){ + numerator *= 10; + if(pos.count(numerator)){ + int p = pos[numerator]; + string a = res.substr(0, p), b = res.substr(p); + return a + "(" + b + ")"; + } + + pos[numerator] = res.size(); + res += ('0' + (numerator / denominator)); + numerator %= denominator; + } + return res; + } + +private: + int sign(long long x){ + return x > 0 ? 1 : -1; + } +}; + + +int main() { + + cout << Solution().fractionToDecimal(1, 2) << endl; + // 0.5 + + cout << Solution().fractionToDecimal(2, 1) << endl; + // 2 + + cout << Solution().fractionToDecimal(2, 3) << endl; + // 0.(6) + + cout << Solution().fractionToDecimal(4, 333) << endl; + // 0.(012) + + cout << Solution().fractionToDecimal(1, 5) << endl; + // 0.2 + + return 0; +} diff --git a/0167-Two-Sum-II-Input-array-is-sorted/cpp-0167/CMakeLists.txt b/0001-0500/0167-Two-Sum-II-Input-array-is-sorted/cpp-0167/CMakeLists.txt similarity index 100% rename from 0167-Two-Sum-II-Input-array-is-sorted/cpp-0167/CMakeLists.txt rename to 0001-0500/0167-Two-Sum-II-Input-array-is-sorted/cpp-0167/CMakeLists.txt diff --git a/0167-Two-Sum-II-Input-array-is-sorted/cpp-0167/main.cpp b/0001-0500/0167-Two-Sum-II-Input-array-is-sorted/cpp-0167/main.cpp similarity index 100% rename from 0167-Two-Sum-II-Input-array-is-sorted/cpp-0167/main.cpp rename to 0001-0500/0167-Two-Sum-II-Input-array-is-sorted/cpp-0167/main.cpp diff --git a/0167-Two-Sum-II-Input-array-is-sorted/cpp-0167/main2.cpp b/0001-0500/0167-Two-Sum-II-Input-array-is-sorted/cpp-0167/main2.cpp similarity index 100% rename from 0167-Two-Sum-II-Input-array-is-sorted/cpp-0167/main2.cpp rename to 0001-0500/0167-Two-Sum-II-Input-array-is-sorted/cpp-0167/main2.cpp diff --git a/0167-Two-Sum-II-Input-array-is-sorted/cpp-0167/main3.cpp b/0001-0500/0167-Two-Sum-II-Input-array-is-sorted/cpp-0167/main3.cpp similarity index 100% rename from 0167-Two-Sum-II-Input-array-is-sorted/cpp-0167/main3.cpp rename to 0001-0500/0167-Two-Sum-II-Input-array-is-sorted/cpp-0167/main3.cpp diff --git a/0167-Two-Sum-II-Input-array-is-sorted/java-0167/src/Solution1.java b/0001-0500/0167-Two-Sum-II-Input-array-is-sorted/java-0167/src/Solution1.java similarity index 100% rename from 0167-Two-Sum-II-Input-array-is-sorted/java-0167/src/Solution1.java rename to 0001-0500/0167-Two-Sum-II-Input-array-is-sorted/java-0167/src/Solution1.java diff --git a/0167-Two-Sum-II-Input-array-is-sorted/java-0167/src/Solution2.java b/0001-0500/0167-Two-Sum-II-Input-array-is-sorted/java-0167/src/Solution2.java similarity index 100% rename from 0167-Two-Sum-II-Input-array-is-sorted/java-0167/src/Solution2.java rename to 0001-0500/0167-Two-Sum-II-Input-array-is-sorted/java-0167/src/Solution2.java diff --git a/0167-Two-Sum-II-Input-array-is-sorted/java-0167/src/Solution3.java b/0001-0500/0167-Two-Sum-II-Input-array-is-sorted/java-0167/src/Solution3.java similarity index 100% rename from 0167-Two-Sum-II-Input-array-is-sorted/java-0167/src/Solution3.java rename to 0001-0500/0167-Two-Sum-II-Input-array-is-sorted/java-0167/src/Solution3.java diff --git a/0001-0500/0168-Excel-Sheet-Column-Title/cpp-0168/CMakeLists.txt b/0001-0500/0168-Excel-Sheet-Column-Title/cpp-0168/CMakeLists.txt new file mode 100644 index 00000000..9a66f9ee --- /dev/null +++ b/0001-0500/0168-Excel-Sheet-Column-Title/cpp-0168/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_0168) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0168 main.cpp) \ No newline at end of file diff --git a/0001-0500/0168-Excel-Sheet-Column-Title/cpp-0168/main.cpp b/0001-0500/0168-Excel-Sheet-Column-Title/cpp-0168/main.cpp new file mode 100644 index 00000000..e6f8d59e --- /dev/null +++ b/0001-0500/0168-Excel-Sheet-Column-Title/cpp-0168/main.cpp @@ -0,0 +1,51 @@ +/// Source : https://leetcode.com/problems/excel-sheet-column-title/ +/// Author : liuyubobobo +/// Time : 2021-06-28 + +#include +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(logn) +/// Space Complexity: O(1) +class Solution { +public: + string convertToTitle(int columnNumber) { + + string res = ""; + while(columnNumber){ + int c = columnNumber % 26; + if(c == 0) c += 26; + + res += string(1, 'A' + c - 1); + columnNumber = (columnNumber - c) / 26; + } + reverse(res.begin(), res.end()); + return res; + } +}; + + +int main() { + + cout << Solution().convertToTitle(1) << endl; + // A + + cout << Solution().convertToTitle(28) << endl; + // AB + + cout << Solution().convertToTitle(701) << endl; + // ZY + + cout << Solution().convertToTitle(2147483647) << endl; + // FXSHRXW + + cout << Solution().convertToTitle(52) << endl; + // AZ + + return 0; +} diff --git a/0169-Majority-Element/cpp-0169/CMakeLists.txt b/0001-0500/0169-Majority-Element/cpp-0169/CMakeLists.txt similarity index 100% rename from 0169-Majority-Element/cpp-0169/CMakeLists.txt rename to 0001-0500/0169-Majority-Element/cpp-0169/CMakeLists.txt diff --git a/0169-Majority-Element/cpp-0169/main.cpp b/0001-0500/0169-Majority-Element/cpp-0169/main.cpp similarity index 100% rename from 0169-Majority-Element/cpp-0169/main.cpp rename to 0001-0500/0169-Majority-Element/cpp-0169/main.cpp diff --git a/0169-Majority-Element/cpp-0169/main2.cpp b/0001-0500/0169-Majority-Element/cpp-0169/main2.cpp similarity index 100% rename from 0169-Majority-Element/cpp-0169/main2.cpp rename to 0001-0500/0169-Majority-Element/cpp-0169/main2.cpp diff --git a/0169-Majority-Element/cpp-0169/main3.cpp b/0001-0500/0169-Majority-Element/cpp-0169/main3.cpp similarity index 100% rename from 0169-Majority-Element/cpp-0169/main3.cpp rename to 0001-0500/0169-Majority-Element/cpp-0169/main3.cpp diff --git a/0169-Majority-Element/cpp-0169/main4.cpp b/0001-0500/0169-Majority-Element/cpp-0169/main4.cpp similarity index 100% rename from 0169-Majority-Element/cpp-0169/main4.cpp rename to 0001-0500/0169-Majority-Element/cpp-0169/main4.cpp diff --git a/0169-Majority-Element/cpp-0169/main5.cpp b/0001-0500/0169-Majority-Element/cpp-0169/main5.cpp similarity index 100% rename from 0169-Majority-Element/cpp-0169/main5.cpp rename to 0001-0500/0169-Majority-Element/cpp-0169/main5.cpp diff --git a/0001-0500/0169-Majority-Element/py-0169/Solution.py b/0001-0500/0169-Majority-Element/py-0169/Solution.py new file mode 100644 index 00000000..91ef31b4 --- /dev/null +++ b/0001-0500/0169-Majority-Element/py-0169/Solution.py @@ -0,0 +1,13 @@ +# Source : https://leetcode.com/problems/majority-element/ +# Author : penpenps +# Time : 2019-07-22 + +from typing import List + +# Sort nums and pick the (n/2)-th number +# Time Complexity: O(nlogn) +# Space Complexity: O(n) + +class Solution: + def majorityElement(self, nums: List[int]) -> int: + return sorted(nums)[len(nums)//2] diff --git a/0001-0500/0169-Majority-Element/py-0169/Solution2.py b/0001-0500/0169-Majority-Element/py-0169/Solution2.py new file mode 100644 index 00000000..134f5203 --- /dev/null +++ b/0001-0500/0169-Majority-Element/py-0169/Solution2.py @@ -0,0 +1,18 @@ +# Source : https://leetcode.com/problems/majority-element/ +# Author : penpenps +# Time : 2019-07-22 + +from typing import List + +# Count occurance for each number and find out the one whose occurance more than n/2 times +# Time Complexity: O(n) +# Space Complexity: O(n) + +import collections +class Solution: + def majorityElement(self, nums: List[int]) -> int: + m = collections.Counter(nums) + n = len(nums) + for k,v in m.items(): + if v >= n/2: + return k diff --git a/0001-0500/0169-Majority-Element/py-0169/Solution3.py b/0001-0500/0169-Majority-Element/py-0169/Solution3.py new file mode 100644 index 00000000..991edcf6 --- /dev/null +++ b/0001-0500/0169-Majority-Element/py-0169/Solution3.py @@ -0,0 +1,21 @@ +# Source : https://leetcode.com/problems/majority-element/ +# Author : penpenps +# Time : 2019-07-22 + +from typing import List + +# Randomly pick one to check whether the answer +# Time Complexity: Worst: O(infinity) Average: O(n) +# Space Complexity: O(1) + +import random +class Solution: + def majorityElement(self, nums: List[int]) -> int: + def occurance(nums, target): + return sum(1 if x == target else 0 for x in nums) + + n = len(nums) + while True: + index = random.randint(0, n-1) + if occurance(nums, nums[index]) >= n / 2: + return nums[index] diff --git a/0001-0500/0169-Majority-Element/py-0169/Solution4.py b/0001-0500/0169-Majority-Element/py-0169/Solution4.py new file mode 100644 index 00000000..beb73d5f --- /dev/null +++ b/0001-0500/0169-Majority-Element/py-0169/Solution4.py @@ -0,0 +1,28 @@ +# Source : https://leetcode.com/problems/majority-element/ +# Author : penpenps +# Time : 2019-07-22 + +from typing import List + +# Recursivly divide two half parts and search most occurance number +# Time Complexity: O(nlogn) +# Space Complexity: O(logn) + +class Solution: + def majorityElement(self, nums: List[int]) -> int: + def occurance(nums, left, right, target): + return sum(1 if x == target else 0 for x in nums[left:right+1]) + def helper(nums, left, right): + length = right - left + 1 + if length <= 2: + return nums[left] + mid = (left+right) // 2 + leftMaj = helper(nums, left, mid) + rightMaj = helper(nums, mid+1, right) + if leftMaj == rightMaj: + return leftMaj + leftMajCnt = occurance(nums, left, mid, leftMaj) + rightMajCnt = occurance(nums, mid+1, right, rightMaj) + + return leftMaj if leftMajCnt > rightMajCnt else rightMaj + return helper(nums, 0, len(nums)-1) diff --git a/0001-0500/0169-Majority-Element/py-0169/Solution5.py b/0001-0500/0169-Majority-Element/py-0169/Solution5.py new file mode 100644 index 00000000..5267e498 --- /dev/null +++ b/0001-0500/0169-Majority-Element/py-0169/Solution5.py @@ -0,0 +1,23 @@ +# Source : https://leetcode.com/problems/majority-element/ +# Author : penpenps +# Time : 2019-07-22 + +from typing import List + +# Boyer-Moore Voting Algorithm, count for one number, if not equal to current number, count minus 1 until ot 0 then try another number +# Time Complexity: O(n) +# Space Complexity: O(1) + +class Solution: + def majorityElement(self, nums: List[int]) -> int: + ans = nums[0] + count = 0 + for n in nums: + if count == 0: + ans = n + count += 1 + elif n == ans: + count += 1 + else: + count -= 1 + return ans diff --git a/old/0170 Two Sum III - Data structure design/cpp-Two-Sum-III/CMakeLists.txt b/0001-0500/0170-Two-Sum-III-Data-structure-design/cpp-0170/CMakeLists.txt similarity index 100% rename from old/0170 Two Sum III - Data structure design/cpp-Two-Sum-III/CMakeLists.txt rename to 0001-0500/0170-Two-Sum-III-Data-structure-design/cpp-0170/CMakeLists.txt diff --git a/0001-0500/0170-Two-Sum-III-Data-structure-design/cpp-0170/main.cpp b/0001-0500/0170-Two-Sum-III-Data-structure-design/cpp-0170/main.cpp new file mode 100644 index 00000000..9c04c587 --- /dev/null +++ b/0001-0500/0170-Two-Sum-III-Data-structure-design/cpp-0170/main.cpp @@ -0,0 +1,56 @@ +/// Source : https://leetcode.com/problems/two-sum-iii-data-structure-design/ +/// Author : liuyubobobo +/// Time : 2016-12-03 +#include +#include +#include +#include + +using namespace std; + + +/// Using HashMap +/// Time Complexity: add: O(1) , find: O(n) +/// Space Complexity: O(n) +class TwoSum { + +private: + // The numbers store the number pair represent (number, count of the number) + unordered_map numbers; + +public: + // Add the number to an internal data structure. + void add(int number) { + numbers[number] += 1; + } + + // Find if there exists any pair of numbers which sum is equal to the value. + bool find(int value) { + + for( unordered_map::iterator iter = numbers.begin() ; iter != numbers.end() ; iter ++ ){ + int num = iter->first; + if( numbers.find(value - num) != numbers.end() ){ + if( value - num == num && numbers[num] == 1 ) + continue; + + return true; + } + } + + return false; + } +}; + + +int main() { + + TwoSum twoSum; + twoSum.add(1); + twoSum.add(3); + twoSum.add(5); + + cout << twoSum.find(4) << endl; + cout << twoSum.find(7) << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0171-Excel-Sheet-Column/cpp-0171/CMakeLists.txt b/0001-0500/0171-Excel-Sheet-Column/cpp-0171/CMakeLists.txt new file mode 100644 index 00000000..18a0a55e --- /dev/null +++ b/0001-0500/0171-Excel-Sheet-Column/cpp-0171/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0171) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0171 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0171-Excel-Sheet-Column/cpp-0171/main.cpp b/0001-0500/0171-Excel-Sheet-Column/cpp-0171/main.cpp new file mode 100644 index 00000000..e5d66858 --- /dev/null +++ b/0001-0500/0171-Excel-Sheet-Column/cpp-0171/main.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/excel-sheet-column-number/description/ +/// Author : liuyubobobo +/// Time : 2018-08-30 + +#include +#include + +using namespace std; + + +/// 26-based number +/// Time Complexity: O(len(s)) +/// Space Complexity: O(1) +class Solution { +public: + int titleToNumber(string s) { + + int num = 0; + for(char c: s) + num = num * 26 + (c - 'A' + 1); + + return num; + } +}; + + +int main() { + + cout << Solution().titleToNumber("A") << endl; // 1 + cout << Solution().titleToNumber("AB") << endl; // 28 + cout << Solution().titleToNumber("ZY") << endl; // 701 + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0172-Factorial-Trailing-Zeroes/cpp-0172/CMakeLists.txt b/0001-0500/0172-Factorial-Trailing-Zeroes/cpp-0172/CMakeLists.txt new file mode 100644 index 00000000..9e142993 --- /dev/null +++ b/0001-0500/0172-Factorial-Trailing-Zeroes/cpp-0172/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_0172) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0172 main.cpp) diff --git a/0001-0500/0172-Factorial-Trailing-Zeroes/cpp-0172/main.cpp b/0001-0500/0172-Factorial-Trailing-Zeroes/cpp-0172/main.cpp new file mode 100644 index 00000000..7c10ed51 --- /dev/null +++ b/0001-0500/0172-Factorial-Trailing-Zeroes/cpp-0172/main.cpp @@ -0,0 +1,26 @@ +/// Source : https://leetcode.com/problems/factorial-trailing-zeroes/ +/// Author : liuyubobobo +/// Time : 2022-03-24 + +#include + +using namespace std; + + +/// Math +/// Time Complexity: O(logn) +/// Space Complexity: O(1) +class Solution { +public: + int trailingZeroes(int n) { + int res = 0; + for(int p = 5; p <= n; p *= 5) res += n / p; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0173-Binary-Search-Tree-Iterator/cpp-0173/CMakeLists.txt b/0001-0500/0173-Binary-Search-Tree-Iterator/cpp-0173/CMakeLists.txt new file mode 100644 index 00000000..e910bcef --- /dev/null +++ b/0001-0500/0173-Binary-Search-Tree-Iterator/cpp-0173/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0173) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main3.cpp) +add_executable(cpp_0173 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0173-Binary-Search-Tree-Iterator/cpp-0173/main.cpp b/0001-0500/0173-Binary-Search-Tree-Iterator/cpp-0173/main.cpp new file mode 100644 index 00000000..5dde8cca --- /dev/null +++ b/0001-0500/0173-Binary-Search-Tree-Iterator/cpp-0173/main.cpp @@ -0,0 +1,64 @@ +/// Source : https://leetcode.com/problems/binary-search-tree-iterator/description/ +/// Author : liuyubobobo +/// Time : 2018-06-06 + +#include +#include + +using namespace std; + +/// Definition for binary tree +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +/// Using an array to store all the elements +/// +/// Time Complexity: initial: O(n) +/// hasNext: O(1) +/// next: O(1) +/// Space Complexity: O(n) +class BSTIterator { + +private: + vector data; + int nextIndex; + +public: + BSTIterator(TreeNode *root) { + data.clear(); + inOrder(root); + + nextIndex = 0; + } + + /** @return whether we have a next smallest number */ + bool hasNext() { + return nextIndex < data.size(); + } + + /** @return the next smallest number */ + int next() { + return data[nextIndex ++]; + } + +private: + void inOrder(TreeNode* node){ + + if(node == NULL) + return; + + inOrder(node->left); + data.push_back(node->val); + inOrder(node->right); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0173-Binary-Search-Tree-Iterator/cpp-0173/main2.cpp b/0001-0500/0173-Binary-Search-Tree-Iterator/cpp-0173/main2.cpp new file mode 100644 index 00000000..1c7d58af --- /dev/null +++ b/0001-0500/0173-Binary-Search-Tree-Iterator/cpp-0173/main2.cpp @@ -0,0 +1,96 @@ +/// Source : https://leetcode.com/problems/binary-search-tree-iterator/description/ +/// Author : liuyubobobo +/// Time : 2018-06-06 + +#include +#include +#include +#include + +using namespace std; + +/// Definition for binary tree +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +/// Using My Non-recursive Inorder Traversal Algorithm +/// +/// Time Complexity: initial: O(1) +/// hasNext: O(h) +/// next: O(h) +/// Space Complexity: O(h) +class BSTIterator { + +private: + struct Command{ + string s; // go, visit + TreeNode* node; + Command(string s, TreeNode* node): s(s), node(node){} + }; + + stack myStack; + +public: + BSTIterator(TreeNode *root) { + + if(root != NULL) + myStack.push(Command("go", root)); + } + + /** @return whether we have a next smallest number */ + bool hasNext() { + + while(!myStack.empty()){ + Command command = myStack.top(); + myStack.pop(); + + if(command.s == "visit"){ + myStack.push(command); + return true; + } + else{ + assert(command.s == "go"); + if(command.node->right) + myStack.push(Command("go",command.node->right)); + myStack.push(Command("visit", command.node)); + if(command.node->left) + myStack.push(Command("go",command.node->left)); + } + } + + return false; + } + + /** @return the next smallest number */ + int next() { + + while(!myStack.empty()){ + Command command = myStack.top(); + myStack.pop(); + + if(command.s == "visit") + return command.node->val; + else{ + assert(command.s == "go"); + if(command.node->right) + myStack.push(Command("go",command.node->right)); + myStack.push(Command("visit", command.node)); + if(command.node->left) + myStack.push(Command("go",command.node->left)); + } + } + + assert(false); + return -1; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0173-Binary-Search-Tree-Iterator/cpp-0173/main3.cpp b/0001-0500/0173-Binary-Search-Tree-Iterator/cpp-0173/main3.cpp new file mode 100644 index 00000000..450a39c0 --- /dev/null +++ b/0001-0500/0173-Binary-Search-Tree-Iterator/cpp-0173/main3.cpp @@ -0,0 +1,68 @@ +/// Source : https://leetcode.com/problems/binary-search-tree-iterator/description/ +/// Author : liuyubobobo +/// Time : 2018-06-06 + +#include +#include +#include +#include + +using namespace std; + +/// Definition for binary tree +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +/// Using Classic Non-recursive Inorder Traversal Algorithm +/// +/// Time Complexity: initial: O(h) +/// hasNext: O(1) +/// next: O(h) +/// Space Complexity: O(h) +class BSTIterator { + +private: + stack myStack; + +public: + BSTIterator(TreeNode *root) { + + TreeNode* node = root; + while(node != NULL){ + myStack.push(node); + node = node->left; + } + } + + /** @return whether we have a next smallest number */ + bool hasNext() { + + return !myStack.empty(); + } + + /** @return the next smallest number */ + int next() { + + assert(hasNext()); + TreeNode* retNode = myStack.top(); + myStack.pop(); + + TreeNode* node = retNode->right; + while(node != NULL){ + myStack.push(node); + node = node->left; + } + + return retNode->val; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0174-Dungeon-Game/cpp-0174/CMakeLists.txt b/0001-0500/0174-Dungeon-Game/cpp-0174/CMakeLists.txt new file mode 100644 index 00000000..57cf5a07 --- /dev/null +++ b/0001-0500/0174-Dungeon-Game/cpp-0174/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0174) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0174 main.cpp) diff --git a/0001-0500/0174-Dungeon-Game/cpp-0174/main.cpp b/0001-0500/0174-Dungeon-Game/cpp-0174/main.cpp new file mode 100644 index 00000000..32b5c560 --- /dev/null +++ b/0001-0500/0174-Dungeon-Game/cpp-0174/main.cpp @@ -0,0 +1,38 @@ +/// Source : https://leetcode.com/problems/dungeon-game/ +/// Author : liuyubobobo +/// Time : 2021-10-02 + +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(R * C) +/// Space Complexity: O(R * C) +class Solution { +public: + int calculateMinimumHP(vector>& dungeon) { + + int R = dungeon.size(), C = dungeon[0].size(); + vector> dp(R, vector(C)); + + dp[R - 1][C - 1] = max(1 - dungeon[R - 1][C - 1], 1); + for(int j = C - 2; j >= 0; j --) + dp[R - 1][j] = max(dp[R - 1][j + 1] - dungeon[R - 1][j], 1); + + for(int i = R - 2; i >= 0; i --){ + dp[i][C - 1] = max(dp[i + 1][C - 1] - dungeon[i][C - 1], 1); + for(int j = C - 2; j >= 0; j --) + dp[i][j] = max(min(dp[i + 1][j], dp[i][j + 1]) - dungeon[i][j], 1); + } + return dp[0][0]; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0179-Largest-Number/cpp-0179/CMakeLists.txt b/0001-0500/0179-Largest-Number/cpp-0179/CMakeLists.txt new file mode 100644 index 00000000..1810d43c --- /dev/null +++ b/0001-0500/0179-Largest-Number/cpp-0179/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_0179) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0179 main.cpp) \ No newline at end of file diff --git a/0001-0500/0179-Largest-Number/cpp-0179/main.cpp b/0001-0500/0179-Largest-Number/cpp-0179/main.cpp new file mode 100644 index 00000000..5ed75dde --- /dev/null +++ b/0001-0500/0179-Largest-Number/cpp-0179/main.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/largest-number/ +/// Author : liuyubobobo +/// Time : 2021-04-12 + +#include +#include +#include +#include + +using namespace std; + + +/// Sorting +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + string largestNumber(vector& nums) { + + vector v; + for(int num: nums) v.push_back(to_string(num)); + + sort(v.begin(), v.end(), [](const string& a, const string& b){ + + return a + b > b + a; + }); + + string res = ""; + for(const string& s: v) res += s; + + while(res[0] == '0') res = res.substr(1); + return res.size() ? res : "0"; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0186-Reverse-Words-in-a-String-II/cpp-0186/CMakeLists.txt b/0001-0500/0186-Reverse-Words-in-a-String-II/cpp-0186/CMakeLists.txt new file mode 100644 index 00000000..df71e3ef --- /dev/null +++ b/0001-0500/0186-Reverse-Words-in-a-String-II/cpp-0186/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0186) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main2.cpp) +add_executable(cpp_0186 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0186-Reverse-Words-in-a-String-II/cpp-0186/main.cpp b/0001-0500/0186-Reverse-Words-in-a-String-II/cpp-0186/main.cpp new file mode 100644 index 00000000..286156aa --- /dev/null +++ b/0001-0500/0186-Reverse-Words-in-a-String-II/cpp-0186/main.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/reverse-words-in-a-string-ii/description/ +/// Author : liuyubobobo +/// Time : 2018-08-12 + +#include +#include + +using namespace std; + +/// Using a Stack to reverse the input +/// Time Complexity: O(len(s)) +/// Space Complexity: O(len(s)) +class Solution { +public: + void reverseWords(vector& str) { + + vector stack; + int start = 0; + string cur = ""; + for(int i = start; i <= str.size() ;) + if(i == str.size() || str[i] == ' '){ + stack.push_back(cur); + start = i + 1; + i = start; + cur = ""; + } + else + cur += str[i++]; + + int index = 0; + for(int i = stack.size() - 1; i >= 0 ; i --){ + for(int j = 0; j < stack[i].size() ; j ++) + str[index++] = stack[i][j]; + if(i > 0) + str[index++] = ' '; + } + } +}; + + +void print_vec(const vector& vec){ + for(char c: vec) + cout << c << " "; + cout << endl; +} + +int main() { + + vector str1 = {'t', 'h', 'e', ' ', + 's', 'k', 'y', ' ', + 'i', 's', ' ', + 'b', 'l', 'u', 'e'}; + Solution().reverseWords(str1); + print_vec(str1); + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0186-Reverse-Words-in-a-String-II/cpp-0186/main2.cpp b/0001-0500/0186-Reverse-Words-in-a-String-II/cpp-0186/main2.cpp new file mode 100644 index 00000000..1b40b1ce --- /dev/null +++ b/0001-0500/0186-Reverse-Words-in-a-String-II/cpp-0186/main2.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/reverse-words-in-a-string-ii/description/ +/// Author : liuyubobobo +/// Time : 2018-08-12 + +#include +#include + +using namespace std; + +/// Reverse and then Reverse +/// Time Complexity: O(len(s)) +/// Space Complexity: O(1) +class Solution { +public: + void reverseWords(vector& str) { + + reverse(str, 0, str.size() - 1); + int start = 0; + for(int i = start + 1; i <= str.size() ;) + if(i == str.size() || str[i] == ' '){ + reverse(str, start, i - 1); + start = i + 1; + i = start + 1; + } + else + i ++; + } + +private: + void reverse(vector& s, int start, int end){ + for(int i = start, j = end; i < j; i ++, j --) + swap(s[i], s[j]); + } +}; + + +void print_vec(const vector& vec){ + for(char c: vec) + cout << c << " "; + cout << endl; +} + +int main() { + + vector str1 = {'t', 'h', 'e', ' ', + 's', 'k', 'y', ' ', + 'i', 's', ' ', + 'b', 'l', 'u', 'e'}; + Solution().reverseWords(str1); + print_vec(str1); + + return 0; +} \ No newline at end of file diff --git a/0188-Best-Time-to-Buy-and-Sell-Stock-IV/cpp-0188/CMakeLists.txt b/0001-0500/0188-Best-Time-to-Buy-and-Sell-Stock-IV/cpp-0188/CMakeLists.txt similarity index 100% rename from 0188-Best-Time-to-Buy-and-Sell-Stock-IV/cpp-0188/CMakeLists.txt rename to 0001-0500/0188-Best-Time-to-Buy-and-Sell-Stock-IV/cpp-0188/CMakeLists.txt diff --git a/0188-Best-Time-to-Buy-and-Sell-Stock-IV/cpp-0188/main.cpp b/0001-0500/0188-Best-Time-to-Buy-and-Sell-Stock-IV/cpp-0188/main.cpp similarity index 100% rename from 0188-Best-Time-to-Buy-and-Sell-Stock-IV/cpp-0188/main.cpp rename to 0001-0500/0188-Best-Time-to-Buy-and-Sell-Stock-IV/cpp-0188/main.cpp diff --git a/0188-Best-Time-to-Buy-and-Sell-Stock-IV/cpp-0188/main2.cpp b/0001-0500/0188-Best-Time-to-Buy-and-Sell-Stock-IV/cpp-0188/main2.cpp similarity index 100% rename from 0188-Best-Time-to-Buy-and-Sell-Stock-IV/cpp-0188/main2.cpp rename to 0001-0500/0188-Best-Time-to-Buy-and-Sell-Stock-IV/cpp-0188/main2.cpp diff --git a/0188-Best-Time-to-Buy-and-Sell-Stock-IV/cpp-0188/main3.cpp b/0001-0500/0188-Best-Time-to-Buy-and-Sell-Stock-IV/cpp-0188/main3.cpp similarity index 100% rename from 0188-Best-Time-to-Buy-and-Sell-Stock-IV/cpp-0188/main3.cpp rename to 0001-0500/0188-Best-Time-to-Buy-and-Sell-Stock-IV/cpp-0188/main3.cpp diff --git a/0001-0500/0189-Rotate-Array/cpp-0189/CMakeLists.txt b/0001-0500/0189-Rotate-Array/cpp-0189/CMakeLists.txt new file mode 100644 index 00000000..40c24be3 --- /dev/null +++ b/0001-0500/0189-Rotate-Array/cpp-0189/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0189) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main5.cpp) +add_executable(cpp_0189 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0189-Rotate-Array/cpp-0189/main.cpp b/0001-0500/0189-Rotate-Array/cpp-0189/main.cpp new file mode 100644 index 00000000..10ecb20f --- /dev/null +++ b/0001-0500/0189-Rotate-Array/cpp-0189/main.cpp @@ -0,0 +1,48 @@ +/// Source : https://leetcode.com/problems/rotate-array/description/ +/// Author : liuyubobobo +/// Time : 2018-08-10 + +#include +#include +#include + +using namespace std; + +/// Using Queue +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { +public: + void rotate(vector& nums, int k) { + + queue q; + while(k -- && !nums.empty()) + q.push(nums.back()), nums.pop_back(); + for(int i = 0 ; i <= k ; i ++) + q.push(q.front()), q.pop(); + + while(!q.empty()) + nums.insert(nums.begin(), q.front()), q.pop(); + return; + } +}; + + +void print_vec(const vector& vec){ + for(int e: vec) + cout << e << " "; + cout << endl; +} + +int main() { + + vector nums1 = {1, 2, 3, 4, 5, 6, 7}; + Solution().rotate(nums1, 3); + print_vec(nums1); + + vector nums2 = {1, 2}; + Solution().rotate(nums2, 3); + print_vec(nums2); + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0189-Rotate-Array/cpp-0189/main2.cpp b/0001-0500/0189-Rotate-Array/cpp-0189/main2.cpp new file mode 100644 index 00000000..8f9b321e --- /dev/null +++ b/0001-0500/0189-Rotate-Array/cpp-0189/main2.cpp @@ -0,0 +1,65 @@ +/// Source : https://leetcode.com/problems/rotate-array/description/ +/// Author : liuyubobobo +/// Time : 2018-08-10 + +#include +#include +#include + +using namespace std; + +/// Using Queue and rotate the elements in original nums +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + void rotate(vector& nums, int k) { + + queue q; + int kk = k; + for(int i = (int)nums.size() - 1; i >= 0 && kk --; i --) + q.push(nums[i]); + for(int i = q.size() ; i < kk ; i ++) + q.push(q.front()), q.pop(); + + for(int i = (int)nums.size() - k - 1; i >= 0; i --) + nums[i + k] = nums[i]; + + while(!q.empty()){ + k --; + if(k < 0) + k += nums.size(); + k %= nums.size(); + nums[k] = q.front(); + q.pop(); + } + return; + } +}; + + +void print_vec(const vector& vec){ + for(int e: vec) + cout << e << " "; + cout << endl; +} + +int main() { + + vector nums1 = {1, 2, 3, 4, 5, 6, 7}; + Solution().rotate(nums1, 3); + print_vec(nums1); + // 5 6 7 1 2 3 4 + + vector nums2 = {1, 2}; + Solution().rotate(nums2, 3); + print_vec(nums2); + // 2 1 + + vector nums3 = {1, 2}; + Solution().rotate(nums3, 2); + print_vec(nums3); + // 1 2 + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0189-Rotate-Array/cpp-0189/main3.cpp b/0001-0500/0189-Rotate-Array/cpp-0189/main3.cpp new file mode 100644 index 00000000..6b530393 --- /dev/null +++ b/0001-0500/0189-Rotate-Array/cpp-0189/main3.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/rotate-array/description/ +/// Author : liuyubobobo +/// Time : 2018-08-10 + +#include +#include +#include + +using namespace std; + +/// Using O(1) Space but O(n^2) operations +/// Time Complexity: O(n^2) +/// Space Complexity: O(1) +class Solution { +public: + void rotate(vector& nums, int k) { + + while(k --){ + int t = nums.back(); + for(int i = (int)nums.size() - 2; i >= 0; i --) + nums[i + 1] = nums[i]; + nums[0] = t; + } + return; + } +}; + + +void print_vec(const vector& vec){ + for(int e: vec) + cout << e << " "; + cout << endl; +} + +int main() { + + vector nums1 = {1, 2, 3, 4, 5, 6, 7}; + Solution().rotate(nums1, 3); + print_vec(nums1); + // 5 6 7 1 2 3 4 + + vector nums2 = {1, 2}; + Solution().rotate(nums2, 3); + print_vec(nums2); + // 2 1 + + vector nums3 = {1, 2}; + Solution().rotate(nums3, 2); + print_vec(nums3); + // 1 2 + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0189-Rotate-Array/cpp-0189/main4.cpp b/0001-0500/0189-Rotate-Array/cpp-0189/main4.cpp new file mode 100644 index 00000000..2e3cc2e3 --- /dev/null +++ b/0001-0500/0189-Rotate-Array/cpp-0189/main4.cpp @@ -0,0 +1,63 @@ +/// Source : https://leetcode.com/problems/rotate-array/description/ +/// Author : liuyubobobo +/// Time : 2018-08-10 + +#include +#include +#include + +using namespace std; + +/// Cyclic Replacements +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + void rotate(vector& nums, int k) { + + int start = 0, cur = 0, t = nums[cur]; + for(int i = 0; i < nums.size() ; i ++){ + int next = (cur + k) % nums.size(); + int t2 = nums[next]; + nums[next] = t; + t = t2; + cur = next; + + if(cur == start) + start ++, cur = start, t = nums[cur]; + } + return; + } +}; + + +void print_vec(const vector& vec){ + for(int e: vec) + cout << e << " "; + cout << endl; +} + +int main() { + + vector nums1 = {1, 2, 3, 4, 5, 6, 7}; + Solution().rotate(nums1, 3); + print_vec(nums1); + // 5 6 7 1 2 3 4 + + vector nums2 = {1, 2}; + Solution().rotate(nums2, 3); + print_vec(nums2); + // 2 1 + + vector nums3 = {1, 2}; + Solution().rotate(nums3, 2); + print_vec(nums3); + // 1 2 + + vector nums4 = {1, 2, 3, 4, 5, 6}; + Solution().rotate(nums4, 3); + print_vec(nums4); + // 5 6 1 2 3 4 + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0189-Rotate-Array/cpp-0189/main5.cpp b/0001-0500/0189-Rotate-Array/cpp-0189/main5.cpp new file mode 100644 index 00000000..c8bcf37b --- /dev/null +++ b/0001-0500/0189-Rotate-Array/cpp-0189/main5.cpp @@ -0,0 +1,61 @@ +/// Source : https://leetcode.com/problems/rotate-array/description/ +/// Author : liuyubobobo +/// Time : 2018-08-10 + +#include +#include +#include + +using namespace std; + +/// Using Reverse +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + void rotate(vector& nums, int k) { + + k %= nums.size(); + reverse(nums, 0, nums.size() - 1); + reverse(nums, 0, k - 1); + reverse(nums, k, nums.size() - 1); + } + +private: + void reverse(vector& nums, int start, int end){ + for(int i = start, j = end; i < j; i ++, j --) + swap(nums[i], nums[j]); + } +}; + + +void print_vec(const vector& vec){ + for(int e: vec) + cout << e << " "; + cout << endl; +} + +int main() { + + vector nums1 = {1, 2, 3, 4, 5, 6, 7}; + Solution().rotate(nums1, 3); + print_vec(nums1); + // 5 6 7 1 2 3 4 + + vector nums2 = {1, 2}; + Solution().rotate(nums2, 3); + print_vec(nums2); + // 2 1 + + vector nums3 = {1, 2}; + Solution().rotate(nums3, 2); + print_vec(nums3); + // 1 2 + + vector nums4 = {1, 2, 3, 4, 5, 6}; + Solution().rotate(nums4, 2); + print_vec(nums4); + // 5 6 1 2 3 4 + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0190-Reverse-Bits/cpp-0190/CMakeLists.txt b/0001-0500/0190-Reverse-Bits/cpp-0190/CMakeLists.txt new file mode 100644 index 00000000..0bbbe398 --- /dev/null +++ b/0001-0500/0190-Reverse-Bits/cpp-0190/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0190) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0190 main.cpp) \ No newline at end of file diff --git a/0001-0500/0190-Reverse-Bits/cpp-0190/main.cpp b/0001-0500/0190-Reverse-Bits/cpp-0190/main.cpp new file mode 100644 index 00000000..14964255 --- /dev/null +++ b/0001-0500/0190-Reverse-Bits/cpp-0190/main.cpp @@ -0,0 +1,28 @@ +/// Source : https://leetcode.com/problems/reverse-bits/ +/// Author : liuyubobobo +/// Time : 2021-03-28 + +#include + + +/// Bitwise Operations +/// Time Complexity: O(logn) +/// Space Complexity: O(1) +class Solution { +public: + uint32_t reverseBits(uint32_t n) { + + uint32_t res = 0; + for(int i = 0; i < 32; i ++){ + res = (res << 1) + (n & 1); + n >>= 1; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0191-Number-of-1-Bits/cpp-0191/CMakeLists.txt b/0001-0500/0191-Number-of-1-Bits/cpp-0191/CMakeLists.txt new file mode 100644 index 00000000..450e9861 --- /dev/null +++ b/0001-0500/0191-Number-of-1-Bits/cpp-0191/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0191) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main2.cpp) +add_executable(cpp_0191 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0191-Number-of-1-Bits/cpp-0191/main.cpp b/0001-0500/0191-Number-of-1-Bits/cpp-0191/main.cpp new file mode 100644 index 00000000..38cd7006 --- /dev/null +++ b/0001-0500/0191-Number-of-1-Bits/cpp-0191/main.cpp @@ -0,0 +1,32 @@ +/// Source : https://leetcode.com/problems/number-of-1-bits/description/ +/// Author : liuyubobobo +/// Time : 2018-08-29 + +#include + +using namespace std; + + +/// Loop and Count +/// Two bit operations needed. +/// +/// Time Complexity: O(32) +/// Space Complexity: O(1) +class Solution { +public: + int hammingWeight(uint32_t n) { + + int res = 0; + while(n){ + res += (n & 1); + n >>= 1; + } + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0191-Number-of-1-Bits/cpp-0191/main2.cpp b/0001-0500/0191-Number-of-1-Bits/cpp-0191/main2.cpp new file mode 100644 index 00000000..61bc8633 --- /dev/null +++ b/0001-0500/0191-Number-of-1-Bits/cpp-0191/main2.cpp @@ -0,0 +1,32 @@ +/// Source : https://leetcode.com/problems/number-of-1-bits/description/ +/// Author : liuyubobobo +/// Time : 2018-08-29 + +#include + +using namespace std; + + +/// And Trick +/// Only one bit operation needed. +/// +/// Time Complexity: O(32) +/// Space Complexity: O(1) +class Solution { +public: + int hammingWeight(uint32_t n) { + + int res = 0; + while(n){ + n &= (n - 1) + res ++; + } + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0198-House-Robber/cpp-0198/CMakeLists.txt b/0001-0500/0198-House-Robber/cpp-0198/CMakeLists.txt similarity index 100% rename from 0198-House-Robber/cpp-0198/CMakeLists.txt rename to 0001-0500/0198-House-Robber/cpp-0198/CMakeLists.txt diff --git a/0198-House-Robber/cpp-0198/main.cpp b/0001-0500/0198-House-Robber/cpp-0198/main.cpp similarity index 100% rename from 0198-House-Robber/cpp-0198/main.cpp rename to 0001-0500/0198-House-Robber/cpp-0198/main.cpp diff --git a/0198-House-Robber/cpp-0198/main2.cpp b/0001-0500/0198-House-Robber/cpp-0198/main2.cpp similarity index 100% rename from 0198-House-Robber/cpp-0198/main2.cpp rename to 0001-0500/0198-House-Robber/cpp-0198/main2.cpp diff --git a/0198-House-Robber/cpp-0198/main3.cpp b/0001-0500/0198-House-Robber/cpp-0198/main3.cpp similarity index 100% rename from 0198-House-Robber/cpp-0198/main3.cpp rename to 0001-0500/0198-House-Robber/cpp-0198/main3.cpp diff --git a/0198-House-Robber/cpp-0198/main4.cpp b/0001-0500/0198-House-Robber/cpp-0198/main4.cpp similarity index 100% rename from 0198-House-Robber/cpp-0198/main4.cpp rename to 0001-0500/0198-House-Robber/cpp-0198/main4.cpp diff --git a/0198-House-Robber/cpp-0198/main5.cpp b/0001-0500/0198-House-Robber/cpp-0198/main5.cpp similarity index 100% rename from 0198-House-Robber/cpp-0198/main5.cpp rename to 0001-0500/0198-House-Robber/cpp-0198/main5.cpp diff --git a/0198-House-Robber/cpp-0198/main6.cpp b/0001-0500/0198-House-Robber/cpp-0198/main6.cpp similarity index 100% rename from 0198-House-Robber/cpp-0198/main6.cpp rename to 0001-0500/0198-House-Robber/cpp-0198/main6.cpp diff --git a/0198-House-Robber/java-0198/src/Solution1.java b/0001-0500/0198-House-Robber/java-0198/src/Solution1.java similarity index 100% rename from 0198-House-Robber/java-0198/src/Solution1.java rename to 0001-0500/0198-House-Robber/java-0198/src/Solution1.java diff --git a/0198-House-Robber/java-0198/src/Solution2.java b/0001-0500/0198-House-Robber/java-0198/src/Solution2.java similarity index 100% rename from 0198-House-Robber/java-0198/src/Solution2.java rename to 0001-0500/0198-House-Robber/java-0198/src/Solution2.java diff --git a/0198-House-Robber/java-0198/src/Solution3.java b/0001-0500/0198-House-Robber/java-0198/src/Solution3.java similarity index 100% rename from 0198-House-Robber/java-0198/src/Solution3.java rename to 0001-0500/0198-House-Robber/java-0198/src/Solution3.java diff --git a/0198-House-Robber/java-0198/src/Solution4.java b/0001-0500/0198-House-Robber/java-0198/src/Solution4.java similarity index 100% rename from 0198-House-Robber/java-0198/src/Solution4.java rename to 0001-0500/0198-House-Robber/java-0198/src/Solution4.java diff --git a/0198-House-Robber/java-0198/src/Solution5.java b/0001-0500/0198-House-Robber/java-0198/src/Solution5.java similarity index 100% rename from 0198-House-Robber/java-0198/src/Solution5.java rename to 0001-0500/0198-House-Robber/java-0198/src/Solution5.java diff --git a/0198-House-Robber/java-0198/src/Solution6.java b/0001-0500/0198-House-Robber/java-0198/src/Solution6.java similarity index 100% rename from 0198-House-Robber/java-0198/src/Solution6.java rename to 0001-0500/0198-House-Robber/java-0198/src/Solution6.java diff --git a/0001-0500/0199-Binary-Tree-Right-Side-View/cpp-0199/CMakeLists.txt b/0001-0500/0199-Binary-Tree-Right-Side-View/cpp-0199/CMakeLists.txt new file mode 100644 index 00000000..ab4316ce --- /dev/null +++ b/0001-0500/0199-Binary-Tree-Right-Side-View/cpp-0199/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(cpp_0199) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0199 main2.cpp) \ No newline at end of file diff --git a/0001-0500/0199-Binary-Tree-Right-Side-View/cpp-0199/main.cpp b/0001-0500/0199-Binary-Tree-Right-Side-View/cpp-0199/main.cpp new file mode 100644 index 00000000..ac5da6d1 --- /dev/null +++ b/0001-0500/0199-Binary-Tree-Right-Side-View/cpp-0199/main.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/binary-tree-right-side-view/ +/// Author : liuyubobobo +/// Time : 2019-09-26 + +#include +#include + +using namespace std; + + +/// BFS +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// 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: + vector rightSideView(TreeNode* root) { + + vector res; + if(!root) return res; + + vector cur = {root}; + while(cur.size()){ + res.push_back(cur.back()->val); + + vector next; + for(TreeNode* node: cur){ + if(node->left) next.push_back(node->left); + if(node->right) next.push_back(node->right); + } + cur = next; + } + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0199-Binary-Tree-Right-Side-View/cpp-0199/main2.cpp b/0001-0500/0199-Binary-Tree-Right-Side-View/cpp-0199/main2.cpp new file mode 100644 index 00000000..31d937e5 --- /dev/null +++ b/0001-0500/0199-Binary-Tree-Right-Side-View/cpp-0199/main2.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/binary-tree-right-side-view/ +/// Author : liuyubobobo +/// Time : 2019-09-26 + +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(h) + +/// 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 { + +private: + vector res; + +public: + vector rightSideView(TreeNode* root) { + + if(!root) return res; + + dfs(root, 0); + return res; + } + +private: + void dfs(TreeNode* node, int d){ + + if(res.size() <= d) res.push_back(0); + res[d] = node->val; + + if(node->left) dfs(node->left, d + 1); + if(node->right) dfs(node->right, d + 1); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0200-Number-of-Islands/cpp-0200/CMakeLists.txt b/0001-0500/0200-Number-of-Islands/cpp-0200/CMakeLists.txt new file mode 100644 index 00000000..d4093b63 --- /dev/null +++ b/0001-0500/0200-Number-of-Islands/cpp-0200/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0200) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main2.cpp) +add_executable(cpp_0200 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0200-Number-of-Islands/cpp-0200/main.cpp b/0001-0500/0200-Number-of-Islands/cpp-0200/main.cpp new file mode 100644 index 00000000..b7109375 --- /dev/null +++ b/0001-0500/0200-Number-of-Islands/cpp-0200/main.cpp @@ -0,0 +1,97 @@ +/// Source : https://leetcode.com/problems/number-of-islands/description/ +/// Author : liuyubobobo +/// Time : 2017-11-18 + +#include +#include +#include + +using namespace std; + +/// Floodfill - DFS +/// Recursion implementation +/// +/// Time Complexity: O(n*m) +/// Space Complexity: O(n*m) +class Solution { + +private: + int d[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + int m, n; + vector> visited; + + bool inArea(int x, int y){ + return x >= 0 && x < m && y >= 0 && y < n; + } + + void dfs(vector>& grid, int x, int y){ + + //assert(inArea(x,y)); + visited[x][y] = true; + for(int i = 0; i < 4; i ++){ + int newx = x + d[i][0]; + int newy = y + d[i][1]; + if(inArea(newx, newy) && !visited[newx][newy] && grid[newx][newy] == '1') + dfs(grid, newx, newy); + } + + return; + } + +public: + int numIslands(vector>& grid) { + + m = grid.size(); + if(m == 0) + return 0; + n = grid[0].size(); + if(n == 0) + return 0; + + for(int i = 0 ; i < m ; i ++) + visited.push_back(vector(n, false)); + + int res = 0; + for(int i = 0 ; i < m ; i ++) + for(int j = 0 ; j < n ; j ++) + if(grid[i][j] == '1' && !visited[i][j]){ + dfs(grid, i, j); + res ++; + } + return res; + } +}; + + +int main() { + + char g1[4][5] = { + {'1','1','1','1','0'}, + {'1','1','0','1','0'}, + {'1','1','0','0','0'}, + {'0','0','0','0','0'} + }; + vector> grid1; + for(int i = 0 ; i < 4 ; i ++) + grid1.push_back( vector(g1[i], g1[i] + sizeof( g1[i])/sizeof(char))); + + cout << Solution().numIslands(grid1) << endl; + // 1 + + // --- + + char g2[4][5] = { + {'1','1','0','0','0'}, + {'1','1','0','0','0'}, + {'0','0','1','0','0'}, + {'0','0','0','1','1'} + }; + vector> grid2; + for(int i = 0 ; i < 4 ; i ++) + grid2.push_back(vector(g2[i], g2[i] + sizeof( g2[i])/sizeof(char))); + + cout << Solution().numIslands(grid2) << endl; + // 2 + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0200-Number-of-Islands/cpp-0200/main2.cpp b/0001-0500/0200-Number-of-Islands/cpp-0200/main2.cpp new file mode 100644 index 00000000..886395a1 --- /dev/null +++ b/0001-0500/0200-Number-of-Islands/cpp-0200/main2.cpp @@ -0,0 +1,98 @@ +/// Source : https://leetcode.com/problems/number-of-islands/description/ +/// Author : liuyubobobo +/// Time : 2018-08-29 + +#include +#include +#include +#include + +using namespace std; + +/// Floodfill - DFS +/// Non-recursion implementation +/// +/// Time Complexity: O(n*m) +/// Space Complexity: O(n*m) +class Solution { + +private: + int d[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + int m, n; + +public: + int numIslands(vector>& grid) { + + m = grid.size(); + if(m == 0) + return 0; + n = grid[0].size(); + if(n == 0) + return 0; + + vector> visited(m, vector(n, false)); + + int res = 0; + for(int i = 0 ; i < m ; i ++) + for(int j = 0 ; j < n ; j ++) + if(grid[i][j] == '1' && !visited[i][j]){ + dfs(grid, i, j, visited); + res ++; + } + return res; + } + +private: + void dfs(vector>& grid, int x, int y, vector>& visited){ + + stack> q; + q.push(make_pair(x, y)); + visited[x][y] = true; + while(!q.empty()){ + int curx = q.top().first; + int cury = q.top().second; + q.pop(); + + for(int i = 0; i < 4; i ++){ + int newX = curx + d[i][0]; + int newY = cury + d[i][1]; + if(inArea(newX, newY) && !visited[newX][newY] && grid[newX][newY] == '1'){ + q.push(make_pair(newX, newY)); + visited[newX][newY] = true; + } + } + } + + return; + } + + bool inArea(int x, int y){ + return x >= 0 && x < m && y >= 0 && y < n; + } +}; + + +int main() { + + vector> grid1 = { + {'1','1','1','1','0'}, + {'1','1','0','1','0'}, + {'1','1','0','0','0'}, + {'0','0','0','0','0'} + }; + cout << Solution().numIslands(grid1) << endl; + // 1 + + // --- + + vector> grid2 = { + {'1','1','0','0','0'}, + {'1','1','0','0','0'}, + {'0','0','1','0','0'}, + {'0','0','0','1','1'} + }; + cout << Solution().numIslands(grid2) << endl; + // 3 + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0200-Number-of-Islands/cpp-0200/main3.cpp b/0001-0500/0200-Number-of-Islands/cpp-0200/main3.cpp new file mode 100644 index 00000000..3f339ae0 --- /dev/null +++ b/0001-0500/0200-Number-of-Islands/cpp-0200/main3.cpp @@ -0,0 +1,96 @@ +/// Source : https://leetcode.com/problems/number-of-islands/description/ +/// Author : liuyubobobo +/// Time : 2018-08-25 + +#include +#include +#include +#include + +using namespace std; + +/// Floodfill - BFS +/// Time Complexity: O(n*m) +/// Space Complexity: O(n*m) +class Solution { + +private: + int d[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + int m, n; + +public: + int numIslands(vector>& grid) { + + m = grid.size(); + if(m == 0) + return 0; + n = grid[0].size(); + if(n == 0) + return 0; + + vector> visited(m, vector(n, false)); + + int res = 0; + for(int i = 0 ; i < m ; i ++) + for(int j = 0 ; j < n ; j ++) + if(grid[i][j] == '1' && !visited[i][j]){ + bfs(grid, i, j, visited); + res ++; + } + return res; + } + +private: + void bfs(vector>& grid, int x, int y, vector>& visited){ + + queue> q; + q.push(make_pair(x, y)); + visited[x][y] = true; + while(!q.empty()){ + int curx = q.front().first; + int cury = q.front().second; + q.pop(); + + for(int i = 0; i < 4; i ++){ + int newX = curx + d[i][0]; + int newY = cury + d[i][1]; + if(inArea(newX, newY) && !visited[newX][newY] && grid[newX][newY] == '1'){ + q.push(make_pair(newX, newY)); + visited[newX][newY] = true; + } + } + } + + return; + } + + bool inArea(int x, int y){ + return x >= 0 && x < m && y >= 0 && y < n; + } +}; + + +int main() { + + vector> grid1 = { + {'1','1','1','1','0'}, + {'1','1','0','1','0'}, + {'1','1','0','0','0'}, + {'0','0','0','0','0'} + }; + cout << Solution().numIslands(grid1) << endl; + // 1 + + // --- + + vector> grid2 = { + {'1','1','0','0','0'}, + {'1','1','0','0','0'}, + {'0','0','1','0','0'}, + {'0','0','0','1','1'} + }; + cout << Solution().numIslands(grid2) << endl; + // 3 + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0200-Number-of-Islands/cpp-0200/main4.cpp b/0001-0500/0200-Number-of-Islands/cpp-0200/main4.cpp new file mode 100644 index 00000000..91de3259 --- /dev/null +++ b/0001-0500/0200-Number-of-Islands/cpp-0200/main4.cpp @@ -0,0 +1,126 @@ +/// Source : https://leetcode.com/problems/number-of-islands/description/ +/// Author : liuyubobobo +/// Time : 2018-08-26 + +#include +#include +#include +#include + +using namespace std; + +/// Using union-find +/// Time Complexity: O(n*m) +/// Space Complexity: O(n*m) +class UnionFind{ + +private: + vector rank, parent; + +public: + UnionFind(int n){ + rank.clear(); + parent.clear(); + for( int i = 0 ; i < n ; i ++ ){ + parent.push_back(i); + rank.push_back(1); + } + } + + int find(int p){ + while(p != parent[p]){ + parent[p] = parent[parent[p]]; + p = parent[p]; + } + return p; + } + + bool isConnected(int p , int q){ + return find(p) == find(q); + } + + void unionElements(int p, int q){ + + int pRoot = find(p); + int qRoot = find(q); + + if(pRoot == qRoot) + return; + + if(rank[pRoot] < rank[qRoot]) + parent[pRoot] = qRoot; + else if(rank[qRoot] < rank[pRoot]) + parent[qRoot] = pRoot; + else{ // rank[pRoot] == rank[qRoot] + parent[pRoot] = qRoot; + rank[qRoot] += 1; + } + } +}; + +class Solution { + +private: + int d[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + int m, n; + +public: + int numIslands(vector>& grid) { + + m = grid.size(); + if(m == 0) + return 0; + n = grid[0].size(); + if(n == 0) + return 0; + + UnionFind uf(m * n); + for(int i = 0; i < m; i ++) + for(int j = 0; j < n; j ++) + if(grid[i][j] == '1') + for(int k = 0; k < 4; k ++){ + int newX = i + d[k][0]; + int newY = j + d[k][1]; + if(inArea(newX, newY) && grid[newX][newY] == '1') + uf.unionElements(i * n + j, newX * n + newY); + } + + unordered_set regions; + for(int i = 0 ; i < m; i ++) + for(int j = 0; j < n; j ++) + if(grid[i][j] == '1') + regions.insert(uf.find(i * n + j)); + return regions.size(); + } + +private: + bool inArea(int x, int y){ + return x >= 0 && x < m && y >= 0 && y < n; + } +}; + + +int main() { + + vector> grid1 = { + {'1','1','1','1','0'}, + {'1','1','0','1','0'}, + {'1','1','0','0','0'}, + {'0','0','0','0','0'} + }; + cout << Solution().numIslands(grid1) << endl; + // 1 + + // --- + + vector> grid2 = { + {'1','1','0','0','0'}, + {'1','1','0','0','0'}, + {'0','0','1','0','0'}, + {'0','0','0','1','1'} + }; + cout << Solution().numIslands(grid2) << endl; + // 3 + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0200-Number-of-Islands/java-0200/src/Solution.java b/0001-0500/0200-Number-of-Islands/java-0200/src/Solution.java new file mode 100644 index 00000000..0a944f05 --- /dev/null +++ b/0001-0500/0200-Number-of-Islands/java-0200/src/Solution.java @@ -0,0 +1,77 @@ +/// Source : https://leetcode.com/problems/number-of-islands/description/ +/// Author : liuyubobobo +/// Time : 2017-11-18 + +/// Floodfill - DFS +/// Recursion implementation +/// +/// Time Complexity: O(n*m) +/// Space Complexity: O(n*m) +class Solution { + + private int d[][] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + private int m, n; + private boolean visited[][]; + + public int numIslands(char[][] grid) { + + if(grid == null || grid.length == 0 || grid[0].length == 0) + return 0; + + m = grid.length; + n = grid[0].length; + + visited = new boolean[m][n]; + + int res = 0; + for(int i = 0 ; i < m ; i ++) + for(int j = 0 ; j < n ; j ++) + if(grid[i][j] == '1' && !visited[i][j]){ + dfs(grid, i, j); + res ++; + } + + return res; + } + + private void dfs(char[][] grid, int x, int y){ + + //assert(inArea(x,y)); + visited[x][y] = true; + for(int i = 0; i < 4; i ++){ + int newx = x + d[i][0]; + int newy = y + d[i][1]; + if(inArea(newx, newy) && !visited[newx][newy] && grid[newx][newy] == '1') + dfs(grid, newx, newy); + } + + return; + } + + private boolean inArea(int x, int y){ + return x >= 0 && x < m && y >= 0 && y < n; + } + + public static void main(String[] args) { + + char grid1[][] = { + {'1','1','1','1','0'}, + {'1','1','0','1','0'}, + {'1','1','0','0','0'}, + {'0','0','0','0','0'} + }; + System.out.println((new Solution()).numIslands(grid1)); + // 1 + + // --- + + char grid2[][] = { + {'1','1','0','0','0'}, + {'1','1','0','0','0'}, + {'0','0','1','0','0'}, + {'0','0','0','1','1'} + }; + System.out.println((new Solution()).numIslands(grid2)); + // 3 + } +} diff --git a/0001-0500/0200-Number-of-Islands/java-0200/src/Solution2.java b/0001-0500/0200-Number-of-Islands/java-0200/src/Solution2.java new file mode 100644 index 00000000..ef5e3908 --- /dev/null +++ b/0001-0500/0200-Number-of-Islands/java-0200/src/Solution2.java @@ -0,0 +1,87 @@ +/// Source : https://leetcode.com/problems/number-of-islands/description/ +/// Author : liuyubobobo +/// Time : 2018-08-29 + +import java.util.Stack; +import javafx.util.Pair; + +/// Floodfill - DFS +/// Non-recursion implementation +/// +/// Time Complexity: O(n*m) +/// Space Complexity: O(n*m) +class Solution2 { + + private int d[][] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + private int m, n; + private boolean visited[][]; + + public int numIslands(char[][] grid) { + + if(grid == null || grid.length == 0 || grid[0].length == 0) + return 0; + + m = grid.length; + n = grid[0].length; + + visited = new boolean[m][n]; + + int res = 0; + for(int i = 0 ; i < m ; i ++) + for(int j = 0 ; j < n ; j ++) + if(grid[i][j] == '1' && !visited[i][j]){ + dfs(grid, i, j); + res ++; + } + + return res; + } + + private void dfs(char[][] grid, int x, int y){ + + Stack> q = new Stack<>(); + q.push(new Pair(x, y)); + visited[x][y] = true; + while(!q.isEmpty()){ + Pair cur = q.pop(); + int curx = cur.getKey(); + int cury = cur.getValue(); + + for(int i = 0; i < 4; i ++){ + int newX = curx + d[i][0]; + int newY = cury + d[i][1]; + if(inArea(newX, newY) && !visited[newX][newY] && grid[newX][newY] == '1'){ + q.push(new Pair(newX, newY)); + visited[newX][newY] = true; + } + } + } + } + + private boolean inArea(int x, int y){ + return x >= 0 && x < m && y >= 0 && y < n; + } + + public static void main(String[] args) { + + char grid1[][] = { + {'1','1','1','1','0'}, + {'1','1','0','1','0'}, + {'1','1','0','0','0'}, + {'0','0','0','0','0'} + }; + System.out.println((new Solution2()).numIslands(grid1)); + // 1 + + // --- + + char grid2[][] = { + {'1','1','0','0','0'}, + {'1','1','0','0','0'}, + {'0','0','1','0','0'}, + {'0','0','0','1','1'} + }; + System.out.println((new Solution2()).numIslands(grid2)); + // 3 + } +} diff --git a/0001-0500/0200-Number-of-Islands/java-0200/src/Solution3.java b/0001-0500/0200-Number-of-Islands/java-0200/src/Solution3.java new file mode 100644 index 00000000..e5b18f2f --- /dev/null +++ b/0001-0500/0200-Number-of-Islands/java-0200/src/Solution3.java @@ -0,0 +1,85 @@ +/// Source : https://leetcode.com/problems/number-of-islands/description/ +/// Author : liuyubobobo +/// Time : 2018-08-26 +import java.util.Queue; +import java.util.LinkedList; +import javafx.util.Pair; + +/// Floodfill - BFS +/// Time Complexity: O(n*m) +/// Space Complexity: O(n*m) +class Solution3 { + + private int d[][] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + private int m, n; + private boolean visited[][]; + + public int numIslands(char[][] grid) { + + if(grid == null || grid.length == 0 || grid[0].length == 0) + return 0; + + m = grid.length; + n = grid[0].length; + + visited = new boolean[m][n]; + + int res = 0; + for(int i = 0 ; i < m ; i ++) + for(int j = 0 ; j < n ; j ++) + if(grid[i][j] == '1' && !visited[i][j]){ + bfs(grid, i, j); + res ++; + } + + return res; + } + + private void bfs(char[][] grid, int x, int y){ + + Queue> q = new LinkedList<>(); + q.add(new Pair(x, y)); + visited[x][y] = true; + while(!q.isEmpty()){ + Pair cur = q.remove(); + int curx = cur.getKey(); + int cury = cur.getValue(); + + for(int i = 0; i < 4; i ++){ + int newX = curx + d[i][0]; + int newY = cury + d[i][1]; + if(inArea(newX, newY) && !visited[newX][newY] && grid[newX][newY] == '1'){ + q.add(new Pair(newX, newY)); + visited[newX][newY] = true; + } + } + } + } + + private boolean inArea(int x, int y){ + return x >= 0 && x < m && y >= 0 && y < n; + } + + public static void main(String[] args) { + + char grid1[][] = { + {'1','1','1','1','0'}, + {'1','1','0','1','0'}, + {'1','1','0','0','0'}, + {'0','0','0','0','0'} + }; + System.out.println((new Solution3()).numIslands(grid1)); + // 1 + + // --- + + char grid2[][] = { + {'1','1','0','0','0'}, + {'1','1','0','0','0'}, + {'0','0','1','0','0'}, + {'0','0','0','1','1'} + }; + System.out.println((new Solution3()).numIslands(grid2)); + // 3 + } +} diff --git a/0001-0500/0200-Number-of-Islands/java-0200/src/Solution4.java b/0001-0500/0200-Number-of-Islands/java-0200/src/Solution4.java new file mode 100644 index 00000000..dff087b0 --- /dev/null +++ b/0001-0500/0200-Number-of-Islands/java-0200/src/Solution4.java @@ -0,0 +1,114 @@ +/// Source : https://leetcode.com/problems/number-of-islands/description/ +/// Author : liuyubobobo +/// Time : 2018-08-26 + +import java.util.Arrays; +import java.util.HashSet; + +/// Using Union-Find +/// Time Complexity: O(n*m) +/// Space Complexity: O(n*m) +class Solution4 { + + private class UnionFind { + + private int[] rank; + private int[] parent; + + public UnionFind(int count){ + rank = new int[count]; + parent = new int[count]; + + for(int i = 0 ; i < count ; i ++){ + parent[i] = i; + rank[i] = 1; + } + } + + private int find(int p){ + while(p != parent[p]){ + parent[p] = parent[parent[p]]; + p = parent[p]; + } + return p; + } + + public boolean isConnected(int p , int q){ + return find(p) == find(q); + } + + public void unionElements(int p, int q){ + + int pRoot = find(p); + int qRoot = find(q); + + if(pRoot == qRoot) + return; + + if(rank[pRoot] < rank[qRoot]) + parent[pRoot] = qRoot; + else if(rank[qRoot] < rank[pRoot]) + parent[qRoot] = pRoot; + else{ // rank[pRoot] == rank[qRoot] + parent[pRoot] = qRoot; + rank[qRoot] += 1; + } + } + } + + private int d[][] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + private int m, n; + + public int numIslands(char[][] grid) { + + if(grid == null || grid.length == 0 || grid[0].length == 0) + return 0; + + m = grid.length; + n = grid[0].length; + + UnionFind uf = new UnionFind(m * n); + for(int i = 0 ; i < m ; i ++) + for(int j = 0; j < n ; j ++) + if(grid[i][j] == '1') + for(int k = 0; k < 4; k ++){ + int newX = i + d[k][0], newY = j + d[k][1]; + if(inArea(newX, newY) && grid[newX][newY] == '1') + uf.unionElements(i * n + j, newX * n + newY); + } + + HashSet islands = new HashSet<>(); + for(int i = 0 ; i < m ; i ++) + for(int j = 0; j < n ; j ++) + if(grid[i][j] == '1') + islands.add(uf.find(i * n + j)); + return islands.size(); + } + + private boolean inArea(int x, int y){ + return x >= 0 && x < m && y >= 0 && y < n; + } + + public static void main(String[] args) { + + char grid1[][] = { + {'1','1','1','1','0'}, + {'1','1','0','1','0'}, + {'1','1','0','0','0'}, + {'0','0','0','0','0'} + }; + System.out.println((new Solution4()).numIslands(grid1)); + // 1 + + // --- + + char grid2[][] = { + {'1','1','0','0','0'}, + {'1','1','0','0','0'}, + {'0','0','1','0','0'}, + {'0','0','0','1','1'} + }; + System.out.println((new Solution4()).numIslands(grid2)); + // 3 + } +} diff --git a/0001-0500/0201-Bitwise-AND-of-Numbers-Range/cpp-0201/CMakeLists.txt b/0001-0500/0201-Bitwise-AND-of-Numbers-Range/cpp-0201/CMakeLists.txt new file mode 100644 index 00000000..4aa64bf0 --- /dev/null +++ b/0001-0500/0201-Bitwise-AND-of-Numbers-Range/cpp-0201/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0201) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0201 main.cpp) diff --git a/0001-0500/0201-Bitwise-AND-of-Numbers-Range/cpp-0201/main.cpp b/0001-0500/0201-Bitwise-AND-of-Numbers-Range/cpp-0201/main.cpp new file mode 100644 index 00000000..c51a648a --- /dev/null +++ b/0001-0500/0201-Bitwise-AND-of-Numbers-Range/cpp-0201/main.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/bitwise-and-of-numbers-range/ +/// Author : liuyubobobo +/// Time : 2021-08-03 + +#include + +using namespace std; + + +/// Bit-wise +/// Time Complexity: O(logn) +/// Space Complexity: O(1) +class Solution { +public: + int rangeBitwiseAnd(int left, int right) { + + int cur = 0; + for(int i = 30; i >= 0; i --){ + if(left < cur + (1 << i) && cur + (1 << i) <= right) + break; + else if(left >= cur + (1 << i)) + cur += (1 << i); + } + return cur; + } +}; + + +int main() { + + cout << Solution().rangeBitwiseAnd(5, 7) << endl; + // 4 + + return 0; +} diff --git a/0001-0500/0202-Happy-Number/cpp-0202/CMakeLists.txt b/0001-0500/0202-Happy-Number/cpp-0202/CMakeLists.txt new file mode 100644 index 00000000..6adf6c78 --- /dev/null +++ b/0001-0500/0202-Happy-Number/cpp-0202/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_Happy_Number) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main3.cpp) +add_executable(cpp_Happy_Number ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0202-Happy-Number/cpp-0202/main.cpp b/0001-0500/0202-Happy-Number/cpp-0202/main.cpp new file mode 100644 index 00000000..3fb408fa --- /dev/null +++ b/0001-0500/0202-Happy-Number/cpp-0202/main.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/happy-number/ +/// Author : liuyubobobo +/// Time : 2017-01-18 + +#include +#include + +using namespace std; + +/// Using HashTable +/// Time Complexity: O(logn) +/// Space Complexity: O(logn) +class Solution { +public: + bool isHappy(int n) { + + unordered_set record; + record.insert(n); + while(n != 1){ + n = op(n); + if( record.find(n) == record.end() ) + record.insert(n); + else + return false; + } + + return true; + } + +private: + int op(int x){ + int res = 0; + while(x){ + int t = x % 10; + res += t * t; + x /= 10; + } + return res; + } +}; + + +void print_bool(bool res){ + + cout << (res ? "True" : "False") << endl; +} + +int main() { + + print_bool(Solution().isHappy(19)); + // true + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0202-Happy-Number/cpp-0202/main2.cpp b/0001-0500/0202-Happy-Number/cpp-0202/main2.cpp new file mode 100644 index 00000000..c632b048 --- /dev/null +++ b/0001-0500/0202-Happy-Number/cpp-0202/main2.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/happy-number/ +/// Author : liuyubobobo +/// Time : 2020-04-03 + +#include + +using namespace std; + +/// Floyd's Cycle-Finding Algorithm +/// Time Complexity: O(logn) +/// Space Complexity: O(1) +class Solution { +public: + bool isHappy(int n) { + + if(n == 1) return true; + + int slow = op(n); if(slow == 1) return true; + int fast =op(slow); if(fast == 1) return true; + while(slow != fast){ + slow = op(slow); + fast = op(fast); if(fast == 1) return true; + fast = op(fast); if(fast == 1) return true; + } + + return false; + } + +private: + int op(int x){ + int res = 0; + while(x){ + int t = x % 10; + res += t * t; + x /= 10; + } + return res; + } +}; + + +void print_bool(bool res){ + + cout << (res ? "True" : "False") << endl; +} + +int main() { + + print_bool(Solution().isHappy(19)); + // true + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0202-Happy-Number/cpp-0202/main3.cpp b/0001-0500/0202-Happy-Number/cpp-0202/main3.cpp new file mode 100644 index 00000000..296149c3 --- /dev/null +++ b/0001-0500/0202-Happy-Number/cpp-0202/main3.cpp @@ -0,0 +1,49 @@ +/// Source : https://leetcode.com/problems/happy-number/ +/// Author : liuyubobobo +/// Time : 2020-04-03 + +#include +#include + +using namespace std; + +/// The only cycle is 4-16-37-58-89-145-42-20-4 +/// Time Complexity: O(logn) +/// Space Complexity: O(1) +class Solution { +public: + bool isHappy(int n) { + + set cycle = {4, 16, 37, 58, 89, 145, 42, 20}; + while(n != 1){ + if(cycle.count(n)) return false; + n = op(n); + } + return true; + } + +private: + int op(int x){ + int res = 0; + while(x){ + int t = x % 10; + res += t * t; + x /= 10; + } + return res; + } +}; + + +void print_bool(bool res){ + + cout << (res ? "True" : "False") << endl; +} + +int main() { + + print_bool(Solution().isHappy(19)); + // true + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0203-Remove-Linked-List-Elements/cpp-0203/CMakeLists.txt b/0001-0500/0203-Remove-Linked-List-Elements/cpp-0203/CMakeLists.txt new file mode 100644 index 00000000..b7e1db3e --- /dev/null +++ b/0001-0500/0203-Remove-Linked-List-Elements/cpp-0203/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0203) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main2.cpp) +add_executable(cpp_0203 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0203-Remove-Linked-List-Elements/cpp-0203/main.cpp b/0001-0500/0203-Remove-Linked-List-Elements/cpp-0203/main.cpp new file mode 100644 index 00000000..c5dbf03d --- /dev/null +++ b/0001-0500/0203-Remove-Linked-List-Elements/cpp-0203/main.cpp @@ -0,0 +1,108 @@ +/// Source : https://leetcode.com/problems/remove-linked-list-elements/description/ +/// Author : liuyubobobo +/// Time : 2017-11-15 + +#include + +using namespace std; + +///Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} +}; + +/// LinkedList Test Helper Functions +ListNode* createLinkedList(int arr[], int n){ + + if(n == 0) + return NULL; + + ListNode* head = new ListNode(arr[0]); + ListNode* curNode = head; + for(int i = 1 ; i < n ; i ++){ + curNode->next = new ListNode(arr[i]); + curNode = curNode->next; + } + + return head; +} + +void printLinkedList(ListNode* head){ + + if(head == NULL){ + cout << "NULL" << endl; + return; + } + + ListNode* curNode = head; + while(curNode != NULL){ + cout << curNode->val; + if(curNode->next != NULL) + cout << " -> "; + curNode = curNode->next; + } + + cout << endl; + + return; +} + +void deleteLinkedList(ListNode* head){ + + ListNode* curNode = head; + while(curNode != NULL){ + ListNode* delNode = curNode; + curNode = curNode->next; + delete delNode; + } + + return; +} + + +/// Linear Scan with dummy head +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + ListNode* removeElements(ListNode* head, int val) { + + ListNode* dummyHead = new ListNode(0); + dummyHead->next = head; + + ListNode* cur = dummyHead; + while(cur->next != NULL){ + if(cur->next->val == val){ + ListNode* delNode = cur->next; + cur->next = delNode->next; + delete delNode; + } + else + cur = cur->next; + } + + ListNode* retNode = dummyHead->next; + delete dummyHead; + + return retNode; + } +}; + + +int main() { + + int arr[] = {1, 2, 6, 3, 4, 5, 6}; + int n = sizeof(arr) / sizeof(int); + + ListNode* head = createLinkedList(arr, n); + printLinkedList(head); + + Solution().removeElements(head, 6); + printLinkedList(head); + + deleteLinkedList(head); + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0203-Remove-Linked-List-Elements/cpp-0203/main2.cpp b/0001-0500/0203-Remove-Linked-List-Elements/cpp-0203/main2.cpp new file mode 100644 index 00000000..5858fdfa --- /dev/null +++ b/0001-0500/0203-Remove-Linked-List-Elements/cpp-0203/main2.cpp @@ -0,0 +1,42 @@ +/// Source : https://leetcode.com/problems/remove-linked-list-elements/description/ +/// Author : liuyubobobo +/// Time : 2018-09-17 + +#include + +using namespace std; + +///Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} +}; + + +/// Recursive +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + ListNode* removeElements(ListNode* head, int val) { + + if(!head) + return head; + + if(head->val == val){ + ListNode* node = head->next; + delete head; + return removeElements(node, val); + } + + head->next = removeElements(head->next, val); + return head; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0203-Remove-Linked-List-Elements/java-0203/src/ListNode.java b/0001-0500/0203-Remove-Linked-List-Elements/java-0203/src/ListNode.java similarity index 100% rename from 0203-Remove-Linked-List-Elements/java-0203/src/ListNode.java rename to 0001-0500/0203-Remove-Linked-List-Elements/java-0203/src/ListNode.java diff --git a/0203-Remove-Linked-List-Elements/java-0203/src/Solution.java b/0001-0500/0203-Remove-Linked-List-Elements/java-0203/src/Solution.java similarity index 100% rename from 0203-Remove-Linked-List-Elements/java-0203/src/Solution.java rename to 0001-0500/0203-Remove-Linked-List-Elements/java-0203/src/Solution.java diff --git a/0001-0500/0203-Remove-Linked-List-Elements/java-0203/src/Solution2.java b/0001-0500/0203-Remove-Linked-List-Elements/java-0203/src/Solution2.java new file mode 100644 index 00000000..583ae0c6 --- /dev/null +++ b/0001-0500/0203-Remove-Linked-List-Elements/java-0203/src/Solution2.java @@ -0,0 +1,24 @@ +public class Solution2 { + + public ListNode removeElements(ListNode head, int val) { + + if(head == null) + return head; + + ListNode node = removeElements(head.next, val); + head.next = node; + return head.val == val ? node : head; + } + + public static void main(String[] args) { + + int[] arr = {1, 2, 6, 3, 4, 5, 6}; + int val = 6; + + ListNode head = new ListNode(arr); + System.out.println(head); + + (new Solution()).removeElements(head, val); + System.out.println(head); + } +} diff --git a/0001-0500/0204-Count-Primes/cpp-0204/CMakeLists.txt b/0001-0500/0204-Count-Primes/cpp-0204/CMakeLists.txt new file mode 100644 index 00000000..d68c6c7b --- /dev/null +++ b/0001-0500/0204-Count-Primes/cpp-0204/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0204) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0204 main.cpp) \ No newline at end of file diff --git a/0001-0500/0204-Count-Primes/cpp-0204/main.cpp b/0001-0500/0204-Count-Primes/cpp-0204/main.cpp new file mode 100644 index 00000000..dc7d376d --- /dev/null +++ b/0001-0500/0204-Count-Primes/cpp-0204/main.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/count-primes/submissions/ +/// Author : liuyubobobo +/// Time : 2020-12-02 + +#include +#include + +using namespace std; + + +/// Shieve Prime +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + int countPrimes(int n) { + + int res = 0; + vector shieve(n, false); + for(int i = 2; i < n; i ++) + if(!shieve[i]){ + res ++; + for(int j = i; j < n; j += i) shieve[j] = true; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0205-Isomorphic-Strings/cpp-0205/CMakeLists.txt b/0001-0500/0205-Isomorphic-Strings/cpp-0205/CMakeLists.txt new file mode 100644 index 00000000..70e234b5 --- /dev/null +++ b/0001-0500/0205-Isomorphic-Strings/cpp-0205/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0205) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0205 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0205-Isomorphic-Strings/cpp-0205/main.cpp b/0001-0500/0205-Isomorphic-Strings/cpp-0205/main.cpp new file mode 100644 index 00000000..b36480dd --- /dev/null +++ b/0001-0500/0205-Isomorphic-Strings/cpp-0205/main.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/isomorphic-strings/description/ +/// Author : liuyubobobo +/// Time : 2018-06-01 + +#include + +using namespace std; + +/// Mapping +/// Time Complexity: O(len(s)) +/// Space Complexity: O(len of charset) +class Solution { +public: + bool isIsomorphic(string s, string t) { + + if(s.size() != t.size()) + return false; + + int map[256]; + memset(map, -1, sizeof(map)); + + bool mapped[256]; + memset(mapped, false, sizeof(mapped)); + + for(int i = 0 ; i < s.size() ; i ++){ + if(map[s[i]] == -1){ + if(mapped[t[i]]) + return false; + map[s[i]] = t[i]; + mapped[t[i]] = true; + } + else if(map[s[i]] != t[i]) + return false; + } + return true; + } +}; + + +void print_bool(bool res){ + cout << (res ? "True" : "False") << endl; +} + +int main() { + + print_bool(Solution().isIsomorphic("egg", "add")); + print_bool(Solution().isIsomorphic("foo", "bar")); + print_bool(Solution().isIsomorphic("paper", "title")); + print_bool(Solution().isIsomorphic("aa", "ab")); + + return 0; +} \ No newline at end of file diff --git a/0206-Reverse-Linked-List/cpp-0206/CMakeLists.txt b/0001-0500/0206-Reverse-Linked-List/cpp-0206/CMakeLists.txt similarity index 100% rename from 0206-Reverse-Linked-List/cpp-0206/CMakeLists.txt rename to 0001-0500/0206-Reverse-Linked-List/cpp-0206/CMakeLists.txt diff --git a/0206-Reverse-Linked-List/cpp-0206/main.cpp b/0001-0500/0206-Reverse-Linked-List/cpp-0206/main.cpp similarity index 100% rename from 0206-Reverse-Linked-List/cpp-0206/main.cpp rename to 0001-0500/0206-Reverse-Linked-List/cpp-0206/main.cpp diff --git a/0206-Reverse-Linked-List/cpp-0206/main2.cpp b/0001-0500/0206-Reverse-Linked-List/cpp-0206/main2.cpp similarity index 100% rename from 0206-Reverse-Linked-List/cpp-0206/main2.cpp rename to 0001-0500/0206-Reverse-Linked-List/cpp-0206/main2.cpp diff --git a/0206-Reverse-Linked-List/java-0206/src/Solution1.java b/0001-0500/0206-Reverse-Linked-List/java-0206/src/Solution1.java similarity index 100% rename from 0206-Reverse-Linked-List/java-0206/src/Solution1.java rename to 0001-0500/0206-Reverse-Linked-List/java-0206/src/Solution1.java diff --git a/0206-Reverse-Linked-List/java-0206/src/Solution2.java b/0001-0500/0206-Reverse-Linked-List/java-0206/src/Solution2.java similarity index 100% rename from 0206-Reverse-Linked-List/java-0206/src/Solution2.java rename to 0001-0500/0206-Reverse-Linked-List/java-0206/src/Solution2.java diff --git a/0001-0500/0207-Course-Schedule/cpp-0207/CMakeLists.txt b/0001-0500/0207-Course-Schedule/cpp-0207/CMakeLists.txt new file mode 100644 index 00000000..b5f647da --- /dev/null +++ b/0001-0500/0207-Course-Schedule/cpp-0207/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(cpp_0207) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(cpp_0207 main.cpp) \ No newline at end of file diff --git a/0001-0500/0207-Course-Schedule/cpp-0207/main.cpp b/0001-0500/0207-Course-Schedule/cpp-0207/main.cpp new file mode 100644 index 00000000..057ab6ec --- /dev/null +++ b/0001-0500/0207-Course-Schedule/cpp-0207/main.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/course-schedule-ii/ +/// Author : liuyubobobo +/// Time : 2018-12-16 +/// Updated: 2023-07-13 + +#include +#include +#include + +using namespace std; + + +/// T +/// Time Complexity: O(m + n) +/// Space Complexity: O(m + n) +class Solution { + +public: + bool canFinish(int n, vector>& prerequisites) { + + vector> g(n); + for(const vector& p: prerequisites){ + int from = p[1]; + int to = p[0]; + g[from].push_back(to); + } + + vector indegrees(n, 0); + for(int u = 0; u < n; u ++) + for(int v: g[u]) indegrees[v] ++; + + queue q; + int left = n; + for(int u = 0; u < n; u ++) + if(indegrees[u] == 0) q.push(u), left --; + + while(!q.empty()){ + int u = q.front(); q.pop(); + for(int v: g[u]){ + indegrees[v] --; + if(indegrees[v] == 0) q.push(v), left --; + } + } + return left == 0; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0208-Implement-Trie-Prefix-Tree/cpp-0208/CMakeLists.txt b/0001-0500/0208-Implement-Trie-Prefix-Tree/cpp-0208/CMakeLists.txt similarity index 100% rename from 0208-Implement-Trie-Prefix-Tree/cpp-0208/CMakeLists.txt rename to 0001-0500/0208-Implement-Trie-Prefix-Tree/cpp-0208/CMakeLists.txt diff --git a/0208-Implement-Trie-Prefix-Tree/cpp-0208/main.cpp b/0001-0500/0208-Implement-Trie-Prefix-Tree/cpp-0208/main.cpp similarity index 100% rename from 0208-Implement-Trie-Prefix-Tree/cpp-0208/main.cpp rename to 0001-0500/0208-Implement-Trie-Prefix-Tree/cpp-0208/main.cpp diff --git a/0208-Implement-Trie-Prefix-Tree/cpp-0208/main2.cpp b/0001-0500/0208-Implement-Trie-Prefix-Tree/cpp-0208/main2.cpp similarity index 100% rename from 0208-Implement-Trie-Prefix-Tree/cpp-0208/main2.cpp rename to 0001-0500/0208-Implement-Trie-Prefix-Tree/cpp-0208/main2.cpp diff --git a/0001-0500/0209-Minimum-Size-Subarray-Sum/cpp-0209/CMakeLists.txt b/0001-0500/0209-Minimum-Size-Subarray-Sum/cpp-0209/CMakeLists.txt new file mode 100644 index 00000000..08568bee --- /dev/null +++ b/0001-0500/0209-Minimum-Size-Subarray-Sum/cpp-0209/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0209) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main4.cpp) +add_executable(cpp_0209 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0209-Minimum-Size-Subarray-Sum/cpp-0209/main.cpp b/0001-0500/0209-Minimum-Size-Subarray-Sum/cpp-0209/main.cpp new file mode 100644 index 00000000..ae64de82 --- /dev/null +++ b/0001-0500/0209-Minimum-Size-Subarray-Sum/cpp-0209/main.cpp @@ -0,0 +1,43 @@ +/// https://leetcode.com/problems/minimum-size-subarray-sum/description/ +/// Author : liuyubobobo +/// Time : 2017-11-13 + +#include +#include +#include + +using namespace std; + + +// Sum Prefix +// Time Complexity: O(n^2) +// Space Complexity: O(n) +class Solution { +public: + int minSubArrayLen(int s, vector& nums) { + + assert(s > 0); + + vector sums(nums.size() + 1, 0); + for(int i = 1 ; i <= nums.size() ; i ++) + sums[i] = sums[i-1] + nums[i-1]; + + int res = nums.size() + 1; + for(int l = 0 ; l < nums.size() ; l ++) + for(int r = l ; r < nums.size() ; r ++) + if(sums[r+1] - sums[l] >= s) + res = min(res, r - l + 1); + + return res == nums.size() + 1 ? 0 : res; + } +}; + + +int main() { + + vector nums1 = {2, 3, 1, 2, 4, 3}; + int s1 = 7; + cout << Solution().minSubArrayLen(s1, vec1) << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0209-Minimum-Size-Subarray-Sum/cpp-0209/main2.cpp b/0001-0500/0209-Minimum-Size-Subarray-Sum/cpp-0209/main2.cpp new file mode 100644 index 00000000..a9f89380 --- /dev/null +++ b/0001-0500/0209-Minimum-Size-Subarray-Sum/cpp-0209/main2.cpp @@ -0,0 +1,45 @@ +/// https://leetcode.com/problems/minimum-size-subarray-sum/description/ +/// Author : liuyubobobo +/// Time : 2019-03-03 + +#include +#include +#include + +using namespace std; + + +// Brute Force + Greedy +// Time Complexity: O(n^2) +// Space Complexity: O(1) +class Solution { +public: + int minSubArrayLen(int s, vector& nums) { + + assert(s > 0); + + int res = nums.size() + 1; + for(int l = 0 ; l < nums.size() ; l ++) { + int sum = 0; + for (int r = l; r < nums.size(); r++){ + sum += nums[r]; + if(sum >= s){ + res = min(res, r - l + 1); + break; + } + } + } + + return res == nums.size() + 1 ? 0 : res; + } +}; + + +int main() { + + vector nums1 = {2, 3, 1, 2, 4, 3}; + int s1 = 7; + cout << Solution().minSubArrayLen(s1, vec1) << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0209-Minimum-Size-Subarray-Sum/cpp-0209/main3.cpp b/0001-0500/0209-Minimum-Size-Subarray-Sum/cpp-0209/main3.cpp new file mode 100644 index 00000000..ab898602 --- /dev/null +++ b/0001-0500/0209-Minimum-Size-Subarray-Sum/cpp-0209/main3.cpp @@ -0,0 +1,53 @@ +/// https://leetcode.com/problems/minimum-size-subarray-sum/description/ +/// Author : liuyubobobo +/// Time : 2017-11-13 + +#include +#include +#include +#include + +using namespace std; + + +// Sum Prefix + Binary Search +// Time Complexity: O(nlogn) +// Space Complexity: O(n) +class Solution { +public: + int minSubArrayLen(int s, vector& nums) { + + assert(s > 0); + + vector sums(nums.size() + 1, 0); + for(int i = 1 ; i <= nums.size() ; i ++) + sums[i] = sums[i-1] + nums[i-1]; + + int res = nums.size() + 1; + for(int l = 0; l < (int)nums.size(); l ++){ + auto r_bound = lower_bound(sums.begin(), sums.end(), sums[l] + s); + if(r_bound != sums.end()){ + int r = r_bound - sums.begin(); + res = min(res, r - l); + } + } + + return res == nums.size() + 1 ? 0 : res; + } +}; + +int main() { + + vector nums1 = {2, 3, 1, 2, 4, 3}; + int s1 = 7; + cout << Solution().minSubArrayLen(s1, nums1) << endl; + // 2 + + // --- + + vector nums2 = {}; + int s2 = 100; + cout << Solution().minSubArrayLen(s2, nums2) << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0209-Minimum-Size-Subarray-Sum/cpp-0209/main4.cpp b/0001-0500/0209-Minimum-Size-Subarray-Sum/cpp-0209/main4.cpp new file mode 100644 index 00000000..96f1a638 --- /dev/null +++ b/0001-0500/0209-Minimum-Size-Subarray-Sum/cpp-0209/main4.cpp @@ -0,0 +1,48 @@ +/// https://leetcode.com/problems/minimum-size-subarray-sum/description/ +/// Author : liuyubobobo +/// Time : 2017-11-13 + +#include +#include +#include + +using namespace std; + + +// Sliding Window +// Time Complexity: O(n) +// Space Complexity: O(1) +class Solution { +public: + int minSubArrayLen(int s, vector& nums) { + + assert(s > 0); + + int l = 0 , r = -1; // sliding window: nums[l...r] + int sum = 0; + int res = nums.size() + 1; + + while(l < nums.size()){ + + if(r + 1 < nums.size() && sum < s) + sum += nums[++r]; + else + sum -= nums[l++]; + + if(sum >= s) + res = min(res, r - l + 1); + } + + return res == nums.size() + 1 ? 0 : res; + } +}; + + +int main() { + + vector nums1 = {2, 3, 1, 2, 4, 3}; + int s1 = 7; + cout << Solution().minSubArrayLen(s1, nums1) << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0209-Minimum-Size-Subarray-Sum/cpp-0209/main5.cpp b/0001-0500/0209-Minimum-Size-Subarray-Sum/cpp-0209/main5.cpp new file mode 100644 index 00000000..8dc44430 --- /dev/null +++ b/0001-0500/0209-Minimum-Size-Subarray-Sum/cpp-0209/main5.cpp @@ -0,0 +1,53 @@ +/// https://leetcode.com/problems/minimum-size-subarray-sum/description/ +/// Author : liuyubobobo +/// Time : 2017-11-13 + +#include +#include +#include + +using namespace std; + + +// Sliding Window +// Another Implementation +// Time Complexity: O(n) +// Space Complexity: O(1) +class Solution { +public: + int minSubArrayLen(int s, vector& nums) { + + assert(s > 0); + + int l = 0 , r = -1; // sliding window: nums[l...r] + int sum = 0; + int res = nums.size() + 1; + + while(r + 1 < nums.size()){ + + while(r + 1 < nums.size() && sum < s) + sum += nums[++r]; + + if(sum >= s) + res = min(res, r - l + 1); + + while(l < nums.size() && sum >= s){ + sum -= nums[l++]; + if(sum >= s) + res = min(res, r - l + 1); + } + } + + return res == nums.size() + 1 ? 0 : res; + } +}; + + +int main() { + + vector nums1 = {2, 3, 1, 2, 4, 3}; + int s1 = 7; + cout << Solution().minSubArrayLen(s1, nums1) << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0209-Minimum-Size-Subarray-Sum/java-0209/src/Solution1.java b/0001-0500/0209-Minimum-Size-Subarray-Sum/java-0209/src/Solution1.java new file mode 100644 index 00000000..57a24c0f --- /dev/null +++ b/0001-0500/0209-Minimum-Size-Subarray-Sum/java-0209/src/Solution1.java @@ -0,0 +1,35 @@ +/// https://leetcode.com/problems/minimum-size-subarray-sum/description/ +/// Author : liuyubobobo +/// Time : 2017-11-13 + +// Sum Prefix +// Time Complexity: O(n^2) +// Space Complexity: O(n) +public class Solution1 { + + public int minSubArrayLen(int s, int[] nums) { + + if(s <= 0 || nums == null) + throw new IllegalArgumentException("Illigal Arguments"); + + int[] sums = new int[nums.length + 1]; + sums[0] = 0; + for(int i = 1 ; i <= nums.length ; i ++) + sums[i] = sums[i-1] + nums[i-1]; + + int res = nums.length + 1; + for(int l = 0 ; l < nums.length ; l ++) + for(int r = l ; r < nums.length ; r ++) + if(sums[r+1] - sums[l] >= s) + res = Math.min(res, r - l + 1); + + return res == nums.length + 1 ? 0 : res; + } + + public static void main(String[] args) { + + int[] nums = {2, 3, 1, 2, 4, 3}; + int s = 7; + System.out.println((new Solution1()).minSubArrayLen(s, nums)); + } +} diff --git a/0001-0500/0209-Minimum-Size-Subarray-Sum/java-0209/src/Solution2.java b/0001-0500/0209-Minimum-Size-Subarray-Sum/java-0209/src/Solution2.java new file mode 100644 index 00000000..bd2c26ee --- /dev/null +++ b/0001-0500/0209-Minimum-Size-Subarray-Sum/java-0209/src/Solution2.java @@ -0,0 +1,36 @@ +/// https://leetcode.com/problems/minimum-size-subarray-sum/description/ +/// Author : liuyubobobo +/// Time : 2019-03-03 + +// Brute Force + Greedy +// Time Complexity: O(n^2) +// Space Complexity: O(1) +public class Solution2 { + + public int minSubArrayLen(int s, int[] nums) { + + if(s <= 0 || nums == null) + throw new IllegalArgumentException("Illigal Arguments"); + + int res = nums.length + 1; + for(int l = 0 ; l < nums.length ; l ++) { + int sum = 0; + for (int r = l; r < nums.length; r++){ + sum += nums[r]; + if(sum >= s){ + res = Math.min(res, r - l + 1); + break; + } + } + } + + return res == nums.length + 1 ? 0 : res; + } + + public static void main(String[] args) { + + int[] nums = {2, 3, 1, 2, 4, 3}; + int s = 7; + System.out.println((new Solution2()).minSubArrayLen(s, nums)); + } +} diff --git a/0001-0500/0209-Minimum-Size-Subarray-Sum/java-0209/src/Solution3.java b/0001-0500/0209-Minimum-Size-Subarray-Sum/java-0209/src/Solution3.java new file mode 100644 index 00000000..0699885e --- /dev/null +++ b/0001-0500/0209-Minimum-Size-Subarray-Sum/java-0209/src/Solution3.java @@ -0,0 +1,66 @@ +/// https://leetcode.com/problems/minimum-size-subarray-sum/description/ +/// Author : liuyubobobo +/// Time : 2017-11-13 + +// Sum Prefix + Binary Search +// Time Complexity: O(nlogn) +// Space Complexity: O(n) +public class Solution3 { + + public int minSubArrayLen(int s, int[] nums) { + + if(s <= 0 || nums == null) + throw new IllegalArgumentException("Illigal Arguments"); + + int[] sums = new int[nums.length + 1]; + sums[0] = 0; + for(int i = 1 ; i <= nums.length ; i ++) + sums[i] = sums[i-1] + nums[i-1]; + + int res = nums.length + 1; + for(int l = 0 ; l < nums.length; l ++){ + // Unfortunately, there's no lowerBound method in Java, + // We need to implement our own lowerBound :( + int r = lowerBound(sums, sums[l] + s); + if(r != sums.length) + res = Math.min(res, r - l); + } + + return res == nums.length + 1 ? 0 : res; + } + + // Find the smallest number index which is larger or equal to target + // in a sorted array nums + // If there's no such a number, in which all number in nums are smaller than target + // return nums.length + private int lowerBound(int[] nums, int target){ + + if(nums == null /*|| !isSorted(nums)*/) + throw new IllegalArgumentException("Illegal argument nums in lowerBound."); + + int l = 0, r = nums.length; + while(l != r){ + int mid = l + (r - l) / 2; + if(nums[mid] >= target) + r = mid; + else + l = mid + 1; + } + + return l; + } + + private boolean isSorted(int[] nums){ + for(int i = 1 ; i < nums.length ; i ++) + if(nums[i] < nums[i-1]) + return false; + return true; + } + + public static void main(String[] args) { + + int[] nums = {2, 3, 1, 2, 4, 3}; + int s = 7; + System.out.println((new Solution3()).minSubArrayLen(s, nums)); + } +} diff --git a/0001-0500/0209-Minimum-Size-Subarray-Sum/java-0209/src/Solution4.java b/0001-0500/0209-Minimum-Size-Subarray-Sum/java-0209/src/Solution4.java new file mode 100644 index 00000000..8849e5b8 --- /dev/null +++ b/0001-0500/0209-Minimum-Size-Subarray-Sum/java-0209/src/Solution4.java @@ -0,0 +1,39 @@ +/// https://leetcode.com/problems/minimum-size-subarray-sum/description/ +/// Author : liuyubobobo +/// Time : 2017-11-13 + +// Sliding Window +// Time Complexity: O(n) +// Space Complexity: O(1) +public class Solution4 { + + public int minSubArrayLen(int s, int[] nums) { + + if(s <= 0 || nums == null) + throw new IllegalArgumentException("Illigal Arguments"); + + int l = 0 , r = -1; // sliding window: nums[l...r] + int sum = 0; + int res = nums.length + 1; + + while(l < nums.length){ + + if(r + 1 < nums.length && sum < s) + sum += nums[++r]; + else + sum -= nums[l++]; + + if(sum >= s) + res = Math.min(res, r - l + 1); + } + + return res == nums.length + 1 ? 0 : res; + } + + public static void main(String[] args) { + + int[] nums = {2, 3, 1, 2, 4, 3}; + int s = 7; + System.out.println((new Solution4()).minSubArrayLen(s, nums)); + } +} diff --git a/0001-0500/0209-Minimum-Size-Subarray-Sum/java-0209/src/Solution5.java b/0001-0500/0209-Minimum-Size-Subarray-Sum/java-0209/src/Solution5.java new file mode 100644 index 00000000..824beb64 --- /dev/null +++ b/0001-0500/0209-Minimum-Size-Subarray-Sum/java-0209/src/Solution5.java @@ -0,0 +1,44 @@ +/// https://leetcode.com/problems/minimum-size-subarray-sum/description/ +/// Author : liuyubobobo +/// Time : 2017-11-13 + +// Sliding Window +// Another Implementation +// Time Complexity: O(n) +// Space Complexity: O(1) +public class Solution5 { + + public int minSubArrayLen(int s, int[] nums) { + + if(s <= 0 || nums == null) + throw new IllegalArgumentException("Illigal Arguments"); + + int l = 0 , r = -1; // sliding window: nums[l...r] + int sum = 0; + int res = nums.length + 1; + + while(r + 1 < nums.length){ + + while(r + 1 < nums.length && sum < s) + sum += nums[++r]; + + if(sum >= s) + res = Math.min(res, r - l + 1); + + while(l < nums.length && sum >= s){ + sum -= nums[l++]; + if(sum >= s) + res = Math.min(res, r - l + 1); + } + } + + return res == nums.length + 1 ? 0 : res; + } + + public static void main(String[] args) { + + int[] nums = {2, 3, 1, 2, 4, 3}; + int s = 7; + System.out.println((new Solution5()).minSubArrayLen(s, nums)); + } +} diff --git a/0001-0500/0210-Course-Schedule-II/cpp-0210/CMakeLists.txt b/0001-0500/0210-Course-Schedule-II/cpp-0210/CMakeLists.txt new file mode 100644 index 00000000..3ccd37f7 --- /dev/null +++ b/0001-0500/0210-Course-Schedule-II/cpp-0210/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(cpp_0210) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(cpp_0210 main.cpp) \ No newline at end of file diff --git a/0001-0500/0210-Course-Schedule-II/cpp-0210/main.cpp b/0001-0500/0210-Course-Schedule-II/cpp-0210/main.cpp new file mode 100644 index 00000000..fa88156f --- /dev/null +++ b/0001-0500/0210-Course-Schedule-II/cpp-0210/main.cpp @@ -0,0 +1,71 @@ +/// Source : https://leetcode.com/problems/course-schedule-ii/ +/// Author : liuyubobobo +/// Time : 2018-12-16 +/// Updated: 2022-04-12 + +#include +#include +#include + +using namespace std; + + +/// Topological Order +/// Time Complexity: O(V + E) +/// Space Complexity: O(V + E) +class Solution { +public: + vector findOrder(int numCourses, vector>& prerequisites) { + + vector pre(numCourses, 0); + vector> g(numCourses); + for(const vector& p: prerequisites){ + int from = p[1]; + int to = p[0]; + g[from].push_back(to); + pre[to] ++; + } + + queue q; + for(int i = 0; i < numCourses; i ++) + if(pre[i] == 0) + q.push(i); + + vector res; + while(!q.empty()){ + int id = q.front(); + q.pop(); + + res.push_back(id); + for(int next: g[id]){ + pre[next] --; + if(pre[next] == 0) + q.push(next); + } + } + + if(res.size() == numCourses) + return res; + return {}; + } +}; + + +void print_vec(const vector& vec){ + for(int e: vec) + cout << e << " "; + cout << endl; +} + +int main() { + + vector> pre1 = {{1,0}}; + print_vec(Solution().findOrder(2, pre1)); + // 0 1 + + vector> pre2 = {{1,0},{2,0},{3,1},{3,2}}; + print_vec(Solution().findOrder(4, pre2)); + // 0 1 2 3 + + return 0; +} \ No newline at end of file diff --git a/0211-Add-and-Search-Word-Data-structure-design/cpp-0211/CMakeLists.txt b/0001-0500/0211-Add-and-Search-Word-Data-structure-design/cpp-0211/CMakeLists.txt similarity index 100% rename from 0211-Add-and-Search-Word-Data-structure-design/cpp-0211/CMakeLists.txt rename to 0001-0500/0211-Add-and-Search-Word-Data-structure-design/cpp-0211/CMakeLists.txt diff --git a/0211-Add-and-Search-Word-Data-structure-design/cpp-0211/main.cpp b/0001-0500/0211-Add-and-Search-Word-Data-structure-design/cpp-0211/main.cpp similarity index 100% rename from 0211-Add-and-Search-Word-Data-structure-design/cpp-0211/main.cpp rename to 0001-0500/0211-Add-and-Search-Word-Data-structure-design/cpp-0211/main.cpp diff --git a/0001-0500/0211-Add-and-Search-Word-Data-structure-design/java-0211/src/WordDictionary.java b/0001-0500/0211-Add-and-Search-Word-Data-structure-design/java-0211/src/WordDictionary.java new file mode 100644 index 00000000..41b7d3b0 --- /dev/null +++ b/0001-0500/0211-Add-and-Search-Word-Data-structure-design/java-0211/src/WordDictionary.java @@ -0,0 +1,70 @@ +/// Source : https://leetcode.com/problems/add-and-search-word-data-structure-design/ +/// Author : liuyubobobo +/// Time : 2019-09-01 + +/// Trie + Recursive DFS +/// Time Complexity: addWord: O(len(word)) +/// search: O(size(trie)) +/// Space Complexity: O(sum(len(wi))) where wi is the length of the ith word +public class WordDictionary { + + private class Node{ + + public boolean isWord; + public Node next[]; + + public Node(boolean isWord){ + this.isWord = isWord; + next = new Node[26]; + } + + public Node(){ + this(false); + } + } + + private Node root; + + /** Initialize your data structure here. */ + public WordDictionary() { + root = new Node(); + } + + /** Adds a word into the data structure. */ + public void addWord(String word) { + + Node cur = root; + for(int i = 0 ; i < word.length() ; i ++){ + char c = word.charAt(i); + if(cur.next[c - 'a'] == null) + cur.next[c - 'a'] = new Node(); + cur = cur.next[c - 'a']; + } + cur.isWord = true; + } + + /** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */ + public boolean search(String word) { + return match(root, word, 0); + } + + private boolean match(Node node, String word, int index){ + + if(index == word.length()) + return node.isWord; + + char c = word.charAt(index); + + if(c != '.'){ + if(node.next[c - 'a'] == null) + return false; + return match(node.next[c - 'a'], word, index + 1); + } + else{ + for(char nextChar = 'a'; nextChar <= 'z'; nextChar ++) + if(node.next[nextChar - 'a'] != null && match(node.next[nextChar - 'a'], word, index + 1)) + return true; + return false; + } + } +} \ No newline at end of file diff --git a/0001-0500/0211-Add-and-Search-Word-Data-structure-design/java-0211/src/WordDictionary2.java b/0001-0500/0211-Add-and-Search-Word-Data-structure-design/java-0211/src/WordDictionary2.java new file mode 100644 index 00000000..b97f26cc --- /dev/null +++ b/0001-0500/0211-Add-and-Search-Word-Data-structure-design/java-0211/src/WordDictionary2.java @@ -0,0 +1,72 @@ +/// Source : https://leetcode.com/problems/add-and-search-word-data-structure-design/ +/// Author : liuyubobobo +/// Time : 2022-11-13 + +import java.util.*; + +/// Trie + Non-Recursive DFS +/// Time Complexity: addWord: O(len(word)) +/// search: O(size(trie)) +/// Space Complexity: O(sum(len(wi))) where wi is the length of the ith word +public class WordDictionary2 { + + private class Node{ + + public boolean isWord = false; + public int index; + public Node next[]; + + public Node(int index){ + this.index = index; + next = new Node[26]; + } + } + + private Node root; + + /** Initialize your data structure here. */ + public WordDictionary2() { + root = new Node(0); + } + + /** Adds a word into the data structure. */ + public void addWord(String word) { + + Node cur = root; + for(int i = 0 ; i < word.length() ; i ++){ + char c = word.charAt(i); + if(cur.next[c - 'a'] == null) + cur.next[c - 'a'] = new Node(i + 1); + cur = cur.next[c - 'a']; + } + cur.isWord = true; + } + + /** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */ + public boolean search(String word) { + + Deque nodeStack = new LinkedList<>(); + + nodeStack.push(root); + while(!nodeStack.isEmpty()){ + Node node = nodeStack.poll(); + if(node.index == word.length()){ + if(node.isWord) return true; + continue; + } + + char c = word.charAt(node.index); + if(c != '.'){ + if(node.next[c - 'a'] != null) + nodeStack.push(node.next[c - 'a']); + } + else{ + for(char nextChar = 0; nextChar < 26; nextChar ++){ + if(node.next[nextChar] != null) + nodeStack.push(node.next[nextChar]); + } + } + } + return false; + } +} \ No newline at end of file diff --git a/0001-0500/0212-Word-Search-II/cpp-0212/CMakeLists.txt b/0001-0500/0212-Word-Search-II/cpp-0212/CMakeLists.txt new file mode 100644 index 00000000..c1554db6 --- /dev/null +++ b/0001-0500/0212-Word-Search-II/cpp-0212/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(cpp_0212) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(cpp_0212 main.cpp) \ No newline at end of file diff --git a/0001-0500/0212-Word-Search-II/cpp-0212/main.cpp b/0001-0500/0212-Word-Search-II/cpp-0212/main.cpp new file mode 100644 index 00000000..684b8b1c --- /dev/null +++ b/0001-0500/0212-Word-Search-II/cpp-0212/main.cpp @@ -0,0 +1,118 @@ +/// Source : https://leetcode.com/problems/word-search-ii/ +/// Author : liuyubobobo +/// Time : 2019-02-08 +/// Updated: 2022-11-05 + +#include +#include +#include +#include + +using namespace std; + + +/// Trie + DFS +/// Shrink the Trie while searching is a big optimization +/// Time Complexity: O(4 ^ (m * n) * maxlen) +/// Space Complexity: O(m * n + total_letters_in_words) +class Solution { + +private: + class Node{ + public: + vector next; + int sz = 0; + bool end = false, found = false; + + Node() : next(26, nullptr){}; + }; + Node* root = nullptr; + + const int d[4][2] = {{-1, 0}, {0,1}, {1, 0}, {0, -1}}; + int R, C; + +public: + vector findWords(vector>& board, vector& words) { + + root = new Node; + for(const string& word: words) + insert(word); + + R = board.size(), C = board[0].size(); + vector res; + + for(int i = 0 ; i < R ; i ++) + for(int j = 0 ; j < C ; j ++){ + vector> visited(R, vector(C, false)); + Node* cur = root; + string s = ""; + searchWord(board, i, j, cur, s, visited, res); + } + return res; + } + +private: + // start from board[x][y], find word s + void searchWord(const vector> &board, int x, int y, Node* cur, string& s, + vector>& visited, vector& res){ + + if(cur->next[board[x][y] - 'a'] == nullptr) return; + + s += board[x][y]; + + Node* parent = cur; + cur = cur->next[board[x][y] - 'a']; + if(cur->end && !cur->found){ + res.push_back(s); + cur->found = true; + } + + visited[x][y] = true; + for(int i = 0 ; i < 4 ; i ++){ + int nextx = x + d[i][0]; + int nexty = y + d[i][1]; + if(in_area(nextx, nexty) && !visited[nextx][nexty]) + searchWord(board, nextx, nexty, cur, s, visited, res); + } + visited[x][y] = false; + s.pop_back(); + + if(cur->sz == 0){ + parent->next[board[x][y] - 'a'] = nullptr; + parent->sz --; + } + } + + void insert(const string& word){ + + Node* cur = root; + for(char c: word){ + if(cur->next[c - 'a'] == nullptr) + cur->next[c - 'a'] = new Node(), cur->sz ++; + cur = cur->next[c - 'a']; + } + cur->end = true; + } + + bool in_area(int x , int y){ + return x >= 0 && x < R && y >= 0 && y < C; + } +}; + + +void print_vec(const vector& v){ + for(const string& s: v) cout << s << ' '; + cout << '\n'; +} + +int main() { + + vector> board1 = {{'o','a','a','n'}, + {'e','t','a','e'}, + {'i','h','k','r'}, + {'i','f','l','v'}}; + vector words1 = {"oath","pea","eat","rain"}; + print_vec(Solution().findWords(board1, words1)); + + return 0; +} \ No newline at end of file diff --git a/0213-House-Robber-II/cpp-0213/CMakeLists.txt b/0001-0500/0213-House-Robber-II/cpp-0213/CMakeLists.txt similarity index 100% rename from 0213-House-Robber-II/cpp-0213/CMakeLists.txt rename to 0001-0500/0213-House-Robber-II/cpp-0213/CMakeLists.txt diff --git a/0213-House-Robber-II/cpp-0213/main.cpp b/0001-0500/0213-House-Robber-II/cpp-0213/main.cpp similarity index 100% rename from 0213-House-Robber-II/cpp-0213/main.cpp rename to 0001-0500/0213-House-Robber-II/cpp-0213/main.cpp diff --git a/0001-0500/0215-Kth-Largest-Element-in-an-Array/cpp-0215/CMakeLists.txt b/0001-0500/0215-Kth-Largest-Element-in-an-Array/cpp-0215/CMakeLists.txt new file mode 100644 index 00000000..5aff63ac --- /dev/null +++ b/0001-0500/0215-Kth-Largest-Element-in-an-Array/cpp-0215/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_Kth_Largest_Element_in_an_Array) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main3.cpp) +add_executable(cpp_Kth_Largest_Element_in_an_Array ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0215-Kth-Largest-Element-in-an-Array/cpp-0215/main.cpp b/0001-0500/0215-Kth-Largest-Element-in-an-Array/cpp-0215/main.cpp new file mode 100644 index 00000000..3af938b5 --- /dev/null +++ b/0001-0500/0215-Kth-Largest-Element-in-an-Array/cpp-0215/main.cpp @@ -0,0 +1,42 @@ +/// Source : https://leetcode.com/problems/kth-largest-element-in-an-array/ +/// Author : liuyubobobo +/// Time : 2018-01-07 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// Sorting +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + int findKthLargest(vector& nums, int k) { + + sort(nums.begin(), nums.end(), [](int a, int b){return a > b;}); + return nums[k - 1]; + } +}; + + +int main() { + + vector nums1 = {3, 2, 1, 5, 6, 4}; + cout << Solution().findKthLargest(nums1, 2) << endl; + // 5 + + vector nums2 = {3, 1, 2, 4}; + cout << Solution().findKthLargest(nums2, 2) << endl; + // 3 + + vector nums3 = {3, 3, 3, 3, 3, 3, 3, 3, 3}; + cout << Solution().findKthLargest(nums3, 8) << endl; + // 3 + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0215-Kth-Largest-Element-in-an-Array/cpp-0215/main2.cpp b/0001-0500/0215-Kth-Largest-Element-in-an-Array/cpp-0215/main2.cpp new file mode 100644 index 00000000..7a10ea70 --- /dev/null +++ b/0001-0500/0215-Kth-Largest-Element-in-an-Array/cpp-0215/main2.cpp @@ -0,0 +1,51 @@ +/// Source : https://leetcode.com/problems/kth-largest-element-in-an-array/ +/// Author : liuyubobobo +/// Time : 2018-01-07 + +#include +#include +#include +#include +#include +#include + +using namespace std; + + +/// Using Min Heap to store the k largest elements +/// Time Complexity: O(nlogk) +/// Space Complexity: O(k) +class Solution { +public: + int findKthLargest(vector& nums, int k) { + + priority_queue, greater> pq; + for(int e: nums) + if(pq.size() != k) + pq.push(e); + else if(e > pq.top()){ + pq.pop(); + pq.push(e); + } + + return pq.top(); + } +}; + + +int main() { + + vector nums1 = {3, 2, 1, 5, 6, 4}; + cout << Solution().findKthLargest(nums1, 2) << endl; + // 5 + + vector nums2 = {3, 1, 2, 4}; + cout << Solution().findKthLargest(nums2, 2) << endl; + // 3 + + vector nums3 = {3, 3, 3, 3, 3, 3, 3, 3, 3}; + cout << Solution().findKthLargest(nums3, 8) << endl; + // 3 + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0215-Kth-Largest-Element-in-an-Array/cpp-0215/main3.cpp b/0001-0500/0215-Kth-Largest-Element-in-an-Array/cpp-0215/main3.cpp new file mode 100644 index 00000000..0cfa274d --- /dev/null +++ b/0001-0500/0215-Kth-Largest-Element-in-an-Array/cpp-0215/main3.cpp @@ -0,0 +1,73 @@ +/// Source : https://leetcode.com/problems/kth-largest-element-in-an-array/ +/// Author : liuyubobobo +/// Time : 2017-01-20 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// Based on Quick Sort Partition. +/// Time Complexity: O(n) +/// Space Complexity: O(logn) +class Solution { +public: + int findKthLargest(vector& nums, int k) { + + srand(time(NULL)); + return findKthLargest(nums, 0, nums.size()-1 , k - 1 ); + } + +private: + int findKthLargest(vector& nums, int l, int r, int k){ + + if( l == r ) + return nums[l]; + + int p = partition(nums, l, r); + + if( p == k ) + return nums[p]; + else if( k < p ) + return findKthLargest(nums, l, p-1, k); + else // k > p + return findKthLargest(nums, p+1 , r, k); + } + + int partition( vector& nums, int l, int r ){ + + int p = rand()%(r-l+1) + l; + swap( nums[l] , nums[p] ); + + int lt = l + 1; //[l+1...lt) > p ; [lt..i) < p + for( int i = l + 1 ; i <= r ; i ++ ) + if( nums[i] > nums[l] ) + swap(nums[i], nums[lt++]); + + swap(nums[l], nums[lt-1]); + + return lt-1; + } +}; + + +int main() { + + vector nums1 = {3, 2, 1, 5, 6, 4}; + cout << Solution().findKthLargest(nums1, 2) << endl; + // 5 + + vector nums2 = {3, 1, 2, 4}; + cout << Solution().findKthLargest(nums2, 2) << endl; + // 3 + + vector nums3 = {3, 3, 3, 3, 3, 3, 3, 3, 3}; + cout << Solution().findKthLargest(nums3, 8) << endl; + // 3 + + return 0; +} \ No newline at end of file diff --git a/0216-Combination-Sum-III/cpp-0216/CMakeLists.txt b/0001-0500/0216-Combination-Sum-III/cpp-0216/CMakeLists.txt similarity index 100% rename from 0216-Combination-Sum-III/cpp-0216/CMakeLists.txt rename to 0001-0500/0216-Combination-Sum-III/cpp-0216/CMakeLists.txt diff --git a/0216-Combination-Sum-III/cpp-0216/main.cpp b/0001-0500/0216-Combination-Sum-III/cpp-0216/main.cpp similarity index 100% rename from 0216-Combination-Sum-III/cpp-0216/main.cpp rename to 0001-0500/0216-Combination-Sum-III/cpp-0216/main.cpp diff --git a/old/0217 Contains Duplicate/cpp-Contains-Duplicate/CMakeLists.txt b/0001-0500/0217 Contains Duplicate/cpp-0217/CMakeLists.txt similarity index 100% rename from old/0217 Contains Duplicate/cpp-Contains-Duplicate/CMakeLists.txt rename to 0001-0500/0217 Contains Duplicate/cpp-0217/CMakeLists.txt diff --git a/0001-0500/0217 Contains Duplicate/cpp-0217/main.cpp b/0001-0500/0217 Contains Duplicate/cpp-0217/main.cpp new file mode 100644 index 00000000..99fcf2c2 --- /dev/null +++ b/0001-0500/0217 Contains Duplicate/cpp-0217/main.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/contains-duplicate/ +/// Author : liuyubobobo +/// Time : 2017-01-18 + +#include +#include +#include + +using namespace std; + +/// Using HashTable +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + bool containsDuplicate(vector& nums) { + + unordered_set record; + for( int i = 0 ; i < nums.size() ; i ++ ) + if( record.find( nums[i] ) == record.end() ) + record.insert( nums[i] ); + else + return true; + + return false; + } +}; + + +void print_bool(bool res){ + cout << (res ? "True" : "False") << endl; +} + +int main() { + + vector vec = {0, 0, 1}; + print_bool(Solution().containsDuplicate(vec)); + + return 0; +} \ No newline at end of file diff --git a/0218-The-Skyline-Problem/cpp-0218/CMakeLists.txt b/0001-0500/0218-The-Skyline-Problem/cpp-0218/CMakeLists.txt similarity index 100% rename from 0218-The-Skyline-Problem/cpp-0218/CMakeLists.txt rename to 0001-0500/0218-The-Skyline-Problem/cpp-0218/CMakeLists.txt diff --git a/0001-0500/0218-The-Skyline-Problem/cpp-0218/main.cpp b/0001-0500/0218-The-Skyline-Problem/cpp-0218/main.cpp new file mode 100644 index 00000000..222acdee --- /dev/null +++ b/0001-0500/0218-The-Skyline-Problem/cpp-0218/main.cpp @@ -0,0 +1,160 @@ +/// Source : https://leetcode.com/problems/the-skyline-problem/description/ +/// Author : liuyubobobo +/// Time : 2017-10-28 +/// updated: 2019-03-14 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// Using Segment Tree +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class SegmentTree{ + +private: + int n; + vector tree, lazy; + +public: + SegmentTree(int n): n(n), tree(4 * n, 0), lazy(4 * n, 0){} + + void add(int l, int r, int h){ + update(0, 0, n-1, l, r, h); + } + + int query(int index){ + return query(0, 0, n-1, index); + } + +private: + void update(int treeID, int treeL, int treeR, int l, int r, int h){ + + if(lazy[treeID] != 0){ + tree[treeID] = max(tree[treeID], lazy[treeID]); // max + if(treeL != treeR){ + lazy[2 * treeID + 1] = max(lazy[treeID], lazy[2 * treeID + 1]); // max + lazy[2 * treeID + 2] = max(lazy[treeID], lazy[2 * treeID + 2]); // max + } + lazy[treeID] = 0; + } + + if(treeL == l && treeR == r){ + tree[treeID] = max(tree[treeID], h); // max + if(treeL != treeR){ + lazy[2 * treeID + 1] = max(h, lazy[2 * treeID + 1]); // max + lazy[2 * treeID + 2] = max(h, lazy[2 * treeID + 2]); // max + } + return; + } + + int mid = (treeL + treeR) / 2; + + if(r <= mid) + update(2 * treeID + 1, treeL, mid, l, r, h); + else if(l >= mid + 1) + update(2 * treeID + 2, mid + 1, treeR, l, r, h); + else{ + update(2 * treeID + 1, treeL, mid, l, mid, h); + update(2 * treeID + 2, mid + 1, treeR, mid + 1, r, h); + } + + return; + } + + int query(int treeID, int treeL, int treeR, int index){ + + if(lazy[treeID] != 0){ + tree[treeID] = max(tree[treeID], lazy[treeID]); // max + if(treeL != treeR){ + lazy[2 * treeID + 1] = max(lazy[treeID], lazy[2 * treeID + 1]); // max + lazy[2 * treeID + 2] = max(lazy[treeID], lazy[2 * treeID + 2]); // max + } + lazy[treeID] = 0; + } + + if(treeL == treeR){ + assert(treeL == index); + return tree[treeID]; + } + + int mid = (treeL + treeR) / 2; + + if(index <= mid) + return query(2 * treeID + 1, treeL, mid, index); + + return query(2 * treeID + 2, mid + 1, treeR, index); + } +}; + + +class Solution { +public: + vector> getSkyline(vector>& buildings) { + + // Coordinate compression + set unique_points; + for(const vector& info: buildings){ + unique_points.insert(info[0]); + unique_points.insert(info[1]-1); + unique_points.insert(info[1]); + } + + unordered_map indexes; + vector pos; + for(int p: unique_points){ + indexes[p] = pos.size(); + pos.push_back(p); + } + + // segment tree + SegmentTree stree(pos.size()); + for(const vector& info: buildings) + stree.add(indexes[info[0]], indexes[info[1]-1], info[2]); + + // get results + vector> res; + unique_points.clear(); + for(const vector& info: buildings){ + unique_points.insert(info[0]); + unique_points.insert(info[1]); + } + + int last = 0; + for(int p: unique_points){ + int h = stree.query(indexes[p]); + if(h != last) + res.push_back({p, h}); + last = h; + } + + return res; + } +}; + + +int main() { + + int n = 5; + int buildings[5][3] = { + {2, 9, 10}, + {3, 7, 15}, + {5, 12, 12}, + {15, 20, 10}, + {19, 24, 8} + }; + vector> vec; + for(int i = 0 ; i < n ; i ++) + vec.push_back(vector(buildings[i], buildings[i] + 3)); + + vector> res = Solution().getSkyline(vec); + for(pair p: res) + cout << p.first << " " << p.second << endl; + + return 0; +} \ No newline at end of file diff --git a/0219-Contains-Duplicate-II/cpp-0219/CMakeLists.txt b/0001-0500/0219-Contains-Duplicate-II/cpp-0219/CMakeLists.txt similarity index 100% rename from 0219-Contains-Duplicate-II/cpp-0219/CMakeLists.txt rename to 0001-0500/0219-Contains-Duplicate-II/cpp-0219/CMakeLists.txt diff --git a/0001-0500/0219-Contains-Duplicate-II/cpp-0219/main.cpp b/0001-0500/0219-Contains-Duplicate-II/cpp-0219/main.cpp new file mode 100644 index 00000000..21e6f254 --- /dev/null +++ b/0001-0500/0219-Contains-Duplicate-II/cpp-0219/main.cpp @@ -0,0 +1,55 @@ +/// Source : https://leetcode.com/problems/contains-duplicate-ii/description/ +/// Author : liuyubobobo +/// Time : 2017-11-15 + +#include +#include +#include + +using namespace std; + +/// Using Hash Set +/// Time Complexity: O(n) +/// Space Complexity: O(k) +class Solution { +public: + bool containsNearbyDuplicate(vector& nums, int k) { + + if(nums.size() <= 1) + return false; + + if(k <= 0) + return false; + + unordered_set record; + for(int i = 0 ; i < nums.size() ; i ++){ + + if(record.find(nums[i]) != record.end()) + return true; + + record.insert(nums[i]); + + // 保持record中最多有k个元素 + // 因为在下一次循环中会添加一个新元素,使得总共考虑k+1个元素 + if(record.size() == k + 1) + record.erase(nums[i - k]); + } + + return false; + } +}; + + +void print_bool(bool b){ + cout << (b ? "True" : "False") << endl; +} + +int main() { + + vector nums = {1, 2, 1}; + int k = 1; + + print_bool(Solution().containsNearbyDuplicate(nums, k)); + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0219-Contains-Duplicate-II/cpp-0219/main2.cpp b/0001-0500/0219-Contains-Duplicate-II/cpp-0219/main2.cpp new file mode 100644 index 00000000..6b296c84 --- /dev/null +++ b/0001-0500/0219-Contains-Duplicate-II/cpp-0219/main2.cpp @@ -0,0 +1,51 @@ +/// Source : https://leetcode.com/problems/contains-duplicate-ii/description/ +/// Author : liuyubobobo +/// Time : 2019-04-10 + +#include +#include +#include + +using namespace std; + +/// Using Hash Map +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + bool containsNearbyDuplicate(vector& nums, int k) { + + if(nums.size() <= 1) + return false; + + if(k <= 0) + return false; + + unordered_map record; + record[nums[0]] = 0; + for(int i = 1 ; i < nums.size() ; i ++){ + + if(record.count(nums[i]) && i - record[nums[i]] <= k) + return true; + + record[nums[i]] = i; + } + + return false; + } +}; + + +void print_bool(bool b){ + cout << (b ? "True" : "False") << endl; +} + +int main() { + + vector nums = {1, 2, 1}; + int k = 1; + + print_bool(Solution().containsNearbyDuplicate(nums, k)); + + return 0; +} \ No newline at end of file diff --git a/0219-Contains-Duplicate-II/java-0219/src/Solution.java b/0001-0500/0219-Contains-Duplicate-II/java-0219/src/Solution.java similarity index 100% rename from 0219-Contains-Duplicate-II/java-0219/src/Solution.java rename to 0001-0500/0219-Contains-Duplicate-II/java-0219/src/Solution.java diff --git a/0001-0500/0219-Contains-Duplicate-II/java-0219/src/Solution2.java b/0001-0500/0219-Contains-Duplicate-II/java-0219/src/Solution2.java new file mode 100644 index 00000000..8a290c62 --- /dev/null +++ b/0001-0500/0219-Contains-Duplicate-II/java-0219/src/Solution2.java @@ -0,0 +1,42 @@ +/// Source : https://leetcode.com/problems/contains-duplicate-ii/description/ +/// Author : liuyubobobo +/// Time : 2019-04-10 + +import java.util.HashMap; + +/// Using Hash Map +/// Time Complexity: O(n) +/// Space Complexity: O(n) +public class Solution2 { + + public boolean containsNearbyDuplicate(int[] nums, int k) { + + if(nums == null || nums.length <= 1) + return false; + + if(k <= 0) + return false; + + HashMap record = new HashMap<>(); + record.put(nums[0], 0); + for(int i = 1; i < nums.length; i ++){ + if(record.containsKey(nums[i]) && i - record.get(nums[i]) <= k) + return true; + + record.put(nums[i], i); + } + + return false; + } + + private static void printBool(boolean b){ + System.out.println(b ? "True" : "False"); + } + + public static void main(String[] args) { + + int[] nums = {1, 2, 1}; + int k = 1; + printBool((new Solution()).containsNearbyDuplicate(nums, k)); + } +} diff --git a/0220-Contains-Duplicate-III/cpp-0220/CMakeLists.txt b/0001-0500/0220-Contains-Duplicate-III/cpp-0220/CMakeLists.txt similarity index 100% rename from 0220-Contains-Duplicate-III/cpp-0220/CMakeLists.txt rename to 0001-0500/0220-Contains-Duplicate-III/cpp-0220/CMakeLists.txt diff --git a/0220-Contains-Duplicate-III/cpp-0220/main.cpp b/0001-0500/0220-Contains-Duplicate-III/cpp-0220/main.cpp similarity index 100% rename from 0220-Contains-Duplicate-III/cpp-0220/main.cpp rename to 0001-0500/0220-Contains-Duplicate-III/cpp-0220/main.cpp diff --git a/0220-Contains-Duplicate-III/cpp-0220/main2.cpp b/0001-0500/0220-Contains-Duplicate-III/cpp-0220/main2.cpp similarity index 100% rename from 0220-Contains-Duplicate-III/cpp-0220/main2.cpp rename to 0001-0500/0220-Contains-Duplicate-III/cpp-0220/main2.cpp diff --git a/0220-Contains-Duplicate-III/java-0220/src/Solution1.java b/0001-0500/0220-Contains-Duplicate-III/java-0220/src/Solution1.java similarity index 100% rename from 0220-Contains-Duplicate-III/java-0220/src/Solution1.java rename to 0001-0500/0220-Contains-Duplicate-III/java-0220/src/Solution1.java diff --git a/0220-Contains-Duplicate-III/java-0220/src/Solution2.java b/0001-0500/0220-Contains-Duplicate-III/java-0220/src/Solution2.java similarity index 100% rename from 0220-Contains-Duplicate-III/java-0220/src/Solution2.java rename to 0001-0500/0220-Contains-Duplicate-III/java-0220/src/Solution2.java diff --git a/0001-0500/0221-Maximal-Square/cpp-0221/CMakeLists.txt b/0001-0500/0221-Maximal-Square/cpp-0221/CMakeLists.txt new file mode 100644 index 00000000..4763834c --- /dev/null +++ b/0001-0500/0221-Maximal-Square/cpp-0221/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(cpp_0221) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0221 main5.cpp) \ No newline at end of file diff --git a/0001-0500/0221-Maximal-Square/cpp-0221/main.cpp b/0001-0500/0221-Maximal-Square/cpp-0221/main.cpp new file mode 100644 index 00000000..76bbdb44 --- /dev/null +++ b/0001-0500/0221-Maximal-Square/cpp-0221/main.cpp @@ -0,0 +1,43 @@ +/// Source : https://leetcode.com/problems/maximal-square/ +/// Author : liuyubobobo +/// Time : 2020-01-04 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(m * n * m * n * min(m, n)) +/// Space Complexity: O(1) +class Solution { +public: + int maximalSquare(vector>& matrix) { + + int res = 0; + for(int i = 0; i < matrix.size(); i ++) + for(int j = 0; j < matrix[i].size(); j ++) + if(matrix[i][j] == '1'){ + for(int len = 1; i + len <= matrix.size() && j + len <= matrix[i].size(); len ++) + if(ok(matrix, i, j, len)) res = max(res, len * len); + else break; + } + return res; + } + +private: + bool ok(const vector>& matrix, int x, int y, int len){ + + for(int i = x; i < x + len; i ++) + for(int j = y; j < y + len; j ++) + if(matrix[i][j] == '0') return false; + return true; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0221-Maximal-Square/cpp-0221/main2.cpp b/0001-0500/0221-Maximal-Square/cpp-0221/main2.cpp new file mode 100644 index 00000000..992b8934 --- /dev/null +++ b/0001-0500/0221-Maximal-Square/cpp-0221/main2.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/maximal-square/ +/// Author : liuyubobobo +/// Time : 2020-01-04 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(m * n * min(m, n) * max(m, n)) +/// Space Complexity: O(1) +class Solution { +public: + int maximalSquare(vector>& matrix) { + + int res = 0; + for(int i = 0; i < matrix.size(); i ++) + for(int j = 0; j < matrix[i].size(); j ++) + if(matrix[i][j] == '1'){ + for(int len = 0; i + len < matrix.size() && j + len < matrix[i].size(); len ++) + if(okrow(matrix, i + len, j, len) && okcol(matrix, i, j + len, len)) + res = max(res, (len + 1) * (len + 1)); + else break; + } + return res; + } + +private: + bool okrow(const vector>& matrix, int x, int y, int len){ + + for(int j = y; j <= y + len; j ++) + if(matrix[x][j] == '0') return false; + return true; + } + + bool okcol(const vector>& matrix, int x, int y, int len){ + + for(int i = x; i <= x + len; i ++) + if(matrix[i][y] == '0') return false; + return true; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0221-Maximal-Square/cpp-0221/main3.cpp b/0001-0500/0221-Maximal-Square/cpp-0221/main3.cpp new file mode 100644 index 00000000..209beb19 --- /dev/null +++ b/0001-0500/0221-Maximal-Square/cpp-0221/main3.cpp @@ -0,0 +1,36 @@ +/// Source : https://leetcode.com/problems/maximal-square/ +/// Author : liuyubobobo +/// Time : 2020-01-06 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(m * n) +/// Space Complexity: O(m * n) +class Solution { +public: + int maximalSquare(vector>& matrix) { + + if(matrix.size() == 0) return 0; + + vector> dp(matrix.size() + 1, vector(matrix[0].size() + 1, 0)); + int res = 0; + for(int i = 0; i < matrix.size(); i ++) + for(int j = 0; j < matrix[i].size(); j ++) + if(matrix[i][j] == '1'){ + dp[i + 1][j + 1] = min(dp[i][j], min(dp[i][j + 1], dp[i + 1][j])) + 1; + res = max(res, dp[i + 1][j + 1]); + } + return res * res; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0221-Maximal-Square/cpp-0221/main4.cpp b/0001-0500/0221-Maximal-Square/cpp-0221/main4.cpp new file mode 100644 index 00000000..a59a5547 --- /dev/null +++ b/0001-0500/0221-Maximal-Square/cpp-0221/main4.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/maximal-square/ +/// Author : liuyubobobo +/// Time : 2020-01-06 + +#include +#include + +using namespace std; + + +/// Dynamic Programming with Space Optimization +/// Time Complexity: O(m * n) +/// Space Complexity: O(n) +class Solution { +public: + int maximalSquare(vector>& matrix) { + + if(matrix.size() == 0) return 0; + + vector dp(matrix[0].size() + 1, 0); + int res = 0, pre = 0; + for(int i = 0; i < matrix.size(); i ++) + for(int j = 0; j < matrix[i].size(); j ++){ + int temp = dp[j + 1]; + if(matrix[i][j] == '1'){ + dp[j + 1] = min(dp[j], min(dp[j + 1], pre)) + 1; + res = max(res, dp[j + 1]); + } + else dp[j + 1] = 0; + pre = temp; + } + return res * res; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0221-Maximal-Square/cpp-0221/main5.cpp b/0001-0500/0221-Maximal-Square/cpp-0221/main5.cpp new file mode 100644 index 00000000..238580aa --- /dev/null +++ b/0001-0500/0221-Maximal-Square/cpp-0221/main5.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/maximal-square/ +/// Author : liuyubobobo +/// Time : 2020-01-06 + +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(m * n) +/// Space Complexity: O(m * n) +class Solution { +public: + int maximalSquare(vector>& matrix) { + + if(matrix.size() == 0) return 0; + + vector> dp(matrix.size() + 1, vector(matrix[0].size() + 1, -1)); + int res = 0; + for(int i = matrix.size() - 1; i >= 0; i --) + for(int j = matrix[i].size() - 1; j >= 0; j --) + res = max(res, dfs(matrix, i, j, dp)); + return res * res; + } + +private: + int dfs(const vector>& matrix, int x, int y, + vector>& dp){ + + if(x == 0 || y == 0) return dp[x][y] = matrix[x][y] == '1' ? 1 : 0; + if(matrix[x][y] == '0') return dp[x][y] = 0; + if(dp[x][y] != -1) return dp[x][y]; + + int res = min(min(dfs(matrix, x - 1, y, dp), dfs(matrix, x, y - 1, dp)), + dfs(matrix, x - 1, y - 1, dp)) + 1; + return dp[x][y] = res; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0221-Maximal-Square/py-0221/Solution.py b/0001-0500/0221-Maximal-Square/py-0221/Solution.py new file mode 100644 index 00000000..282d844d --- /dev/null +++ b/0001-0500/0221-Maximal-Square/py-0221/Solution.py @@ -0,0 +1,24 @@ +# Source : https://leetcode.com/problems/maximal-square/ +# Author : penpenps +# Time : 2019-07-24 + +from typing import List + +# DP solution, dp[i][i] represents the length of largest square end with matrix[i][j] +# Then, dp[i][j] = min(dp[i-1][j-1], dp[i][j-1], dp[i-1][j]) + 1 +# Time Complexity: O(n^2) +# Space Complexity: O(n^2) + +class Solution: + def maximalSquare(self, matrix: List[List[str]]) -> int: + if not matrix or not matrix[0]: return 0 + n = len(matrix) + m = len(matrix[0]) + + dp = [[1 if matrix[i][j] == '1' else 0 for j in range(m)] for i in range(n)] + + for i in range(1, n): + for j in range(1, m): + if matrix[i][j] == '1': + dp[i][j] = min(dp[i-1][j-1], dp[i][j-1], dp[i-1][j]) + 1 + return max(max(row) for row in dp)**2 \ No newline at end of file diff --git a/0001-0500/0221-Maximal-Square/py-0221/Solution2.py b/0001-0500/0221-Maximal-Square/py-0221/Solution2.py new file mode 100644 index 00000000..5868d4c4 --- /dev/null +++ b/0001-0500/0221-Maximal-Square/py-0221/Solution2.py @@ -0,0 +1,28 @@ +# Source : https://leetcode.com/problems/maximal-square/ +# Author : penpenps +# Time : 2019-07-24 + +from typing import List + +# modify matrix in-place +# Time Complexity: O(n^2) +# Space Complexity: O(1) + +class Solution: + def maximalSquare(self, matrix: List[List[str]]) -> int: + if not matrix or not matrix[0]: return 0 + n = len(matrix) + m = len(matrix[0]) + + for i in range(n): + matrix[i][0] = 1 if matrix[i][0] == '1' else 0 + for j in range(1, m): + matrix[0][j] = 1 if matrix[0][j] == '1' else 0 + + for i in range(1, n): + for j in range(1, m): + if matrix[i][j] == '1': + matrix[i][j] = min(matrix[i-1][j-1], matrix[i][j-1], matrix[i-1][j]) + 1 + else: + matrix[i][j] = 0 + return max(max(row) for row in matrix)**2 \ No newline at end of file diff --git a/0001-0500/0222-Count-Complete-Tree-Nodes/cpp-0222/CMakeLists.txt b/0001-0500/0222-Count-Complete-Tree-Nodes/cpp-0222/CMakeLists.txt new file mode 100644 index 00000000..d3b2fe1a --- /dev/null +++ b/0001-0500/0222-Count-Complete-Tree-Nodes/cpp-0222/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0222) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0222 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0222-Count-Complete-Tree-Nodes/cpp-0222/main.cpp b/0001-0500/0222-Count-Complete-Tree-Nodes/cpp-0222/main.cpp new file mode 100644 index 00000000..a97fad5a --- /dev/null +++ b/0001-0500/0222-Count-Complete-Tree-Nodes/cpp-0222/main.cpp @@ -0,0 +1,77 @@ +/// Source : https://leetcode.com/problems/count-complete-tree-nodes/ +/// Author : liuyubobobo +/// Time : 2018-08-02 +/// Updated: 2020-10-22 + +#include +#include + +using namespace std; + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + + +/// Recursion +/// Time Complexity: O(h^2) where h is the height of the tree +/// Space Complexity: O(h) +class Solution { + +public: + int countNodes(TreeNode* root) { + + if(root == NULL) + return 0; + + int left = leftHeight(root); + int right = rightHeight(root); + if(left == right) + return (1 << left) - 1; + +// assert(left == right + 1); + return 1 + countNodes(root->left) + countNodes(root->right); + } + +private: + int leftHeight(TreeNode* root){ + if(root == NULL) + return 0; + return 1 + leftHeight(root->left); + } + + int rightHeight(TreeNode* root){ + if(root == NULL) + return 0; + return 1 + rightHeight(root->right); + } +}; + + +int main() { + + TreeNode* root = new TreeNode(1); + + TreeNode* left = new TreeNode(2); + root->left = left; + + TreeNode* right = new TreeNode(3); + root->right = right; + + TreeNode* leftleft = new TreeNode(4); + root->left->left = leftleft; + + TreeNode* leftright = new TreeNode(5); + root->left->right = leftright; + + TreeNode* rightleft = new TreeNode(6); + root->right->left = rightleft; + + cout << Solution().countNodes(root) << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0222-Count-Complete-Tree-Nodes/java-0222/Solution.java b/0001-0500/0222-Count-Complete-Tree-Nodes/java-0222/Solution.java new file mode 100644 index 00000000..27fded11 --- /dev/null +++ b/0001-0500/0222-Count-Complete-Tree-Nodes/java-0222/Solution.java @@ -0,0 +1,22 @@ +/// Source : https://leetcode.com/problems/count-complete-tree-nodes/ +/// Author : Mark Zhang +/// Time : 2020-07-09 + +/// Recursion +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +class Solution { + public int countNodes(TreeNode root) { + if(root == null) + return 0; + + if(root.left == null && root.right == null) + return 1; + + int countLeft = countNodes(root.left); + int countRight = countNodes(root.right); + + return countLeft + countRight + 1; + } +} diff --git a/0001-0500/0223-Rectangle-Area/cpp-0223/CMakeLists.txt b/0001-0500/0223-Rectangle-Area/cpp-0223/CMakeLists.txt new file mode 100644 index 00000000..0270dac1 --- /dev/null +++ b/0001-0500/0223-Rectangle-Area/cpp-0223/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0223) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0223 main.cpp) diff --git a/0001-0500/0223-Rectangle-Area/cpp-0223/main.cpp b/0001-0500/0223-Rectangle-Area/cpp-0223/main.cpp new file mode 100644 index 00000000..843290ac --- /dev/null +++ b/0001-0500/0223-Rectangle-Area/cpp-0223/main.cpp @@ -0,0 +1,41 @@ +/// Source : https://leetcode.com/problems/rectangle-area/ +/// Author : liuyubobobo +/// Time : 2021-09-29 + +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(1) +/// Space Complexity: O(1) +class Solution { +public: + int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) { + + int total = abs(ax1 - ax2) * abs(ay1 - ay2) + abs(bx1 - bx2) * abs(by1 - by2); + + if(ax2 <= bx1 || bx2 <= ax1) return total; + + if(ay2 <= by1 || by2 <= ay1) return total; + + int x, y; + if(ax1 <= bx1) x = bx2 <= ax2 ? bx2 - bx1 : ax2 - bx1; + else x = ax2 <= bx2 ? ax2 - ax1 : bx2 - ax1; + + if(ay1 <= by1) y = by2 <= ay2 ? by2 - by1 : ay2 - by1; + else y = ay2 <= by2 ? ay2 - ay1 : by2 - ay1; + + return total - x * y; + } +}; + + +int main() { + + cout << Solution().computeArea(-5, 4, 0, 5, -3, -3, 3, 3) << endl; + // 41 + + return 0; +} diff --git a/0001-0500/0224-Basic-Calculator/cpp-0224/CMakeLists.txt b/0001-0500/0224-Basic-Calculator/cpp-0224/CMakeLists.txt new file mode 100644 index 00000000..4401e346 --- /dev/null +++ b/0001-0500/0224-Basic-Calculator/cpp-0224/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0224) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0224 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0224-Basic-Calculator/cpp-0224/main.cpp b/0001-0500/0224-Basic-Calculator/cpp-0224/main.cpp new file mode 100644 index 00000000..cff2b971 --- /dev/null +++ b/0001-0500/0224-Basic-Calculator/cpp-0224/main.cpp @@ -0,0 +1,93 @@ +/// Source : https://leetcode.com/problems/basic-calculator/description/ +/// Author : liuyubobobo +/// Time : 2018-09-03 +/// Updated: 2022-11-20 + +#include +#include +#include + +using namespace std; + + +/// Two Stacks +/// Shunting-Yard Algorithms: https://en.wikipedia.org/wiki/Shunting-yard_algorithm +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int calculate(string s2) { + + string s; + for(char c: s2) if(c != ' ') s += c; + + int n = s.size(); + vector right(n, -1); + vector left; + for(int i = 0; i < n; i ++) { + if (s[i] == '(') left.push_back(i); + else if (s[i] == ')') right[left.back()] = i, left.pop_back(); + } + + return parse(s, 0, n - 1, right); + } + +private: + int parse(const string& s, int l, int r, const vector& right){ + + vector nums; + vector ops; + + for(int i = l; i <= r; ){ + if(s[i] == '+' || s[i] == '-'){ + ops.push_back(s[i++]); + if(nums.empty()) nums.push_back(0); + } + else if(s[i] == '('){ + nums.push_back(parse(s, i + 1, right[i] - 1, right)); + cal(nums, ops); + i = right[i] + 1; + } + else{ + int j = i, num = 0; + for(; j <= r && isdigit(s[j]); j ++) + num = num * 10 + (s[j] - '0'); + + nums.push_back(num); + cal(nums, ops); + i = j; + } + } + + assert(nums.size() == 1); + return nums.back(); + } + + void cal(vector& nums, vector& ops){ + + if(!ops.empty() && (ops.back() == '+' || ops.back() == '-')){ + + int second = nums.back(); + nums.pop_back(); + + int first = nums.empty() ? 0 : nums.back(); + if(!nums.empty()) nums.pop_back(); + + nums.push_back(ops.back() == '+' ? (first + second) : (first - second)); + ops.pop_back(); + } + } +}; + + +int main() { + + cout << Solution().calculate("1 + 1") << endl; // 2 + cout << Solution().calculate(" 2-1 + 2 ") << endl; // 3 + cout << Solution().calculate("(1+(4+5+2)-3)+(6+8)") << endl; // 23 + cout << Solution().calculate("-2+ 1") << endl; // -1 + cout << Solution().calculate("1-(-2)") << endl; // 3 + cout << Solution().calculate("-(3+(4+5))") << endl; // -12 + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0225-Implement-Stack-using-Queues/cpp-0225/CMakeLists.txt b/0001-0500/0225-Implement-Stack-using-Queues/cpp-0225/CMakeLists.txt new file mode 100644 index 00000000..9211c5d3 --- /dev/null +++ b/0001-0500/0225-Implement-Stack-using-Queues/cpp-0225/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0225) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main4.cpp) +add_executable(cpp_0225 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0225-Implement-Stack-using-Queues/cpp-0225/main.cpp b/0001-0500/0225-Implement-Stack-using-Queues/cpp-0225/main.cpp new file mode 100644 index 00000000..dd4dc431 --- /dev/null +++ b/0001-0500/0225-Implement-Stack-using-Queues/cpp-0225/main.cpp @@ -0,0 +1,87 @@ +/// Source : https://leetcode.com/problems/implement-stack-using-queues/description/ +/// Author : liuyubobobo +/// Time : 2018-09-29 + +#include +#include + +using namespace std; + + +/// Naive Implementation +/// Time Complexity: init: O(1) +/// push: O(1) +/// pop: O(n) +/// top: O(n) +/// empty: O(1) +/// Space Complexity: O(n) +class MyStack { + +private: + queue q; + +public: + /** Initialize your data structure here. */ + MyStack() {} + + /** Push element x onto stack. */ + void push(int x) { + q.push(x); + } + + /** Removes the element on top of the stack and returns that element. */ + int pop() { + + assert(!empty()); + + queue q2; + while(q.size() > 1){ + q2.push(q.front()); + q.pop(); + } + + int ret = q.front(); + q.pop(); + + while(!q2.empty()){ + q.push(q2.front()); + q2.pop(); + } + + return ret; + } + + /** Get the top element. */ + int top() { + + assert(!empty()); + + queue q2; + while(q.size() > 1){ + q2.push(q.front()); + q.pop(); + } + + int ret = q.front(); + q2.push(ret); + q.pop(); + + while(!q2.empty()){ + q.push(q2.front()); + q2.pop(); + } + + return ret; + } + + /** Returns whether the stack is empty. */ + bool empty() { + return q.empty(); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0225-Implement-Stack-using-Queues/cpp-0225/main2.cpp b/0001-0500/0225-Implement-Stack-using-Queues/cpp-0225/main2.cpp new file mode 100644 index 00000000..29102c79 --- /dev/null +++ b/0001-0500/0225-Implement-Stack-using-Queues/cpp-0225/main2.cpp @@ -0,0 +1,75 @@ +/// Source : https://leetcode.com/problems/implement-stack-using-queues/description/ +/// Author : liuyubobobo +/// Time : 2018-09-29 + +#include +#include +#include + +using namespace std; + + +/// Naive Implementation +/// Using a variable to record top element:) +/// +/// Time Complexity: init: O(1) +/// push: O(1) +/// pop: O(n) +/// top: O(1) +/// empty: O(1) +/// Space Complexity: O(n) +class MyStack { + +private: + queue q; + int topV; + +public: + /** Initialize your data structure here. */ + MyStack() {} + + /** Push element x onto stack. */ + void push(int x) { + q.push(x); + topV = x; + } + + /** Removes the element on top of the stack and returns that element. */ + int pop() { + assert(!empty()); + + queue q2; + while(q.size() > 1){ + q2.push(q.front()); + q.pop(); + } + + int ret = q.front(); + q.pop(); + + while(!q2.empty()){ + q.push(q2.front()); + topV = q2.front(); + q2.pop(); + } + + return ret; + } + + /** Get the top element. */ + int top() { + assert(!empty()); + return topV; + } + + /** Returns whether the stack is empty. */ + bool empty() { + return q.empty(); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0225-Implement-Stack-using-Queues/cpp-0225/main3.cpp b/0001-0500/0225-Implement-Stack-using-Queues/cpp-0225/main3.cpp new file mode 100644 index 00000000..3d8138d0 --- /dev/null +++ b/0001-0500/0225-Implement-Stack-using-Queues/cpp-0225/main3.cpp @@ -0,0 +1,72 @@ +/// Source : https://leetcode.com/problems/implement-stack-using-queues/description/ +/// Author : liuyubobobo +/// Time : 2018-09-29 + +#include +#include +#include + +using namespace std; + + +/// Naive Implementation +/// Using a variable to record top element:) +/// +/// Time Complexity: init: O(1) +/// push: O(n) +/// pop: O(1) +/// top: O(1) +/// empty: O(1) +/// Space Complexity: O(n) +class MyStack { + +private: + queue q; + +public: + /** Initialize your data structure here. */ + MyStack() {} + + /** Push element x onto stack. */ + void push(int x) { + + queue q2; + while(!q.empty()){ + q2.push(q.front()); + q.pop(); + } + + q.push(x); + + while(!q2.empty()){ + q.push(q2.front()); + q2.pop(); + } + } + + /** Removes the element on top of the stack and returns that element. */ + int pop() { + + assert(!empty()); + int ret = q.front(); + q.pop(); + return ret; + } + + /** Get the top element. */ + int top() { + assert(!empty()); + return q.front(); + } + + /** Returns whether the stack is empty. */ + bool empty() { + return q.empty(); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0225-Implement-Stack-using-Queues/cpp-0225/main4.cpp b/0001-0500/0225-Implement-Stack-using-Queues/cpp-0225/main4.cpp new file mode 100644 index 00000000..1b3f70db --- /dev/null +++ b/0001-0500/0225-Implement-Stack-using-Queues/cpp-0225/main4.cpp @@ -0,0 +1,67 @@ +/// Source : https://leetcode.com/problems/implement-stack-using-queues/description/ +/// Author : liuyubobobo +/// Time : 2018-09-29 + +#include +#include +#include + +using namespace std; + + +/// Using only one queue! +/// +/// Time Complexity: init: O(1) +/// push: O(n) +/// pop: O(1) +/// top: O(1) +/// empty: O(1) +/// Space Complexity: O(n) +class MyStack { + +private: + queue q; + int sz = 0; + +public: + /** Initialize your data structure here. */ + MyStack(): sz(0) {} + + /** Push element x onto stack. */ + void push(int x) { + q.push(x); + for(int i = 0; i < sz; i ++){ + int e = q.front(); + q.pop(); + q.push(e); + } + sz ++; + } + + /** Removes the element on top of the stack and returns that element. */ + int pop() { + + assert(!empty()); + int ret = q.front(); + q.pop(); + sz --; + return ret; + } + + /** Get the top element. */ + int top() { + assert(!empty()); + return q.front(); + } + + /** Returns whether the stack is empty. */ + bool empty() { + return q.empty(); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0226-Invert-Binary-Tree/cpp-0226/CMakeLists.txt b/0001-0500/0226-Invert-Binary-Tree/cpp-0226/CMakeLists.txt similarity index 100% rename from 0226-Invert-Binary-Tree/cpp-0226/CMakeLists.txt rename to 0001-0500/0226-Invert-Binary-Tree/cpp-0226/CMakeLists.txt diff --git a/0226-Invert-Binary-Tree/cpp-0226/main.cpp b/0001-0500/0226-Invert-Binary-Tree/cpp-0226/main.cpp similarity index 100% rename from 0226-Invert-Binary-Tree/cpp-0226/main.cpp rename to 0001-0500/0226-Invert-Binary-Tree/cpp-0226/main.cpp diff --git a/0226-Invert-Binary-Tree/cpp-0226/main2.cpp b/0001-0500/0226-Invert-Binary-Tree/cpp-0226/main2.cpp similarity index 100% rename from 0226-Invert-Binary-Tree/cpp-0226/main2.cpp rename to 0001-0500/0226-Invert-Binary-Tree/cpp-0226/main2.cpp diff --git a/0226-Invert-Binary-Tree/java-0226/src/Solution1.java b/0001-0500/0226-Invert-Binary-Tree/java-0226/src/Solution1.java similarity index 100% rename from 0226-Invert-Binary-Tree/java-0226/src/Solution1.java rename to 0001-0500/0226-Invert-Binary-Tree/java-0226/src/Solution1.java diff --git a/0226-Invert-Binary-Tree/java-0226/src/Solution2.java b/0001-0500/0226-Invert-Binary-Tree/java-0226/src/Solution2.java similarity index 100% rename from 0226-Invert-Binary-Tree/java-0226/src/Solution2.java rename to 0001-0500/0226-Invert-Binary-Tree/java-0226/src/Solution2.java diff --git a/0001-0500/0226-Invert-Binary-Tree/py-0226/Solution.py b/0001-0500/0226-Invert-Binary-Tree/py-0226/Solution.py new file mode 100644 index 00000000..34b22843 --- /dev/null +++ b/0001-0500/0226-Invert-Binary-Tree/py-0226/Solution.py @@ -0,0 +1,25 @@ +# Source : https://leetcode.com/problems/invert-binary-tree/ +# Author : penpenps +# Time : 2019-08-01 + +# Recursive +# Time Complexity: O(n), the number of tree's nodes +# Space Complexity: O(h), the height of tree + +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution: + def invertTree(self, root: TreeNode) -> TreeNode: + if not root: return root + if root.left: + root.left = self.invertTree(root.left) + if root.right: + root.right = self.invertTree(root.right) + if root.left or root.right: + root.left, root.right = root.right, root.left + return root \ No newline at end of file diff --git a/0001-0500/0226-Invert-Binary-Tree/py-0226/Solution2.py b/0001-0500/0226-Invert-Binary-Tree/py-0226/Solution2.py new file mode 100644 index 00000000..2258584d --- /dev/null +++ b/0001-0500/0226-Invert-Binary-Tree/py-0226/Solution2.py @@ -0,0 +1,28 @@ +# Source : https://leetcode.com/problems/invert-binary-tree/ +# Author : penpenps +# Time : 2019-08-01 + +# BFS, iterative +# Time Complexity: O(n), the number of tree's nodes +# Space Complexity: O(n), the max node number by level + +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution: + def invertTree(self, root: TreeNode) -> TreeNode: + if not root: return root + queue = [root] + while queue: + node = queue.pop(0) + node.left, node.right = node.right, node.left + if node.left: + queue.append(node.left) + if node.right: + queue.append(node.right) + return root + \ No newline at end of file diff --git a/0001-0500/0227-Basic-Calculator-II/cpp-0227/CMakeLists.txt b/0001-0500/0227-Basic-Calculator-II/cpp-0227/CMakeLists.txt new file mode 100644 index 00000000..1ab1f90a --- /dev/null +++ b/0001-0500/0227-Basic-Calculator-II/cpp-0227/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0227) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0227 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0227-Basic-Calculator-II/cpp-0227/main.cpp b/0001-0500/0227-Basic-Calculator-II/cpp-0227/main.cpp new file mode 100644 index 00000000..d8c9584e --- /dev/null +++ b/0001-0500/0227-Basic-Calculator-II/cpp-0227/main.cpp @@ -0,0 +1,84 @@ +/// Source : https://leetcode.com/problems/basic-calculator-ii/description/ +/// Author : liuyubobobo +/// Time : 2018-09-03 + +#include +#include +#include + +using namespace std; + + +/// Two Stacks +/// Shunting-Yard Algorithms: https://en.wikipedia.org/wiki/Shunting-yard_algorithm +/// +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int calculate(string s) { + + vector nums; + vector ops; + for(int i = 0; i < s.size() ; ){ + if(isdigit(s[i])){ + int num = s[i] - '0'; + int j; + for(j = i + 1; j < s.size() && isdigit(s[j]); j ++) + num = num * 10 + (s[j] - '0'); + i = j; + + nums.push_back(num); + if(!ops.empty() && (ops.back() == '*' || ops.back() == '/')) + calc(nums, ops); + } + else if(s[i] != ' '){ + if((s[i] == '+' || s[i] == '-') && !ops.empty() && (ops.back() == '+' || ops.back() == '-')) + calc(nums, ops); + ops.push_back(s[i++]); + } + else + i ++; + } + if(nums.size() != 1){ + assert(nums.size() == 2); + calc(nums, ops); + } + + return nums.back(); + } + +private: + void calc(vector& nums, vector& ops){ + + assert(nums.size() >= 2); + int second = nums.back(); + nums.pop_back(); + int first = nums.back(); + nums.pop_back(); + + assert(!ops.empty()); + char op = ops.back(); + ops.pop_back(); + + switch(op){ + case '+': nums.push_back(first + second); return; + case '-': nums.push_back(first - second); return; + case '*': nums.push_back(first * second); return; + case '/': nums.push_back(first / second); return; + default: assert(false); return; + } + } +}; + + +int main() { + + cout << Solution().calculate("3+2*2") << endl; // 7 + cout << Solution().calculate(" 3/2 ") << endl; // 1 + cout << Solution().calculate(" 3+5 / 2 ") << endl; // 5 + cout << Solution().calculate("42") << endl; // 42 + cout << Solution().calculate("1-1+1") << endl; // 1 + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0228-Summary-Ranges/cpp-0228/CMakeLists.txt b/0001-0500/0228-Summary-Ranges/cpp-0228/CMakeLists.txt new file mode 100644 index 00000000..78212ef8 --- /dev/null +++ b/0001-0500/0228-Summary-Ranges/cpp-0228/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0228) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0228 main.cpp) \ No newline at end of file diff --git a/0001-0500/0228-Summary-Ranges/cpp-0228/main.cpp b/0001-0500/0228-Summary-Ranges/cpp-0228/main.cpp new file mode 100644 index 00000000..88e1d4cb --- /dev/null +++ b/0001-0500/0228-Summary-Ranges/cpp-0228/main.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/summary-ranges/ +/// Author : liuyubobobo +/// Time : 2021-01-10 + +#include +#include + +using namespace std; + + +/// Split +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + vector summaryRanges(vector& nums) { + + vector res; + for(int start = 0, i = 1; i <= nums.size(); i ++) + if(i == nums.size() || nums[i] != nums[i - 1] + 1){ + if(i - start == 1) res.push_back(to_string(nums[start])); + else res.push_back(to_string(nums[start]) + "->" + to_string(nums[i - 1])); + + start = i; + i = start; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0229-Majority-Element-II/cpp-0229/CMakeLists.txt b/0001-0500/0229-Majority-Element-II/cpp-0229/CMakeLists.txt new file mode 100644 index 00000000..5a22d45d --- /dev/null +++ b/0001-0500/0229-Majority-Element-II/cpp-0229/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0229) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0229 main.cpp) diff --git a/0001-0500/0229-Majority-Element-II/cpp-0229/main.cpp b/0001-0500/0229-Majority-Element-II/cpp-0229/main.cpp new file mode 100644 index 00000000..f9d31e88 --- /dev/null +++ b/0001-0500/0229-Majority-Element-II/cpp-0229/main.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/majority-element-ii/ +/// Author : liuyubobobo +/// Time : 2021-10-21 + +#include +#include + +using namespace std; + + +/// Sorting +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + vector majorityElement(vector& nums) { + + vector res; + + int n = nums.size(); + sort(nums.begin(), nums.end()); + for(int start = 0, i = 1; i <= n; i ++) + if(i == n || nums[i] != nums[start]){ + if(i - start > n / 3) res.push_back(nums[start]); + start = i; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0230-Kth-Smallest-Element-in-a-BST/cpp-0230/CMakeLists.txt b/0001-0500/0230-Kth-Smallest-Element-in-a-BST/cpp-0230/CMakeLists.txt new file mode 100644 index 00000000..ff62cebc --- /dev/null +++ b/0001-0500/0230-Kth-Smallest-Element-in-a-BST/cpp-0230/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0230) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0230 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0230-Kth-Smallest-Element-in-a-BST/cpp-0230/main.cpp b/0001-0500/0230-Kth-Smallest-Element-in-a-BST/cpp-0230/main.cpp new file mode 100644 index 00000000..7d7af4e1 --- /dev/null +++ b/0001-0500/0230-Kth-Smallest-Element-in-a-BST/cpp-0230/main.cpp @@ -0,0 +1,51 @@ +/// Source : https://leetcode.com/problems/kth-smallest-element-in-a-bst/description/ +/// Author : liuyubobobo +/// Time : 2018-07-29 +#include + +using namespace std; + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +/// Inorder Traversal +/// Time Complexity: O(n) +/// Space Complexity: O(h) where h is the height of the BST +class Solution { + +private: + int index; + +public: + int kthSmallest(TreeNode* root, int k) { + index = 0; + return kthSmallestNode(root, k)->val; + } + +private: + TreeNode* kthSmallestNode(TreeNode* node, int k){ + + if(node == NULL) + return NULL; + + TreeNode* res = kthSmallestNode(node->left, k); + if(res) return res; + + index ++; + if(index == k) + return node; + + return kthSmallestNode(node->right, k); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0231-Power-of-Two/cpp-0231/CMakeLists.txt b/0001-0500/0231-Power-of-Two/cpp-0231/CMakeLists.txt new file mode 100644 index 00000000..b51ed654 --- /dev/null +++ b/0001-0500/0231-Power-of-Two/cpp-0231/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_0231) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0231 main.cpp) \ No newline at end of file diff --git a/0001-0500/0231-Power-of-Two/cpp-0231/main.cpp b/0001-0500/0231-Power-of-Two/cpp-0231/main.cpp new file mode 100644 index 00000000..0139228b --- /dev/null +++ b/0001-0500/0231-Power-of-Two/cpp-0231/main.cpp @@ -0,0 +1,27 @@ +/// Source : https://leetcode.com/problems/power-of-two/ +/// Author : liuyubobobo +/// Time : 2021-04-21 + +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(logn) +/// Space Complexity: O(1) +class Solution { +public: + bool isPowerOfTwo(int n) { + + if(n <= 0) return false; + while(n % 2 == 0) n /= 2; + return n == 1; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0232-Implement-Queue-using-Stacks/cpp-0232/CMakeLists.txt b/0001-0500/0232-Implement-Queue-using-Stacks/cpp-0232/CMakeLists.txt new file mode 100644 index 00000000..89bdafa3 --- /dev/null +++ b/0001-0500/0232-Implement-Queue-using-Stacks/cpp-0232/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0232) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main3.cpp) +add_executable(cpp_0232 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0232-Implement-Queue-using-Stacks/cpp-0232/main.cpp b/0001-0500/0232-Implement-Queue-using-Stacks/cpp-0232/main.cpp new file mode 100644 index 00000000..90ca5992 --- /dev/null +++ b/0001-0500/0232-Implement-Queue-using-Stacks/cpp-0232/main.cpp @@ -0,0 +1,66 @@ +/// Source : https://leetcode.com/problems/implement-queue-using-stacks/description/ +/// Author : liuyubobobo +/// Time : 2018-09-14 + +#include +#include + +using namespace std; + +/// Two Stacks +/// The Queue front is the top of Stack +/// +/// Time Complexity: push: O(n) +/// pop: O(1) +/// peek: O(1) +/// empty: O(1) +/// +/// Space Complexity: O(n) +class MyQueue { + +private: + stack s; + +public: + /** Initialize your data structure here. */ + MyQueue() {} + + /** Push element x to the back of queue. */ + void push(int x) { + stack s2; + while(!s.empty()){ + s2.push(s.top()); + s.pop(); + } + s.push(x); + while(!s2.empty()){ + s.push(s2.top()); + s2.pop(); + } + } + + /** Removes the element from in front of queue and returns that element. */ + int pop() { + + int ret = s.top(); + s.pop(); + + return ret; + } + + /** Get the front element. */ + int peek() { + return s.top(); + } + + /** Returns whether the queue is empty. */ + bool empty() { + return s.empty(); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0232-Implement-Queue-using-Stacks/cpp-0232/main2.cpp b/0001-0500/0232-Implement-Queue-using-Stacks/cpp-0232/main2.cpp new file mode 100644 index 00000000..bbc0144d --- /dev/null +++ b/0001-0500/0232-Implement-Queue-using-Stacks/cpp-0232/main2.cpp @@ -0,0 +1,81 @@ +/// Source : https://leetcode.com/problems/implement-queue-using-stacks/description/ +/// Author : liuyubobobo +/// Time : 2018-05-14 + +#include +#include + +using namespace std; + +/// Two Stacks +/// The Queue tail is the top of Stack +/// +/// Time Complexity: push: O(1) +/// pop: O(n) +/// peek: O(n) +/// empty: O(1) +/// +/// Space Complexity: O(n) +class MyQueue { + +private: + stack s; + +public: + /** Initialize your data structure here. */ + MyQueue() {} + + /** Push element x to the back of queue. */ + void push(int x) { + s.push(x); + } + + /** Removes the element from in front of queue and returns that element. */ + int pop() { + + stack s2; + while(!s.empty()){ + s2.push(s.top()); + s.pop(); + } + + int ret = s2.top(); + s2.pop(); + + while(!s2.empty()){ + s.push(s2.top()); + s2.pop(); + } + + return ret; + } + + /** Get the front element. */ + int peek() { + stack s2; + while(!s.empty()){ + s2.push(s.top()); + s.pop(); + } + + int ret = s2.top(); + + while(!s2.empty()){ + s.push(s2.top()); + s2.pop(); + } + + return ret; + } + + /** Returns whether the queue is empty. */ + bool empty() { + return s.empty(); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0232-Implement-Queue-using-Stacks/cpp-0232/main3.cpp b/0001-0500/0232-Implement-Queue-using-Stacks/cpp-0232/main3.cpp new file mode 100644 index 00000000..c585830a --- /dev/null +++ b/0001-0500/0232-Implement-Queue-using-Stacks/cpp-0232/main3.cpp @@ -0,0 +1,67 @@ +/// Source : https://leetcode.com/problems/implement-queue-using-stacks/description/ +/// Author : liuyubobobo +/// Time : 2018-09-14 + +#include +#include + +using namespace std; + +/// Two Stacks +/// All the elements store in the two stacks all together +/// +/// Time Complexity: push: O(1) +/// pop: O(1) in average +/// peek: O(1) +/// empty: O(1) +/// +/// Space Complexity: O(n) +class MyQueue { + +private: + stack s1, s2; + int front; + +public: + /** Initialize your data structure here. */ + MyQueue() {} + + /** Push element x to the back of queue. */ + void push(int x) { + if(s1.empty()) + front = x; + s1.push(x); + } + + /** Removes the element from in front of queue and returns that element. */ + int pop() { + + if(s2.empty()){ + while(!s1.empty()){ + s2.push(s1.top()); + s1.pop(); + } + } + int ret = s2.top(); + s2.pop(); + return ret; + } + + /** Get the front element. */ + int peek() { + if(!s2.empty()) + return s2.top(); + return front; + } + + /** Returns whether the queue is empty. */ + bool empty() { + return s1.empty() && s2.empty(); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0233-Number-of-Digit-One/cpp-0233/CMakeLists.txt b/0001-0500/0233-Number-of-Digit-One/cpp-0233/CMakeLists.txt new file mode 100644 index 00000000..839a5856 --- /dev/null +++ b/0001-0500/0233-Number-of-Digit-One/cpp-0233/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(cpp_0233) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0233 main.cpp) \ No newline at end of file diff --git a/0001-0500/0233-Number-of-Digit-One/cpp-0233/main.cpp b/0001-0500/0233-Number-of-Digit-One/cpp-0233/main.cpp new file mode 100644 index 00000000..9e6bc0e4 --- /dev/null +++ b/0001-0500/0233-Number-of-Digit-One/cpp-0233/main.cpp @@ -0,0 +1,63 @@ +#include +#include +#include + +using namespace std; + + +/// Digit DP +/// Time Complexity: O(logn) +/// Space Complexity: O(logn) +class Solution { +public: + int countDigitOne(int n) { + + if(!n) return 0; + + vector digits = get_digits(n); + vector> dp(digits.size(), vector(2, -1)); + return dfs(0, 1, digits, dp); + } + +private: + int dfs(int index, int limit, + const vector& digits, vector>& dp){ + + if(index == digits.size()) return 0; + if(dp[index][limit] != -1) return dp[index][limit]; + + int bound = limit ? digits[index] : 9; + int res = 0; + for(int i = 0; i <= bound; i ++){ + res += dfs(index + 1, limit && i == bound, digits, dp); + if(i == 1) res += i == bound ? get_num(digits, index + 1) + 1 : pow(10, digits.size() - index - 1); + } + return dp[index][limit] = res; + } + + int get_num(const vector& digits, int start){ + int res = 0; + for(int i = start; i < digits.size(); i ++) + res = res * 10 + digits[i]; + return res; + } + + vector get_digits(int x){ + vector res; + while(x) res.push_back(x % 10), x /= 10; + reverse(res.begin(), res.end()); + return res; + } +}; + + +int main() { + + cout << Solution().countDigitOne(13) << endl; + // 6 + + cout << Solution().countDigitOne(100) << endl; + // 21 + + return 0; +} diff --git a/0001-0500/0234-Palindrome-Linked-List/cpp-0234/CMakeLists.txt b/0001-0500/0234-Palindrome-Linked-List/cpp-0234/CMakeLists.txt new file mode 100644 index 00000000..8c5e4e38 --- /dev/null +++ b/0001-0500/0234-Palindrome-Linked-List/cpp-0234/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0234) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0234 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0234-Palindrome-Linked-List/cpp-0234/main.cpp b/0001-0500/0234-Palindrome-Linked-List/cpp-0234/main.cpp new file mode 100644 index 00000000..2730b1d1 --- /dev/null +++ b/0001-0500/0234-Palindrome-Linked-List/cpp-0234/main.cpp @@ -0,0 +1,75 @@ +/// Source : https://leetcode.com/problems/palindrome-linked-list/description/ +/// Author : liuyubobobo +/// Time : 2018-05-10 + +#include + +using namespace std; + +/// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} +}; + +/// Two Pointers to Reverse and Traverse +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + bool isPalindrome(ListNode* head) { + + if(head == NULL || head->next == NULL) + return true; + + ListNode* slow = head; + ListNode* fast = head; + while(fast->next != NULL && fast->next->next != NULL){ + slow = slow->next; + fast = fast->next->next; + } + + slow->next = reverse(slow->next); + + slow = slow->next; + ListNode* cur = head; + while(slow != NULL){ + if(cur->val != slow->val) + return false; + else{ + slow = slow->next; + cur = cur->next; + } + } + return true; + } + +private: + ListNode* reverse(ListNode* head){ + + if(head == NULL || head->next == NULL) + return head; + + ListNode* pre = head; + ListNode* cur = head->next; + ListNode* next = cur->next; + head->next = NULL; + + while(true){ + cur->next = pre; + pre = cur; + cur = next; + if(cur == NULL) + break; + next = cur->next; + } + + return pre; + } +}; + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree/cpp-0235/CMakeLists.txt b/0001-0500/0235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree/cpp-0235/CMakeLists.txt similarity index 100% rename from 0235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree/cpp-0235/CMakeLists.txt rename to 0001-0500/0235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree/cpp-0235/CMakeLists.txt diff --git a/0001-0500/0235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree/cpp-0235/main.cpp b/0001-0500/0235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree/cpp-0235/main.cpp new file mode 100644 index 00000000..d58b0477 --- /dev/null +++ b/0001-0500/0235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree/cpp-0235/main.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/description/ +/// Author : liuyubobobo +/// Time : 2017-11-18 + +#include +#include + +using namespace std; + + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + + +/// Recursive +/// Time Complexity: O(lgn), where n is the node's number of the tree +/// Space Complexity: O(h), where h is the height of the tree +class Solution { +public: + TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { + + assert(!p && !q); + + if(!root) return root; + + if(p->val < root->val && q->val < root->val) + return lowestCommonAncestor(root->left, p, q); + if(p->val > root->val && q->val > root->val) + return lowestCommonAncestor(root->right, p, q); + + assert(p->val == root->val || q->val == root->val + || (root->val - p->val) * (root->val - q->val) < 0); + + return root; + } +}; + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree/cpp-0235/main2.cpp b/0001-0500/0235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree/cpp-0235/main2.cpp new file mode 100644 index 00000000..2ef6e9b3 --- /dev/null +++ b/0001-0500/0235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree/cpp-0235/main2.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/description/ +/// Author : liuyubobobo +/// Time : 2018-12-16 + +#include +#include + +using namespace std; + + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + + +/// Non-Recursive +/// Time Complexity: O(lgn), where n is the node's number of the tree +/// Space Complexity: O(1) +class Solution { +public: + TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { + + if(!root) return root; + + TreeNode* cur = root; + while(cur) { + if (p->val < cur->val && q->val < cur->val) + cur = cur->left; + else if (p->val > cur->val && q->val > cur->val) + cur = cur->right; + else + return cur; + } + + return NULL; + } +}; + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree/java-0235/src/Solution.java b/0001-0500/0235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree/java-0235/src/Solution.java new file mode 100644 index 00000000..4578173c --- /dev/null +++ b/0001-0500/0235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree/java-0235/src/Solution.java @@ -0,0 +1,28 @@ +/// Source : https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/description/ +/// Author : liuyubobobo +/// Time : 2017-11-18 + +/// Recursive +/// Time Complexity: O(lgn), where n is the node's number of the tree +/// Space Complexity: O(h), where h is the height of the tree +class Solution { + + public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { + + if(p == null || q == null) + throw new IllegalArgumentException("p or q can not be null."); + + if(root == null) + return null; + + if(p.val < root.val && q.val < root.val) + return lowestCommonAncestor(root.left, p, q); + if(p.val > root.val && q.val > root.val) + return lowestCommonAncestor(root.right, p, q); + + assert p.val == root.val || q.val == root.val + || (root.val - p.val) * (root.val - q.val) < 0; + + return root; + } +} diff --git a/0001-0500/0235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree/java-0235/src/Solution2.java b/0001-0500/0235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree/java-0235/src/Solution2.java new file mode 100644 index 00000000..d8e7a418 --- /dev/null +++ b/0001-0500/0235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree/java-0235/src/Solution2.java @@ -0,0 +1,26 @@ +/// Source : https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/description/ +/// Author : liuyubobobo +/// Time : 2018-12-16 + +/// Non-Recursive +/// Time Complexity: O(lgn), where n is the node's number of the tree +/// Space Complexity: O(1) +class Solution2 { + + public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { + + if(root == null) + return root; + + TreeNode cur = root; + while(cur != null){ + if(p.val < cur.val && q.val < cur.val) + cur = cur.left; + else if(p.val > cur.val && q.val > cur.val) + cur = cur.right; + else + return cur; + } + return null; + } +} diff --git a/0001-0500/0235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree/java-0235/src/TreeNode.java b/0001-0500/0235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree/java-0235/src/TreeNode.java new file mode 100644 index 00000000..8f0dd22f --- /dev/null +++ b/0001-0500/0235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree/java-0235/src/TreeNode.java @@ -0,0 +1,7 @@ +// Definition for a binary tree node. +class TreeNode { + int val; + TreeNode left; + TreeNode right; + TreeNode(int x) { val = x; } +} \ No newline at end of file diff --git a/0001-0500/0236-Lowest-Common-Ancestor-of-a-Binary-Tree/cpp-0236/CMakeLists.txt b/0001-0500/0236-Lowest-Common-Ancestor-of-a-Binary-Tree/cpp-0236/CMakeLists.txt new file mode 100644 index 00000000..f11fc977 --- /dev/null +++ b/0001-0500/0236-Lowest-Common-Ancestor-of-a-Binary-Tree/cpp-0236/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_Lowest_Common_Ancestor_of_a_Binary_Tree) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main4.cpp) +add_executable(cpp_Lowest_Common_Ancestor_of_a_Binary_Tree ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0236-Lowest-Common-Ancestor-of-a-Binary-Tree/cpp-0236/main.cpp b/0001-0500/0236-Lowest-Common-Ancestor-of-a-Binary-Tree/cpp-0236/main.cpp new file mode 100644 index 00000000..83a2fdbc --- /dev/null +++ b/0001-0500/0236-Lowest-Common-Ancestor-of-a-Binary-Tree/cpp-0236/main.cpp @@ -0,0 +1,59 @@ +/// Source : https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/description/ +/// Author : liuyubobobo +/// Time : 2020-04-22 + +#include +#include + +using namespace std; + +/// Find two paths +/// Time Complexity: O(3n) +/// Space Complexity: O(2n) + +///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) { + + vector path1; + dfs(root, p, path1); + + vector path2; + dfs(root, q, path2); + + TreeNode* res; + for(int i = 0; i < path1.size() && i < path2.size(); i ++) + if(path1[i] == path2[i]) res = path1[i]; + else break; + return res; + } + +private: + bool dfs(TreeNode* node, TreeNode* target, vector& path){ + + if(!node) return false; + + path.push_back(node); + if(node == target) return true; + + if(dfs(node->left, target, path)) return true; + if(dfs(node->right, target, path)) return true; + + path.pop_back(); + return false; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0236-Lowest-Common-Ancestor-of-a-Binary-Tree/cpp-0236/main2.cpp b/0001-0500/0236-Lowest-Common-Ancestor-of-a-Binary-Tree/cpp-0236/main2.cpp new file mode 100644 index 00000000..eebec561 --- /dev/null +++ b/0001-0500/0236-Lowest-Common-Ancestor-of-a-Binary-Tree/cpp-0236/main2.cpp @@ -0,0 +1,56 @@ +/// Source : https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/description/ +/// Author : liuyubobobo +/// Time : 2017-01-30 + +#include +#include + +using namespace std; + +/// Recursion implementation +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +///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: + // 在root中寻找p和q + // 如果p和q都在root所在的二叉树中, 则返回LCA + // 如果p和q只有一个在root所在的二叉树中, 则返回p或者q + // 如果p和q均不在root所在的二叉树中, 则返回NULL + TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { + + if(root == NULL) + return root; + + if(root == p || root == q) + return root; + + TreeNode *left = lowestCommonAncestor(root->left, p, q); + TreeNode *right = lowestCommonAncestor(root->right, p, q); + + if(left != NULL && right != NULL) + return root; + + if(left != NULL) + return left; + + if(right != NULL) + return right; + + return NULL; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0236-Lowest-Common-Ancestor-of-a-Binary-Tree/cpp-0236/main3.cpp b/0001-0500/0236-Lowest-Common-Ancestor-of-a-Binary-Tree/cpp-0236/main3.cpp new file mode 100644 index 00000000..605d61bd --- /dev/null +++ b/0001-0500/0236-Lowest-Common-Ancestor-of-a-Binary-Tree/cpp-0236/main3.cpp @@ -0,0 +1,64 @@ +/// Source : https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/description/ +/// Author : liuyubobobo +/// Time : 2018-11-17 + +#include +#include + +using namespace std; + +/// Another Recursion implementation +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +///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 { + +private: + TreeNode* ret = 0; + +public: + TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { + dfs(root, p, q); + assert(ret); + return ret; + } + +private: + // 在root中寻找p和q, 如果包含则返回 true + // 否则返回false + // + // root是p或者q;root的左子树包含p或q;root的右子树包含p或q;三个条件有两个满足 + // 则 ret = root + bool dfs(TreeNode* root, TreeNode* p, TreeNode* q) { + + if(!root) + return false; + + bool mid = false; + if(root == p || root == q) + mid = true; + + bool left = dfs(root->left, p, q); + bool right = dfs(root->right, p, q); + + if(mid + left + right >= 2) + ret = root; + + return mid + left + right; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0236-Lowest-Common-Ancestor-of-a-Binary-Tree/cpp-0236/main4.cpp b/0001-0500/0236-Lowest-Common-Ancestor-of-a-Binary-Tree/cpp-0236/main4.cpp new file mode 100644 index 00000000..b99a82f9 --- /dev/null +++ b/0001-0500/0236-Lowest-Common-Ancestor-of-a-Binary-Tree/cpp-0236/main4.cpp @@ -0,0 +1,92 @@ +/// Source : https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/description/ +/// Author : liuyubobobo +/// Time : 2020-04-22 + +#include +#include +#include +#include + +using namespace std; + +/// Binary Lifting +/// Time Complexity: init: O(nlogn) +/// query: O(logn) +/// Space Complexity: O(nlogn) + +///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 { + +private: + map tin, tout; + map parents; + vector nodes; + map> up; + +public: + TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { + + int time = 0; + + int depth = dfs(root, root, time); + + if(isAncestor(p, q)) return p; + if(isAncestor(q, p)) return q; + + // up + for(TreeNode* node: nodes) + up[node].push_back(parents[node]); + + int d = ceil(log2(depth)); + for(int i = 1; i <= d; i ++) + for(TreeNode* node: nodes) + up[node].push_back(up[up[node][i - 1]][i - 1]); + + // lca + for(int i = d; i >= 0; i --) + if(!isAncestor(up[p][i], q)) + p = up[p][i]; + return up[p][0]; + } + +private: + // a is x's ancestor? + bool isAncestor(TreeNode* a, TreeNode* x){ + return tin[a] <= tin[x] && tout[a] >= tout[x]; + } + + int dfs(TreeNode* node, TreeNode* p, int& time){ + + if(!node) return 0; + + nodes.push_back(node); + parents[node] = p; + + int depth = 0; + + tin[node] = time ++; + depth = max(depth, 1 + dfs(node->left, node, time)); + depth = max(depth, 1 + dfs(node->right, node, time)); + tout[node] = time ++; + + return depth; + } +}; + + +int main() { + +// [-1,0,3,-2,4,null,null,8] +// 8 +// 4 +// Expected: 0 + + return 0; +} \ No newline at end of file diff --git a/0237-Delete-Node-in-a-Linked-List/cpp-0237/CMakeLists.txt b/0001-0500/0237-Delete-Node-in-a-Linked-List/cpp-0237/CMakeLists.txt similarity index 100% rename from 0237-Delete-Node-in-a-Linked-List/cpp-0237/CMakeLists.txt rename to 0001-0500/0237-Delete-Node-in-a-Linked-List/cpp-0237/CMakeLists.txt diff --git a/0237-Delete-Node-in-a-Linked-List/cpp-0237/main.cpp b/0001-0500/0237-Delete-Node-in-a-Linked-List/cpp-0237/main.cpp similarity index 100% rename from 0237-Delete-Node-in-a-Linked-List/cpp-0237/main.cpp rename to 0001-0500/0237-Delete-Node-in-a-Linked-List/cpp-0237/main.cpp diff --git a/0237-Delete-Node-in-a-Linked-List/java-0237/src/ListNode.java b/0001-0500/0237-Delete-Node-in-a-Linked-List/java-0237/src/ListNode.java similarity index 100% rename from 0237-Delete-Node-in-a-Linked-List/java-0237/src/ListNode.java rename to 0001-0500/0237-Delete-Node-in-a-Linked-List/java-0237/src/ListNode.java diff --git a/0237-Delete-Node-in-a-Linked-List/java-0237/src/Solution.java b/0001-0500/0237-Delete-Node-in-a-Linked-List/java-0237/src/Solution.java similarity index 100% rename from 0237-Delete-Node-in-a-Linked-List/java-0237/src/Solution.java rename to 0001-0500/0237-Delete-Node-in-a-Linked-List/java-0237/src/Solution.java diff --git a/0001-0500/0238-Product-of-Array-Except-Self/cpp-0238/CMakeLists.txt b/0001-0500/0238-Product-of-Array-Except-Self/cpp-0238/CMakeLists.txt new file mode 100644 index 00000000..3efcc2cd --- /dev/null +++ b/0001-0500/0238-Product-of-Array-Except-Self/cpp-0238/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0238) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0238 main.cpp) diff --git a/0001-0500/0238-Product-of-Array-Except-Self/cpp-0238/main.cpp b/0001-0500/0238-Product-of-Array-Except-Self/cpp-0238/main.cpp new file mode 100644 index 00000000..1311668e --- /dev/null +++ b/0001-0500/0238-Product-of-Array-Except-Self/cpp-0238/main.cpp @@ -0,0 +1,38 @@ +/// Source : https://leetcode.com/problems/product-of-array-except-self/ +/// Author : liuyubobobo +/// Time : 2021-11-27 + +#include +#include + +using namespace std; + + +/// Pre + Suf +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector productExceptSelf(vector& nums) { + + int n = nums.size(); + + vector pre(n, nums[0]); + for(int i = 1; i < n; i ++) pre[i] = pre[i - 1] * nums[i]; + + vector suf(n, nums.back()); + for(int i = n - 2; i >= 0; i --) suf[i] = suf[i + 1] * nums[i]; + + vector res(n); + res[0] = suf[1]; res[n - 1] = pre[n - 2]; + for(int i = 1; i + 1 < n; i ++) + res[i] = pre[i - 1] * suf[i + 1]; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0238-Product-of-Array-Except-Self/py-0238/Solution.py b/0001-0500/0238-Product-of-Array-Except-Self/py-0238/Solution.py new file mode 100644 index 00000000..3ce6698d --- /dev/null +++ b/0001-0500/0238-Product-of-Array-Except-Self/py-0238/Solution.py @@ -0,0 +1,26 @@ +# Source : https://leetcode.com/problems/product-of-array-except-self/ +# Author : penpenps +# Time : 2019-08-01 + +from typing import List + +# For i-th element, the product except itself equals product of 0 to i-1 and i+1 element to the end +# We can get left and right accumlate product for each index by traversaling from 0 to the end and reverse once again +# Time Complexity: O(n) +# Space Complexity: O(n) + +class Solution: + def productExceptSelf(self, nums: List[int]) -> List[int]: + left, right = [_ for _ in nums], [_ for _ in nums] + n = len(nums) + for i in range(1, n): + left[i] *= left[i-1] + for i in range(n-2, -1, -1): + right[i] *= right[i+1] + + ans = [0]*n + for i in range(n): + left_part = left[i-1] if i > 0 else 1 + right_part = right[i+1] if i < n-1 else 1 + ans[i] = left_part * right_part + return ans diff --git a/0001-0500/0238-Product-of-Array-Except-Self/py-0238/Solution2.py b/0001-0500/0238-Product-of-Array-Except-Self/py-0238/Solution2.py new file mode 100644 index 00000000..50303504 --- /dev/null +++ b/0001-0500/0238-Product-of-Array-Except-Self/py-0238/Solution2.py @@ -0,0 +1,21 @@ +# Source : https://leetcode.com/problems/product-of-array-except-self/ +# Author : penpenps +# Time : 2019-08-01 + +from typing import List + +# Construct answer the same way we build left part array like solution #1 and then reversly multiple one by one to get the corresponding right part product value +# Time Complexity: O(n) +# Space Complexity: O(1) + +class Solution: + def productExceptSelf(self, nums: List[int]) -> List[int]: + n = len(nums) + ans = [1]*n + for i in range(1, n): + ans[i] = ans[i-1]*nums[i-1] + R = 1 + for i in range(n-1, -1, -1): + ans[i] = ans[i]*R + R *= nums[i] + return ans \ No newline at end of file diff --git a/0001-0500/0239-Sliding-Window-Maximum/cpp-0239/CMakeLists.txt b/0001-0500/0239-Sliding-Window-Maximum/cpp-0239/CMakeLists.txt new file mode 100644 index 00000000..dba1744c --- /dev/null +++ b/0001-0500/0239-Sliding-Window-Maximum/cpp-0239/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(0239_Sliding_Window_Maximum) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(0239_Sliding_Window_Maximum main2.cpp) \ No newline at end of file diff --git a/0001-0500/0239-Sliding-Window-Maximum/cpp-0239/main.cpp b/0001-0500/0239-Sliding-Window-Maximum/cpp-0239/main.cpp new file mode 100644 index 00000000..d31d68a9 --- /dev/null +++ b/0001-0500/0239-Sliding-Window-Maximum/cpp-0239/main.cpp @@ -0,0 +1,227 @@ +/// Source : https://leetcode.com/problems/sliding-window-maximum/description/ +/// Author : liuyubobobo +/// Time : 2017-11-22 + +#include +#include +#include +#include + +using namespace std; + + +/// Using Index Max Heap +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) + +// 最大索引堆 +template +class IndexMaxHeap{ + +private: + Item *data; // 最大索引堆中的数据 + int *indexes; // 最大索引堆中的索引, indexes[x] = i 表示索引i在x的位置 + int *reverse; // 最大索引堆中的反向索引, reverse[i] = x 表示索引i在x的位置 + + int count; + int capacity; + + // 索引堆中, 数据之间的比较根据data的大小进行比较, 但实际操作的是索引 + void shiftUp( int k ){ + + while( k > 1 && data[indexes[k/2]] < data[indexes[k]] ){ + swap( indexes[k/2] , indexes[k] ); + reverse[indexes[k/2]] = k/2; + reverse[indexes[k]] = k; + k /= 2; + } + } + + // 索引堆中, 数据之间的比较根据data的大小进行比较, 但实际操作的是索引 + void shiftDown( int k ){ + + while( 2*k <= count ){ + int j = 2*k; + if( j + 1 <= count && data[indexes[j+1]] > data[indexes[j]] ) + j += 1; + + if( data[indexes[k]] >= data[indexes[j]] ) + break; + + swap( indexes[k] , indexes[j] ); + reverse[indexes[k]] = k; + reverse[indexes[j]] = j; + k = j; + } + } + +public: + // 构造函数, 构造一个空的索引堆, 可容纳capacity个元素 + IndexMaxHeap(int capacity){ + + data = new Item[capacity+1]; + indexes = new int[capacity+1]; + reverse = new int[capacity+1]; + for( int i = 0 ; i <= capacity ; i ++ ) + reverse[i] = 0; + + count = 0; + this->capacity = capacity; + } + + ~IndexMaxHeap(){ + delete[] data; + delete[] indexes; + delete[] reverse; + } + + // 返回索引堆中的元素个数 + int size(){ + return count; + } + + // 返回一个布尔值, 表示索引堆中是否为空 + bool isEmpty(){ + return count == 0; + } + + // 向最大索引堆中插入一个新的元素, 新元素的索引为i, 元素为item + // 传入的i对用户而言,是从0索引的 + void insert(int i, Item item){ + assert( count + 1 <= capacity ); + assert( i + 1 >= 1 && i + 1 <= capacity ); + + // 再插入一个新元素前,还需要保证索引i所在的位置是没有元素的。 + assert( !contain(i) ); + + i += 1; + data[i] = item; + indexes[count+1] = i; + reverse[i] = count+1; + count++; + + shiftUp(count); + } + + // 从最大索引堆中取出堆顶元素, 即索引堆中所存储的最大数据 + Item extractMax(){ + assert( count > 0 ); + + Item ret = data[indexes[1]]; + swap( indexes[1] , indexes[count] ); + reverse[indexes[count]] = 0; + reverse[indexes[1]] = 1; + count--; + shiftDown(1); + return ret; + } + + // 从最大索引堆中取出堆顶元素的索引 + int extractMaxIndex(){ + assert( count > 0 ); + + int ret = indexes[1] - 1; + swap( indexes[1] , indexes[count] ); + reverse[indexes[count]] = 0; + reverse[indexes[1]] = 1; + count--; + shiftDown(1); + return ret; + } + + // 获取最大索引堆中的堆顶元素 + Item getMax(){ + assert( count > 0 ); + return data[indexes[1]]; + } + + // 获取最大索引堆中的堆顶元素的索引 + int getMaxIndex(){ + assert( count > 0 ); + return indexes[1]-1; + } + + // 看索引i所在的位置是否存在元素 + bool contain( int i ){ + assert( i + 1 >= 1 && i + 1 <= capacity ); + return reverse[i+1] != 0; + } + + // 获取最大索引堆中索引为i的元素 + Item getItem( int i ){ + assert( contain(i) ); + return data[i+1]; + } + + // 将最大索引堆中索引为i的元素修改为newItem + void change( int i , Item newItem ){ + + assert( contain(i) ); + i += 1; + data[i] = newItem; + + shiftUp( reverse[i] ); + shiftDown( reverse[i] ); + } + + void remove(int i){ + + change(i, INT_MIN); + + i += 1; + + int pos = reverse[i]; + swap( indexes[pos] , indexes[count] ); + reverse[indexes[count]] = count; + reverse[indexes[pos]] = pos; + + shiftDown( pos ); + shiftUp( pos ); + + assert(reverse[i] == count); + reverse[i] = 0; + count--; + } +}; + + +class Solution { +public: + vector maxSlidingWindow(vector& nums, int k) { + + if(k == 0 || nums.size() == 0) + return vector(); + + if(k == 1) + return nums; + + IndexMaxHeap ipq(nums.size()); + for(int i = 0 ; i < k - 1 ; i ++) + ipq.insert(i, nums[i]); + + vector res; + for(int i = k - 1 ; i < nums.size() ; i ++){ + ipq.insert(i, nums[i]); + res.push_back(ipq.getMax()); + + assert(ipq.size() == k); + ipq.remove(i - (k - 1)); + } + + return res; + } +}; + + +void print_vec(const vector& vec){ + for(int e: vec) cout << e << " "; cout << endl; +} + +int main() { + + vector nums = {1, 3, -1, -3, 5, 3, 6, 7}; + print_vec(Solution().maxSlidingWindow(nums, 3)); + // 3 3 5 5 6 7 + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0239-Sliding-Window-Maximum/cpp-0239/main2.cpp b/0001-0500/0239-Sliding-Window-Maximum/cpp-0239/main2.cpp new file mode 100644 index 00000000..bff64a95 --- /dev/null +++ b/0001-0500/0239-Sliding-Window-Maximum/cpp-0239/main2.cpp @@ -0,0 +1,90 @@ +/// Source : https://leetcode.com/problems/sliding-window-maximum/description/ +/// Author : liuyubobobo +/// Time : 2020-04-27 + +#include +#include +#include +#include + +using namespace std; + + +/// Using Segment Tree +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class SegmentTree{ + +private: + int n; + vector data, tree; + +public: + SegmentTree(const vector& initData): data(initData), n(initData.size()), tree(4 * n){ + buildSegTree(0, 0, n - 1); + } + + int query(int qL, int qR){ + return query(0, 0, n-1, qL, qR); + } + +private: + void buildSegTree(int treeID, int l, int r){ + + if(l == r){ + tree[treeID] = data[l]; + return; + } + + int mid = (l + r) / 2; + buildSegTree(treeID * 2 + 1, l, mid); + buildSegTree(treeID * 2 + 2, mid + 1, r); + tree[treeID] = max(tree[treeID * 2 + 1], tree[treeID * 2 + 2]); + return; + } + + int query(int treeID, int treeL, int treeR, int qL, int qR){ + + if(treeL > qR || treeR < qL) return 0; + + if(qL <= treeL && qR >= treeR) + return tree[treeID]; + + int mid = (treeL + treeR) / 2; + int leftRes = query(2 * treeID + 1, treeL, mid, qL, qR); + int rightRes = query(2 * treeID + 2, mid + 1, treeR, qL, qR); + return max(leftRes, rightRes); + } +}; + +class Solution { +public: + vector maxSlidingWindow(vector& nums, int k) { + + if(k == 0 || nums.size() == 0) + return vector(); + + if(k == 1) return nums; + + SegmentTree segmentTree(nums); + vector res; + for(int i = k - 1 ; i < nums.size() ; i ++) + res.push_back(segmentTree.query(i - (k - 1), i)); + + return res; + } +}; + + +void print_vec(const vector& vec){ + for(int e: vec) cout << e << " "; cout << endl; +} + +int main() { + + vector nums = {1, 3, -1, -3, 5, 3, 6, 7}; + print_vec(Solution().maxSlidingWindow(nums, 3)); + // 3 3 5 5 6 7 + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0239-Sliding-Window-Maximum/cpp-0239/main3.cpp b/0001-0500/0239-Sliding-Window-Maximum/cpp-0239/main3.cpp new file mode 100644 index 00000000..6fd9f2f9 --- /dev/null +++ b/0001-0500/0239-Sliding-Window-Maximum/cpp-0239/main3.cpp @@ -0,0 +1,55 @@ +/// Source : https://leetcode.com/problems/sliding-window-maximum/description/ +/// Author : liuyubobobo +/// Time : 2020-04-27 + +#include +#include +#include +#include + +using namespace std; + + +/// Using a map as a priority queue +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + vector maxSlidingWindow(vector& nums, int k) { + + if(k == 0 || nums.size() == 0) + return vector(); + + if(k == 1) return nums; + + map window; + for(int i = 0; i < k - 1; i ++) + window[nums[i]] ++; + + vector res; + for(int i = k - 1 ; i < nums.size() ; i ++){ + + window[nums[i]] ++; + res.push_back(window.rbegin()->first); + + window[nums[i - k + 1]] --; + if(window[nums[i - k + 1]] == 0) window.erase(nums[i - k + 1]); + } + + return res; + } +}; + + +void print_vec(const vector& vec){ + for(int e: vec) cout << e << " "; cout << endl; +} + +int main() { + + vector nums = {1, 3, -1, -3, 5, 3, 6, 7}; + print_vec(Solution().maxSlidingWindow(nums, 3)); + // 3 3 5 5 6 7 + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0239-Sliding-Window-Maximum/cpp-0239/main4.cpp b/0001-0500/0239-Sliding-Window-Maximum/cpp-0239/main4.cpp new file mode 100644 index 00000000..f45199e5 --- /dev/null +++ b/0001-0500/0239-Sliding-Window-Maximum/cpp-0239/main4.cpp @@ -0,0 +1,58 @@ +/// Source : https://leetcode.com/problems/sliding-window-maximum/description/ +/// Author : liuyubobobo +/// Time : 2017-11-22 + +#include +#include +#include +#include + +using namespace std; + + +/// Using Deque as a Decreasing Queue +/// It's a template problem! :) +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector maxSlidingWindow(vector& nums, int k) { + + if(k == 0 || nums.size() == 0) + return vector(); + + if(k == 1) + return nums; + + deque q; + vector res; + for(int i = 0 ; i < nums.size() ; i ++){ + + while(!q.empty() && q.back() < nums[i]) + q.pop_back(); + q.push_back(nums[i]); + + if(i >= k - 1){ + res.push_back(q.front()); + if(q.front() == nums[i - (k - 1)]) + q.pop_front(); + } + } + + return res; + } +}; + + +void print_vec(const vector& vec){ + for(int e: vec) cout << e << " "; cout << endl; +} + +int main() { + + vector nums = {1, 3, -1, -3, 5, 3, 6, 7}; + print_vec(Solution().maxSlidingWindow(nums, 3)); + // 3 3 5 5 6 7 + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0239-Sliding-Window-Maximum/cpp-0239/main5.cpp b/0001-0500/0239-Sliding-Window-Maximum/cpp-0239/main5.cpp new file mode 100644 index 00000000..dd43fa01 --- /dev/null +++ b/0001-0500/0239-Sliding-Window-Maximum/cpp-0239/main5.cpp @@ -0,0 +1,63 @@ +/// Source : https://leetcode.com/problems/sliding-window-maximum/description/ +/// Author : liuyubobobo +/// Time : 2019-03-09 + +#include +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector maxSlidingWindow(vector& nums, int k) { + + int n = nums.size(); + + if(k == 0 || n == 0) + return vector(); + + if(k == 1) + return nums; + + vector right(n); + int cur = nums[0]; + for(int i = 0; i < n; i ++){ + if(i % k == 0) cur = nums[i]; + else cur = max(cur, nums[i]); + right[i] = cur; + } + + vector left(n); + cur = nums[n - 1]; + for(int i = n - 1; i >= 0; i --){ + if(i % k == k - 1) cur = nums[i]; + else cur = max(cur, nums[i]); + left[i] = cur; + } + + vector res(n - k + 1); + for(int i = 0; i <= n - k; i ++) + res[i] = max(left[i], right[min(i + k - 1, n - 1)]); + + return res; + } +}; + + +void print_vec(const vector& vec){ + for(int e: vec) cout << e << " "; cout << endl; +} + +int main() { + + vector nums = {1, 3, -1, -3, 5, 3, 6, 7}; + print_vec(Solution().maxSlidingWindow(nums, 3)); + // 3 3 5 5 6 7 + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0240-Search-a-2D-Matrix-II/cpp-0240/CMakeLists.txt b/0001-0500/0240-Search-a-2D-Matrix-II/cpp-0240/CMakeLists.txt new file mode 100644 index 00000000..4817f607 --- /dev/null +++ b/0001-0500/0240-Search-a-2D-Matrix-II/cpp-0240/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0240) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0240 main.cpp) \ No newline at end of file diff --git a/0001-0500/0240-Search-a-2D-Matrix-II/cpp-0240/main.cpp b/0001-0500/0240-Search-a-2D-Matrix-II/cpp-0240/main.cpp new file mode 100644 index 00000000..9c471ef1 --- /dev/null +++ b/0001-0500/0240-Search-a-2D-Matrix-II/cpp-0240/main.cpp @@ -0,0 +1,68 @@ +/// Source : https://leetcode.com/problems/search-a-2d-matrix-ii/ +/// Author : liuyubobobo +/// Time : 2021-02-23 + +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(min(R, C) * log(min(R, C))) +/// Space Complexity: O(1) +class Solution { + +private: + int R, C; + +public: + bool searchMatrix(vector>& matrix, int target) { + + R = matrix.size(); + if(R == 0) return false; + + C = matrix[0].size(); + if(C == 0) return false; + + for(int i = 0; i < min(R, C); i ++){ + if(binary_search_h(matrix, i, target)) return true; + if(binary_search_v(matrix, i, target)) return true; + } + return false; + } + +private: + bool binary_search_h(vector>& matrix, int start, int target){ + vector::iterator iter = lower_bound(matrix[start].begin() + start, matrix[start].end(), target); + return iter != matrix[start].end() && *iter == target; + } + + bool binary_search_v(vector>& matrix, int start, int target){ + + int l = start, r = R - 1; + while(l <= r){ + int mid = (l + r) / 2; + if(matrix[mid][start] == target) return true; + else if(matrix[mid][start] < target) l = mid + 1; + else r = mid - 1; + } + return false; + } +}; + + +int main() { + + vector> matrix1 ={ + {1,4,7,11,15}, + {2,5,8,12,19}, + {3,6,9,16,22}, + {10,13,14,17,24}, + {18,21,23,26,30} + }; + cout << Solution().searchMatrix(matrix1, 20) << endl; + // 0 + + return 0; +} diff --git a/0001-0500/0241-Different-Ways-to-Add-Parentheses/cpp-0241/CMakeLists.txt b/0001-0500/0241-Different-Ways-to-Add-Parentheses/cpp-0241/CMakeLists.txt new file mode 100644 index 00000000..60cd7605 --- /dev/null +++ b/0001-0500/0241-Different-Ways-to-Add-Parentheses/cpp-0241/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_0241) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0241 main.cpp) diff --git a/0001-0500/0241-Different-Ways-to-Add-Parentheses/cpp-0241/main.cpp b/0001-0500/0241-Different-Ways-to-Add-Parentheses/cpp-0241/main.cpp new file mode 100644 index 00000000..e50a987b --- /dev/null +++ b/0001-0500/0241-Different-Ways-to-Add-Parentheses/cpp-0241/main.cpp @@ -0,0 +1,76 @@ +/// Source : https://leetcode.com/problems/different-ways-to-add-parentheses/ +/// Author : liuyubobobo +/// Time : 2022-06-30 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n!) +/// Space Complexity: O(n) +class Solution { +public: + vector diffWaysToCompute(string exp) { + + vector nums; + vector ops; + for(int start = 0, i = 1; i <= exp.size(); i ++) + if(i == exp.size() || !isdigit(exp[i])){ + nums.push_back(atoi(exp.substr(start, i - start).c_str())); + + if(i < exp.size()) ops.push_back(exp[i]); + + start = i + 1; + i = start; + } + +// for(int e: nums) cout << e << ' '; cout << '\n'; +// for(char op: ops) cout << op << ' '; cout << '\n'; + + vector res = dfs(nums, ops, 0, nums.size() - 1); + return res; + } + +private: + vector dfs(const vector& nums, const vector& ops, int l, int r){ + + if(l == r) return {nums[l]}; + + vector res; + for(int left_end = l; left_end < r; left_end ++){ + vector a = dfs(nums, ops, l, left_end); + vector b = dfs(nums, ops, left_end + 1, r); + + for(int e1: a) + for(int e2: b) + res.push_back(calc(e1, e2, ops[left_end])); + } + return res; + } + + int calc(int a, int b, char op){ + if(op == '+') return a + b; + if(op == '-') return a - b; + if(op == '*') return a * b; + + assert(false); + return -1; + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << ' '; cout << '\n'; +} + +int main() { + + print_vec(Solution().diffWaysToCompute("2-1-1")); + + print_vec(Solution().diffWaysToCompute("2*3-4*5")); + + return 0; +} diff --git a/old/0242 Valid Anagram/cpp-Valid-Anagram/CMakeLists.txt b/0001-0500/0242-Valid-Anagram/cpp-0242/CMakeLists.txt similarity index 100% rename from old/0242 Valid Anagram/cpp-Valid-Anagram/CMakeLists.txt rename to 0001-0500/0242-Valid-Anagram/cpp-0242/CMakeLists.txt diff --git a/0001-0500/0242-Valid-Anagram/cpp-0242/main.cpp b/0001-0500/0242-Valid-Anagram/cpp-0242/main.cpp new file mode 100644 index 00000000..a2f493ef --- /dev/null +++ b/0001-0500/0242-Valid-Anagram/cpp-0242/main.cpp @@ -0,0 +1,31 @@ +/// Source : https://leetcode.com/problems/valid-anagram/ +/// Author : liuyubobobo +/// Time : 2018-08-13 + +#include + +using namespace std; + +/// Sorting +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + bool isAnagram(string s, string t) { + + sort(s.begin(), s.end()); + sort(t.begin(), t.end()); + + return s == t; + } +}; + + +int main() { + + cout << Solution().isAnagram("anagram", "nagaram") << endl; + cout << Solution().isAnagram("rat", "car") << endl; + cout << Solution().isAnagram("ab", "a") << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0242-Valid-Anagram/cpp-0242/main2.cpp b/0001-0500/0242-Valid-Anagram/cpp-0242/main2.cpp new file mode 100644 index 00000000..f77f691b --- /dev/null +++ b/0001-0500/0242-Valid-Anagram/cpp-0242/main2.cpp @@ -0,0 +1,41 @@ +/// Source : https://leetcode.com/problems/valid-anagram/ +/// Author : liuyubobobo +/// Time : 2017-01-17 + +#include + +using namespace std; + +/// Using Hashtable +/// Time Complexity: O(n) +/// Space Complexity: O(26) +class Solution { +public: + bool isAnagram(string s, string t) { + + if( s.size() != t.size() ) + return false; + + int freq[26] = {0}; + for( int i = 0 ; i < s.size() ; i ++ ) + freq[s[i]-'a'] ++; + + for( int i = 0 ; i < t.size() ; i ++ ){ + freq[t[i]-'a'] --; + if( freq[t[i]-'a'] < 0 ) + return false; + } + + return true; + } +}; + + +int main() { + + cout << Solution().isAnagram("anagram", "nagaram") << endl; + cout << Solution().isAnagram("rat", "car") << endl; + cout << Solution().isAnagram("ab", "a") << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0243-Shortest-Word-Distance/cpp-0243/CMakeLists.txt b/0001-0500/0243-Shortest-Word-Distance/cpp-0243/CMakeLists.txt new file mode 100644 index 00000000..a048bd6d --- /dev/null +++ b/0001-0500/0243-Shortest-Word-Distance/cpp-0243/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(cpp_0243) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(cpp_0243 main.cpp) \ No newline at end of file diff --git a/0001-0500/0243-Shortest-Word-Distance/cpp-0243/main.cpp b/0001-0500/0243-Shortest-Word-Distance/cpp-0243/main.cpp new file mode 100644 index 00000000..ac0e4d39 --- /dev/null +++ b/0001-0500/0243-Shortest-Word-Distance/cpp-0243/main.cpp @@ -0,0 +1,39 @@ +/// Source : https://leetcode.com/problems/shortest-word-distance/ +/// Author : liuyubobobo +/// Time : 2019-02-13 + +#include +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(n) +/// Space Compelxity: O(1) +class Solution { +public: + int shortestDistance(vector& words, string word1, string word2) { + + int last_index = -1, last_tag = 0, res = INT_MAX; + for(int i = 0; i < words.size(); i ++){ + int cur_tag = 0; + if(words[i] == word1) cur_tag = 1; + else if(words[i] == word2) cur_tag = 2; + + if(last_tag && cur_tag && cur_tag != last_tag) + res = min(res, i - last_index); + + if(cur_tag) + last_index = i, last_tag = cur_tag; + } + + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0244-Shortest-Word-Distance-II/cpp-0244/CMakeLists.txt b/0001-0500/0244-Shortest-Word-Distance-II/cpp-0244/CMakeLists.txt new file mode 100644 index 00000000..17ccfba6 --- /dev/null +++ b/0001-0500/0244-Shortest-Word-Distance-II/cpp-0244/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(cpp_0244) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(cpp_0244 main.cpp) \ No newline at end of file diff --git a/0001-0500/0244-Shortest-Word-Distance-II/cpp-0244/main.cpp b/0001-0500/0244-Shortest-Word-Distance-II/cpp-0244/main.cpp new file mode 100644 index 00000000..a6fe58d3 --- /dev/null +++ b/0001-0500/0244-Shortest-Word-Distance-II/cpp-0244/main.cpp @@ -0,0 +1,48 @@ +/// Source : https://leetcode.com/problems/shortest-word-distance-ii/ +/// Author : liuyubobobo +/// Time : 2019-02-13 + +#include +#include +#include + +using namespace std; + + +/// Search in two sorted index array +/// Time Complexity: init: O(n) +/// search: O(n) +/// Space Complexity: O(n) +class WordDistance { + +private: + unordered_map> pos; + +public: + WordDistance(vector words) { + for (int i = 0; i < words.size(); i++) + pos[words[i]].push_back(i); + } + + int shortest(string word1, string word2) { + + vector& vec1 = pos[word1]; + vector& vec2 = pos[word2]; + + int i1 = 0, i2 = 0; + int res = abs(vec1[i1] - vec2[i2]); + while(i1 < vec1.size() && i2 < vec2.size()){ + res = min(res, abs(vec1[i1] - vec2[i2])); + if(vec1[i1] < vec2[i2]) i1 ++; + else i2 ++; + } + + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0245-Shortest-Word-Distance-III/cpp-0245/CMakeLists.txt b/0001-0500/0245-Shortest-Word-Distance-III/cpp-0245/CMakeLists.txt new file mode 100644 index 00000000..18e8509a --- /dev/null +++ b/0001-0500/0245-Shortest-Word-Distance-III/cpp-0245/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(cpp_0245) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(cpp_0245 main.cpp) \ No newline at end of file diff --git a/0001-0500/0245-Shortest-Word-Distance-III/cpp-0245/main.cpp b/0001-0500/0245-Shortest-Word-Distance-III/cpp-0245/main.cpp new file mode 100644 index 00000000..22b6f871 --- /dev/null +++ b/0001-0500/0245-Shortest-Word-Distance-III/cpp-0245/main.cpp @@ -0,0 +1,49 @@ +/// Source : https://leetcode.com/problems/shortest-word-distance-iii/ +/// Author : liuyubobobo +/// Time : 2019-02-14 +#include +#include + +using namespace std; + + +/// Same as 243 +/// Just deal with when word1 == word2 +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int shortestWordDistance(vector& words, string word1, string word2) { + + if(word1 == word2){ + int last = -1, res = INT_MAX; + for(int i = 0; i < words.size(); i ++) + if(words[i] == word1){ + if(last != -1) res = min(res, i - last); + last = i; + } + return res; + } + + int last_index = -1, last_tag = 0, res = INT_MAX; + for(int i = 0; i < words.size(); i ++){ + int cur_tag = 0; + if(words[i] == word1) cur_tag = 1; + else if(words[i] == word2) cur_tag = 2; + + if(last_tag && cur_tag && cur_tag != last_tag) + res = min(res, i - last_index); + + if(cur_tag) + last_index = i, last_tag = cur_tag; + } + + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0246-Strobogrammatic-Number/cpp-0246/CMakeLists.txt b/0001-0500/0246-Strobogrammatic-Number/cpp-0246/CMakeLists.txt new file mode 100644 index 00000000..a1814c41 --- /dev/null +++ b/0001-0500/0246-Strobogrammatic-Number/cpp-0246/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0246) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0246 main.cpp) \ No newline at end of file diff --git a/0001-0500/0246-Strobogrammatic-Number/cpp-0246/main.cpp b/0001-0500/0246-Strobogrammatic-Number/cpp-0246/main.cpp new file mode 100644 index 00000000..46f7a098 --- /dev/null +++ b/0001-0500/0246-Strobogrammatic-Number/cpp-0246/main.cpp @@ -0,0 +1,42 @@ +/// Source : https://leetcode.com/problems/strobogrammatic-number/ +/// Author : liuyubobobo +/// Time : 2021-03-08 + +#include +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +public: + bool isStrobogrammatic(string num) { + + const map table = { + {'0', '0'}, + {'1', '1'}, +// {'2', '2'}, +// {'5', '5'}, + {'6', '9'}, + {'8', '8'}, + {'9', '6'} + }; + + string r = ""; + for(char c: num) + if(!table.count(c)) return false; + else r += table.at(c); + reverse(r.begin(), r.end()); + return num == r; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0247-Strobogrammatic-Number-II/cpp-0247/CMakeLists.txt b/0001-0500/0247-Strobogrammatic-Number-II/cpp-0247/CMakeLists.txt new file mode 100644 index 00000000..38ea6904 --- /dev/null +++ b/0001-0500/0247-Strobogrammatic-Number-II/cpp-0247/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0247) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0247 main.cpp) \ No newline at end of file diff --git a/0001-0500/0247-Strobogrammatic-Number-II/cpp-0247/main.cpp b/0001-0500/0247-Strobogrammatic-Number-II/cpp-0247/main.cpp new file mode 100644 index 00000000..1f92f862 --- /dev/null +++ b/0001-0500/0247-Strobogrammatic-Number-II/cpp-0247/main.cpp @@ -0,0 +1,61 @@ +/// Source : https://leetcode.com/problems/strobogrammatic-number-ii/ +/// Author : liuyubobobo +/// Time : 2021-03-08 + +#include +#include +#include + +using namespace std; + + +/// Backtracking +/// Time Complexity: O((n / 2) ^ 5) +/// Space Complexity: O(n) +class Solution { + +private: + const map table = { + {'0', '0'}, + {'1', '1'}, + // {'2', '2'}, + // {'5', '5'}, + {'6', '9'}, + {'8', '8'}, + {'9', '6'} + }; + +public: + vector findStrobogrammatic(int n) { + + vector res; + string cur(n, ' '); + dfs(0, n, cur, res); + return res; + } + +private: + void dfs(int index, int n, string& cur, vector& res){ + + if(index > (n - 1) / 2){ + res.push_back(cur); + return; + } + + for(const pair& p: table){ + + if(index == 0 && p.first == '0' && n > 1) continue; + + if(n % 2 && index == n / 2 && (p.first == '6' || p.first == '9')) continue; + + cur[index] = p.first; + cur[n - index - 1] = p.second; + dfs(index + 1, n, cur, res); + } + } +}; + +int main() { + + return 0; +} diff --git a/0001-0500/0248-Strobogrammatic-Number-III/cpp-0248/CMakeLists.txt b/0001-0500/0248-Strobogrammatic-Number-III/cpp-0248/CMakeLists.txt new file mode 100644 index 00000000..5cf4d28b --- /dev/null +++ b/0001-0500/0248-Strobogrammatic-Number-III/cpp-0248/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0248) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0248 main.cpp) \ No newline at end of file diff --git a/0001-0500/0248-Strobogrammatic-Number-III/cpp-0248/main.cpp b/0001-0500/0248-Strobogrammatic-Number-III/cpp-0248/main.cpp new file mode 100644 index 00000000..f7106b2a --- /dev/null +++ b/0001-0500/0248-Strobogrammatic-Number-III/cpp-0248/main.cpp @@ -0,0 +1,69 @@ +/// Source : https://leetcode.com/problems/strobogrammatic-number-iii/ +/// Author : liuyubobobo +/// Time : 2021-03-08 + +#include +#include + +using namespace std; + + +/// Backtracking +/// Time Complexity: O(|high| * O((|high| / 2) ^ 5)) +/// Space Complexity: O(|high|) +class Solution { + +private: + const map table = { + {'0', '0'}, + {'1', '1'}, + // {'2', '2'}, + // {'5', '5'}, + {'6', '9'}, + {'8', '8'}, + {'9', '6'} + }; + +public: + int strobogrammaticInRange(string low, string high) { + + int res = 0; + for(int len = low.size(); len <= high.size(); len ++){ + string cur(len, ' '); + res += dfs(0, len, to_long_long(low), to_long_long(high), cur); + } + return res; + } + +private: + int dfs(int index, int n, long long low, long long high, string& cur){ + + if(index > (n - 1) / 2){ + long long num = to_long_long(cur); + return low <= num && num <= high; + } + + int res = 0; + for(const pair& p: table){ + + if(index == 0 && p.first == '0' && n > 1) continue; + + if(n % 2 && index == n / 2 && (p.first == '6' || p.first == '9')) continue; + + cur[index] = p.first; + cur[n - index - 1] = p.second; + res += dfs(index + 1, n, low, high, cur); + } + return res; + } + + long long to_long_long(const string& s){ + return atoll(s.c_str()); + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0249-Group-Shifted-Strings/cpp-0249/CMakeLists.txt b/0001-0500/0249-Group-Shifted-Strings/cpp-0249/CMakeLists.txt new file mode 100644 index 00000000..65b5fb08 --- /dev/null +++ b/0001-0500/0249-Group-Shifted-Strings/cpp-0249/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0249) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0249 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0249-Group-Shifted-Strings/cpp-0249/main.cpp b/0001-0500/0249-Group-Shifted-Strings/cpp-0249/main.cpp new file mode 100644 index 00000000..a0a02976 --- /dev/null +++ b/0001-0500/0249-Group-Shifted-Strings/cpp-0249/main.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/group-shifted-strings/description/ +/// Author : liuyubobobo +/// Time : 2018-10-03 + +#include +#include +#include +#include + +using namespace std; + + +/// Using HashMap +/// Time Complexity: O(n * average len of s) +/// Space Compleity: O(n * average len of s) +class Solution { + +public: + vector> groupStrings(vector& strings) { + + unordered_map> map; + for(const string& s: strings){ + string key = getKey(s); + map[key].push_back(s); + } + + vector> res; + for(const pair>& p: map) + res.push_back(p.second); + return res; + } + +private: + string getKey(string s){ + + int dis = 26 - (s[0] - 'a'); + for(int i = 0; i < s.size(); i ++) + s[i] = 'a' + (s[i] + dis) % 26; + return s; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0250-Count-Univalue-Subtrees/cpp-0250/CMakeLists.txt b/0001-0500/0250-Count-Univalue-Subtrees/cpp-0250/CMakeLists.txt new file mode 100644 index 00000000..55ad08e2 --- /dev/null +++ b/0001-0500/0250-Count-Univalue-Subtrees/cpp-0250/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0250) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main5.cpp) +add_executable(cpp_0250 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0250-Count-Univalue-Subtrees/cpp-0250/main.cpp b/0001-0500/0250-Count-Univalue-Subtrees/cpp-0250/main.cpp new file mode 100644 index 00000000..f488f67b --- /dev/null +++ b/0001-0500/0250-Count-Univalue-Subtrees/cpp-0250/main.cpp @@ -0,0 +1,58 @@ +/// Source : https://leetcode.com/problems/count-univalue-subtrees/description/ +/// Author : liuyubobobo +/// Time : 2018-06-02 + +#include + +using namespace std; + + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +/// Recursive +/// Time Complexity: O(n^2) +/// Space Complexty: O(h) +class Solution { +public: + int countUnivalSubtrees(TreeNode* root) { + + if(root == NULL) + return 0; + + int res = 0; + if(root->left != NULL) + res += countUnivalSubtrees(root->left); + + if(root->right != NULL) + res += countUnivalSubtrees(root->right); + + if(isUnivalTree(root, root->val)) + res += 1; + + return res; + } + +private: + bool isUnivalTree(TreeNode* root, int val){ + + if(root == NULL) + return true; + + if(root->val != val) + return false; + + return isUnivalTree(root->left, val) && isUnivalTree(root->right, val); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0250-Count-Univalue-Subtrees/cpp-0250/main2.cpp b/0001-0500/0250-Count-Univalue-Subtrees/cpp-0250/main2.cpp new file mode 100644 index 00000000..2ea6bd38 --- /dev/null +++ b/0001-0500/0250-Count-Univalue-Subtrees/cpp-0250/main2.cpp @@ -0,0 +1,61 @@ +/// Source : https://leetcode.com/problems/count-univalue-subtrees/description/ +/// Author : liuyubobobo +/// Time : 2018-06-02 + +#include + +using namespace std; + + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +/// Recursive +/// Time Complexity: O(n) +/// Space Complexty: O(h) +class Solution { +public: + int countUnivalSubtrees(TreeNode* root) { + + if(root == NULL) + return 0; + + return dfs(root).second; + } + +private: + pair dfs(TreeNode* root){ + + pair leftRes, rightRes; + int res = 0; + bool isUnivalTree = true; + + if(root->left != NULL) { + leftRes = dfs(root->left); + res += leftRes.second; + isUnivalTree = isUnivalTree && leftRes.first && root->val == root->left->val; + } + + if(root->right != NULL) { + rightRes = dfs(root->right); + res += rightRes.second; + isUnivalTree = isUnivalTree && rightRes.first && root->val == root->right->val; + } + + if(isUnivalTree) + res += 1; + + return make_pair(isUnivalTree, res); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0250-Count-Univalue-Subtrees/cpp-0250/main3.cpp b/0001-0500/0250-Count-Univalue-Subtrees/cpp-0250/main3.cpp new file mode 100644 index 00000000..4a0e3714 --- /dev/null +++ b/0001-0500/0250-Count-Univalue-Subtrees/cpp-0250/main3.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/count-univalue-subtrees/description/ +/// Author : liuyubobobo +/// Time : 2018-06-02 + +#include + +using namespace std; + + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +/// Recursive +/// Use class variable to store the result +/// Time Complexity: O(n) +/// Space Complexty: O(h) +class Solution { + +private: + int result = 0; + +public: + int countUnivalSubtrees(TreeNode* root) { + + if(root) dfs(root); + return result; + } + +private: + bool dfs(TreeNode* node){ + + bool ok = true; + if(node->left){ + bool isLeft = dfs(node->left); + if(!isLeft || node->val != node->left->val) ok = false; + } + + if(node->right){ + bool isRight = dfs(node->right); + if(!isRight || node->val != node->right->val) ok = false; + } + + if(ok) result ++; + return ok; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0250-Count-Univalue-Subtrees/cpp-0250/main4.cpp b/0001-0500/0250-Count-Univalue-Subtrees/cpp-0250/main4.cpp new file mode 100644 index 00000000..6ee45e76 --- /dev/null +++ b/0001-0500/0250-Count-Univalue-Subtrees/cpp-0250/main4.cpp @@ -0,0 +1,66 @@ +/// Source : https://leetcode.com/problems/count-univalue-subtrees/description/ +/// Author : liuyubobobo +/// Time : 2019-03-02 + +#include + +using namespace std; + + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +/// Recursive +/// Treat null as univalue subtree and make the implementation much more concise :-) +/// +/// Time Complexity: O(n) +/// Space Complexty: O(h) +class Solution { + +private: + int result = 0; + +public: + int countUnivalSubtrees(TreeNode* root) { + + dfs(root); + return result; + } + +private: + bool dfs(TreeNode* node){ + + if(!node) return true; + + bool isLeft = dfs(node->left), isRight = dfs(node->right); + bool ok = isLeft && (!node->left || node->val == node->left->val) && + isRight && (!node->right || node->val == node->right->val); + + if(ok) result ++; + return ok; + } +}; + + +int main() { + +// 5 +// / \ +// 1 5 +// / \ \ +// 5 5 5 + TreeNode *root = new TreeNode(5); + root->left = new TreeNode(1); + root->right = new TreeNode(5); + root->left->left = new TreeNode(5); + root->left->right = new TreeNode(5); + root->right->right = new TreeNode(5); + cout << Solution().countUnivalSubtrees(root) << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0250-Count-Univalue-Subtrees/cpp-0250/main5.cpp b/0001-0500/0250-Count-Univalue-Subtrees/cpp-0250/main5.cpp new file mode 100644 index 00000000..09e8f932 --- /dev/null +++ b/0001-0500/0250-Count-Univalue-Subtrees/cpp-0250/main5.cpp @@ -0,0 +1,65 @@ +/// Source : https://leetcode.com/problems/count-univalue-subtrees/description/ +/// Author : liuyubobobo +/// Time : 2019-03-03 + +#include + +using namespace std; + + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +/// Recursive +/// Pass parent value to make the implementation even more concise :-) +/// +/// Time Complexity: O(n) +/// Space Complexty: O(h) +class Solution { + +private: + int result = 0; + +public: + int countUnivalSubtrees(TreeNode* root) { + + dfs(root, NULL); + return result; + } + +private: + bool dfs(TreeNode* node, TreeNode* parent){ + + if(!node) return true; + + bool isLeft = dfs(node->left, node), isRight = dfs(node->right, node); + if(!isLeft || !isRight) return false; + + result ++; + return parent && node->val == parent->val; + } +}; + + +int main() { + +// 5 +// / \ +// 1 5 +// / \ \ +// 5 5 5 + TreeNode *root = new TreeNode(5); + root->left = new TreeNode(1); + root->right = new TreeNode(5); + root->left->left = new TreeNode(5); + root->left->right = new TreeNode(5); + root->right->right = new TreeNode(5); + cout << Solution().countUnivalSubtrees(root) << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0251-Flatten-2D-Vector/cpp-0251/CMakeLists.txt b/0001-0500/0251-Flatten-2D-Vector/cpp-0251/CMakeLists.txt new file mode 100644 index 00000000..82cedef8 --- /dev/null +++ b/0001-0500/0251-Flatten-2D-Vector/cpp-0251/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_0251) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0251 main.cpp) diff --git a/0001-0500/0251-Flatten-2D-Vector/cpp-0251/main.cpp b/0001-0500/0251-Flatten-2D-Vector/cpp-0251/main.cpp new file mode 100644 index 00000000..a5b84be3 --- /dev/null +++ b/0001-0500/0251-Flatten-2D-Vector/cpp-0251/main.cpp @@ -0,0 +1,41 @@ +/// Source : https://leetcode.com/problems/flatten-2d-vector/ +/// Author : liuyubobobo +/// Time : 2022-07-30 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: init: O(n) +/// query: O(1) +/// Space Complexity: O(n) +class Vector2D { + +private: + vector data; + int cur = -1; + +public: + Vector2D(vector>& vec){ + + for(int i = 0; i < vec.size(); i ++) + for(int e: vec[i]) data.push_back(e); + } + + int next() { + return data[++ cur]; + } + + bool hasNext() { + return cur + 1 < data.size(); + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0252-Meeting-Rooms/cpp-0252/CMakeLists.txt b/0001-0500/0252-Meeting-Rooms/cpp-0252/CMakeLists.txt new file mode 100644 index 00000000..0fc91319 --- /dev/null +++ b/0001-0500/0252-Meeting-Rooms/cpp-0252/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0252) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0252 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0252-Meeting-Rooms/cpp-0252/main.cpp b/0001-0500/0252-Meeting-Rooms/cpp-0252/main.cpp new file mode 100644 index 00000000..16b556b5 --- /dev/null +++ b/0001-0500/0252-Meeting-Rooms/cpp-0252/main.cpp @@ -0,0 +1,44 @@ +/// Source : https://leetcode.com/problems/meeting-rooms/description/ +/// Author : liuyubobobo +/// Time : 2018-09-10 + +#include +#include + +using namespace std; + + +/// Brute Force see if overlapped for every two intervals +/// Time Complexity: O(n^2) +/// Space Complexity: O(1) + +/// Definition for an interval. +struct Interval { + int start; + int end; + Interval() : start(0), end(0) {} + Interval(int s, int e) : start(s), end(e) {} +}; + +class Solution { +public: + bool canAttendMeetings(vector& intervals) { + + for(int i = 0; i < intervals.size(); i ++) + for(int j = i + 1; j < intervals.size(); j ++) + if(overlapped(intervals[i], intervals[j])) + return false; + return true; + } + +private: + bool overlapped(const Interval& i1, const Interval& i2){ + return max(i1.start, i2.start) < min(i1.end, i2.end); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0252-Meeting-Rooms/cpp-0252/main2.cpp b/0001-0500/0252-Meeting-Rooms/cpp-0252/main2.cpp new file mode 100644 index 00000000..ee948775 --- /dev/null +++ b/0001-0500/0252-Meeting-Rooms/cpp-0252/main2.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/meeting-rooms/description/ +/// Author : liuyubobobo +/// Time : 2018-09-10 + +#include +#include + +using namespace std; + + +/// Sorting and see if overlapped linearly +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) + +/// Definition for an interval. +struct Interval { + int start; + int end; + Interval() : start(0), end(0) {} + Interval(int s, int e) : start(s), end(e) {} +}; + +class Solution { +public: + bool canAttendMeetings(vector& intervals) { + + sort(intervals.begin(), intervals.end(), cmpIntervals); + for(int i = 1; i < intervals.size(); i ++) + if(intervals[i].start < intervals[i - 1].end) + return false; + return true; + } + +private: + static bool cmpIntervals(const Interval& i1, const Interval& i2){ + if(i1.start != i2.start) + return i1.start < i2.start; + return i1.end < i2.end; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0253-Meeting-Rooms-II/cpp-0253/CMakeLists.txt b/0001-0500/0253-Meeting-Rooms-II/cpp-0253/CMakeLists.txt new file mode 100644 index 00000000..f5276dd0 --- /dev/null +++ b/0001-0500/0253-Meeting-Rooms-II/cpp-0253/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0253) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main4.cpp) +add_executable(cpp_0253 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0253-Meeting-Rooms-II/cpp-0253/main.cpp b/0001-0500/0253-Meeting-Rooms-II/cpp-0253/main.cpp new file mode 100644 index 00000000..b1130202 --- /dev/null +++ b/0001-0500/0253-Meeting-Rooms-II/cpp-0253/main.cpp @@ -0,0 +1,69 @@ +/// Source : https://leetcode.com/problems/meeting-rooms-ii/description/ +/// Author : liuyubobobo +/// Time : 2018-09-10 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) + +/// Definition for an interval. +struct Interval { + int start; + int end; + Interval() : start(0), end(0) {} + Interval(int s, int e) : start(s), end(e) {} +}; + +class Solution { + +public: + int minMeetingRooms(vector& intervals) { + + sort(intervals.begin(), intervals.end(), cmpIntervals); + + vector rooms; + int sz = 0, res = 0; + for(const Interval& meeting: intervals){ + + for(Interval& room: rooms) + if(room.end != -1 && room.end <= meeting.start){ + room.start = room.end = -1; + sz --; + } + + bool ok = false; + for(Interval& room: rooms) + if(room.start == -1){ + room = meeting; + ok = true; + break; + } + if(!ok) + rooms.push_back(meeting); + sz ++; + + res = max(res, sz); + } + + return res; + } + +private: + static bool cmpIntervals(const Interval& i1, const Interval& i2){ + if(i1.start != i2.start) + return i1.start < i2.start; + return i1.end < i2.end; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0253-Meeting-Rooms-II/cpp-0253/main2.cpp b/0001-0500/0253-Meeting-Rooms-II/cpp-0253/main2.cpp new file mode 100644 index 00000000..a3bb422c --- /dev/null +++ b/0001-0500/0253-Meeting-Rooms-II/cpp-0253/main2.cpp @@ -0,0 +1,67 @@ +/// Source : https://leetcode.com/problems/meeting-rooms-ii/description/ +/// Author : liuyubobobo +/// Time : 2018-09-10 + +#include +#include +#include + +using namespace std; + + +/// Simulation +/// Using Priority Queue +/// +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) + +/// Definition for an interval. +struct Interval { + int start; + int end; + Interval() : start(0), end(0) {} + Interval(int s, int e) : start(s), end(e) {} +}; + +class Solution { + +private: + class CompareInterval{ + public: + bool operator()(const Interval& a, const Interval& b){ + return a.end > b.end; + } + }; + +public: + int minMeetingRooms(vector& intervals) { + + sort(intervals.begin(), intervals.end(), cmpIntervals); + + priority_queue, CompareInterval> rooms; + int res = 0; + for(const Interval& meeting: intervals){ + + while(!rooms.empty() && rooms.top().end <= meeting.start) + rooms.pop(); + + rooms.push(meeting); + res = max(res, (int)rooms.size()); + } + + return res; + } + +private: + static bool cmpIntervals(const Interval& i1, const Interval& i2){ + if(i1.start != i2.start) + return i1.start < i2.start; + return i1.end < i2.end; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0253-Meeting-Rooms-II/cpp-0253/main3.cpp b/0001-0500/0253-Meeting-Rooms-II/cpp-0253/main3.cpp new file mode 100644 index 00000000..2d5524a3 --- /dev/null +++ b/0001-0500/0253-Meeting-Rooms-II/cpp-0253/main3.cpp @@ -0,0 +1,58 @@ +/// Source : https://leetcode.com/problems/meeting-rooms-ii/description/ +/// Author : liuyubobobo +/// Time : 2018-09-10 + +#include +#include + +using namespace std; + + +/// Two Pointers +/// Sorting start time and end time seperately. +/// +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) + +/// Definition for an interval. +struct Interval { + int start; + int end; + Interval() : start(0), end(0) {} + Interval(int s, int e) : start(s), end(e) {} +}; + +class Solution { +public: + int minMeetingRooms(vector& intervals) { + + if(intervals.size() == 0) + return 0; + + vector starts, ends; + for(const Interval& interval: intervals){ + starts.push_back(interval.start); + ends.push_back(interval.end); + } + sort(starts.begin(), starts.end()); + sort(ends.begin(), ends.end()); + + + int res = 1, sz = 1; + int end_index = 0; + for(int start_index = 1; start_index < starts.size(); start_index ++){ + while(end_index < ends.size() && ends[end_index] <= starts[start_index]) + end_index ++, sz --; + sz ++; + res = max(res, sz); + } + + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0253-Meeting-Rooms-II/cpp-0253/main4.cpp b/0001-0500/0253-Meeting-Rooms-II/cpp-0253/main4.cpp new file mode 100644 index 00000000..4d66a1b0 --- /dev/null +++ b/0001-0500/0253-Meeting-Rooms-II/cpp-0253/main4.cpp @@ -0,0 +1,55 @@ +/// Source : https://leetcode.com/problems/meeting-rooms-ii/description/ +/// Author : liuyubobobo +/// Time : 2018-09-10 + +#include +#include + +using namespace std; + + +/// Dealing with start time and end time seperately +/// make start time and end time in a pair structure +/// and deal with them in one single vector:) +/// +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) + +/// Definition for an interval. +struct Interval { + int start; + int end; + Interval() : start(0), end(0) {} + Interval(int s, int e) : start(s), end(e) {} +}; + +class Solution { +public: + int minMeetingRooms(vector& intervals) { + + vector> timepoints; + for(const Interval& interval: intervals){ + timepoints.push_back(make_pair(interval.start, 's')); + timepoints.push_back(make_pair(interval.end, 'e')); + } + sort(timepoints.begin(), timepoints.end()); + + int res = 0; + int cur = 0; + for(const pair& p: timepoints) + if(p.second == 's'){ + cur ++; + res = max(res, cur); + } + else + cur --; + + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0254-Factor-Combinations/cpp-0254/CMakeLists.txt b/0001-0500/0254-Factor-Combinations/cpp-0254/CMakeLists.txt similarity index 100% rename from 0254-Factor-Combinations/cpp-0254/CMakeLists.txt rename to 0001-0500/0254-Factor-Combinations/cpp-0254/CMakeLists.txt diff --git a/0254-Factor-Combinations/cpp-0254/main.cpp b/0001-0500/0254-Factor-Combinations/cpp-0254/main.cpp similarity index 100% rename from 0254-Factor-Combinations/cpp-0254/main.cpp rename to 0001-0500/0254-Factor-Combinations/cpp-0254/main.cpp diff --git a/0001-0500/0256-Paint-House/cpp-0256/CMakeLists.txt b/0001-0500/0256-Paint-House/cpp-0256/CMakeLists.txt new file mode 100644 index 00000000..c17b3f04 --- /dev/null +++ b/0001-0500/0256-Paint-House/cpp-0256/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_0256) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0256 main.cpp) \ No newline at end of file diff --git a/0001-0500/0256-Paint-House/cpp-0256/main.cpp b/0001-0500/0256-Paint-House/cpp-0256/main.cpp new file mode 100644 index 00000000..d236d7f2 --- /dev/null +++ b/0001-0500/0256-Paint-House/cpp-0256/main.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/paint-house/ +/// Author : liuyubobobo +/// Time : 2021-05-04 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int minCost(vector>& costs) { + + int n = costs.size(); + + vector> dp(n, vector(3, INT_MAX)); + dp[0] = costs[0]; + for(int i = 1; i < n; i ++) + for(int j = 0; j < 3; j ++){ + for(int k = 0; k < 3; k ++) + if(k != j) dp[i][j] = min(dp[i][j], dp[i - 1][k] + costs[i][j]); + } + return *min_element(dp.back().begin(), dp.back().end()); + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0257-Binary-Tree-Paths/cpp-0257/CMakeLists.txt b/0001-0500/0257-Binary-Tree-Paths/cpp-0257/CMakeLists.txt new file mode 100644 index 00000000..d1c1203a --- /dev/null +++ b/0001-0500/0257-Binary-Tree-Paths/cpp-0257/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0257) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main4.cpp) +add_executable(cpp_0257 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0257-Binary-Tree-Paths/cpp-0257/main.cpp b/0001-0500/0257-Binary-Tree-Paths/cpp-0257/main.cpp new file mode 100644 index 00000000..711c2021 --- /dev/null +++ b/0001-0500/0257-Binary-Tree-Paths/cpp-0257/main.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/binary-tree-paths/description/ +/// Author : liuyubobobo +/// Time : 2017-11-17 + +#include +#include +#include + +using namespace std; + + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + + +/// Recursive +/// Time Complexity: O(n), where n is the node's number in the tree +/// Space Complexity: O(h), where h is the height of the tree +class Solution { +public: + vector binaryTreePaths(TreeNode* root) { + + vector res; + + if(root == NULL) + return res; + + if(root->left == NULL && root->right == NULL){ + res.push_back(to_string(root->val)); + return res; + } + + vector leftPaths = binaryTreePaths(root->left); + for(int i = 0 ; i < leftPaths.size() ; i ++) + res.push_back(to_string(root->val) + "->" + leftPaths[i]); + + vector rightPaths = binaryTreePaths(root->right); + for(int i = 0 ; i < rightPaths.size() ; i ++) + res.push_back(to_string(root->val) + "->" + rightPaths[i]); + + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0257-Binary-Tree-Paths/cpp-0257/main2.cpp b/0001-0500/0257-Binary-Tree-Paths/cpp-0257/main2.cpp new file mode 100644 index 00000000..289ffa84 --- /dev/null +++ b/0001-0500/0257-Binary-Tree-Paths/cpp-0257/main2.cpp @@ -0,0 +1,58 @@ +/// Source : https://leetcode.com/problems/binary-tree-paths/description/ +/// Author : liuyubobobo +/// Time : 2020-10-20 + +#include +#include +#include + +using namespace std; + + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + + +/// Recursive +/// Time Complexity: O(n), where n is the node's number in the tree +/// Space Complexity: O(h), where h is the height of the tree +class Solution { +public: + vector binaryTreePaths(TreeNode* root) { + + if(root == nullptr) return {}; + + vector path; + vector res; + dfs(root, path, res); + return res; + } + +private: + void dfs(TreeNode* node, vector& path, vector& res){ + + path.push_back(node); + if(node->left == nullptr && node->right == nullptr){ + string str = to_string(path[0]->val); + for(int i = 1; i < path.size(); i ++) + str += "->" + to_string(path[i]->val); + res.push_back(str); + } + + if(node->left) dfs(node->left, path, res); + if(node->right) dfs(node->right, path, res); + + path.pop_back(); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0257-Binary-Tree-Paths/cpp-0257/main3.cpp b/0001-0500/0257-Binary-Tree-Paths/cpp-0257/main3.cpp new file mode 100644 index 00000000..a5db76d0 --- /dev/null +++ b/0001-0500/0257-Binary-Tree-Paths/cpp-0257/main3.cpp @@ -0,0 +1,58 @@ +/// Source : https://leetcode.com/problems/binary-tree-paths/description/ +/// Author : liuyubobobo +/// Time : 2018-11-17 + +#include +#include +#include +#include + +using namespace std; + + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + + +/// Non-Recursive +/// Using Stack +/// +/// Time Complexity: O(n), where n is the node's number in the tree +/// Space Complexity: O(h), where h is the height of the tree +class Solution { +public: + vector binaryTreePaths(TreeNode* root) { + + vector res; + if(root == NULL) + return res; + + stack> stack; + stack.push(make_pair(root, to_string(root->val))); + while(!stack.empty()){ + TreeNode* cur = stack.top().first; + string s = stack.top().second; + stack.pop(); + + if(!cur->left && !cur->right) + res.push_back(s); + + if(cur->left) + stack.push(make_pair(cur->left, s + "->" + to_string(cur->left->val))); + if(cur->right) + stack.push(make_pair(cur->right, s + "->" + to_string(cur->right->val))); + } + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0257-Binary-Tree-Paths/cpp-0257/main4.cpp b/0001-0500/0257-Binary-Tree-Paths/cpp-0257/main4.cpp new file mode 100644 index 00000000..381ecc82 --- /dev/null +++ b/0001-0500/0257-Binary-Tree-Paths/cpp-0257/main4.cpp @@ -0,0 +1,94 @@ +/// Source : https://leetcode.com/problems/binary-tree-paths/description/ +/// Author : liuyubobobo +/// Time : 2020-10-20 + +#include +#include +#include +#include + +using namespace std; + + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x, TreeNode* lt, TreeNode* rt) : val(x), left(lt), right(rt) {} + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + + +/// Non-Recursive +/// Using Command Stack to simulate system stack +/// +/// Time Complexity: O(n), where n is the node's number in the tree +/// Space Complexity: O(h), where h is the height of the tree +class Solution { + +private: + struct Command{ + string s; // go, print, pop + TreeNode* node; + Command(string s, TreeNode* node): s(s), node(node){} + }; + +public: + vector binaryTreePaths(TreeNode* root) { + + if(root == nullptr) return {}; + + vector res; + if(root == NULL) + return res; + + stack command_stack; + vector path; + + command_stack.push(Command("go", root)); + + while(!command_stack.empty()){ + Command command = command_stack.top(); + command_stack.pop(); + + if(command.s == "do"){ + path.push_back(command.node); + if(command.node->left == nullptr && command.node->right == nullptr){ + string str = to_string(path[0]->val); + for(int i = 1; i < path.size(); i ++) + str += "->" + to_string(path[i]->val); + res.push_back(str); + } + } + else if(command.s == "pop"){ + path.pop_back(); + } + else{ + command_stack.push(Command("pop", command.node)); + + if(command.node->right) + command_stack.push(Command("go",command.node->right)); + if(command.node->left) + command_stack.push(Command("go",command.node->left)); + + command_stack.push(Command("do", command.node)); + + } + } + return res; + } +}; + + +void print_vec(const vector& v){ + for(const string& s: v) cout << s << '\n'; +} + +int main() { + + TreeNode* root1 = new TreeNode(1, new TreeNode(2, NULL, new TreeNode(5)), new TreeNode(3)); + print_vec(Solution().binaryTreePaths(root1)); + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0257-Binary-Tree-Paths/java-0257/src/Solution1.java b/0001-0500/0257-Binary-Tree-Paths/java-0257/src/Solution1.java new file mode 100644 index 00000000..cab5f0c7 --- /dev/null +++ b/0001-0500/0257-Binary-Tree-Paths/java-0257/src/Solution1.java @@ -0,0 +1,43 @@ +/// Source : https://leetcode.com/problems/binary-tree-paths/description/ +/// Author : liuyubobobo +/// Time : 2017-11-17 + +import java.util.List; +import java.util.ArrayList; + +/// Recursive +/// Time Complexity: O(n), where n is the node's number in the tree +/// Space Complexity: O(h), where h is the height of the tree +public class Solution1 { + + public List binaryTreePaths(TreeNode root) { + + ArrayList res = new ArrayList(); + + if(root == null) + return res; + + if(root.left == null && root.right == null){ + res.add(Integer.toString(root.val)); + return res; + } + + List leftPaths = binaryTreePaths(root.left); + for(String s: leftPaths){ + StringBuilder sb = new StringBuilder(Integer.toString(root.val)); + sb.append("->"); + sb.append(s); + res.add(sb.toString()); + } + + List rightPaths = binaryTreePaths(root.right); + for(String s: rightPaths) { + StringBuilder sb = new StringBuilder(Integer.toString(root.val)); + sb.append("->"); + sb.append(s); + res.add(sb.toString()); + } + + return res; + } +} diff --git a/0001-0500/0257-Binary-Tree-Paths/java-0257/src/Solution2.java b/0001-0500/0257-Binary-Tree-Paths/java-0257/src/Solution2.java new file mode 100644 index 00000000..dbcd7833 --- /dev/null +++ b/0001-0500/0257-Binary-Tree-Paths/java-0257/src/Solution2.java @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/binary-tree-paths/description/ +/// Author : liuyubobobo +/// Time : 2017-11-17 + +import java.util.List; +import java.util.ArrayList; +import java.util.Stack; +import javafx.util.Pair; + +/// Non-Recursive +/// Using Stack +/// +/// Time Complexity: O(n), where n is the node's number in the tree +/// Space Complexity: O(h), where h is the height of the tree +public class Solution2 { + + public List binaryTreePaths(TreeNode root) { + + List res = new ArrayList(); + if(root == null) + return res; + + Stack> stack = new Stack<>(); + stack.push(new Pair(root, Integer.toString(root.val))); + while(!stack.empty()){ + TreeNode cur = stack.peek().getKey(); + String s = stack.peek().getValue(); + stack.pop(); + + if(cur.left == null && cur.right == null) + res.add(s); + + if(cur.left != null) + stack.push(new Pair<>(cur.left, s + "->" + Integer.toString(cur.left.val))); + if(cur.right != null) + stack.push(new Pair<>(cur.right, s + "->" + Integer.toString(cur.right.val))); + } + return res; + } +} diff --git a/0001-0500/0257-Binary-Tree-Paths/java-0257/src/TreeNode.java b/0001-0500/0257-Binary-Tree-Paths/java-0257/src/TreeNode.java new file mode 100644 index 00000000..f408f764 --- /dev/null +++ b/0001-0500/0257-Binary-Tree-Paths/java-0257/src/TreeNode.java @@ -0,0 +1,7 @@ +// Definition for a binary tree node. +public class TreeNode { + int val; + TreeNode left; + TreeNode right; + TreeNode(int x) { val = x; } +} \ No newline at end of file diff --git a/0001-0500/0258-Add-Digits/cpp-0258/CMakeLists.txt b/0001-0500/0258-Add-Digits/cpp-0258/CMakeLists.txt new file mode 100644 index 00000000..44ca2503 --- /dev/null +++ b/0001-0500/0258-Add-Digits/cpp-0258/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_0258) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0258 main.cpp) diff --git a/0001-0500/0258-Add-Digits/cpp-0258/main.cpp b/0001-0500/0258-Add-Digits/cpp-0258/main.cpp new file mode 100644 index 00000000..0eb38b99 --- /dev/null +++ b/0001-0500/0258-Add-Digits/cpp-0258/main.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/add-digits/ +/// Author : liuyubobobo +/// Time : 2022-02-07 + +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O((logn)^2) +/// Space Complexity: O(1) +class Solution { +public: + int addDigits(int num) { + while(num >= 10) + num = digit_sum(num); + return num; + } + +private: + int digit_sum(int num){ + int res = 0; + while(num) res += num % 10, num /= 10; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/old/0259 3Sum Smaller/cpp-3Sum-Smaller/CMakeLists.txt b/0001-0500/0259-3Sum-Smaller/cpp-0259/CMakeLists.txt similarity index 100% rename from old/0259 3Sum Smaller/cpp-3Sum-Smaller/CMakeLists.txt rename to 0001-0500/0259-3Sum-Smaller/cpp-0259/CMakeLists.txt diff --git a/0001-0500/0259-3Sum-Smaller/cpp-0259/main1.cpp b/0001-0500/0259-3Sum-Smaller/cpp-0259/main1.cpp new file mode 100644 index 00000000..657ff2b6 --- /dev/null +++ b/0001-0500/0259-3Sum-Smaller/cpp-0259/main1.cpp @@ -0,0 +1,83 @@ +/// Source : https://leetcode.com/problems/3sum-smaller/ +/// Author : liuyubobobo +/// Time : 2016-12-05 + +#include +#include +#include +#include + +using namespace std; + + +/// Binary Search +/// Sort the entire numbers first. +/// For every number nums[i] and nums[j] in numbers, +/// use binary search to find index k, +/// which makes nums[i] + nums[j] + nums[k] is the closest sum less than the target. +/// +/// Time Complexity: O(nlogn) + O((n^2)logn) +/// Space Complexity: O(1) +class Solution { +public: + int threeSumSmaller(vector& nums, int target) { + + // There're testcases which the nums.size < 3 + //assert( nums.size() >= 3 ); + if( nums.size() < 3 ) + return 0; + + sort(nums.begin(), nums.end()); + + int res = 0; + for( int i = 0 ; i < nums.size() - 2 ; i ++ ){ + for( int j = i + 1 ; j < nums.size() - 1 ; j ++ ){ + int t = target - nums[i] - nums[j]; + + // find the largest index in nums[j+1...nums.size()-1] + // where nums[index] < t + int index = bsearch(nums, j+1, nums.size() - 1, t); + + if(index != -1) + res += (index - j); + } + } + return res; + } + +private: + // find the largest index j in the range [l...r] where nums[j] < target + // return -1 if there's no element less than the given target + int bsearch(const vector &nums, int l, int r, int target){ + + assert(l >= 0 && r < nums.size() && l <= r); + + // the left point is l-1 to give the space for non solution. + int left = l-1, right = r; + while(left != right){ + + // Using round-up tecnique to avoid inifinite loop + int mid = left + (right - left + 1) / 2; + + if(nums[mid] >= target) + right = mid - 1; + else + left = mid; + } + + if(left <= l - 1) + return -1; + + return left; + } +}; + + +int main() { + + vector nums1 = {-2, 0, 1, 3}; + int target1 = 4; + cout << Solution().threeSumSmaller(nums1, target1) << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0259-3Sum-Smaller/cpp-0259/main2.cpp b/0001-0500/0259-3Sum-Smaller/cpp-0259/main2.cpp new file mode 100644 index 00000000..df673417 --- /dev/null +++ b/0001-0500/0259-3Sum-Smaller/cpp-0259/main2.cpp @@ -0,0 +1,58 @@ +/// Source : https://leetcode.com/problems/3sum-smaller/ +/// Author : liuyubobobo +/// Time : 2016-12-05 +#include +#include +#include +#include + +using namespace std; + + +/// Two Pointers +/// Sort the entire numbers first. +/// For every number nums[i], +/// using two pointers technique to find indexes j and k, +/// which makes nums[i] + nums[j] + nums[k] < target. +/// Then, we can use j and k to calculate how many pairs can be got between nums[j] and nums[k]. +/// +/// Time Complexity: O(nlogn) + O(n^2) +/// Space Complexity: O(1) +class Solution { +public: + int threeSumSmaller(vector& nums, int target) { + + // There're testcases which the nums.size < 3 + //assert(nums.size() >= 3); + if(nums.size() < 3) + return 0; + + sort(nums.begin(), nums.end()); + + int res = 0; + for(int i = 0 ; i < nums.size() - 2 ; i ++){ + + int j = i + 1, k = nums.size() - 1; + while(j < k){ + + if(nums[i] + nums[j] + nums[k] < target){ + res += (k - j); + j ++; + } + else + k --; + } + } + return res; + } +}; + + +int main() { + + vector nums1 = {-2, 0, 1, 3}; + int target1 = 4; + cout << Solution().threeSumSmaller(nums1, target1) << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0260-Single-Number-III/cpp-0260/CMakeLists.txt b/0001-0500/0260-Single-Number-III/cpp-0260/CMakeLists.txt new file mode 100644 index 00000000..1a0decbe --- /dev/null +++ b/0001-0500/0260-Single-Number-III/cpp-0260/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0260) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0260 main.cpp) diff --git a/0001-0500/0260-Single-Number-III/cpp-0260/main.cpp b/0001-0500/0260-Single-Number-III/cpp-0260/main.cpp new file mode 100644 index 00000000..e14687c3 --- /dev/null +++ b/0001-0500/0260-Single-Number-III/cpp-0260/main.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/single-number-iii/ +/// Author : liuyubobobo +/// Time : 2021-10-29 + +#include +#include +#include + +using namespace std; + + +/// Using Map +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector singleNumber(vector& nums) { + + map f; + for(int e: nums) f[e] ++; + + vector res; + for(const pair& p: f) + if(p.second == 1) res.push_back(p.first); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0261-Graph-Valid-Tree/cpp-0261/CMakeLists.txt b/0001-0500/0261-Graph-Valid-Tree/cpp-0261/CMakeLists.txt new file mode 100644 index 00000000..236f4e15 --- /dev/null +++ b/0001-0500/0261-Graph-Valid-Tree/cpp-0261/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0261) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0261 main.cpp) diff --git a/0001-0500/0261-Graph-Valid-Tree/cpp-0261/main.cpp b/0001-0500/0261-Graph-Valid-Tree/cpp-0261/main.cpp new file mode 100644 index 00000000..e9e643cd --- /dev/null +++ b/0001-0500/0261-Graph-Valid-Tree/cpp-0261/main.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/graph-valid-tree/ +/// Author : liuyubobobo +/// Time : 2021-08-21 + +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + bool validTree(int n, vector>& edges) { + + if(edges.size() != n - 1) return false; + + vector> g(n); + for(const vector& e: edges) + g[e[0]].push_back(e[1]), g[e[1]].push_back(e[0]); + + vector visited(n, false); + int cc = 0; + for(int i = 0; i < n; i ++) + if(!visited[i]){ + dfs(g, i, visited); + cc ++; + } + return cc == 1; + } + +private: + void dfs(const vector>& g, int u, vector& visited){ + + visited[u] = true; + for(int v: g[u]) + if(!visited[v]) dfs(g, v, visited); + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0263-Ugly-Number/cpp-0263/CMakeLists.txt b/0001-0500/0263-Ugly-Number/cpp-0263/CMakeLists.txt new file mode 100644 index 00000000..0284a346 --- /dev/null +++ b/0001-0500/0263-Ugly-Number/cpp-0263/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(0263_Ugly_Number) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(0263_Ugly_Number main.cpp) \ No newline at end of file diff --git a/0001-0500/0263-Ugly-Number/cpp-0263/main.cpp b/0001-0500/0263-Ugly-Number/cpp-0263/main.cpp new file mode 100644 index 00000000..153d972d --- /dev/null +++ b/0001-0500/0263-Ugly-Number/cpp-0263/main.cpp @@ -0,0 +1,30 @@ +/// Source : https://leetcode.com/problems/ugly-number/ +/// Author : liuyubobobo +/// Time : 2021-04-10 + +#include + +using namespace std; + + +/// Mathematics +/// Time Complexity: O(logn) +/// Space Complexity: O(1) +class Solution { +public: + bool isUgly(int n) { + + if(n == 0) return false; + + while(n % 2 == 0) n /= 2; + while(n % 3 == 0) n /= 3; + while(n % 5 == 0) n /= 5; + return n == 1; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0264-Ugly-Number-II/cpp-0264/CMakeLists.txt b/0001-0500/0264-Ugly-Number-II/cpp-0264/CMakeLists.txt new file mode 100644 index 00000000..d0489bf7 --- /dev/null +++ b/0001-0500/0264-Ugly-Number-II/cpp-0264/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_0264) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0264 main.cpp) \ No newline at end of file diff --git a/0001-0500/0264-Ugly-Number-II/cpp-0264/main.cpp b/0001-0500/0264-Ugly-Number-II/cpp-0264/main.cpp new file mode 100644 index 00000000..7622f755 --- /dev/null +++ b/0001-0500/0264-Ugly-Number-II/cpp-0264/main.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/ugly-number-ii/ +/// Author : liuyubobobo +/// Time : 2021-04-11 + +#include +#include + +using namespace std; + + +/// Using Set +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + int nthUglyNumber(int n) { + + set set; + set.insert(1); + for(int i = 0; i < n - 1; i ++){ + long long x = *set.begin(); + set.erase(x); + set.insert(x * 2); + set.insert(x * 3); + set.insert(x * 5); + } + return *set.begin(); + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0265-Paint-House-II/cpp-0265/CMakeLists.txt b/0001-0500/0265-Paint-House-II/cpp-0265/CMakeLists.txt new file mode 100644 index 00000000..0f8bd7af --- /dev/null +++ b/0001-0500/0265-Paint-House-II/cpp-0265/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_0265) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0265 main.cpp) \ No newline at end of file diff --git a/0001-0500/0265-Paint-House-II/cpp-0265/main.cpp b/0001-0500/0265-Paint-House-II/cpp-0265/main.cpp new file mode 100644 index 00000000..0887de20 --- /dev/null +++ b/0001-0500/0265-Paint-House-II/cpp-0265/main.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/paint-house-ii/ +/// Author : liuyubobobo +/// Time : 2021-05-04 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(n*k^2) +/// Space Complexity: O(nk) +class Solution { +public: + int minCostII(vector>& costs) { + + int n = costs.size(), k = costs[0].size(); + + vector> dp(n, vector(k, INT_MAX)); + dp[0] = costs[0]; + for(int i = 1; i < n; i ++) + for(int j = 0; j < k; j ++){ + for(int kk = 0; kk < k; kk ++) + if(kk != j) dp[i][j] = min(dp[i][j], dp[i - 1][kk] + costs[i][j]); + } + return *min_element(dp.back().begin(), dp.back().end()); + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0266-Palindrome-Permutation/cpp-0266/CMakeLists.txt b/0001-0500/0266-Palindrome-Permutation/cpp-0266/CMakeLists.txt new file mode 100644 index 00000000..30243a8e --- /dev/null +++ b/0001-0500/0266-Palindrome-Permutation/cpp-0266/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0266) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0266 main.cpp) \ No newline at end of file diff --git a/0001-0500/0266-Palindrome-Permutation/cpp-0266/main.cpp b/0001-0500/0266-Palindrome-Permutation/cpp-0266/main.cpp new file mode 100644 index 00000000..4f2a9a17 --- /dev/null +++ b/0001-0500/0266-Palindrome-Permutation/cpp-0266/main.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/palindrome-permutation/ +/// Author : liuyubobobo +/// Time : 2021-01-01 + +#include +#include +using namespace std; + + +/// Statistics +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + bool canPermutePalindrome(string s) { + + vector freq(256, 0); + for(char c: s) + freq[c] ++; + + int even = 0, odd = 0; + for(int e: freq) + if(e % 2) odd ++; + else even ++; + + return odd <= 1; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0267-Palindrome-Permutation-II/cpp-0267/CMakeLists.txt b/0001-0500/0267-Palindrome-Permutation-II/cpp-0267/CMakeLists.txt new file mode 100644 index 00000000..6807e7c2 --- /dev/null +++ b/0001-0500/0267-Palindrome-Permutation-II/cpp-0267/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0267) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0267 main.cpp) \ No newline at end of file diff --git a/0001-0500/0267-Palindrome-Permutation-II/cpp-0267/main.cpp b/0001-0500/0267-Palindrome-Permutation-II/cpp-0267/main.cpp new file mode 100644 index 00000000..663e62f4 --- /dev/null +++ b/0001-0500/0267-Palindrome-Permutation-II/cpp-0267/main.cpp @@ -0,0 +1,60 @@ +/// Source : https://leetcode.com/problems/palindrome-permutation-ii/ +/// Author : liuyubobobo +/// Time : 2020-01-01 + +#include +#include + +using namespace std; + + +/// Backtrack +/// Time Complexity: O((|s| / 2)^(|s| / 2)) +/// Space Complexity: O(|s|) +class Solution { +public: + vector generatePalindromes(string s) { + + vector freq(256, 0); + for(char c: s) + freq[c] ++; + + int even = 0, odd = 0; + char oddchar = 0; + for(int ch = 0; ch < freq.size(); ch ++) + if(freq[ch] % 2) + odd ++, oddchar = ch; + else even ++; + + if(odd > 1) return {}; + + string cur(s.size(), oddchar); + if(oddchar) freq[oddchar] --; + vector res; + dfs(freq, 0, cur, res); + return res; + } + +private: + void dfs(vector& freq, int index, string& cur, vector& res){ + + if(index >= cur.size() / 2){ + res.push_back(cur); + return; + } + + for(char ch = 0; ch < freq.size(); ch ++) + if(freq[ch]){ + cur[index] = cur[cur.size() - index - 1] = ch; + freq[ch] -= 2; + dfs(freq, index + 1, cur, res); + freq[ch] += 2; + } + } +}; + + +int main() { + + return 0; +} diff --git a/0268-Missing-Number/cpp-0268/CMakeLists.txt b/0001-0500/0268-Missing-Number/cpp-0268/CMakeLists.txt similarity index 100% rename from 0268-Missing-Number/cpp-0268/CMakeLists.txt rename to 0001-0500/0268-Missing-Number/cpp-0268/CMakeLists.txt diff --git a/0268-Missing-Number/cpp-0268/main.cpp b/0001-0500/0268-Missing-Number/cpp-0268/main.cpp similarity index 100% rename from 0268-Missing-Number/cpp-0268/main.cpp rename to 0001-0500/0268-Missing-Number/cpp-0268/main.cpp diff --git a/0268-Missing-Number/cpp-0268/main2.cpp b/0001-0500/0268-Missing-Number/cpp-0268/main2.cpp similarity index 100% rename from 0268-Missing-Number/cpp-0268/main2.cpp rename to 0001-0500/0268-Missing-Number/cpp-0268/main2.cpp diff --git a/0268-Missing-Number/cpp-0268/main3.cpp b/0001-0500/0268-Missing-Number/cpp-0268/main3.cpp similarity index 100% rename from 0268-Missing-Number/cpp-0268/main3.cpp rename to 0001-0500/0268-Missing-Number/cpp-0268/main3.cpp diff --git a/0268-Missing-Number/cpp-0268/main4.cpp b/0001-0500/0268-Missing-Number/cpp-0268/main4.cpp similarity index 100% rename from 0268-Missing-Number/cpp-0268/main4.cpp rename to 0001-0500/0268-Missing-Number/cpp-0268/main4.cpp diff --git a/0001-0500/0269-Alien-Dictionary/cpp-0269/CMakeLists.txt b/0001-0500/0269-Alien-Dictionary/cpp-0269/CMakeLists.txt new file mode 100644 index 00000000..830ef666 --- /dev/null +++ b/0001-0500/0269-Alien-Dictionary/cpp-0269/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_0269) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0269 main.cpp) \ No newline at end of file diff --git a/0001-0500/0269-Alien-Dictionary/cpp-0269/main.cpp b/0001-0500/0269-Alien-Dictionary/cpp-0269/main.cpp new file mode 100644 index 00000000..dcbe23a8 --- /dev/null +++ b/0001-0500/0269-Alien-Dictionary/cpp-0269/main.cpp @@ -0,0 +1,146 @@ +/// Source : https://leetcode.com/problems/alien-dictionary/ +/// Author : liuyubobobo +/// Time : 2021-07-22 + +#include +#include +#include +#include +#include +#include + +using namespace std; + + +/// Radix Sorting + TopoSort +/// Time Complexity: O(characters number) +/// Space Complexity: O(|max_word|) +class Solution { +public: + string alienOrder(vector& words) { + + int n = words.size(); + + map> g; + for(const string& word: words) + for(char c: word) g[c]; + + vector temp(n); + if(!build_graph(words, 0, words.size() - 1, 0, g, temp)){ +// cout << "build graph failed" << endl; + return ""; + } + +// for(const pair>& p: g){ +// cout << p.first << " : "; +// for(char e: p.second) cout << e << ' '; +// cout << endl; +// } + return bfs(g); + } + +private: + string bfs(const map>& g){ + + vector indegs(26, 0); + vector alphabets(26, 0); + for(const pair>& p: g){ + alphabets[p.first - 'a'] = 1; + for(char to: p.second){ + indegs[to - 'a'] ++; + alphabets[to - 'a'] = 1; + } + } + + queue q; + vector visited(26, false); + for(int i = 0; i < 26; i ++) + if(alphabets[i] && indegs[i] == 0){ + q.push((char)('a' + i)); + visited[i] = true; + } + + string res = ""; + while(!q.empty()){ + char cur = q.front(); + q.pop(); + + res += string(1, cur); + + if(g.count(cur) == 0) continue; + + for(char next: g.at(cur)) + if(!visited[next - 'a']){ + indegs[next - 'a'] --; + if(indegs[next - 'a'] == 0){ + q.push(next); + visited[next - 'a'] = true; + } + } + } + return res.size() == accumulate(alphabets.begin(), alphabets.end(), 0) ? res : ""; + } + + bool build_graph(const vector& words, int l, int r, int index, + map>& g, vector& temp){ + + if(l >= r) return true; + + bool all_empty = true; + for(int i = l; i <= r; i ++) + if(index >= words[i].size()) temp[i] = ' '; + else{ + temp[i] = words[i][index]; + all_empty = false; + } + + if(all_empty) return true; + + vector order; + for(int start = l, i = l + 1; i <= r + 1; i ++) + if(i == r + 1 || temp[i] != temp[start]){ + if(temp[start] != ' ' && find(order.begin(), order.end(), temp[start]) != order.end()) + return false; + + if(temp[start] == ' ' && index && order.size()) return false; + + order.push_back(temp[start]); + if(!build_graph(words, start, i - 1, index + 1, g, temp)) + return false; + start = i; + i = start; + } + + for(int i = 0; i < order.size(); i ++) + for(int j = i + 1; j < order.size(); j ++) + if(order[i] != ' ' && order[j] != ' ') + g[order[i]].insert(order[j]); + return true; + } +}; + + +int main() { + + vector words1 = {"wrt","wrf","er","ett","rftt"}; + cout << Solution().alienOrder(words1) << endl; + // wertf + + vector words2 = {"z","x"}; + cout << Solution().alienOrder(words2) << endl; + // zx + + vector words3 = {"z","x", "z"}; + cout << Solution().alienOrder(words3) << endl; + // "" + + vector words4 = {"z","z"}; + cout << Solution().alienOrder(words4) << endl; + // "z" + + vector words5 = {"abc","ab"}; + cout << Solution().alienOrder(words5) << endl; + // "" + + return 0; +} diff --git a/0001-0500/0273-Integer-to-English-Words/cpp-0273/CMakeLists.txt b/0001-0500/0273-Integer-to-English-Words/cpp-0273/CMakeLists.txt new file mode 100644 index 00000000..6d6cbbf3 --- /dev/null +++ b/0001-0500/0273-Integer-to-English-Words/cpp-0273/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0273) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0273 main.cpp) diff --git a/0001-0500/0273-Integer-to-English-Words/cpp-0273/main.cpp b/0001-0500/0273-Integer-to-English-Words/cpp-0273/main.cpp new file mode 100644 index 00000000..8259270e --- /dev/null +++ b/0001-0500/0273-Integer-to-English-Words/cpp-0273/main.cpp @@ -0,0 +1,102 @@ +/// Source : https://leetcode.com/problems/integer-to-english-words/ +/// Author : liuyubobobo +/// Time : 2021-10-10 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(log(num)) +/// Space Complexity: O(1) +class Solution { + +private: + const string nums[20] = { + "Zero", "One", "Two", "Three", "Four", + "Five", "Six", "Seven", "Eight", "Nine", + "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", + "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" + }; + const string nums10[10] = { + "Zero", "Ten", "Twenty", "Thirty", "Forty", + "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" + }; + +public: + string numberToWords(int num) { + + if(num == 0) return "Zero"; + + vector segs; + while(num){ + segs.push_back(num % 1000); + num /= 1000; + } + + string res = ""; + for(int i = segs.size() - 1; i >= 0; i --){ + res += numberToWords(segs[i], i); + while(res.back() == ' ') res.pop_back(); + res += " "; + } + res.pop_back(); + return res; + } + +private: + string numberToWords(int num, int p){ + + if(num == 0) return ""; + + string res = ""; + if(num >= 100) { + res += nums[num / 100] + " Hundred "; + num %= 100; + } + + if(num > 0){ + if(num < 20) res += nums[num] + " "; + else{ + res += nums10[num / 10] + " "; + num %= 10; + if(num > 0) res += nums[num] + " "; + } + } + + if(p == 1) res += "Thousand"; + if(p == 2) res += "Million"; + if(p == 3) res += "Billion"; + + return res; + } +}; + + +int main() { + + cout << Solution().numberToWords(123) << endl; + // One Hundred Twenty Three + + cout << Solution().numberToWords(12345) << endl; + // Twelve Thousand Three Hundred Forty Five + + cout << Solution().numberToWords(1234567) << endl; + // One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven + + cout << Solution().numberToWords(1234567891) << endl; + // One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One + + cout << Solution().numberToWords(1000) << endl; + // One Thousand + + cout << Solution().numberToWords(1000000) << endl; + // One Million + + cout << Solution().numberToWords(1000010) << endl; + // One Million Ten + + return 0; +} diff --git a/0001-0500/0274-H-Index/cpp-0274/CMakeLists.txt b/0001-0500/0274-H-Index/cpp-0274/CMakeLists.txt new file mode 100644 index 00000000..6315043b --- /dev/null +++ b/0001-0500/0274-H-Index/cpp-0274/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_0274) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0274 main.cpp) \ No newline at end of file diff --git a/0001-0500/0274-H-Index/cpp-0274/main.cpp b/0001-0500/0274-H-Index/cpp-0274/main.cpp new file mode 100644 index 00000000..e0b9a2c3 --- /dev/null +++ b/0001-0500/0274-H-Index/cpp-0274/main.cpp @@ -0,0 +1,36 @@ +/// Source : https://leetcode.com/problems/h-index/ +/// Author : liuyubobobo +/// Time : 2021-07-10 + +#include +#include + +using namespace std; + + +/// Sorintg and Binary Search +/// Time Complexity: O(max_v * logn) +/// Sapce Complexity: O(1) +class Solution { +public: + int hIndex(vector& citations) { + + sort(citations.begin(), citations.end()); + + for(int h = citations.back(); h >= 0; h --){ + int x = citations.end() - lower_bound(citations.begin(), citations.end(), h); + if(x >= h) return h; + } + assert(false); + return -1; + } +}; + +int main() { + + vector citations1 = {100}; + cout << Solution().hIndex(citations1) << endl; + // 1 + + return 0; +} diff --git a/0001-0500/0275-H-Index-II/cpp-0275/CMakeLists.txt b/0001-0500/0275-H-Index-II/cpp-0275/CMakeLists.txt new file mode 100644 index 00000000..337b68bc --- /dev/null +++ b/0001-0500/0275-H-Index-II/cpp-0275/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_0275) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0275 main.cpp) \ No newline at end of file diff --git a/0001-0500/0275-H-Index-II/cpp-0275/main.cpp b/0001-0500/0275-H-Index-II/cpp-0275/main.cpp new file mode 100644 index 00000000..93f183d5 --- /dev/null +++ b/0001-0500/0275-H-Index-II/cpp-0275/main.cpp @@ -0,0 +1,31 @@ +/// Source : https://leetcode.com/problems/h-index-ii/ +/// Author : liuyubobobo +/// Time : 2021-07-11 + +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(maxv * logn) +/// Space Complexity: O(1) +class Solution { +public: + int hIndex(vector& citations) { + + for(int h = citations.back(); h >= 0; h --){ + int x = citations.end() - lower_bound(citations.begin(), citations.end(), h); + if(x >= h) return h; + } + assert(false); + return -1; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0276-Paint-Fence/cpp-0276/CMakeLists.txt b/0001-0500/0276-Paint-Fence/cpp-0276/CMakeLists.txt new file mode 100644 index 00000000..03604367 --- /dev/null +++ b/0001-0500/0276-Paint-Fence/cpp-0276/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0276) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0276 main.cpp) diff --git a/0001-0500/0276-Paint-Fence/cpp-0276/main.cpp b/0001-0500/0276-Paint-Fence/cpp-0276/main.cpp new file mode 100644 index 00000000..f68053e8 --- /dev/null +++ b/0001-0500/0276-Paint-Fence/cpp-0276/main.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/paint-fence/ +/// Author : liuyubobobo +/// Time : 2021-08-09 + +#include +#include + +using namespace std; + + +/// Memoization +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int numWays(int n, int k) { + + vector> dp(2, vector(n, -1)); + return k * dfs(n, k, 1, false, dp); + } + +private: + int dfs(const int n, const int k, int index, bool same, + vector>& dp){ + + if(index == n) return 1; + if(dp[same][index] != -1) return dp[same][index]; + + int res = 0; + if(same) res += (k - 1) * dfs(n, k, index + 1, false, dp); + else{ + res += (k - 1) * dfs(n, k, index + 1, false, dp); + res += dfs(n, k, index + 1, true, dp); + } + return dp[same][index] = res; + } +}; + + +int main() { + + cout << Solution().numWays(3, 2) << endl; + // 6 + + cout << Solution().numWays(1, 1) << endl; + // 1 + + cout << Solution().numWays(7, 2) << endl; + // 42 + + return 0; +} diff --git a/0001-0500/0277-Find-the-Celebrity/cpp-0277/CMakeLists.txt b/0001-0500/0277-Find-the-Celebrity/cpp-0277/CMakeLists.txt new file mode 100644 index 00000000..4cfdfe13 --- /dev/null +++ b/0001-0500/0277-Find-the-Celebrity/cpp-0277/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0277) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0277 main.cpp) \ No newline at end of file diff --git a/0001-0500/0277-Find-the-Celebrity/cpp-0277/main.cpp b/0001-0500/0277-Find-the-Celebrity/cpp-0277/main.cpp new file mode 100644 index 00000000..c693028c --- /dev/null +++ b/0001-0500/0277-Find-the-Celebrity/cpp-0277/main.cpp @@ -0,0 +1,36 @@ +/// Source : https://leetcode.com/problems/find-the-celebrity/ +/// Author : liuyubobobo +/// Time : 2021-02-22 + +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n^2) +/// Space Complexity: O(1) +bool knows(int a, int b); + +class Solution { +public: + int findCelebrity(int n) { + + for(int i = 0; i < n; i ++){ + bool ok = true; + for(int j = 0; j < n; j ++) + if(j != i){ + if(!knows(j, i)){ok = false; break;} + if(knows(i, j)){ok = false; break;} + } + if(ok) return i; + } + return -1; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0278-First-Bad-Version/cpp-0278/CMakeLists.txt b/0001-0500/0278-First-Bad-Version/cpp-0278/CMakeLists.txt new file mode 100644 index 00000000..4a1099f4 --- /dev/null +++ b/0001-0500/0278-First-Bad-Version/cpp-0278/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_0278) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0278 main.cpp) \ No newline at end of file diff --git a/0001-0500/0278-First-Bad-Version/cpp-0278/main.cpp b/0001-0500/0278-First-Bad-Version/cpp-0278/main.cpp new file mode 100644 index 00000000..451691e3 --- /dev/null +++ b/0001-0500/0278-First-Bad-Version/cpp-0278/main.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/first-bad-version/ +/// Author : liuyubobobo +/// Time : 2021-06-12 + +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(logn) +/// Space Complexity: O(1) + +// The API isBadVersion is defined for you. +bool isBadVersion(int version); + +class Solution { +public: + int firstBadVersion(int n) { + + int l = 1, r = n; + while(l < r){ + int mid = l + (r - l) / 2; + if(isBadVersion(mid)) r = mid; + else l = mid + 1; + } + return l; + } +}; + + +int main() { + + return 0; +} diff --git a/0279-Perfect-Squares/cpp-0279/CMakeLists.txt b/0001-0500/0279-Perfect-Squares/cpp-0279/CMakeLists.txt similarity index 100% rename from 0279-Perfect-Squares/cpp-0279/CMakeLists.txt rename to 0001-0500/0279-Perfect-Squares/cpp-0279/CMakeLists.txt diff --git a/0279-Perfect-Squares/cpp-0279/main.cpp b/0001-0500/0279-Perfect-Squares/cpp-0279/main.cpp similarity index 100% rename from 0279-Perfect-Squares/cpp-0279/main.cpp rename to 0001-0500/0279-Perfect-Squares/cpp-0279/main.cpp diff --git a/0279-Perfect-Squares/cpp-0279/main2.cpp b/0001-0500/0279-Perfect-Squares/cpp-0279/main2.cpp similarity index 100% rename from 0279-Perfect-Squares/cpp-0279/main2.cpp rename to 0001-0500/0279-Perfect-Squares/cpp-0279/main2.cpp diff --git a/0279-Perfect-Squares/cpp-0279/main3.cpp b/0001-0500/0279-Perfect-Squares/cpp-0279/main3.cpp similarity index 100% rename from 0279-Perfect-Squares/cpp-0279/main3.cpp rename to 0001-0500/0279-Perfect-Squares/cpp-0279/main3.cpp diff --git a/0279-Perfect-Squares/java-0279/src/Solution1.java b/0001-0500/0279-Perfect-Squares/java-0279/src/Solution1.java similarity index 100% rename from 0279-Perfect-Squares/java-0279/src/Solution1.java rename to 0001-0500/0279-Perfect-Squares/java-0279/src/Solution1.java diff --git a/0279-Perfect-Squares/java-0279/src/Solution2.java b/0001-0500/0279-Perfect-Squares/java-0279/src/Solution2.java similarity index 100% rename from 0279-Perfect-Squares/java-0279/src/Solution2.java rename to 0001-0500/0279-Perfect-Squares/java-0279/src/Solution2.java diff --git a/0279-Perfect-Squares/java-0279/src/Solution3.java b/0001-0500/0279-Perfect-Squares/java-0279/src/Solution3.java similarity index 100% rename from 0279-Perfect-Squares/java-0279/src/Solution3.java rename to 0001-0500/0279-Perfect-Squares/java-0279/src/Solution3.java diff --git a/0001-0500/0280-Wiggle-Sort/cpp-0280/CMakeLists.txt b/0001-0500/0280-Wiggle-Sort/cpp-0280/CMakeLists.txt new file mode 100644 index 00000000..e8dbab7b --- /dev/null +++ b/0001-0500/0280-Wiggle-Sort/cpp-0280/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_0280) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_0280 main.cpp) diff --git a/0001-0500/0280-Wiggle-Sort/cpp-0280/main.cpp b/0001-0500/0280-Wiggle-Sort/cpp-0280/main.cpp new file mode 100644 index 00000000..3ed1b191 --- /dev/null +++ b/0001-0500/0280-Wiggle-Sort/cpp-0280/main.cpp @@ -0,0 +1,29 @@ +/// Source : https://leetcode.com/problems/wiggle-sort/description/ +/// Author : liuyubobobo +/// Time : 2023-02-08 + +#include +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + void wiggleSort(vector& nums) { + + sort(nums.begin(), nums.end()); + for(int i = 1; i + 1 < nums.size(); i += 2) + swap(nums[i], nums[i + 1]); + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0282-Expression-Add-Operators/cpp-0282/CMakeLists.txt b/0001-0500/0282-Expression-Add-Operators/cpp-0282/CMakeLists.txt new file mode 100644 index 00000000..8d3dbe00 --- /dev/null +++ b/0001-0500/0282-Expression-Add-Operators/cpp-0282/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0282) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0282 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0282-Expression-Add-Operators/cpp-0282/main.cpp b/0001-0500/0282-Expression-Add-Operators/cpp-0282/main.cpp new file mode 100644 index 00000000..5ae5c47f --- /dev/null +++ b/0001-0500/0282-Expression-Add-Operators/cpp-0282/main.cpp @@ -0,0 +1,121 @@ +/// Source : https://leetcode.com/problems/expression-add-operators/description/ +/// Author : liuyubobobo +/// Time : 2018-09-03 + +#include +#include +#include +#include + +using namespace std; + + +/// Backtracking to split num and eval +/// The eval function comes from Leetcode 227 +/// https://leetcode.com/problems/basic-calculator-ii/description/ +/// +/// Time Complexity: O(n*3^n) +/// Space Complexity: O(3^n) +class Solution { +public: + vector addOperators(string num, int target) { + + if(num == "") + return {}; + vector ret; + split(num, 0, target, "", ' ', -1, 0ll, ret); + return ret; + } + +private: + void split(const string& num, int index, int target, const string& expr, + char lastop, long long pre, long long res, vector& ret){ + + if(index == num.size()){ + if(res == (long long)target) + ret.push_back(expr); + return; + } + + int end = num.size(); + if(num[index] == '0') + end = index + 1; + + for(int i = index + 1; i <= end; i ++){ + int len = i - index; + string cur_num_s = num.substr(index, len); + long long cur = atoll(cur_num_s.c_str()); + + char next_lastop = ' '; + long long next_pre = cur; + long long next_res = res; + + if(expr != "" && expr[expr.size() - 1] == '*' && (lastop == '+' || lastop == '-')){ + assert(pre != -1); + if(lastop == '+') + next_res -= pre, next_res += pre * cur; + else + next_res += pre, next_res -= pre * cur; + next_pre = pre * cur; + next_lastop = lastop; + } + else if(expr != ""){ + switch(expr[expr.size() - 1]){ + case '+': next_res += cur; break; + case '-': next_res -= cur; break; + case '*': next_res *= cur; break; + default:assert(false); break; + } + next_lastop = expr[expr.size() - 1]; + } + else + next_res = cur; + + if(index + len == num.size()) + split(num, index + len, target, expr + cur_num_s, + ' ', next_pre, next_res, ret); + else{ + split(num, index + len, target, expr + cur_num_s + "*", + next_lastop, next_pre, next_res, ret); + split(num, index + len, target, expr + cur_num_s + "+", + next_lastop, next_pre, next_res, ret); + split(num, index + len, target, expr + cur_num_s + "-", + next_lastop, next_pre, next_res, ret); + } + } + } +}; + + +void print_vec(const vector& vec){ + cout << "[ "; + for(const string& e: vec) + cout << e << " "; + cout << "]" << endl; +} + +int main() { + + string nums1 = "123"; + print_vec(Solution().addOperators(nums1, 6)); //2 + + string nums2 = "232"; + print_vec(Solution().addOperators(nums2, 8)); // 2 + + string nums3 = "105"; + print_vec(Solution().addOperators(nums3, 5)); // 2 + + string nums4 = "00"; + print_vec(Solution().addOperators(nums4, 0)); // 3 + + string nums5 = "3456237490"; + print_vec(Solution().addOperators(nums5, 9191)); // 0 + + string nums6 = "2147483647"; + print_vec(Solution().addOperators(nums6, 2147483647)); // 1 + + string nums7 = "2147483648"; + print_vec(Solution().addOperators(nums7, -2147483648)); // 0 + + return 0; +} \ No newline at end of file diff --git a/0283-Move-Zeroes/cpp-0283/CMakeLists.txt b/0001-0500/0283-Move-Zeroes/cpp-0283/CMakeLists.txt similarity index 100% rename from 0283-Move-Zeroes/cpp-0283/CMakeLists.txt rename to 0001-0500/0283-Move-Zeroes/cpp-0283/CMakeLists.txt diff --git a/0283-Move-Zeroes/cpp-0283/main.cpp b/0001-0500/0283-Move-Zeroes/cpp-0283/main.cpp similarity index 100% rename from 0283-Move-Zeroes/cpp-0283/main.cpp rename to 0001-0500/0283-Move-Zeroes/cpp-0283/main.cpp diff --git a/0283-Move-Zeroes/cpp-0283/main2.cpp b/0001-0500/0283-Move-Zeroes/cpp-0283/main2.cpp similarity index 100% rename from 0283-Move-Zeroes/cpp-0283/main2.cpp rename to 0001-0500/0283-Move-Zeroes/cpp-0283/main2.cpp diff --git a/0283-Move-Zeroes/cpp-0283/main3.cpp b/0001-0500/0283-Move-Zeroes/cpp-0283/main3.cpp similarity index 100% rename from 0283-Move-Zeroes/cpp-0283/main3.cpp rename to 0001-0500/0283-Move-Zeroes/cpp-0283/main3.cpp diff --git a/0283-Move-Zeroes/cpp-0283/main4.cpp b/0001-0500/0283-Move-Zeroes/cpp-0283/main4.cpp similarity index 100% rename from 0283-Move-Zeroes/cpp-0283/main4.cpp rename to 0001-0500/0283-Move-Zeroes/cpp-0283/main4.cpp diff --git a/0283-Move-Zeroes/java-0283/src/Solution1.java b/0001-0500/0283-Move-Zeroes/java-0283/src/Solution1.java similarity index 100% rename from 0283-Move-Zeroes/java-0283/src/Solution1.java rename to 0001-0500/0283-Move-Zeroes/java-0283/src/Solution1.java diff --git a/0283-Move-Zeroes/java-0283/src/Solution2.java b/0001-0500/0283-Move-Zeroes/java-0283/src/Solution2.java similarity index 100% rename from 0283-Move-Zeroes/java-0283/src/Solution2.java rename to 0001-0500/0283-Move-Zeroes/java-0283/src/Solution2.java diff --git a/0283-Move-Zeroes/java-0283/src/Solution3.java b/0001-0500/0283-Move-Zeroes/java-0283/src/Solution3.java similarity index 100% rename from 0283-Move-Zeroes/java-0283/src/Solution3.java rename to 0001-0500/0283-Move-Zeroes/java-0283/src/Solution3.java diff --git a/0283-Move-Zeroes/java-0283/src/Solution4.java b/0001-0500/0283-Move-Zeroes/java-0283/src/Solution4.java similarity index 100% rename from 0283-Move-Zeroes/java-0283/src/Solution4.java rename to 0001-0500/0283-Move-Zeroes/java-0283/src/Solution4.java diff --git a/0001-0500/0284-Peeking-Iterator/cpp-0284/CMakeLists.txt b/0001-0500/0284-Peeking-Iterator/cpp-0284/CMakeLists.txt new file mode 100644 index 00000000..0f42228f --- /dev/null +++ b/0001-0500/0284-Peeking-Iterator/cpp-0284/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0284) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0284 main.cpp) \ No newline at end of file diff --git a/0001-0500/0284-Peeking-Iterator/cpp-0284/main.cpp b/0001-0500/0284-Peeking-Iterator/cpp-0284/main.cpp new file mode 100644 index 00000000..60bec395 --- /dev/null +++ b/0001-0500/0284-Peeking-Iterator/cpp-0284/main.cpp @@ -0,0 +1,74 @@ +/// Source : https://leetcode.com/problems/peeking-iterator/ +/// Author : liuyubobobo +/// Time : 2021-02-08 + +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(1) for every method +/// Space Complexity: O(1) + +/// Below is the interface for Iterator, which is already defined for you. +/// **DO NOT** modify the interface for Iterator. +class Iterator { + +public: + struct Data; + Data* data; + + Iterator(const vector& nums); + Iterator(const Iterator& iter); + + // Returns the next element in the iteration. + int next(); + + // Returns true if the iteration has more elements. + bool hasNext() const; +}; + +class PeekingIterator : public Iterator { + +private: + int p_value = -1; + bool p_has_value; + +public: + PeekingIterator(const vector& nums) : Iterator(nums) { + // Initialize any member here. + // **DO NOT** save a copy of nums and manipulate it directly. + // You should only use the Iterator interface methods. + + p_has_value = Iterator::hasNext(); + if(p_has_value) + p_value = Iterator::next(); + } + + // Returns the next element in the iteration without advancing the iterator. + int peek() { + return p_value; + } + + // hasNext() and next() should behave the same as in the Iterator interface. + // Override them if needed. + int next() { + int ret = p_value; + p_has_value = Iterator::hasNext(); + if(p_has_value) + p_value = Iterator::next(); + return ret; + } + + bool hasNext() const { + return p_has_value; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0285-Inorder-Successor-in-BST/cpp-0285/CMakeLists.txt b/0001-0500/0285-Inorder-Successor-in-BST/cpp-0285/CMakeLists.txt new file mode 100644 index 00000000..96a88132 --- /dev/null +++ b/0001-0500/0285-Inorder-Successor-in-BST/cpp-0285/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0285) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0285 main.cpp) \ No newline at end of file diff --git a/0001-0500/0285-Inorder-Successor-in-BST/cpp-0285/main.cpp b/0001-0500/0285-Inorder-Successor-in-BST/cpp-0285/main.cpp new file mode 100644 index 00000000..f766b39b --- /dev/null +++ b/0001-0500/0285-Inorder-Successor-in-BST/cpp-0285/main.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/inorder-successor-in-bst/ +/// Author : liuyubobobo +/// Time : 2021-04-08 + +#include +#include + +using namespace std; + + + +/// Inorder DFS and using array to store all elements +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// 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* inorderSuccessor(TreeNode* root, TreeNode* p) { + + vector v; + inorder(root, v); + + for(int i = 1; i < v.size(); i ++) + if(v[i - 1] == p) return v[i]; + + return nullptr; + } + +private: + void inorder(TreeNode* node, vector& v){ + + if(!node) return; + + inorder(node->left, v); + v.push_back(node); + inorder(node->right, v); + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0286-Walls-and-Gates/cpp-0286/CMakeLists.txt b/0001-0500/0286-Walls-and-Gates/cpp-0286/CMakeLists.txt new file mode 100644 index 00000000..d3baaebd --- /dev/null +++ b/0001-0500/0286-Walls-and-Gates/cpp-0286/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0286) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0286 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0286-Walls-and-Gates/cpp-0286/main.cpp b/0001-0500/0286-Walls-and-Gates/cpp-0286/main.cpp new file mode 100644 index 00000000..bf8a9a6a --- /dev/null +++ b/0001-0500/0286-Walls-and-Gates/cpp-0286/main.cpp @@ -0,0 +1,77 @@ +/// Source : https://leetcode.com/problems/walls-and-gates/description/ +/// Author : liuyubobobo +/// Time : 2018-08-25 +/// Updated: 2019-06-12 + +#include +#include +#include + +using namespace std; + + +/// BFS +/// Time Complexity: O(n*m) +/// Space Complexity: O(n*m) +class Solution { + +private: + const int d[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; + int m, n; + + const int GATE = 0; + const int EMPTY = INT_MAX; + const int WALL = -1; + +public: + void wallsAndGates(vector>& rooms) { + + m = rooms.size(); + if(m == 0) + return; + n = rooms[0].size(); + + bfs(rooms); + return; + } + +private: + void bfs(vector>& rooms){ + + queue, int>> q; + for(int i = 0; i < m; i ++) + for(int j = 0; j < n; j ++) + if(rooms[i][j] == GATE) + q.push(make_pair(make_pair(i, j), 0)); + + vector> visited(m, vector(n, false)); + + while(!q.empty()){ + int curx = q.front().first.first; + int cury = q.front().first.second; + int step = q.front().second; + q.pop(); + + rooms[curx][cury] = step; + for(int i = 0; i < 4; i ++){ + int newX = curx + d[i][0]; + int newY = cury + d[i][1]; + if(inArea(newX, newY) && !visited[newX][newY] && rooms[newX][newY] == EMPTY){ + visited[newX][newY] = true; + rooms[newX][newY] = step + 1; + q.push(make_pair(make_pair(newX, newY), step + 1)); + } + } + } + } + + bool inArea(int x, int y){ + return x >= 0 && x < m && y >= 0 && y < n; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0287-Find-the-Duplicate-Number/cpp-0287/CMakeLists.txt b/0001-0500/0287-Find-the-Duplicate-Number/cpp-0287/CMakeLists.txt similarity index 100% rename from 0287-Find-the-Duplicate-Number/cpp-0287/CMakeLists.txt rename to 0001-0500/0287-Find-the-Duplicate-Number/cpp-0287/CMakeLists.txt diff --git a/0287-Find-the-Duplicate-Number/cpp-0287/main.cpp b/0001-0500/0287-Find-the-Duplicate-Number/cpp-0287/main.cpp similarity index 100% rename from 0287-Find-the-Duplicate-Number/cpp-0287/main.cpp rename to 0001-0500/0287-Find-the-Duplicate-Number/cpp-0287/main.cpp diff --git a/old/0288 Unique Word Abbreviation/cpp-Unique-Word-Abbreviation/CMakeLists.txt b/0001-0500/0288-Unique-Word-Abbreviation/cpp-0288/CMakeLists.txt similarity index 100% rename from old/0288 Unique Word Abbreviation/cpp-Unique-Word-Abbreviation/CMakeLists.txt rename to 0001-0500/0288-Unique-Word-Abbreviation/cpp-0288/CMakeLists.txt diff --git a/0001-0500/0288-Unique-Word-Abbreviation/cpp-0288/main.cpp b/0001-0500/0288-Unique-Word-Abbreviation/cpp-0288/main.cpp new file mode 100644 index 00000000..0d66bb5c --- /dev/null +++ b/0001-0500/0288-Unique-Word-Abbreviation/cpp-0288/main.cpp @@ -0,0 +1,66 @@ +/// Source : https://leetcode.com/problems/unique-word-abbreviation/ +/// Author : liuyubobobo +/// Time : 2018-08-13 + +#include +#include +#include +#include +#include +#include +#include + +using namespace std; + +/// Brute Force +/// Iterate all words in dictionary to see isUnique +/// Time Complexity: init : O(n) +/// isUnique : O(n) +/// Space Complexity: O(n) +class ValidWordAbbr { + +private: + unordered_set words; + +public: + ValidWordAbbr(vector dictionary): + words(dictionary.begin(), dictionary.end()) {} + + bool isUnique(string word) { + + for(const string& e: words){ + if(e == word) + continue; + + int l = e.size(); + if(l == word.size() && e[0] == word[0] && e[l - 1] == word[l - 1]) + return false; + } + return true; + } +}; + + +void print_bool(bool res){ + cout << (res ? "True" : "False") << endl; +} + +int main() { + + vector dictionary; + dictionary.push_back("deer"); + dictionary.push_back("door"); + dictionary.push_back("cake"); + dictionary.push_back("card"); + dictionary.push_back("hello"); + + ValidWordAbbr vwa(dictionary); + + print_bool(vwa.isUnique("dear")); + print_bool(vwa.isUnique("cart")); + print_bool(vwa.isUnique("cane")); + print_bool(vwa.isUnique("make")); + print_bool(vwa.isUnique("hello")); + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0288-Unique-Word-Abbreviation/cpp-0288/main2.cpp b/0001-0500/0288-Unique-Word-Abbreviation/cpp-0288/main2.cpp new file mode 100644 index 00000000..26dde001 --- /dev/null +++ b/0001-0500/0288-Unique-Word-Abbreviation/cpp-0288/main2.cpp @@ -0,0 +1,103 @@ +/// Source : https://leetcode.com/problems/unique-word-abbreviation/ +/// Author : liuyubobobo +/// Time : 2016-12-03 + +#include +#include +#include +#include +#include +#include +#include + +using namespace std; + +/// Using HashMap +/// The tricky part here is that we need another set to store all the different words. +/// For function isUnique, we need to see: +/// - The dictionary doesn't contain the word, then it's unique +/// - The dictionary contains exactly the same word, +/// and no aother word's abbreviation is the same, then it's unique (tricky) +/// - The dictionary contains other words have the same abbreviation, +/// then it's not unique. +/// +/// Time Complexity: +/// If there are n words and the longest word contains slen character, then +/// the building time : O(n*slen) +/// isUnique : O(slen) +/// Space Complexity: O(n) +class ValidWordAbbr { + +private: + unordered_set words; + unordered_map abbr_words; + + string abbr(const string &word){ + + //assert( word.size() >= 2 ); + + // According to the test cases, + // If a word's length is less than 2, + // Then the abbreviation is itself. + if(word.size() <= 2) + return word; + + int num = word.substr(1, word.size() - 2).size(); + return word[0] + to_string(num) + word[word.size()-1]; + } + +public: + ValidWordAbbr(vector dictionary) { + for(const string& word: dictionary) + if(words.find(word) == words.end()){ + words.insert(word); + abbr_words[abbr(dictionary[i])] += 1; + } + } + + bool isUnique(string word) { + if(words.find(word) == words.end()) + return abbr_words[abbr(word)] == 0; + + return abbr_words[abbr(word)] == 1; + } + + void show(){ + + cout << "words :" << endl; + for(unordered_set::iterator iter = words.begin() ; iter != words.end() ; iter ++ ) + cout << " " << *iter << endl; + + cout << "abbr_words :" << endl; + for(unordered_map::iterator iter = abbr_words.begin() ; iter != abbr_words.end() ; iter ++ ) + cout << " ( " << iter->first << " , " << iter->second << " )"< dictionary; + dictionary.push_back("deer"); + dictionary.push_back("door"); + dictionary.push_back("cake"); + dictionary.push_back("card"); + dictionary.push_back("hello"); + + ValidWordAbbr vwa(dictionary); + vwa.show(); + + print_bool(vwa.isUnique("dear")); + print_bool(vwa.isUnique("cart")); + print_bool(vwa.isUnique("cane")); + print_bool(vwa.isUnique("make")); + print_bool(vwa.isUnique("hello")); + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0289-Game-of-Life/cpp-0289/CMakeLists.txt b/0001-0500/0289-Game-of-Life/cpp-0289/CMakeLists.txt new file mode 100644 index 00000000..406a4e39 --- /dev/null +++ b/0001-0500/0289-Game-of-Life/cpp-0289/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0289) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0289 main.cpp) \ No newline at end of file diff --git a/0001-0500/0289-Game-of-Life/cpp-0289/main.cpp b/0001-0500/0289-Game-of-Life/cpp-0289/main.cpp new file mode 100644 index 00000000..43f87bd4 --- /dev/null +++ b/0001-0500/0289-Game-of-Life/cpp-0289/main.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/game-of-life/ +/// Author : liuyubobobo +/// Time : 2020-12-30 +/// Updated: 2022-04-11 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(m * n) +/// Space Complexity: O(m * n) +class Solution { + +public: + void gameOfLife(vector>& board) { + + int R = board.size(), C = board[0].size(); + vector> res(R, vector(C, 0)); + + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++){ + + int num = 0; + for(int ii = max(0, i - 1); ii <= min(i + 1, R - 1); ii ++) + for(int jj = max(0, j - 1); jj <= min(j + 1, C - 1); jj ++){ + if(ii == i && jj == j) continue; + num += board[ii][jj]; + } + + if(board[i][j]){ + if(num < 2 || num > 3) res[i][j] = 0; + else res[i][j] = 1; + } + else{ + if(num == 3) res[i][j] = 1; + } + } + + board = res; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0290-Word-Pattern/cpp-0290/CMakeLists.txt b/0001-0500/0290-Word-Pattern/cpp-0290/CMakeLists.txt new file mode 100644 index 00000000..1dca938e --- /dev/null +++ b/0001-0500/0290-Word-Pattern/cpp-0290/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0290) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main2.cpp) +add_executable(cpp_0290 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0290-Word-Pattern/cpp-0290/main.cpp b/0001-0500/0290-Word-Pattern/cpp-0290/main.cpp new file mode 100644 index 00000000..f6cc802b --- /dev/null +++ b/0001-0500/0290-Word-Pattern/cpp-0290/main.cpp @@ -0,0 +1,84 @@ +/// Source : https://leetcode.com/problems/word-pattern/description/ +/// Author : liuyubobobo +/// Time : 2018-07-03 + +#include +#include +#include +#include + +using namespace std; + + +/// HashMap +/// TimeComplexity: O(n) +/// Space Complexity: O(n) +class Solution { + +public: + bool wordPattern(string pattern, string str) { + + vector words = split(str); + if(pattern.size() != words.size()) + return false; + + unordered_map map1; + unordered_map map2; + for(int i = 0 ; i < pattern.size() ; i++) + if(map1.find(pattern[i]) == map1.end()){ + if(map2.find(words[i]) != map2.end()) + return false; + map1[pattern[i]] = words[i]; + map2[words[i]] = pattern[i]; + } + else{ + string s = map1[pattern[i]]; + if(s != words[i]) + return false; + } + + return true; + } + +private: + vector split(const string& s){ + + vector res; + int start = 0; + for(int i = start + 1 ; i <= s.size() ; ) + if(i == s.size() || s[i] == ' '){ + res.push_back(s.substr(start, i - start)); + start = i + 1; + i = start + 1; + } + else + i ++; + return res; + } +}; + + +void print_bool(bool res){ + cout << (res ? "True" : "False") << endl; +} + +int main() { + + string pattern1 = "abba"; + string str1 = "dog cat cat dog"; + print_bool(Solution().wordPattern(pattern1, str1)); + + string pattern2 = "abba"; + string str2 = "dog cat cat fish"; + print_bool(Solution().wordPattern(pattern2, str2)); + + string pattern3 = "aaaa"; + string str3 = "dog cat cat dog"; + print_bool(Solution().wordPattern(pattern3, str3)); + + string pattern4 = "abba"; + string str4 = "dog dog dog dog"; + print_bool(Solution().wordPattern(pattern4, str4)); + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0290-Word-Pattern/cpp-0290/main2.cpp b/0001-0500/0290-Word-Pattern/cpp-0290/main2.cpp new file mode 100644 index 00000000..260e166d --- /dev/null +++ b/0001-0500/0290-Word-Pattern/cpp-0290/main2.cpp @@ -0,0 +1,85 @@ +/// Source : https://leetcode.com/problems/word-pattern/description/ +/// Author : liuyubobobo +/// Time : 2018-07-03 + +#include +#include +#include +#include + +using namespace std; + + +/// HashMap to record the position of each character in pattern and word in str +/// TimeComplexity: O(n) +/// Space Complexity: O(n) +class Solution { + +public: + bool wordPattern(string pattern, string str) { + + vector words = split(str); + if(pattern.size() != words.size()) + return false; + + unordered_map map1; + unordered_map map2; + for(int i = 0 ; i < pattern.size() ; i++){ + unordered_map::iterator iter1 = map1.find(pattern[i]); + unordered_map::iterator iter2 = map2.find(words[i]); + + int i1 = (iter1 == map1.end() ? -1 : map1[pattern[i]]); + int i2 = (iter2 == map2.end() ? -1 : map2[words[i]]); + + if(i1 != i2) + return false; + + map1[pattern[i]] = i; + map2[words[i]] = i; + } + + return true; + } + +private: + vector split(const string& s){ + + vector res; + int start = 0; + for(int i = start + 1 ; i <= s.size() ; ) + if(i == s.size() || s[i] == ' '){ + res.push_back(s.substr(start, i - start)); + start = i + 1; + i = start + 1; + } + else + i ++; + return res; + } +}; + + +void print_bool(bool res){ + cout << (res ? "True" : "False") << endl; +} + +int main() { + + string pattern1 = "abba"; + string str1 = "dog cat cat dog"; + print_bool(Solution().wordPattern(pattern1, str1)); + + string pattern2 = "abba"; + string str2 = "dog cat cat fish"; + print_bool(Solution().wordPattern(pattern2, str2)); + + string pattern3 = "aaaa"; + string str3 = "dog cat cat dog"; + print_bool(Solution().wordPattern(pattern3, str3)); + + string pattern4 = "abba"; + string str4 = "dog dog dog dog"; + print_bool(Solution().wordPattern(pattern4, str4)); + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0292-Nim-Game/cpp-0292/CMakeLists.txt b/0001-0500/0292-Nim-Game/cpp-0292/CMakeLists.txt new file mode 100644 index 00000000..82169e08 --- /dev/null +++ b/0001-0500/0292-Nim-Game/cpp-0292/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0292) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0292 main.cpp) diff --git a/0001-0500/0292-Nim-Game/cpp-0292/main.cpp b/0001-0500/0292-Nim-Game/cpp-0292/main.cpp new file mode 100644 index 00000000..68ef7b03 --- /dev/null +++ b/0001-0500/0292-Nim-Game/cpp-0292/main.cpp @@ -0,0 +1,24 @@ +/// Source : https://leetcode.com/problems/nim-game/ +/// Author : liuyubobobo +/// Time : 2021-09-17 + +#include + +using namespace std; + + +/// Basic Nim +/// Time Complexity: O(1) +/// Space Complexity: O(1) +class Solution { +public: + bool canWinNim(int n) { + return n % 4; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0295-Find-Median-from-Data-Stream/cpp-0295/CMakeLists.txt b/0001-0500/0295-Find-Median-from-Data-Stream/cpp-0295/CMakeLists.txt new file mode 100644 index 00000000..c6cf0dd3 --- /dev/null +++ b/0001-0500/0295-Find-Median-from-Data-Stream/cpp-0295/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(cpp_0295) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0295 main3.cpp) \ No newline at end of file diff --git a/0001-0500/0295-Find-Median-from-Data-Stream/cpp-0295/main.cpp b/0001-0500/0295-Find-Median-from-Data-Stream/cpp-0295/main.cpp new file mode 100644 index 00000000..ba7cff20 --- /dev/null +++ b/0001-0500/0295-Find-Median-from-Data-Stream/cpp-0295/main.cpp @@ -0,0 +1,68 @@ +/// https://leetcode.com/problems/find-median-from-data-stream/ +/// Author : liuyubobobo +/// Time : 2019-09-22 + +#include +#include + +using namespace std; + + +/// Insertion Sort +/// Time Complexity: add: O(n) +/// findMedian: O(1) +class MedianFinder { + +private: + vector data; + +public: + /** initialize your data structure here. */ + MedianFinder() {} + + void addNum(int num) { + + data.push_back(num); + + int i; + for(i = (int)data.size() - 1; i >= 1 && data[i] > data[i - 1]; i --) + swap(data[i], data[i - 1]); + } + + double findMedian() { + + if(data.size() % 2) return data[data.size() / 2]; + return (data[data.size() / 2 - 1] + data[data.size() / 2]) / 2.0; + } +}; + + +int main() { + + MedianFinder mf; + mf.addNum(6); + cout << "after adding 6 :" << mf.findMedian() << endl; // 6 + + mf.addNum(10); + cout << "after adding 10 :" << mf.findMedian() << endl; // 8 + + mf.addNum(2); + cout << "after adding 2 :" << mf.findMedian() << endl; // 6 + + mf.addNum(6); + cout << "after adding 6 :" << mf.findMedian() << endl; // 6 + + mf.addNum(5); + cout << "after adding 5 :" << mf.findMedian() << endl; // 6 + + mf.addNum(0); + cout << "after adding 0 :" << mf.findMedian() << endl; // 5.5 + + mf.addNum(6); + cout << "after adding 6 :" << mf.findMedian() << endl; // 6.0 + + mf.addNum(3); + cout << "after adding 3 :" << mf.findMedian() << endl; // 5.5 + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0295-Find-Median-from-Data-Stream/cpp-0295/main2.cpp b/0001-0500/0295-Find-Median-from-Data-Stream/cpp-0295/main2.cpp new file mode 100644 index 00000000..26e89aec --- /dev/null +++ b/0001-0500/0295-Find-Median-from-Data-Stream/cpp-0295/main2.cpp @@ -0,0 +1,93 @@ +/// https://leetcode.com/problems/find-median-from-data-stream/ +/// Author : liuyubobobo +/// Time : 2019-09-22 + +#include +#include + +using namespace std; + + +/// Using TreeMap +/// Time Complexity: add: O(logn) +/// findMedian: O(logn) +class MedianFinder { + +private: + map data; + int count = 0; + + map::iterator iter; + int index = 0; + +public: + /** initialize your data structure here. */ + MedianFinder() {} + + void addNum(int num) { + + if(!count){ + data[num] ++; + iter = data.begin(); + count ++; + return; + } + + data[num] ++; + if(count % 2){ // odd number + if(num < iter->first){ + if(index) index --; + else iter --, index = iter->second - 1; + } + } + else{ // even number + if(num >= iter->first){ + if(index + 1 < iter->second) index ++; + else iter ++, index = 0; + } + } + count ++; + } + + double findMedian() { + + if(count % 2) return iter->first; + + if(index + 1 < iter->second) return iter->first; + + map::iterator iter2 = iter; + iter2 ++; + return (iter->first + iter2->first) / 2.0; + } +}; + + +int main() { + + MedianFinder mf; + mf.addNum(6); + cout << "after adding 6 " << mf.findMedian() << endl; // 6 + + mf.addNum(10); + cout << "after adding 10 " << mf.findMedian() << endl; // 8 + + mf.addNum(2); + cout << "after adding 2 " << mf.findMedian() << endl; // 6 + + mf.addNum(6); + cout << "after adding 6 " << mf.findMedian() << endl; // 6 + + mf.addNum(5); + cout << "after adding 5 " << mf.findMedian() << endl; // 6 + + mf.addNum(0); + cout << "after adding 0 " << mf.findMedian() << endl; // 5.5 + + mf.addNum(6); + cout << "after adding 6 " << mf.findMedian() << endl; // 6.0 + + mf.addNum(3); + cout << "after adding 3 " << mf.findMedian() << endl; // 5.5 + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0295-Find-Median-from-Data-Stream/cpp-0295/main3.cpp b/0001-0500/0295-Find-Median-from-Data-Stream/cpp-0295/main3.cpp new file mode 100644 index 00000000..2c56787e --- /dev/null +++ b/0001-0500/0295-Find-Median-from-Data-Stream/cpp-0295/main3.cpp @@ -0,0 +1,71 @@ +/// https://leetcode.com/problems/find-median-from-data-stream/ +/// Author : liuyubobobo +/// Time : 2019-09-23 + +#include +#include +#include + +using namespace std; + + +/// Two Priority Queue +/// Time Complexity: add: O(logn) +/// findMedian: O(logn) +class MedianFinder { + +private: + priority_queue left; // maxheap + priority_queue, greater> right; // minheap + +public: + /** initialize your data structure here. */ + MedianFinder() {} + + void addNum(int num) { + + if(!left.size() && !right.size()){ + left.push(num); + return; + } + + if((left.size() + right.size()) % 2){ // odd + if(num >= left.top()) right.push(num); + else{ + right.push(left.top()); + left.pop(); + left.push(num); + } + } + else{ // even + if(num <= right.top()) left.push(num); + else{ + left.push(right.top()); + right.pop(); + right.push(num); + } + } + } + + double findMedian() { + + if((left.size() + right.size()) % 2) return left.top(); + return (left.top() + right.top()) / 2.0; + } +}; + + +int main() { + + MedianFinder mf; + mf.addNum(40); + cout << "after adding 40 : " << mf.findMedian() << endl; // 40 + + mf.addNum(12); + cout << "after adding 12 : " << mf.findMedian() << endl; // 26 + + mf.addNum(16); + cout << "after adding 16 : " << mf.findMedian() << endl; // 16 + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0296-Best-Meeting-Point/cpp-0296/CMakeLists.txt b/0001-0500/0296-Best-Meeting-Point/cpp-0296/CMakeLists.txt new file mode 100644 index 00000000..63453cfb --- /dev/null +++ b/0001-0500/0296-Best-Meeting-Point/cpp-0296/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0296) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0296 main.cpp) diff --git a/0001-0500/0296-Best-Meeting-Point/cpp-0296/main.cpp b/0001-0500/0296-Best-Meeting-Point/cpp-0296/main.cpp new file mode 100644 index 00000000..26e387b4 --- /dev/null +++ b/0001-0500/0296-Best-Meeting-Point/cpp-0296/main.cpp @@ -0,0 +1,43 @@ +/// Source : https://leetcode.com/problems/best-meeting-point/ +/// Author : liuyubobobo +/// Time : 2021-09-08 + +#include +#include + +using namespace std; + + +/// deal with x and y separately in Manhattan Distance Problem +/// Time Complexity: O(mnlog(mn)) +/// Space Complexity: O(mn) +class Solution { +public: + int minTotalDistance(vector>& grid) { + + vector rows, cols; + for(int i = 0; i < grid.size(); i ++) + for(int j = 0; j < grid[i].size(); j ++) + if(grid[i][j] == 1){ + rows.push_back(i); + cols.push_back(j); + } + + sort(rows.begin(), rows.end()); + sort(cols.begin(), cols.end()); + int m = rows.size(); + + int x = rows[m / 2], y = cols[m / 2]; + + int d = 0; + for(int i = 0; i < m; i ++) + d += abs(x - rows[i]) + abs(y - cols[i]); + return d; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0297-Serialize-and-Deserialize-Binary-Tree/cpp-0297/CMakeLists.txt b/0001-0500/0297-Serialize-and-Deserialize-Binary-Tree/cpp-0297/CMakeLists.txt new file mode 100644 index 00000000..77ee4506 --- /dev/null +++ b/0001-0500/0297-Serialize-and-Deserialize-Binary-Tree/cpp-0297/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0297) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main2.cpp) +add_executable(cpp_0297 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0297-Serialize-and-Deserialize-Binary-Tree/cpp-0297/main.cpp b/0001-0500/0297-Serialize-and-Deserialize-Binary-Tree/cpp-0297/main.cpp new file mode 100644 index 00000000..4659b618 --- /dev/null +++ b/0001-0500/0297-Serialize-and-Deserialize-Binary-Tree/cpp-0297/main.cpp @@ -0,0 +1,123 @@ +/// Source : https://leetcode.com/problems/serialize-and-deserialize-binary-tree/description/ +/// Author : liuyubobobo +/// Time : 2018-09-17 + +#include +#include +#include +#include + +using namespace std; + + +/// BFS +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +class Codec { +public: + + // Encodes a tree to a single string. + string serialize(TreeNode* root) { + + if(!root) + return "[null]"; + + string ret = "["; + + queue q; + q.push(root); + ret += to_string(root->val); + while(!q.empty()){ + TreeNode* cur = q.front(); + q.pop(); + + if(cur->left){ + ret += "," + to_string(cur->left->val); + q.push(cur->left); + } + else + ret += ",null"; + + if(cur->right){ + ret += "," + to_string(cur->right->val); + q.push(cur->right); + } + else + ret += ",null"; + } + return ret + "]"; + } + + // Decodes your encoded data to tree. + TreeNode* deserialize(string data) { + vector vec = get_vector(data); + + if(vec.size() == 0 || (vec.size() == 1 && vec[0] == "null")) + return NULL; + + TreeNode* root = new TreeNode(atoi(vec[0].c_str())); + queue q; + q.push(root); + int index = 1; + while(!q.empty()){ + TreeNode* cur = q.front(); + q.pop(); + + assert(vec.size() - index >= 2); + if(vec[index] != "null"){ + cur->left = new TreeNode(atoi(vec[index].c_str())); + q.push(cur->left); + } + index ++; + + if(vec[index] != "null"){ + cur->right = new TreeNode(atoi(vec[index].c_str())); + q.push(cur->right); + } + index ++; + } + return root; + } + +private: + vector get_vector(const string& data){ + + string s = data.substr(1, data.size() - 2) + ","; + + vector res; + int i = 0; + while(i < s.size()){ + int comma = s.find(',', i); + res.push_back(s.substr(i, comma - i)); + i = comma + 1; + } + return res; + } +}; + + +int main() { + + TreeNode* root = new TreeNode(1); + root->left = new TreeNode(2); + root->right = new TreeNode(3); + root->right->left = new TreeNode(4); + root->right->right = new TreeNode(5); + + string s = Codec().serialize(root); + cout << s << endl; + + TreeNode* x = Codec().deserialize(s); + cout << Codec().serialize(x) << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0297-Serialize-and-Deserialize-Binary-Tree/cpp-0297/main2.cpp b/0001-0500/0297-Serialize-and-Deserialize-Binary-Tree/cpp-0297/main2.cpp new file mode 100644 index 00000000..3b354041 --- /dev/null +++ b/0001-0500/0297-Serialize-and-Deserialize-Binary-Tree/cpp-0297/main2.cpp @@ -0,0 +1,116 @@ +/// Source : https://leetcode.com/problems/serialize-and-deserialize-binary-tree/description/ +/// Author : liuyubobobo +/// Time : 2018-09-17 + +#include +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +class Codec { +public: + + // Encodes a tree to a single string. + string serialize(TreeNode* root) { + + if(!root) + return "[null]"; + + string ret = "["; + dfs(root, ret); + ret.pop_back(); + return ret + "]"; + } + + // Decodes your encoded data to tree. + TreeNode* deserialize(string data) { + vector vec = get_vector(data); + + if(vec.size() == 0 || (vec.size() == 1 && vec[0] == "null")) + return NULL; + +// for(const string& s: vec) +// cout << s << " "; +// cout << endl; + + int index = 0; + return dfs(vec, index); + } + +private: + TreeNode* dfs(const vector& vec, int& index){ + + if(index == vec.size() || vec[index] == "null") + return NULL; + + TreeNode* node = new TreeNode(atoi(vec[index].c_str())); + index ++; + node->left = dfs(vec, index); + + index ++; + node->right = dfs(vec, index); + + return node; + } + + void dfs(TreeNode* node, string& ret){ + + ret += to_string(node->val) + ","; + + if(node->left) + dfs(node->left, ret); + else + ret += "null,"; + + if(node->right) + dfs(node->right, ret); + else + ret += "null,"; + } + + vector get_vector(const string& data){ + + string s = data.substr(1, data.size() - 2) + ","; + + vector res; + int i = 0; + while(i < s.size()){ + int comma = s.find(',', i); + res.push_back(s.substr(i, comma - i)); + i = comma + 1; + } + return res; + } +}; + + +int main() { + + TreeNode* root = new TreeNode(1); + root->left = new TreeNode(2); + root->right = new TreeNode(3); + root->right->left = new TreeNode(4); + root->right->right = new TreeNode(5); + + string s = Codec().serialize(root); + cout << s << endl; + + TreeNode* x = Codec().deserialize(s); + cout << Codec().serialize(x) << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0298-Binary-Tree-Longest-Consecutive-Sequence/cpp-0298/CMakeLists.txt b/0001-0500/0298-Binary-Tree-Longest-Consecutive-Sequence/cpp-0298/CMakeLists.txt new file mode 100644 index 00000000..d6325186 --- /dev/null +++ b/0001-0500/0298-Binary-Tree-Longest-Consecutive-Sequence/cpp-0298/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_0298) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0298 main.cpp) \ No newline at end of file diff --git a/0001-0500/0298-Binary-Tree-Longest-Consecutive-Sequence/cpp-0298/main.cpp b/0001-0500/0298-Binary-Tree-Longest-Consecutive-Sequence/cpp-0298/main.cpp new file mode 100644 index 00000000..dbc7afb4 --- /dev/null +++ b/0001-0500/0298-Binary-Tree-Longest-Consecutive-Sequence/cpp-0298/main.cpp @@ -0,0 +1,58 @@ +/// Source : https://leetcode.com/problems/binary-tree-longest-consecutive-sequence/ +/// Author : liuyubobobo +/// Time : 2021-07-31 + +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(h) + +/// 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 { + +private: + int res = 0; + +public: + int longestConsecutive(TreeNode* root) { + + res = 0; + dfs(root, 1); + return res; + } + +private: + void dfs(TreeNode* node, int k){ + + res = max(res, k); + + if(node->left){ + if(node->left->val == node->val + 1) dfs(node->left, k + 1); + else dfs(node->left, 1); + } + + if(node->right){ + if(node->right->val == node->val + 1) dfs(node->right, k + 1); + else dfs(node->right, 1); + } + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0299-Bulls-and-Cows/cpp-0299/CMakeLists.txt b/0001-0500/0299-Bulls-and-Cows/cpp-0299/CMakeLists.txt new file mode 100644 index 00000000..5c7c1b58 --- /dev/null +++ b/0001-0500/0299-Bulls-and-Cows/cpp-0299/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0299) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0299 main.cpp) diff --git a/0001-0500/0299-Bulls-and-Cows/cpp-0299/main.cpp b/0001-0500/0299-Bulls-and-Cows/cpp-0299/main.cpp new file mode 100644 index 00000000..6679563e --- /dev/null +++ b/0001-0500/0299-Bulls-and-Cows/cpp-0299/main.cpp @@ -0,0 +1,38 @@ +/// Source : https://leetcode.com/problems/bulls-and-cows/ +/// Author : liuyubobobo +/// Time : 2021-11-07 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + string getHint(string secret, string guess) { + + int n = secret.size(); + + vector a(10, 0), b(10, 0); + int bull = 0; + for(int i = 0; i < n; i ++) + if(secret[i] == guess[i]) bull ++; + else a[secret[i] - '0'] ++, b[guess[i] - '0'] ++; + + int cow = 0; + for(int i = 0; i < 10; i ++) + cow += min(a[i], b[i]); + + return to_string(bull) + "A" + to_string(cow) + "B"; + } +}; + + +int main() { + + return 0; +} diff --git a/0300-Longest-Increasing-Subsequence/cpp-0300/CMakeLists.txt b/0001-0500/0300-Longest-Increasing-Subsequence/cpp-0300/CMakeLists.txt similarity index 100% rename from 0300-Longest-Increasing-Subsequence/cpp-0300/CMakeLists.txt rename to 0001-0500/0300-Longest-Increasing-Subsequence/cpp-0300/CMakeLists.txt diff --git a/0300-Longest-Increasing-Subsequence/cpp-0300/main.cpp b/0001-0500/0300-Longest-Increasing-Subsequence/cpp-0300/main.cpp similarity index 100% rename from 0300-Longest-Increasing-Subsequence/cpp-0300/main.cpp rename to 0001-0500/0300-Longest-Increasing-Subsequence/cpp-0300/main.cpp diff --git a/0300-Longest-Increasing-Subsequence/cpp-0300/main2.cpp b/0001-0500/0300-Longest-Increasing-Subsequence/cpp-0300/main2.cpp similarity index 100% rename from 0300-Longest-Increasing-Subsequence/cpp-0300/main2.cpp rename to 0001-0500/0300-Longest-Increasing-Subsequence/cpp-0300/main2.cpp diff --git a/0300-Longest-Increasing-Subsequence/cpp-0300/main3.cpp b/0001-0500/0300-Longest-Increasing-Subsequence/cpp-0300/main3.cpp similarity index 100% rename from 0300-Longest-Increasing-Subsequence/cpp-0300/main3.cpp rename to 0001-0500/0300-Longest-Increasing-Subsequence/cpp-0300/main3.cpp diff --git a/0300-Longest-Increasing-Subsequence/java-0300/src/Solution1.java b/0001-0500/0300-Longest-Increasing-Subsequence/java-0300/src/Solution1.java similarity index 100% rename from 0300-Longest-Increasing-Subsequence/java-0300/src/Solution1.java rename to 0001-0500/0300-Longest-Increasing-Subsequence/java-0300/src/Solution1.java diff --git a/0300-Longest-Increasing-Subsequence/java-0300/src/Solution2.java b/0001-0500/0300-Longest-Increasing-Subsequence/java-0300/src/Solution2.java similarity index 100% rename from 0300-Longest-Increasing-Subsequence/java-0300/src/Solution2.java rename to 0001-0500/0300-Longest-Increasing-Subsequence/java-0300/src/Solution2.java diff --git a/0300-Longest-Increasing-Subsequence/java-0300/src/Solution3.java b/0001-0500/0300-Longest-Increasing-Subsequence/java-0300/src/Solution3.java similarity index 100% rename from 0300-Longest-Increasing-Subsequence/java-0300/src/Solution3.java rename to 0001-0500/0300-Longest-Increasing-Subsequence/java-0300/src/Solution3.java diff --git a/0001-0500/0301-Remove-Invalid-Parentheses/cpp-0301/CMakeLists.txt b/0001-0500/0301-Remove-Invalid-Parentheses/cpp-0301/CMakeLists.txt new file mode 100644 index 00000000..c83cd1ba --- /dev/null +++ b/0001-0500/0301-Remove-Invalid-Parentheses/cpp-0301/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0301) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main2.cpp) +add_executable(cpp_0301 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0301-Remove-Invalid-Parentheses/cpp-0301/main.cpp b/0001-0500/0301-Remove-Invalid-Parentheses/cpp-0301/main.cpp new file mode 100644 index 00000000..5e9ba44f --- /dev/null +++ b/0001-0500/0301-Remove-Invalid-Parentheses/cpp-0301/main.cpp @@ -0,0 +1,106 @@ +/// Source : https://leetcode.com/problems/remove-invalid-parentheses/description/ +/// Author : liuyubobobo +/// Time : 2018-11-02 + +#include +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(2^n) +/// Space Complexity: O(n) +class Solution { + +private: + int n; + int maxlen; + +public: + vector removeInvalidParentheses(string s) { + + n = s.size(); + maxlen = 0; + + unordered_set res; + dfs(s, 0, 0, "", res); + return vector(res.begin(), res.end()); + } + +private: + void dfs(const string& s, int index, int left, const string& cur, + unordered_set& res){ + + if(index == n){ + if(left == 0){ + if(cur.size() > maxlen){ + res.clear(); + maxlen = cur.size(); + } + + if(cur.size() == maxlen) + res.insert(cur); + } + return; + } + + if(s[index] != '(' && s[index] != ')') + dfs(s, index + 1, left, cur + s[index], res); + else if(s[index] == '('){ + dfs(s, index + 1, left + 1, cur + s[index], res); + if(cur.size() + n - (index + 1) >= maxlen) + dfs(s, index + 1, left, cur, res); + } + else{ + if(left > 0) + dfs(s, index + 1, left - 1, cur + s[index], res); + if(cur.size() + n - (index + 1) >= maxlen) + dfs(s, index + 1, left, cur, res); + } + } +}; + + +void print_vec(const vector& vec){ + + cout << vec.size() << " : "; + for(const string& e: vec) + cout << e << " "; + cout << endl; +} + +int main() { + + string s1 = "()())()"; + print_vec(Solution().removeInvalidParentheses(s1)); + // 6 + // (())() ()()() + + string s2 = "(a)())()"; + print_vec(Solution().removeInvalidParentheses(s2)); + // 7 + // (a())() (a)()() + + string s3 = ")("; + print_vec(Solution().removeInvalidParentheses(s3)); + // 0 + + string s4 = "n"; + print_vec(Solution().removeInvalidParentheses(s4)); + // 1 + // n + + string s5 = "x("; + print_vec(Solution().removeInvalidParentheses(s5)); + // 1 + // x + + string s6 = "(("; + print_vec(Solution().removeInvalidParentheses(s6)); + // 0 + + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0301-Remove-Invalid-Parentheses/cpp-0301/main2.cpp b/0001-0500/0301-Remove-Invalid-Parentheses/cpp-0301/main2.cpp new file mode 100644 index 00000000..ae2fc730 --- /dev/null +++ b/0001-0500/0301-Remove-Invalid-Parentheses/cpp-0301/main2.cpp @@ -0,0 +1,119 @@ +/// Source : https://leetcode.com/problems/remove-invalid-parentheses/description/ +/// Author : liuyubobobo +/// Time : 2018-11-02 + +#include +#include +#include + +using namespace std; + + +/// Calculate how many '(' and ')' are there +/// int the result maximum len expression first +/// Time Complexity: O(2^n) +/// Space Complexity: O(n) +class Solution { + +private: + int n, maxlen; + +public: + vector removeInvalidParentheses(string s) { + + n = s.size(); + + int total_left = 0, total_right = 0, l = 0, r = 0; + for(char c: s){ + if(c == '(') total_left ++; + else if(c == ')') total_right ++; + + if(c == '(') l ++; + else if(c == ')'){ + if(l > 0) l --; + else r ++; + } + } + + int rem_left = total_left - l, rem_right = total_right - r; +// cout << "rem_left : " << rem_left << " ; rem_right : " << rem_right << endl; + maxlen = s.size() - l - r; + + unordered_set res; + dfs(s, 0, rem_left, rem_right, "", res); + return vector(res.begin(), res.end()); + } + +private: + void dfs(const string& s, int index, int rem_left, int rem_right, + const string& cur, unordered_set& res){ + + if(cur.size() == maxlen){ + if(!rem_left && !rem_right) + res.insert(cur); + return; + } + + if(index == n || cur.size() > maxlen) + return; + + if(s[index] != '(' && s[index] != ')') + dfs(s, index + 1, rem_left, rem_right, cur + s[index], res); + else if(s[index] == '('){ + if(rem_left) + dfs(s, index + 1, rem_left - 1, rem_right, cur + s[index], res); + dfs(s, index + 1, rem_left, rem_right, cur, res); + } + else{ + if(rem_right && rem_right > rem_left) + dfs(s, index + 1, rem_left, rem_right - 1, cur + s[index], res); + dfs(s, index + 1, rem_left, rem_right, cur, res); + } + } +}; + + +void print_vec(const vector& vec){ + + cout << vec.size() << " : "; + for(const string& e: vec) + cout << e << " "; + cout << endl; +} + +int main() { + + string s1 = "()())()"; + print_vec(Solution().removeInvalidParentheses(s1)); + // 6 + // (())() ()()() + + string s2 = "(a)())()"; + print_vec(Solution().removeInvalidParentheses(s2)); + // 7 + // (a())() (a)()() + + string s3 = ")("; + print_vec(Solution().removeInvalidParentheses(s3)); + // 0 + + string s4 = "n"; + print_vec(Solution().removeInvalidParentheses(s4)); + // 1 + // n + + string s5 = "x("; + print_vec(Solution().removeInvalidParentheses(s5)); + // 1 + // x + + string s6 = "(("; + print_vec(Solution().removeInvalidParentheses(s6)); + // 0 + + string s7 = "(()"; + print_vec(Solution().removeInvalidParentheses(s7)); + // 2 + + return 0; +} \ No newline at end of file diff --git a/0303-Range-Sum-Query-Immutable/cpp-0303/CMakeLists.txt b/0001-0500/0303-Range-Sum-Query-Immutable/cpp-0303/CMakeLists.txt similarity index 100% rename from 0303-Range-Sum-Query-Immutable/cpp-0303/CMakeLists.txt rename to 0001-0500/0303-Range-Sum-Query-Immutable/cpp-0303/CMakeLists.txt diff --git a/0303-Range-Sum-Query-Immutable/cpp-0303/main.cpp b/0001-0500/0303-Range-Sum-Query-Immutable/cpp-0303/main.cpp similarity index 100% rename from 0303-Range-Sum-Query-Immutable/cpp-0303/main.cpp rename to 0001-0500/0303-Range-Sum-Query-Immutable/cpp-0303/main.cpp diff --git a/0001-0500/0304-Range-Sum-Query-2D-Immutable/cpp-0304/CMakeLists.txt b/0001-0500/0304-Range-Sum-Query-2D-Immutable/cpp-0304/CMakeLists.txt new file mode 100644 index 00000000..4482d1b2 --- /dev/null +++ b/0001-0500/0304-Range-Sum-Query-2D-Immutable/cpp-0304/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0304) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0304 main.cpp) \ No newline at end of file diff --git a/0001-0500/0304-Range-Sum-Query-2D-Immutable/cpp-0304/main.cpp b/0001-0500/0304-Range-Sum-Query-2D-Immutable/cpp-0304/main.cpp new file mode 100644 index 00000000..37ba8e19 --- /dev/null +++ b/0001-0500/0304-Range-Sum-Query-2D-Immutable/cpp-0304/main.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/range-sum-query-2d-immutable/ +/// Author : liuyubobobo +/// Time : 2021-03-01 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: init: O(n^2) +/// query: O(1) +/// Space Complexity: O(n^2) +class NumMatrix { + +private: + vector> dp; + +public: + NumMatrix(vector>& matrix) { + + int R = matrix.size(); + if(R == 0) return; + + int C = matrix[0].size(); + if(C == 0) return; + + dp = vector>(R + 1, vector(C + 1, 0)); + + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++) + dp[i + 1][j + 1] = matrix[i][j] + dp[i][j + 1] + dp[i + 1][j] - dp[i][j]; + } + + int sumRegion(int row1, int col1, int row2, int col2) { + + return dp[row2 + 1][col2 + 1] - dp[row1][col2 + 1] - dp[row2 + 1][col1] + dp[row1][col1]; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0305-Number-of-Islands-II/cpp-0305/CMakeLists.txt b/0001-0500/0305-Number-of-Islands-II/cpp-0305/CMakeLists.txt new file mode 100644 index 00000000..76fd5e50 --- /dev/null +++ b/0001-0500/0305-Number-of-Islands-II/cpp-0305/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_0305) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_0305 main.cpp) diff --git a/0001-0500/0305-Number-of-Islands-II/cpp-0305/main.cpp b/0001-0500/0305-Number-of-Islands-II/cpp-0305/main.cpp new file mode 100644 index 00000000..49cbc366 --- /dev/null +++ b/0001-0500/0305-Number-of-Islands-II/cpp-0305/main.cpp @@ -0,0 +1,85 @@ +/// Source : https://leetcode.com/problems/number-of-islands-ii/description/ +/// Author : liuyubobobo +/// Time : 2023-02-15 + +#include +#include + +using namespace std; + + +/// Using UF +/// Time Complexity: O(|positions|) +/// Space Complexity: O(R * C) +class UF{ + +private: + vector parent; + +public: + UF(int n) : parent(n){ + for(int i = 0 ; i < n ; i ++) + parent[i] = i; + } + + int find(int p){ + if(p != parent[p]) + parent[p] = find(parent[p]); + return parent[p]; + } + + bool is_connected(int p, int q){ + return find(p) == find(q); + } + + void union_elements(int p, int q){ + + int p_root = find(p), q_root = find(q); + + if(p_root == q_root) return; + + parent[p_root] = q_root; + } +}; + +class Solution { + +private: + const int dirs[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; + +public: + vector numIslands2(int R, int C, vector>& positions) { + + vector> g(R, vector(C, 0)); + int sz = 0; + + vector res; + + UF uf(R * C); + for(const vector& pos: positions){ + int x = pos[0], y = pos[1]; + if(g[x][y] != 1){ + g[x][y] = 1; sz ++; + for(int d = 0; d < 4; d ++){ + int nx = x + dirs[d][0], ny = y + dirs[d][1]; + if(!in_area(R, C, nx, ny) || g[nx][ny] == 0 || uf.is_connected(x * C + y, nx * C + ny)) + continue; + uf.union_elements(x * C + y, nx * C + ny); + sz --; + } + } + res.push_back(sz); + } + return res; + } + + bool in_area(int R, int C, int x, int y){ + return 0 <= x && x < R && 0 <= y && y < C; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0306-Additive-Number/cpp-0306/CMakeLists.txt b/0001-0500/0306-Additive-Number/cpp-0306/CMakeLists.txt new file mode 100644 index 00000000..ff45e2df --- /dev/null +++ b/0001-0500/0306-Additive-Number/cpp-0306/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_0306) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0306 main.cpp) diff --git a/0001-0500/0306-Additive-Number/cpp-0306/main.cpp b/0001-0500/0306-Additive-Number/cpp-0306/main.cpp new file mode 100644 index 00000000..0b027cab --- /dev/null +++ b/0001-0500/0306-Additive-Number/cpp-0306/main.cpp @@ -0,0 +1,67 @@ +/// Source : https://leetcode.com/problems/additive-number/ +/// Author : liuyubobobo +/// Time : 2022-01-09 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { +public: + bool isAdditiveNumber(string num) { + + int n = num.size(); + for(int len1 = 1; len1 <= 17 && len1 + 2 <= n; len1 ++) + for(int len2 = 1; len2 <= 17 && len1 + len2 + 1 <= n; len2 ++) + if(ok(n, num, len1, len2)) return true; + return false; + } + +private: + bool ok(int n, const string& num, int len1, int len2){ + + if(num[0] == '0' && len1 > 1) return false; + if(num[len1] == '0' && len2 > 1) return false; + + vector v; + v.push_back(atoll(num.substr(0, len1).c_str())); + v.push_back(atoll(num.substr(len1, len2).c_str())); + + int cur_index = len1 + len2; + while(cur_index < n){ + + long long next = v[v.size() - 2] + v[v.size() - 1]; + string next_s = to_string(next); + int next_s_len = next_s.size(); + if(num.substr(cur_index, next_s_len) == next_s) + cur_index += next_s_len; + else + return false; + v.push_back(next); + } + return true; + } +}; + + +int main() { + + cout << Solution().isAdditiveNumber("112358") << endl; + // 1 + + cout << Solution().isAdditiveNumber("199100199") << endl; + // 1 + + cout << Solution().isAdditiveNumber("111") << endl; + // 0 + + cout << Solution().isAdditiveNumber("101") << endl; + // 1 + + return 0; +} diff --git a/0001-0500/0307-Range-Sum-Query-Mutable/cpp-0307/CMakeLists.txt b/0001-0500/0307-Range-Sum-Query-Mutable/cpp-0307/CMakeLists.txt new file mode 100644 index 00000000..b89bafc2 --- /dev/null +++ b/0001-0500/0307-Range-Sum-Query-Mutable/cpp-0307/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0307) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main2.cpp) +add_executable(cpp_0307 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0307-Range-Sum-Query-Mutable/cpp-0307/main.cpp b/0001-0500/0307-Range-Sum-Query-Mutable/cpp-0307/main.cpp new file mode 100644 index 00000000..421fbb2a --- /dev/null +++ b/0001-0500/0307-Range-Sum-Query-Mutable/cpp-0307/main.cpp @@ -0,0 +1,143 @@ +/// Source : https://leetcode.com/problems/range-sum-query-mutable/description/ +/// Author : liuyubobobo +/// Time : 2017-10-28 + +#include +#include +#include + +using namespace std; + +/// Segment Tree +/// Time Complexity: update: O(logn) +/// query: O(logn) +/// Space Complexity: O(n) +class SegmentTree{ + +private: + vector tree; + vector nums; + +public: + SegmentTree(const vector& nums){ + + if(nums.size() == 0) + return; + + for(int num: nums) + (this->nums).push_back(num); + + int size = 4*nums.size(); + for(int i = 0 ; i < size ; i ++) + tree.push_back(-1); + + treeBuild(0, 0, nums.size()-1); + } + + void update(int index, int val){ + assert(index >= 0 && index < nums.size()); + nums[index] = val; + update(0, 0, nums.size()-1, index, val); + } + + int query(int l, int r){ + assert(l >= 0 && l < nums.size()); + assert(r >= 0 && r < nums.size()); + return query(0, 0, nums.size()-1, l, r); + } + + void print(){ + for(int e: tree) + cout << e << " "; + cout << endl; + } + +private: + void treeBuild(int treeID, int nodeLeftBound, int nodeRightBound){ + + assert(nodeLeftBound <= nodeRightBound); + if(nodeLeftBound == nodeRightBound){ + tree[treeID] = nums[nodeLeftBound]; + return; + } + + int mid = (nodeLeftBound + nodeRightBound) / 2; + treeBuild(treeID * 2 + 1, nodeLeftBound, mid); + treeBuild(treeID * 2 + 2, mid + 1, nodeRightBound); + + tree[treeID] = tree[treeID * 2 + 1] + tree[treeID * 2 + 2]; + } + + void update(int treeID, int nodeLeftBound, int nodeRightBound, int index, int val){ + + assert(nodeLeftBound <= nodeRightBound); + if(nodeLeftBound == nodeRightBound){ + assert(index == nodeLeftBound); + tree[treeID] = val; + return; + } + + int mid = (nodeLeftBound + nodeRightBound)/2; + if(index >= nodeLeftBound && index <= mid) + update(treeID * 2 + 1, nodeLeftBound, mid, index, val); + else + update(treeID * 2 + 2, mid+1, nodeRightBound, index, val); + + tree[treeID] = tree[treeID * 2 + 1] + tree[treeID * 2 + 2]; + } + + int query(int treeID, int nodeLeftBound, int nodeRightBound, int l, int r){ + + if(l == nodeLeftBound && r == nodeRightBound) + return tree[treeID]; + + int mid = (nodeLeftBound + nodeRightBound) / 2; + if(r <= mid) + return query(treeID * 2 + 1, nodeLeftBound, mid, l, r); + if(l >= mid + 1) + return query(treeID * 2 + 2, mid + 1, nodeRightBound, l, r); + + return query(treeID * 2 + 1, nodeLeftBound, mid, l, mid) + + query(treeID * 2 + 2, mid + 1, nodeRightBound, mid + 1, r); + } +}; + +class NumArray { + +private: + SegmentTree tree; + +public: + NumArray(vector nums):tree(nums) {} + + void update(int i, int val) { + tree.update(i, val); + } + + int sumRange(int i, int j) { + return tree.query(i, j); + } +}; + + +int main() { + + vector nums1 = {1, 3, 5}; + NumArray obj1(nums1); + + cout << obj1.sumRange(0, 2) << endl; + obj1.update(1, 2); + cout << obj1.sumRange(0, 2) << endl; + + cout << endl; + + // --- + + vector nums2 = {0, 9, 5, 7, 3}; + NumArray obj2(nums2); + + cout << obj2.sumRange(4, 4) << endl; + cout << obj2.sumRange(2, 4) << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0307-Range-Sum-Query-Mutable/cpp-0307/main2.cpp b/0001-0500/0307-Range-Sum-Query-Mutable/cpp-0307/main2.cpp new file mode 100644 index 00000000..98c9e991 --- /dev/null +++ b/0001-0500/0307-Range-Sum-Query-Mutable/cpp-0307/main2.cpp @@ -0,0 +1,99 @@ +/// Source : https://leetcode.com/problems/range-sum-query-mutable/description/ +/// Author : liuyubobobo +/// Time : 2019-08-11 + +#include +#include +#include +#include +#include +#include + +using namespace std; + +/// Bucket +/// Time Complexity: init: O(n) +/// update: O(logn) +/// query: O(sqrt(n)) +/// Space Complexity: O(n) +class NumArray { + +private: + vector bucket, arr, sum; + const int bucket_sz; + +public: + NumArray(vector nums): arr(nums.begin(), nums.end()), bucket_sz(sqrt(arr.size())) { + + bucket.push_back(0); + while(bucket.back() != nums.size()){ + int l = bucket.back(); + int r = min(bucket.back() + bucket_sz, (int)nums.size()); + bucket.push_back(r); + sum.push_back(accumulate(nums.begin() + l, nums.begin() + r, 0)); + } + +// cout << "bucket_sz = " << bucket_sz << endl; +// for(int e: bucket) cout << e << " "; cout << endl; +// for(int e: sum) cout << e << " "; cout << endl; + } + + void update(int i, int val) { + int o = arr[i]; + arr[i] = val; + + vector::iterator iter = lower_bound(bucket.begin(), bucket.end(), i); + int index = iter - bucket.begin(); + if(bucket[index] != i) index --; + + sum[index] = sum[index] - o + val; + } + + int sumRange(int i, int j) { + + vector::iterator iter = lower_bound(bucket.begin(), bucket.end(), i); + int index = iter - bucket.begin(); + if(bucket[index] != i) index --; + + if(i >= bucket[index] && j < bucket[index + 1]) return sumNaive(i, j); + + int res = sumNaive(i, bucket[index + 1] - 1); + index ++; + while(j >= bucket[index]){ + + if(j < bucket[index + 1]) res += sumNaive(bucket[index], j); + else res += sum[index]; + + index ++; + } + return res; + } + +private: + int sumNaive(int i, int j){ + return accumulate(arr.begin() + i, arr.begin() + (j + 1), 0); + } +}; + + +int main() { + + vector nums1 = {1, 3, 5}; + NumArray obj1(nums1); + + cout << obj1.sumRange(0, 2) << endl; + obj1.update(1, 2); + cout << obj1.sumRange(0, 2) << endl; + + cout << endl; + + // --- + + vector nums2 = {0, 9, 5, 7, 3}; + NumArray obj2(nums2); + + cout << obj2.sumRange(4, 4) << endl; + cout << obj2.sumRange(2, 4) << endl; + + return 0; +} \ No newline at end of file diff --git a/0308-Range-Sum-Query-2D-Mutable/cpp-0308/CMakeLists.txt b/0001-0500/0308-Range-Sum-Query-2D-Mutable/cpp-0308/CMakeLists.txt similarity index 100% rename from 0308-Range-Sum-Query-2D-Mutable/cpp-0308/CMakeLists.txt rename to 0001-0500/0308-Range-Sum-Query-2D-Mutable/cpp-0308/CMakeLists.txt diff --git a/0308-Range-Sum-Query-2D-Mutable/cpp-0308/main.cpp b/0001-0500/0308-Range-Sum-Query-2D-Mutable/cpp-0308/main.cpp similarity index 100% rename from 0308-Range-Sum-Query-2D-Mutable/cpp-0308/main.cpp rename to 0001-0500/0308-Range-Sum-Query-2D-Mutable/cpp-0308/main.cpp diff --git a/0001-0500/0309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown/cpp-0309/CMakeLists.txt b/0001-0500/0309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown/cpp-0309/CMakeLists.txt new file mode 100644 index 00000000..428d047d --- /dev/null +++ b/0001-0500/0309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown/cpp-0309/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(cpp_0309) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0309 main4.cpp) \ No newline at end of file diff --git a/0001-0500/0309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown/cpp-0309/main.cpp b/0001-0500/0309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown/cpp-0309/main.cpp new file mode 100644 index 00000000..29edfd4a --- /dev/null +++ b/0001-0500/0309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown/cpp-0309/main.cpp @@ -0,0 +1,59 @@ +/// Source : https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/description/ +/// Author : liuyubobobo +/// Time : 2019-06-27 + +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +private: + int n; + +public: + int maxProfit(vector& prices) { + + n = prices.size(); + if(n <= 1) return 0; + + vector buy(n, -1), sell(n, -1); + return _sell(prices, n - 1, buy, sell); + } + +private: + int _sell(const vector& prices, int index, vector& buy, vector& sell){ + + if(index == 0) return 0; + if(index == 1) return max(0, prices[1] - prices[0]); + + if(sell[index] != -1) return sell[index]; + return sell[index] = max(_sell(prices, index - 1, buy, sell), + _buy(prices, index - 1, buy, sell) + prices[index]); + } + + int _buy(const vector& prices, int index, vector& buy, vector& sell){ + + if(index == 0) return -prices[0]; + if(index == 1) return max(-prices[0], -prices[1]); + + if(buy[index] != -1) return buy[index]; + return buy[index] = max(_buy(prices, index - 1, buy, sell), + _sell(prices, index - 2, buy, sell) - prices[index]); + } +}; + + +int main() { + + vector prices1 = {1, 2, 3, 0, 2}; + cout << Solution().maxProfit(prices1) << endl; + // 3 + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown/cpp-0309/main2.cpp b/0001-0500/0309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown/cpp-0309/main2.cpp new file mode 100644 index 00000000..03e0e510 --- /dev/null +++ b/0001-0500/0309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown/cpp-0309/main2.cpp @@ -0,0 +1,44 @@ +/// Source : https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/description/ +/// Author : liuyubobobo +/// Time : 2017-10-23 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int maxProfit(vector& prices) { + + if(prices.size() <= 1) + return 0; + + vector buy(prices.size(), 0); + vector sell(prices.size(), 0); + + buy[0] = -prices[0]; + buy[1] = max(-prices[0], -prices[1]); + sell[1] = max(0, buy[0] + prices[1]); + for(int i = 2 ; i < prices.size() ; i ++){ + sell[i] = max(sell[i-1], buy[i-1] + prices[i]); + buy[i] = max(buy[i-1], sell[i-2] - prices[i]); + } + + return sell.back(); + } +}; + + +int main() { + + vector prices1 = {1, 2, 3, 0, 2}; + cout << Solution().maxProfit(prices1) << endl; + // 3 + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown/cpp-0309/main3.cpp b/0001-0500/0309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown/cpp-0309/main3.cpp new file mode 100644 index 00000000..fe186a2e --- /dev/null +++ b/0001-0500/0309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown/cpp-0309/main3.cpp @@ -0,0 +1,43 @@ +/// Source : https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/description/ +/// Author : liuyubobobo +/// Time : 2017-10-24 + +#include +#include + +using namespace std; + + +/// Dynamic Programming with Space Optimization +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int maxProfit(vector& prices) { + + int n = prices.size(); + + if(n <= 1) + return 0; + + int buy[3] = {-prices[0], max(-prices[0], -prices[1]), 0}; + int sell[3] = {0, max(0, prices[1] - prices[0]), 0}; + + for(int i = 2 ; i < n ; i ++){ + sell[i % 3] = max(sell[(i - 1) % 3], buy[(i - 1) % 3] + prices[i]); + buy[i % 3] = max(buy[(i - 1) % 3], sell[(i - 2) % 3] - prices[i]); + } + + return sell[(n - 1) % 3]; + } +}; + + +int main() { + + vector prices1 = {1, 2, 3, 0, 2}; + cout << Solution().maxProfit(prices1) << endl; + // 3 + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown/cpp-0309/main4.cpp b/0001-0500/0309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown/cpp-0309/main4.cpp new file mode 100644 index 00000000..18a3084f --- /dev/null +++ b/0001-0500/0309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown/cpp-0309/main4.cpp @@ -0,0 +1,45 @@ +/// Source : https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/description/ +/// Author : liuyubobobo +/// Time : 2020-05-25 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Using three states every day +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int maxProfit(vector& prices) { + + int n = prices.size(); + + if(n <= 1) + return 0; + + vector> dp(n, vector(3, 0)); // 0 hold; 1 sell(cooldown); 2 unhold + dp[0][0] = -prices[0]; + + for(int i = 1 ; i < n ; i ++){ + dp[i][0] = max(max(dp[i - 1][0], dp[i - 1][2] - prices[i]), dp[i - 1][1] - prices[i]); + dp[i][1] = dp[i - 1][0] + prices[i]; + dp[i][2] = max(dp[i - 1][1], dp[i - 1][2]); + } + + return max(dp[n - 1][1], dp[n - 1][2]); + } +}; + + +int main() { + + vector prices1 = {1, 2, 3, 0, 2}; + cout << Solution().maxProfit(prices1) << endl; + // 3 + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown/cpp-0309/main5.cpp b/0001-0500/0309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown/cpp-0309/main5.cpp new file mode 100644 index 00000000..65e8be26 --- /dev/null +++ b/0001-0500/0309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown/cpp-0309/main5.cpp @@ -0,0 +1,44 @@ +/// Source : https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/description/ +/// Author : liuyubobobo +/// Time : 2020-05-25 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Using three states every day, with space optimization +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int maxProfit(vector& prices) { + + int n = prices.size(); + + if(n <= 1) + return 0; + + int hold = -prices[0], sell = 0, unhold = 0; + + for(int i = 1 ; i < n ; i ++){ + hold = max(hold, unhold - prices[i]); + unhold = max(sell, unhold); + sell = hold + prices[i]; + } + + return max(unhold, sell); + } +}; + + +int main() { + + vector prices1 = {1, 2, 3, 0, 2}; + cout << Solution().maxProfit(prices1) << endl; + // 3 + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0310-Minimum-Height-Trees/cpp-0310/CMakeLists.txt b/0001-0500/0310-Minimum-Height-Trees/cpp-0310/CMakeLists.txt new file mode 100644 index 00000000..2bdd3dc6 --- /dev/null +++ b/0001-0500/0310-Minimum-Height-Trees/cpp-0310/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0310) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0310 main.cpp) diff --git a/0001-0500/0310-Minimum-Height-Trees/cpp-0310/main.cpp b/0001-0500/0310-Minimum-Height-Trees/cpp-0310/main.cpp new file mode 100644 index 00000000..d74edadd --- /dev/null +++ b/0001-0500/0310-Minimum-Height-Trees/cpp-0310/main.cpp @@ -0,0 +1,60 @@ +/// Source : https://leetcode.com/problems/minimum-height-trees/ +/// Author : liuyubobobo +/// Time : 2021-12-15 + +#include +#include + +using namespace std; + + +/// Tree Centroids +/// Time Complexity: O(V + E) +/// Space Complexity: O(V + E) +class Solution { +public: + vector findMinHeightTrees(int n, vector>& edges) { + + vector> g(n); + for(const vector& e: edges) + g[e[0]].push_back(e[1]), g[e[1]].push_back(e[0]); + + return get_tree_centroid(n, g); + } + +private: + vector get_tree_centroid(int n, const vector>& g){ + + vector degrees(n, 0); + vector leaves; + for(int u = 0; u < n; u ++){ + degrees[u] = g[u].size(); + if(degrees[u] == 0 || degrees[u] == 1){ + leaves.push_back(u); + degrees[u] = 0; + } + } + + int count = leaves.size(); + while(count < n){ + vector new_leaves; + for(int u: leaves){ + for(int v: g[u]){ + degrees[v] --; + if(degrees[v] == 1) new_leaves.push_back(v); + } + degrees[u] = 0; + } + count += new_leaves.size(); + leaves = new_leaves; + } + assert(1 <= leaves.size() && leaves.size() <= 2); + return leaves; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0311-Sparse-Matrix-Multiplication/cpp-0311/CMakeLists.txt b/0001-0500/0311-Sparse-Matrix-Multiplication/cpp-0311/CMakeLists.txt new file mode 100644 index 00000000..bc6e2b41 --- /dev/null +++ b/0001-0500/0311-Sparse-Matrix-Multiplication/cpp-0311/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_0311) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_0311 main.cpp) diff --git a/0001-0500/0311-Sparse-Matrix-Multiplication/cpp-0311/main.cpp b/0001-0500/0311-Sparse-Matrix-Multiplication/cpp-0311/main.cpp new file mode 100644 index 00000000..e90eb92e --- /dev/null +++ b/0001-0500/0311-Sparse-Matrix-Multiplication/cpp-0311/main.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/sparse-matrix-multiplication/description/ +/// Author : liuyubobobo +/// Time : 2023-05-07 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n * m * k) +/// Space Complexity: O(n * m) +class Solution { +public: + vector> multiply(vector>& mat1, vector>& mat2) { + + int n = mat1.size(), k = mat1[0].size(), m = mat2[0].size(); + + vector> res(n, vector(m)); + for(int i = 0; i < n; i ++) + for(int j = 0; j < m; j ++) + for(int p = 0; p < k; p ++) + res[i][j] += mat1[i][p] * mat2[p][j]; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0312-Burst-Balloons/cpp-0312/CMakeLists.txt b/0001-0500/0312-Burst-Balloons/cpp-0312/CMakeLists.txt new file mode 100644 index 00000000..87421766 --- /dev/null +++ b/0001-0500/0312-Burst-Balloons/cpp-0312/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(cpp_0312) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0312 main2.cpp) \ No newline at end of file diff --git a/0001-0500/0312-Burst-Balloons/cpp-0312/main.cpp b/0001-0500/0312-Burst-Balloons/cpp-0312/main.cpp new file mode 100644 index 00000000..57f69164 --- /dev/null +++ b/0001-0500/0312-Burst-Balloons/cpp-0312/main.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/burst-balloons/ +/// Author : liuyubobobo +/// Time : 2020-05-08 + +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(n^3) +/// Space Complexity: O(n^2) +class Solution { +public: + int maxCoins(vector& nums) { + + nums.insert(nums.begin(), 1); + nums.push_back(1); + + int n = nums.size(); + vector> dp(n, vector(n, -1)); + return dfs(nums, 0, n - 1, dp); + } + +private: + int dfs(const vector& nums, int l, int r, vector>& dp){ + + if(l == r) return dp[l][r] = 0; + if(dp[l][r] != -1) return dp[l][r]; + + int res = 0; + for(int k = l + 1; k <= r - 1; k ++) + res = max(res, dfs(nums, l, k, dp) + dfs(nums, k, r, dp) + nums[l] * nums[k] * nums[r]); + return dp[l][r] = res; + } +}; + + +int main() { + + vector nums = {3,1,5,8}; + cout << Solution().maxCoins(nums) << endl; + // 167 + + return 0; +} diff --git a/0001-0500/0312-Burst-Balloons/cpp-0312/main2.cpp b/0001-0500/0312-Burst-Balloons/cpp-0312/main2.cpp new file mode 100644 index 00000000..effc6c8b --- /dev/null +++ b/0001-0500/0312-Burst-Balloons/cpp-0312/main2.cpp @@ -0,0 +1,41 @@ +/// Source : https://leetcode.com/problems/burst-balloons/ +/// Author : liuyubobobo +/// Time : 2020-05-08 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(n^3) +/// Space Complexity: O(n^2) +class Solution { +public: + int maxCoins(vector& nums) { + + nums.insert(nums.begin(), 1); + nums.push_back(1); + + int n = nums.size(); + vector> dp(n, vector(n, 0)); + + for(int len = 2; len < n; len ++) + for(int start = 0; start + len < n; start ++) + for(int k = start + 1; k < start + len; k ++) + dp[start][start + len] = max(dp[start][start + len], + dp[start][k] + dp[k][start + len] + nums[start] * nums[k] * nums[start + len]); + return dp[0][n - 1]; + } +}; + + +int main() { + + vector nums = {3,1,5,8}; + cout << Solution().maxCoins(nums) << endl; + // 167 + + return 0; +} diff --git a/0001-0500/0313-Super-Ugly-Number/cpp-0313/CMakeLists.txt b/0001-0500/0313-Super-Ugly-Number/cpp-0313/CMakeLists.txt new file mode 100644 index 00000000..e3344fa2 --- /dev/null +++ b/0001-0500/0313-Super-Ugly-Number/cpp-0313/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0313) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0313 main2.cpp) diff --git a/0001-0500/0313-Super-Ugly-Number/cpp-0313/main.cpp b/0001-0500/0313-Super-Ugly-Number/cpp-0313/main.cpp new file mode 100644 index 00000000..e03c4617 --- /dev/null +++ b/0001-0500/0313-Super-Ugly-Number/cpp-0313/main.cpp @@ -0,0 +1,45 @@ +/// Source : https://leetcode.com/problems/super-ugly-number/ +/// Author : liuyubobobo +/// Time : 2021-08-09 + +#include +#include +#include + +using namespace std; + + +/// Tree Set +/// Time Complexity: O(nlogn * |primes|) +/// Space Complexity: O(n) +class Solution { +public: + int nthSuperUglyNumber(int n, vector& primes) { + + set set; + set.insert(1); + int index = 0; + while(!set.empty()){ + int cur = *set.begin(); set.erase(set.begin()); + index ++; + if(index == n) return cur; + + for(int p: primes) + if(INT_MAX / cur >= p) + set.insert(cur * p); + } + + assert(false); + return -1; + } +}; + + +int main() { + + vector primes1 = {2, 7, 13, 19}; + cout << Solution().nthSuperUglyNumber(12, primes1) << endl; + // 32 + + return 0; +} diff --git a/0001-0500/0313-Super-Ugly-Number/cpp-0313/main2.cpp b/0001-0500/0313-Super-Ugly-Number/cpp-0313/main2.cpp new file mode 100644 index 00000000..bc81c70d --- /dev/null +++ b/0001-0500/0313-Super-Ugly-Number/cpp-0313/main2.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/super-ugly-number/ +/// Author : liuyubobobo +/// Time : 2021-08-09 + +#include +#include +#include + +using namespace std; + + +/// k pointers +/// Time Complexity: O(n * |primes|) +/// Space Complexity: O(n + |primes|) +class Solution { +public: + int nthSuperUglyNumber(int n, vector& primes) { + + vector res(n, 1); + vector pointers(primes.size(), 0); + for(int i = 1; i < n; i ++){ + + int mink = -1, minv = INT_MAX; + for(int j = 0; j < pointers.size(); j ++) + if(res[pointers[j]] * primes[j] < minv) + minv = res[pointers[j]] * primes[j], mink = j; + + res[i] = minv; + pointers[mink] ++; + + for(int j = 0; j < pointers.size(); j ++) + if(res[pointers[j]] * primes[j] == res[i]) + pointers[j] ++; + } + return res.back(); + } +}; + + +int main() { + + vector primes1 = {2, 7, 13, 19}; + cout << Solution().nthSuperUglyNumber(12, primes1) << endl; + // 32 + + return 0; +} diff --git a/0001-0500/0314-Binary-Tree-Vertical-Order-Traversal/cpp-0314/CMakeLists.txt b/0001-0500/0314-Binary-Tree-Vertical-Order-Traversal/cpp-0314/CMakeLists.txt new file mode 100644 index 00000000..71044129 --- /dev/null +++ b/0001-0500/0314-Binary-Tree-Vertical-Order-Traversal/cpp-0314/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_0314) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0314 main.cpp) diff --git a/0001-0500/0314-Binary-Tree-Vertical-Order-Traversal/cpp-0314/main.cpp b/0001-0500/0314-Binary-Tree-Vertical-Order-Traversal/cpp-0314/main.cpp new file mode 100644 index 00000000..db73bd90 --- /dev/null +++ b/0001-0500/0314-Binary-Tree-Vertical-Order-Traversal/cpp-0314/main.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/binary-tree-vertical-order-traversal/ +/// Author : liuyubobobo +/// Time : 2022-08-08 + +#include +#include +#include +#include + +using namespace std; + + +/// BFS + Map +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// 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> verticalOrder(TreeNode* root) { + + if(root == nullptr) return {}; + + map> table; + queue> q; + q.push({root, 0}); + while(!q.empty()){ + TreeNode* node = q.front().first; + int col = q.front().second; + q.pop(); + + table[col].push_back(node->val); + if(node->left) q.push({node->left, col - 1}); + if(node->right) q.push({node->right, col + 1}); + } + + vector> res; + for(const pair>& p: table) + res.push_back(p.second); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0315-Count-of-Smaller-Numbers-After-Self/cpp-0315/CMakeLists.txt b/0001-0500/0315-Count-of-Smaller-Numbers-After-Self/cpp-0315/CMakeLists.txt new file mode 100644 index 00000000..09fee03f --- /dev/null +++ b/0001-0500/0315-Count-of-Smaller-Numbers-After-Self/cpp-0315/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.12) +project(cpp_0315) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(cpp_0315 main3.cpp) \ No newline at end of file diff --git a/0001-0500/0315-Count-of-Smaller-Numbers-After-Self/cpp-0315/main.cpp b/0001-0500/0315-Count-of-Smaller-Numbers-After-Self/cpp-0315/main.cpp new file mode 100644 index 00000000..72df2c09 --- /dev/null +++ b/0001-0500/0315-Count-of-Smaller-Numbers-After-Self/cpp-0315/main.cpp @@ -0,0 +1,102 @@ +/// Source : https://leetcode.com/problems/count-of-smaller-numbers-after-self/ +/// Author : liuyubobobo +/// Time : 2018-12-03 + +#include +#include +#include + +using namespace std; + + +/// Using BST +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class BST{ + +private: + class TreeNode{ + public: + int val, sz; + TreeNode *left, *right; + TreeNode(int val): val(val), sz(1), left(NULL), right(NULL){} + }; + TreeNode* root; + +public: + BST(): root(NULL){} + + void add(int x){ + root = add(root, x); + } + + int smaller_than(int x){ + return smaller_than(root, x); + } + +private: + TreeNode* add(TreeNode* node, int x){ + if(!node) + return new TreeNode(x); + + if(x <= node->val) + node->left = add(node->left, x); + else + node->right = add(node->right, x); + node->sz ++; + return node; + } + + int smaller_than(TreeNode* node, int x){ + + if(!node) + return 0; + + if(x <= node->val) + return smaller_than(node->left, x); + return (node->left ? node->left->sz : 0) + 1 + smaller_than(node->right, x); + } +}; + +class Solution { +public: + vector countSmaller(vector& nums) { + + vector res; + if(nums.size() == 0) + return res; + + res.push_back(0); + if(nums.size() == 1) + return res; + + BST bst; + bst.add(nums.back()); + for(int i = nums.size() - 2; i >= 0; i --){ + bst.add(nums[i]); + res.push_back(bst.smaller_than(nums[i])); + } + reverse(res.begin(), res.end()); + return res; + } +}; + + +void print_vec(const vector& vec){ + for(int e: vec) + cout << e << " "; + cout << endl; +} + +int main() { + + vector nums1 = {5, 2, 6, 1}; + print_vec(Solution().countSmaller(nums1)); + // 2 1 1 0 + + vector nums2 = {2, 0, 1}; + print_vec(Solution().countSmaller(nums2)); + // 2 0 0 + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0315-Count-of-Smaller-Numbers-After-Self/cpp-0315/main2.cpp b/0001-0500/0315-Count-of-Smaller-Numbers-After-Self/cpp-0315/main2.cpp new file mode 100644 index 00000000..064e2d36 --- /dev/null +++ b/0001-0500/0315-Count-of-Smaller-Numbers-After-Self/cpp-0315/main2.cpp @@ -0,0 +1,83 @@ +/// Source : https://leetcode.com/problems/count-of-smaller-numbers-after-self/ +/// Author : liuyubobobo +/// Time : 2018-12-03 + +#include +#include +#include + +using namespace std; + + +/// Using Merge Sort +/// Sort (value, index) pair to track every element's index +/// +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + vector countSmaller(vector& nums) { + + int n = nums.size(); + + vector> elements; + for(int i = 0; i < n; i ++) + elements.push_back(make_pair(nums[i], i)); + + vector res(n, 0); + vector> aux(n); + merge_sort(elements, 0, n - 1, aux, res); + return res; + } + +private: + void merge_sort(vector>& arr, int l, int r, + vector>& aux, vector& res){ + + if(l >= r) + return; + + int mid = (l + r) / 2; + merge_sort(arr, l, mid, aux, res); + merge_sort(arr, mid + 1, r, aux, res); + if(arr[mid] > arr[mid + 1]) + merge(arr, l, mid, r, aux, res); + } + + void merge(vector>& arr, int l, int mid, int r, + vector>& aux, vector& res){ + + for(int i = l; i <= r; i ++) + aux[i] = arr[i]; + int i = l, j = mid + 1; + for(int k = l; k <= r; k ++) + if(i > mid) + arr[k] = aux[j], j ++; + else if(j > r) + arr[k] = aux[i], res[aux[i].second] += j - mid - 1, i ++; + else if(aux[i] <= aux[j]) + arr[k] = aux[i], res[aux[i].second] += j - mid - 1, i ++; + else + arr[k] = aux[j], j ++; + } +}; + + +void print_vec(const vector& vec){ + for(int e: vec) + cout << e << " "; + cout << endl; +} + +int main() { + + vector nums1 = {5, 2, 6, 1}; + print_vec(Solution().countSmaller(nums1)); + // 2 1 1 0 + + vector nums2 = {2, 0, 1}; + print_vec(Solution().countSmaller(nums2)); + // 2 0 0 + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0315-Count-of-Smaller-Numbers-After-Self/cpp-0315/main3.cpp b/0001-0500/0315-Count-of-Smaller-Numbers-After-Self/cpp-0315/main3.cpp new file mode 100644 index 00000000..3eac4f76 --- /dev/null +++ b/0001-0500/0315-Count-of-Smaller-Numbers-After-Self/cpp-0315/main3.cpp @@ -0,0 +1,90 @@ +/// Source : https://leetcode.com/problems/count-of-smaller-numbers-after-self/ +/// Author : liuyubobobo +/// Time : 2018-12-03 + +#include +#include +#include + +using namespace std; + + +/// Using Merge Sort +/// Using indexes arr to track every element's index +/// +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + vector countSmaller(vector& nums) { + + int n = nums.size(); + + vector indexes(n); // indexes[i] : 在排序过程中,nums第i个元素 + // 对应初始nums中indexes[i]的位置 + // indexes[2] = 5 表示现在nums中第2个元素,在初始nums中索引为5的位置 + for(int i = 0; i < n; i ++) + indexes[i] = i; + + vector res(n, 0); + vector aux(n); + merge_sort(nums, 0, n - 1, indexes, aux, res); + return res; + } + +private: + void merge_sort(vector& arr, int l, int r, + vector& indexes, vector& aux, vector& res){ + + if(l >= r) + return; + + int mid = (l + r) / 2; + merge_sort(arr, l, mid, indexes, aux, res); + merge_sort(arr, mid + 1, r, indexes, aux, res); + if(arr[mid] > arr[mid + 1]) + merge(arr, l, mid, r, indexes, aux, res); + } + + void merge(vector& arr, int l, int mid, int r, + vector& indexes, vector& aux, vector& res){ + + for(int i = l; i <= r; i ++) + aux[i] = arr[i]; + + vector new_indexes(r - l + 1); + int i = l, j = mid + 1; + for(int k = l; k <= r; k ++) + if(i > mid) + arr[k] = aux[j], new_indexes[k - l] = indexes[j], j ++; + else if(j > r) + arr[k] = aux[i], new_indexes[k - l] = indexes[i], res[indexes[i]] += j - mid - 1, i ++; + else if(aux[i] <= aux[j]) + arr[k] = aux[i], new_indexes[k - l] = indexes[i], res[indexes[i]] += j - mid - 1, i ++; + else + arr[k] = aux[j], new_indexes[k - l] = indexes[j], j ++; + + for(int k = l; k <= r; k ++) + indexes[k] = new_indexes[k - l]; + } +}; + + +void print_vec(const vector& vec){ + for(int e: vec) + cout << e << " "; + cout << endl; +} + +int main() { + + vector nums1 = {5, 2, 6, 1}; + print_vec(Solution().countSmaller(nums1)); + // 2 1 1 0 + + vector nums2 = {2, 0, 1}; + print_vec(Solution().countSmaller(nums2)); + // 2 0 0 + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0316-Remove-Duplicate-Letters/cpp-0316/CMakeLists.txt b/0001-0500/0316-Remove-Duplicate-Letters/cpp-0316/CMakeLists.txt new file mode 100644 index 00000000..23a57b20 --- /dev/null +++ b/0001-0500/0316-Remove-Duplicate-Letters/cpp-0316/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0316) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0316 main.cpp) \ No newline at end of file diff --git a/0001-0500/0316-Remove-Duplicate-Letters/cpp-0316/main.cpp b/0001-0500/0316-Remove-Duplicate-Letters/cpp-0316/main.cpp new file mode 100644 index 00000000..ef3e9749 --- /dev/null +++ b/0001-0500/0316-Remove-Duplicate-Letters/cpp-0316/main.cpp @@ -0,0 +1,55 @@ +/// Source : https://leetcode.com/problems/remove-duplicate-letters/ +/// Author : liuyubobobo +/// Time : 2020-12-01 + +#include +#include + +using namespace std; + + +/// Mono Stack +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + string removeDuplicateLetters(string s) { + + vector left(26, 0), used(26, 0); + for(char c: s) left[c - 'a'] ++; + + string res = ""; + for(char c: s){ + if(!used[c - 'a']){ + while(res != "" && left[res.back() - 'a'] && c <= res.back()){ + used[res.back() - 'a'] = false ; + res.pop_back(); + } + res += c, used[c - 'a'] = true; + } + left[c - 'a'] --; + } + return res; + } +}; + + +int main() { + + cout << Solution().removeDuplicateLetters("bcabc") << endl; + // abc + + cout << Solution().removeDuplicateLetters("cbacdcbc") << endl; + // acdb + + cout << Solution().removeDuplicateLetters("cdadabcc") << endl; + // adbc + + cout << Solution().removeDuplicateLetters("ccacbaba") << endl; + // acb + + cout << Solution().removeDuplicateLetters("abacb") << endl; + // abc + + return 0; +} diff --git a/0001-0500/0317-Shortest-Distance-from-All-Buildings/cpp-0317/CMakeLists.txt b/0001-0500/0317-Shortest-Distance-from-All-Buildings/cpp-0317/CMakeLists.txt new file mode 100644 index 00000000..d38e603f --- /dev/null +++ b/0001-0500/0317-Shortest-Distance-from-All-Buildings/cpp-0317/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0317) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0317 main.cpp) diff --git a/0001-0500/0317-Shortest-Distance-from-All-Buildings/cpp-0317/main.cpp b/0001-0500/0317-Shortest-Distance-from-All-Buildings/cpp-0317/main.cpp new file mode 100644 index 00000000..2d14e744 --- /dev/null +++ b/0001-0500/0317-Shortest-Distance-from-All-Buildings/cpp-0317/main.cpp @@ -0,0 +1,76 @@ +/// Source : https://leetcode.com/problems/shortest-distance-from-all-buildings/ +/// Author : liuyubobobo +/// Time : 2021-09-22 + +#include +#include +#include + +using namespace std; + + +/// BFS +/// Time Complexity: O(R * C * R * C) +/// Space Complexity: O(R * C * R * C) +class Solution { + +private: + const int dirs[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; + int R, C; + +public: + int shortestDistance(vector>& grid) { + + R = grid.size(), C = grid[0].size(); + + vector>> dis; + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++) + if(grid[i][j] == 1) + dis.push_back(bfs(grid, i, j)); + + int res = INT_MAX; + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++) + if(grid[i][j] == 0){ + int tres = 0; + for(int k = 0; k < dis.size(); k ++) + if(dis[k][i][j] == INT_MAX){ + tres = INT_MAX; + break; + } + else tres += dis[k][i][j]; + res = min(res, tres); + } + return res == INT_MAX ? -1 : res; + } + +private: + vector> bfs(const vector>& grid, int x, int y){ + + vector> dis(R, vector(C, INT_MAX)); + queue q; + q.push(x * C + y); + dis[x][y] = 0; + + while(!q.empty()){ + int cur = q.front(); q.pop(); + int cx = cur / C, cy = cur % C; + + for(int d = 0; d < 4; d ++){ + int nx = cx + dirs[d][0], ny = cy + dirs[d][1]; + if(0 <= nx && nx < R && 0 <= ny && ny < C && grid[nx][ny] == 0 && dis[nx][ny] == INT_MAX){ + dis[nx][ny] = 1 + dis[cx][cy]; + q.push(nx * C + ny); + } + } + } + return dis; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0318-Maximum-Product-of-Word-Lengths/cpp-0318/CMakeLists.txt b/0001-0500/0318-Maximum-Product-of-Word-Lengths/cpp-0318/CMakeLists.txt new file mode 100644 index 00000000..f0f8ad1a --- /dev/null +++ b/0001-0500/0318-Maximum-Product-of-Word-Lengths/cpp-0318/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_0318) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0318 main.cpp) \ No newline at end of file diff --git a/0001-0500/0318-Maximum-Product-of-Word-Lengths/cpp-0318/main.cpp b/0001-0500/0318-Maximum-Product-of-Word-Lengths/cpp-0318/main.cpp new file mode 100644 index 00000000..90dd7a46 --- /dev/null +++ b/0001-0500/0318-Maximum-Product-of-Word-Lengths/cpp-0318/main.cpp @@ -0,0 +1,41 @@ +/// Source : https://leetcode.com/problems/maximum-product-of-word-lengths/ +/// Author : liuyubobobo +/// Time : 2021-05-27 + +#include +#include + +using namespace std; + + +/// bitwise + brute force +/// Time Complexity: O(n * average_words_len + n^2) +/// Space Complexity: O(n) +class Solution { +public: + int maxProduct(vector& words) { + + int n = words.size(); + vector bits(n, 0); + for(int i = 0; i < n; i ++) + for(char c: words[i]) + bits[i] |= (1 << (c - 'a')); + + int res = 0; + for(int i = 0; i < n; i ++) + for(int j = i + 1; j < n; j ++) + if((bits[i] & bits[j]) == 0) + res = max(res, (int)words[i].size() * (int)words[j].size()); + return res; + } +}; + + +int main() { + + vector words1 = {"abcw","baz","foo","bar","xtfn","abcdef"}; + cout << Solution().maxProduct(words1) << endl; + // 16 + + return 0; +} diff --git a/0319-Bulb-Switcher/cpp-0319/CMakeLists.txt b/0001-0500/0319-Bulb-Switcher/cpp-0319/CMakeLists.txt similarity index 100% rename from 0319-Bulb-Switcher/cpp-0319/CMakeLists.txt rename to 0001-0500/0319-Bulb-Switcher/cpp-0319/CMakeLists.txt diff --git a/0319-Bulb-Switcher/cpp-0319/main.cpp b/0001-0500/0319-Bulb-Switcher/cpp-0319/main.cpp similarity index 100% rename from 0319-Bulb-Switcher/cpp-0319/main.cpp rename to 0001-0500/0319-Bulb-Switcher/cpp-0319/main.cpp diff --git a/0319-Bulb-Switcher/cpp-0319/main2.cpp b/0001-0500/0319-Bulb-Switcher/cpp-0319/main2.cpp similarity index 100% rename from 0319-Bulb-Switcher/cpp-0319/main2.cpp rename to 0001-0500/0319-Bulb-Switcher/cpp-0319/main2.cpp diff --git a/0001-0500/0321-Create-Maximum-Number/cpp-0321/CMakeLists.txt b/0001-0500/0321-Create-Maximum-Number/cpp-0321/CMakeLists.txt new file mode 100644 index 00000000..b35106c7 --- /dev/null +++ b/0001-0500/0321-Create-Maximum-Number/cpp-0321/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0321) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0321 main.cpp) \ No newline at end of file diff --git a/0001-0500/0321-Create-Maximum-Number/cpp-0321/main.cpp b/0001-0500/0321-Create-Maximum-Number/cpp-0321/main.cpp new file mode 100644 index 00000000..b7755ed1 --- /dev/null +++ b/0001-0500/0321-Create-Maximum-Number/cpp-0321/main.cpp @@ -0,0 +1,98 @@ +/// Source : https://leetcode.com/problems/create-maximum-number/ +/// Author : liuyubobobo +/// Time : 2020-12-02 + +#include +#include +#include + +using namespace std; + + +/// Mono Stack +/// Time Complexity: O(k * (|nums1| + |nums2|)) +/// Space Complexity: O(|nums1| + |nums2|) +class Solution { +public: + vector maxNumber(vector& nums1, vector& nums2, int k) { + + string s1 = "", s2 = ""; + for(int e: nums1) s1 += ('0' + e); + for(int e: nums2) s2 += ('0' + e); + + string res(k, '0'); + for(int i = 0; i <= k; i ++){ + int sz1 = i, sz2 = k - i; + if(sz1 >= 0 && sz1 <= nums1.size() && sz2 >= 0 && sz2 <= nums2.size()){ + string a = get(s1, sz1); + string b = get(s2, sz2); + assert(a.size() + b.size() == k); + + string tres = merge(a, b); + assert(tres.size() == k); + + if(tres > res) res = tres; + } + } + + vector ret; + for(char c: res) ret.push_back(c - '0'); + return ret; + } + +private: + string merge(const string& s1, const string& s2){ + + int i = 0, j = 0; + string res; + while(i < s1.size() && j < s2.size()){ + if(s1.substr(i) > s2.substr(j)) res += s1[i ++]; + else res += s2[j ++]; + } + if(j < s2.size()) res += s2.substr(j); + else if(i < s1.size()) res += s1.substr(i); + return res; + } + + string get(const string& s, int sz){ + + int remove = (int)s.size() - sz; + assert(remove >= 0); + + string stack = ""; + for(char c: s){ + while(stack != "" && remove && c > stack.back()) + stack.pop_back(), remove --; + stack += c; + } + while(stack.size() != sz) stack.pop_back(); + return stack; + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << " "; cout << endl; +} + +int main() { + + vector numsa1 = {3, 4, 6, 5}, numsb1 = {9, 1, 2, 5, 8, 3}; + print_vec(Solution().maxNumber(numsa1, numsb1, 5)); + // 9 8 6 5 3 + + vector numsa2 = {6, 7}, numsb2 = {6, 0, 4}; + print_vec(Solution().maxNumber(numsa2, numsb2, 5)); + // 6 7 6 0 4 + + vector numsa3 = {3, 9}, numsb3 = {8, 9}; + print_vec(Solution().maxNumber(numsa3, numsb3, 3)); + // 9 8 9 + + vector numsa4 = {1,6,5,4,7,3,9,5,3,7,8,4,1,1,4}; + vector numsb4 = {4,3,1,3,5,9}; + print_vec(Solution().maxNumber(numsa4, numsb4, 21)); + // 4,3,1,6,5,4,7,3,9,5,3,7,8,4,1,3,5,9,1,1,4 + + return 0; +} diff --git a/0322-Coin-Change/cpp-0322/CMakeLists.txt b/0001-0500/0322-Coin-Change/cpp-0322/CMakeLists.txt similarity index 100% rename from 0322-Coin-Change/cpp-0322/CMakeLists.txt rename to 0001-0500/0322-Coin-Change/cpp-0322/CMakeLists.txt diff --git a/0001-0500/0322-Coin-Change/cpp-0322/main.cpp b/0001-0500/0322-Coin-Change/cpp-0322/main.cpp new file mode 100644 index 00000000..464f4254 --- /dev/null +++ b/0001-0500/0322-Coin-Change/cpp-0322/main.cpp @@ -0,0 +1,71 @@ +/// Source : https://leetcode.com/problems/coin-change/solution/ +/// Author : liuyubobobo +/// Time : 2018-03-08 + +#include +#include +#include + +using namespace std; + +/// Memory Search +/// +/// Time Complexity: O(coins_size * amount) +/// Space Complexity: O(amount) +class Solution { + +private: + vector dp; + int max_amount; + +public: + int coinChange(vector& coins, int amount) { + max_amount = amount + 1; + dp = vector(amount+1, -1); + int res = search(coins, amount); + return res == max_amount ? -1 : res; + } + +private: + int search(const vector& coins, int amount){ + + if(amount == 0) + return 0; + + if(dp[amount] != -1) + return dp[amount]; + + int res = max_amount; + for(int coin: coins) + if(amount - coin >= 0) + res = min(res, 1 + search(coins, amount -coin)); + return dp[amount] = res; + } +}; + + +int main() { + + vector coins1 = {1, 2, 5}; + cout<< Solution().coinChange(coins1, 11) << endl; + // 3 + + vector coins2 = {2}; + cout << Solution().coinChange(coins2, 1) << endl; + // -1 + + vector coins3 = {2}; + int amount3 = 3; + cout << Solution().coinChange(coins3, 3) << endl; + // -1 + + vector coins4 = {2, 5, 10, 1}; + cout << Solution().coinChange(coins4, 27) << endl; + // 4 + + vector coins5 = {186, 419, 83, 408}; + cout << Solution().coinChange(coins5, 6249) << endl; + // 20 + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0322-Coin-Change/cpp-0322/main2.cpp b/0001-0500/0322-Coin-Change/cpp-0322/main2.cpp new file mode 100644 index 00000000..a34ec12a --- /dev/null +++ b/0001-0500/0322-Coin-Change/cpp-0322/main2.cpp @@ -0,0 +1,55 @@ +/// Source : https://leetcode.com/problems/coin-change/solution/ +/// Author : liuyubobobo +/// Time : 2018-03-08 + +#include +#include + +using namespace std; + +/// Dynamic Problem +/// 0-1 backpack problem +/// +/// Time Complexity: O(coins_size * amount) +/// Space Complexity: O(amount) +class Solution { +public: + int coinChange(vector& coins, int amount) { + + vector dp(amount+1, amount + 1); + dp[0] = 0; + + for(int coin: coins) + for(int j = coin ; j <= amount ; j ++) + dp[j] = min(dp[j], dp[j-coin] + 1); + + return dp[amount] == amount + 1 ? -1 : dp[amount]; + } +}; + + +int main() { + + vector coins1 = {1, 2, 5}; + cout<< Solution().coinChange(coins1, 11) << endl; + // 3 + + vector coins2 = {2}; + cout << Solution().coinChange(coins2, 1) << endl; + // -1 + + vector coins3 = {2}; + int amount3 = 3; + cout << Solution().coinChange(coins3, 3) << endl; + // -1 + + vector coins4 = {2, 5, 10, 1}; + cout << Solution().coinChange(coins4, 27) << endl; + // 4 + + vector coins5 = {186, 419, 83, 408}; + cout << Solution().coinChange(coins5, 6249) << endl; + // 20 + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0322-Coin-Change/cpp-0322/main3.cpp b/0001-0500/0322-Coin-Change/cpp-0322/main3.cpp new file mode 100644 index 00000000..a05b5423 --- /dev/null +++ b/0001-0500/0322-Coin-Change/cpp-0322/main3.cpp @@ -0,0 +1,56 @@ +/// Source : https://leetcode.com/problems/coin-change/solution/ +/// Author : liuyubobobo +/// Time : 2018-03-08 + +#include +#include + +using namespace std; + +/// Dynamic Problem +/// 0-1 backpack problem +/// +/// Time Complexity: O(coins_size * amount) +/// Space Complexity: O(amount) +class Solution { +public: + int coinChange(vector& coins, int amount) { + + vector dp(amount + 1, amount + 1); + dp[0] = 0; + + for(int i = 1 ; i <= amount ; i ++) + for(int coin: coins) + if(i - coin >= 0) + dp[i] = min(dp[i], dp[i-coin] + 1); + + return dp[amount] == amount + 1 ? -1 : dp[amount]; + } +}; + + +int main() { + + vector coins1 = {1, 2, 5}; + cout<< Solution().coinChange(coins1, 11) << endl; + // 3 + + vector coins2 = {2}; + cout << Solution().coinChange(coins2, 1) << endl; + // -1 + + vector coins3 = {2}; + int amount3 = 3; + cout << Solution().coinChange(coins3, 3) << endl; + // -1 + + vector coins4 = {2, 5, 10, 1}; + cout << Solution().coinChange(coins4, 27) << endl; + // 4 + + vector coins5 = {186, 419, 83, 408}; + cout << Solution().coinChange(coins5, 6249) << endl; + // 20 + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0322-Coin-Change/java-0322/src/Solution.java b/0001-0500/0322-Coin-Change/java-0322/src/Solution.java new file mode 100644 index 00000000..277ac283 --- /dev/null +++ b/0001-0500/0322-Coin-Change/java-0322/src/Solution.java @@ -0,0 +1,15 @@ +class Solution { + public int coinChange(int[] coins, int amount) { + + int n = coins.length; + + int[] dp = new int[amount + 1]; + for(int s = 0; s <= amount; s ++) dp[s] = Integer.MAX_VALUE / 2; + dp[0] = 0; + + for(int i = 0; i < n; i ++) + for(int s = coins[i]; s <= amount; s ++) + dp[s] = Math.min(dp[s], 1 + dp[s - coins[i]]); + return dp[amount] < Integer.MAX_VALUE / 2 ? dp[amount] : -1; + } +} \ No newline at end of file diff --git a/0001-0500/0323-Number-of-Connected-Components-in-an-Undirected-Graph/cpp-0323/CMakeLists.txt b/0001-0500/0323-Number-of-Connected-Components-in-an-Undirected-Graph/cpp-0323/CMakeLists.txt new file mode 100644 index 00000000..d1dc21d9 --- /dev/null +++ b/0001-0500/0323-Number-of-Connected-Components-in-an-Undirected-Graph/cpp-0323/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_0323) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0323 main.cpp) \ No newline at end of file diff --git a/0001-0500/0323-Number-of-Connected-Components-in-an-Undirected-Graph/cpp-0323/main.cpp b/0001-0500/0323-Number-of-Connected-Components-in-an-Undirected-Graph/cpp-0323/main.cpp new file mode 100644 index 00000000..ab3b26e0 --- /dev/null +++ b/0001-0500/0323-Number-of-Connected-Components-in-an-Undirected-Graph/cpp-0323/main.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/ +/// Author : liuyubobobo +/// Time : 2021-05-01 + +#include +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(V + E) +/// Space Complexity: O(V + E) +class Solution { +public: + int countComponents(int n, vector>& edges) { + + vector> g(n); + for(const vector& e: edges) + g[e[0]].push_back(e[1]), g[e[1]].push_back(e[0]); + + int res = 0; + vector visited(n, false); + for(int i = 0; i < n; i ++) + if(!visited[i]){ + res ++; + dfs(g, i, visited); + } + return res; + } + +private: + void dfs(const vector>& g, int u, vector& visited){ + + visited[u] = true; + for(int v: g[u]) + if(!visited[v]) dfs(g, v, visited); + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0324-Wiggle-Sort-II/cpp-0324/CMakeLists.txt b/0001-0500/0324-Wiggle-Sort-II/cpp-0324/CMakeLists.txt new file mode 100644 index 00000000..bab742ff --- /dev/null +++ b/0001-0500/0324-Wiggle-Sort-II/cpp-0324/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_0324) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0324 main.cpp) diff --git a/0001-0500/0324-Wiggle-Sort-II/cpp-0324/main.cpp b/0001-0500/0324-Wiggle-Sort-II/cpp-0324/main.cpp new file mode 100644 index 00000000..98cef480 --- /dev/null +++ b/0001-0500/0324-Wiggle-Sort-II/cpp-0324/main.cpp @@ -0,0 +1,71 @@ +/// Source : https://leetcode.com/problems/wiggle-sort-ii/ +/// Author : liuyubobobo +/// Time : 2022-06-27 + +#include +#include +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + void wiggleSort(vector& nums) { + + int n = nums.size(); + + sort(nums.begin(), nums.end()); + + vector res(n); + int index = 0; + for(int i = 0; i < n; i += 2) res[i] = nums[index ++]; + for(int i = 1; i < n; i += 2) res[i] = nums[index ++]; + + if(ok(n, res)){ + nums = res; + return; + } + + assert(n % 2 == 0); + + index = 0; + for(int i = 1; i < n; i += 2) res[i] = nums[index ++]; + for(int i = 0; i < n; i += 2) res[i] = nums[index ++]; + reverse(res.begin(), res.end()); + assert(ok(n, res)); + nums = res; + } + +private: + bool ok(int n, const vector& a){ + + for(int i = 1; i + 1 < n; i ++){ + if(i % 2 == 1){ + if(!(a[i - 1] < a[i] && a[i] > a[i + 1])) return false; + } + else{ + if(!(a[i - 1] > a[i] && a[i] < a[i + 1])) return false; + } + } + return true; + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << ' '; cout << '\n'; +} + +int main() { + + vector nums1 = {4, 5, 5, 6}; + Solution().wiggleSort(nums1); + print_vec(nums1); + + return 0; +} diff --git a/0001-0500/0325-Maximum-Size-Subarray-Sum-Equals-k/cpp-0325/CMakeLists.txt b/0001-0500/0325-Maximum-Size-Subarray-Sum-Equals-k/cpp-0325/CMakeLists.txt new file mode 100644 index 00000000..840f5e23 --- /dev/null +++ b/0001-0500/0325-Maximum-Size-Subarray-Sum-Equals-k/cpp-0325/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0325) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0325 main.cpp) diff --git a/0001-0500/0325-Maximum-Size-Subarray-Sum-Equals-k/cpp-0325/main.cpp b/0001-0500/0325-Maximum-Size-Subarray-Sum-Equals-k/cpp-0325/main.cpp new file mode 100644 index 00000000..4e1dfec2 --- /dev/null +++ b/0001-0500/0325-Maximum-Size-Subarray-Sum-Equals-k/cpp-0325/main.cpp @@ -0,0 +1,36 @@ +/// Source : https://leetcode.com/problems/maximum-size-subarray-sum-equals-k/ +/// Author : liuyubobobo +/// Time : 2021-09-29 + +#include +#include +#include + +using namespace std; + + +/// Using Map +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int maxSubArrayLen(vector& nums, int k) { + + map map; + map[0] = -1; + + int presum = 0, res = 0; + for(int i = 0; i < nums.size(); i ++){ + presum += nums[i]; + if(map.count(presum - k)) res = max(res, i - map[presum - k]); + if(!map.count(presum)) map[presum] = i; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0326-Power-of-Three/cpp-0326/CMakeLists.txt b/0001-0500/0326-Power-of-Three/cpp-0326/CMakeLists.txt new file mode 100644 index 00000000..afbb70ef --- /dev/null +++ b/0001-0500/0326-Power-of-Three/cpp-0326/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_0326) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0326 main.cpp) \ No newline at end of file diff --git a/0001-0500/0326-Power-of-Three/cpp-0326/main.cpp b/0001-0500/0326-Power-of-Three/cpp-0326/main.cpp new file mode 100644 index 00000000..bc69fb78 --- /dev/null +++ b/0001-0500/0326-Power-of-Three/cpp-0326/main.cpp @@ -0,0 +1,27 @@ +/// Source : https://leetcode.com/problems/implement-stack-using-queues/ +/// Author : liuyubobobo +/// Time : 2021-04-27 + +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(logn) +/// Space Complexity: O(1) +class Solution { +public: + bool isPowerOfThree(int n) { + + if(n <= 0) return false; + while(n % 3 == 0) n /= 3; + return n == 1; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0328-Odd-Even-Linked-List/cpp-0328/CMakeLists.txt b/0001-0500/0328-Odd-Even-Linked-List/cpp-0328/CMakeLists.txt new file mode 100644 index 00000000..cd5099a2 --- /dev/null +++ b/0001-0500/0328-Odd-Even-Linked-List/cpp-0328/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0328) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main2.cpp) +add_executable(cpp_0328 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0328-Odd-Even-Linked-List/cpp-0328/main.cpp b/0001-0500/0328-Odd-Even-Linked-List/cpp-0328/main.cpp new file mode 100644 index 00000000..f1261ff7 --- /dev/null +++ b/0001-0500/0328-Odd-Even-Linked-List/cpp-0328/main.cpp @@ -0,0 +1,60 @@ +/// Source : https://leetcode.com/problems/odd-even-linked-list/description/ +/// Author : liuyubobobo +/// Time : 2018-10-01 + +#include + +using namespace std; + + +/// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} +}; + + +/// Split the Linked List into two and then merge +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + ListNode* oddEvenList(ListNode* head) { + + if(head == NULL || head->next == NULL || head->next->next == NULL) + return head; + + ListNode* dummyHead1 = new ListNode(-1); + ListNode* dummyHead2 = new ListNode(-1); + ListNode* p1 = dummyHead1; + ListNode* p2 = dummyHead2; + ListNode* p = head; + for(int i = 0; p; i ++) + if(i % 2 == 0){ + p1->next = p; + p = p->next; + p1 = p1->next; + p1->next = NULL; + } + else{ + p2->next = p; + p = p->next; + p2 = p2->next; + p2->next = NULL; + } + + p1->next = dummyHead2->next; + ListNode* ret = dummyHead1->next; + + delete dummyHead1; + delete dummyHead2; + return ret; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0328-Odd-Even-Linked-List/cpp-0328/main2.cpp b/0001-0500/0328-Odd-Even-Linked-List/cpp-0328/main2.cpp new file mode 100644 index 00000000..36dae46f --- /dev/null +++ b/0001-0500/0328-Odd-Even-Linked-List/cpp-0328/main2.cpp @@ -0,0 +1,55 @@ +/// Source : https://leetcode.com/problems/odd-even-linked-list/description/ +/// Author : liuyubobobo +/// Time : 2018-10-01 + +#include + +using namespace std; + + +/// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} +}; + + +/// Split the Linked List into two and then merge +/// Keep one in original Linked List +/// +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + ListNode* oddEvenList(ListNode* head) { + + if(head == NULL || head->next == NULL || head->next->next == NULL) + return head; + + ListNode* dummyHead2 = new ListNode(-1); + ListNode* p2 = dummyHead2; + ListNode* p = head; + while(p->next){ + p2->next = p->next; + if(p->next->next == NULL){ + p->next = NULL; + break; + } + p->next = p->next->next; + p = p->next; + p2 = p2->next; + p2->next = NULL; + } + + p->next = dummyHead2->next; + delete dummyHead2; + return head; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0329-Longest-Increasing-Path-in-a-Matrix/cpp-0329/CMakeLists.txt b/0001-0500/0329-Longest-Increasing-Path-in-a-Matrix/cpp-0329/CMakeLists.txt new file mode 100644 index 00000000..fca6cff3 --- /dev/null +++ b/0001-0500/0329-Longest-Increasing-Path-in-a-Matrix/cpp-0329/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0329) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0329 main.cpp) \ No newline at end of file diff --git a/0001-0500/0329-Longest-Increasing-Path-in-a-Matrix/cpp-0329/main.cpp b/0001-0500/0329-Longest-Increasing-Path-in-a-Matrix/cpp-0329/main.cpp new file mode 100644 index 00000000..e52fab95 --- /dev/null +++ b/0001-0500/0329-Longest-Increasing-Path-in-a-Matrix/cpp-0329/main.cpp @@ -0,0 +1,70 @@ +/// Source : https://leetcode.com/problems/longest-increasing-path-in-a-matrix/ +/// Author : liuyubobobo +/// Time : 2021-02-25 + +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(R * C) +/// Space Complexity: O(R * C) +class Solution { + +private: + int R, C; + const int dirs[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; + +public: + int longestIncreasingPath(vector>& matrix) { + + R = matrix.size(); + if(R == 0) return 0; + + C = matrix[0].size(); + if(C == 0) return 0; + + vector> dp(R, vector(C, -1)); + int res = 1; + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++){ + if(dp[i][j] == -1) dfs(matrix, i, j, dp); + res = max(res, dp[i][j]); + } + return res; + } + +private: + int dfs(const vector>& matrix, int x, int y, vector>& dp){ + + if(dp[x][y] != -1) return dp[x][y]; + + int res = 1; + for(int d = 0; d < 4; d ++){ + int nextx = x + dirs[d][0], nexty = y + dirs[d][1]; + if(in_area(nextx, nexty) && matrix[nextx][nexty] > matrix[x][y]) + res = max(res, 1 + dfs(matrix, nextx, nexty, dp)); + } + return dp[x][y] = res; + } + + bool in_area(int x, int y){ + return x >= 0 && x < R && y >= 0 && y < C; + } +}; + + +int main() { + + vector> matrix1 = {{9,9,4},{6,6,8},{2,1,1}}; + cout << Solution().longestIncreasingPath(matrix1) << endl; + // 4 + + vector> matrix2 = {{3,4,5},{3,2,6},{2,2,1}}; + cout << Solution().longestIncreasingPath(matrix2) << endl; + // 4 + + return 0; +} diff --git a/0001-0500/0330-Patching-Array/cpp-0330/CMakeLists.txt b/0001-0500/0330-Patching-Array/cpp-0330/CMakeLists.txt new file mode 100644 index 00000000..29f32f7f --- /dev/null +++ b/0001-0500/0330-Patching-Array/cpp-0330/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0330) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0330 main.cpp) \ No newline at end of file diff --git a/0001-0500/0330-Patching-Array/cpp-0330/main.cpp b/0001-0500/0330-Patching-Array/cpp-0330/main.cpp new file mode 100644 index 00000000..44244bae --- /dev/null +++ b/0001-0500/0330-Patching-Array/cpp-0330/main.cpp @@ -0,0 +1,42 @@ +#include +#include + +using namespace std; + + +class Solution { +public: + int minPatches(vector& nums, int n) { + + long long r = 0ll; + int res = 0, i = 0; + while(r < n) + if(i < nums.size() && nums[i] <= r + 1) + r += nums[i ++]; + else + res ++, r += (r + 1); + return res; + } +}; + + +int main() { + + vector nums1 = {1, 3}; + cout << Solution().minPatches(nums1, 6) << endl; + // 1 + + vector nums2 = {1, 5, 10}; + cout << Solution().minPatches(nums2, 20) << endl; + // 2 + + vector nums3 = {1, 2, 2}; + cout << Solution().minPatches(nums3, 5) << endl; + // 0 + + vector nums4 = {}; + cout << Solution().minPatches(nums4, 7) << endl; + // 3 + + return 0; +} diff --git a/0001-0500/0331-Verify-Preorder-Serialization-of-a-Binary-Tree/cpp-0331/CMakeLists.txt b/0001-0500/0331-Verify-Preorder-Serialization-of-a-Binary-Tree/cpp-0331/CMakeLists.txt new file mode 100644 index 00000000..19fbeb43 --- /dev/null +++ b/0001-0500/0331-Verify-Preorder-Serialization-of-a-Binary-Tree/cpp-0331/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0331) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0331 main3.cpp) \ No newline at end of file diff --git a/0001-0500/0331-Verify-Preorder-Serialization-of-a-Binary-Tree/cpp-0331/main.cpp b/0001-0500/0331-Verify-Preorder-Serialization-of-a-Binary-Tree/cpp-0331/main.cpp new file mode 100644 index 00000000..c9b2717a --- /dev/null +++ b/0001-0500/0331-Verify-Preorder-Serialization-of-a-Binary-Tree/cpp-0331/main.cpp @@ -0,0 +1,72 @@ +/// Source : https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/ +/// Author : liuyubobobo +/// Time : 2021-03-11 + +#include +#include +#include + +using namespace std; + + +/// Using Stack to simulate +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + bool isValidSerialization(string preorder) { + + vector data; + for(int start = 0, i = 1; i <= preorder.size(); i ++) + if(i == preorder.size() || preorder[i] == ','){ + if(preorder[start] == '#') + data.push_back(-1); + else + data.push_back(atoi(preorder.substr(start, i - start).c_str())); + + start = i + 1; + i = start; + } + + if(data.size() == 1 && data[0] == -1) return true; + + stack> stack; + for(int i = 0; i < data.size(); i ++){ + int e = data[i]; + if(e == -1){ + if(stack.empty()) return false; + stack.top().second ++; + + while(!stack.empty() && stack.top().second == 2) + stack.pop(); + } + else{ + if(stack.empty()){ + if(i) return false; + } + else + stack.top().second ++; + stack.push({e, 0}); + } + } + return stack.empty(); + } +}; + + +int main() { + + cout << Solution().isValidSerialization("9,3,4,#,#,1,#,#,2,#,6,#,#") << endl; + // true + + cout << Solution().isValidSerialization("1,#") << endl; + // false + + cout << Solution().isValidSerialization("9,#,#,1") << endl; + // false + + cout << Solution().isValidSerialization("9,3,4,#,#,1,#,#,#,2,#,6,#,#") << endl; + // false + + return 0; +} diff --git a/0001-0500/0331-Verify-Preorder-Serialization-of-a-Binary-Tree/cpp-0331/main2.cpp b/0001-0500/0331-Verify-Preorder-Serialization-of-a-Binary-Tree/cpp-0331/main2.cpp new file mode 100644 index 00000000..eec2008f --- /dev/null +++ b/0001-0500/0331-Verify-Preorder-Serialization-of-a-Binary-Tree/cpp-0331/main2.cpp @@ -0,0 +1,59 @@ +/// Source : https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/ +/// Author : liuyubobobo +/// Time : 2021-03-11 + +#include +#include +#include + +using namespace std; + + +/// Using slots +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + bool isValidSerialization(string preorder) { + + vector data; + for(int start = 0, i = 1; i <= preorder.size(); i ++) + if(i == preorder.size() || preorder[i] == ','){ + if(preorder[start] == '#') + data.push_back(-1); + else + data.push_back(atoi(preorder.substr(start, i - start).c_str())); + + start = i + 1; + i = start; + } + + int slots = 1; + for(int e: data){ + slots --; + if(slots < 0) return false; + + if(e != -1) slots += 2; + + } + return slots == 0; + } +}; + + +int main() { + + cout << Solution().isValidSerialization("9,3,4,#,#,1,#,#,2,#,6,#,#") << endl; + // true + + cout << Solution().isValidSerialization("1,#") << endl; + // false + + cout << Solution().isValidSerialization("9,#,#,1") << endl; + // false + + cout << Solution().isValidSerialization("9,3,4,#,#,1,#,#,#,2,#,6,#,#") << endl; + // false + + return 0; +} diff --git a/0001-0500/0331-Verify-Preorder-Serialization-of-a-Binary-Tree/cpp-0331/main3.cpp b/0001-0500/0331-Verify-Preorder-Serialization-of-a-Binary-Tree/cpp-0331/main3.cpp new file mode 100644 index 00000000..88373d3f --- /dev/null +++ b/0001-0500/0331-Verify-Preorder-Serialization-of-a-Binary-Tree/cpp-0331/main3.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/ +/// Author : liuyubobobo +/// Time : 2021-03-11 + +#include +#include +#include + +using namespace std; + + +/// Split and using slots +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + bool isValidSerialization(string preorder) { + + int slots = 1; + for(int start = 0, i = 1; i <= preorder.size(); i ++) + if(i == preorder.size() || preorder[i] == ','){ + int cur = 0; + if(preorder[start] != '#') + cur = 1; + + slots --; + if(slots < 0) return false; + if(cur) slots += 2; + + start = i + 1; + i = start; + } + return slots == 0; + } +}; + + +int main() { + + cout << Solution().isValidSerialization("9,3,4,#,#,1,#,#,2,#,6,#,#") << endl; + // true + + cout << Solution().isValidSerialization("1,#") << endl; + // false + + cout << Solution().isValidSerialization("9,#,#,1") << endl; + // false + + cout << Solution().isValidSerialization("9,3,4,#,#,1,#,#,#,2,#,6,#,#") << endl; + // false + + return 0; +} diff --git a/0001-0500/0332-Reconstruct-Itinerary/cpp-0332/CMakeLists.txt b/0001-0500/0332-Reconstruct-Itinerary/cpp-0332/CMakeLists.txt new file mode 100644 index 00000000..67dee4eb --- /dev/null +++ b/0001-0500/0332-Reconstruct-Itinerary/cpp-0332/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_0332) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0332 main.cpp) diff --git a/0001-0500/0332-Reconstruct-Itinerary/cpp-0332/main.cpp b/0001-0500/0332-Reconstruct-Itinerary/cpp-0332/main.cpp new file mode 100644 index 00000000..d55f50d9 --- /dev/null +++ b/0001-0500/0332-Reconstruct-Itinerary/cpp-0332/main.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/reconstruct-itinerary/ +/// Author : liuyubobobo +/// Time : 2022-01-27 + +#include +#include +#include +#include + +using namespace std; + + +/// Euler Path +/// Time Complexity: O(V + E) +/// Space Complexity: O(V + E) +class Solution { +public: + vector findItinerary(vector>& tickets) { + + map> g; + for(const vector& e: tickets) g[e[0]].push_back(e[1]); + for(const pair>& p: g) + sort(g[p.first].begin(), g[p.first].end(), greater()); + + vector res; + + stack stack; + stack.push("JFK"); + while(!stack.empty()){ + if(g[stack.top()].size()){ + string u = stack.top(), v = g[u].back(); + stack.push(v); + g[u].pop_back(); + } + else{ + res.push_back(stack.top()); + stack.pop(); + } + } + + reverse(res.begin(), res.end()); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0334-Increasing-Triplet-Subsequence/cpp-0334/CMakeLists.txt b/0001-0500/0334-Increasing-Triplet-Subsequence/cpp-0334/CMakeLists.txt new file mode 100644 index 00000000..ad0640be --- /dev/null +++ b/0001-0500/0334-Increasing-Triplet-Subsequence/cpp-0334/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0334) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0334 main2.cpp) \ No newline at end of file diff --git a/0001-0500/0334-Increasing-Triplet-Subsequence/cpp-0334/main.cpp b/0001-0500/0334-Increasing-Triplet-Subsequence/cpp-0334/main.cpp new file mode 100644 index 00000000..1ff8305f --- /dev/null +++ b/0001-0500/0334-Increasing-Triplet-Subsequence/cpp-0334/main.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/increasing-triplet-subsequence/ +/// Author : liuyubobobo +/// Time : 2020-12-18 + +#include +#include + +using namespace std; + + +/// LIS +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + bool increasingTriplet(vector& nums) { + + vector dp = {nums[0]}; + for(int i = 1; i < nums.size(); i ++){ + vector::iterator iter = lower_bound(dp.begin(), dp.end(), nums[i]); + if(iter == dp.end()) + dp.push_back(nums[i]); + else + dp[iter - dp.begin()] = nums[i]; + + } + return dp.size() >= 3; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0334-Increasing-Triplet-Subsequence/cpp-0334/main2.cpp b/0001-0500/0334-Increasing-Triplet-Subsequence/cpp-0334/main2.cpp new file mode 100644 index 00000000..dbcfca95 --- /dev/null +++ b/0001-0500/0334-Increasing-Triplet-Subsequence/cpp-0334/main2.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/increasing-triplet-subsequence/ +/// Author : liuyubobobo +/// Time : 2020-12-18 + +#include +#include + +using namespace std; + + +/// LIS - but only for 3 elements +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + bool increasingTriplet(vector& nums) { + + int a = nums[0], b = INT_MAX; + for(int i = 1; i < nums.size(); i ++){ + if(nums[i] > b) return true; + else if(nums[i] <= b && nums[i] > a) b = nums[i]; + else{ + assert(nums[i] <= a); + a = nums[i]; + } + } + return false; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0335-Self-Crossing/cpp-0335/CMakeLists.txt b/0001-0500/0335-Self-Crossing/cpp-0335/CMakeLists.txt new file mode 100644 index 00000000..68d39435 --- /dev/null +++ b/0001-0500/0335-Self-Crossing/cpp-0335/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0335) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0335 main.cpp) diff --git a/0001-0500/0335-Self-Crossing/cpp-0335/main.cpp b/0001-0500/0335-Self-Crossing/cpp-0335/main.cpp new file mode 100644 index 00000000..626f5d61 --- /dev/null +++ b/0001-0500/0335-Self-Crossing/cpp-0335/main.cpp @@ -0,0 +1,91 @@ +/// Source : https://leetcode.com/problems/self-crossing/ +/// Author : liuyubobobo +/// Time : 2021-10-28 + +#include +#include + +using namespace std; + + +/// Geography +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { + +private: + typedef struct Point{ + long long x, y; + Point(long long x, long long y) : x(x), y(y){} + }Point; + + const int dirs[4][2] = {{0, 1}, {-1, 0}, {0, -1}, {1, 0}}; + +public: + bool isSelfCrossing(vector& dis) { + + int n = dis.size(); + int L = 5; + + vector> segs; + Point cur(0, 0); + for(int i = 0; i < n; i ++){ + Point next(cur.x + dirs[i % 4][0] * dis[i], cur.y + dirs[i % 4][1] * dis[i]); + segs.push_back({cur, next}); + + for(int j = i - 2; j >= max(0, i - L); j --) + if(intersect(segs[i].first, segs[i].second, segs[j].first, segs[j].second)) + return true; + + cur = next; + } + return false; + } + +private: + bool on_segment(Point p, Point q, Point r) + { + if (q.x <= max(p.x, r.x) && q.x >= min(p.x, r.x) && + q.y <= max(p.y, r.y) && q.y >= min(p.y, r.y)) + return true; + return false; + } + + int orientation(Point p, Point q, Point r) + { + long long val = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); + if (val == 0) return 0; // collinear + return (val > 0)? 1: 2; // clock or counterclock wise + } + + bool intersect(Point p1, Point q1, Point p2, Point q2){ + + int o1 = orientation(p1, q1, p2); + int o2 = orientation(p1, q1, q2); + int o3 = orientation(p2, q2, p1); + int o4 = orientation(p2, q2, q1); + + if (o1 != o2 && o3 != o4) + return true; + + if (o1 == 0 && on_segment(p1, p2, q1)) return true; + if (o2 == 0 && on_segment(p1, q2, q1)) return true; + if (o3 == 0 && on_segment(p2, p1, q2)) return true; + if (o4 == 0 && on_segment(p2, q1, q2)) return true; + return false; + } +}; + + +int main() { + + vector dis1 = {2, 1, 1, 2}; + cout << Solution().isSelfCrossing(dis1) << endl; + // 1 + + vector dis2 = {3, 3, 4, 2, 2}; + cout << Solution().isSelfCrossing(dis2) << endl; + // 0 + + return 0; +} diff --git a/0001-0500/0336-Palindrome-Pairs/cpp-0336/CMakeLists.txt b/0001-0500/0336-Palindrome-Pairs/cpp-0336/CMakeLists.txt new file mode 100644 index 00000000..d9c5c3b9 --- /dev/null +++ b/0001-0500/0336-Palindrome-Pairs/cpp-0336/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_0336) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0336 main.cpp) \ No newline at end of file diff --git a/0001-0500/0336-Palindrome-Pairs/cpp-0336/main.cpp b/0001-0500/0336-Palindrome-Pairs/cpp-0336/main.cpp new file mode 100644 index 00000000..94dc7526 --- /dev/null +++ b/0001-0500/0336-Palindrome-Pairs/cpp-0336/main.cpp @@ -0,0 +1,86 @@ +/// Source : https://leetcode.com/problems/palindrome-pairs/ +/// Author : liuyubobobo +/// Time : 2022-09-17 + +#include +#include +#include +#include + +using namespace std; + + +/// String Hash +/// Time Complexity: O(n^2 * k) where k is the average length pf each words +/// Space Complexity: O(n * k) +class Solution { + +private: + const unsigned long long B = 13331; + +public: + vector> palindromePairs(vector& words) { + + int n = words.size(); + vector> hash(n), rhash(n); + + int maxlen = 0; + for(int i = 0; i < n; i ++){ + int len = words[i].size(); + maxlen = max(maxlen, len); + + hash[i].resize(len + 1, 0); + for(int j = 0; j < len; j ++) + hash[i][j + 1] = hash[i][j] * B + words[i][j]; + + rhash[i].resize(len + 1, 0); + for(int j = len - 1; j >= 0; j --) + rhash[i][j] = rhash[i][j + 1] * B + words[i][j]; + } + + vector powB(maxlen + 1, 1); + for(int i = 1; i <= maxlen; i ++) powB[i] = powB[i - 1] * B; + + vector> res; + for(int i = 0; i < n; i ++){ + int len1 = words[i].size(); + for(int j = 0; j < n; j ++){ + + if(j == i) continue; + + int len2 = words[j].size(); + + if(len1 <= len2){ + if(hash[i].back() != rhash[j][len2 - len1]) continue; + if(hash[j][len2 - len1] != rhash[j][0] - rhash[j][len2 - len1] * powB[len2 - len1]) continue; + res.push_back({i, j}); + } + else{ // len1 > len2 + if(hash[i][len2] != rhash[j][0]) continue; + if(hash[i].back() - hash[i][len2] * powB[len1 - len2] != rhash[i][len2]) continue; + res.push_back({i, j}); + } + } + } + return res; + } +}; + + +void print_res(const vector>& v){ + for(const vector& e: v) + cout << "(" << e[0] << "," << e[1] << ")"; + cout << '\n'; +} + +int main() { + + vector words1 = {"a","ab"}; + print_res(Solution().palindromePairs(words1)); + + vector words2 = {"abcd","dcba","lls","s","sssll"}; + print_res(Solution().palindromePairs(words2)); + // [[0,1],[1,0],[3,2],[2,4]] + + return 0; +} diff --git a/0337-House-Robber-III/cpp-0337/CMakeLists.txt b/0001-0500/0337-House-Robber-III/cpp-0337/CMakeLists.txt similarity index 100% rename from 0337-House-Robber-III/cpp-0337/CMakeLists.txt rename to 0001-0500/0337-House-Robber-III/cpp-0337/CMakeLists.txt diff --git a/0337-House-Robber-III/cpp-0337/main.cpp b/0001-0500/0337-House-Robber-III/cpp-0337/main.cpp similarity index 100% rename from 0337-House-Robber-III/cpp-0337/main.cpp rename to 0001-0500/0337-House-Robber-III/cpp-0337/main.cpp diff --git a/0337-House-Robber-III/cpp-0337/main2.cpp b/0001-0500/0337-House-Robber-III/cpp-0337/main2.cpp similarity index 100% rename from 0337-House-Robber-III/cpp-0337/main2.cpp rename to 0001-0500/0337-House-Robber-III/cpp-0337/main2.cpp diff --git a/0337-House-Robber-III/cpp-0337/main3.cpp b/0001-0500/0337-House-Robber-III/cpp-0337/main3.cpp similarity index 100% rename from 0337-House-Robber-III/cpp-0337/main3.cpp rename to 0001-0500/0337-House-Robber-III/cpp-0337/main3.cpp diff --git a/0001-0500/0338-Counting-Bits/cpp-0338/CMakeLists.txt b/0001-0500/0338-Counting-Bits/cpp-0338/CMakeLists.txt new file mode 100644 index 00000000..4036aa14 --- /dev/null +++ b/0001-0500/0338-Counting-Bits/cpp-0338/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0338) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0338 main.cpp) \ No newline at end of file diff --git a/0001-0500/0338-Counting-Bits/cpp-0338/main.cpp b/0001-0500/0338-Counting-Bits/cpp-0338/main.cpp new file mode 100644 index 00000000..5354e05d --- /dev/null +++ b/0001-0500/0338-Counting-Bits/cpp-0338/main.cpp @@ -0,0 +1,29 @@ +/// Source : https://leetcode.com/problems/counting-bits/ +/// Author : liuyubobobo +/// Time : 2021-03-02 + +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector countBits(int num) { + + vector dp(num + 1, 0); + for(int i = 1; i <= num; i ++) + dp[i] = 1 + dp[i - (i & (-i))]; + return dp; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0339-Nested-List-Weight-Sum/cpp-0339/CMakeLists.txt b/0001-0500/0339-Nested-List-Weight-Sum/cpp-0339/CMakeLists.txt new file mode 100644 index 00000000..03b92b43 --- /dev/null +++ b/0001-0500/0339-Nested-List-Weight-Sum/cpp-0339/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0339) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0339 main.cpp) \ No newline at end of file diff --git a/0001-0500/0339-Nested-List-Weight-Sum/cpp-0339/main.cpp b/0001-0500/0339-Nested-List-Weight-Sum/cpp-0339/main.cpp new file mode 100644 index 00000000..479fdc52 --- /dev/null +++ b/0001-0500/0339-Nested-List-Weight-Sum/cpp-0339/main.cpp @@ -0,0 +1,65 @@ +/// Source : https://leetcode.com/problems/nested-list-weight-sum/ +/// Author : liuyubobobo +/// Time : 2021-01-15 + +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(h) + +// This is the interface that allows for creating nested lists. +// You should not implement it, or speculate about its implementation +class NestedInteger { + public: + // Constructor initializes an empty nested list. + NestedInteger(); + + // Constructor initializes a single integer. + NestedInteger(int value); + + // Return true if this NestedInteger holds a single integer, rather than a nested list. + bool isInteger() const; + + // Return the single integer that this NestedInteger holds, if it holds a single integer + // The result is undefined if this NestedInteger holds a nested list + int getInteger() const; + + // Set this NestedInteger to hold a single integer. + void setInteger(int value); + + // Set this NestedInteger to hold a nested list and adds a nested integer to it. + void add(const NestedInteger &ni); + + // Return the nested list that this NestedInteger holds, if it holds a nested list + // The result is undefined if this NestedInteger holds a single integer + const vector &getList() const; +}; + +class Solution { +public: + int depthSum(vector& nestedList) { + + return depthSum(nestedList, 1); + } + +private: + int depthSum(const vector& nestedList, int d){ + + int res = 0; + for(const NestedInteger& e: nestedList) + if(e.isInteger()) res += d * e.getInteger(); + else res += depthSum(e.getList(), d + 1); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0340-Longest-Substring-with-At-Most-K-Distinct-Characters/cpp-0340/CMakeLists.txt b/0001-0500/0340-Longest-Substring-with-At-Most-K-Distinct-Characters/cpp-0340/CMakeLists.txt new file mode 100644 index 00000000..5848e04f --- /dev/null +++ b/0001-0500/0340-Longest-Substring-with-At-Most-K-Distinct-Characters/cpp-0340/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(cpp_0340) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0340 main.cpp) \ No newline at end of file diff --git a/0001-0500/0340-Longest-Substring-with-At-Most-K-Distinct-Characters/cpp-0340/main.cpp b/0001-0500/0340-Longest-Substring-with-At-Most-K-Distinct-Characters/cpp-0340/main.cpp new file mode 100644 index 00000000..3c803a81 --- /dev/null +++ b/0001-0500/0340-Longest-Substring-with-At-Most-K-Distinct-Characters/cpp-0340/main.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/ +/// Author : liuyubobobo +/// Time : 2019-02-23 + +#include +#include +#include + +using namespace std; + + +/// Sliding Window +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int lengthOfLongestSubstringKDistinct(string s, int k) { + + if(!k) return 0; + + int l = 0, r = -1, res = 0; + unordered_map freq; + while(r + 1 < s.size()){ + + while(r + 1 < s.size() && ok(freq, s[r + 1], k)) + freq[s[r + 1]] ++, r ++; + // assert(freq.size() == k); + res = max(res, r - l + 1); + + while(l <= r && freq.size() >= k){ + freq[s[l]] --; + if(freq[s[l]] == 0) freq.erase(s[l]); + l ++; + } + } + return res; + } + +private: + bool ok(const unordered_map& freq, char c, int k){ + + if(freq.size() <= k - 1) return true; + + assert(freq.size() == k); + return freq.count(c); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0340-Longest-Substring-with-At-Most-K-Distinct-Characters/cpp-0340/main2.cpp b/0001-0500/0340-Longest-Substring-with-At-Most-K-Distinct-Characters/cpp-0340/main2.cpp new file mode 100644 index 00000000..aa08b6a7 --- /dev/null +++ b/0001-0500/0340-Longest-Substring-with-At-Most-K-Distinct-Characters/cpp-0340/main2.cpp @@ -0,0 +1,43 @@ +/// Source : https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/ +/// Author : liuyubobobo +/// Time : 2019-02-23 + +#include +#include +#include + +using namespace std; + + +/// Sliding Window (Another implement version) +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int lengthOfLongestSubstringKDistinct(string s, int k) { + + if(!k) return 0; + + int l = 0, r = -1, res = 0; + unordered_map freq; + while(r + 1 < s.size()){ + + if(freq.size() < k || freq.count(s[r + 1])) + freq[s[r + 1]] ++, r ++; + else{ + freq[s[l]] --; + if(freq[s[l]] == 0) freq.erase(s[l]); + l ++; + } + + res = max(res, r - l + 1); + } + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0341-Flatten-Nested-List-Iterator/cpp-0341/CMakeLists.txt b/0001-0500/0341-Flatten-Nested-List-Iterator/cpp-0341/CMakeLists.txt new file mode 100644 index 00000000..3da70caf --- /dev/null +++ b/0001-0500/0341-Flatten-Nested-List-Iterator/cpp-0341/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(cpp_0341) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0341 main.cpp) \ No newline at end of file diff --git a/0001-0500/0341-Flatten-Nested-List-Iterator/cpp-0341/main.cpp b/0001-0500/0341-Flatten-Nested-List-Iterator/cpp-0341/main.cpp new file mode 100644 index 00000000..39db2d88 --- /dev/null +++ b/0001-0500/0341-Flatten-Nested-List-Iterator/cpp-0341/main.cpp @@ -0,0 +1,69 @@ +/// Source : https://leetcode.com/problems/flatten-nested-list-iterator/ +/// Author : liuyubobobo +/// Time : 2019-06-10 + +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(h) + +// This is the interface that allows for creating nested lists. +// You should not implement it, or speculate about its implementation +class NestedInteger { + +public: + // Return true if this NestedInteger holds a single integer, rather than a nested list. + bool isInteger() const{return true;} + + // Return the single integer that this NestedInteger holds, if it holds a single integer + // The result is undefined if this NestedInteger holds a nested list + int getInteger() const{return -1;} + + // Return the nested list that this NestedInteger holds, if it holds a nested list + // The result is undefined if this NestedInteger holds a single integer + const vector &getList() const{return {};} +}; + +class NestedIterator { + +private: + vector data; + int i; + +public: + NestedIterator(vector &nestedList) { + + dfs(nestedList); + i = 0; + } + + int next() { + + return data[i ++]; + } + + bool hasNext() { + return i < data.size(); + } + +private: + void dfs(const vector& nestedList){ + + for(const NestedInteger& e: nestedList) + if(e.isInteger()) + data.push_back(e.getInteger()); + else + dfs(e.getList()); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0342-Power-of-Four/cpp-0342/CMakeLists.txt b/0001-0500/0342-Power-of-Four/cpp-0342/CMakeLists.txt new file mode 100644 index 00000000..762c1e9a --- /dev/null +++ b/0001-0500/0342-Power-of-Four/cpp-0342/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_0342) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0342 main.cpp) \ No newline at end of file diff --git a/0001-0500/0342-Power-of-Four/cpp-0342/main.cpp b/0001-0500/0342-Power-of-Four/cpp-0342/main.cpp new file mode 100644 index 00000000..96bdbd63 --- /dev/null +++ b/0001-0500/0342-Power-of-Four/cpp-0342/main.cpp @@ -0,0 +1,26 @@ +/// Source : https://leetcode.com/problems/power-of-four/ +/// Author : liuyubobobo +/// Time : 2021-04-27 + +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(logn) +/// Space Complexity: O(1) +class Solution { +public: + bool isPowerOfFour(int n) { + if(n <= 0) return false; + while(n % 4 == 0) n /= 4; + return n == 1; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0343-Integer-Break/cpp-0343/CMakeLists.txt b/0001-0500/0343-Integer-Break/cpp-0343/CMakeLists.txt new file mode 100644 index 00000000..edb8411e --- /dev/null +++ b/0001-0500/0343-Integer-Break/cpp-0343/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0343) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main4.cpp) +add_executable(cpp_0343 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0343-Integer-Break/cpp-0343/main.cpp b/0001-0500/0343-Integer-Break/cpp-0343/main.cpp new file mode 100644 index 00000000..35160ff4 --- /dev/null +++ b/0001-0500/0343-Integer-Break/cpp-0343/main.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/integer-break/description/ +/// Author : liuyubobobo +/// Time : 2017-11-19 + +#include +#include +#include + +using namespace std; + +/// Memory Search +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { +private: + vector memo; + + int max3(int a, int b, int c){ + return max(a, max(b, c)); + } + + int breakInteger(int n){ + + if(n == 1) + return 1; + + if(memo[n] != -1) + return memo[n]; + + int res = -1; + for(int i = 1 ; i <= n - 1 ; i ++) + res = max3(res, i * (n - i) , i * breakInteger(n - i)); + memo[n] = res; + return res; + } + +public: + int integerBreak(int n) { + assert(n >= 1); + memo.clear(); + for(int i = 0 ; i < n + 1 ; i ++) + memo.push_back(-1); + return breakInteger(n); + } +}; + + +int main() { + + cout << Solution().integerBreak(2) << endl; + cout << Solution().integerBreak(10) << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0343-Integer-Break/cpp-0343/main2.cpp b/0001-0500/0343-Integer-Break/cpp-0343/main2.cpp new file mode 100644 index 00000000..f10f9dfb --- /dev/null +++ b/0001-0500/0343-Integer-Break/cpp-0343/main2.cpp @@ -0,0 +1,45 @@ +/// Source : https://leetcode.com/problems/integer-break/description/ +/// Author : liuyubobobo +/// Time : 2017-11-19 + +#include +#include + +using namespace std; + +/// Dynamic Programming +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { + +private: + int max3(int a, int b, int c ){ + return max(max(a, b), c); + } + +public: + int integerBreak(int n) { + + assert(n >= 1); + + vector memo(n + 1, -1); + + memo[1] = 1; + for(int i = 2 ; i <= n ; i ++) + for(int j = 1 ; j <= i - 1 ; j ++) + memo[i] = max3(memo[i], j * (i - j), j * memo[i - j]); + + return memo[n]; + } +}; + + +int main() { + + cout << Solution().integerBreak(2) << endl; + cout << Solution().integerBreak(3) << endl; + cout << Solution().integerBreak(4) << endl; + cout << Solution().integerBreak(10) << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0343-Integer-Break/cpp-0343/main3.cpp b/0001-0500/0343-Integer-Break/cpp-0343/main3.cpp new file mode 100644 index 00000000..27d53d07 --- /dev/null +++ b/0001-0500/0343-Integer-Break/cpp-0343/main3.cpp @@ -0,0 +1,45 @@ +/// Source : https://leetcode.com/problems/integer-break/description/ +/// Author : liuyubobobo +/// Time : 2019-07-24 + +#include +#include + +using namespace std; + +/// Dynamic Programming +/// Deal with 2, 3 and 4 seperately +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { + +public: + int integerBreak(int n) { + + assert(n >= 1); + if(n == 2) return 1; + if(n == 3) return 2; + + vector memo(n + 1, -1); + memo[0] = 0; + memo[1] = 1; + memo[2] = 2; + memo[3] = 3; + for(int i = 2 ; i <= n ; i ++) + for(int j = 1 ; j <= i / 2 ; j ++) + memo[i] = max(memo[i], memo[j] * memo[i - j]); + + return memo[n]; + } +}; + + +int main() { + + cout << Solution().integerBreak(2) << endl; + cout << Solution().integerBreak(3) << endl; + cout << Solution().integerBreak(4) << endl; + cout << Solution().integerBreak(10) << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0343-Integer-Break/cpp-0343/main4.cpp b/0001-0500/0343-Integer-Break/cpp-0343/main4.cpp new file mode 100644 index 00000000..c1987717 --- /dev/null +++ b/0001-0500/0343-Integer-Break/cpp-0343/main4.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/integer-break/description/ +/// Author : liuyubobobo +/// Time : 2021-03-27 + +#include +#include + +using namespace std; + +/// Mathematics +/// Time Complexity: O(log(n)) +/// Space Complexity: O(log(n)) +class Solution { +public: + int integerBreak(int n) { + + if(n <= 2) return 1; + if(n == 3) return 2; + + int n3 = n / 3; + if(n % 3 == 1) n3 --; + + int res = mypow(3, n3); + if(n % 3 == 1) res = res * 4; + if(n % 3 == 2) res = res * 2; + return res; + } + +private: + int mypow(int a, int k){ + + if(k == 0) return 1; + + int t = mypow(a, k / 2); + int res = t * t; + if(k % 2) res = res * a; + return res; + } +}; + + +int main() { + + cout << Solution().integerBreak(2) << endl; + cout << Solution().integerBreak(3) << endl; + cout << Solution().integerBreak(4) << endl; + cout << Solution().integerBreak(10) << endl; + + return 0; +} \ No newline at end of file diff --git a/0343-Integer-Break/java-0343/src/Solution1.java b/0001-0500/0343-Integer-Break/java-0343/src/Solution1.java similarity index 100% rename from 0343-Integer-Break/java-0343/src/Solution1.java rename to 0001-0500/0343-Integer-Break/java-0343/src/Solution1.java diff --git a/0343-Integer-Break/java-0343/src/Solution2.java b/0001-0500/0343-Integer-Break/java-0343/src/Solution2.java similarity index 100% rename from 0343-Integer-Break/java-0343/src/Solution2.java rename to 0001-0500/0343-Integer-Break/java-0343/src/Solution2.java diff --git a/0001-0500/0343-Integer-Break/java-0343/src/Solution3.java b/0001-0500/0343-Integer-Break/java-0343/src/Solution3.java new file mode 100644 index 00000000..f82cfef4 --- /dev/null +++ b/0001-0500/0343-Integer-Break/java-0343/src/Solution3.java @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/integer-break/description/ +/// Author : liuyubobobo +/// Time : 2019-07-24 + +/// Dynamic Programming +/// Deal with 2, 3 and 4 seperately +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +public class Solution3 { + + public int integerBreak(int n) { + + if(n < 1) + throw new IllegalArgumentException("n should be greater than zero"); + if(n == 2) return 1; + if(n == 3) return 2; + + int[] memo = new int[n+1]; + memo[1] = 1; + memo[2] = 2; + memo[3] = 3; + for(int i = 2 ; i <= n ; i ++) + for(int j = 1 ; j <= i / 2 ; j ++) + memo[i] = Math.max(memo[i], memo[j] * memo[i - j]); + + return memo[n]; + } + + public static void main(String[] args) { + + System.out.println((new Solution2()).integerBreak(2)); + System.out.println((new Solution2()).integerBreak(10)); + } +} diff --git a/0001-0500/0344-Reverse-String/cpp-0344/CMakeLists.txt b/0001-0500/0344-Reverse-String/cpp-0344/CMakeLists.txt new file mode 100644 index 00000000..fbfb09af --- /dev/null +++ b/0001-0500/0344-Reverse-String/cpp-0344/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0344) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0344 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0344-Reverse-String/cpp-0344/main.cpp b/0001-0500/0344-Reverse-String/cpp-0344/main.cpp new file mode 100644 index 00000000..00aef259 --- /dev/null +++ b/0001-0500/0344-Reverse-String/cpp-0344/main.cpp @@ -0,0 +1,31 @@ +/// Source : https://leetcode.com/problems/reverse-string/description/ +/// Author : liuyubobobo +/// Time : 2018-06-04 + +#include + +using namespace std; + +/// Two Pointers +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + void reverseString(vector& s) { + + int i = 0, j = s.size() - 1; + while(i < j){ + swap(s[i], s[j]); + i ++; + j --; + } + } +}; + + +int main() { + + cout << Solution().reverseString("hello") << endl; + + return 0; +} \ No newline at end of file diff --git a/old/0345 Reverse Vowels of a String/cpp-Reverse-Vowels-of-a-String/CMakeLists.txt b/0001-0500/0345-Reverse-Vowels-of-a-String/cpp-0345/CMakeLists.txt similarity index 100% rename from old/0345 Reverse Vowels of a String/cpp-Reverse-Vowels-of-a-String/CMakeLists.txt rename to 0001-0500/0345-Reverse-Vowels-of-a-String/cpp-0345/CMakeLists.txt diff --git a/0001-0500/0345-Reverse-Vowels-of-a-String/cpp-0345/main.cpp b/0001-0500/0345-Reverse-Vowels-of-a-String/cpp-0345/main.cpp new file mode 100644 index 00000000..259ed7d6 --- /dev/null +++ b/0001-0500/0345-Reverse-Vowels-of-a-String/cpp-0345/main.cpp @@ -0,0 +1,59 @@ +/// Source : https://leetcode.com/problems/reverse-vowels-of-a-string/ +/// Author : liuyubobobo +/// Time : 2016-12-06 +#include +#include +#include +#include +#include + +using namespace std; + + +/// Two Pointers +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + string reverseVowels(string s) { + + int i = nextVowelIndex(s, 0); + int j = preVowelIndex(s, s.size() - 1); + while(i < j){ + swap(s[i], s[j]); + i = nextVowelIndex(s, i + 1); + j = preVowelIndex(s, j - 1); + } + + return s; + } + +private: + int nextVowelIndex(const string &s, int index){ + for(int i = index ; i < s.size() ; i ++) + if(isVowel(s[i])) + return i; + return s.size(); + } + + int preVowelIndex(const string &s, int index ){ + for(int i = index ; i >= 0 ; i --) + if(isVowel(s[i])) + return i; + return -1; + } + + bool isVowel(char c){ + char lowerc = tolower(c); + return lowerc == 'a' || lowerc == 'e' || lowerc == 'i' || lowerc == 'o' || lowerc == 'u'; + } +}; + + +int main() { + + cout << Solution().reverseVowels("hello") << endl; + cout << Solution().reverseVowels("leetcode") << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0346-Moving-Average-from-Data-Stream/cpp-0346/CMakeLists.txt b/0001-0500/0346-Moving-Average-from-Data-Stream/cpp-0346/CMakeLists.txt new file mode 100644 index 00000000..6e69e41a --- /dev/null +++ b/0001-0500/0346-Moving-Average-from-Data-Stream/cpp-0346/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0346) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0346 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0346-Moving-Average-from-Data-Stream/cpp-0346/main.cpp b/0001-0500/0346-Moving-Average-from-Data-Stream/cpp-0346/main.cpp new file mode 100644 index 00000000..b6ca3e8e --- /dev/null +++ b/0001-0500/0346-Moving-Average-from-Data-Stream/cpp-0346/main.cpp @@ -0,0 +1,45 @@ +/// Source : https://leetcode.com/problems/moving-average-from-data-stream/description/ +/// Author : liuyubobobo +/// Time : 2018-08-24 + +#include +#include + +using namespace std; + + +/// Using Queue +/// Time Complexity: O(1) +/// Space Complexity: O(size) +class MovingAverage { + +private: + queue q; + int sz, sum; + +public: + /** Initialize your data structure here. */ + MovingAverage(int size) { + sz = size; + sum = 0; + } + + double next(int val) { + + if(q.size() == sz){ + sum -= q.front(); + q.pop(); + } + + sum += val; + q.push(val); + + return (double)sum / q.size(); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0347-Top-K-Frequent-Elements/cpp-0347/CMakeLists.txt b/0001-0500/0347-Top-K-Frequent-Elements/cpp-0347/CMakeLists.txt new file mode 100644 index 00000000..3b327873 --- /dev/null +++ b/0001-0500/0347-Top-K-Frequent-Elements/cpp-0347/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0347) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main4.cpp) +add_executable(cpp_0347 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0347-Top-K-Frequent-Elements/cpp-0347/main.cpp b/0001-0500/0347-Top-K-Frequent-Elements/cpp-0347/main.cpp new file mode 100644 index 00000000..d790e292 --- /dev/null +++ b/0001-0500/0347-Top-K-Frequent-Elements/cpp-0347/main.cpp @@ -0,0 +1,61 @@ +/// Source : https://leetcode.com/problems/top-k-frequent-elements/description/ +/// Author : liuyubobobo +/// Time : 2017-11-17 + +#include +#include +#include +#include +#include + +using namespace std; + +/// Using Tree Set +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { + +public: + vector topKFrequent(vector& nums, int k) { + + assert(k > 0); + + unordered_map freq; + for(int num: nums) + freq[num] ++; + +// cout << "freq:" << endl; +// for(pairp: freq) +// cout << "v: " << p.first << " f: " << p.second << endl; +// cout << endl; + + assert(k <= freq.size()); + + set, greater>> record; + for(pair p: freq) + record.insert(make_pair(p.second, p.first)); + + vector res; + for(int i = 0 ; i < k ; i ++){ + set>::iterator iter = record.begin(); + advance(iter, i); + assert(iter != record.end()); + res.push_back(iter->second); + } + + return res; + } +}; + + +void print_vec(const vector& vec){ + for(int e: vec) cout << e << " "; cout << endl; +} + +int main() { + + vector nums = {1, 1, 1, 2, 2, 3}; + print_vec(Solution().topKFrequent(nums, 2)); + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0347-Top-K-Frequent-Elements/cpp-0347/main2.cpp b/0001-0500/0347-Top-K-Frequent-Elements/cpp-0347/main2.cpp new file mode 100644 index 00000000..016bc001 --- /dev/null +++ b/0001-0500/0347-Top-K-Frequent-Elements/cpp-0347/main2.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/top-k-frequent-elements/description/ +/// Author : liuyubobobo +/// Time : 2017-11-17 + +#include +#include +#include +#include +#include + +using namespace std; + +/// Sorting +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { + +private: + unordered_map freq; + +public: + vector topKFrequent(vector& nums, int k) { + + assert(k > 0); + + freq.clear(); + for(int i = 0 ; i < nums.size() ; i ++ ) + freq[nums[i]] ++; + + assert(k <= freq.size()); + + vector res; + for(pair p: freq) + res.push_back(p.first); + + sort(res.begin(), res.end(), [this](int a, int b){ + if(this->freq[a] != this->freq[b]) + return this->freq[a] > this->freq[b]; + return a < b; + }); + + return vector(res.begin(), res.begin() + k); + } +}; + + +void print_vec(const vector& vec){ + for(int e: vec) cout << e << " "; cout << endl; +} + +int main() { + + vector nums = {1, 1, 1, 2, 2, 3}; + print_vec(Solution().topKFrequent(nums, 2)); + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0347-Top-K-Frequent-Elements/cpp-0347/main3.cpp b/0001-0500/0347-Top-K-Frequent-Elements/cpp-0347/main3.cpp new file mode 100644 index 00000000..2618a042 --- /dev/null +++ b/0001-0500/0347-Top-K-Frequent-Elements/cpp-0347/main3.cpp @@ -0,0 +1,62 @@ +/// Source : https://leetcode.com/problems/top-k-frequent-elements/description/ +/// Author : liuyubobobo +/// Time : 2017-11-17 + +#include +#include +#include +#include +#include + +using namespace std; + +/// Priority Queue +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + vector topKFrequent(vector& nums, int k) { + + assert(k > 0); + + // 统计每个元素出现的频率 + unordered_map freq; + for(int i = 0 ; i < nums.size() ; i ++ ) + freq[nums[i]] ++; + + assert(k <= freq.size()); + + // 扫描freq,维护当前出现频率最高的k个元素 + // 在优先队列中,按照频率排序,所以数据对是 (频率,元素) 的形式 + priority_queue, vector>, greater>> pq; + for(const pair& p: freq){ + if(pq.size() == k && p.second > pq.top().first) pq.pop(); + if(pq.size() < k) pq.push(make_pair(p.second , p.first)); + } + + vector res; + while(!pq.empty()){ + res.push_back(pq.top().second); + pq.pop(); + } + + return res; + } +}; + + +void print_vec(const vector& vec){ + for(int e: vec) cout << e << " "; cout << endl; +} + +int main() { + + vector nums1 = {1, 1, 1, 2, 2, 3}; + print_vec(Solution().topKFrequent(nums1, 2)); + + vector nums2 = {3, 0, 1, 0}; + print_vec(Solution().topKFrequent(nums2, 1)); + // 0 + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0347-Top-K-Frequent-Elements/cpp-0347/main4.cpp b/0001-0500/0347-Top-K-Frequent-Elements/cpp-0347/main4.cpp new file mode 100644 index 00000000..8e1e47a4 --- /dev/null +++ b/0001-0500/0347-Top-K-Frequent-Elements/cpp-0347/main4.cpp @@ -0,0 +1,63 @@ +/// Source : https://leetcode.com/problems/top-k-frequent-elements/description/ +/// Author : liuyubobobo +/// Time : 2020-03-13 + +#include +#include +#include +#include +#include +#include + +using namespace std; + +/// Priority Queue for n-k elements +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + vector topKFrequent(vector& nums, int k) { + + assert(k > 0); + + // 统计每个元素出现的频率 + unordered_map freq; + for(int i = 0 ; i < nums.size() ; i ++ ) + freq[nums[i]] ++; + + assert(k <= freq.size()); + + // 扫描freq,维护当前出现频率最低的 n - k 个元素 + // 在优先队列中,按照频率排序,所以数据对是 (频率,元素) 的形式 + priority_queue> pq; + for(const pair& p: freq){ + if(freq.size() - k && pq.size() == freq.size() - k && p.second < pq.top().first) pq.pop(); + if(pq.size() < freq.size() - k) pq.push(make_pair(p.second , p.first)); + } + + set not_contains; + while(!pq.empty()){ + not_contains.insert(pq.top().second); + pq.pop(); + } + + vector res; + for(const pair& p: freq) + if(!not_contains.count(p.first)) + res.push_back(p.first); + return res; + } +}; + + +void print_vec(const vector& vec){ + for(int e: vec) cout << e << " "; cout << endl; +} + +int main() { + + vector nums = {1, 1, 1, 2, 2, 3}; + print_vec(Solution().topKFrequent(nums, 2)); + + return 0; +} \ No newline at end of file diff --git a/0347-Top-K-Frequent-Elements/java-0347/src/Solution1.java b/0001-0500/0347-Top-K-Frequent-Elements/java-0347/src/Solution1.java similarity index 100% rename from 0347-Top-K-Frequent-Elements/java-0347/src/Solution1.java rename to 0001-0500/0347-Top-K-Frequent-Elements/java-0347/src/Solution1.java diff --git a/0347-Top-K-Frequent-Elements/java-0347/src/Solution2.java b/0001-0500/0347-Top-K-Frequent-Elements/java-0347/src/Solution2.java similarity index 100% rename from 0347-Top-K-Frequent-Elements/java-0347/src/Solution2.java rename to 0001-0500/0347-Top-K-Frequent-Elements/java-0347/src/Solution2.java diff --git a/0001-0500/0347-Top-K-Frequent-Elements/java-0347/src/Solution3.java b/0001-0500/0347-Top-K-Frequent-Elements/java-0347/src/Solution3.java new file mode 100644 index 00000000..6dc8723a --- /dev/null +++ b/0001-0500/0347-Top-K-Frequent-Elements/java-0347/src/Solution3.java @@ -0,0 +1,68 @@ +/// Source : https://leetcode.com/problems/top-k-frequent-elements/description/ +/// Author : liuyubobobo +/// Time : 2017-11-17 + +import java.util.*; +import java.util.HashMap; + +/// Priority Queue +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution3 { + + private class Pair implements Comparable{ + public int num, freq; + + public Pair(int num, int freq){ + this.num = num; + this.freq = freq; + } + + @Override + public int compareTo(Pair another){ + return this.freq - another.freq; + } + } + + public List topKFrequent(int[] nums, int k) { + + if(k <= 0) + throw new IllegalArgumentException("k should be greater than 0"); + + HashMap freq = new HashMap(); + for(int i = 0 ; i < nums.length ; i ++) + if(freq.containsKey(nums[i])) + freq.put(nums[i], freq.get(nums[i]) + 1); + else + freq.put(nums[i], 1); + + if(k > freq.size()) + throw new IllegalArgumentException("k should be less than the number of unique numbers in nums"); + + PriorityQueue pq = new PriorityQueue<>(); + for(Integer num: freq.keySet()){ + int numFreq = freq.get(num); + if(pq.size() == k && numFreq > pq.peek().freq) pq.poll(); + if(pq.size() < k) pq.add(new Pair(num, numFreq)); + } + + ArrayList res = new ArrayList(); + while(!pq.isEmpty()) + res.add(pq.poll().num); + + return res; + } + + private static void printList(List nums){ + for(Integer num: nums) + System.out.print(num + " "); + System.out.println(); + } + + public static void main(String[] args) { + + int[] nums = {1, 1, 1, 2, 2, 3}; + int k = 2; + printList((new Solution3()).topKFrequent(nums, k)); + } +} diff --git a/0001-0500/0347-Top-K-Frequent-Elements/java-0347/src/Solution4.java b/0001-0500/0347-Top-K-Frequent-Elements/java-0347/src/Solution4.java new file mode 100644 index 00000000..463a8a42 --- /dev/null +++ b/0001-0500/0347-Top-K-Frequent-Elements/java-0347/src/Solution4.java @@ -0,0 +1,74 @@ +/// Source : https://leetcode.com/problems/top-k-frequent-elements/description/ +/// Author : liuyubobobo +/// Time : 2020-03-14 + +import java.util.*; +import java.util.HashMap; +import java.util.HashSet; + + +/// Priority Queue contains n - k elements +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution4 { + + private class Pair implements Comparable{ + public int num, freq; + + public Pair(int num, int freq){ + this.num = num; + this.freq = freq; + } + + @Override + public int compareTo(Pair another){ + return another.freq - this.freq; + } + } + + public List topKFrequent(int[] nums, int k) { + + if(k <= 0) + throw new IllegalArgumentException("k should be greater than 0"); + + HashMap freq = new HashMap(); + for(int i = 0 ; i < nums.length ; i ++) + if(freq.containsKey(nums[i])) + freq.put(nums[i], freq.get(nums[i]) + 1); + else + freq.put(nums[i], 1); + + if(k > freq.size()) + throw new IllegalArgumentException("k should be less than the number of unique numbers in nums"); + + PriorityQueue pq = new PriorityQueue<>(); + for(Integer num: freq.keySet()){ + int numFreq = freq.get(num); + if(freq.size() - k > 0 && pq.size() == freq.size() - k && numFreq < pq.peek().freq) pq.poll(); + if(freq.size() - k > 0 && pq.size() < freq.size() - k) pq.add(new Pair(num, numFreq)); + } + + HashSet notContains = new HashSet<>(); + while(!pq.isEmpty()) + notContains.add(pq.poll().num); + + ArrayList res = new ArrayList(); + for(Integer key: freq.keySet()) + if(!notContains.contains(key)) res.add(key); + + return res; + } + + private static void printList(List nums){ + for(Integer num: nums) + System.out.print(num + " "); + System.out.println(); + } + + public static void main(String[] args) { + + int[] nums = {1, 1, 1, 2, 2, 3}; + int k = 2; + printList((new Solution4()).topKFrequent(nums, k)); + } +} diff --git a/0001-0500/0348-Design-Tic-Tac-Toe/cpp-0348/CMakeLists.txt b/0001-0500/0348-Design-Tic-Tac-Toe/cpp-0348/CMakeLists.txt new file mode 100644 index 00000000..cf7a2e4b --- /dev/null +++ b/0001-0500/0348-Design-Tic-Tac-Toe/cpp-0348/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_0348) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0348 main.cpp) \ No newline at end of file diff --git a/0001-0500/0348-Design-Tic-Tac-Toe/cpp-0348/main.cpp b/0001-0500/0348-Design-Tic-Tac-Toe/cpp-0348/main.cpp new file mode 100644 index 00000000..1e1a6de9 --- /dev/null +++ b/0001-0500/0348-Design-Tic-Tac-Toe/cpp-0348/main.cpp @@ -0,0 +1,74 @@ +/// Source : https://leetcode.com/problems/find-winner-on-a-tic-tac-toe-game/ +/// Author : liuyubobobo +/// Time : 2021-05-22 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: init: O(1) +/// move: O(n) +/// Space Complexity: O(n^2) +class TicTacToe { + +private: + vector> board; + int n, winner; + +public: + /** Initialize your data structure here. */ + TicTacToe(int n) : n(n), board(n, vector(n, 0)), winner(0){ + } + + /** Player {player} makes a move at ({row}, {col}). + @param row The row of the board. + @param col The column of the board. + @param player The player, can be either 1 or 2. + @return The current winning condition, can be either: + 0: No one wins. + 1: Player 1 wins. + 2: Player 2 wins. */ + int move(int row, int col, int player) { + + if(winner) return winner; + + board[row][col] = player; + + int j; + for(j = 0; j < n; j ++) + if(board[row][j] != player) + break; + if(j == n){winner = player; return player;} + + int i; + for(i = 0; i < n; i ++) + if(board[i][col] != player) + break; + if(i == n){winner = player; return player;} + + if(row == col){ + for(i = 0, j = 0; i < n && j < n; i ++, j ++) + if(board[i][j] != player) + break; + if(i == n){winner = player; return player;} + } + + if(row + col == n - 1){ + for(i = 0, j = n - 1; i < n && j >= 0; i ++, j --) + if(board[i][j] != player) + break; + if(i == n){winner = player; return player;} + } + + return 0; + } +}; + + +int main() { + + return 0; +} diff --git a/0349-Intersection-of-Two-Arrays/cpp-0349/CMakeLists.txt b/0001-0500/0349-Intersection-of-Two-Arrays/cpp-0349/CMakeLists.txt similarity index 100% rename from 0349-Intersection-of-Two-Arrays/cpp-0349/CMakeLists.txt rename to 0001-0500/0349-Intersection-of-Two-Arrays/cpp-0349/CMakeLists.txt diff --git a/0349-Intersection-of-Two-Arrays/cpp-0349/main.cpp b/0001-0500/0349-Intersection-of-Two-Arrays/cpp-0349/main.cpp similarity index 100% rename from 0349-Intersection-of-Two-Arrays/cpp-0349/main.cpp rename to 0001-0500/0349-Intersection-of-Two-Arrays/cpp-0349/main.cpp diff --git a/0349-Intersection-of-Two-Arrays/java-0349/src/Solution.java b/0001-0500/0349-Intersection-of-Two-Arrays/java-0349/src/Solution.java similarity index 100% rename from 0349-Intersection-of-Two-Arrays/java-0349/src/Solution.java rename to 0001-0500/0349-Intersection-of-Two-Arrays/java-0349/src/Solution.java diff --git a/0001-0500/0350-Intersection-of-Two-Arrays-II/cpp-0350/CMakeLists.txt b/0001-0500/0350-Intersection-of-Two-Arrays-II/cpp-0350/CMakeLists.txt new file mode 100644 index 00000000..b0ee4754 --- /dev/null +++ b/0001-0500/0350-Intersection-of-Two-Arrays-II/cpp-0350/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0350) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main3.cpp) +add_executable(cpp_0350 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0350-Intersection-of-Two-Arrays-II/cpp-0350/main.cpp b/0001-0500/0350-Intersection-of-Two-Arrays-II/cpp-0350/main.cpp new file mode 100644 index 00000000..96365a03 --- /dev/null +++ b/0001-0500/0350-Intersection-of-Two-Arrays-II/cpp-0350/main.cpp @@ -0,0 +1,48 @@ +/// Source : https://leetcode.com/problems/intersection-of-two-arrays-ii/description/ +/// Author : liuyubobobo +/// Time : 2017-11-14 + +#include +#include +#include +using namespace std; + + +/// Using Hash Map +/// Time Complexity: O(len(nums1) + len(nums2)) +/// Space Complexity: O(len(nums1)) +class Solution { +public: + vector intersect(vector& nums1, vector& nums2) { + + unordered_map record; + for(int i = 0 ; i < nums1.size() ; i ++) + record[nums1[i]] += 1; + + vector resultVector; + for(int i = 0 ; i < nums2.size() ; i ++) + if(record[nums2[i]] > 0){ + resultVector.push_back(nums2[i]); + record[nums2[i]] --; + } + + return resultVector; + } +}; + + +void print_vec(const vector& vec){ + for(int e: vec) + cout << e << " "; + cout << endl; +} + +int main() { + + vector nums1 = {1, 2, 2, 1}; + vector nums2 = {2, 2}; + + print_vec(Solution().intersect(nums1, nums2)); + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0350-Intersection-of-Two-Arrays-II/cpp-0350/main2.cpp b/0001-0500/0350-Intersection-of-Two-Arrays-II/cpp-0350/main2.cpp new file mode 100644 index 00000000..6372a1ab --- /dev/null +++ b/0001-0500/0350-Intersection-of-Two-Arrays-II/cpp-0350/main2.cpp @@ -0,0 +1,51 @@ +/// Source : https://leetcode.com/problems/intersection-of-two-arrays-ii/description/ +/// Author : liuyubobobo +/// Time : 2017-11-14 + +#include +#include +#include + +using namespace std; + + +/// Using Hash Map +/// Time Complexity: O(len(nums1) + len(nums2)*log(len(nums1))) +/// Space Complexity: O(len(nums1)) +class Solution { +public: + vector intersect(vector& nums1, vector& nums2) { + + multiset record; + for(int num: nums1) + record.insert(num); + + multiseSt result; + for(int num: nums2){ + multiset::iterator iter = record.find(num); + if( iter != record.end()){ + result.insert(num); + record.erase(iter); + } + } + + return vector(result.begin(), result.end()); + } +}; + + +void print_vec(const vector& vec){ + for(int e: vec) + cout << e << " "; + cout << endl; +} + +int main() { + + vector nums1 = {1, 2, 2, 1}; + vector nums2 = {2, 2}; + + print_vec(Solution().intersect(nums1, nums2)); + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0350-Intersection-of-Two-Arrays-II/cpp-0350/main3.cpp b/0001-0500/0350-Intersection-of-Two-Arrays-II/cpp-0350/main3.cpp new file mode 100644 index 00000000..7ee3968f --- /dev/null +++ b/0001-0500/0350-Intersection-of-Two-Arrays-II/cpp-0350/main3.cpp @@ -0,0 +1,51 @@ +/// Source : https://leetcode.com/problems/intersection-of-two-arrays-ii/description/ +/// Author : liuyubobobo +/// Time : 2019-04-08 + +#include +#include +#include + +using namespace std; + + +/// Sorting and Two Pointers +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + vector intersect(vector& nums1, vector& nums2) { + + sort(nums1.begin(), nums1.end()); + sort(nums2.begin(), nums2.end()); + + vector res; + + int i = 0, j = 0; + while(i < nums1.size() && j < nums2.size()){ + + if(nums1[i] == nums2[j]) res.push_back(nums1[i]), i ++, j ++; + else if(nums1[i] < nums2[j]) i ++; + else j ++; + } + + return res; + } +}; + + +void print_vec(const vector& vec){ + for(int e: vec) + cout << e << " "; + cout << endl; +} + +int main() { + + vector nums1 = {1, 2, 2, 1}; + vector nums2 = {2, 2}; + + print_vec(Solution().intersect(nums1, nums2)); + + return 0; +} \ No newline at end of file diff --git a/0350-Intersection-of-Two-Arrays-II/java-0350/src/Solution.java b/0001-0500/0350-Intersection-of-Two-Arrays-II/java-0350/src/Solution.java similarity index 100% rename from 0350-Intersection-of-Two-Arrays-II/java-0350/src/Solution.java rename to 0001-0500/0350-Intersection-of-Two-Arrays-II/java-0350/src/Solution.java diff --git a/0001-0500/0350-Intersection-of-Two-Arrays-II/java-0350/src/Solution2.java b/0001-0500/0350-Intersection-of-Two-Arrays-II/java-0350/src/Solution2.java new file mode 100644 index 00000000..fc42ab6c --- /dev/null +++ b/0001-0500/0350-Intersection-of-Two-Arrays-II/java-0350/src/Solution2.java @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/intersection-of-two-arrays-ii/description/ +/// Author : liuyubobobo +/// Time : 2019-04-08 + +import java.util.Arrays; +import java.util.ArrayList; + + +/// Sorting and Two Pointers +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +public class Solution2 { + + public int[] intersect(int[] nums1, int[] nums2) { + + Arrays.sort(nums1); + Arrays.sort(nums2); + + ArrayList res = new ArrayList<>(); + + int i = 0, j = 0; + while(i < nums1.length && j < nums2.length){ + + if(nums1[i] == nums2[j]){ + res.add(nums1[i]); + i ++; + j ++; + } + else if(nums1[i] < nums2[j]) i ++; + else j ++; + } + + int[] ret = new int[res.size()]; + int index = 0; + for(Integer num: res) + ret[index++] = num; + + return ret; + } + + private static void printArr(int[] arr){ + for(int e: arr) + System.out.print(e + " "); + System.out.println(); + } + + public static void main(String[] args) { + + int[] nums1 = {1, 2, 2, 1}; + int[] nums2 = {2, 2}; + int[] res = (new Solution()).intersect(nums1, nums2); + printArr(res); + } +} diff --git a/0001-0500/0352-Data-Stream-as-Disjoint-Intervals/cpp-0352/CMakeLists.txt b/0001-0500/0352-Data-Stream-as-Disjoint-Intervals/cpp-0352/CMakeLists.txt new file mode 100644 index 00000000..fbb8d4f1 --- /dev/null +++ b/0001-0500/0352-Data-Stream-as-Disjoint-Intervals/cpp-0352/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0352) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0352 main.cpp) diff --git a/0001-0500/0352-Data-Stream-as-Disjoint-Intervals/cpp-0352/main.cpp b/0001-0500/0352-Data-Stream-as-Disjoint-Intervals/cpp-0352/main.cpp new file mode 100644 index 00000000..32760c3d --- /dev/null +++ b/0001-0500/0352-Data-Stream-as-Disjoint-Intervals/cpp-0352/main.cpp @@ -0,0 +1,65 @@ +/// Source : https://leetcode.com/problems/data-stream-as-disjoint-intervals/ +/// Author : liuyubobobo +/// Time : 2021-10-08 + +#include +#include +#include + +using namespace std; + + +/// Using Map to record Segments +/// Time Complexity: init : O(1) +/// addNum: O(logn) +/// get_interval: O(m) where m is the segments number +/// Space Complexity: O(m) +class SummaryRanges { + +private: + map left; // l, r + map right; // r, l; + +public: + SummaryRanges() {} + + void addNum(int val) { + + if(!left.empty()) { + map::iterator iter = left.upper_bound(val); + if (iter != left.begin()) iter--; + if (iter->first <= val && val <= iter->second) return; + } + + pair interval = {val, val}; + if(right.count(val - 1)){ + int r = val - 1, l = right[r]; + right.erase(r); + left.erase(l); + interval.first = l; + } + if(left.count(val + 1)){ + int l = val + 1, r = left[l]; + left.erase(l); + right.erase(r); + interval.second = r; + } + + left[interval.first] = interval.second; + right[interval.second] = interval.first; + } + + vector> getIntervals() { + + vector> res; + for(const pair& p: left) + res.push_back({p.first, p.second}); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0354-Russian-Doll-Envelopes/cpp-0354/CMakeLists.txt b/0001-0500/0354-Russian-Doll-Envelopes/cpp-0354/CMakeLists.txt new file mode 100644 index 00000000..748ade2e --- /dev/null +++ b/0001-0500/0354-Russian-Doll-Envelopes/cpp-0354/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0354) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0354 main2.cpp) \ No newline at end of file diff --git a/0001-0500/0354-Russian-Doll-Envelopes/cpp-0354/main.cpp b/0001-0500/0354-Russian-Doll-Envelopes/cpp-0354/main.cpp new file mode 100644 index 00000000..b99f157e --- /dev/null +++ b/0001-0500/0354-Russian-Doll-Envelopes/cpp-0354/main.cpp @@ -0,0 +1,49 @@ +/// Source : https://leetcode.com/problems/russian-doll-envelopes/ +/// Author : liuyubobobo +/// Time : 2021-03-03 + +#include +#include + +using namespace std; + + +/// LIS +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { +public: + int maxEnvelopes(vector>& envelopes) { + + if(envelopes.empty()) return 0; + + sort(envelopes.begin(), envelopes.end()); + + vector dp(envelopes.size(), 1); + for(int i = 1; i < envelopes.size(); i ++){ + dp[i] = 1; + for(int j = i - 1; j >= 0; j --) + if(envelopes[i][0] > envelopes[j][0] && envelopes[i][1] > envelopes[j][1]) + dp[i] = max(dp[i], 1 + dp[j]); + } + return *max_element(dp.begin(), dp.end()); + } +}; + + +int main() { + + vector> envelopes1 = { + {5,4},{6,4},{6,7},{2,3} + }; + cout << Solution().maxEnvelopes(envelopes1) << endl; + // 3 + + vector> envelopes2 = { + {1,3},{3,5},{6,7},{6,8},{8,4},{9,5} + }; + cout << Solution().maxEnvelopes(envelopes2) << endl; + // 3 + + return 0; +} diff --git a/0001-0500/0354-Russian-Doll-Envelopes/cpp-0354/main2.cpp b/0001-0500/0354-Russian-Doll-Envelopes/cpp-0354/main2.cpp new file mode 100644 index 00000000..e7255124 --- /dev/null +++ b/0001-0500/0354-Russian-Doll-Envelopes/cpp-0354/main2.cpp @@ -0,0 +1,75 @@ +/// Source : https://leetcode.com/problems/russian-doll-envelopes/ +/// Author : liuyubobobo +/// Time : 2021-03-03 + +#include +#include +#include + +using namespace std; + + +/// LIS - O(nlogn) +/// How to sort the two dimensional data is the key! +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { + +public: + int maxEnvelopes(vector>& envelopes) { + + if(envelopes.empty()) return 0; + + sort(envelopes.begin(), envelopes.end(), + [](const vector& e1, const vector& e2){ + + if(e1[0] != e2[0]) return e1[0] < e2[0]; + return e1[1] > e2[1]; + }); + + vector v(envelopes.size()); + for(int i = 0; i < envelopes.size(); i ++) + v[i] = envelopes[i][1]; + + return lis(v); + } + +private: + int lis(const vector& v){ + + vector dp; + for(int e: v){ + if(dp.empty() || e > dp.back()) + dp.push_back(e); + else{ + vector::iterator iter = lower_bound(dp.begin(), dp.end(), e); + if(iter != dp.end()) dp[iter - dp.begin()] = e; + } + } + return dp.size(); + } +}; + + +int main() { + + vector> envelopes1 = { + {5,4},{6,4},{6,7},{2,3} + }; + cout << Solution().maxEnvelopes(envelopes1) << endl; + // 3 + + vector> envelopes2 = { + {1,3},{3,5},{6,7},{6,8},{8,4},{9,5} + }; + cout << Solution().maxEnvelopes(envelopes2) << endl; + // 3 + + vector> envelopes3 = { + {1,2},{2,3},{3,4},{3,5},{4,5},{5,5},{5,6},{6,7},{7,8} + }; + cout << Solution().maxEnvelopes(envelopes3) << endl; + // 7 + + return 0; +} diff --git a/0001-0500/0357-Count-Numbers-with-Unique-Digits/cpp-0357/CMakeLists.txt b/0001-0500/0357-Count-Numbers-with-Unique-Digits/cpp-0357/CMakeLists.txt new file mode 100644 index 00000000..8aa92127 --- /dev/null +++ b/0001-0500/0357-Count-Numbers-with-Unique-Digits/cpp-0357/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_0357) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0357 main.cpp) diff --git a/0001-0500/0357-Count-Numbers-with-Unique-Digits/cpp-0357/main.cpp b/0001-0500/0357-Count-Numbers-with-Unique-Digits/cpp-0357/main.cpp new file mode 100644 index 00000000..0769d659 --- /dev/null +++ b/0001-0500/0357-Count-Numbers-with-Unique-Digits/cpp-0357/main.cpp @@ -0,0 +1,31 @@ +/// Source : https://leetcode.com/problems/count-numbers-with-unique-digits/ +/// Author : liuyubobobo +/// Time : 2022-04-10 + +#include + +using namespace std; + + +/// Math +/// Time Complexity: O((logn)^2) +/// Space Complexity: O(1) +class Solution { +public: + int countNumbersWithUniqueDigits(int n) { + + int res = 1; + for(int w = 1; w <= n; w ++){ + int tres = 9, choice = 9; + for(int i = 1; i < w; i ++) tres *= choice, choice --; + res += tres; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0359-Logger-Rate-Limiter/cpp-0359/CMakeLists.txt b/0001-0500/0359-Logger-Rate-Limiter/cpp-0359/CMakeLists.txt new file mode 100644 index 00000000..7c4ee770 --- /dev/null +++ b/0001-0500/0359-Logger-Rate-Limiter/cpp-0359/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0359) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0359 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0359-Logger-Rate-Limiter/cpp-0359/main.cpp b/0001-0500/0359-Logger-Rate-Limiter/cpp-0359/main.cpp new file mode 100644 index 00000000..997c6875 --- /dev/null +++ b/0001-0500/0359-Logger-Rate-Limiter/cpp-0359/main.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/logger-rate-limiter/description/ +/// Author : liuyubobobo +/// Time : 2018-10-02 + +#include +#include +#include + +using namespace std; + + +/// Using a Queue and HashSet +/// Time Complexity: init: O(1) +/// shouldPrintMessage: O(10) +/// Space Complexity: O(10) +class Logger { + +private: + unordered_set messages; + queue> q; + +public: + /** Initialize your data structure here. */ + Logger() {} + + /** Returns true if the message should be printed in the given timestamp, otherwise returns false. + If this method returns false, the message will not be printed. + The timestamp is in seconds granularity. */ + bool shouldPrintMessage(int timestamp, string message) { + + while(!q.empty()){ + if(timestamp - q.front().first >= 10){ + messages.erase(q.front().second); + q.pop(); + } + else + break; + } + + if(messages.count(message)) + return false; + + messages.insert(message); + q.push(make_pair(timestamp, message)); + return true; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/old/0360 Sort Transformed Array/cpp-Sort-Transformed-Array/CMakeLists.txt b/0001-0500/0360-Sort-Transformed-Array/cpp-0360/CMakeLists.txt similarity index 100% rename from old/0360 Sort Transformed Array/cpp-Sort-Transformed-Array/CMakeLists.txt rename to 0001-0500/0360-Sort-Transformed-Array/cpp-0360/CMakeLists.txt diff --git a/0001-0500/0360-Sort-Transformed-Array/cpp-0360/main.cpp b/0001-0500/0360-Sort-Transformed-Array/cpp-0360/main.cpp new file mode 100644 index 00000000..d28f11d3 --- /dev/null +++ b/0001-0500/0360-Sort-Transformed-Array/cpp-0360/main.cpp @@ -0,0 +1,110 @@ +/// Source : https://leetcode.com/problems/sort-transformed-array/description/ +/// Author : liuyubobobo +/// Time : 2016-12-26 + +#include +#include +#include +#include + +using namespace std; + + +/// Mathematics +/// Based on the middle axis -b/(2a) to get the proper order of the transformation +/// Need to pay attention when a == 0 +/// +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + vector sortTransformedArray(const vector& nums, int a, int b, int c) { + + vector res; + + if(a == 0){ + // If a == 0, the result of the transform is linear + for(int i = 0 ; i < nums.size() ; i ++) + res.push_back(applyTransform(nums[i], a, b, c)); + + // If b < 0, we need to reverse the result to make the res be sorted + // from small elements to large elements + if(b < 0) + reverseArray(res); + } + else{ + // If a != 0, we need to find the middle axis first + // which can be calculated as - b / 2*a + double m = - double(b) / double(2 * a); + //cout<<"m = "< nums = {-4, -2, 2, 4}; + print_vec(Solution().sortTransformedArray(nums, 1, 3, 5)); + print_vec(Solution().sortTransformedArray(nums, -1, 3, 5)); + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0362-Design-Hit-Counter/cpp-0362/CMakeLists.txt b/0001-0500/0362-Design-Hit-Counter/cpp-0362/CMakeLists.txt new file mode 100644 index 00000000..416f2838 --- /dev/null +++ b/0001-0500/0362-Design-Hit-Counter/cpp-0362/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_0362) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0362 main.cpp) diff --git a/0001-0500/0362-Design-Hit-Counter/cpp-0362/main.cpp b/0001-0500/0362-Design-Hit-Counter/cpp-0362/main.cpp new file mode 100644 index 00000000..af67ce68 --- /dev/null +++ b/0001-0500/0362-Design-Hit-Counter/cpp-0362/main.cpp @@ -0,0 +1,39 @@ +/// Source : https://leetcode.com/problems/design-hit-counter/ +/// Author : liuyubobobo +/// Time : 2022-09-07 + +#include +#include +#include + +using namespace std; + + +/// Using deque +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class HitCounter { + +private: + deque hits; + +public: + HitCounter() {} + + void hit(int timestamp) { + hits.push_back(timestamp); + while(timestamp - hits.front() + 1 > 300) hits.pop_front(); + } + + int getHits(int timestamp) { + + while(!hits.empty() && timestamp - hits.front() + 1 > 300) hits.pop_front(); + return hits.size(); + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0363-Max-Sum-of-Rectangle-No-Larger-Than-K/cpp-0363/CMakeLists.txt b/0001-0500/0363-Max-Sum-of-Rectangle-No-Larger-Than-K/cpp-0363/CMakeLists.txt new file mode 100644 index 00000000..a08b4edd --- /dev/null +++ b/0001-0500/0363-Max-Sum-of-Rectangle-No-Larger-Than-K/cpp-0363/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_0363) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0363 main.cpp) \ No newline at end of file diff --git a/0001-0500/0363-Max-Sum-of-Rectangle-No-Larger-Than-K/cpp-0363/main.cpp b/0001-0500/0363-Max-Sum-of-Rectangle-No-Larger-Than-K/cpp-0363/main.cpp new file mode 100644 index 00000000..4f56b24c --- /dev/null +++ b/0001-0500/0363-Max-Sum-of-Rectangle-No-Larger-Than-K/cpp-0363/main.cpp @@ -0,0 +1,65 @@ +/// Source : https://leetcode.com/problems/max-sum-of-rectangle-no-larger-than-k/ +/// Author : liuyubobobo +/// Time : 2021-04-21 + +#include +#include +#include + +using namespace std; + + +/// Using TreeSet +/// Time Complexity: O(n^3*logn) +/// Space Complexity: O(n^2) +class Solution { +public: + int maxSumSubmatrix(vector>& matrix, int k) { + + int R = matrix.size(), C = matrix[0].size(); + vector> presum(R + 1, vector(C, 0)); + for(int j = 0; j < C; j ++) + for(int i = 0; i < R; i ++) + presum[i + 1][j] = presum[i][j] + matrix[i][j]; + + int res = INT_MIN; + for(int r1 = 0; r1 < R; r1 ++) + for(int r2 = r1; r2 < R; r2 ++){ + + vector v(C); + for(int j = 0; j < C; j ++) + v[j] = presum[r2 + 1][j] - presum[r1][j]; + + res = max(res, solve(v, k)); + } + return res; + } + +private: + int solve(const vector& v, int k){ + + set seen; + seen.insert(0); + + int sum = 0, res = INT_MIN; + for(int e: v){ + + sum += e; + set::iterator iter = seen.lower_bound(sum - k); + if(iter != seen.end()) + res = max(res, sum - *iter); + seen.insert(sum); + } + return res; + } +}; + + +int main() { + + vector> matrix1 = {{2, 2, -1}}; + cout << Solution().maxSumSubmatrix(matrix1, 0) << endl; + // -1 + + return 0; +} diff --git a/0001-0500/0364-Nested-List-Weight-Sum-II/cpp-0364/CMakeLists.txt b/0001-0500/0364-Nested-List-Weight-Sum-II/cpp-0364/CMakeLists.txt new file mode 100644 index 00000000..3bd0f562 --- /dev/null +++ b/0001-0500/0364-Nested-List-Weight-Sum-II/cpp-0364/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0364) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0364 main.cpp) \ No newline at end of file diff --git a/0001-0500/0364-Nested-List-Weight-Sum-II/cpp-0364/main.cpp b/0001-0500/0364-Nested-List-Weight-Sum-II/cpp-0364/main.cpp new file mode 100644 index 00000000..fde8702a --- /dev/null +++ b/0001-0500/0364-Nested-List-Weight-Sum-II/cpp-0364/main.cpp @@ -0,0 +1,75 @@ +/// Source : https://leetcode.com/problems/nested-list-weight-sum-ii/ +/// Author : liuyubobobo +/// Time : 2021-01-15 + +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(h) + +// This is the interface that allows for creating nested lists. +// You should not implement it, or speculate about its implementation +class NestedInteger { + public: + // Constructor initializes an empty nested list. + NestedInteger(); + + // Constructor initializes a single integer. + NestedInteger(int value); + + // Return true if this NestedInteger holds a single integer, rather than a nested list. + bool isInteger() const; + + // Return the single integer that this NestedInteger holds, if it holds a single integer + // The result is undefined if this NestedInteger holds a nested list + int getInteger() const; + + // Set this NestedInteger to hold a single integer. + void setInteger(int value); + + // Set this NestedInteger to hold a nested list and adds a nested integer to it. + void add(const NestedInteger &ni); + + // Return the nested list that this NestedInteger holds, if it holds a nested list + // The result is undefined if this NestedInteger holds a single integer + const vector &getList() const; +}; + +class Solution { +public: + int depthSumInverse(vector& nestedList) { + + int depth = get_depth(nestedList); + return depthSumInverse(nestedList, depth); + } + +private: + int depthSumInverse(const vector& nestedList, int d){ + + int res = 0; + for(const NestedInteger& e: nestedList) + if(e.isInteger()) res += d * e.getInteger(); + else res += depthSumInverse(e.getList(), d - 1); + return res; + } + + int get_depth(const vector& nestedList){ + + int d = 1; + for(const NestedInteger& e: nestedList) + if(!e.isInteger()) + d = max(d, 1 + get_depth(e.getList())); + return d; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0365-Water-and-Jug-Problem/cpp-0365/CMakeLists.txt b/0001-0500/0365-Water-and-Jug-Problem/cpp-0365/CMakeLists.txt new file mode 100644 index 00000000..9aa5894e --- /dev/null +++ b/0001-0500/0365-Water-and-Jug-Problem/cpp-0365/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0365) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0365 main.cpp) \ No newline at end of file diff --git a/0001-0500/0365-Water-and-Jug-Problem/cpp-0365/main.cpp b/0001-0500/0365-Water-and-Jug-Problem/cpp-0365/main.cpp new file mode 100644 index 00000000..eee515e5 --- /dev/null +++ b/0001-0500/0365-Water-and-Jug-Problem/cpp-0365/main.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/water-and-jug-problem/ +/// Author : liuyubobobo +/// Time : 2021-01-27 + +#include +#include +#include + +using namespace std; + + +/// BFS +/// Time Complexity: O(x * y) +/// Space Complexity: O(x * y) +class Solution { +public: + bool canMeasureWater(int x, int y, int z) { + + unordered_set set; + queue> q; + q.push({0, 0}); + set.insert(0); + while(!q.empty()){ + int a = q.front().first, b = q.front().second; + q.pop(); + + if(a == z || b == z || a + b == z) return true; + + if(!set.count(x * 10000000ll + b)) + q.push({x, b}), set.insert(x * 10000000ll + b); + + if(!set.count(a * 10000000ll + y)) + q.push({a, y}), set.insert(a * 10000000ll + y); + + if(!set.count(b)) + q.push({0, b}), set.insert(b); + + if(!set.count(a * 10000000ll)) + q.push({a, 0}), set.insert(a * 10000000ll); + + if(!set.count((a - min(a, y - b)) * 10000000ll + b + min(a, y - b))) + q.push({a - min(a, y - b), b + min(a, y - b)}), + set.insert((a - min(a, y - b)) * 10000000ll + b + min(a, y - b)); + + if(!set.count((a + min(x - a, b)) * 10000000ll + b - min(x - a, b))) + q.push({a + min(x - a, b), b - min(x - a, b)}), + set.insert((a + min(x - a, b)) * 10000000ll + b - min(x - a, b)); + } + return false; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0366-Find-Leaves-of-Binary-Tree/cpp-0366/CMakeLists.txt b/0001-0500/0366-Find-Leaves-of-Binary-Tree/cpp-0366/CMakeLists.txt new file mode 100644 index 00000000..b050ab76 --- /dev/null +++ b/0001-0500/0366-Find-Leaves-of-Binary-Tree/cpp-0366/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_0366) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0366 main.cpp) \ No newline at end of file diff --git a/0001-0500/0366-Find-Leaves-of-Binary-Tree/cpp-0366/main.cpp b/0001-0500/0366-Find-Leaves-of-Binary-Tree/cpp-0366/main.cpp new file mode 100644 index 00000000..aa213550 --- /dev/null +++ b/0001-0500/0366-Find-Leaves-of-Binary-Tree/cpp-0366/main.cpp @@ -0,0 +1,60 @@ +/// Source : https://leetcode.com/problems/find-leaves-of-binary-tree/ +/// Author : liuyubobobo +/// Time : 2021-07-01 + +#include +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +// 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> findLeaves(TreeNode* root) { + + unordered_map level; + level[nullptr] = 0; + dfs(root, level); + + vector> res(level[root] + 1); + for(const pair& p: level) + if(p.first) res[p.second].push_back(p.first->val); + return res; + } + +private: + void dfs(TreeNode* node, unordered_map& level){ + + if(!node) return; + + if(!node->left && !node->right){ + level[node] = 0; + return; + } + + dfs(node->left, level); + dfs(node->right, level); + level[node] = max(level[node->left], level[node->right]) + 1; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0367-Valid-Perfect-Square/cpp-0367/CMakeLists.txt b/0001-0500/0367-Valid-Perfect-Square/cpp-0367/CMakeLists.txt new file mode 100644 index 00000000..f710ddd6 --- /dev/null +++ b/0001-0500/0367-Valid-Perfect-Square/cpp-0367/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0367) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0367 main.cpp) diff --git a/0001-0500/0367-Valid-Perfect-Square/cpp-0367/main.cpp b/0001-0500/0367-Valid-Perfect-Square/cpp-0367/main.cpp new file mode 100644 index 00000000..1948fab5 --- /dev/null +++ b/0001-0500/0367-Valid-Perfect-Square/cpp-0367/main.cpp @@ -0,0 +1,26 @@ +/// Source : https://leetcode.com/problems/valid-perfect-square/ +/// Author : liuyubobobo +/// Time : 2021-11-03 + +#include + +using namespace std; + + +/// Math +/// Time Complexity: O(1) +/// Space Complexity: O(1) +class Solution { +public: + bool isPerfectSquare(int num) { + + int x = (int)(sqrt(num) + 1e-6); + return x * x == num; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0368-Largest-Divisible-Subset/cpp-0368/CMakeLists.txt b/0001-0500/0368-Largest-Divisible-Subset/cpp-0368/CMakeLists.txt new file mode 100644 index 00000000..c3699724 --- /dev/null +++ b/0001-0500/0368-Largest-Divisible-Subset/cpp-0368/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_0368) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0368 main.cpp) \ No newline at end of file diff --git a/0001-0500/0368-Largest-Divisible-Subset/cpp-0368/main.cpp b/0001-0500/0368-Largest-Divisible-Subset/cpp-0368/main.cpp new file mode 100644 index 00000000..6ddd3261 --- /dev/null +++ b/0001-0500/0368-Largest-Divisible-Subset/cpp-0368/main.cpp @@ -0,0 +1,61 @@ +/// Source : https://leetcode.com/problems/largest-divisible-subset/ +/// Author : liuyubobobo +/// Time : 2021-04-23 + +#include +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { +public: + vector largestDivisibleSubset(vector& nums) { + + sort(nums.begin(), nums.end()); + + vector dp(nums.size(), 1), pre(nums.size(), -1); + for(int i = 1; i < nums.size(); i ++) + for(int j = i - 1; j >= 0; j --) + if(nums[i] % nums[j] == 0 && 1 + dp[j] > dp[i]) + dp[i] = 1 + dp[j], pre[i] = j; + + int cur = max_element(dp.begin(), dp.end()) - dp.begin(); + vector res; + while(cur != -1){ + res.push_back(nums[cur]); + cur = pre[cur]; + } + return res; + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << " "; cout << endl; +} + +int main() { + + vector nums1 = {1, 2, 3}; + print_vec(Solution().largestDivisibleSubset(nums1)); + // 1 2 + + vector nums2 = {3, 4, 16, 8}; + print_vec(Solution().largestDivisibleSubset(nums2)); + // 4 8 16 + + vector nums3 = {2000000000}; + print_vec(Solution().largestDivisibleSubset(nums3)); + // 2000000000 + + vector nums4 = {1, 2, 3}; + print_vec(Solution().largestDivisibleSubset(nums4)); + // 1 2 + + return 0; +} diff --git a/0001-0500/0369-Plus-One-Linked-List/cpp-0369/CMakeLists.txt b/0001-0500/0369-Plus-One-Linked-List/cpp-0369/CMakeLists.txt new file mode 100644 index 00000000..c65c7889 --- /dev/null +++ b/0001-0500/0369-Plus-One-Linked-List/cpp-0369/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0369) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0369 main.cpp) \ No newline at end of file diff --git a/0001-0500/0369-Plus-One-Linked-List/cpp-0369/main.cpp b/0001-0500/0369-Plus-One-Linked-List/cpp-0369/main.cpp new file mode 100644 index 00000000..f4a3c96b --- /dev/null +++ b/0001-0500/0369-Plus-One-Linked-List/cpp-0369/main.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/plus-one-linked-list/ +/// Author : liuyubobobo +/// Time : 2020-12-16 + +#include + + +/// Reverse LinkedList and Linear Scan +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode() : val(0), next(nullptr) {} + ListNode(int x) : val(x), next(nullptr) {} + ListNode(int x, ListNode *next) : val(x), next(next) {} +}; + +class Solution { +public: + ListNode* plusOne(ListNode* head) { + + if(!head) return head; + + head = reverse(head); + head->val += 1; + ListNode* cur = head; + while(cur){ + if(cur->val < 10) break; + cur->val = 0; + if(!cur->next) cur->next = new ListNode(1); + else cur->next->val += 1; + + cur = cur->next; + } + return reverse(head); + } + +private: + ListNode* reverse(ListNode* node){ + + if(!node->next) return node; + + ListNode* ret = reverse(node->next); + node->next->next = node; + node->next = nullptr; + return ret; + } +}; + + +int main() { + + return 0; +} diff --git a/0370-Range-Addition/cpp-0370/CMakeLists.txt b/0001-0500/0370-Range-Addition/cpp-0370/CMakeLists.txt similarity index 100% rename from 0370-Range-Addition/cpp-0370/CMakeLists.txt rename to 0001-0500/0370-Range-Addition/cpp-0370/CMakeLists.txt diff --git a/0370-Range-Addition/cpp-0370/main.cpp b/0001-0500/0370-Range-Addition/cpp-0370/main.cpp similarity index 100% rename from 0370-Range-Addition/cpp-0370/main.cpp rename to 0001-0500/0370-Range-Addition/cpp-0370/main.cpp diff --git a/0370-Range-Addition/cpp-0370/main2.cpp b/0001-0500/0370-Range-Addition/cpp-0370/main2.cpp similarity index 100% rename from 0370-Range-Addition/cpp-0370/main2.cpp rename to 0001-0500/0370-Range-Addition/cpp-0370/main2.cpp diff --git a/0001-0500/0372-Super-Pow/cpp-0372/CMakeLists.txt b/0001-0500/0372-Super-Pow/cpp-0372/CMakeLists.txt new file mode 100644 index 00000000..78bee50f --- /dev/null +++ b/0001-0500/0372-Super-Pow/cpp-0372/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_0372) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0372 main.cpp) diff --git a/0001-0500/0372-Super-Pow/cpp-0372/main.cpp b/0001-0500/0372-Super-Pow/cpp-0372/main.cpp new file mode 100644 index 00000000..ebce1f4d --- /dev/null +++ b/0001-0500/0372-Super-Pow/cpp-0372/main.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/super-pow/ +/// Author : liuyubobobo +/// Time : 2021-12-04 + +#include +#include + +using namespace std; + + +/// Quick Pow +/// Time Complexity: O(|b|^2) +/// Space Complexity: O(|b|^2) +class Solution { + +private: + const int MOD = 1337; + +public: + int superPow(int a, vector& b) { + + a %= MOD; + + if(b.empty() || (b.size() == 1 && b[0] == 0)) + return 1; + if(b.size() == 1 && b[0] == 1) + return a; + + vector q; + int cur = 0; + for(int e: b){ + cur = cur * 10 + e; + if(!q.empty() || cur / 2) + q.push_back(cur / 2); + cur %= 2; + } + + int tres = superPow(a, q); + int res = tres * tres % MOD; + if(cur) res = res * a % MOD; + return res; + } +}; + + +int main() { + + vector b1 = {1, 0}; + cout << Solution().superPow(2, b1) << endl; + // 1024 + + vector b2 = {2, 0, 0}; + cout << Solution().superPow(2147483647, b2) << endl; + // 400 + + return 0; +} diff --git a/0001-0500/0373-Find-K-Pairs-with-Smallest-Sums/cpp-0373/CMakeLists.txt b/0001-0500/0373-Find-K-Pairs-with-Smallest-Sums/cpp-0373/CMakeLists.txt new file mode 100644 index 00000000..da84bda9 --- /dev/null +++ b/0001-0500/0373-Find-K-Pairs-with-Smallest-Sums/cpp-0373/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(0373_Find_K_Pairs_with_Smallest_Sums) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(0373_Find_K_Pairs_with_Smallest_Sums ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0373-Find-K-Pairs-with-Smallest-Sums/cpp-0373/main.cpp b/0001-0500/0373-Find-K-Pairs-with-Smallest-Sums/cpp-0373/main.cpp new file mode 100644 index 00000000..149caba6 --- /dev/null +++ b/0001-0500/0373-Find-K-Pairs-with-Smallest-Sums/cpp-0373/main.cpp @@ -0,0 +1,85 @@ +/// Source : https://leetcode.com/problems/find-k-pairs-with-smallest-sums/ +/// Author : liuyubobobo +/// Time : 2018-11-09 + +#include +#include +#include + +using namespace std; + + +/// Using Priority Queue +/// Time Complexity: O(k * log(len(nums1))) +/// Space Complexity: O(len(nums1)) +class Solution { +public: + vector> kSmallestPairs( vector& nums1, vector& nums2, int k) { + + if(!nums1.size() || !nums2.size()) + return {}; + + vector> res; + priority_queue>, + vector>>, + greater>>> pq; + for(int i = 0; i < nums1.size(); i ++) + pq.push(make_pair(nums1[i] + nums2[0], make_pair(i, 0))); + + while(k-- && !pq.empty()){ + pair p = pq.top().second; + + res.push_back({nums1[p.first], nums2[p.second]}); + pq.pop(); + + if(p.second + 1 < nums2.size()){ + p.second ++; + pq.push(make_pair(nums1[p.first] + nums2[p.second], p)); + } + } + + return res; + } +}; + + +void print_vec(const vector>& vec){ + for(const vector& p: vec) + cout << "(" << p[0] << "," << p[1] << ") "; + cout << endl; +} + +int main() { + + vector A1 = {1, 7, 11}; + vector B1 = {2, 4, 6}; + print_vec(Solution().kSmallestPairs(A1, B1, 3)); + // (1, 2) (1, 4) (1, 6) + + vector A2 = {1, 1, 2}; + vector B2 = {1, 2, 3}; + print_vec(Solution().kSmallestPairs(A2, B2, 2)); + // (1, 1) (1, 1) + + vector A3 = {1, 2}; + vector B3 = {3}; + print_vec(Solution().kSmallestPairs(A3, B3, 3)); + // (1, 3) (2, 3) + + vector A4 = {1, 1, 2}; + vector B4 = {1, 2, 3}; + print_vec(Solution().kSmallestPairs(A4, B4, 10)); + // (1, 1) (1, 1) (2, 1) (1, 2) (1, 2) (2, 2) (1, 3) (1, 3) (2, 3) + + vector A5 = {1, 2, 4}; + vector B5 = {-1, 1, 2}; + print_vec(Solution().kSmallestPairs(A5, B5, 100)); + // (1, -1) (2, -1) (1, 1) (4, -1) (2, 1) (1, 2) (2, 2) (4, 1) (4, 2) + + vector A6 = {-10, -4, 0, 0, 6}; + vector B6 = {3, 5, 6, 7, 8, 100}; + print_vec(Solution().kSmallestPairs(A6, B6, 10)); + // (-10, 3) (-10, 5) (-10, 6) (-10, 7) (-10, 8) (-4, 3) (-4, 5) (-4, 6) (-4, 7) (0, 3) + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0374-Guess-Number-Higher-or-Lower/cpp-0374/CMakeLists.txt b/0001-0500/0374-Guess-Number-Higher-or-Lower/cpp-0374/CMakeLists.txt new file mode 100644 index 00000000..0953ffa8 --- /dev/null +++ b/0001-0500/0374-Guess-Number-Higher-or-Lower/cpp-0374/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0374) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0374 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0374-Guess-Number-Higher-or-Lower/cpp-0374/main.cpp b/0001-0500/0374-Guess-Number-Higher-or-Lower/cpp-0374/main.cpp new file mode 100644 index 00000000..790346bb --- /dev/null +++ b/0001-0500/0374-Guess-Number-Higher-or-Lower/cpp-0374/main.cpp @@ -0,0 +1,42 @@ +/// Source : https://leetcode.com/problems/guess-number-higher-or-lower/description/ +/// Author : liuyubobobo +/// Time : 2018-04-27 + +#include +#include + +using namespace std; + +// Forward declaration of guess API. +// @param num, your guess +// @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 +int guess(int num); + + +/// Binary Search +/// Time Complexity: O(logn) +/// Space Complexity: O(1) +class Solution { +public: + int guessNumber(int n) { + + int l = 1, r = n; + while(l <= r){ + int mid = l + (r - l) / 2; + int ret = guess(mid); + if(ret == 0) + return mid; + else if(ret < 0) + r = mid - 1; + else + l = mid + 1; + } + + assert(false); + } +}; + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0374-Guess-Number-Higher-or-Lower/cpp-0374/main2.cpp b/0001-0500/0374-Guess-Number-Higher-or-Lower/cpp-0374/main2.cpp new file mode 100644 index 00000000..aa1c160a --- /dev/null +++ b/0001-0500/0374-Guess-Number-Higher-or-Lower/cpp-0374/main2.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/guess-number-higher-or-lower/description/ +/// Author : liuyubobobo +/// Time : 2018-04-27 + +#include +#include + +using namespace std; + +// Forward declaration of guess API. +// @param num, your guess +// @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 +int guess(int num); + + +/// Ternary Search +/// Time Complexity: O(log3(n)) +/// Space Complexity: O(1) +class Solution { +public: + int guessNumber(int n) { + + int l = 1, r = n; + while(l <= r){ + int mid1 = l + (r - l) / 3; + int mid2 = r - (r - l) / 3; + int ret1 = guess(mid1); + if(ret1 == 0) + return mid1; + else if(ret1 < 0) + r = mid1 - 1; + else{ + int ret2 = guess(mid2); + if(ret2 == 0) + return mid2; + else if(ret2 < 0){ + l = mid1 + 1; + r = mid2 - 1; + } + else + l = mid2 + 1; + } + } + + assert(false); + } +}; + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0375-Guess-Number-Higher-or-Lower-II/cpp-0375/CMakeLists.txt b/0001-0500/0375-Guess-Number-Higher-or-Lower-II/cpp-0375/CMakeLists.txt new file mode 100644 index 00000000..cd3b7308 --- /dev/null +++ b/0001-0500/0375-Guess-Number-Higher-or-Lower-II/cpp-0375/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0375) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0375 main.cpp) diff --git a/0001-0500/0375-Guess-Number-Higher-or-Lower-II/cpp-0375/main.cpp b/0001-0500/0375-Guess-Number-Higher-or-Lower-II/cpp-0375/main.cpp new file mode 100644 index 00000000..5d8c78f6 --- /dev/null +++ b/0001-0500/0375-Guess-Number-Higher-or-Lower-II/cpp-0375/main.cpp @@ -0,0 +1,44 @@ +/// Source : https://leetcode.com/problems/guess-number-higher-or-lower-ii/ +/// Author : liuyubobobo +/// Time : 2021-11-27 + +#include +#include + +using namespace std; + + +/// Memoization +/// Time Complexity: O(n^3) +/// Space Complexity: O(n^2) +class Solution { +public: + int getMoneyAmount(int n) { + vector> dp(n + 1, vector(n + 1, -1)); + return dfs(1, n, dp); + } + +private: + int dfs(int l, int r, vector>& dp){ + + if(l == r) return 0; + if(l + 1 == r) return l; + if(l + 2 == r) return l + 1; + if(dp[l][r] != -1) return dp[l][r]; + + int res = INT_MAX; + for(int root = l + 1; root < r; root ++){ + res = min(res, root + max(dfs(l, root - 1, dp), dfs(root + 1, r, dp))); + } + return dp[l][r] = res; + } +}; + + +int main() { + + cout << Solution().getMoneyAmount(10) << endl; + // 16 + + return 0; +} diff --git a/0001-0500/0376-Wiggle-Subsequence/cpp-0376/CMakeLists.txt b/0001-0500/0376-Wiggle-Subsequence/cpp-0376/CMakeLists.txt new file mode 100644 index 00000000..b39ab13b --- /dev/null +++ b/0001-0500/0376-Wiggle-Subsequence/cpp-0376/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0376) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0376 main.cpp) \ No newline at end of file diff --git a/0001-0500/0376-Wiggle-Subsequence/cpp-0376/main.cpp b/0001-0500/0376-Wiggle-Subsequence/cpp-0376/main.cpp new file mode 100644 index 00000000..9596e440 --- /dev/null +++ b/0001-0500/0376-Wiggle-Subsequence/cpp-0376/main.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/wiggle-subsequence/submissions/ +/// Author : liuyubobobo +/// Time : 2020-12-12 + +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int wiggleMaxLength(vector& nums) { + + if(nums.size() <= 1) return nums.size(); + + nums = del_dup(nums); + + if(nums.size() <= 2) return nums.size(); + + int diff = nums[1] - nums[0], res = 2; + for(int i = 2; i < nums.size(); i ++) + if((nums[i] - nums[i - 1]) * diff < 0) + res ++, diff = nums[i] - nums[i - 1]; + return res; + } + +private: + vector del_dup(const vector& nums){ + + vector res = {nums[0]}; + for(int i = 1; i < nums.size(); i ++) + if(nums[i] != res.back()) res.push_back(nums[i]); + return res; + } +}; + + +int main() { + + vector nums1 = {1, 7, 4, 9, 2, 5}; + cout << Solution().wiggleMaxLength(nums1) << endl; + // 6 + + vector nums2 = {1,17,5,10,13,15,10,5,16,8}; + cout << Solution().wiggleMaxLength(nums2) << endl; + // 7 + + vector nums3 = {1,2,3,4,5,6,7,8,9}; + cout << Solution().wiggleMaxLength(nums3) << endl; + // 2 + + return 0; +} diff --git a/0377-Combination-Sum-IV/cpp-0377/CMakeLists.txt b/0001-0500/0377-Combination-Sum-IV/cpp-0377/CMakeLists.txt similarity index 100% rename from 0377-Combination-Sum-IV/cpp-0377/CMakeLists.txt rename to 0001-0500/0377-Combination-Sum-IV/cpp-0377/CMakeLists.txt diff --git a/0001-0500/0377-Combination-Sum-IV/cpp-0377/main.cpp b/0001-0500/0377-Combination-Sum-IV/cpp-0377/main.cpp new file mode 100644 index 00000000..0f5613b6 --- /dev/null +++ b/0001-0500/0377-Combination-Sum-IV/cpp-0377/main.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/combination-sum-iv/description/ +/// Author : liuyubobobo +/// Time : 2018-03-04 + +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(n * target) +/// Space Complexity: O(n * target) +class Solution { + +private: + vector memo; + +public: + int combinationSum4(vector& nums, int target) { + + if(nums.size() == 0) + return 0; + + memo = vector(target + 1, -1); + solve(nums, target); + + return memo[target]; + } + +private: + int solve(const vector& nums, int target){ + + if(target == 0) + return 1; + + if(memo[target] != -1) + return memo[target]; + + int res = 0; + for(int i = 0; i < nums.size() ; i ++) + if(target >= nums[i]) + res += solve(nums, target - nums[i]); + + return memo[target] = res; + } +}; + + +int main() { + + vector nums1 = {1, 2, 3}; + int target1 = 4; + cout << Solution().combinationSum4(nums1, target1) << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0377-Combination-Sum-IV/cpp-0377/main2.cpp b/0001-0500/0377-Combination-Sum-IV/cpp-0377/main2.cpp new file mode 100644 index 00000000..ae39d993 --- /dev/null +++ b/0001-0500/0377-Combination-Sum-IV/cpp-0377/main2.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/combination-sum-iv/description/ +/// Author : liuyubobobo +/// Time : 2018-02-28 +/// updated: 2019-03-31 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(n * target) +/// Space Complexity: O(target) +class Solution { +public: + int combinationSum4(vector& nums, int target) { + + int n = nums.size(); + if(n == 0) + return 0; + + vector memo(target + 1, 0); + memo[0] = 1; + + for(int i = 1; i <= target; i++) + for(int j = 0; j < n; j ++) + if(nums[j] <= i){ + if(memo[i] == -1 || memo[i - nums[j]] == -1 || + (long long)memo[i] + (long long)memo[i - nums[j]] > INT_MAX) + memo[i] = -1; + else memo[i] += memo[i - nums[j]]; + } + assert(memo[target] != -1); + return memo[target]; + } +}; + + +int main() { + + vector nums1 = {1, 2, 3}; + int target1 = 4; + cout << Solution().combinationSum4(nums1, target1) << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0378-Kth-Smallest-Element-in-a-Sorted-Matrix/cpp-0378/CMakeLists.txt b/0001-0500/0378-Kth-Smallest-Element-in-a-Sorted-Matrix/cpp-0378/CMakeLists.txt new file mode 100644 index 00000000..63519b43 --- /dev/null +++ b/0001-0500/0378-Kth-Smallest-Element-in-a-Sorted-Matrix/cpp-0378/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.12) +project(cpp_0378) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0378 main2.cpp) \ No newline at end of file diff --git a/0001-0500/0378-Kth-Smallest-Element-in-a-Sorted-Matrix/cpp-0378/main.cpp b/0001-0500/0378-Kth-Smallest-Element-in-a-Sorted-Matrix/cpp-0378/main.cpp new file mode 100644 index 00000000..b74628b8 --- /dev/null +++ b/0001-0500/0378-Kth-Smallest-Element-in-a-Sorted-Matrix/cpp-0378/main.cpp @@ -0,0 +1,95 @@ +/// Source : https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/ +/// Author : liuyubobobo +/// Time : 2018-11-13 + +#include +#include +#include +#include + +using namespace std; + + +/// Using Priority Queue +/// Time Complexity: O(m * n * logk) +/// Space Complexity: O(k) +class Solution { + +private: + class Element{ + public: + int x, y, val; + Element(int x, int y, int val): x(x), y(y), val(val){} + }; + + class CompareElement{ + public: + bool operator()(const Element& e1, const Element& e2){ + return e1.val > e2.val; + } + }; + +public: + int kthSmallest(vector>& matrix, int k) { + + int m = matrix.size(), n = matrix[0].size(); + priority_queue, CompareElement> pq; + vector> visited(m, vector(n, false)); + + pq.push(Element(0, 0, matrix[0][0])); + visited[0][0] = true; + + int cur; + for(int i = 0; i < k; i ++){ + int x = pq.top().x, y = pq.top().y; + cur = pq.top().val; + pq.pop(); + + if(x + 1 < m && !visited[x + 1][y]){ + pq.push(Element(x + 1, y, matrix[x + 1][y])); + visited[x + 1][y] = true; + } + + if(y + 1 < n && !visited[x][y + 1]){ + pq.push(Element(x, y + 1, matrix[x][y + 1])); + visited[x][y + 1] = true; + } + } + + return cur; + } +}; + + +int main() { + + vector> matrix1 = {{-5}}; + cout << Solution().kthSmallest(matrix1, 1) << endl; + // -5 + + vector> matrix2 = { + {1, 5, 9}, + {10, 11, 13}, + {12, 13, 15} + }; + cout << Solution().kthSmallest(matrix2, 8) << endl; + // 13 + + vector> matrix3 = { + {1, 3, 5}, + {6, 7, 12}, + {11, 14, 14} + }; + cout << Solution().kthSmallest(matrix3, 3) << endl; + // 5 + + vector> matrix4 = { + {1, 3, 5}, + {6, 7, 12}, + {11, 14, 14} + }; + cout << Solution().kthSmallest(matrix4, 6) << endl; + // 11 + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0378-Kth-Smallest-Element-in-a-Sorted-Matrix/cpp-0378/main2.cpp b/0001-0500/0378-Kth-Smallest-Element-in-a-Sorted-Matrix/cpp-0378/main2.cpp new file mode 100644 index 00000000..82b80993 --- /dev/null +++ b/0001-0500/0378-Kth-Smallest-Element-in-a-Sorted-Matrix/cpp-0378/main2.cpp @@ -0,0 +1,106 @@ +/// Source : https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/ +/// Author : liuyubobobo +/// Time : 2018-11-13 +/// Updated: 2022-08-02 + +#include +#include +#include +#include + +using namespace std; + + +/// Using Binary Search +/// pay attention to the edge case when l + h is negative, +/// normally in binary search, we are searching for index, so l and h are both non-negative +/// but when l and h can be negative, we need to do a special discuss +/// See line 36 and test case 5 for details +/// +/// Time Complexity: O(m * n * log(max - min)) +/// Space Complexity: O(1) +class Solution { + +private: + int m, n; + +public: + int kthSmallest(vector>& matrix, int k) { + + m = matrix.size(); + n = matrix[0].size(); + + int l = matrix[0][0], h = matrix[m - 1][n - 1]; + while(l < h){ + int sum = l + h, mid = sum / 2; + if(sum < 0 && sum % 2) mid --; + + int rank = get_rank(matrix, mid); + if(rank >= k) + h = mid; + else + l = mid + 1; + } + + return l; + } + +private: + int get_rank(const vector>& matrix, int target){ + + int res = 0; + for(int i = 0; i < m && matrix[i][0] <= target; i ++) + for(int j = 0; j < n && matrix[i][j] <= target; j ++) + res ++; + return res; + } +}; + + +int main() { + + vector> matrix1 = {{-5}}; + cout << Solution().kthSmallest(matrix1, 1) << endl; + // -5 + + vector> matrix2 = { + {1, 5, 9}, + {10, 11, 13}, + {12, 13, 15} + }; + cout << Solution().kthSmallest(matrix2, 8) << endl; + // 13 + + vector> matrix3 = { + {1, 3, 5}, + {6, 7, 12}, + {11, 14, 14} + }; + cout << Solution().kthSmallest(matrix3, 3) << endl; + // 5 + + vector> matrix4 = { + {1, 3, 5}, + {6, 7, 12}, + {11, 14, 14} + }; + cout << Solution().kthSmallest(matrix4, 6) << endl; + // 11 + + vector> matrix5 = { + {-5, -4}, + {-5, -4} + }; + cout << Solution().kthSmallest(matrix5, 2) << endl; + // -5 + + vector> matrix6 = { + {1, 5, 9}, + {10, 11, 13}, + {12, 13, 15} + }; + cout << Solution().kthSmallest(matrix6, 8) << endl; + // 13 + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0380-Insert-Delete-GetRandom-O(1)/cpp-0380/CMakeLists.txt b/0001-0500/0380-Insert-Delete-GetRandom-O(1)/cpp-0380/CMakeLists.txt new file mode 100644 index 00000000..acc2b179 --- /dev/null +++ b/0001-0500/0380-Insert-Delete-GetRandom-O(1)/cpp-0380/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0380) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0380 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0380-Insert-Delete-GetRandom-O(1)/cpp-0380/main.cpp b/0001-0500/0380-Insert-Delete-GetRandom-O(1)/cpp-0380/main.cpp new file mode 100644 index 00000000..1b919c94 --- /dev/null +++ b/0001-0500/0380-Insert-Delete-GetRandom-O(1)/cpp-0380/main.cpp @@ -0,0 +1,98 @@ +/// Source : https://leetcode.com/problems/insert-delete-getrandom-o1/description/ +/// Author : liuyubobobo +/// Time : 2018-07-08 + +#include +#include +#include + +using namespace std; + +/// Vector to stroe all elements +/// HashMap to restore all maps between elements and index +/// Time Complexity: O(1) +/// Space Complexity: O(n) +class RandomizedSet { + +private: + vector nums; + unordered_map index; + +public: + /** Initialize your data structure here. */ + RandomizedSet() { + nums.clear(); + index.clear(); + } + + /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */ + bool insert(int val) { + if(index.find(val) == index.end()){ + nums.push_back(val); + index[val] = nums.size() - 1; + return true; + } + return false; + } + + /** Removes a value from the set. Returns true if the set contained the specified element. */ + bool remove(int val) { + if(index.find(val) != index.end()){ + int i = index[val]; + index.erase(val); + + int num = nums.back(); + nums.pop_back(); + + if(num != val){ + nums[i] = num; + index[num] = i; + } + + return true; + } + return false; + } + + /** Get a random element from the set. */ + int getRandom() { + int rndIndex = rand() % nums.size(); + return nums[rndIndex]; + } + + void printInfo(){ + cout << "nums : "; + for(int num: nums) + cout << num << " "; + cout << endl; + + cout << "index : "; + for(const pair& p: index) + cout << "( " << p.first << " , " << p.second << " ) "; + cout << endl; + } +}; + + +void print_bool(bool res){ + cout << (res ? "True" : "False") << endl; +} + +int main() { + + RandomizedSet randomSet; + print_bool(randomSet.insert(0)); + randomSet.printInfo(); + print_bool(randomSet.remove(0)); + randomSet.printInfo(); + print_bool(randomSet.insert(-1)); + randomSet.printInfo(); + print_bool(randomSet.remove(0)); + randomSet.printInfo(); + + for(int i = 0 ; i < 10 ; i ++) + cout << randomSet.getRandom() << " "; + cout << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0381-Insert-Delete-GetRandom-O(1)-Duplicates-allowed/cpp-0381/CMakeLists.txt b/0001-0500/0381-Insert-Delete-GetRandom-O(1)-Duplicates-allowed/cpp-0381/CMakeLists.txt new file mode 100644 index 00000000..8f4a2af5 --- /dev/null +++ b/0001-0500/0381-Insert-Delete-GetRandom-O(1)-Duplicates-allowed/cpp-0381/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0381) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0381 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0381-Insert-Delete-GetRandom-O(1)-Duplicates-allowed/cpp-0381/main.cpp b/0001-0500/0381-Insert-Delete-GetRandom-O(1)-Duplicates-allowed/cpp-0381/main.cpp new file mode 100644 index 00000000..ee6a0e7e --- /dev/null +++ b/0001-0500/0381-Insert-Delete-GetRandom-O(1)-Duplicates-allowed/cpp-0381/main.cpp @@ -0,0 +1,70 @@ +/// Source : https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/description/ +/// Author : liuyubobobo +/// Time : 2018-07-08 + +#include +#include +#include +#include + +using namespace std; + +/// Vector to stroe all elements +/// HashMap to restore all maps between elements and index +/// Time Complexity: O(1) +/// Space Complexity: O(n) +class RandomizedCollection { + +private: + vector nums; + unordered_map> indexes; + +public: + /** Initialize your data structure here. */ + RandomizedCollection() { + nums.clear(); + indexes.clear(); + } + + /** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */ + bool insert(int val) { + nums.push_back(val); + indexes[val].insert(nums.size() - 1); + + return indexes[val].size() == 1; + } + + /** Removes a value from the collection. Returns true if the collection contained the specified element. */ + bool remove(int val) { + if(indexes.find(val) != indexes.end()){ + int i = *indexes[val].begin(); + indexes[val].erase(i); + if(indexes[val].size() == 0) + indexes.erase(val); + + int num = nums.back(); + nums.pop_back(); + if(!(num == val && nums.size() == i)){ + + nums[i] = num; + indexes[num].erase(nums.size()); + indexes[num].insert(i); + } + + return true; + } + return false; + } + + /** Get a random element from the collection. */ + int getRandom() { + int rndIndex = rand() % nums.size(); + return nums[rndIndex]; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0382-Linked-List-Random-Node/cpp-0382/CMakeLists.txt b/0001-0500/0382-Linked-List-Random-Node/cpp-0382/CMakeLists.txt new file mode 100644 index 00000000..4488fe77 --- /dev/null +++ b/0001-0500/0382-Linked-List-Random-Node/cpp-0382/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0382) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0382 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0382-Linked-List-Random-Node/cpp-0382/main.cpp b/0001-0500/0382-Linked-List-Random-Node/cpp-0382/main.cpp new file mode 100644 index 00000000..75efede2 --- /dev/null +++ b/0001-0500/0382-Linked-List-Random-Node/cpp-0382/main.cpp @@ -0,0 +1,63 @@ +/// Source : https://leetcode.com/problems/linked-list-random-node/description/ +/// Author : liuyubobobo +/// Time : 2018-07-08 + +#include + +using namespace std; + +/// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} +}; + +/// Reservoir Sampling +/// The detail of Resevoir Sampling can be seen here: +/// https://www.geeksforgeeks.org/reservoir-sampling/ +/// +/// Attention: Don't use srand in the random problem in Leetcode +/// Since it may lead to WA +/// I think the test code use its own random seed to verify your submitted code +/// +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { + +private: + ListNode* head; + +public: + /** @param head The linked list's head. + Note that the head is guaranteed to be not null, so it contains at least one node. */ + Solution(ListNode* head) { + this->head = head; + } + + /** Returns a random node's value. */ + int getRandom() { + + int res = head->val; + ListNode* cur = head->next; + int index = 1; + + // srand(time(NULL)); + while(cur != NULL){ + int rnd = rand() % (index + 1); + if(rnd == 0) + res = cur->val; + + cur = cur->next; + index ++; + } + + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0382-Linked-List-Random-Node/cpp-0382/main2.cpp b/0001-0500/0382-Linked-List-Random-Node/cpp-0382/main2.cpp new file mode 100644 index 00000000..6eeee9fc --- /dev/null +++ b/0001-0500/0382-Linked-List-Random-Node/cpp-0382/main2.cpp @@ -0,0 +1,75 @@ +/// Source : https://leetcode.com/problems/linked-list-random-node/description/ +/// Author : liuyubobobo +/// Time : 2018-07-09 + +#include +#include +#include + +using namespace std; + +/// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} +}; + +/// Reservoir Sampling +/// The detail of Resevoir Sampling can be seen here: +/// https://www.geeksforgeeks.org/reservoir-sampling/ +/// +/// Attention: Don't use srand in the random problem in Leetcode +/// Since it may lead to WA +/// I think the test code use its own random seed to verify your submitted code +/// +/// This code is based on using more general reservor sampling algorithm +/// where k = 1 +/// +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +private: + vector nums; + +public: + /** @param head The linked list's head. + Note that the head is guaranteed to be not null, so it contains at least one node. */ + Solution(ListNode* head) { + nums.clear(); + while(head){ + nums.push_back(head->val); + head = head->next; + } + } + + /** Returns a random node's value. */ + int getRandom() { + // In this problem, k == 1 + return reservorSampling(nums, 1)[0]; + } + +private: + /// General Reservor Sampling Algorithm + /// From vector nums, randomly pick k elements:) + vector reservorSampling(const vector& nums, int k){ + + assert(k >= 1 && k <= nums.size()); + vector res(nums.begin(), nums.begin() + k); + + for(int i = k ; i < nums.size() ; i ++){ + int index = rand() % (i + 1); + if(index < k) + res[index] = nums[i]; + } + + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0383-Ransom-Note/cpp-0383/CMakeLists.txt b/0001-0500/0383-Ransom-Note/cpp-0383/CMakeLists.txt new file mode 100644 index 00000000..70dd8607 --- /dev/null +++ b/0001-0500/0383-Ransom-Note/cpp-0383/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0383) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0383 main.cpp) diff --git a/0001-0500/0383-Ransom-Note/cpp-0383/main.cpp b/0001-0500/0383-Ransom-Note/cpp-0383/main.cpp new file mode 100644 index 00000000..e1c22624 --- /dev/null +++ b/0001-0500/0383-Ransom-Note/cpp-0383/main.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/ransom-note/ +/// Author : liuyubobobo +/// Time : 2021-08-09 + +#include +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(n + m) +/// Space Complexity: O(1) +class Solution { +public: + bool canConstruct(string ransomNote, string magazine) { + + vector f1(26, 0); + for(char c: ransomNote) f1[c - 'a'] ++; + + vector f2(26, 0); + for(char c: magazine) f2[c - 'a'] ++; + + for(int i = 0; i < 26; i ++) + if(f1[i] > f2[i]) return false; + return true; + } +}; + + +int main() { + + return 0; +} diff --git a/0384-Shuffle-an-Array/cpp-0384/CMakeLists.txt b/0001-0500/0384-Shuffle-an-Array/cpp-0384/CMakeLists.txt similarity index 100% rename from 0384-Shuffle-an-Array/cpp-0384/CMakeLists.txt rename to 0001-0500/0384-Shuffle-an-Array/cpp-0384/CMakeLists.txt diff --git a/0384-Shuffle-an-Array/cpp-0384/main.cpp b/0001-0500/0384-Shuffle-an-Array/cpp-0384/main.cpp similarity index 100% rename from 0384-Shuffle-an-Array/cpp-0384/main.cpp rename to 0001-0500/0384-Shuffle-an-Array/cpp-0384/main.cpp diff --git a/0384-Shuffle-an-Array/cpp-0384/main2.cpp b/0001-0500/0384-Shuffle-an-Array/cpp-0384/main2.cpp similarity index 100% rename from 0384-Shuffle-an-Array/cpp-0384/main2.cpp rename to 0001-0500/0384-Shuffle-an-Array/cpp-0384/main2.cpp diff --git a/0384-Shuffle-an-Array/cpp-0384/main3.cpp b/0001-0500/0384-Shuffle-an-Array/cpp-0384/main3.cpp similarity index 100% rename from 0384-Shuffle-an-Array/cpp-0384/main3.cpp rename to 0001-0500/0384-Shuffle-an-Array/cpp-0384/main3.cpp diff --git a/0001-0500/0385-Mini-Parser/cpp-0385/CMakeLists.txt b/0001-0500/0385-Mini-Parser/cpp-0385/CMakeLists.txt new file mode 100644 index 00000000..4f14b5ed --- /dev/null +++ b/0001-0500/0385-Mini-Parser/cpp-0385/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_0385) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0385 main.cpp) diff --git a/0001-0500/0385-Mini-Parser/cpp-0385/main.cpp b/0001-0500/0385-Mini-Parser/cpp-0385/main.cpp new file mode 100644 index 00000000..9bd99bdf --- /dev/null +++ b/0001-0500/0385-Mini-Parser/cpp-0385/main.cpp @@ -0,0 +1,123 @@ +/// Source : https://leetcode.com/problems/mini-parser/ +/// Author : liuyubobobo +/// Time : 2022-04-14 + +#include +#include +#include + +using namespace std; + + +/// Recursive +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +// This is the interface that allows for creating nested lists. +// You should not implement it, or speculate about its implementation +class NestedInteger { + +private: + bool is_integer; + int x; + vector v; + +public: + // Constructor initializes an empty nested list. + NestedInteger(){} + + // Constructor initializes a single integer. + NestedInteger(int value) : is_integer(true), x(value){}; + + // Return true if this NestedInteger holds a single integer, rather than a nested list. + bool isInteger(){ + return is_integer; + }; + + // Return the single integer that this NestedInteger holds, if it holds a single integer + // The result is undefined if this NestedInteger holds a nested list + int getInteger(){ + assert(is_integer); + return x; + }; + + // Set this NestedInteger to hold a single integer. + void setInteger(int value){ + is_integer = true; + x = value; + } + + // Set this NestedInteger to hold a nested list and adds a nested integer to it. + void add(const NestedInteger &ni){ + is_integer = false; + v.push_back(ni); + } + + // Return the nested list that this NestedInteger holds, if it holds a nested list + // The result is undefined if this NestedInteger holds a single integer + const vector getList() const{ + return v; + } +}; + +class Solution { +public: + NestedInteger deserialize(string s) { + + int n = s.size(); + vector right(n, -1), stack; + for(int i = 0; i < n; i ++){ + if(s[i] == '[') stack.push_back(i); + else if(s[i] == ']'){ + assert(!stack.empty()); + int l = stack.back(); stack.pop_back(); + right[l] = i; + } + } + return dfs(s, 0, n - 1, right); + } + +private: + NestedInteger dfs(const string& s, int l, int r, const vector& right){ + + if(l + 1 == r && s[l] == '['){ + NestedInteger res; + return res; + } + + if(isdigit(s[l]) || s[l] == '-'){ + NestedInteger res; + int x = atol(s.substr(l, r - l + 1).c_str()); + res.setInteger(x); + return res; + } + + assert(s[l] == '[' && s[r] == ']'); + NestedInteger res; + for(int start = l + 1, i = l + 1; i <= r;){ + if(i == r || s[i] == ','){ + res.add(dfs(s, start, i - 1, right)); + start = i + 1; + i = start; + } + else if(s[i] == '['){ + assert(right[i] <= r && s[right[i]] == ']'); + res.add(dfs(s, i, right[i], right)); + start = right[i] + 2; + i = start; + } + else i ++; + } + return res; + } +}; + + +int main() { + + Solution().deserialize("[123,[456,[789]]]"); + + Solution().deserialize("-3"); + + return 0; +} diff --git a/0386-Lexicographical-Numbers/cpp-0386/CMakeLists.txt b/0001-0500/0386-Lexicographical-Numbers/cpp-0386/CMakeLists.txt similarity index 100% rename from 0386-Lexicographical-Numbers/cpp-0386/CMakeLists.txt rename to 0001-0500/0386-Lexicographical-Numbers/cpp-0386/CMakeLists.txt diff --git a/0386-Lexicographical-Numbers/cpp-0386/main.cpp b/0001-0500/0386-Lexicographical-Numbers/cpp-0386/main.cpp similarity index 100% rename from 0386-Lexicographical-Numbers/cpp-0386/main.cpp rename to 0001-0500/0386-Lexicographical-Numbers/cpp-0386/main.cpp diff --git a/0387-First-Unique-Character-in-a-String/cpp-0387/CMakeLists.txt b/0001-0500/0387-First-Unique-Character-in-a-String/cpp-0387/CMakeLists.txt similarity index 100% rename from 0387-First-Unique-Character-in-a-String/cpp-0387/CMakeLists.txt rename to 0001-0500/0387-First-Unique-Character-in-a-String/cpp-0387/CMakeLists.txt diff --git a/0001-0500/0387-First-Unique-Character-in-a-String/cpp-0387/main.cpp b/0001-0500/0387-First-Unique-Character-in-a-String/cpp-0387/main.cpp new file mode 100644 index 00000000..9203bf5f --- /dev/null +++ b/0001-0500/0387-First-Unique-Character-in-a-String/cpp-0387/main.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/first-unique-character-in-a-string/description/ +/// Author : liuyubobobo +/// Time : 2017-10-16 + +#include + +using namespace std; + + +/// Using Hash Map +/// Time Complexity: O(len(s)) +/// Space Complexity: O(26) +class Solution { + +public: + int firstUniqChar(string s) { + int freq[26] = {0}; + for(char c: s) + freq[c-'a'] ++; + + for(int i = 0 ; i < s.size() ; i ++) + if(freq[s[i]-'a'] == 1) + return i; + + return -1; + } +}; + + +int main() { + + cout << Solution().firstUniqChar("leetcode") << endl; + cout << Solution().firstUniqChar("loveleetcode") << endl; + return 0; +} \ No newline at end of file diff --git a/0001-0500/0387-First-Unique-Character-in-a-String/java-0387/src/Solution.java b/0001-0500/0387-First-Unique-Character-in-a-String/java-0387/src/Solution.java new file mode 100644 index 00000000..0953777b --- /dev/null +++ b/0001-0500/0387-First-Unique-Character-in-a-String/java-0387/src/Solution.java @@ -0,0 +1,21 @@ +/// Source : https://leetcode.com/problems/first-unique-character-in-a-string/description/ +/// Author : liuyubobobo +/// Time : 2017-10-16 + +/// Using Hash Map +/// Time Complexity: O(len(s)) +/// Space Complexity: O(26) +class Solution { + public int firstUniqChar(String s) { + + int[] freq = new int[26]; + for(int i = 0 ; i < s.length() ; i ++) + freq[s.charAt(i) - 'a'] ++; + + for(int i = 0 ; i < s.length() ; i ++) + if(freq[s.charAt(i) - 'a'] == 1) + return i; + + return -1; + } +} diff --git a/0388-Longest-Absolute-File-Path/cpp-0388/CMakeLists.txt b/0001-0500/0388-Longest-Absolute-File-Path/cpp-0388/CMakeLists.txt similarity index 100% rename from 0388-Longest-Absolute-File-Path/cpp-0388/CMakeLists.txt rename to 0001-0500/0388-Longest-Absolute-File-Path/cpp-0388/CMakeLists.txt diff --git a/0388-Longest-Absolute-File-Path/cpp-0388/main.cpp b/0001-0500/0388-Longest-Absolute-File-Path/cpp-0388/main.cpp similarity index 100% rename from 0388-Longest-Absolute-File-Path/cpp-0388/main.cpp rename to 0001-0500/0388-Longest-Absolute-File-Path/cpp-0388/main.cpp diff --git a/0389-Find-the-Difference/cpp-0389/CMakeLists.txt b/0001-0500/0389-Find-the-Difference/cpp-0389/CMakeLists.txt similarity index 100% rename from 0389-Find-the-Difference/cpp-0389/CMakeLists.txt rename to 0001-0500/0389-Find-the-Difference/cpp-0389/CMakeLists.txt diff --git a/0389-Find-the-Difference/cpp-0389/main.cpp b/0001-0500/0389-Find-the-Difference/cpp-0389/main.cpp similarity index 100% rename from 0389-Find-the-Difference/cpp-0389/main.cpp rename to 0001-0500/0389-Find-the-Difference/cpp-0389/main.cpp diff --git a/0390-Elimination-Game/cpp-0390/CMakeLists.txt b/0001-0500/0390-Elimination-Game/cpp-0390/CMakeLists.txt similarity index 100% rename from 0390-Elimination-Game/cpp-0390/CMakeLists.txt rename to 0001-0500/0390-Elimination-Game/cpp-0390/CMakeLists.txt diff --git a/0390-Elimination-Game/cpp-0390/main.cpp b/0001-0500/0390-Elimination-Game/cpp-0390/main.cpp similarity index 100% rename from 0390-Elimination-Game/cpp-0390/main.cpp rename to 0001-0500/0390-Elimination-Game/cpp-0390/main.cpp diff --git a/0391-Perfect-Rectangle/cpp-0391/CMakeLists.txt b/0001-0500/0391-Perfect-Rectangle/cpp-0391/CMakeLists.txt similarity index 100% rename from 0391-Perfect-Rectangle/cpp-0391/CMakeLists.txt rename to 0001-0500/0391-Perfect-Rectangle/cpp-0391/CMakeLists.txt diff --git a/0391-Perfect-Rectangle/cpp-0391/main.cpp b/0001-0500/0391-Perfect-Rectangle/cpp-0391/main.cpp similarity index 100% rename from 0391-Perfect-Rectangle/cpp-0391/main.cpp rename to 0001-0500/0391-Perfect-Rectangle/cpp-0391/main.cpp diff --git a/0001-0500/0392-Is-Subsequence/cpp-0392/CMakeLists.txt b/0001-0500/0392-Is-Subsequence/cpp-0392/CMakeLists.txt new file mode 100644 index 00000000..94cb5c4d --- /dev/null +++ b/0001-0500/0392-Is-Subsequence/cpp-0392/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(cpp_0392) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0392 main.cpp) \ No newline at end of file diff --git a/0001-0500/0392-Is-Subsequence/cpp-0392/main.cpp b/0001-0500/0392-Is-Subsequence/cpp-0392/main.cpp new file mode 100644 index 00000000..83c0e105 --- /dev/null +++ b/0001-0500/0392-Is-Subsequence/cpp-0392/main.cpp @@ -0,0 +1,30 @@ +/// Source : https://leetcode.com/problems/is-subsequence/ +/// Author : liuyubobobo +/// Time : 2019-08-04 + +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(len(s) + len(t)) +/// Space Complexity: O(1) +class Solution { +public: + bool isSubsequence(string s, string t) { + + int index = -1; + for(char c: s){ + index = t.find(c, index + 1); + if(index == string::npos) return false; + } + return true; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0393-UTF-8-Validation/cpp-0393/CMakeLists.txt b/0001-0500/0393-UTF-8-Validation/cpp-0393/CMakeLists.txt new file mode 100644 index 00000000..3b9aeebe --- /dev/null +++ b/0001-0500/0393-UTF-8-Validation/cpp-0393/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0393) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main2.cpp) +add_executable(cpp_0393 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0393-UTF-8-Validation/cpp-0393/main.cpp b/0001-0500/0393-UTF-8-Validation/cpp-0393/main.cpp new file mode 100644 index 00000000..f9f3786f --- /dev/null +++ b/0001-0500/0393-UTF-8-Validation/cpp-0393/main.cpp @@ -0,0 +1,78 @@ +/// Source : https://leetcode.com/problems/utf-8-validation/ +/// Author : liuyubobobo +/// Time : 2018-10-31 + +#include +#include + +using namespace std; + + +/// Using Binary String +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + bool validUtf8(vector& data) { + + for(int i = 0; i < data.size(); ){ + string byte = get_binary_str(data[i]); + if(byte[0] == '0') + i ++; + else if(byte.substr(0, 3) == "110"){ + if(i + 1 >= data.size()) + return false; + if(!is10(data[i + 1])) + return false; + i += 2; + } + else if(byte.substr(0, 4) == "1110"){ + if(i + 2 >= data.size()) + return false; + for(int j = 1; j <= 2; j ++) + if(!is10(data[i + j])) + return false; + i += 3; + } + else if(byte.substr(0, 5) == "11110"){ + if(i + 3 >= data.size()) + return false; + for(int j = 1; j <= 3; j ++) + if(!is10(data[i + j])) + return false; + i += 4; + } + else + return false; + } + + return true; + } + +private: + bool is10(int byte){ + string s = get_binary_str(byte); + return s[0] == '1' && s[1] == '0'; + } + + string get_binary_str(int data){ + string ret = ""; + for(int i = 0; i < 8; i ++){ + ret += '0' + data % 2; + data /= 2; + } + reverse(ret.begin(), ret.end()); + return ret; + } +}; + + +int main() { + + vector data1 = {197, 130, 1}; + // 11000101 10000010 00000001 + cout << Solution().validUtf8(data1) << endl; + // true + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0393-UTF-8-Validation/cpp-0393/main2.cpp b/0001-0500/0393-UTF-8-Validation/cpp-0393/main2.cpp new file mode 100644 index 00000000..9fbf9fbc --- /dev/null +++ b/0001-0500/0393-UTF-8-Validation/cpp-0393/main2.cpp @@ -0,0 +1,67 @@ +/// Source : https://leetcode.com/problems/utf-8-validation/ +/// Author : liuyubobobo +/// Time : 2018-10-31 + +#include +#include + +using namespace std; + + +/// Using Bit Manipulation +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + bool validUtf8(vector& data) { + + for(int i = 0; i < data.size(); ){ + int byte = data[i] & 0b11111111; + if(!(byte & 0b10000000)) + i ++; + else if((byte & 0b11000000) == 0b11000000 && !(byte & 0b00100000)){ + if(i + 1 >= data.size()) + return false; + if(!is10(data[i + 1])) + return false; + i += 2; + } + else if((byte & 0b11100000) == 0b11100000 && !(byte & 0b00010000)){ + if(i + 2 >= data.size()) + return false; + for(int j = 1; j <= 2; j ++) + if(!is10(data[i + j])) + return false; + i += 3; + } + else if((byte & 0b11110000) == 0b11110000 && !(byte & 0b00001000)){ + if(i + 3 >= data.size()) + return false; + for(int j = 1; j <= 3; j ++) + if(!is10(data[i + j])) + return false; + i += 4; + } + else + return false; + } + + return true; + } + +private: + bool is10(int byte){ + return (byte & 0b10000000) && !(byte & 0b01000000); + } +}; + + +int main() { + + vector data1 = {197, 130, 1}; + // 11000101 10000010 00000001 + cout << Solution().validUtf8(data1) << endl; + // true + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0394-Decode-String/cpp-0394/CMakeLists.txt b/0001-0500/0394-Decode-String/cpp-0394/CMakeLists.txt new file mode 100644 index 00000000..e86c04ac --- /dev/null +++ b/0001-0500/0394-Decode-String/cpp-0394/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0394) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main3.cpp) +add_executable(cpp_0394 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0394-Decode-String/cpp-0394/main.cpp b/0001-0500/0394-Decode-String/cpp-0394/main.cpp new file mode 100644 index 00000000..51584262 --- /dev/null +++ b/0001-0500/0394-Decode-String/cpp-0394/main.cpp @@ -0,0 +1,69 @@ +/// Source : https://leetcode.com/problems/decode-string/description/ +/// Author : liuyubobobo +/// Time : 2018-09-29 + +#include +#include + +using namespace std; + + +/// DFS - recursion algorithm +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + string decodeString(string s) { + int end; + return dfs(s, 0, end); + } + +private: + string dfs(const string& s, int start, int& end){ + + string res = ""; + for(int i = start; i < s.size();) + if(isalpha(s[i])) + res += s[i++]; + else if(isdigit(s[i])){ + int j; + for(j = i + 1; j < s.size() && isdigit(s[j]); j ++); + int num = atoi(s.substr(i, j - i).c_str()); + assert(s[j] == '['); + + int e; + string sub = dfs(s, j + 1, e); + while(num --) + res += sub; + + assert(s[e] == ']'); + i = e + 1; + } + else{ + assert(s[i] == ']'); + end = i; + return res; + } + + end = s.size(); + return res; + } +}; + + +int main() { + + string s1 = "3[a]2[bc]"; + cout << Solution().decodeString(s1) << endl; + // "aaabcbc" + + string s2 = "3[a2[c]]"; + cout << Solution().decodeString(s2) << endl; + // "accaccacc" + + string s3 = "2[abc]3[cd]ef"; + cout << Solution().decodeString(s3) << endl; + // "abcabccdcdcdef" + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0394-Decode-String/cpp-0394/main2.cpp b/0001-0500/0394-Decode-String/cpp-0394/main2.cpp new file mode 100644 index 00000000..306036e6 --- /dev/null +++ b/0001-0500/0394-Decode-String/cpp-0394/main2.cpp @@ -0,0 +1,67 @@ +/// Source : https://leetcode.com/problems/decode-string/description/ +/// Author : liuyubobobo +/// Time : 2018-09-29 + +#include +#include +#include + +using namespace std; + + +/// Using Stack - non recursion algorithm +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + string decodeString(string s) { + + vector stack; + vector nums; + + stack.push_back(""); + for(int i = 0; i < s.size();) + if(isalpha(s[i])) + stack.back() += s[i ++]; + else if(isdigit(s[i])){ + int j; + for(j = i + 1; j < s.size() && isdigit(s[j]); j ++); + nums.push_back(atoi(s.substr(i, j - i).c_str())); + stack.push_back(""); + assert(s[j] == '['); + i = j + 1; + } + else{ + assert(s[i] == ']'); + string tres = stack.back(); + stack.pop_back(); + + int num = nums.back(); + nums.pop_back(); + + while(num --) + stack.back() += tres; + + i ++; + } + return stack.back(); + } +}; + + +int main() { + + string s1 = "3[a]2[bc]"; + cout << Solution().decodeString(s1) << endl; + // "aaabcbc" + + string s2 = "3[a2[c]]"; + cout << Solution().decodeString(s2) << endl; + // "accaccacc" + + string s3 = "2[abc]3[cd]ef"; + cout << Solution().decodeString(s3) << endl; + // "abcabccdcdcdef" + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0394-Decode-String/cpp-0394/main3.cpp b/0001-0500/0394-Decode-String/cpp-0394/main3.cpp new file mode 100644 index 00000000..369528f5 --- /dev/null +++ b/0001-0500/0394-Decode-String/cpp-0394/main3.cpp @@ -0,0 +1,76 @@ +/// Source : https://leetcode.com/problems/decode-string/description/ +/// Author : liuyubobobo +/// Time : 2021-12-19 + +#include +#include +#include +#include + +using namespace std; + + +/// DFS - recursion algorithm +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + string decodeString(string s) { + + int n = s.size(); + + // ends[i] 表示如果 s[i] == '[', 其对应的 ']' 的位置 + vector ends(n, -1); + stack stack; + for(int i = 0; i < n; i ++) { + if (s[i] == '[') stack.push(i); + else if (s[i] == ']') ends[stack.top()] = i, stack.pop(); + } + + return dfs(s, 0, n - 1, ends); + } + +private: + string dfs(const string& s, int l, int r, const vector& ends){ + + if(l > r) return ""; + + // 如果 s[l] 是字符,则可以直接处理后面 + if(isalpha(s[l])) return string(1, s[l]) + dfs(s, l + 1, r, ends); + + // 否则 s[l] 一定是数字 + assert(isdigit(s[l])); + int num = 0, i; // num 是当前完整的数字(数字可能多位) + for(i = l; isdigit(s[i]); i ++) + num = num * 10 + (s[i] - '0'); + + // 数字最后一位的后一个字符一定是 '[' + assert(s[i] == '['); + string res = ""; + string t = dfs(s, i + 1, ends[i] - 1, ends); // 递归求出 [] 中的字符串 + while(num --) res += t; // 这个字符串重复 num 次 + + // 如果 ']' 后续还有未处理的字符,则继续递归处理 + if(ends[i] + 1 <= r) res += dfs(s, ends[i] + 1, r, ends); + + return res; + } +}; + + +int main() { + + string s1 = "3[a]2[bc]"; + cout << Solution().decodeString(s1) << endl; + // "aaabcbc" + + string s2 = "3[a2[c]]"; + cout << Solution().decodeString(s2) << endl; + // "accaccacc" + + string s3 = "2[abc]3[cd]ef"; + cout << Solution().decodeString(s3) << endl; + // "abcabccdcdcdef" + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0395-Longest-Substring-with-At-Least-K-Repeating-Characters/cpp-0395/CMakeLists.txt b/0001-0500/0395-Longest-Substring-with-At-Least-K-Repeating-Characters/cpp-0395/CMakeLists.txt new file mode 100644 index 00000000..3f842084 --- /dev/null +++ b/0001-0500/0395-Longest-Substring-with-At-Least-K-Repeating-Characters/cpp-0395/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0395) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0395 main.cpp) \ No newline at end of file diff --git a/0001-0500/0395-Longest-Substring-with-At-Least-K-Repeating-Characters/cpp-0395/main.cpp b/0001-0500/0395-Longest-Substring-with-At-Least-K-Repeating-Characters/cpp-0395/main.cpp new file mode 100644 index 00000000..8eaa5fa6 --- /dev/null +++ b/0001-0500/0395-Longest-Substring-with-At-Least-K-Repeating-Characters/cpp-0395/main.cpp @@ -0,0 +1,58 @@ +/// Source : https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/ +/// Author : liuyubobobo +/// Time : 2021-03-01 + +#include +#include + +using namespace std; + + +/// Divide and Conquered +/// Time Complexity: O(nlogn) +/// Space Complexity: O(logn) +class Solution { +public: + int longestSubstring(string s, int k) { + + int n = s.size(); + vector> presum(26, vector(n + 1, 0)); + for(int i = 0; i < n; i ++) + for(int c = 0; c < 26; c ++) + presum[c][i + 1] = presum[c][i] + (s[i] == 'a' + c); + + return solve(s, k, 0, n - 1, presum); + } + +private: + int solve(const string& s, int k, int l, int r, const vector>& presum){ + + if(l > r || r - l + 1 < k) return 0; + + int breakchar = -1; + for(int c = 0; c < 26; c ++) + if((presum[c][r + 1] - presum[c][l]) && presum[c][r + 1] - presum[c][l] < k){ + breakchar = c; + break; + } + + if(breakchar == -1) return r - l + 1; + + int pos = -1; + for(int i = l; i <= r; i ++) + if(s[i] == 'a' + breakchar){ + pos = i; + break; + } + return max(solve(s, k, l, pos - 1, presum), solve(s, k, pos + 1, r, presum)); + } +}; + + +int main() { + + cout << Solution().longestSubstring("aaabb", 3) << endl; + // 3 + + return 0; +} diff --git a/0001-0500/0396-Rotate-Function/cpp-0396/CMakeLists.txt b/0001-0500/0396-Rotate-Function/cpp-0396/CMakeLists.txt new file mode 100644 index 00000000..5c6b2f59 --- /dev/null +++ b/0001-0500/0396-Rotate-Function/cpp-0396/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_0396) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0396 main.cpp) diff --git a/0001-0500/0396-Rotate-Function/cpp-0396/main.cpp b/0001-0500/0396-Rotate-Function/cpp-0396/main.cpp new file mode 100644 index 00000000..bd225b42 --- /dev/null +++ b/0001-0500/0396-Rotate-Function/cpp-0396/main.cpp @@ -0,0 +1,44 @@ +/// Source : https://leetcode.com/problems/rotate-function/ +/// Author : liuyubobobo +/// Time : 2022-04-21 + +#include +#include + +using namespace std; + + +/// Presum +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int maxRotateFunction(vector& nums) { + + int n = nums.size(); + vector presum(n + 1, 0); + for(int i = 0; i < n; i ++) presum[i + 1] = presum[i] + nums[i]; + + int cur = 0; + for(int i = 0; i < n; i ++) cur += i * nums[i]; + + int res = cur; + for(int i = 1; i < n; i ++){ + cur -= presum[n] - presum[i]; + cur -= presum[i - 1]; + cur += (n - 1) * nums[i - 1]; + res = max(res, cur); + } + return res; + } +}; + + +int main() { + + vector nums1 = {4, 3, 2, 6}; + cout << Solution().maxRotateFunction(nums1) << '\n'; + // 26 + + return 0; +} diff --git a/0001-0500/0397-Integer-Replacement/cpp-0397/CMakeLists.txt b/0001-0500/0397-Integer-Replacement/cpp-0397/CMakeLists.txt new file mode 100644 index 00000000..97b4dd14 --- /dev/null +++ b/0001-0500/0397-Integer-Replacement/cpp-0397/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0397) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0397 main.cpp) diff --git a/0001-0500/0397-Integer-Replacement/cpp-0397/main.cpp b/0001-0500/0397-Integer-Replacement/cpp-0397/main.cpp new file mode 100644 index 00000000..26bc345a --- /dev/null +++ b/0001-0500/0397-Integer-Replacement/cpp-0397/main.cpp @@ -0,0 +1,32 @@ +/// Source : https://leetcode.com/problems/integer-replacement/ +/// Author : liuyubobobo +/// Time : 2021-11-18 + +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(logn) +/// Space Complexity: O(1) +class Solution { +public: + int integerReplacement(long long n) { + + int res = 0; + while(n != 1){ + if(n == 3) n = 1, res += 2; + else if(n % 2 == 0) res ++, n /= 2; + else if((n + 1) % 4 == 0) n ++, res ++; + else n --, res ++; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0398-Random-Pick-Index/cpp-0398/CMakeLists.txt b/0001-0500/0398-Random-Pick-Index/cpp-0398/CMakeLists.txt new file mode 100644 index 00000000..b0d2a4b2 --- /dev/null +++ b/0001-0500/0398-Random-Pick-Index/cpp-0398/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0398) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0398 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0398-Random-Pick-Index/cpp-0398/main.cpp b/0001-0500/0398-Random-Pick-Index/cpp-0398/main.cpp new file mode 100644 index 00000000..4214d63c --- /dev/null +++ b/0001-0500/0398-Random-Pick-Index/cpp-0398/main.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/random-pick-index/description/ +/// Author : liuyubobobo +/// Time : 2018-07-08 + +#include +#include + +using namespace std; + + +/// Reservor Sampling +/// The detail of Resevoir Sampling can be seen here: +/// https://www.geeksforgeeks.org/reservoir-sampling/ +/// +/// Attention: Don't use srand in the random problem in Leetcode +/// Since it may lead to WA +/// I think the test code use its own random seed to verify your submitted code +/// +/// Time Complexity: init: O(n) +/// pick: O(n) +/// Space Complexity: O(1) +class Solution { + +private: + vector nums; + +public: + Solution(vector nums) { + + for(int num: nums) + this->nums.push_back(num); + } + + int pick(int target) { + + int res = -1; + int cnt = 0; + for(int i = 0 ; i < nums.size() ; i ++) + if(nums[i] == target){ + cnt ++; + int rnd = rand() % cnt; + if(rnd == 0) + res = i; + } + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0399-Evaluate-Division/cpp-0399/CMakeLists.txt b/0001-0500/0399-Evaluate-Division/cpp-0399/CMakeLists.txt new file mode 100644 index 00000000..ec171fb7 --- /dev/null +++ b/0001-0500/0399-Evaluate-Division/cpp-0399/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0399) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0399 main.cpp) \ No newline at end of file diff --git a/0001-0500/0399-Evaluate-Division/cpp-0399/main.cpp b/0001-0500/0399-Evaluate-Division/cpp-0399/main.cpp new file mode 100644 index 00000000..9d10eb6d --- /dev/null +++ b/0001-0500/0399-Evaluate-Division/cpp-0399/main.cpp @@ -0,0 +1,72 @@ +/// Source : https://leetcode.com/problems/evaluate-division/ +/// Author : liuyubobobo +/// Time : 2021-01-05 + +#include +#include +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(q * n) +/// Space Complexity: O(n) +class Solution { +public: + vector calcEquation(vector>& equations, + vector& values, + vector>& queries) { + + unordered_map> g; + for(int i = 0; i < values.size(); i ++) + g[equations[i][0]][equations[i][1]] = values[i], + g[equations[i][1]][equations[i][0]] = 1.0 / values[i]; + + vector res; + for(const vector& q: queries){ + unordered_set visited; + res.push_back(dfs(g, q[0], q[1], visited)); + } + return res; + } + +private: + double dfs(const unordered_map>& g, + const string& s, const string& t, unordered_set& visited){ + + if(!g.count(s)) return -1.0; + if(s == t) return 1.0; + + visited.insert(s); + for(const pair& p: g.at(s)) + if(!visited.count(p.first)){ + double tres = dfs(g, p.first, t, visited); + if(tres >= 0.0) return tres * p.second; + } + return -1.0; + } +}; + + +void print_vec(const vector& res){ + for(double e: res) cout << e << " "; cout << endl; +} + +int main() { + + vector> equations1 = {{"a","b"},{"b","c"}}; + vector values1 = {2.0, 3.0}; + vector> queries1 = {{"a","c"},{"b","a"},{"a","e"},{"a","a"},{"x","x"}}; + print_vec(Solution().calcEquation(equations1, values1, queries1)); + // 6.00000,0.50000,-1.00000,1.00000,-1.00000 + + vector> equations2 = {{"a","b"},{"b","c"},{"a","c"}}; + vector values2 = {2.0, 3.0, 6.0}; + vector> queries2 = {{"a","c"},{"b","a"},{"a","e"},{"a","a"},{"x","x"}}; + print_vec(Solution().calcEquation(equations2, values2, queries2)); + // 6.00000,0.50000,-1.00000,1.00000,-1.00000 + + return 0; +} diff --git a/0001-0500/0400-Nth-Digit/cpp-0400/CMakeLists.txt b/0001-0500/0400-Nth-Digit/cpp-0400/CMakeLists.txt new file mode 100644 index 00000000..5d157a9f --- /dev/null +++ b/0001-0500/0400-Nth-Digit/cpp-0400/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0400) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0400 main.cpp) diff --git a/0001-0500/0400-Nth-Digit/cpp-0400/main.cpp b/0001-0500/0400-Nth-Digit/cpp-0400/main.cpp new file mode 100644 index 00000000..1d2b6313 --- /dev/null +++ b/0001-0500/0400-Nth-Digit/cpp-0400/main.cpp @@ -0,0 +1,43 @@ +/// Source : https://leetcode.com/problems/nth-digit/ +/// Author : liuyubobobo +/// Time : 2021-11-29 + +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(logn) +/// Space Complexity: O(1) +class Solution { +public: + int findNthDigit(int n) { + + n --; + + int d = 1; + long long total = 9; + while(n >= total * d) + n -= total * d, d ++, total *= 10; + return to_string(total / 9 + n / d)[n % d] - '0'; + } +}; + + +int main() { + + cout << Solution().findNthDigit(3) << endl; + // 3 + + cout << Solution().findNthDigit(11) << endl; + // 0 + + cout << Solution().findNthDigit(100) << endl; + // 5 + + cout << Solution().findNthDigit(1000) << endl; + // 3 + + return 0; +} diff --git a/0001-0500/0401-Binary-Watch/cpp-0401/CMakeLists.txt b/0001-0500/0401-Binary-Watch/cpp-0401/CMakeLists.txt new file mode 100644 index 00000000..b219e33f --- /dev/null +++ b/0001-0500/0401-Binary-Watch/cpp-0401/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(cpp_0401) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0401 main2.cpp) \ No newline at end of file diff --git a/0001-0500/0401-Binary-Watch/cpp-0401/main.cpp b/0001-0500/0401-Binary-Watch/cpp-0401/main.cpp new file mode 100644 index 00000000..a18fc597 --- /dev/null +++ b/0001-0500/0401-Binary-Watch/cpp-0401/main.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/binary-watch/ +/// Author : liuyubobobo +/// Time : 2020-02-15 + +#include +#include +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(2^10) +/// Space Complexity: O(1) +class Solution { + +public: + vector readBinaryWatch(int num) { + + vector res; + for(int i = 0; i < (1 << 10); i ++) + if(num_of_ones(i) == num){ + int m = i & 0b111111, h = i >> 6; + if(h < 12 && m < 60){ + stringstream ss; + ss << h << ":" << setfill('0') << setw(2) << m; + res.push_back(ss.str()); + } + } + return res; + } + +private: + int num_of_ones(int x){ + int res = 0; + while(x) res += x % 2, x /= 2; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0401-Binary-Watch/cpp-0401/main2.cpp b/0001-0500/0401-Binary-Watch/cpp-0401/main2.cpp new file mode 100644 index 00000000..3aac302d --- /dev/null +++ b/0001-0500/0401-Binary-Watch/cpp-0401/main2.cpp @@ -0,0 +1,60 @@ +/// Source : https://leetcode.com/problems/binary-watch/ +/// Author : liuyubobobo +/// Time : 2020-02-15 + +#include +#include +#include +#include + +using namespace std; + + +/// Backtracking +/// Time Complexity: O(2^10) +/// Space Complexity: O(1) +class Solution { + +public: + vector readBinaryWatch(int num) { + + vector res; + vector bits(10, false); + go(bits, 0, num, res); + return res; + } + +private: + void go(vector& bits, int index, int num, vector& res){ + + if(index == 10){ + int h = 0; + for(int i = 0; i < 4; i ++) h = h * 2 + bits[i]; + + int m = 0; + for(int i = 4; i < 10; i ++) m = m * 2 + bits[i]; + + if(h < 12 && m < 60){ + stringstream ss; + ss << h << ":" << setfill('0') << setw(2) << m; + res.push_back(ss.str()); + } + + return; + } + + if(10 - index > num) go(bits, index + 1, num, res); + if(num){ + bits[index] = true; + go(bits, index + 1, num - 1, res); + bits[index] = false; + } + return; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0402-Remove-K-Digits/cpp-0402/CMakeLists.txt b/0001-0500/0402-Remove-K-Digits/cpp-0402/CMakeLists.txt new file mode 100644 index 00000000..0d7688f2 --- /dev/null +++ b/0001-0500/0402-Remove-K-Digits/cpp-0402/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(cpp_0402) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0402 main.cpp) \ No newline at end of file diff --git a/0001-0500/0402-Remove-K-Digits/cpp-0402/main.cpp b/0001-0500/0402-Remove-K-Digits/cpp-0402/main.cpp new file mode 100644 index 00000000..de79e4eb --- /dev/null +++ b/0001-0500/0402-Remove-K-Digits/cpp-0402/main.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/remove-k-digits/ +/// Author : liuyubobobo +/// Time : 2020-05-21 + +#include +#include + +using namespace std; + + +/// Monotone Stack +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + string removeKdigits(string num, int k) { + + string res = ""; + for(int i = 0; i < num.size(); i ++){ + while(res.size() && res.back() > num[i] && k){ + res.pop_back(); + k --; + } + res += num[i]; + } + + while(k) res.pop_back(), k --; + + int start = 0; + while(start < res.size() && res[start] == '0') start ++; + res = res.substr(start); + + return res.size() ? res : "0"; + } +}; + + +int main() { + + cout << Solution().removeKdigits("10", 2) << endl; + // 0 + + cout << Solution().removeKdigits("112", 1) << endl; + // 11 + + return 0; +} diff --git a/0001-0500/0403-Frog-Jump/cpp-0403/CMakeLists.txt b/0001-0500/0403-Frog-Jump/cpp-0403/CMakeLists.txt new file mode 100644 index 00000000..056da844 --- /dev/null +++ b/0001-0500/0403-Frog-Jump/cpp-0403/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_0403) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0403 main.cpp) \ No newline at end of file diff --git a/0001-0500/0403-Frog-Jump/cpp-0403/main.cpp b/0001-0500/0403-Frog-Jump/cpp-0403/main.cpp new file mode 100644 index 00000000..973f1f72 --- /dev/null +++ b/0001-0500/0403-Frog-Jump/cpp-0403/main.cpp @@ -0,0 +1,64 @@ +/// Source : https://leetcode.com/problems/frog-jump/ +/// Author : liuyubobobo +/// Time : 2021-04-28 + +#include +#include +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(n^2) +/// Space Complexity: O(n^2) +class Solution { +public: + bool canCross(vector& stones) { + + set stones_set; + for(int stone: stones) stones_set.insert(stone); + + if(!stones_set.count(0)) return false; + if(!stones_set.count(1)) return false; + + map, bool> dp; // {pos, steps} + return dfs(stones_set, 1, 1, stones.back(), dp); + } + +private: + bool dfs(const set& stones_set, int pos, int step, int end, + map, bool>& dp){ + + if(pos > end) return false; + if(pos == end) return true; + if(!stones_set.count(pos)) return false; + + if(dp.count({pos, step})) return dp[{pos, step}]; + + bool res = dfs(stones_set, pos + step + 1, step + 1, end, dp); + if(res) return dp[{pos, step}] = true; + + res = dfs(stones_set, pos + step, step, end, dp); + if(res) return dp[{pos, step}] = true; + + if(step - 1 > 0) + res = dfs(stones_set, pos + (step - 1), step - 1, end, dp); + return dp[{pos, step}] = res; + } +}; + + +int main() { + + vector stones1 = {0, 1, 3, 5, 6, 8, 12, 17}; + cout << Solution().canCross(stones1) << endl; + // true + + vector stones2 = {0, 1, 2, 3, 4, 8, 9, 11}; + cout << Solution().canCross(stones2) << endl; + // false; + + return 0; +} diff --git a/0001-0500/0404-Sum-of-Left-Leaves/cpp-0404/CMakeLists.txt b/0001-0500/0404-Sum-of-Left-Leaves/cpp-0404/CMakeLists.txt new file mode 100644 index 00000000..ae1497b2 --- /dev/null +++ b/0001-0500/0404-Sum-of-Left-Leaves/cpp-0404/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(cpp_0404) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0404 main.cpp) \ No newline at end of file diff --git a/0001-0500/0404-Sum-of-Left-Leaves/cpp-0404/main.cpp b/0001-0500/0404-Sum-of-Left-Leaves/cpp-0404/main.cpp new file mode 100644 index 00000000..9f72fab7 --- /dev/null +++ b/0001-0500/0404-Sum-of-Left-Leaves/cpp-0404/main.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/sum-of-left-leaves/ +/// Author : liuyubobobo +/// Time : 2019-04-22 + +#include + +using namespace std; + + +/// Recursion +/// Time Complexity: O(n) +/// Space Complexity: O(h) + +/// 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 { + +private: + int res = 0; + +public: + int sumOfLeftLeaves(TreeNode* root) { + + if(!root) return 0; + + dfs(root, false); + return res; + } + +private: + void dfs(TreeNode* node, bool isLeft){ + + if(!node->left && !node->right){ + if(isLeft) res += node->val; + return; + } + + if(node->left) dfs(node->left, true); + if(node->right) dfs(node->right, false); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0404-Sum-of-Left-Leaves/cpp-0404/main2.cpp b/0001-0500/0404-Sum-of-Left-Leaves/cpp-0404/main2.cpp new file mode 100644 index 00000000..0bac8334 --- /dev/null +++ b/0001-0500/0404-Sum-of-Left-Leaves/cpp-0404/main2.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/sum-of-left-leaves/ +/// Author : liuyubobobo +/// Time : 2019-04-22 + +#include + +using namespace std; + + +/// Recursion +/// Don't use class member variable +/// Time Complexity: O(n) +/// Space Complexity: O(h) + +/// 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: + int sumOfLeftLeaves(TreeNode* root) { + + if(!root) return 0; + + return dfs(root, false); + } + +private: + int dfs(TreeNode* node, bool isLeft){ + + if(!node->left && !node->right){ + if(isLeft) return node->val; + return 0; + } + + int res = 0; + if(node->left) res += dfs(node->left, true); + if(node->right) res += dfs(node->right, false); + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0405-Convert-a-Number-to-Hexadecimal/cpp-0405/CMakeLists.txt b/0001-0500/0405-Convert-a-Number-to-Hexadecimal/cpp-0405/CMakeLists.txt new file mode 100644 index 00000000..f2a8c16b --- /dev/null +++ b/0001-0500/0405-Convert-a-Number-to-Hexadecimal/cpp-0405/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0405) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0405 main.cpp) diff --git a/0001-0500/0405-Convert-a-Number-to-Hexadecimal/cpp-0405/main.cpp b/0001-0500/0405-Convert-a-Number-to-Hexadecimal/cpp-0405/main.cpp new file mode 100644 index 00000000..34b89ec0 --- /dev/null +++ b/0001-0500/0405-Convert-a-Number-to-Hexadecimal/cpp-0405/main.cpp @@ -0,0 +1,29 @@ +/// Source : https://leetcode.com/problems/convert-a-number-to-hexadecimal/ +/// Author : liuyubobobo +/// Time : 2021-10-01 + +#include +#include + +using namespace std; + + +/// Std +/// Time Complexity: O(log(num)) +/// Space Complexity: O(1) +class Solution { +public: + string toHex(int num) { + + stringstream ss; + + ss << hex << num; + return ss.str(); + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0406-Queue-Reconstruction-by-Height/cpp-0406/CMakeLists.txt b/0001-0500/0406-Queue-Reconstruction-by-Height/cpp-0406/CMakeLists.txt new file mode 100644 index 00000000..fd975cf4 --- /dev/null +++ b/0001-0500/0406-Queue-Reconstruction-by-Height/cpp-0406/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_0406) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0406 main.cpp) diff --git a/0001-0500/0406-Queue-Reconstruction-by-Height/cpp-0406/main.cpp b/0001-0500/0406-Queue-Reconstruction-by-Height/cpp-0406/main.cpp new file mode 100644 index 00000000..021c621e --- /dev/null +++ b/0001-0500/0406-Queue-Reconstruction-by-Height/cpp-0406/main.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/queue-reconstruction-by-height/ +/// Author : liuyubobobo +/// Time : 2022-06-29 + +#include +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(nlogn + n^2) +/// Space Complexity: O(n) +class Solution { +public: + vector> reconstructQueue(vector>& people) { + + sort(people.begin(), people.end(), + [](const vector& p1, const vector& p2){ + if(p1[0] != p2[0]) return p1[0] > p2[0]; + return p1[1] < p2[1]; + }); + + vector> res = {people[0]}; + for(int i = 1; i < people.size(); i ++){ + + int j = 0, cnt = 0; + for(; j < (int)res.size() && cnt < people[i][1]; j ++){ + if(res[j][0] >= people[i][0]) cnt ++; + } + + auto iter = res.begin() + j; + res.insert(iter, people[i]); + } + return res; + } +}; + + +void print_vec(const vector>& v){ + for(const vector& p: v) + cout << '(' << p[0] << ',' << p[1] << ')'; + cout << '\n'; +} + +int main() { + + vector> people1 = {{7, 0}, {4, 4}, {7, 1}, {5, 0}, {6, 1}, {5, 2}}; + print_vec(Solution().reconstructQueue(people1)); + + return 0; +} diff --git a/0001-0500/0407-Trapping-Rain-Water-II/cpp-0407/CMakeLists.txt b/0001-0500/0407-Trapping-Rain-Water-II/cpp-0407/CMakeLists.txt new file mode 100644 index 00000000..9f0676bf --- /dev/null +++ b/0001-0500/0407-Trapping-Rain-Water-II/cpp-0407/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0407) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0407 main.cpp) diff --git a/0001-0500/0407-Trapping-Rain-Water-II/cpp-0407/main.cpp b/0001-0500/0407-Trapping-Rain-Water-II/cpp-0407/main.cpp new file mode 100644 index 00000000..178cbead --- /dev/null +++ b/0001-0500/0407-Trapping-Rain-Water-II/cpp-0407/main.cpp @@ -0,0 +1,77 @@ +/// Source : https://leetcode.com/problems/trapping-rain-water-ii/ +/// Author : liuyubobobo +/// Time : 2021-11-03 + +#include +#include +#include + +using namespace std; + + +/// Using PQ +/// This solution is analysis is amazing: +/// https://leetcode.com/problems/trapping-rain-water-ii/discuss/89461/Java-solution-using-PriorityQueue +/// +/// Time Compelexity: O(R * C * log(R * C)) +/// Space Complexity: O(R * C) +class Solution { + +private: + const int dirs[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; + int R, C; + +public: + int trapRainWater(vector>& heightMap) { + + R = heightMap.size(), C = heightMap[0].size(); + + priority_queue, vector>, greater>> pq; // height, pos + vector visited(R * C, false); + for(int i = 0; i < R; i ++){ + pq.push({heightMap[i][0], i * C + 0}); + pq.push({heightMap[i][C - 1], i * C + C - 1}); + visited[i * C + 0] = visited[i * C + C - 1] = true; + } + for(int j = 1; j + 1 < C; j ++){ + pq.push({heightMap[0][j], j}); + pq.push({heightMap[R - 1][j], (R - 1) * C + j}); + visited[j] = visited[(R - 1) * C + j] = true; + } + + int res = 0; + while(!pq.empty()){ + int h = pq.top().first, pos = pq.top().second; + pq.pop(); + + int x = pos / C, y = pos % C; + res += max(0, h - heightMap[x][y]); + + for(int d = 0; d < 4; d ++){ + int nx = x + dirs[d][0], ny = y + dirs[d][1]; + if(in_area(nx, ny) && !visited[nx * C + ny]){ + pq.push({max(h, heightMap[nx][ny]), nx * C + ny}); + visited[nx * C + ny] = true; + } + } + } + return res; + } + +private: + bool in_area(int x, int y){ + return 0 <= x && x < R && 0 <= y && y < C; + } +}; + + +int main() { + + vector> height1 = { + {12,13,1,12},{13,4,13,12},{13,8,10,12},{12,13,12,12},{13,13,13,13} + }; + cout << Solution().trapRainWater(height1) << endl; + // 14 + + return 0; +} diff --git a/0001-0500/0410-Split-Array-Largest-Sum/cpp-0410/CMakeLists.txt b/0001-0500/0410-Split-Array-Largest-Sum/cpp-0410/CMakeLists.txt new file mode 100644 index 00000000..218594f1 --- /dev/null +++ b/0001-0500/0410-Split-Array-Largest-Sum/cpp-0410/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(cpp_0410) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0410 main4.cpp) \ No newline at end of file diff --git a/0001-0500/0410-Split-Array-Largest-Sum/cpp-0410/main.cpp b/0001-0500/0410-Split-Array-Largest-Sum/cpp-0410/main.cpp new file mode 100644 index 00000000..3069a0bb --- /dev/null +++ b/0001-0500/0410-Split-Array-Largest-Sum/cpp-0410/main.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/split-array-largest-sum/ +/// Author : liuyubobobo +/// Time : 2020-05-11 + +#include +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(n * n * m) +/// Space Complexity: O(n * m) +class Solution { + +private: + int n; + +public: + int splitArray(vector& nums, int m) { + + n = nums.size(); + vector pre(n + 1, 0); + for(int i = 0; i < n; i ++) + pre[i + 1] = pre[i] + nums[i]; + + vector> dp(m, vector(n, -1)); + return dfs(nums, m - 1, 0, pre, dp); + } + +private: + int dfs(const vector& nums, int m, int start, + const vector& pre, vector>& dp){ + + if(dp[m][start] != -1) return dp[m][start]; + if(m == 0) return dp[m][start] = pre[n] - pre[start]; + + int res = INT_MAX; + for(int i = start; i + m < n; i ++) + res =min(res, max((int)(pre[i + 1] - pre[start]), dfs(nums, m - 1, i + 1, pre, dp))); + return dp[m][start] = res; + } +}; + + +int main() { + + vector nums = {7, 2, 5, 10, 8}; + cout << Solution().splitArray(nums, 2) << endl; + // 18 + + return 0; +} diff --git a/0001-0500/0410-Split-Array-Largest-Sum/cpp-0410/main2.cpp b/0001-0500/0410-Split-Array-Largest-Sum/cpp-0410/main2.cpp new file mode 100644 index 00000000..285f2c5a --- /dev/null +++ b/0001-0500/0410-Split-Array-Largest-Sum/cpp-0410/main2.cpp @@ -0,0 +1,45 @@ +/// Source : https://leetcode.com/problems/split-array-largest-sum/ +/// Author : liuyubobobo +/// Time : 2020-05-11 + +#include +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(n * n * m) +/// Space Complexity: O(n * m) +class Solution { + +public: + int splitArray(vector& nums, int m) { + + int n = nums.size(); + vector pre(n + 1, 0); + for(int i = 0; i < n; i ++) + pre[i + 1] = pre[i] + nums[i]; + + vector> dp(m, vector(n, INT_MAX)); + for(int start = 0; start < n; start ++) + dp[0][start] = pre[n] - pre[start]; + + for(int k = 1; k < m; k ++) + for(int start = 0; start < n; start ++) + for(int i = start; i + k < n; i ++) + dp[k][start] = min(dp[k][start], max((int)(pre[i + 1] - pre[start]), dp[k - 1][i + 1])); + return dp[m - 1][0]; + } +}; + + +int main() { + + vector nums = {7, 2, 5, 10, 8}; + cout << Solution().splitArray(nums, 2) << endl; + // 18 + + return 0; +} diff --git a/0001-0500/0410-Split-Array-Largest-Sum/cpp-0410/main3.cpp b/0001-0500/0410-Split-Array-Largest-Sum/cpp-0410/main3.cpp new file mode 100644 index 00000000..4f64ae71 --- /dev/null +++ b/0001-0500/0410-Split-Array-Largest-Sum/cpp-0410/main3.cpp @@ -0,0 +1,48 @@ +/// Source : https://leetcode.com/problems/split-array-largest-sum/ +/// Author : liuyubobobo +/// Time : 2020-05-11 + +#include +#include +#include + +using namespace std; + + +/// Dynamic Programming with Space Optimization +/// Time Complexity: O(n * n * m) +/// Space Complexity: O(n) +class Solution { + +public: + int splitArray(vector& nums, int m) { + + int n = nums.size(); + vector pre(n + 1, 0); + for(int i = 0; i < n; i ++) + pre[i + 1] = pre[i] + nums[i]; + + vector dp(n); + for(int start = 0; start < n; start ++) + dp[start] = pre[n] - pre[start]; + + for(int k = 1; k < m; k ++){ + vector tdp(n, INT_MAX); + for(int start = 0; start < n; start ++) + for(int i = start; i + k < n; i ++) + tdp[start] = min(tdp[start], max((int)(pre[i + 1] - pre[start]), dp[i + 1])); + dp = tdp; + } + return dp[0]; + } +}; + + +int main() { + + vector nums = {7, 2, 5, 10, 8}; + cout << Solution().splitArray(nums, 2) << endl; + // 18 + + return 0; +} diff --git a/0001-0500/0410-Split-Array-Largest-Sum/cpp-0410/main4.cpp b/0001-0500/0410-Split-Array-Largest-Sum/cpp-0410/main4.cpp new file mode 100644 index 00000000..fe6c133b --- /dev/null +++ b/0001-0500/0410-Split-Array-Largest-Sum/cpp-0410/main4.cpp @@ -0,0 +1,61 @@ +/// Source : https://leetcode.com/problems/split-array-largest-sum/ +/// Author : liuyubobobo +/// Time : 2020-05-11 + +#include +#include +#include + +using namespace std; + + +/// Binary Search + Greedy +/// Time Complexity: O(nlog(sum)) +/// Space Complexity: O(n) +class Solution { + +public: + int splitArray(vector& nums, int m) { + + long long l = 1ll, r = 0ll; + for(int num: nums) r += num; + + while(l < r){ + long long mid = (l + r) / 2; + if(ok(nums, m, mid)) r = mid; + else l = mid + 1; + } + return l; + } + +private: + bool ok(const vector& nums, int m, long long len){ + + if(*max_element(nums.begin(), nums.end()) > len) return false; + + int res = 1; + long long cur = 0ll; + for(int e: nums){ + if(cur + e > len){ + res ++; + cur = e; + } + else cur += e; + } + return res <= m; + } +}; + + +int main() { + + vector nums1 = {7, 2, 5, 10, 8}; + cout << Solution().splitArray(nums1, 2) << endl; + // 18 + + vector nums2 = {1,2147483647}; + cout << Solution().splitArray(nums2, 2) << endl; + // 2147483647 + + return 0; +} diff --git a/0001-0500/0412-Fizz-Buzz/cpp-0412/CMakeLists.txt b/0001-0500/0412-Fizz-Buzz/cpp-0412/CMakeLists.txt new file mode 100644 index 00000000..8a9575cc --- /dev/null +++ b/0001-0500/0412-Fizz-Buzz/cpp-0412/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0412) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main3.cpp) +add_executable(cpp_0412 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0412-Fizz-Buzz/cpp-0412/main.cpp b/0001-0500/0412-Fizz-Buzz/cpp-0412/main.cpp new file mode 100644 index 00000000..a3004afa --- /dev/null +++ b/0001-0500/0412-Fizz-Buzz/cpp-0412/main.cpp @@ -0,0 +1,36 @@ +/// Source : https://leetcode.com/problems/fizz-buzz/description/ +/// Author : liuyubobobo +/// Time : 2018-09-23 + +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + vector fizzBuzz(int n) { + + vector ret; + for(int i = 1; i <= n; i ++) + if(i % 15 == 0) + ret.push_back("FizzBuzz"); + else if(i % 3 == 0) + ret.push_back("Fizz"); + else if(i % 5 == 0) + ret.push_back("Buzz"); + else + ret.push_back(to_string(i)); + return ret; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0412-Fizz-Buzz/cpp-0412/main2.cpp b/0001-0500/0412-Fizz-Buzz/cpp-0412/main2.cpp new file mode 100644 index 00000000..22e67dc7 --- /dev/null +++ b/0001-0500/0412-Fizz-Buzz/cpp-0412/main2.cpp @@ -0,0 +1,39 @@ +/// Source : https://leetcode.com/problems/fizz-buzz/description/ +/// Author : liuyubobobo +/// Time : 2018-09-23 + +#include +#include + +using namespace std; + + +/// Using String Concatenation +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + vector fizzBuzz(int n) { + + vector ret; + for(int i = 1; i <= n; i ++){ + string s = ""; + if(i % 3 == 0) + s += "Fizz"; + if(i % 5 == 0) + s += "Buzz"; + + if(s == "") + s = to_string(i); + + ret.push_back(s); + } + return ret; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0412-Fizz-Buzz/cpp-0412/main3.cpp b/0001-0500/0412-Fizz-Buzz/cpp-0412/main3.cpp new file mode 100644 index 00000000..e8b67396 --- /dev/null +++ b/0001-0500/0412-Fizz-Buzz/cpp-0412/main3.cpp @@ -0,0 +1,41 @@ +/// Source : https://leetcode.com/problems/fizz-buzz/description/ +/// Author : liuyubobobo +/// Time : 2018-09-23 + +#include +#include +#include + +using namespace std; + + +/// Using Map to make the logic more clear +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + vector fizzBuzz(int n) { + + map map = {{3, "Fizz"}, {5, "Buzz"}}; + + vector ret; + for(int i = 1; i <= n; i ++){ + string s = ""; + for(const pair& p: map) + if(i % p.first == 0) + s += p.second; + + if(s == "") + s = to_string(i); + + ret.push_back(s); + } + return ret; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0413-Arithmetic-Slices/cpp-0413/CMakeLists.txt b/0001-0500/0413-Arithmetic-Slices/cpp-0413/CMakeLists.txt new file mode 100644 index 00000000..349fb7e8 --- /dev/null +++ b/0001-0500/0413-Arithmetic-Slices/cpp-0413/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0413) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0413 main.cpp) \ No newline at end of file diff --git a/0001-0500/0413-Arithmetic-Slices/cpp-0413/main.cpp b/0001-0500/0413-Arithmetic-Slices/cpp-0413/main.cpp new file mode 100644 index 00000000..b8d0084b --- /dev/null +++ b/0001-0500/0413-Arithmetic-Slices/cpp-0413/main.cpp @@ -0,0 +1,29 @@ +#include +#include +#include + +using namespace std; + + +class Solution { +public: + int numberOfArithmeticSlices(vector& A) { + + int n = A.size(); + if(n <= 2) return 0; + + vector dp(n, 0); + dp[2] = A[2] - A[1] == A[1] - A[0]; + + for(int i = 3; i < n; i ++) + if(A[i] - A[i - 1] == A[i - 1] - A[i - 2]) + dp[i] = 1 + dp[i - 1]; + return accumulate(dp.begin(), dp.end(), 0); + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0414-Third-Maximum-Number/cpp-0414/CMakeLists.txt b/0001-0500/0414-Third-Maximum-Number/cpp-0414/CMakeLists.txt new file mode 100644 index 00000000..5b31158d --- /dev/null +++ b/0001-0500/0414-Third-Maximum-Number/cpp-0414/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(cpp_0414) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0414 main.cpp) \ No newline at end of file diff --git a/0001-0500/0414-Third-Maximum-Number/cpp-0414/main.cpp b/0001-0500/0414-Third-Maximum-Number/cpp-0414/main.cpp new file mode 100644 index 00000000..25cf34cb --- /dev/null +++ b/0001-0500/0414-Third-Maximum-Number/cpp-0414/main.cpp @@ -0,0 +1,55 @@ +/// Source : https://leetcode.com/problems/third-maximum-number/ +/// Author : liuyubobobo +/// Time : 2019-09-06 + +#include +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int thirdMax(vector& nums) { + + int count = 0, maxv = INT_MIN; + int a = INT_MIN, b = INT_MIN, c = INT_MIN; + for(int e: nums){ + if(count == 0) a = e, count ++; + else if(count == 1 && e != a) b = e, count ++; + else if(count == 2 && e != a && e != b) c = e, count ++; + else if(count == 3 && e > c && e != a && e != b) c = e; + + if(b < c) swap(b, c); + if(a < b) swap(a, b); + + maxv = max(maxv, e); + } + return count < 3 ? maxv : c; + } +}; + + +int main() { + + vector nums1 = {3, 2, 1}; + cout << Solution().thirdMax(nums1) << endl; + // 1 + + vector nums2 = {2, 2, 3, 1}; + cout << Solution().thirdMax(nums2) << endl; + // 1 + + vector nums3 = {1, 2}; + cout << Solution().thirdMax(nums3) << endl; + // 2 + + vector nums4 = {1, -2147483648, 2}; + cout << Solution().thirdMax(nums4) << endl; + // -2147483648 + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0415-Add-Strings/cpp-0415/CMakeLists.txt b/0001-0500/0415-Add-Strings/cpp-0415/CMakeLists.txt new file mode 100644 index 00000000..b70304af --- /dev/null +++ b/0001-0500/0415-Add-Strings/cpp-0415/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0415) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0415 main.cpp) diff --git a/0001-0500/0415-Add-Strings/cpp-0415/main.cpp b/0001-0500/0415-Add-Strings/cpp-0415/main.cpp new file mode 100644 index 00000000..864cc1dc --- /dev/null +++ b/0001-0500/0415-Add-Strings/cpp-0415/main.cpp @@ -0,0 +1,43 @@ +/// Source : https://leetcode.com/problems/add-strings/ +/// Author : liuyubobobo +/// Time : 2021-08-09 + +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + string addStrings(string num1, string num2) { + + reverse(num1.begin(), num1.end()); + reverse(num2.begin(), num2.end()); + + if(num1.size() < num2.size()) swap(num1, num2); + while(num2.size() <= num1.size()) num2 += "0"; + + string res = ""; + int carry = 0; + for(int i = 0; i < num1.size(); i ++){ + int x = (num1[i] - '0') + (num2[i] - '0') + carry; + res += string(1, '0' + x % 10); + carry = x / 10; + } + if(carry) res += "1"; + + reverse(res.begin(), res.end()); + return res == "" ? "0" : res; + } +}; + +int main() { + + cout << Solution().addStrings("11", "123") << endl; + // 134 + + return 0; +} diff --git a/0416-Partition-Equal-Subset-Sum/cpp-0416/CMakeLists.txt b/0001-0500/0416-Partition-Equal-Subset-Sum/cpp-0416/CMakeLists.txt similarity index 100% rename from 0416-Partition-Equal-Subset-Sum/cpp-0416/CMakeLists.txt rename to 0001-0500/0416-Partition-Equal-Subset-Sum/cpp-0416/CMakeLists.txt diff --git a/0416-Partition-Equal-Subset-Sum/cpp-0416/main.cpp b/0001-0500/0416-Partition-Equal-Subset-Sum/cpp-0416/main.cpp similarity index 100% rename from 0416-Partition-Equal-Subset-Sum/cpp-0416/main.cpp rename to 0001-0500/0416-Partition-Equal-Subset-Sum/cpp-0416/main.cpp diff --git a/0416-Partition-Equal-Subset-Sum/cpp-0416/main2.cpp b/0001-0500/0416-Partition-Equal-Subset-Sum/cpp-0416/main2.cpp similarity index 100% rename from 0416-Partition-Equal-Subset-Sum/cpp-0416/main2.cpp rename to 0001-0500/0416-Partition-Equal-Subset-Sum/cpp-0416/main2.cpp diff --git a/0416-Partition-Equal-Subset-Sum/java-0416/src/Solution1.java b/0001-0500/0416-Partition-Equal-Subset-Sum/java-0416/src/Solution1.java similarity index 100% rename from 0416-Partition-Equal-Subset-Sum/java-0416/src/Solution1.java rename to 0001-0500/0416-Partition-Equal-Subset-Sum/java-0416/src/Solution1.java diff --git a/0416-Partition-Equal-Subset-Sum/java-0416/src/Solution2.java b/0001-0500/0416-Partition-Equal-Subset-Sum/java-0416/src/Solution2.java similarity index 100% rename from 0416-Partition-Equal-Subset-Sum/java-0416/src/Solution2.java rename to 0001-0500/0416-Partition-Equal-Subset-Sum/java-0416/src/Solution2.java diff --git a/0001-0500/0417-Pacific-Atlantic-Water-Flow/cpp-0417/CMakeLists.txt b/0001-0500/0417-Pacific-Atlantic-Water-Flow/cpp-0417/CMakeLists.txt new file mode 100644 index 00000000..c5dc18c1 --- /dev/null +++ b/0001-0500/0417-Pacific-Atlantic-Water-Flow/cpp-0417/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_0417) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0417 main2.cpp) diff --git a/0001-0500/0417-Pacific-Atlantic-Water-Flow/cpp-0417/main.cpp b/0001-0500/0417-Pacific-Atlantic-Water-Flow/cpp-0417/main.cpp new file mode 100644 index 00000000..9f399318 --- /dev/null +++ b/0001-0500/0417-Pacific-Atlantic-Water-Flow/cpp-0417/main.cpp @@ -0,0 +1,63 @@ +/// Source : https://leetcode.com/problems/pacific-atlantic-water-flow/ +/// Author : liuyubobobo +/// Time : 2022-05-09 + +#include +#include + +using namespace std; + + +/// DFS from outside to inside +/// Time Complexity: O(R * C) +/// Space Complexity: O(R * C) +class Solution { + +private: + const int dirs[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; + int R, C; + +public: + vector> pacificAtlantic(vector>& heights) { + + R = heights.size(), C = heights[0].size(); + + vector> pacific(R, vector(C, false)); + for(int j = 0; j < C; j ++) + if(!pacific[0][j]) dfs(heights, 0, j, pacific); + for(int i = 0; i < R; i ++) + if(!pacific[i][0]) dfs(heights, i, 0, pacific); + + vector> atlantic(R, vector(C, false)); + for(int i = 0; i < R; i ++) + if(!atlantic[i][C - 1]) dfs(heights, i, C - 1, atlantic); + for(int j = 0; j < C; j ++) dfs(heights, R - 1, j, atlantic); + + vector> res; + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++) + if(pacific[i][j] && atlantic[i][j]) res.push_back({i, j}); + return res; + } + +private: + void dfs(const vector>& H, int x, int y, vector>& visited){ + + visited[x][y] = true; + for(int d = 0; d < 4; d ++){ + int nx = x + dirs[d][0], ny = y + dirs[d][1]; + if(in_area(nx, ny) && !visited[nx][ny] && H[x][y] <= H[nx][ny]) + dfs(H, nx, ny, visited); + } + } + + bool in_area(int x, int y){ + return 0 <= x && x < R && 0 <= y && y < C; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0417-Pacific-Atlantic-Water-Flow/cpp-0417/main2.cpp b/0001-0500/0417-Pacific-Atlantic-Water-Flow/cpp-0417/main2.cpp new file mode 100644 index 00000000..bc574188 --- /dev/null +++ b/0001-0500/0417-Pacific-Atlantic-Water-Flow/cpp-0417/main2.cpp @@ -0,0 +1,165 @@ +/// Source : https://leetcode.com/problems/pacific-atlantic-water-flow/ +/// Author : liuyubobobo +/// Time : 2022-08-19 + +#include +#include +#include + +using namespace std; + + +/// DFS from inside to outside +/// Shrink vertex to remove all the cycles from the underlying search graph +/// Time Complexity: O(R * C) +/// Space Complexity: O(R * C) +class UF{ + +private: + vector parent; + +public: + UF(int n) : parent(n){ + for(int i = 0 ; i < n ; i ++) + parent[i] = i; + } + + int find(int p){ + if(p != parent[p]) + parent[p] = find(parent[p]); + return parent[p]; + } + + bool is_connected(int p, int q){ + return find(p) == find(q); + } + + void union_elements(int p, int q){ + + int p_root = find(p), q_root = find(q); + + if(p_root == q_root) return; + + parent[p_root] = q_root; + } +}; + +class Solution { + +private: + const int dirs[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; + int R, C; + +public: + vector> pacificAtlantic(vector>& heights) { + + R = heights.size(), C = heights[0].size(); + + // uf 有 R * C 个节点。 + UF uf(R * C); + vector> visited(R, vector(C, false)); + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++){ + // 缩点 + if(!visited[i][j]){ + vector cc; + dfs_cc(heights, i, j, visited, cc); + for(int i = 1; i < cc.size(); i ++) + uf.union_elements(cc[0], cc[i]); + } + } + + // 根据缩好的点,创建新图,这张图是 DAG + // 注意,这张图有 R * C + 2 个节点,索引 R * C 对应 pacific,索引 R * C + 1 对应 atlantic + vector> g(R * C + 2); + for(int x = 0; x < R; x ++) + for(int y = 0; y < C; y ++){ + + // u 是 [x, y] 缩点后对应的点编号 + int u = uf.find(x * C + y); + for(int d = 0; d < 4; d ++){ + int nx = x + dirs[d][0], ny = y + dirs[d][1]; + if(!in_area(nx, ny)) continue; + + // v 是 [nx, ny] 缩点后对应的点编号 + int v = uf.find(nx * C + ny); + if(u == v) continue; + + // 注意,此时 height 的比较,可以扔掉 = 了, + // 因为 u 和 v 不是缩点后的一个节点,所以高度肯定不等 + if(heights[x][y] > heights[nx][ny]) g[u].insert(v); + } + + if(x == 0 || y == 0) g[u].insert(R * C); + if(x == R - 1 || y == C - 1) g[u].insert(R * C + 1); + } + + // 现在,可以在 g 这张新图上,做记忆化搜索了。 + // 因为这张图上边的方向已经代表了从高的地方走向低的地方,所以不需要再使用 height 数组了。 + // 但是,因为建图的方式,我们的搜索是从高向地进行的。 + vector pacific(R * C + 2, -1), atlantic(R * C + 2, -1); + for(int u = 0; u < R * C; u ++){ + if(pacific[u] == -1) dfs(g, u, pacific, atlantic); + } + + vector> res; + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++){ + int u = uf.find(i * C + j); + if(pacific[u] == 1 && atlantic[u] == 1) + res.push_back({i, j}); + } + return res; + } + +private: + void dfs_cc(const vector>& H, int x, int y, + vector>& visited, vector& cc){ + + visited[x][y] = true; + cc.push_back(x * C + y); + + for(int d = 0; d < 4; d ++){ + int nx = x + dirs[d][0], ny = y + dirs[d][1]; + if(in_area(nx, ny) && !visited[nx][ny] && H[x][y] == H[nx][ny]) + dfs_cc(H, nx, ny, visited, cc); + } + } + + void dfs(const vector>& g, int u, + vector& pacific, vector& atlantic){ + + if(u == R * C) pacific[u] = 1; + if(u == R * C + 1) atlantic[u] = 1; + + if(pacific[u] != -1) return; + + for(int v: g[u]){ + dfs(g, v, pacific, atlantic); + if(pacific[v] == 1) pacific[u] = 1; + if(atlantic[v] == 1) atlantic[u] = 1; + } + + if(pacific[u] != 1) pacific[u] = 0; + if(atlantic[u] != 1) atlantic[u] = 0; + } + + bool in_area(int x, int y){ + return 0 <= x && x < R && 0 <= y && y < C; + } +}; + + +int main() { + + vector> heights = { + {1,2,2,3,5}, + {3,2,3,4,4}, + {2,4,5,3,1}, + {6,7,1,4,5}, + {5,1,1,2,4} + }; + Solution().pacificAtlantic(heights); + + return 0; +} diff --git a/0001-0500/0417-Pacific-Atlantic-Water-Flow/java-0417/src/Solution.java b/0001-0500/0417-Pacific-Atlantic-Water-Flow/java-0417/src/Solution.java new file mode 100644 index 00000000..7a164d36 --- /dev/null +++ b/0001-0500/0417-Pacific-Atlantic-Water-Flow/java-0417/src/Solution.java @@ -0,0 +1,79 @@ +/// Source : https://leetcode.com/problems/two-sum/description/ +/// Author : liuyubobobo +/// Time : 2018-06-01 + +import java.util.List; +import java.util.ArrayList; + +/// Floodfill +/// Time Complexity: O(m*n) +/// Space Complexity: O(m*n) +class Solution { + + private int n, m; + private boolean[][] pacific, atlantic; + private int[][] d = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; + + public List pacificAtlantic(int[][] matrix) { + + ArrayList res = new ArrayList<>(); + + n = matrix.length; + if(n == 0) + return res; + m = matrix[0].length; + + pacific = new boolean[n][m]; + atlantic = new boolean[n][m]; + + for(int i = 0 ; i < n ; i ++){ + dfs(matrix, pacific, i, 0); + dfs(matrix, atlantic, i, m - 1); + } + + for(int j = 0 ; j < m ; j ++){ + dfs(matrix, pacific, 0, j); + dfs(matrix, atlantic, n - 1, j); + } + + for(int i = 0 ; i < n ; i ++) + for(int j = 0 ; j < m ; j ++) + if(pacific[i][j] && atlantic[i][j]) + res.add(new int[]{i, j}); + return res; + } + + private void dfs(int[][] matrix, boolean[][] visited, int x, int y){ + + visited[x][y] = true; + for(int i = 0 ; i < 4 ; i ++){ + int newX = x + d[i][0]; + int newY = y + d[i][1]; + if(inArea(newX, newY) && !visited[newX][newY] && matrix[newX][newY] >= matrix[x][y]) + dfs(matrix, visited, newX, newY); + } + } + + private boolean inArea(int x, int y){ + return x >= 0 && x < n && y >= 0 && y < m; + } + + public static void printList(List list){ + for(int[] e: list) + System.out.print("[ " + e[0] + " , " + e[1] + " ] "); + System.out.println(); + } + + public static void main(String[] args){ + + int[][] matrix = new int[][]{ + {1, 2, 2, 3, 5}, + {3, 2, 3, 4, 4}, + {2, 4, 5, 3, 1}, + {6, 7, 1, 4, 5}, + {5, 1, 1, 2, 4} + }; + List res = (new Solution()).pacificAtlantic(matrix); + printList(res); + } +} diff --git a/0001-0500/0419-Battleships-in-a-Board/cpp-0419/CMakeLists.txt b/0001-0500/0419-Battleships-in-a-Board/cpp-0419/CMakeLists.txt new file mode 100644 index 00000000..8ecb6a4d --- /dev/null +++ b/0001-0500/0419-Battleships-in-a-Board/cpp-0419/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0419) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0419 main.cpp) diff --git a/0001-0500/0419-Battleships-in-a-Board/cpp-0419/main.cpp b/0001-0500/0419-Battleships-in-a-Board/cpp-0419/main.cpp new file mode 100644 index 00000000..b603a970 --- /dev/null +++ b/0001-0500/0419-Battleships-in-a-Board/cpp-0419/main.cpp @@ -0,0 +1,39 @@ +/// Source : https://leetcode.com/problems/battleships-in-a-board/ +/// Author : liuyubobobo +/// Time : 2021-12-17 + +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(n^3) +/// Space Complexity: O(1) +class Solution { +public: + int countBattleships(vector>& board) { + + int R = board.size(), C = board[0].size(), res = 0; + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++){ + if(board[i][j] == '.') continue; + + int tres = (i + 1 < R && board[i + 1][j] == 'X') + (j + 1 < C && board[i][j + 1] == 'X'); + if(tres == 0) tres = 1; + res += tres; + + for(int k = j + 1; k < C && board[i][k] == 'X'; k ++) board[i][k] = '.'; + for(int k = i + 1; k < R && board[k][j] == 'X'; k ++) board[k][j] = '.'; + board[i][j] = '.'; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0420-Strong-Password-Checker/cpp-0420/CMakeLists.txt b/0001-0500/0420-Strong-Password-Checker/cpp-0420/CMakeLists.txt new file mode 100644 index 00000000..6581d524 --- /dev/null +++ b/0001-0500/0420-Strong-Password-Checker/cpp-0420/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_0420) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0420 main.cpp) diff --git a/0001-0500/0420-Strong-Password-Checker/cpp-0420/main.cpp b/0001-0500/0420-Strong-Password-Checker/cpp-0420/main.cpp new file mode 100644 index 00000000..624e4036 --- /dev/null +++ b/0001-0500/0420-Strong-Password-Checker/cpp-0420/main.cpp @@ -0,0 +1,138 @@ +/// Source : https://leetcode.com/problems/strong-password-checker/ +/// Author : liuyubobobo +/// Time : 2022-04-30 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(|s|) +/// Space Compelxity: O(|s|) +class Solution { +public: + int strongPasswordChecker(string s) { + + int lower = 0, upper = 0, digit = 0, other = 0; + for(char c: s){ + if(islower(c)) lower ++; + else if(isupper(c)) upper ++; + else if(isdigit(c)) digit ++; + else other ++; + } + + priority_queue pq; + for(int start = 0, i = 1; i <= s.size(); i ++) + if(i == s.size() || s[start] != s[i]){ + if(i - start >= 3) pq.push(i - start); + start = i; + } + + int need_change = !lower + !upper + !digit; + int len = s.size(); + if(len < 6){ + int res = 0; + while(!pq.empty() && need_change){ + assert(pq.top() / 3 == 1); + res ++; + pq.pop(); need_change --; + len ++; + } + + res += pq.size(); len += pq.size(); + res += need_change; len += need_change; + res += max(6 - len, 0); + return res; + } + + if(len <= 20){ + return for20(pq, need_change); + } + + // len > 20 + vector v; + while(!pq.empty()) v.push_back(pq.top()), pq.pop(); + sort(v.begin(), v.end(), [](int a, int b){ + return a % 3 < b % 3; + }); + + int res = 0; + for(int i = 0; i < v.size() && len > 20; i ++){ + if(v[i] % 3 == 0){ + len --; v[i] --; res ++; + } + else if(v[i] % 3 == 1){ + len --; v[i] --; res ++; + if(len <= 20) break; + len --; v[i] --; res ++; + } + } + + for(int i = 0; i < v.size() && len > 20; i ++){ + while(v[i] > 5 && len > 20){ + int t = min(len - 20, 3); + v[i] -= t; len -= t; res += t; + } + } + + if(len == 20){ + for(int e: v) pq.push(e); + return res + for20(pq, need_change); + } + + for(int i = 0; i < v.size() && len > 20; i ++){ + int t = min(len - 20, v[i] - 2); + v[i] -= t; len -= t; res += t; + } + + if(len == 20){ + for(int e: v) pq.push(e); + return res + for20(pq, need_change); + } + + return max(len - 20, 0) + res + need_change; + } + +private: + int for20(priority_queue& pq, int need_change){ + int res = 0; + while(!pq.empty() && need_change){ + int cur = pq.top(); pq.pop(); + res ++, need_change --; + cur -= 3; + if(cur >= 3) pq.push(cur); + } + + if(need_change) res += need_change; + else{ + while(!pq.empty()){ + int cur = pq.top(); pq.pop(); + res += cur / 3; + } + } + return res; + } +}; + + +int main() { + + cout << Solution().strongPasswordChecker("a") << '\n'; + // 5 + + cout << Solution().strongPasswordChecker("aA1") << '\n'; + // 3 + + cout << Solution().strongPasswordChecker("1337C0d3") << '\n'; + // 0 + + cout << Solution().strongPasswordChecker("ABABABABABABABABABAB1") << '\n'; + // 2 + + return 0; +} diff --git a/0001-0500/0421-Maximum-XOR-of-Two-Numbers-in-an-Array/cpp-0421/CMakeLists.txt b/0001-0500/0421-Maximum-XOR-of-Two-Numbers-in-an-Array/cpp-0421/CMakeLists.txt new file mode 100644 index 00000000..f6569f48 --- /dev/null +++ b/0001-0500/0421-Maximum-XOR-of-Two-Numbers-in-an-Array/cpp-0421/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0421) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0421 main.cpp) \ No newline at end of file diff --git a/0001-0500/0421-Maximum-XOR-of-Two-Numbers-in-an-Array/cpp-0421/main.cpp b/0001-0500/0421-Maximum-XOR-of-Two-Numbers-in-an-Array/cpp-0421/main.cpp new file mode 100644 index 00000000..2592416d --- /dev/null +++ b/0001-0500/0421-Maximum-XOR-of-Two-Numbers-in-an-Array/cpp-0421/main.cpp @@ -0,0 +1,95 @@ +/// Source : https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array/ +/// Author : liuyubobobo +/// Time : 2021-05-16 + +#include +#include + +using namespace std; + + +/// Trie +/// Time Complexity: O(nlog(max_num) +/// Space Complexity: O(n * log(max_num)) +class Trie{ + +private: + class Node{ + public: + Node* next[2]; + Node(){ + next[0] = next[1] = nullptr; + }; + }; + + Node* root; + +public: + Trie(){ + root = new Node(); + } + + void add(const vector& nums){ + + Node* pre = root; + for(int e: nums){ + if(!pre->next[e]) + pre->next[e] = new Node(); + pre = pre->next[e]; + } + } + + int query(int num, const vector& nums){ + + Node* pre = root; + int x = 0; + for(int e: nums){ + if(pre->next[1 - e]) + x = x * 2 + (1 - e), pre = pre->next[1 - e]; + else + x = x * 2 + e, pre = pre->next[e]; + } + return num^x; + } +}; + +class Solution { + +public: + int findMaximumXOR(vector& nums) { + + int maxv = *max_element(nums.begin(), nums.end()); + int B = 0; + while(maxv) B ++, maxv >>= 1; + + Trie trie; + int res = 0; + for(int num: nums){ + + vector numb = get_binary(num, B); + trie.add(numb); + res = max(res, trie.query(num, numb)); + } + return res; + } + +private: + vector get_binary(int num, int B){ + + vector res(B); + for(int i = 0; i < B; i ++) + res[i] = num & 1, num >>= 1; + reverse(res.begin(), res.end()); + return res; + } +}; + + +int main() { + + vector nums1 = {3, 10, 5, 25, 2, 8}; + cout << Solution().findMaximumXOR(nums1) << endl; + // 28 + + return 0; +} diff --git a/0001-0500/0422-Valid-Word-Square/cpp-0422/CMakeLists.txt b/0001-0500/0422-Valid-Word-Square/cpp-0422/CMakeLists.txt new file mode 100644 index 00000000..aa64cf96 --- /dev/null +++ b/0001-0500/0422-Valid-Word-Square/cpp-0422/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_0422) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_0422 main.cpp) diff --git a/0001-0500/0422-Valid-Word-Square/cpp-0422/main.cpp b/0001-0500/0422-Valid-Word-Square/cpp-0422/main.cpp new file mode 100644 index 00000000..8a29dca5 --- /dev/null +++ b/0001-0500/0422-Valid-Word-Square/cpp-0422/main.cpp @@ -0,0 +1,32 @@ +/// Source : https://leetcode.com/problems/valid-word-square/description/ +/// Author : liuyubobobo +/// Time : 2023-03-01 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(R * C) +/// Space Complexity: O(1) +class Solution { +public: + bool validWordSquare(vector& words) { + + int R = words.size(); + for(int i = 0; i < R; i++) + for(int j = 0; j < words[i].size(); j++){ + if(j >= R || i >= words[j].size()) return false; + if(words[i][j] != words[j][i]) return false; + } + return true; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0423-Reconstruct-Original-Digits-from-English/cpp-0423/CMakeLists.txt b/0001-0500/0423-Reconstruct-Original-Digits-from-English/cpp-0423/CMakeLists.txt new file mode 100644 index 00000000..f119f8aa --- /dev/null +++ b/0001-0500/0423-Reconstruct-Original-Digits-from-English/cpp-0423/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(cpp_0423) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(cpp_0423 main.cpp) \ No newline at end of file diff --git a/0001-0500/0423-Reconstruct-Original-Digits-from-English/cpp-0423/main.cpp b/0001-0500/0423-Reconstruct-Original-Digits-from-English/cpp-0423/main.cpp new file mode 100644 index 00000000..b0fbf555 --- /dev/null +++ b/0001-0500/0423-Reconstruct-Original-Digits-from-English/cpp-0423/main.cpp @@ -0,0 +1,58 @@ +/// Source : https://leetcode.com/problems/reconstruct-original-digits-from-english/ +/// Author : liuyubobobo +/// Time : 2019-02-14 + +#include +#include +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + string originalDigits(string s) { + + vector freq(26); + for(char c: s) + freq[c - 'a'] ++; + + string res = ""; + + res += check(freq, "zero", 'z', '0'); + res += check(freq, "two", 'w', '2'); + res += check(freq, "four", 'u', '4'); + res += check(freq, "six", 'x', '6'); + res += check(freq, "eight", 'g', '8'); + + res += check(freq, "one", 'o', '1'); + res += check(freq, "three", 'r', '3'); + res += check(freq, "five", 'f', '5'); + res += check(freq, "seven", 'v', '7'); + res += check(freq, "nine", 'i', '9'); + + sort(res.begin(), res.end()); + return res; + } + +private: + string check(vector& freq, const string& s, char base, char res){ + + int num = freq[base - 'a']; + for(char c: s){ + freq[c - 'a'] -= num; + assert(freq[c - 'a'] >= 0); + } + return string(num, res); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0424-Longest-Repeating-Character-Replacement/cpp-0424/CMakeLists.txt b/0001-0500/0424-Longest-Repeating-Character-Replacement/cpp-0424/CMakeLists.txt new file mode 100644 index 00000000..64ce6e27 --- /dev/null +++ b/0001-0500/0424-Longest-Repeating-Character-Replacement/cpp-0424/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0424) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0424 main.cpp) \ No newline at end of file diff --git a/0001-0500/0424-Longest-Repeating-Character-Replacement/cpp-0424/main.cpp b/0001-0500/0424-Longest-Repeating-Character-Replacement/cpp-0424/main.cpp new file mode 100644 index 00000000..0758928e --- /dev/null +++ b/0001-0500/0424-Longest-Repeating-Character-Replacement/cpp-0424/main.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/longest-repeating-character-replacement/ +/// Author : liuyubobobo +/// Time : 2021-02-01 + +#include +#include + +using namespace std; + + +/// Two Pointers +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +public: + int characterReplacement(string s, int k) { + + int res = 0; + for(char c = 'A'; c <= 'Z'; c ++) + res = max(res, solve(s, k, c)); + return res; + } + +private: + int solve(const string& s, int k, char c){ + + int n = s.size(); + vector presum(n + 1, 0); + for(int i = 0; i < n; i ++) + presum[i + 1] = presum[i] + (s[i] == c); + + int l = 0, r = 0, res = 0; + while(l <= n){ + if(r + 1 <= n && presum[r + 1] - presum[l] + k >= r + 1 - l) + r ++, res = max(res, r - l); + else + l ++; + } + return res; + } +}; + + +int main() { + + cout << Solution().characterReplacement("ABAB", 2) << endl; + // 4 + + cout << Solution().characterReplacement("AABABBA", 1) << endl; + // 4 + + return 0; +} diff --git a/0001-0500/0426-Convert-Binary-Search-Tree-to-Sorted-Doubly-Linked-List/cpp-0426/CMakeLists.txt b/0001-0500/0426-Convert-Binary-Search-Tree-to-Sorted-Doubly-Linked-List/cpp-0426/CMakeLists.txt new file mode 100644 index 00000000..11f2472c --- /dev/null +++ b/0001-0500/0426-Convert-Binary-Search-Tree-to-Sorted-Doubly-Linked-List/cpp-0426/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(cpp_0426) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0426 main2.cpp) \ No newline at end of file diff --git a/0001-0500/0426-Convert-Binary-Search-Tree-to-Sorted-Doubly-Linked-List/cpp-0426/main.cpp b/0001-0500/0426-Convert-Binary-Search-Tree-to-Sorted-Doubly-Linked-List/cpp-0426/main.cpp new file mode 100644 index 00000000..3ded50cd --- /dev/null +++ b/0001-0500/0426-Convert-Binary-Search-Tree-to-Sorted-Doubly-Linked-List/cpp-0426/main.cpp @@ -0,0 +1,101 @@ +/// Source : https://leetcode.com/problems/convert-binary-search-tree-to-sorted-doubly-linked-list/ +/// Author : liuyubobobo +/// Time : 2019-04-09 + +#include + +using namespace std; + + +// Definition for a Node. +class Node { +public: + int val; + Node* left; + Node* right; + + Node() {} + + Node(int _val, Node* _left, Node* _right) { + val = _val; + left = _left; + right = _right; + } +}; + + +/// DFS with return value +/// Time Complexity: O(n) +/// Space Complexity: O(h) +class Solution { + +public: + Node* treeToDoublyList(Node* root) { + + if(!root) return root; + + pair p = inOrder(root); + p.second->right = p.first; + p.first->left = p.second; + return p.first; + } + +private: + pair inOrder(Node* node){ + + Node* first, *tail; + if(node->left){ + pair left = inOrder(node->left); + first = left.first; + left.second->right = node; + node->left = left.second; + } + else + first = node; + + if(node->right){ + pair right = inOrder(node->right); + right.first->left = node; + node->right = right.first; + tail = right.second; + } + else + tail = node; + + return make_pair(first, tail); + } + + Node* getFirst(Node* node){ + + Node* cur = node; + if(cur->left) cur = cur->left; + return cur; + } +}; + + +void print_list(Node* head){ + + if(head){ + cout << head->val << " -> "; + Node* cur = head->right; + while(cur != head){ + cout << cur->val << " -> "; + cur = cur->right; + } + } + cout << "NULL" << endl; +} + +int main() { + + Node* one = new Node(1, NULL, NULL); + Node* three = new Node(3, NULL, NULL); + Node* two = new Node(2, one, three); + Node* five = new Node(5, NULL, NULL); + Node* four = new Node(4, two, five); + + print_list(Solution().treeToDoublyList(four)); + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0426-Convert-Binary-Search-Tree-to-Sorted-Doubly-Linked-List/cpp-0426/main2.cpp b/0001-0500/0426-Convert-Binary-Search-Tree-to-Sorted-Doubly-Linked-List/cpp-0426/main2.cpp new file mode 100644 index 00000000..500aed78 --- /dev/null +++ b/0001-0500/0426-Convert-Binary-Search-Tree-to-Sorted-Doubly-Linked-List/cpp-0426/main2.cpp @@ -0,0 +1,93 @@ +/// Source : https://leetcode.com/problems/convert-binary-search-tree-to-sorted-doubly-linked-list/ +/// Author : liuyubobobo +/// Time : 2019-04-09 + +#include + +using namespace std; + + +// Definition for a Node. +class Node { +public: + int val; + Node* left; + Node* right; + + Node() {} + + Node(int _val, Node* _left, Node* _right) { + val = _val; + left = _left; + right = _right; + } +}; + + +/// DFS with reference value +/// Time Complexity: O(n) +/// Space Complexity: O(h) +class Solution { + +public: + Node* treeToDoublyList(Node* root) { + + if(!root) return root; + + Node* first, *tail; + inOrder(root, first, tail); + tail->right = first; + first->left = tail; + return first; + } + +private: + void inOrder(Node* node, Node*& first, Node*& tail){ + + if(node->left){ + inOrder(node->left, first, tail); + tail->right = node; + node->left = tail; + } + else + first = node; + + if(node->right){ + Node* rFirst; + inOrder(node->right, rFirst, tail); + rFirst->left = node; + node->right = rFirst; + } + else + tail = node; + + return; + } +}; + + +void print_list(Node* head){ + + if(head){ + cout << head->val << " -> "; + Node* cur = head->right; + while(cur != head){ + cout << cur->val << " -> "; + cur = cur->right; + } + } + cout << "NULL" << endl; +} + +int main() { + + Node* one = new Node(1, NULL, NULL); + Node* three = new Node(3, NULL, NULL); + Node* two = new Node(2, one, three); + Node* five = new Node(5, NULL, NULL); + Node* four = new Node(4, two, five); + + print_list(Solution().treeToDoublyList(four)); + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0427-Construct-Quad-Tree/cpp-0427/CMakeLists.txt b/0001-0500/0427-Construct-Quad-Tree/cpp-0427/CMakeLists.txt new file mode 100644 index 00000000..6cd09ad7 --- /dev/null +++ b/0001-0500/0427-Construct-Quad-Tree/cpp-0427/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_0427) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0427 main.cpp) diff --git a/0001-0500/0427-Construct-Quad-Tree/cpp-0427/main.cpp b/0001-0500/0427-Construct-Quad-Tree/cpp-0427/main.cpp new file mode 100644 index 00000000..5c5d034e --- /dev/null +++ b/0001-0500/0427-Construct-Quad-Tree/cpp-0427/main.cpp @@ -0,0 +1,91 @@ +/// Source : https://leetcode.com/problems/construct-quad-tree/ +/// Author : liuyubobobo +/// Time : 2022-04-28 + +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(N^2) +/// Space Complexity: O(N^2) + +// Definition for a QuadTree node. +class Node { +public: + bool val; + bool isLeaf; + Node* topLeft; + Node* topRight; + Node* bottomLeft; + Node* bottomRight; + + Node() { + val = false; + isLeaf = false; + topLeft = NULL; + topRight = NULL; + bottomLeft = NULL; + bottomRight = NULL; + } + + Node(bool _val, bool _isLeaf) { + val = _val; + isLeaf = _isLeaf; + topLeft = NULL; + topRight = NULL; + bottomLeft = NULL; + bottomRight = NULL; + } + + Node(bool _val, bool _isLeaf, Node* _topLeft, Node* _topRight, Node* _bottomLeft, Node* _bottomRight) { + val = _val; + isLeaf = _isLeaf; + topLeft = _topLeft; + topRight = _topRight; + bottomLeft = _bottomLeft; + bottomRight = _bottomRight; + } +}; + +class Solution { +public: + Node* construct(vector>& grid) { + + int N = grid.size(); + vector> presum(N + 1, vector(N + 1, 0)); + for(int i = 0; i < N; i ++) + for(int j = 0; j < N; j ++) + presum[i + 1][j + 1] = presum[i + 1][j] + presum[i][j + 1] - presum[i][j] + grid[i][j]; + + return construct(grid, presum, 0, 0, N - 1, N - 1); + } + +private: + Node* construct(const vector>& grid, const vector>& presum, + int x1, int y1, int x2, int y2){ + + int value = presum[x2 + 1][y2 + 1] - presum[x1][y2 + 1] - presum[x2 + 1][y1] + presum[x1][y1]; + int area = (y2 - y1 + 1) * (x2 - x1 + 1); + if(value == area || value == 0) + return new Node(value, true); + + int N = (y2 - y1 + 1); + Node* node0 = construct(grid, presum, x1, y1, x1 + N / 2 - 1, y1 + N / 2 - 1); + Node* node1 = construct(grid, presum, x1, y1 + N / 2, x1 + N / 2 - 1, y1 + N - 1); + Node* node2 = construct(grid, presum, x1 + N / 2, y1, x1 + N - 1, y1 + N / 2 - 1); + Node* node3 = construct(grid, presum, x1 + N / 2, y1 + N / 2, x1 + N - 1, y1 + N - 1); + return new Node(value, false, node0, node1, node2, node3); + } +}; + + +int main() { + + vector> g1 = {{0, 1}, {1, 0}}; + Solution().construct(g1); + + return 0; +} diff --git a/0001-0500/0429-N-ary-Tree-Level-Order-Traversal/cpp-0429/CMakeLists.txt b/0001-0500/0429-N-ary-Tree-Level-Order-Traversal/cpp-0429/CMakeLists.txt new file mode 100644 index 00000000..2ac239f1 --- /dev/null +++ b/0001-0500/0429-N-ary-Tree-Level-Order-Traversal/cpp-0429/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0429) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main2.cpp) +add_executable(cpp_0429 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0429-N-ary-Tree-Level-Order-Traversal/cpp-0429/main.cpp b/0001-0500/0429-N-ary-Tree-Level-Order-Traversal/cpp-0429/main.cpp new file mode 100644 index 00000000..0d3bc6df --- /dev/null +++ b/0001-0500/0429-N-ary-Tree-Level-Order-Traversal/cpp-0429/main.cpp @@ -0,0 +1,64 @@ +/// Source : https://leetcode.com/problems/n-ary-tree-level-order-traversal/ +/// Author : liuyubobobo +/// Time : 2018-10-30 + +#include +#include +#include + +using namespace std; + + +/// Definition for a Node. +class Node { +public: + int val = NULL; + vector children; + + Node() {} + + Node(int _val, vector _children) { + val = _val; + children = _children; + } +}; + + +/// BFS +/// Store step in the queue +/// +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector> levelOrder(Node* root) { + + vector> res; + if(!root) + return res; + + queue> q; + q.push(make_pair(root, 0)); + while(!q.empty()){ + Node* cur = q.front().first; + int step = q.front().second; + q.pop(); + + if(step == res.size()) + res.push_back({cur->val}); + else + res[step].push_back(cur->val); + + for(Node* next: cur->children) + q.push(make_pair(next, step + 1)); + } + + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0429-N-ary-Tree-Level-Order-Traversal/cpp-0429/main2.cpp b/0001-0500/0429-N-ary-Tree-Level-Order-Traversal/cpp-0429/main2.cpp new file mode 100644 index 00000000..ac9ecde3 --- /dev/null +++ b/0001-0500/0429-N-ary-Tree-Level-Order-Traversal/cpp-0429/main2.cpp @@ -0,0 +1,63 @@ +/// Source : https://leetcode.com/problems/n-ary-tree-level-order-traversal/ +/// Author : liuyubobobo +/// Time : 2018-10-30 + +#include +#include +#include + +using namespace std; + + +/// Definition for a Node. +class Node { +public: + int val = NULL; + vector children; + + Node() {} + + Node(int _val, vector _children) { + val = _val; + children = _children; + } +}; + + +/// BFS, using Queue +/// No need to store step in the queue :-) +/// +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector> levelOrder(Node* root) { + + vector> res; + if(!root) + return res; + + queue q; + q.push(root); + while(!q.empty()){ + int n = q.size(); + vector level; + for(int i = 0; i < n; i ++){ + Node* node = q.front(); + q.pop(); + level.push_back(node->val); + for(Node* next: node->children) + q.push(next); + } + res.push_back(level); + } + + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0430-Flatten-a-Multilevel-Doubly-Linked-List/cpp-0430/CMakeLists.txt b/0001-0500/0430-Flatten-a-Multilevel-Doubly-Linked-List/cpp-0430/CMakeLists.txt new file mode 100644 index 00000000..e8854a0d --- /dev/null +++ b/0001-0500/0430-Flatten-a-Multilevel-Doubly-Linked-List/cpp-0430/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0430) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0430 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0430-Flatten-a-Multilevel-Doubly-Linked-List/cpp-0430/main.cpp b/0001-0500/0430-Flatten-a-Multilevel-Doubly-Linked-List/cpp-0430/main.cpp new file mode 100644 index 00000000..5ac37427 --- /dev/null +++ b/0001-0500/0430-Flatten-a-Multilevel-Doubly-Linked-List/cpp-0430/main.cpp @@ -0,0 +1,81 @@ +/// Source : https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list/description/ +/// Author : liuyubobobo +/// Time : 2018-10-02 + +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// Definition for a Node. +class Node { + +public: + int val = NULL; + Node* prev = NULL; + Node* next = NULL; + Node* child = NULL; + + Node() {} + + Node(int _val, Node* _prev, Node* _next, Node* _child) { + val = _val; + prev = _prev; + next = _next; + child = _child; + } +}; + + +class Solution { +public: + Node* flatten(Node* head) { + + if(!head) + return NULL; + + Node* tail; + return flatten(head, tail); + } + +private: + Node* flatten(Node* head, Node*& tail){ + + Node* cur = head; + while(cur){ + if(cur->child){ + Node* subtail; + Node* subhead = flatten(cur->child, subtail); + Node* next = cur->next; + + cur->next = subhead; + subhead->prev = cur; + subtail->next = next; + + if(next) + next->prev = subtail; + else + tail = subtail; + + cur->child = NULL; + cur = next; + } + else{ + if(!cur->next) + tail = cur; + cur = cur->next; + } + } + return head; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0431-Encode-N-ary-Tree-to-Binary-Tree/cpp-0431/CMakeLists.txt b/0001-0500/0431-Encode-N-ary-Tree-to-Binary-Tree/cpp-0431/CMakeLists.txt new file mode 100644 index 00000000..f1cdc201 --- /dev/null +++ b/0001-0500/0431-Encode-N-ary-Tree-to-Binary-Tree/cpp-0431/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_0431) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0431 main.cpp) diff --git a/0001-0500/0431-Encode-N-ary-Tree-to-Binary-Tree/cpp-0431/main.cpp b/0001-0500/0431-Encode-N-ary-Tree-to-Binary-Tree/cpp-0431/main.cpp new file mode 100644 index 00000000..5f5f1551 --- /dev/null +++ b/0001-0500/0431-Encode-N-ary-Tree-to-Binary-Tree/cpp-0431/main.cpp @@ -0,0 +1,83 @@ +/// Source : https://leetcode.com/problems/encode-n-ary-tree-to-binary-tree/ +/// Author : liuyubobobo +/// Time : 2022-04-29 + +#include +#include + +using namespace std; + + +/// Left-Child Right-Sibling Representation +/// Time Complexity: O(n) +/// Space Complexity: O(1) + +// Definition for a Node. +class Node { +public: + int val; + vector children; + + Node() {} + + Node(int _val) { + val = _val; + } + + Node(int _val, vector _children) { + val = _val; + children = _children; + } +}; + +///Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +class Codec { +public: + // Encodes an n-ary tree to a binary tree. + TreeNode* encode(Node* node) { + + if(!node) return nullptr; + + TreeNode* ret = new TreeNode(node->val); + + if(node->children.size() == 0) return ret; + + vector v; + for(Node* child_node: node->children) v.push_back(encode(child_node)); + + for(int i = 1; i < v.size(); i ++) v[i - 1]->right = v[i]; + ret->left = v[0]; + return ret; + } + + // Decodes your binary tree to an n-ary tree. + Node* decode(TreeNode* node) { + + if(!node) return nullptr; + + Node* ret = new Node(node->val); + if(!node->left) return ret; + + TreeNode* cur = node->left; + vector v; + while(cur){ + v.push_back(decode(cur)); + cur = cur->right; + } + ret->children = v; + return ret; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0432-All-O-one-Data-Structure/cpp-0432/CMakeLists.txt b/0001-0500/0432-All-O-one-Data-Structure/cpp-0432/CMakeLists.txt new file mode 100644 index 00000000..75fd9397 --- /dev/null +++ b/0001-0500/0432-All-O-one-Data-Structure/cpp-0432/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_0432) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0432 main.cpp) diff --git a/0001-0500/0432-All-O-one-Data-Structure/cpp-0432/main.cpp b/0001-0500/0432-All-O-one-Data-Structure/cpp-0432/main.cpp new file mode 100644 index 00000000..39988bfe --- /dev/null +++ b/0001-0500/0432-All-O-one-Data-Structure/cpp-0432/main.cpp @@ -0,0 +1,66 @@ +/// Source : https://leetcode.com/problems/all-oone-data-structure/ +/// Author : liuyubobobo +/// Time : 2022-03-15 + +#include +#include +#include + +using namespace std; + + +/// Map + Set +/// Time Complexity: O(logn) for all operations +/// Space Complexity: O(n) +class AllOne { + +private: + map f; + set> fs_set; + +public: + AllOne() {} + + void inc(string key) { + int old_f = f[key]; + f[key] ++; + + if(old_f) fs_set.erase({old_f, key}); + fs_set.insert({old_f + 1, key}); + } + + void dec(string key) { + int old_f = f[key]; + f[key] --; + if(old_f - 1 == 0) f.erase(key); + + fs_set.erase({old_f, key}); + if(old_f - 1) fs_set.insert({old_f - 1, key}); + } + + string getMaxKey() { + if(fs_set.empty()) return ""; + return fs_set.rbegin()->second; + } + + string getMinKey() { + if(fs_set.empty()) return ""; + return fs_set.begin()->second; + } +}; + + +int main() { + + AllOne obj; + obj.inc("hello"); + obj.inc("hello"); + cout << obj.getMaxKey() << '\n'; + cout << obj.getMinKey() << '\n'; + + obj.inc("leet"); + cout << obj.getMaxKey() << '\n'; + cout << obj.getMinKey() << '\n'; + + return 0; +} diff --git a/0001-0500/0433-Minimum-Genetic-Mutation/cpp-0433/CMakeLists.txt b/0001-0500/0433-Minimum-Genetic-Mutation/cpp-0433/CMakeLists.txt new file mode 100644 index 00000000..1429bc97 --- /dev/null +++ b/0001-0500/0433-Minimum-Genetic-Mutation/cpp-0433/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_0433) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0433 main.cpp) diff --git a/0001-0500/0433-Minimum-Genetic-Mutation/cpp-0433/main.cpp b/0001-0500/0433-Minimum-Genetic-Mutation/cpp-0433/main.cpp new file mode 100644 index 00000000..2d1f638c --- /dev/null +++ b/0001-0500/0433-Minimum-Genetic-Mutation/cpp-0433/main.cpp @@ -0,0 +1,59 @@ +/// Source : https://leetcode.com/problems/minimum-genetic-mutation/ +/// Author : liuyubobobo +/// Time : 2022-05-06 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// BFS +/// Time Complexity: O(n * |start|) +/// Space Complexity: O(n) +class Solution { + +private: + const vector gene = {'A', 'C', 'G', 'T'}; + +public: + int minMutation(string start, string end, vector& bank) { + + set bank_set(bank.begin(), bank.end()); + map dis; + + queue q; + q.push(start); + dis[start] = 0; + while(!q.empty()){ + string cur = q.front(); + int d = dis[cur]; + q.pop(); + + if(cur == end) return d; + + for(int i = 0; i < cur.size(); i ++) { + char o_gene = cur[i]; + for (int j = 0; j < 4; j++) { + cur[i] = gene[j]; + if(bank_set.count(cur) && !dis.count(cur)){ + dis[cur] = d + 1; + q.push(cur); + } + cur[i] = o_gene; + } + } + + } + return -1; + } +}; + + +int main() { + + return 0; +} diff --git a/0434-Number of-Segments-in-a-String/cpp-0434/CMakeLists.txt b/0001-0500/0434-Number of-Segments-in-a-String/cpp-0434/CMakeLists.txt similarity index 100% rename from 0434-Number of-Segments-in-a-String/cpp-0434/CMakeLists.txt rename to 0001-0500/0434-Number of-Segments-in-a-String/cpp-0434/CMakeLists.txt diff --git a/0434-Number of-Segments-in-a-String/cpp-0434/main.cpp b/0001-0500/0434-Number of-Segments-in-a-String/cpp-0434/main.cpp similarity index 100% rename from 0434-Number of-Segments-in-a-String/cpp-0434/main.cpp rename to 0001-0500/0434-Number of-Segments-in-a-String/cpp-0434/main.cpp diff --git a/0434-Number of-Segments-in-a-String/cpp-0434/main2.cpp b/0001-0500/0434-Number of-Segments-in-a-String/cpp-0434/main2.cpp similarity index 100% rename from 0434-Number of-Segments-in-a-String/cpp-0434/main2.cpp rename to 0001-0500/0434-Number of-Segments-in-a-String/cpp-0434/main2.cpp diff --git a/0434-Number of-Segments-in-a-String/cpp-0434/main3.cpp b/0001-0500/0434-Number of-Segments-in-a-String/cpp-0434/main3.cpp similarity index 100% rename from 0434-Number of-Segments-in-a-String/cpp-0434/main3.cpp rename to 0001-0500/0434-Number of-Segments-in-a-String/cpp-0434/main3.cpp diff --git a/0435-Non-overlapping-Intervals/cpp-0435/CMakeLists.txt b/0001-0500/0435-Non-overlapping-Intervals/cpp-0435/CMakeLists.txt similarity index 100% rename from 0435-Non-overlapping-Intervals/cpp-0435/CMakeLists.txt rename to 0001-0500/0435-Non-overlapping-Intervals/cpp-0435/CMakeLists.txt diff --git a/0001-0500/0435-Non-overlapping-Intervals/cpp-0435/main.cpp b/0001-0500/0435-Non-overlapping-Intervals/cpp-0435/main.cpp new file mode 100644 index 00000000..e845f92e --- /dev/null +++ b/0001-0500/0435-Non-overlapping-Intervals/cpp-0435/main.cpp @@ -0,0 +1,50 @@ +/// https://leetcode.com/problems/non-overlapping-intervals/description/ +/// Author : liuyubobobo +/// Time : 2017-11-19 +/// Updated: 2019-09-22 + +#include +#include + +using namespace std; + + +/// Dynamic Programming based on starting point +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { +public: + int eraseOverlapIntervals(vector>& intervals) { + + if(intervals.size() == 0) + return 0; + + sort(intervals.begin(), intervals.end(), [](const vector& a, const vector& b){ + if(a[0] != b[0]) return a[0] < b[0]; + return a[1] < b[1]; + }); + + vector dp(intervals.size(), 1); + for(int i = 1 ; i < intervals.size() ; i ++) + for(int j = 0 ; j < i ; j ++) + if(intervals[i][0] >= intervals[j][1]) + dp[i] = max(dp[i], 1 + dp[j]); + + return intervals.size() - dp.back(); + } +}; + + +int main() { + + vector> interval1 = {{1,2}, {2,3}, {3,4}, {1,3}}; + cout << Solution().eraseOverlapIntervals(interval1) << endl; + + vector> interval2 = {{1,2}, {1,2}, {1,2}}; + cout << Solution().eraseOverlapIntervals(interval2) << endl; + + vector> interval3 = {{1,2}, {2,3}}; + cout << Solution().eraseOverlapIntervals(interval3) << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0435-Non-overlapping-Intervals/cpp-0435/main2.cpp b/0001-0500/0435-Non-overlapping-Intervals/cpp-0435/main2.cpp new file mode 100644 index 00000000..20d4cc21 --- /dev/null +++ b/0001-0500/0435-Non-overlapping-Intervals/cpp-0435/main2.cpp @@ -0,0 +1,55 @@ +/// https://leetcode.com/problems/non-overlapping-intervals/description/ +/// Author : liuyubobobo +/// Time : 2017-11-19 +/// Updated: 2019-09-22 + +#include +#include + +using namespace std; + + +/// Greedy Algorithm based on starting point +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +public: + int eraseOverlapIntervals(vector>& intervals){ + + if(intervals.size() == 0) + return 0; + + sort(intervals.begin(), intervals.end(), [](const vector& a, const vector& b){ + if(a[0] != b[0]) return a[0] < b[0]; + return a[1] < b[1]; + }); + + int res = 1; + int pre = 0; + for(int i = 1 ; i < intervals.size() ; i ++) + if(intervals[i][0] >= intervals[pre][1]){ + pre = i; + res ++; + } + else if(intervals[i][1] < intervals[pre][1]) + pre = i; + + return intervals.size() - res; + } +}; + + +int main() { + + vector> interval1 = {{1,2}, {2,3}, {3,4}, {1,3}}; + cout << Solution().eraseOverlapIntervals(interval1) << endl; + + vector> interval2 = {{1,2}, {1,2}, {1,2}}; + cout << Solution().eraseOverlapIntervals(interval2) << endl; + + vector> interval3 = {{1,2}, {2,3}}; + cout << Solution().eraseOverlapIntervals(interval3) << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0435-Non-overlapping-Intervals/cpp-0435/main3.cpp b/0001-0500/0435-Non-overlapping-Intervals/cpp-0435/main3.cpp new file mode 100644 index 00000000..507ebeba --- /dev/null +++ b/0001-0500/0435-Non-overlapping-Intervals/cpp-0435/main3.cpp @@ -0,0 +1,50 @@ +/// https://leetcode.com/problems/non-overlapping-intervals/description/ +/// Author : liuyubobobo +/// Time : 2017-11-19 +/// Updated: 2019-09-22 + +#include +#include + +using namespace std; + + +/// Dynamic Programming based on ending point +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { +public: + int eraseOverlapIntervals(vector>& intervals) { + + if(intervals.size() == 0) + return 0; + + sort(intervals.begin(), intervals.end(), [](const vector& a, const vector& b){ + if(a[1] != b[1]) return a[1] < b[1]; + return a[0] < b[0]; + }); + + vector dp(intervals.size(), 1); + for(int i = 1 ; i < intervals.size() ; i ++) + for(int j = 0 ; j < i ; j ++) + if(intervals[i][0] >= intervals[j][1]) + dp[i] = max(dp[i], 1 + dp[j]); + + return intervals.size() - *max_element(dp.begin(), dp.end()); + } +}; + + +int main() { + + vector> interval1 = {{1,2}, {2,3}, {3,4}, {1,3}}; + cout << Solution().eraseOverlapIntervals(interval1) << endl; + + vector> interval2 = {{1,2}, {1,2}, {1,2}}; + cout << Solution().eraseOverlapIntervals(interval2) << endl; + + vector> interval3 = {{1,2}, {2,3}}; + cout << Solution().eraseOverlapIntervals(interval3) << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0435-Non-overlapping-Intervals/cpp-0435/main4.cpp b/0001-0500/0435-Non-overlapping-Intervals/cpp-0435/main4.cpp new file mode 100644 index 00000000..07fa7361 --- /dev/null +++ b/0001-0500/0435-Non-overlapping-Intervals/cpp-0435/main4.cpp @@ -0,0 +1,52 @@ +/// https://leetcode.com/problems/non-overlapping-intervals/description/ +/// Author : liuyubobobo +/// Time : 2017-11-19 +/// Updated: 2019-09-22 + +#include +#include + +using namespace std; + + +/// Greedy Algorithm based on ending point +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int eraseOverlapIntervals(vector>& intervals) { + + if(intervals.size() == 0) + return 0; + + sort(intervals.begin(), intervals.end(), [](const vector& a, const vector& b){ + if(a[1] != b[1]) return a[1] < b[1]; + return a[0] < b[0]; + }); + + int res = 1; + int pre = 0; + for(int i = 1 ; i < intervals.size() ; i ++) + if(intervals[i][0] >= intervals[pre][1]){ + res ++; + pre = i; + } + + return intervals.size() - res; + } +}; + + +int main() { + + vector> interval1 = {{1,2}, {2,3}, {3,4}, {1,3}}; + cout << Solution().eraseOverlapIntervals(interval1) << endl; + + vector> interval2 = {{1,2}, {1,2}, {1,2}}; + cout << Solution().eraseOverlapIntervals(interval2) << endl; + + vector> interval3 = {{1,2}, {2,3}}; + cout << Solution().eraseOverlapIntervals(interval3) << endl; + + return 0; +} \ No newline at end of file diff --git a/0435-Non-overlapping-Intervals/java-0435/src/Solution1.java b/0001-0500/0435-Non-overlapping-Intervals/java-0435/src/Solution1.java similarity index 100% rename from 0435-Non-overlapping-Intervals/java-0435/src/Solution1.java rename to 0001-0500/0435-Non-overlapping-Intervals/java-0435/src/Solution1.java diff --git a/0435-Non-overlapping-Intervals/java-0435/src/Solution2.java b/0001-0500/0435-Non-overlapping-Intervals/java-0435/src/Solution2.java similarity index 100% rename from 0435-Non-overlapping-Intervals/java-0435/src/Solution2.java rename to 0001-0500/0435-Non-overlapping-Intervals/java-0435/src/Solution2.java diff --git a/0435-Non-overlapping-Intervals/java-0435/src/Solution3.java b/0001-0500/0435-Non-overlapping-Intervals/java-0435/src/Solution3.java similarity index 100% rename from 0435-Non-overlapping-Intervals/java-0435/src/Solution3.java rename to 0001-0500/0435-Non-overlapping-Intervals/java-0435/src/Solution3.java diff --git a/0435-Non-overlapping-Intervals/java-0435/src/Solution4.java b/0001-0500/0435-Non-overlapping-Intervals/java-0435/src/Solution4.java similarity index 100% rename from 0435-Non-overlapping-Intervals/java-0435/src/Solution4.java rename to 0001-0500/0435-Non-overlapping-Intervals/java-0435/src/Solution4.java diff --git a/0001-0500/0436-Find-Right-Interval/cpp-0436/CMakeLists.txt b/0001-0500/0436-Find-Right-Interval/cpp-0436/CMakeLists.txt new file mode 100644 index 00000000..adbc37ea --- /dev/null +++ b/0001-0500/0436-Find-Right-Interval/cpp-0436/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_0436) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0436 main.cpp) diff --git a/0001-0500/0436-Find-Right-Interval/cpp-0436/main.cpp b/0001-0500/0436-Find-Right-Interval/cpp-0436/main.cpp new file mode 100644 index 00000000..ae275895 --- /dev/null +++ b/0001-0500/0436-Find-Right-Interval/cpp-0436/main.cpp @@ -0,0 +1,48 @@ +/// Source : https://leetcode.com/problems/find-right-interval/ +/// Author : liuyubobobo +/// Time : 2022-05-19 + +#include +#include +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + vector findRightInterval(vector>& intervals) { + + int n = intervals.size(); + vector, int>> data(n); + for(int i = 0; i < n; i ++) + data[i] = {{intervals[i][0], intervals[i][1]}, i}; + sort(data.begin(), data.end()); + + vector res(n, -1); + for(int i = 0; i < n; i ++){ + int start = data[i].first.first, end = data[i].first.second, index = data[i].second; + auto iter = lower_bound(data.begin(), data.end(), make_pair(make_pair(end, INT_MIN), INT_MIN)); + if(iter != data.end()) res[index] = iter->second; + } + return res; + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << ' '; cout << '\n'; +} + +int main() { + + vector> intervals1 = {{3, 4}, {2, 3}, {1, 2}}; + print_vec(Solution().findRightInterval(intervals1)); + // -1 0 1 + + return 0; +} diff --git a/0437-Path-Sum-III/cpp-0437/CMakeLists.txt b/0001-0500/0437-Path-Sum-III/cpp-0437/CMakeLists.txt similarity index 100% rename from 0437-Path-Sum-III/cpp-0437/CMakeLists.txt rename to 0001-0500/0437-Path-Sum-III/cpp-0437/CMakeLists.txt diff --git a/0001-0500/0437-Path-Sum-III/cpp-0437/main.cpp b/0001-0500/0437-Path-Sum-III/cpp-0437/main.cpp new file mode 100644 index 00000000..49056e37 --- /dev/null +++ b/0001-0500/0437-Path-Sum-III/cpp-0437/main.cpp @@ -0,0 +1,91 @@ +/// Source : https://leetcode.com/problems/path-sum-iii/description/ +/// Author : liuyubobobo +/// Time : 2017-11-18 + +#include + +using namespace std; + + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + + +/// Recursive +/// Time Complexity: O(n^2), where n is the node's number of the tree +/// Space Complexity: O(h), where h is the height of the tree +class Solution { + +public: + int pathSum(TreeNode* root, int sum) { + + if(root == NULL) + return 0; + + return findPath(root, sum) + + pathSum(root->left , sum) + + pathSum(root->right , sum); + } + +private: + int findPath(TreeNode* node, int num){ + + if(node == NULL) + return 0; + + int res = 0; + if(node->val == num) + res += 1; + + res += findPath(node->left , num - node->val); + res += findPath(node->right , num - node->val); + + return res; + } +}; + +int main() { + + /***************** + * Test case: + * + * 10 + * / \ + * 5 -3 + * / \ \ + * 3 2 11 + * / \ \ + * 3 -2 1 + *****************/ + TreeNode* node1 = new TreeNode(3); + TreeNode* node2 = new TreeNode(-2); + + TreeNode* node3 = new TreeNode(3); + node3->left = node1; + node3->right = node2; + + TreeNode* node4 = new TreeNode(1); + TreeNode* node5 = new TreeNode(2); + node5->right = node4; + + TreeNode* node6 = new TreeNode(5); + node6->left = node3; + node6->right = node5; + + TreeNode* node7 = new TreeNode(11); + TreeNode* node8 = new TreeNode(-3); + node8->right = node7; + + TreeNode* node9 = new TreeNode(10); + node9->left = node6; + node9->right = node8; + + cout << Solution().pathSum(node9, 8) << endl; + + return 0; +} diff --git a/0001-0500/0437-Path-Sum-III/java-0437/src/Solution.java b/0001-0500/0437-Path-Sum-III/java-0437/src/Solution.java new file mode 100644 index 00000000..70ab58dd --- /dev/null +++ b/0001-0500/0437-Path-Sum-III/java-0437/src/Solution.java @@ -0,0 +1,81 @@ +/// Source : https://leetcode.com/problems/path-sum-iii/description/ +/// Author : liuyubobobo +/// Time : 2017-11-18 + +/// Recursive +/// Time Complexity: O(n^2), where n is the node's number of the tree +/// Space Complexity: O(h), where h is the height of the tree +class Solution { + + /// Definition for a binary tree node. + public static class TreeNode { + int val; + TreeNode left; + TreeNode right; + TreeNode(int x) { val = x; } + } + + public int pathSum(TreeNode root, int sum) { + + if(root == null) + return 0; + + return findPath(root, sum) + + pathSum(root.left , sum) + + pathSum(root.right , sum); + } + + private int findPath(TreeNode node, int num){ + + if(node == null) + return 0; + + int res = 0; + if(node.val == num) + res += 1; + + res += findPath(node.left , num - node.val); + res += findPath(node.right , num - node.val); + + return res; + } + + public static void main(String[] args) { + + /***************** + * Test case: + * + * 10 + * / \ + * 5 -3 + * / \ \ + * 3 2 11 + * / \ \ + * 3 -2 1 + *****************/ + TreeNode node1 = new TreeNode(3); + TreeNode node2 = new TreeNode(-2); + + TreeNode node3 = new TreeNode(3); + node3.left = node1; + node3.right = node2; + + TreeNode node4 = new TreeNode(1); + TreeNode node5 = new TreeNode(2); + node5.right = node4; + + TreeNode node6 = new TreeNode(5); + node6.left = node3; + node6.right = node5; + + TreeNode node7 = new TreeNode(11); + TreeNode node8 = new TreeNode(-3); + node8.right = node7; + + TreeNode node9 = new TreeNode(10); + node9.left = node6; + node9.right = node8; + + System.out.println((new Solution()).pathSum(node9, 8)); + } +} diff --git a/0438-Find-All-Anagrams-in-a-String/cpp-0438/CMakeLists.txt b/0001-0500/0438-Find-All-Anagrams-in-a-String/cpp-0438/CMakeLists.txt similarity index 100% rename from 0438-Find-All-Anagrams-in-a-String/cpp-0438/CMakeLists.txt rename to 0001-0500/0438-Find-All-Anagrams-in-a-String/cpp-0438/CMakeLists.txt diff --git a/0438-Find-All-Anagrams-in-a-String/cpp-0438/main.cpp b/0001-0500/0438-Find-All-Anagrams-in-a-String/cpp-0438/main.cpp similarity index 100% rename from 0438-Find-All-Anagrams-in-a-String/cpp-0438/main.cpp rename to 0001-0500/0438-Find-All-Anagrams-in-a-String/cpp-0438/main.cpp diff --git a/0001-0500/0439-Ternary-Expression-Parser/cpp-0439/CMakeLists.txt b/0001-0500/0439-Ternary-Expression-Parser/cpp-0439/CMakeLists.txt new file mode 100644 index 00000000..ee6d6e7c --- /dev/null +++ b/0001-0500/0439-Ternary-Expression-Parser/cpp-0439/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_0439) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0439 main.cpp) \ No newline at end of file diff --git a/0001-0500/0439-Ternary-Expression-Parser/cpp-0439/main.cpp b/0001-0500/0439-Ternary-Expression-Parser/cpp-0439/main.cpp new file mode 100644 index 00000000..324d06ae --- /dev/null +++ b/0001-0500/0439-Ternary-Expression-Parser/cpp-0439/main.cpp @@ -0,0 +1,64 @@ +/// Source : https://leetcode.com/problems/ternary-expression-parser/ +/// Author : liuyubobobo +/// Time : 2021-06-12 + +#include +#include +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + string parseTernary(string expression) { + + int n = expression.size(); + vector match(n, -1); + stack stack; + for(int i = 0; i < n; i ++) + if(expression[i] == '?') + stack.push(i); + else if(expression[i] == ':'){ + assert(!stack.empty()); + match[stack.top()] = i; + match[i] = stack.top(); + stack.pop(); + } + + return eval(expression, 0, n - 1, match); + } + +private: + string eval(const string& exp, int l, int r, const vector& match){ + + if(l == r){ +// assert(isdigit(exp[l])); + return exp.substr(l, 1); + } + + assert(exp[l] == 'T' || exp[l] == 'F'); + assert(exp[l + 1] == '?'); + if(exp[l] == 'T') return eval(exp, l + 2, match[l + 1] - 1, match); + return eval(exp, match[l + 1] + 1, r, match); + } +}; + + +int main() { + + cout << Solution().parseTernary("T?2:3") << endl; + // 2 + + cout << Solution().parseTernary("F?1:T?4:5") << endl; + // 4 + + cout << Solution().parseTernary("T?T?F:5:3") << endl; + // F + + return 0; +} diff --git a/0001-0500/0440-K-th-Smallest-in-Lexicographical-Order/cpp-0440/CMakeLists.txt b/0001-0500/0440-K-th-Smallest-in-Lexicographical-Order/cpp-0440/CMakeLists.txt new file mode 100644 index 00000000..23bd8c5b --- /dev/null +++ b/0001-0500/0440-K-th-Smallest-in-Lexicographical-Order/cpp-0440/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_0440) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0440 main.cpp) diff --git a/0001-0500/0440-K-th-Smallest-in-Lexicographical-Order/cpp-0440/main.cpp b/0001-0500/0440-K-th-Smallest-in-Lexicographical-Order/cpp-0440/main.cpp new file mode 100644 index 00000000..45d0d7a3 --- /dev/null +++ b/0001-0500/0440-K-th-Smallest-in-Lexicographical-Order/cpp-0440/main.cpp @@ -0,0 +1,97 @@ +/// Source : https://leetcode.com/problems/k-th-smallest-in-lexicographical-order/ +/// Author : liuyubobobo +/// Time : 2022-03-23 + +#include +#include +#include + +using namespace std; + + +/// Digital DP +/// Time Complexity: O(logn) +/// Space Complexity: O(logn) +class Solution { + +private: + vector pow10; + vector> dp; + +public: + int findKthNumber(int n, int k) { + + pow10.assign(15, 1); + for(int i = 1; i < 15; i ++) + pow10[i] = pow10[i - 1] * 10ll; + + dp = vector>(2, vector(20, -1)); + + string s = to_string(n); + string cur = ""; + assert(solve(s, cur, 0, k - 1)); + return cur == "" ? 1 : atoi(cur.c_str()); + } + +private: + bool solve(const string& s, string& cur, int index, int k){ + + if(k == 0) return true; + + int cnt_total = index == 0 ? 0 : 1; + for(int d = (index == 0 ? 1 : 0); d <= 9; d ++){ + int cnt = get_cnt(s, cur + (char)('0' + d), index + 1); + if(k < cnt_total + cnt){ + cur += (char)('0' + d); + solve(s, cur, index + 1, k - cnt_total); + return true; + } + cnt_total += cnt; + } + return false; + } + + int get_cnt(const string& s, const string& cur, int index){ + + int res = 0; + for(int len = index; len < s.size(); len ++) + res += pow10[len - index]; + + if(cur <= s.substr(0, cur.size())) + res += get_cnt_dfs(s, index, cur < s.substr(0, cur.size())); + return res; + } + + int get_cnt_dfs(const string& s, int index, bool can_over){ + + if(index == s.size()) return 1; + if(dp[can_over][index] != -1) return dp[can_over][index]; + + int res = 0; + for(int d = 0; d <= (can_over ? 9 : (s[index] - '0')); d ++){ + res += get_cnt_dfs(s, index + 1, can_over || d < s[index] - '0'); + } + return dp[can_over][index] = res; + } +}; + + +int main() { + + cout << Solution().findKthNumber(13, 2) << '\n'; + // 10 + + cout << Solution().findKthNumber(1, 1) << '\n'; + // 1 + + cout << Solution().findKthNumber(10, 3) << '\n'; + // 2 + + cout << Solution().findKthNumber(100, 10) << '\n'; + // 17 + + cout << Solution().findKthNumber(681692778, 351251360) << '\n'; + // 416126219 + + return 0; +} diff --git a/0001-0500/0441-Arranging-Coins/cpp-0441/CMakeLists.txt b/0001-0500/0441-Arranging-Coins/cpp-0441/CMakeLists.txt new file mode 100644 index 00000000..dee85ea7 --- /dev/null +++ b/0001-0500/0441-Arranging-Coins/cpp-0441/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0441) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0441 main.cpp) diff --git a/0001-0500/0441-Arranging-Coins/cpp-0441/main.cpp b/0001-0500/0441-Arranging-Coins/cpp-0441/main.cpp new file mode 100644 index 00000000..b931386c --- /dev/null +++ b/0001-0500/0441-Arranging-Coins/cpp-0441/main.cpp @@ -0,0 +1,22 @@ +/// Source : https://leetcode.com/problems/arranging-coins/ +/// Author : liuyubobobo +/// Time : 2021-10-09 + +#include + + +/// Mathematics +/// Time Complexity: O(1) +/// Space Complexity: O(1) +class Solution { +public: + int arrangeCoins(int n) { + + return int(sqrt(2.0 * n + 0.25) - 0.5 + 1e-6); + } +}; + + +int main() { + return 0; +} diff --git a/0001-0500/0442-Find-All-Duplicates-in-an-Array/cpp-0442/CMakeLists.txt b/0001-0500/0442-Find-All-Duplicates-in-an-Array/cpp-0442/CMakeLists.txt new file mode 100644 index 00000000..d12e9128 --- /dev/null +++ b/0001-0500/0442-Find-All-Duplicates-in-an-Array/cpp-0442/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0442) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0442 main.cpp) diff --git a/0001-0500/0442-Find-All-Duplicates-in-an-Array/cpp-0442/main.cpp b/0001-0500/0442-Find-All-Duplicates-in-an-Array/cpp-0442/main.cpp new file mode 100644 index 00000000..41f0ba12 --- /dev/null +++ b/0001-0500/0442-Find-All-Duplicates-in-an-Array/cpp-0442/main.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/find-all-duplicates-in-an-array/ +/// Author : liuyubobobo +/// Time : 2021-10-05 + +#include +#include +#include + +using namespace std; + + +/// Using Map +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector findDuplicates(vector& nums) { + + map f; + for(int e: nums) f[e] ++; + + vector res; + for(const pair& p: f) + if(p.second == 2) res.push_back(p.first); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/0443-String-Compression/cpp-0443/CMakeLists.txt b/0001-0500/0443-String-Compression/cpp-0443/CMakeLists.txt similarity index 100% rename from 0443-String-Compression/cpp-0443/CMakeLists.txt rename to 0001-0500/0443-String-Compression/cpp-0443/CMakeLists.txt diff --git a/0443-String-Compression/cpp-0443/main.cpp b/0001-0500/0443-String-Compression/cpp-0443/main.cpp similarity index 100% rename from 0443-String-Compression/cpp-0443/main.cpp rename to 0001-0500/0443-String-Compression/cpp-0443/main.cpp diff --git a/0001-0500/0444-Sequence-Reconstruction/cpp-0444/CMakeLists.txt b/0001-0500/0444-Sequence-Reconstruction/cpp-0444/CMakeLists.txt new file mode 100644 index 00000000..2b587b02 --- /dev/null +++ b/0001-0500/0444-Sequence-Reconstruction/cpp-0444/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_0444) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0444 main.cpp) diff --git a/0001-0500/0444-Sequence-Reconstruction/cpp-0444/main.cpp b/0001-0500/0444-Sequence-Reconstruction/cpp-0444/main.cpp new file mode 100644 index 00000000..52aefa50 --- /dev/null +++ b/0001-0500/0444-Sequence-Reconstruction/cpp-0444/main.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/sequence-reconstruction/ +/// Author : liuyubobobo +/// Time : 2022-07-22 + +#include +#include +#include + +using namespace std; + + +/// Topological Sort +/// Time Complexity: O(n + m) +/// Space Complexity: O(n + m) +class Solution { +public: + bool sequenceReconstruction(vector& nums, vector>& sequences) { + + int n = nums.size(); + + vector> g(n); + for(const vector& seq: sequences){ + for(int i = 1; i < seq.size(); i ++){ + int a = seq[i - 1] - 1, b = seq[i] - 1; + g[a].push_back(b); + } + } + + vector indegrees(n, 0); + for(int u = 0; u < n; u ++) + for(int v: g[u]) indegrees[v] ++; + + queue q; + for(int u = 0; u < n; u ++) + if(indegrees[u] == 0) q.push(u); + + vector res; + while(!q.empty()){ + if(q.size() > 1) return false; + + int u = q.front(); q.pop(); + res.push_back(u + 1); + for(int v: g[u]){ + indegrees[v] --; + if(indegrees[v] == 0) q.push(v); + } + } + + return res == nums; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0445-Add-Two-Numbers-II/cpp-0445/CMakeLists.txt b/0001-0500/0445-Add-Two-Numbers-II/cpp-0445/CMakeLists.txt new file mode 100644 index 00000000..0b17df6e --- /dev/null +++ b/0001-0500/0445-Add-Two-Numbers-II/cpp-0445/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(cpp_0445) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0445 main3.cpp) \ No newline at end of file diff --git a/0001-0500/0445-Add-Two-Numbers-II/cpp-0445/main.cpp b/0001-0500/0445-Add-Two-Numbers-II/cpp-0445/main.cpp new file mode 100644 index 00000000..c6f10e33 --- /dev/null +++ b/0001-0500/0445-Add-Two-Numbers-II/cpp-0445/main.cpp @@ -0,0 +1,58 @@ +/// Source : https://leetcode.com/problems/add-two-numbers-ii/ +/// Author : liuyubobobo +/// Time : 2019-09-21 + +#include + +using namespace std; + + +/// Using reverse +/// Time Complexity: O(m + n + max(m, n)) +/// Space Complexity: O(1) + +/// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} +}; + +class Solution { +public: + ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { + + l1 = reverse(l1); + l2 = reverse(l2); + ListNode* dummyHead = new ListNode(-1), *cur = dummyHead; + int carry = 0; + for(ListNode* node1 = l1, *node2 = l2; node1 || node2 || carry; + node1 = node1 ? node1->next : NULL, node2 = node2 ? node2->next : NULL){ + + int x = node1 ? node1->val : 0; + x += node2 ? node2->val : 0; + x += carry; + cur->next = new ListNode(x % 10); + cur = cur->next; + carry = x / 10; + } + return reverse(dummyHead->next); + } + +private: + ListNode* reverse(ListNode* node){ + + if(!node->next) return node; + + ListNode* ret = reverse(node->next); + node->next->next = node; + node->next = NULL; + return ret; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0445-Add-Two-Numbers-II/cpp-0445/main2.cpp b/0001-0500/0445-Add-Two-Numbers-II/cpp-0445/main2.cpp new file mode 100644 index 00000000..88a55cf0 --- /dev/null +++ b/0001-0500/0445-Add-Two-Numbers-II/cpp-0445/main2.cpp @@ -0,0 +1,56 @@ +/// Source : https://leetcode.com/problems/add-two-numbers-ii/ +/// Author : liuyubobobo +/// Time : 2019-09-21 + +#include +#include + +using namespace std; + + +/// Using Stack +/// Time Complexity: O(m + n + max(m, n)) +/// Space Complexity: O(m + n) + +/// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} +}; + +class Solution { +public: + ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { + + stack stack1, stack2, stack; + ListNode* node = l1; + while(node) stack1.push(node), node = node->next; + node = l2; + while(node) stack2.push(node), node = node->next; + + int carry = 0; + while(!stack1.empty() || !stack2.empty() || carry){ + + int x = 0; + if(!stack1.empty()) x += stack1.top()->val, stack1.pop(); + if(!stack2.empty()) x += stack2.top()->val, stack2.pop(); + x += carry; + + stack.push(new ListNode(x % 10)); + carry = x / 10; + } + + ListNode* ret = stack.top(), *cur = ret; + stack.pop(); + while(!stack.empty()) + cur->next = stack.top(), cur = cur->next, stack.pop(); + return ret; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0445-Add-Two-Numbers-II/cpp-0445/main3.cpp b/0001-0500/0445-Add-Two-Numbers-II/cpp-0445/main3.cpp new file mode 100644 index 00000000..b8202e01 --- /dev/null +++ b/0001-0500/0445-Add-Two-Numbers-II/cpp-0445/main3.cpp @@ -0,0 +1,79 @@ +/// Source : https://leetcode.com/problems/add-two-numbers-ii/ +/// Author : liuyubobobo +/// Time : 2019-09-21 + +#include +#include + +using namespace std; + + +/// Recursion +/// Time Complexity: O(m + n + max(m, n)) +/// Space Complexity: O(max(m, n)) + +/// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} +}; + +class Solution { +public: + ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { + + int len1 = get_length(l1), len2 = get_length(l2); + int len = max(len1, len2); + + if(len1 != len2){ + ListNode* head = len1 < len2 ? l1 : l2; + for(int i = 0; i < len - min(len1, len2); i ++){ + ListNode* node = new ListNode(0); + node->next = head; + head = node; + } + if(len1 < len2) l1 = head; + else l2 = head; + } + + int carry = 0; + ListNode* res = go(l1, l2, carry); + if(carry){ + ListNode* node = new ListNode(1); + node->next = res; + res = node; + } + return res; + } + +private: + int get_length(ListNode* head){ + + if(!head) return 0; + return 1 + get_length(head->next); + } + + ListNode* go(ListNode* l1, ListNode* l2, int& carry){ + + if(!l1){ + assert(!l2); + carry = 0; + return NULL; + } + + int c = 0; + ListNode* next = go(l1->next, l2->next, c); + int x = l1->val + l2->val + c; + ListNode* res = new ListNode(x % 10); + res->next = next; + carry = x / 10; + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0446-Arithmetic-Slices-II-Subsequence/cpp-0446/CMakeLists.txt b/0001-0500/0446-Arithmetic-Slices-II-Subsequence/cpp-0446/CMakeLists.txt new file mode 100644 index 00000000..77335f26 --- /dev/null +++ b/0001-0500/0446-Arithmetic-Slices-II-Subsequence/cpp-0446/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0446) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0446 main.cpp) \ No newline at end of file diff --git a/0001-0500/0446-Arithmetic-Slices-II-Subsequence/cpp-0446/main.cpp b/0001-0500/0446-Arithmetic-Slices-II-Subsequence/cpp-0446/main.cpp new file mode 100644 index 00000000..37b31404 --- /dev/null +++ b/0001-0500/0446-Arithmetic-Slices-II-Subsequence/cpp-0446/main.cpp @@ -0,0 +1,66 @@ +/// Source : https://leetcode.com/problems/arithmetic-slices-ii-subsequence/ +/// Author : liuyubobobo +/// Time : 2021-02-19 + +#include +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(n^2) +/// Space Complexity: O(n^2) +class Solution { +public: + int numberOfArithmeticSlices(vector& A) { + + int n = A.size(); + if(n < 3) return 0; + + vector> dp(n); + for(int i = 1; i < n; i ++){ + for(int j = i - 1; j >= 0; j --){ + long long d = (long long)A[i] - A[j]; + if(dp[j].count(d)) + dp[i][d] += dp[j][d] + 1; + else + dp[i][d] += 1; +// cout << i << " " << d << " : " << dp[i][d] << endl; + } + } + + int res = 0; + for(int i = 0; i < n; i ++) + for(const pair& p: dp[i]) res += p.second; + + return res - n * (n - 1) / 2; + } +}; + + +int main() { + + vector nums1 = {2, 4, 6, 8, 10}; + cout << Solution().numberOfArithmeticSlices(nums1) << endl; + // 7 + + vector nums2 = {0, 1, 2, 3, 4, 5}; + cout << Solution().numberOfArithmeticSlices(nums2) << endl; + // 12 + + vector nums3 = {2, 2, 3, 4}; + cout << Solution().numberOfArithmeticSlices(nums3) << endl; + // 2 + + vector nums4 = {1, 1, 1, 1}; + cout << Solution().numberOfArithmeticSlices(nums4) << endl; + // 5 + + vector nums5 = {0,2000000000,-294967296}; + cout << Solution().numberOfArithmeticSlices(nums5) << endl; + // 0 + + return 0; +} diff --git a/0447-Number-of-Boomerangs/cpp-0447/CMakeLists.txt b/0001-0500/0447-Number-of-Boomerangs/cpp-0447/CMakeLists.txt similarity index 100% rename from 0447-Number-of-Boomerangs/cpp-0447/CMakeLists.txt rename to 0001-0500/0447-Number-of-Boomerangs/cpp-0447/CMakeLists.txt diff --git a/0001-0500/0447-Number-of-Boomerangs/cpp-0447/main.cpp b/0001-0500/0447-Number-of-Boomerangs/cpp-0447/main.cpp new file mode 100644 index 00000000..d2ea0fbf --- /dev/null +++ b/0001-0500/0447-Number-of-Boomerangs/cpp-0447/main.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/number-of-boomerangs/description/ +/// Author : liuyubobobo +/// Time : 2017-11-15 + +#include +#include +#include +#include +#include + +using namespace std; + +/// Using Hash Map +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { +public: + int numberOfBoomerangs(vector>& points) { + + int res = 0; + for( int i = 0 ; i < points.size() ; i ++ ){ + + // record中存储 点i 到所有其他点的距离出现的频次 + unordered_map record; + for(int j = 0 ; j < points.size() ; j ++) + if(j != i) + // 计算距离时不进行开根运算, 以保证精度 + record[dis(points[i], points[j])] += 1; + + for(unordered_map::iterator iter = record.begin() ; iter != record.end() ; iter ++) + res += (iter->second) * (iter->second - 1); + } + return res; + } + +private: + int dis(const vector &pa, const vector &pb){ + return (pa[0] - pb[0]) * (pa[0] - pb[0]) + + (pa[1] - pb[1]) * (pa[1] - pb[1]); + } +}; + + +int main() { + + vector> vec; + vec.push_back(make_pair(0, 0)); + vec.push_back(make_pair(1, 0)); + vec.push_back(make_pair(2, 0)); + + cout << Solution().numberOfBoomerangs(vec) << endl; + + return 0; +} \ No newline at end of file diff --git a/0447-Number-of-Boomerangs/java-0447/src/Solution.java b/0001-0500/0447-Number-of-Boomerangs/java-0447/src/Solution.java similarity index 100% rename from 0447-Number-of-Boomerangs/java-0447/src/Solution.java rename to 0001-0500/0447-Number-of-Boomerangs/java-0447/src/Solution.java diff --git a/0001-0500/0448-Find-All-Numbers-Disappeared-in-an-Array/cpp-0448/CMakeLists.txt b/0001-0500/0448-Find-All-Numbers-Disappeared-in-an-Array/cpp-0448/CMakeLists.txt new file mode 100644 index 00000000..ba84313d --- /dev/null +++ b/0001-0500/0448-Find-All-Numbers-Disappeared-in-an-Array/cpp-0448/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0448) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0448 main2.cpp) \ No newline at end of file diff --git a/0001-0500/0448-Find-All-Numbers-Disappeared-in-an-Array/cpp-0448/main.cpp b/0001-0500/0448-Find-All-Numbers-Disappeared-in-an-Array/cpp-0448/main.cpp new file mode 100644 index 00000000..47ceef75 --- /dev/null +++ b/0001-0500/0448-Find-All-Numbers-Disappeared-in-an-Array/cpp-0448/main.cpp @@ -0,0 +1,32 @@ +/// Source : https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/ +/// Author : liuyubobobo +/// Time : 2021-02-12 + +#include +#include + +using namespace std; + + +/// Using HashMap +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector findDisappearedNumbers(vector& nums) { + + int n = nums.size(); + vector visited(n + 1, 0); + for(int e: nums) visited[e] ++; + + vector res; + for(int e = 1; e <= n; e ++) if(!visited[e]) res.push_back(e); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0448-Find-All-Numbers-Disappeared-in-an-Array/cpp-0448/main2.cpp b/0001-0500/0448-Find-All-Numbers-Disappeared-in-an-Array/cpp-0448/main2.cpp new file mode 100644 index 00000000..8d40b936 --- /dev/null +++ b/0001-0500/0448-Find-All-Numbers-Disappeared-in-an-Array/cpp-0448/main2.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/ +/// Author : liuyubobobo +/// Time : 2021-02-12 + +#include +#include + +using namespace std; + + +/// Using elements as index +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + vector findDisappearedNumbers(vector& nums) { + + for(int i = 0; i < nums.size(); ) + if(nums[i] > 0){ + int pos = nums[i] - 1; + if(nums[pos] < 0) i ++; + else{ + swap(nums[pos], nums[i]); + nums[pos] = -nums[pos]; + } + } + else i ++; + + vector res; + for(int i = 0; i < nums.size(); i ++) + if(nums[i] > 0) res.push_back(i + 1); + return res; + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << " "; cout << endl; +} + +int main() { + + vector nums1 = {4, 3, 2, 7, 8, 2, 3, 1}; + print_vec(Solution().findDisappearedNumbers(nums1)); + + return 0; +} diff --git a/0001-0500/0449-Serialize-and-Deserialize-BST/cpp-0449/CMakeLists.txt b/0001-0500/0449-Serialize-and-Deserialize-BST/cpp-0449/CMakeLists.txt new file mode 100644 index 00000000..62164d21 --- /dev/null +++ b/0001-0500/0449-Serialize-and-Deserialize-BST/cpp-0449/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_0449) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0449 main.cpp) diff --git a/0001-0500/0449-Serialize-and-Deserialize-BST/cpp-0449/main.cpp b/0001-0500/0449-Serialize-and-Deserialize-BST/cpp-0449/main.cpp new file mode 100644 index 00000000..3023e519 --- /dev/null +++ b/0001-0500/0449-Serialize-and-Deserialize-BST/cpp-0449/main.cpp @@ -0,0 +1,104 @@ +/// Source : https://leetcode.com/problems/serialize-and-deserialize-bst/ +/// Author : liuyubobobo +/// Time : 2022-05-10 + +#include +#include + +using namespace std; + + +/// Same as serialize and deserialize binary tree +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +class Codec { +public: + + // Encodes a tree to a single string. + string serialize(TreeNode* root) { + + if(!root) + return "[null]"; + + string ret = "["; + dfs(root, ret); + ret.pop_back(); + return ret + "]"; + } + + // Decodes your encoded data to tree. + TreeNode* deserialize(string data) { + + vector vec = get_vector(data); + + if(vec.size() == 0 || (vec.size() == 1 && vec[0] == "null")) + return NULL; + +// for(const string& s: vec) +// cout << s << " "; +// cout << endl; + + int index = 0; + return dfs(vec, index); + } + +private: + TreeNode* dfs(const vector& vec, int& index){ + + if(index == vec.size() || vec[index] == "null") + return NULL; + + TreeNode* node = new TreeNode(atoi(vec[index].c_str())); + index ++; + node->left = dfs(vec, index); + + index ++; + node->right = dfs(vec, index); + + return node; + } + + void dfs(TreeNode* node, string& ret){ + + ret += to_string(node->val) + ","; + + if(node->left) + dfs(node->left, ret); + else + ret += "null,"; + + if(node->right) + dfs(node->right, ret); + else + ret += "null,"; + } + + vector get_vector(const string& data){ + + string s = data.substr(1, data.size() - 2) + ","; + + vector res; + int i = 0; + while(i < s.size()){ + int comma = s.find(',', i); + res.push_back(s.substr(i, comma - i)); + i = comma + 1; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0450-Delete-Node-in-a-BST/cpp-0450/CMakeLists.txt b/0001-0500/0450-Delete-Node-in-a-BST/cpp-0450/CMakeLists.txt new file mode 100644 index 00000000..b4860924 --- /dev/null +++ b/0001-0500/0450-Delete-Node-in-a-BST/cpp-0450/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(cpp_0450) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0450 main.cpp) \ No newline at end of file diff --git a/0001-0500/0450-Delete-Node-in-a-BST/cpp-0450/main.cpp b/0001-0500/0450-Delete-Node-in-a-BST/cpp-0450/main.cpp new file mode 100644 index 00000000..5b2e5b70 --- /dev/null +++ b/0001-0500/0450-Delete-Node-in-a-BST/cpp-0450/main.cpp @@ -0,0 +1,68 @@ +/// Source : https://leetcode.com/problems/delete-node-in-a-bst/ +/// Author : liuyubobobo +/// Time : 2019-04-30 + +#include + +using namespace std; + + +/// Recursion +/// Time Complexity: O(logn) +/// Space Complexity: O(h) + +/// 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* deleteNode(TreeNode* root, int key) { + + if(!root) + return NULL; + + if(key < root->val){ + root->left = deleteNode(root->left, key); + return root; + } + + if(key > root->val){ + root->right = deleteNode(root->right, key); + return root; + } + + if(!root->right) return root->left; + + if(!root->left) return root->right; + + TreeNode* p = root, *minnode = root->right; + while(minnode->left){ + p = minnode; + minnode = minnode->left; + } + + root->val = minnode->val; + root->right = deleteMinNode(root->right); + return root; + } + +private: + TreeNode* deleteMinNode(TreeNode* root){ + + if(!root->left) return root->right; + root->left = deleteMinNode(root->left); + return root; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/old/0451 Sort Characters By Frequency/cpp-Sort-Characters-By-Frequency/CMakeLists.txt b/0001-0500/0451-Sort-Characters-By-Frequency/cpp-0451/CMakeLists.txt similarity index 100% rename from old/0451 Sort Characters By Frequency/cpp-Sort-Characters-By-Frequency/CMakeLists.txt rename to 0001-0500/0451-Sort-Characters-By-Frequency/cpp-0451/CMakeLists.txt diff --git a/0001-0500/0451-Sort-Characters-By-Frequency/cpp-0451/main.cpp b/0001-0500/0451-Sort-Characters-By-Frequency/cpp-0451/main.cpp new file mode 100644 index 00000000..327a2b6c --- /dev/null +++ b/0001-0500/0451-Sort-Characters-By-Frequency/cpp-0451/main.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/sort-characters-by-frequency/ +/// Author : liuyubobobo +/// Time : 2017-01-17 + +#include + +using namespace std; + +/// Sorting +/// Time Complexity: O(n) +/// Space Complexity: O(256) +class Solution { +public: + string frequencySort(string s) { + + pair freq[256]; + for(int i = 0 ; i < 256 ; i ++){ + freq[i].first = 0; + freq[i].second = i; + } + + for(int i = 0 ; i < s.size() ; i ++) + freq[s[i]].first ++; + + sort(freq, freq + 256, greater>()); + + int index = 0; + for(int i = 0 ; i < s.size() ; i ++){ + while(!freq[index].first) + index ++; + s[i] = freq[index].second; + freq[index].first --; + } + + return s; + } +}; + + +int main() { + + cout << Solution().frequencySort("tree") << endl; + cout << Solution().frequencySort("cccaaa") << endl; + cout << Solution().frequencySort("Aabb") << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0451-Sort-Characters-By-Frequency/java-0451/src/Solution.java b/0001-0500/0451-Sort-Characters-By-Frequency/java-0451/src/Solution.java new file mode 100644 index 00000000..237b771b --- /dev/null +++ b/0001-0500/0451-Sort-Characters-By-Frequency/java-0451/src/Solution.java @@ -0,0 +1,48 @@ +/// Source : https://leetcode.com/problems/sort-characters-by-frequency/ +/// Author : liuyubobobo +/// Time : 2020-02-27 + +import java.util.ArrayList; +import java.util.Collections; + + +/// Sorting +/// Time Complexity: O(nlogn) +/// Space Complexity: O(256) +class Solution { + + private class Pair implements Comparable{ + + public char c; + public int f; + + public Pair(char c, int f){ + this.c = c; + this.f = f; + } + + @Override + public int compareTo(Pair another){ + return another.f - this.f; + } + } + + public String frequencySort(String s) { + + int[] freq = new int[256]; + for(char c: s.toCharArray()) + freq[c] ++; + + ArrayList lst = new ArrayList<>(); + for(char c = 0; c < 256; c ++) + if(freq[c] != 0) + lst.add(new Pair(c, freq[c])); + + Collections.sort(lst); + + StringBuilder sb = new StringBuilder(); + for(Pair p: lst) + for(int i = 0; i < p.f; i ++) sb.append(p.c); + return sb.toString(); + } +} \ No newline at end of file diff --git a/0001-0500/0452-Minimum-Number-of-Arrows-to-Burst-Balloons/cpp-0452/CMakeLists.txt b/0001-0500/0452-Minimum-Number-of-Arrows-to-Burst-Balloons/cpp-0452/CMakeLists.txt new file mode 100644 index 00000000..4d18763f --- /dev/null +++ b/0001-0500/0452-Minimum-Number-of-Arrows-to-Burst-Balloons/cpp-0452/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0452) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0452 main.cpp) diff --git a/0001-0500/0452-Minimum-Number-of-Arrows-to-Burst-Balloons/cpp-0452/main.cpp b/0001-0500/0452-Minimum-Number-of-Arrows-to-Burst-Balloons/cpp-0452/main.cpp new file mode 100644 index 00000000..013c5cf2 --- /dev/null +++ b/0001-0500/0452-Minimum-Number-of-Arrows-to-Burst-Balloons/cpp-0452/main.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/ +/// Author : liuyubobobo +/// Time : 2021-09-06 + +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + int findMinArrowShots(vector>& points) { + + sort(points.begin(), points.end()); + pair cur = {points[0][0], points[0][1]}; + + int res = 0; + for(int i = 1; i < points.size(); i ++){ + vector p = points[i]; + if(p[0] > cur.second) res ++, cur = {p[0], p[1]}; + else cur.first = min(cur.first, p[0]), cur.second = min(cur.second, p[1]); + } + res ++; + return res; + } +}; + + +int main() { + + vector> points1 = {{10, 16}, {2, 8}, {1, 6}, {7, 12}}; + cout << Solution().findMinArrowShots(points1) << endl; + // 2 + + return 0; +} diff --git a/0001-0500/0453-Minimum-Moves-to-Equal-Array-Elements/cpp-0453/CMakeLists.txt b/0001-0500/0453-Minimum-Moves-to-Equal-Array-Elements/cpp-0453/CMakeLists.txt new file mode 100644 index 00000000..0c433895 --- /dev/null +++ b/0001-0500/0453-Minimum-Moves-to-Equal-Array-Elements/cpp-0453/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_0453) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0453 main.cpp) \ No newline at end of file diff --git a/0001-0500/0453-Minimum-Moves-to-Equal-Array-Elements/cpp-0453/main.cpp b/0001-0500/0453-Minimum-Moves-to-Equal-Array-Elements/cpp-0453/main.cpp new file mode 100644 index 00000000..39784eae --- /dev/null +++ b/0001-0500/0453-Minimum-Moves-to-Equal-Array-Elements/cpp-0453/main.cpp @@ -0,0 +1,44 @@ +/// Source : https://leetcode.com/problems/minimum-moves-to-equal-array-elements/ +/// Author : liuyubobobo +/// Time : 2021-05-19 + +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int minMoves(vector& nums) { + + long long sum = 0ll, n = nums.size(), minv = nums[0]; + + for(long long e: nums){ + sum += e; + minv = min(minv, e); + } + return sum - minv * n; + } +}; + + +int main() { + + vector nums1 = {1, 2, 3}; + cout << Solution().minMoves(nums1) << endl; + // 3 + + vector nums2 = {1, 2}; + cout << Solution().minMoves(nums2) << endl; + // 1 + + vector nums3 = {1, (int)1e9}; + cout << Solution().minMoves(nums3) << endl; + // 999999999 + + return 0; +} diff --git a/0454-4Sum-II/cpp-0454/CMakeLists.txt b/0001-0500/0454-4Sum-II/cpp-0454/CMakeLists.txt similarity index 100% rename from 0454-4Sum-II/cpp-0454/CMakeLists.txt rename to 0001-0500/0454-4Sum-II/cpp-0454/CMakeLists.txt diff --git a/0454-4Sum-II/cpp-0454/main.cpp b/0001-0500/0454-4Sum-II/cpp-0454/main.cpp similarity index 100% rename from 0454-4Sum-II/cpp-0454/main.cpp rename to 0001-0500/0454-4Sum-II/cpp-0454/main.cpp diff --git a/0454-4Sum-II/cpp-0454/main2.cpp b/0001-0500/0454-4Sum-II/cpp-0454/main2.cpp similarity index 100% rename from 0454-4Sum-II/cpp-0454/main2.cpp rename to 0001-0500/0454-4Sum-II/cpp-0454/main2.cpp diff --git a/0454-4Sum-II/java-0454/src/Solution1.java b/0001-0500/0454-4Sum-II/java-0454/src/Solution1.java similarity index 100% rename from 0454-4Sum-II/java-0454/src/Solution1.java rename to 0001-0500/0454-4Sum-II/java-0454/src/Solution1.java diff --git a/0454-4Sum-II/java-0454/src/Solution2.java b/0001-0500/0454-4Sum-II/java-0454/src/Solution2.java similarity index 100% rename from 0454-4Sum-II/java-0454/src/Solution2.java rename to 0001-0500/0454-4Sum-II/java-0454/src/Solution2.java diff --git a/0455-Assign-Cookies/cpp-0455/CMakeLists.txt b/0001-0500/0455-Assign-Cookies/cpp-0455/CMakeLists.txt similarity index 100% rename from 0455-Assign-Cookies/cpp-0455/CMakeLists.txt rename to 0001-0500/0455-Assign-Cookies/cpp-0455/CMakeLists.txt diff --git a/0455-Assign-Cookies/cpp-0455/main.cpp b/0001-0500/0455-Assign-Cookies/cpp-0455/main.cpp similarity index 100% rename from 0455-Assign-Cookies/cpp-0455/main.cpp rename to 0001-0500/0455-Assign-Cookies/cpp-0455/main.cpp diff --git a/0455-Assign-Cookies/cpp-0455/main2.cpp b/0001-0500/0455-Assign-Cookies/cpp-0455/main2.cpp similarity index 100% rename from 0455-Assign-Cookies/cpp-0455/main2.cpp rename to 0001-0500/0455-Assign-Cookies/cpp-0455/main2.cpp diff --git a/0455-Assign-Cookies/java-0455/src/Solution.java b/0001-0500/0455-Assign-Cookies/java-0455/src/Solution.java similarity index 100% rename from 0455-Assign-Cookies/java-0455/src/Solution.java rename to 0001-0500/0455-Assign-Cookies/java-0455/src/Solution.java diff --git a/0455-Assign-Cookies/java-0455/src/Solution2.java b/0001-0500/0455-Assign-Cookies/java-0455/src/Solution2.java similarity index 100% rename from 0455-Assign-Cookies/java-0455/src/Solution2.java rename to 0001-0500/0455-Assign-Cookies/java-0455/src/Solution2.java diff --git a/0001-0500/0456-132-Pattern/cpp-0456/CMakeLists.txt b/0001-0500/0456-132-Pattern/cpp-0456/CMakeLists.txt new file mode 100644 index 00000000..4b38ad49 --- /dev/null +++ b/0001-0500/0456-132-Pattern/cpp-0456/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0456) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0456 main.cpp) \ No newline at end of file diff --git a/0001-0500/0456-132-Pattern/cpp-0456/main.cpp b/0001-0500/0456-132-Pattern/cpp-0456/main.cpp new file mode 100644 index 00000000..69be15bf --- /dev/null +++ b/0001-0500/0456-132-Pattern/cpp-0456/main.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/132-pattern/ +/// Author : liuyubobobo +/// Time : 2021-03-23 +/// Updated: 2022-05-24 + +#include +#include +#include + +using namespace std; + + +/// Reverse to find 32-pattern first and greedily check 1-part +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + bool find132pattern(vector& nums) { + + int n = nums.size(); + if(n <= 2) return false; + + set> s; + s.insert(nums[n - 1]); + s.insert(nums[n - 2]); + int t = nums[n - 2] > nums[n - 1] ? nums[n - 1] : INT_MIN; + + for(int i = n - 3; i >= 0; i --){ + if(nums[i] < t) return true; + + auto iter = s.upper_bound(nums[i]); + if(iter != s.end()) + t = max(t, *iter); + s.insert(nums[i]); + } + + return false; + } +}; + + +int main() { + + vector nums1 = {1, 2, 3, 4}; + cout << Solution().find132pattern(nums1) << endl; + // 0 + + vector nums2 = {1, 0, 1, -4, -3}; + cout << Solution().find132pattern(nums2) << endl; + // 0 + + vector nums3 = {1, 3, 2, 4, 5}; + cout << Solution().find132pattern(nums3) << endl; + // 1 + + return 0; +} diff --git a/0001-0500/0457-Circular-Array-Loop/cpp-0457/CMakeLists.txt b/0001-0500/0457-Circular-Array-Loop/cpp-0457/CMakeLists.txt new file mode 100644 index 00000000..86357786 --- /dev/null +++ b/0001-0500/0457-Circular-Array-Loop/cpp-0457/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0457) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0457 main.cpp) diff --git a/0001-0500/0457-Circular-Array-Loop/cpp-0457/main.cpp b/0001-0500/0457-Circular-Array-Loop/cpp-0457/main.cpp new file mode 100644 index 00000000..26812597 --- /dev/null +++ b/0001-0500/0457-Circular-Array-Loop/cpp-0457/main.cpp @@ -0,0 +1,83 @@ +/// Source : https://leetcode.com/problems/circular-array-loop/ +/// Author : liuyubobobo +/// Time : 2021-08-06 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + bool circularArrayLoop(vector& nums) { + + int n = nums.size(); + vector visited(n, false); + vector dp(n, -1); + + bool positive; + for(int i = 0; i < nums.size(); i ++) + if(dp[i] == -1){ + positive = nums[i] > 0; + visited.assign(n, false); + visited[i] = true; + for(int j = ((i + nums[i]) % n + n) % n;;j = ((j + nums[j]) % n + n) % n) + if(dp[j] == 0) break; + else if(j == ((j + nums[j]) % n + n) % n) break; + else if(positive != nums[j] > 0) break; + else if(visited[j]) return true; + else visited[j] = true; + + dp[i] = 0; + visited[i] = false; + for(int j = ((i + nums[i]) % n + n) % n; ;j = ((j + nums[j]) % n + n) % n){ + if(!visited[j]) break; + visited[j] = false; + dp[j] = 0; + } + } + return false; + } +}; + + +int main() { + + vector nums1 = {2, -1, 1, 2, 2}; + cout << Solution().circularArrayLoop(nums1) << endl; + // true + + vector nums2 = {-1, 2}; + cout << Solution().circularArrayLoop(nums2) << endl; + // false + + vector nums3 = {-2, 1, -1, -2, -2}; + cout << Solution().circularArrayLoop(nums3) << endl; + // false + + vector nums4 = {2, -1, 1, -2, -2}; + cout << Solution().circularArrayLoop(nums4) << endl; + // false + + vector nums5 = {1, 1, 2}; + cout << Solution().circularArrayLoop(nums5) << endl; + // true + + vector nums6 = {2, 2, 2, 2, 2, 4, 7}; + cout << Solution().circularArrayLoop(nums6) << endl; + // false + + vector nums7 = {-2, 1, -1, -2, -2}; + cout << Solution().circularArrayLoop(nums7) << endl; + // false + + vector nums8 = {-2, -3, -9}; + cout << Solution().circularArrayLoop(nums8) << endl; + // false + + return 0; +} diff --git a/0001-0500/0458-Poor-Pigs/cpp-0458/CMakeLists.txt b/0001-0500/0458-Poor-Pigs/cpp-0458/CMakeLists.txt new file mode 100644 index 00000000..f543e352 --- /dev/null +++ b/0001-0500/0458-Poor-Pigs/cpp-0458/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(cpp_0458) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0458 main.cpp) \ No newline at end of file diff --git a/0001-0500/0458-Poor-Pigs/cpp-0458/main.cpp b/0001-0500/0458-Poor-Pigs/cpp-0458/main.cpp new file mode 100644 index 00000000..1f5fd319 --- /dev/null +++ b/0001-0500/0458-Poor-Pigs/cpp-0458/main.cpp @@ -0,0 +1,32 @@ +/// Source : https://leetcode.com/problems/poor-pigs/ +/// Author : liuyubobobo +/// Time : 2019-05-02 + +#include +#include + +using namespace std; + + +/// Mathematics +/// A better explanation than official solution if here: +/// https://leetcode.com/problems/poor-pigs/discuss/94266/Another-explanation-and-solution +/// +/// Time Complexity: O(log(buckets)) +/// Space Complexity: O(1) +class Solution { +public: + int poorPigs(int buckets, int minutesToDie, int minutesToTest) { + + int res = 0; + while((int)pow(minutesToTest / minutesToDie + 1, res) < buckets) + res ++; + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0459-Repeated-Substring-Pattern/cpp-0459/CMakeLists.txt b/0001-0500/0459-Repeated-Substring-Pattern/cpp-0459/CMakeLists.txt new file mode 100644 index 00000000..64f48c06 --- /dev/null +++ b/0001-0500/0459-Repeated-Substring-Pattern/cpp-0459/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_0459) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_0459 main.cpp) diff --git a/0001-0500/0459-Repeated-Substring-Pattern/cpp-0459/main.cpp b/0001-0500/0459-Repeated-Substring-Pattern/cpp-0459/main.cpp new file mode 100644 index 00000000..565e9e81 --- /dev/null +++ b/0001-0500/0459-Repeated-Substring-Pattern/cpp-0459/main.cpp @@ -0,0 +1,43 @@ +/// Source : https://leetcode.com/problems/repeated-substring-pattern/description/ +/// Author : liuyubobobo +/// Time : 2023-08-21 + +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(sqrt(n) * n) +/// Space Complexity: O(n) +class Solution { +public: + bool repeatedSubstringPattern(string s) { + + int n = s.size(); + if(n == 1) return false; + for(int i = 1; i * i <= n; i ++){ + if(n % i) continue; + + if(ok(n, s, i)) return true; + + if(i * i == n || i == 1) continue; + if(ok(n, s, n / i)) return true; + } + return false; + } + +private: + bool ok(int n, const string& s, int len){ + string subs = s.substr(0, len); + for(int i = len; i <= n - len; i += len) + if(s.substr(i, len) != subs) return false; + return true; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0460-LFU-Cache/cpp-0460/CMakeLists.txt b/0001-0500/0460-LFU-Cache/cpp-0460/CMakeLists.txt new file mode 100644 index 00000000..1cdb4aa5 --- /dev/null +++ b/0001-0500/0460-LFU-Cache/cpp-0460/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_0460) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_0460 main.cpp) diff --git a/0001-0500/0460-LFU-Cache/cpp-0460/main.cpp b/0001-0500/0460-LFU-Cache/cpp-0460/main.cpp new file mode 100644 index 00000000..b7cfdb61 --- /dev/null +++ b/0001-0500/0460-LFU-Cache/cpp-0460/main.cpp @@ -0,0 +1,90 @@ +/// Source : https://leetcode.com/problems/lfu-cache/description/ +/// Author : liuyubobobo +/// Time : 2023-01-28 + +#include +#include +#include + +using namespace std; + + +/// Using Map +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class LFUCache { + +private: + map cache; // key->value + map> f; // key->{f, timer} + map, int> f2; // {f, timer}->key + int capacity, timer; + +public: + LFUCache(int capacity) : capacity(capacity), timer(0) {} + + int get(int key) { + auto iter = cache.find(key); + if(iter == cache.end()) return -1; + + assert(f.count(key)); + pair old_f = f[key]; + pair new_f = {old_f.first + 1, timer ++}; + f[key] = new_f; + + assert(f2.count(old_f)); + f2.erase(old_f); + f2[new_f] = key; + + return iter->second; + } + + void put(int key, int value) { + + auto iter = cache.find(key); + if(iter != cache.end()){ + update(key, value); + return; + } + + if(cache.size() == capacity){ + pair del_f = f2.begin()->first; + int key = f2[del_f]; + + cache.erase(key); + f.erase(key); + f2.erase(f2.begin()); + } + + if(cache.size() < capacity){ + cache[key] = value; + pair new_f = {1, timer ++}; + f[key] = new_f; + f2[new_f] = key; + } + } + +private: + void update(int key, int value){ + + auto iter = cache.find(key); + assert(iter != cache.end()); + + assert(f.count(key)); + pair old_f = f[key]; + pair new_f = {old_f.first + 1, timer ++}; + f[key] = new_f; + + assert(f2.count(old_f)); + f2.erase(old_f); + f2[new_f] = key; + + cache[key] = value; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0461-Hamming-Distance/cpp-0461/CMakeLists.txt b/0001-0500/0461-Hamming-Distance/cpp-0461/CMakeLists.txt new file mode 100644 index 00000000..fe9a4094 --- /dev/null +++ b/0001-0500/0461-Hamming-Distance/cpp-0461/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_0461) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0461 main.cpp) \ No newline at end of file diff --git a/0001-0500/0461-Hamming-Distance/cpp-0461/main.cpp b/0001-0500/0461-Hamming-Distance/cpp-0461/main.cpp new file mode 100644 index 00000000..bb892dc9 --- /dev/null +++ b/0001-0500/0461-Hamming-Distance/cpp-0461/main.cpp @@ -0,0 +1,31 @@ +/// Source : https://leetcode.com/problems/hamming-distance/ +/// Author : liuyubobobo +/// Time : 2021-05-26 + +#include + +using namespace std; + + +/// bitwise +/// Time Complexity: O(log(max(x, y))) +/// Space Complexity: O(1) +class Solution { +public: + int hammingDistance(int x, int y) { + + int res = 0; + while(x | y){ + res += (x & 1) ^ (y & 1); + x >>= 1; + y >>= 1; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0462-Minimum-Moves-to-Equal-Array-Elements-II/cpp-0462/CMakeLists.txt b/0001-0500/0462-Minimum-Moves-to-Equal-Array-Elements-II/cpp-0462/CMakeLists.txt new file mode 100644 index 00000000..25394531 --- /dev/null +++ b/0001-0500/0462-Minimum-Moves-to-Equal-Array-Elements-II/cpp-0462/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_0462) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0462 main.cpp) \ No newline at end of file diff --git a/0001-0500/0462-Minimum-Moves-to-Equal-Array-Elements-II/cpp-0462/main.cpp b/0001-0500/0462-Minimum-Moves-to-Equal-Array-Elements-II/cpp-0462/main.cpp new file mode 100644 index 00000000..9d5a5cc7 --- /dev/null +++ b/0001-0500/0462-Minimum-Moves-to-Equal-Array-Elements-II/cpp-0462/main.cpp @@ -0,0 +1,31 @@ +/// Source : https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii/ +/// Author : liuyubobobo +/// Time : 2021-05-19 + +#include +#include + +using namespace std; + + +/// Mathematics +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + int minMoves2(vector& nums) { + + sort(nums.begin(), nums.end()); + int a = nums[nums.size() / 2]; + + int res = 0; + for(int e: nums) res += abs(e - a); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0463-Island-Perimeter/cpp-0463/CMakeLists.txt b/0001-0500/0463-Island-Perimeter/cpp-0463/CMakeLists.txt new file mode 100644 index 00000000..1bc260ef --- /dev/null +++ b/0001-0500/0463-Island-Perimeter/cpp-0463/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0463) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0463 main.cpp) diff --git a/0001-0500/0463-Island-Perimeter/cpp-0463/main.cpp b/0001-0500/0463-Island-Perimeter/cpp-0463/main.cpp new file mode 100644 index 00000000..47068d06 --- /dev/null +++ b/0001-0500/0463-Island-Perimeter/cpp-0463/main.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/island-perimeter/ +/// Author : liuyubobobo +/// Time : 2021-10-03 + +#include +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(R * C) +/// Space Complexity: O(1) +class Solution { + +private: + const int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + int R, C; + +public: + int islandPerimeter(vector>& grid) { + + R = grid.size(), C = grid[0].size(); + int res = 0; + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++){ + if(grid[i][j] == 0) continue; + for(int d = 0; d < 4; d ++){ + int nx = i + dirs[d][0], ny = j + dirs[d][1]; + if(!in_area(nx, ny) || grid[nx][ny] == 0) res ++; + } + } + return res; + } + +private: + bool in_area(int x, int y){ + return x >= 0 && x < R && y >= 0 && y < C; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0464-Can-I-Win/cpp-0464/CMakeLists.txt b/0001-0500/0464-Can-I-Win/cpp-0464/CMakeLists.txt new file mode 100644 index 00000000..2af1584f --- /dev/null +++ b/0001-0500/0464-Can-I-Win/cpp-0464/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_0464) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0464 main.cpp) diff --git a/0001-0500/0464-Can-I-Win/cpp-0464/main.cpp b/0001-0500/0464-Can-I-Win/cpp-0464/main.cpp new file mode 100644 index 00000000..91a2d2be --- /dev/null +++ b/0001-0500/0464-Can-I-Win/cpp-0464/main.cpp @@ -0,0 +1,87 @@ +/// Source : https://leetcode.com/problems/can-i-win/ +/// Author : liuyubobobo +/// Time : 2022-05-24 + +#include +#include +#include +#include + +using namespace std; + + +/// Memoization +/// Time Complexity: O(2^M * M * desiredTotal) +/// Space Complexity: O(2^M * desiredTotal) +class Solution { +public: + bool canIWin(int maxChoosableInteger, int desiredTotal) { + + if(desiredTotal == 0) return true; + + int total = (maxChoosableInteger + 1) * maxChoosableInteger / 2; + + // -1: not calculated + // 0: can not get + // 1: lose + // 2: win + unordered_map dp; + return win(desiredTotal, (1 << maxChoosableInteger) - 1, maxChoosableInteger, total, dp) == 2; + } + +private: + int win(int need, int state, int M, int total, unordered_map& dp){ + + if(need <= 0) return 1; + if(total < need) return 0; + + long long hash = (1ll << M) * need + state; + auto iter = dp.find(hash); + if(iter != dp.end()) return iter->second; + + int w = 0, all = 0; + for(int i = M; i >= 1; i --) + if((state & (1 << (i - 1)))){ + all ++; + int tres = win(need - i, state - (1 << (i - 1)), M, total - i, dp); + if(tres == 1) return dp[hash] = 2; + + w += (tres == 2); + } + + return dp[hash] = (all && w == all); + } +}; + + +int main() { + + cout << Solution().canIWin(10, 11) << '\n'; + // 0 + + cout << Solution().canIWin(10, 0) << '\n'; + // 1 + + cout << Solution().canIWin(10, 1) << '\n'; + // 1 + + cout << Solution().canIWin(5, 50) << '\n'; + // 0 + + cout << Solution().canIWin(20, 209) << '\n'; + // 0 + + cout << Solution().canIWin(20, 300) << '\n'; + // 0 + + cout << Solution().canIWin(12, 49) << '\n'; + // 1 + + cout << Solution().canIWin(6, 16) << '\n'; + // 1 + + cout << Solution().canIWin(20, 152) << '\n'; + // 0 + + return 0; +} diff --git a/0001-0500/0467-Unique-Substrings-in-Wraparound-String/cpp-0467/CMakeLists.txt b/0001-0500/0467-Unique-Substrings-in-Wraparound-String/cpp-0467/CMakeLists.txt new file mode 100644 index 00000000..d1f5331f --- /dev/null +++ b/0001-0500/0467-Unique-Substrings-in-Wraparound-String/cpp-0467/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_0467) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0467 main.cpp) diff --git a/0001-0500/0467-Unique-Substrings-in-Wraparound-String/cpp-0467/main.cpp b/0001-0500/0467-Unique-Substrings-in-Wraparound-String/cpp-0467/main.cpp new file mode 100644 index 00000000..c0070e26 --- /dev/null +++ b/0001-0500/0467-Unique-Substrings-in-Wraparound-String/cpp-0467/main.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/unique-substrings-in-wraparound-string/ +/// Author : liuyubobobo +/// Time : 2022-05-24 + +#include +#include +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(1) +/// Space Complexity: O(1) +class Solution { +public: + int findSubstringInWraproundString(string p) { + + vector len(26, 0); + for(int start = 0, i = 1; i <= p.size(); i ++) + if(i == p.size() || ((p[start] - 'a') + (i - start)) % 26 != (p[i] - 'a')){ + + int l = i - start; + for(int j = start; j < i; j ++) + len[p[j] - 'a'] = max(len[p[j] - 'a'], l --); + start = i; + } + + return accumulate(len.begin(), len.end(), 0); + } +}; + + +int main() { + + cout << Solution().findSubstringInWraproundString("a") << '\n'; + // 1 + + cout << Solution().findSubstringInWraproundString("cac") << '\n'; + // 2 + + cout << Solution().findSubstringInWraproundString("zab") << '\n'; + // 6 + + return 0; +} diff --git a/0001-0500/0468-Validate-IP-Address/cpp-0468/CMakeLists.txt b/0001-0500/0468-Validate-IP-Address/cpp-0468/CMakeLists.txt new file mode 100644 index 00000000..04efb57c --- /dev/null +++ b/0001-0500/0468-Validate-IP-Address/cpp-0468/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_0468) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0468 main.cpp) diff --git a/0001-0500/0468-Validate-IP-Address/cpp-0468/main.cpp b/0001-0500/0468-Validate-IP-Address/cpp-0468/main.cpp new file mode 100644 index 00000000..66079cfe --- /dev/null +++ b/0001-0500/0468-Validate-IP-Address/cpp-0468/main.cpp @@ -0,0 +1,85 @@ +/// Source : https://leetcode.com/problems/validate-ip-address/ +/// Author : liuyubobobo +/// Time : 2021-05-28 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + string validIPAddress(string queryIP) { + + vector v; + if(queryIP.find('.') != string:: npos) + v = split_ip(queryIP, '.'); + + if(queryIP.find(':') != string:: npos) + v = split_ip(queryIP, ':'); + + if(v.size() == 4 && isIPv4(v)) return "IPv4"; + if(v.size() == 8 && isIPv6(v)) return "IPv6"; + return "Neither"; + } + +private: + vector split_ip(const string& ip, char split_char){ + + if(ip[0] == split_char || ip.back() == split_char) return {}; + + vector v; + for(int start = 0, i = 1; i <= ip.size(); i ++) + if(i == ip.size() || ip[i] == split_char){ + v.push_back(ip.substr(start, i - start)); + start = i + 1; + i = start; + } + return v; + } + + bool isIPv4(const vector& v){ + for(const string& s: v) + if(!ipv4_seg(s)) return false; + return true; + } + + bool ipv4_seg(const string& s){ + + if(s == "0") return true; + if(s[0] == '0') return false; + if(s.size() > 3) return false; + + for(char c: s) if(!isdigit(c)) return false; + + int x = atoi(s.c_str()); + return 0 <= x && x <= 255; + } + + bool isIPv6(const vector& v){ + for(const string& s: v) + if(!ipv6_seg(s)) return false; + return true; + } + + bool ipv6_seg(const string& s){ + + if(s == "0") return true; + if(s.size() > 4) return false; + + for(char c: s) + if(!(isdigit(c) || ('a' <= c && c <= 'f') || ('A' <= c && c <= 'F'))) + return false; + return true; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0470-Implement-Rand10-Using-Rand7/cpp-0470/CMakeLists.txt b/0001-0500/0470-Implement-Rand10-Using-Rand7/cpp-0470/CMakeLists.txt new file mode 100644 index 00000000..610389d9 --- /dev/null +++ b/0001-0500/0470-Implement-Rand10-Using-Rand7/cpp-0470/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0872) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main2.cpp) +add_executable(cpp_0872 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0470-Implement-Rand10-Using-Rand7/cpp-0470/main.cpp b/0001-0500/0470-Implement-Rand10-Using-Rand7/cpp-0470/main.cpp new file mode 100644 index 00000000..ae8ddbf7 --- /dev/null +++ b/0001-0500/0470-Implement-Rand10-Using-Rand7/cpp-0470/main.cpp @@ -0,0 +1,41 @@ +/// Source : https://leetcode.com/problems/implement-rand10-using-rand7/description/ +/// Author : liuyubobobo +/// Time : 2018-07-16 + +#include +#include + +using namespace std; + +// The rand7() API is already defined for you. +// int rand7(); +// @return a random integer in the range 1 to 7 +int rand7(){ + return rand() % 7 + 1; +} + +/// Rejection Sampling +/// The accurate expectation for calling number of rand7() can be seen here: +/// https://leetcode.com/problems/implement-rand10-using-rand7/solution/ +/// +/// Time Complexity: O(1) +/// Space Complexity: O(1) +class Solution { +public: + int rand10() { + do{ + int randNum = 7 * (rand7() - 1) + rand7() - 1; + if(randNum <= 39) + return randNum % 10 + 1; + }while(true); + + assert(false); + return -1; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0470-Implement-Rand10-Using-Rand7/cpp-0470/main2.cpp b/0001-0500/0470-Implement-Rand10-Using-Rand7/cpp-0470/main2.cpp new file mode 100644 index 00000000..f06e06a6 --- /dev/null +++ b/0001-0500/0470-Implement-Rand10-Using-Rand7/cpp-0470/main2.cpp @@ -0,0 +1,48 @@ +/// Source : https://leetcode.com/problems/implement-rand10-using-rand7/description/ +/// Author : liuyubobobo +/// Time : 2018-08-05 + +#include +#include + +using namespace std; + +// The rand7() API is already defined for you. +// int rand7(); +// @return a random integer in the range 1 to 7 +int rand7(){ + return rand() % 7 + 1; +} + +/// Rejection Sampling improved +/// Utilizing out-of-range-samples +/// The accurate expectation for calling number of rand7() can be seen here: +/// https://leetcode.com/problems/implement-rand10-using-rand7/solution/ +/// +/// Time Complexity: O(1) +/// Space Complexity: O(1) +class Solution { +public: + int rand10() { + int a = -1, b = rand7(), M = 7; + do{ + a = b; + b = rand7(); + int randNum = 7 * (a - 1) + b - 1; + int largest = 7 * (M - 1) + 7 - 1; + M = largest % 10 + 1; + if(randNum < largest - largest % 10) + return randNum % 10 + 1; + b = randNum % 10 + 1; + }while(true); + + assert(false); + return -1; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0472-Concatenated-Words/cpp-0472/CMakeLists.txt b/0001-0500/0472-Concatenated-Words/cpp-0472/CMakeLists.txt new file mode 100644 index 00000000..913b14fb --- /dev/null +++ b/0001-0500/0472-Concatenated-Words/cpp-0472/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_0472) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0472 main.cpp) diff --git a/0001-0500/0472-Concatenated-Words/cpp-0472/main.cpp b/0001-0500/0472-Concatenated-Words/cpp-0472/main.cpp new file mode 100644 index 00000000..678f9d7c --- /dev/null +++ b/0001-0500/0472-Concatenated-Words/cpp-0472/main.cpp @@ -0,0 +1,103 @@ +/// Source : https://leetcode.com/problems/concatenated-words/ +/// Author : liuyubobobo +/// Time : 2021-12-29 + +#include +#include +#include + +using namespace std; + + +/// Sorting + Trie +/// Time Complexity: O(n * |s|^2) +/// Space Complexity: O(n * |s|) +class Trie { + +private: + class Node{ + + public: + vector next; + bool is_word = false; + + Node() : next(26, nullptr) {}; + }; + + Node* root; + const int NEG_INF = -1000000; + +public: + Trie() : root(new Node()) {} + + void insert(const string& word) { + + Node* cur = root; + for(char c: word){ + if(cur->next[c - 'a'] == nullptr) + cur->next[c - 'a'] = new Node(); + cur = cur->next[c - 'a']; + } + cur->is_word = true; + } + + bool ok(const string& s){ + return query(root, s, 0) >= 2; + } + +private: + int query(Node* node, const string& s, int index) { + + if(index == s.size()) + return (node && node->is_word) ? 1 : NEG_INF; + + int res = NEG_INF; + if(node->next[s[index] - 'a']) + res = max(res, query(node->next[s[index] - 'a'], s, index + 1)); + + if(node->is_word) + res = max(res, 1 + query(root, s, index)); + + return res; + } +}; + +class Solution { +public: + vector findAllConcatenatedWordsInADict(vector& words) { + + sort(words.begin(), words.end(), [](const string& s1, const string& s2){ + return s1.size() < s2.size(); + }); + + Trie trie; + vector res; + for(const string& s: words) { + if(s == "") continue; + else if(trie.ok(s)) res.push_back(s); + else trie.insert(s); + } + return res; + } +}; + + +void print_vec(const vector& res){ + for(const string& e: res) cout << e << ' '; cout << '\n'; +} + +int main() { + + vector words1 = {"cat","cats","catsdogcats","dog","dogcatsdog","hippopotamuses","rat","ratcatdogcat"}; + print_vec(Solution().findAllConcatenatedWordsInADict(words1)); + // "catsdogcats","dogcatsdog","ratcatdogcat" + + vector words2 = {"cat","dog","catdog"}; + print_vec(Solution().findAllConcatenatedWordsInADict(words2)); + // "catdog" + + vector words3 = {"rfkqyuqfjkx","","vnrtysfrzrmzl","gfve","qfpd","lqdqrrcrwdnxeuo","q","klaitgdphcspij","hbsfyfv","adzpbfudkklrw","aozmixr","ife","feclhbvfuk","yeqfqojwtw","sileeztxwjl","ngbqqmbxqcqp","khhqr","dwfcayssyoqc","omwufbdfxu","zhift","kczvhsybloet","crfhpxprbsshsjxd","ilebxwbcto","yaxzfbjbkrxi","imqpzwmshlpj","ta","hbuxhwadlpto","eziwkmg","ovqzgdixrpddzp","c","wnqwqecyjyib","jy","mjfqwltvzk","tpvo","phckcyufdqml","lim","lfz","tgygdt","nhcvpf","fbrpzlk","shwywshtdgmb","bkkxcvg","monmwvytby","nuqhmfj","qtg","cwkuzyamnerp","fmwevhwlezo","ye","hbrcewjxvcezi","tiq","tfsrptug","iznorvonzjfea","gama","apwlmbzit","s","hzkosvn","nberblt","kggdgpljfisylt","mf","h","bljvkypcflsaqe","cijcyrgmqirz","iaxakholawoydvch","e","gttxwpuk","jf","xbrtspfttota","sngqvoijxuv","bztvaal","zxbshnrvbykjql","zz","mlvyoshiktodnsjj","qplci","lzqrxl","qxru","ygjtyzleizme","inx","lwhhjwsl","endjvxjyghrveu","phknqtsdtwxcktmw","wsdthzmlmbhjkm","u","pbqurqfxgqlojmws","mowsjvpvhznbsi","hdkbdxqg","ge","pzchrgef","ukmcowoe","nwhpiid","xdnnl","n","yjyssbsoc","cdzcuunkrf","uvouaghhcyvmlk","aajpfpyljt","jpyntsefxi","wjute","y","pbcnmhf","qmmidmvkn","xmywegmtuno","vuzygv","uxtrdsdfzfssmel","odjgdgzfmrazvnd","a","rdkugsbdpawxi","ivd","bbqeonycaegxfj","lrfkraoheucsvpi","eqrswgkaaaohxx","hqjtkqaqh","berbpmglbjipnuj","wogwczlkyrde","aqufowbig","snjniegvdvotu","ocedkt","bbufnxorixibbd","rzuqsyr","qghoy","evcuanuujszitaoa","wsx","glafbwzdd","znrvjqeyqi","npitruijvyllsi","objltu","ryp","nvybsfrxtlfmp","id","zoolzslgd","owijatklvjzscizr","upmsoxftumyxifyu","xucubv","fctkqlroq","zjv","wzi","ppvs","mflvioemycnphfjt","nwedtubynsb","repgcx","gsfomhvpmy","kdohe","tyycsibbeaxn","wjkfvabn","llkmagl","thkglauzgkeuly","paeurdvexqlw","akdt","ihmfrj","janxk","rqdll","cyhbsuxnlftmjc","yybwsjmajbwtuhkk","ovytgaufpjl","iwbnzhybsx","mumbh","jqmdabmyu","br","lwstjkoxbczkj","vhsgzvwiixxaob","fso","qnebmfl","ooetjiz","lq","msxphqdgz","mqhoggvrvjqrp","xbhkkfg","zxjegsyovdrmw","jav","mshoj","ax","biztkfomz","hujdmcyxdqteqja","gqgsomonv","reqqzzpw","lihdnvud","lznfhbaokxvce","fhxbldylqqewdnj","rlbskqgfvn","lfvobeyolyy","v","iwh","fpbuiujlolnjl","gvwxljbo","ypaotdzjxxrsc","mwrvel","umzpnoiei","ogwilaswn","yw","egdgye","hsrznlzrf","mwdgxaigmxpy","yaqgault","dtlg","cyvfiykmkllf","zxqyhvizqmamj","lvvgoifltzywueyp","abinmy","ppzaecvmx","qsmzc","iddymnl","uskihek","evxtehxtbthq","jvtfzddlgch","czohpyewf","ufzazyxtqxcu","brxpfymuvfvs","xrrcfuusicc","aqhlswbzievij","rv","udvmara","upityz","fecd","suxteeitxtg","dfuydrtbfypbn","cypqodxr","wikfuxwjht","jrliuaifpp","vkmxys","wvpfyfpkvgthq","rmajxis","jncxgviyu","av","nmhskodmidaj","lkfrimprrhen","uip","hstyopbvuiqc","p","vwduwmjpblqo","fnxwgqtvwztje","xwnbcuggl","iehimvoymyjasin","spsqiu","flhyfac","mqrbq","pstsxhplrrmbeddv","hnegtuxx","alsyxezjwtlwmxv","jtxytykkcku","bhhlovgcx","xhhivxnutkx","had","aysulvk","m","anhsyxli","jdkgfc","potn","lcibpxkidmwexp","gwoxjicdkv","tltienw","ngiutnuqbzi","o","tzlyb","vumnwehj","os","np","lhv","uzvgyeette","ipfvr","lpprjjalchhhcmh","k","pciulccqssaqgd","tp","dmzdzveslyjad","wtsbhgkd","eouxbldsxzm","vhtonlampljgzyve","xhnlcrldtfthul","xhflc","upgei","rlaks","yfqvnvtnqspyjbxr","phouoyhvls","voibuvbhhjcdflvl","rgorfbjrofokggaf","dqhqats","zchpicyuawpovm","yzwfor","koat","pybf","fhdzsbiyjld","gznfnqydisn","xz","po","tcjup","wygsnxk","kqlima","fgxnuohrnhg","publurhztntgmimc","zuufzphd","iucrmmmjqtcey","wnnbq","rghzyz","ukjqsjbmp","mdtrgv","vyeikgjdnml","kxwldnmi","apzuhsbssaxj","tkbkoljyodlipof","nkq","ktwtj","vgmkgjwle","t","agylw","vomtuy","jbtvitkqn","vtdxwrclpspcn","rdrls","yxfeoh","upj","myctacn","fdnor","ahqghzhoqprgkym","phiuvdv","jp","fdgpouzjwbq","hqoyefmugjvewhxu","qfzwuwe","fnsbijkeepyxry","oja","qthkcij","zpmqfbmnr","ybaibmzonzqlnmd","svo","gjftyfehik","jfrfgznuaytvaegm","aljhrx","odjq","ogwaxrssjxgvnka","zaqswwofedxj","lugpktauixp","dc","odknlbvxrs","jeobu","vqythyvzxbcgrlbg","hwc","erpbaxq","ujxcxck","rrklkb","wlrwyuy","zmg","yyhga","xwdbycdu","htedgvsrhchox","wr","suhesetv","jonqwhkwezjvjgg","sqqyrxtjkcalswq","hvyimhe","pjzdkmoue","zbphmgoxq","lbdlcumdgixjbcq","ztzdjqmadthtdmv","qcagsyqggcf","if","jpjxcjyi","chyicqibxdgkqtg","iwpdklhum","wljmg","micmun","npdbamofynykqv","ijsnfkpfy","lmq","oyjmeqvhcrvgm","mqopusqktdthpvz","fz","r","qbsqtipq","nxtsnason","xbpipyhh","topsuqomfjrd","islif","gbndakaq","bwnkxnwpzeoohlx","hrtbfnq","fguvomeepxoffg","mat","dzfpfnwbfuj","onlvy","cwcchvsasdylb","rxfcztzqopdi","ybrhodjn","oqkijy","ncvrjo","dphbfaal","xgtpdtkz","sebevsopjvciwljf","rcumyacqdapwczen","mabkapuoud","pbozezeygljfftvy","bvazmzbndl","vl","qiaixdtbhqvlzd","ffjfb","svthrfmkoxbho","cvet","ucgqyvopafyttrh","lbgihet","naiqyufxffdw","vruh","uz","ukffmudygjavem","dccamymhp","wofwgjkykm","fbuujzxhln","kmm","lzandlltowjpwsal","fapfvrmezbsjxs","wiw","sc","soqlh","hzaplclkwl","gcdqbcdwbwa","gadgt","pgowefka","juffuguqepwnfh","nbuinl","cpdxf","sox","fq","lfnrhgsxkhx","xrcorfygjxpi","mwtqjwbhgh","loc","fkglorkkvx","nlzdhucvayrz","azefobxutitrf","rlrstkcbtikklmh","ggk","sbphcejuylh","nraoenhd","zngyodiqlchxyycx","rrbhfwohfv","krzolrglgn","cpjesdzy","yoifoyg","hqqevqjugi","ahmv","xgaujnyclcjq","evhyfnlohavrj","byyvhgh","hyw","kedhvwy","ysljsqminajfipds","rglnpxfqwu","cibpynkxg","su","mbntqrlwyampdg","nig","ldhlhqdyjcfhu","jfymrbafmyoc","tyjmnhlfnrtz","dlazixtlxyvm","fbiguhsfuqo","rhymsno","rkbdlchs","ocbbwwd","astaiamnepwkya","mplirup","edkxjq","g","exlwulswtvot","tlnc","vnrrzerz","ygeraoozbtt","yyifkin","eo","ua","qgztvqdolf","rlzddjzcshvd","khxkdxflwxme","kk","zylbhoaac","cw","iizic","gcdxstpz","kjwdqeg","earjrncmmkdel","kbesuhquepj","nrzbllldgdmyrpgl","hllwnqozf","djpchowhwevbqvjj","zsmhylnjpktb","pxnktxkm","fxwiaqqb","qjwufmwresfsfaok","aa","d","iobioqm","svjgzk","khbzp","euexyudhrioi","yqsj","ngrwqpoh","rwuvd","eruffmlg","bxzovyew","faz","pmvfvyguqdi","jlxnoixsy","hyfrdngjf","ly","eibcapetpmeaid","tpnwwiif","pfgsp","kvhhwkzvtvlhhb","pjxurgqbtldims","rncplkeweoirje","akyprzzphew","wyvfpjyglzrmhfqp","ubheeqt","rmbxlcmn","taqakgim","apsbu","khwnykughmwrlk","vtdlzwpbhcsbvjno","tffmjggrmyil","schgwrrzt","mvndmua","nlwpw","glvbtkegzjs","piwllpgnlpcnezqs","xkelind","urtxsezrwz","zechoc","vfaimxrqnyiq","ybugjsblhzfravzn","btgcpqwovwp","zgxgodlhmix","sfzdknoxzassc","wgzvqkxuqrsqxs","dwneyqisozq","fg","vhfsf","uspujvqhydw","eadosqafyxbmzgr","tyff","blolplosqnfcwx","uwkl","puenodlvotb","iizudxqjvfnky","cjcywjkfvukvveq","jrxd","igwb","dftdyelydzyummmt","uvfmaicednym","oai","higfkfavgeemcgo","naefganqo","iqebfibigljbc","ulicojzjfrc","igxprunj","cymbrl","fqmwciqtynca","zjyagi","mzuejrttefhdwqc","zyiurxvf","wrjxffzbjexsh","wrxw","mhrbdxjwi","htknfa","wfrvxqdkhbwwef","vqsghhhutdget","cwupzrts","hbjnb","wpccoa","nx","howbzhaoscgyk","bilt","wqqatye","zceuuwg","jxzon","kkfj","bwsezd","ifdegsyjtswselk","xweimxlnzoh","tqthlftjblnpht","ww","ss","b","jmruuqscwjp","nxbk","wd","cqkrtbxgzg","xhppcjnq","cfq","tkkolzcfi","wblxki","ijeglxsvc","kcqjjwcwuhvzydm","gubqavlqffhrzz","hiwxrgftittd","caybc","ncsyjlzlxyyklc","poxcgnexmaajzuha","dhaccuualacyl","mtkewbprs","oncggqvr","sqqoffmwkplsgbrp","ioajuppvqluhbdet","dzwwzaelmo","afumtqugec","wglucmugwqi","zveswrjevfz","nxlbkak","pzcejvxzeoybb","fd","vewj","ivws","zjhudtpqsfc","zcmukotirrxx","zksmx","umofzhhowyftz","zbotrokaxaryxlk","ueolqk","dxmzhoq","zvu","cjl","esfmqgvxwfy","npbep","vbgjtbv","poeugoqynkbfiv","fewjjscjrei","yqssxzsydgllfzmo","urxkwcypctjkabi","wqtldwhjouas","tovdtkr","onzgeyddkqwuhnim","ffxviyvsktqrfa","qujhd","pvcz","hiyjlkxmeplnrvxg","hdykehkefp","vepcxhozpjxtreyn","liguhuxudbnh","f","ordxzm","klgohcmmbukz","yrmooliaobbnlap","dutnbetocxylcey","ywdsjegd","cr","blbxhjsgcuoxmqft","ngzdc","srfyjjumcbxole","dazwzwtdjoyuqeqj","xazjarqgfm","fxyfqbeoktcc","qrsjchxp","iltaqzawhgu","sgenjcfxr","yfikp","dvwhbyumthkiktb","walsx","jyajrkcvysicisab","brdeumb","tviihjwxdcz","dnrrgmem","ydgxlrjzucxyid","cdvdpvjlagwmg","ngnpxjkxims","gvyhnchlimsxc","w","jtizpezjl","qe","rjzv","vhnqvi","qm","iedzqswrsnfmnn","lt","utqfcqyrrwm","wtelvsqrru","fjwrhjcrtbcytn","qmqxceuohpiffaq","rmoybqjjgdyo","pmxttqftypfexlv","tg","qa","iqbqjlnpbf","kgaynkddbzllecd","tccvslp","curkxfoimnw","fvnyqkzlheruxr","iiygnzfov","coqs","oa","eiu","vzemmxtklis","lxu","nrwsjaxzwmh","tdayz","oxbbemejgosgcynf","ykbcn","hesvnctfvdsp","ku","rjhykpadahbhj","at","sxlngbtxmqr","wqrom","qzyabzrco","rbbyklndcqdj","cnsmgmwmpbgjq","krvnaf","qrwfajnfahyqocdb","fnlaozmff","vmoymbmytjvfcgt","cijyy","jdgwjbztl","swmalgbgpaplqgz","hfl","typttkrpfvx","tkzpzrscwbx","bwfqqvjcukjbsg","nxqmxr","x","eyavnz","il","dhthp","eyelg","npsoqsw","reogbmveofvusdsx","jvdrjkhxkq","qzjbrpljwuzpl","czqeevvbvcwh","vzuszqvhlmapty","yu","yldwwgezlqur","vorxwgdtgjilgydq","pknt","bgihl","ckorgrm","ixylxjmlfv","bpoaboylced","zea","igfagitkrext","ipvqq","dmoerc","oqxbypihdv","dtjrrkxro","rexuhucxpi","bvmuyarjwqpcoywa","qwdmfpwvamisns","bhopoqdsref","tmnm","cre","ktrniqwoofoeenbz","vlrfcsftapyujmw","updqikocrdyex","bcxw","eaum","oklsqebuzeziisw","fzgyhvnwjcns","dybjywyaodsyw","lmu","eocfru","ztlbggsuzctoc","ilfzpszgrgj","imqypqo","fump","sjvmsbrcfwretbie","oxpmplpcg","wmqigymr","qevdyd","gmuyytguexnyc","hwialkbjgzc","lmg","gijjy","lplrsxznfkoklxlv","xrbasbznvxas","twn","bhqultkyfq","saeq","xbuw","zd","kng","uoay","kfykd","armuwp","gtghfxf","gpucqwbihemixqmy","jedyedimaa","pbdrx","toxmxzimgfao","zlteob","adoshnx","ufgmypupei","rqyex","ljhqsaneicvaerqx","ng","sid","zagpiuiia","re","oadojxmvgqgdodw","jszyeruwnupqgmy","jxigaskpj","zpsbhgokwtfcisj","vep","ebwrcpafxzhb","gjykhz","mfomgxjphcscuxj","iwbdvusywqlsc","opvrnx","mkgiwfvqfkotpdz","inpobubzbvstk","vubuucilxyh","bci","dibmye","rlcnvnuuqfvhw","oorbyyiigppuft","swpksfdxicemjbf","goabwrqdoudf","yjutkeqakoarru","wuznnlyd","vfelxvtggkkk","mxlwbkbklbwfsvr","advraqovan","smkln","jxxvzdjlpyurxpj","ssebtpznwoytjefo","dynaiukctgrzjx","irzosjuncvh","hcnhhrajahitn","vwtifcoqepqyzwya","kddxywvgqxo","syxngevs","batvzmziq","mjewiyo","pzsupxoflq","byzhtvvpj","cqnlvlzr","akvmxzbaei","mwo","vg","ekfkuajjogbxhjii","isdbplotyak","jvkmxhtmyznha","lqjnqzrwrmgt","mbbhfli","bpeohsufree","ajrcsfogh","lucidbnlysamvy","tutjdfnvhahxy","urbrmmadea","hghv","acnjx","athltizloasimp","gu","rjfozvgmdakdhao","iephs","uztnpqhdl","rfuyp","crcszmgplszwfn","zihegt","xbspa","cjbmsamjyqqrasz","ghzlgnfoas","ljxl","cnumquohlcgt","jm","mfccj","hfedli","vtpieworwhyiucs","tdtuquartspkotm","pnkeluekvelj","ugrloq","zljmwt","fkyvqguqq","tpjidglpxqfxv","l","tvvimvroz","yy","opwyfovdz","pwlumocnyuoume","vjqpzkcfc","ihicd","dtttiixlhpikbv","goblttgvmndkqgg","gwsibcqahmyyeagk","prtvoju","lcblwidhjpu","kbu","pey","gkzrpc","bqajopjjlfthe","bc","lqs","zkndgojnjnxqsoqi","zyesldujjlp","drswybwlfyzph","xzluwbtmoxokk","bedrqfui","opajzeahv","lehdfnr","mnlpimduzgmwszc","velbhj","miwdn","wruqc","kscfodjxg","wcbm"}; + print_vec(Solution().findAllConcatenatedWordsInADict(words3)); + + return 0; +} diff --git a/0001-0500/0473-Matchsticks-to-Square/cpp-0473/CMakeLists.txt b/0001-0500/0473-Matchsticks-to-Square/cpp-0473/CMakeLists.txt new file mode 100644 index 00000000..37e53b57 --- /dev/null +++ b/0001-0500/0473-Matchsticks-to-Square/cpp-0473/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0473) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main4.cpp) +add_executable(cpp_0473 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0473-Matchsticks-to-Square/cpp-0473/main.cpp b/0001-0500/0473-Matchsticks-to-Square/cpp-0473/main.cpp new file mode 100644 index 00000000..4d0a9207 --- /dev/null +++ b/0001-0500/0473-Matchsticks-to-Square/cpp-0473/main.cpp @@ -0,0 +1,56 @@ +/// Source : https://leetcode.com/problems/matchsticks-to-square/description/ +/// Author : liuyubobobo +/// Time : 2018-08-28 + +#include +#include +#include + +using namespace std; + + +/// Backtracking +/// Time Complexity: O(4^n) +/// Space Complexity: O(n) +class Solution { +public: + bool makesquare(vector& nums) { + + if(nums.size() == 0) + return false; + + int sum = accumulate(nums.begin(), nums.end(), 0); + if(sum % 4) + return false; + + int side = sum / 4; + vector cur = {side, side, side, side}; + return dfs(nums, 0, cur); + } + +private: + bool dfs(const vector& nums, int index, vector& cur){ + + if(index == nums.size()){ + for(int e: cur) + if(e) + return false; + return true; + } + + for(int i = 0; i < cur.size() ; i ++) + if(cur[i] >= nums[index]){ + cur[i] -= nums[index]; + if(dfs(nums, index + 1, cur)) + return true; + cur[i] += nums[index]; + } + return false; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0473-Matchsticks-to-Square/cpp-0473/main2.cpp b/0001-0500/0473-Matchsticks-to-Square/cpp-0473/main2.cpp new file mode 100644 index 00000000..f371e8f9 --- /dev/null +++ b/0001-0500/0473-Matchsticks-to-Square/cpp-0473/main2.cpp @@ -0,0 +1,59 @@ +/// Source : https://leetcode.com/problems/matchsticks-to-square/description/ +/// Author : liuyubobobo +/// Time : 2018-08-28 + +#include +#include +#include + +using namespace std; + + +/// Backtracking +/// Improvement: Using longer sticks first:) +/// +/// Time Complexity: O(4^n) +/// Space Complexity: O(n) +class Solution { +public: + bool makesquare(vector& nums) { + + if(nums.size() == 0) + return false; + + int sum = accumulate(nums.begin(), nums.end(), 0); + if(sum % 4) + return false; + + int side = sum / 4; + vector cur = {side, side, side, side}; + sort(nums.begin(), nums.end(), greater()); + return dfs(nums, 0, cur); + } + +private: + bool dfs(const vector& nums, int index, vector& cur){ + + if(index == nums.size()){ + for(int e: cur) + if(e) + return false; + return true; + } + + for(int i = 0; i < cur.size() ; i ++) + if(cur[i] >= nums[index]){ + cur[i] -= nums[index]; + if(dfs(nums, index + 1, cur)) + return true; + cur[i] += nums[index]; + } + return false; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0473-Matchsticks-to-Square/cpp-0473/main3.cpp b/0001-0500/0473-Matchsticks-to-Square/cpp-0473/main3.cpp new file mode 100644 index 00000000..46e270e5 --- /dev/null +++ b/0001-0500/0473-Matchsticks-to-Square/cpp-0473/main3.cpp @@ -0,0 +1,80 @@ +/// Source : https://leetcode.com/problems/matchsticks-to-square/description/ +/// Author : liuyubobobo +/// Time : 2018-08-28 + +#include +#include +#include +#include + +using namespace std; + + +/// Memory Search +/// +/// Time Complexity: O(n*2^n) +/// Space Complexity: O(2^n) +class Solution { + +private: + int all, side; + +public: + bool makesquare(vector& nums) { + + if(nums.size() == 0) + return false; + + int total = accumulate(nums.begin(), nums.end(), 0); + if(total % 4) + return false; + + sort(nums.begin(), nums.end(), greater()); + all = (1 << nums.size()) - 1; + side = total / 4; + + vector sum(all + 1, -1); + vector dp(all + 1, -1); // -1 - unvisited, 0 - false, 1 - true + return dfs(nums, 0, dp, sum); + } + +private: + bool dfs(const vector& nums, int state, + vector& dp, vector& sum){ + + if(state == all) + return true; + + if(dp[state] != -1) + return dp[state]; + + int left = getSum(nums, state, sum) % side; + + for(int i = 0; i < nums.size() ; i ++) + if((state & (1 << i)) == 0 && left + nums[i] <= side + && dfs(nums, state | (1 << i), dp, sum)) + return dp[state] = 1; + return dp[state] = 0; + } + + int getSum(const vector& nums, int state, vector& sum){ + + if(sum[state] != -1) + return sum[state]; + + if(state == 0) + return sum[state] = 0; + + for(int i = 0; i < nums.size() ; i ++) + if(state & (1 << i)) + return sum[state] = nums[i] + getSum(nums, state - (1 << i), sum); + assert(false); + return -1; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0473-Matchsticks-to-Square/cpp-0473/main4.cpp b/0001-0500/0473-Matchsticks-to-Square/cpp-0473/main4.cpp new file mode 100644 index 00000000..a3204431 --- /dev/null +++ b/0001-0500/0473-Matchsticks-to-Square/cpp-0473/main4.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/matchsticks-to-square/description/ +/// Author : liuyubobobo +/// Time : 2018-08-28 + +#include +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// +/// Time Complexity: O(n*2^n) +/// Space Complexity: O(2^n) +class Solution { + +public: + bool makesquare(vector& nums) { + + if(nums.size() == 0) + return false; + + int total = accumulate(nums.begin(), nums.end(), 0); + if(total % 4) + return false; + + sort(nums.begin(), nums.end(), greater()); + int all = (1 << nums.size()) - 1; + int side = total / 4; + + vector sum(all + 1, 0); + for(int i = 1; i <= all; i ++) + for(int j = 0; j < nums.size() ; j ++) + if(i & (1 << j)){ + sum[i] = nums[j] + sum[i - (1 << j)]; + break; + } + + // dp[state]: is it possible to make a square from the state. + vector dp(all + 1, false); + dp[0] = true; + for(int i = 1; i <= all; i ++) + for(int j = 0; j < nums.size(); j ++) + if(i & (1 << j) && dp[i - (1 << j)] && sum[i - (1 << j)] % side + nums[j] <= side){ + dp[i] = true; + break; + } + return dp[all]; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/old/0474 Ones and Zeroes/cpp-Ones-and-Zeroes/CMakeLists.txt b/0001-0500/0474-Ones-and-Zeroes/cpp-0474/CMakeLists.txt similarity index 100% rename from old/0474 Ones and Zeroes/cpp-Ones-and-Zeroes/CMakeLists.txt rename to 0001-0500/0474-Ones-and-Zeroes/cpp-0474/CMakeLists.txt diff --git a/0001-0500/0474-Ones-and-Zeroes/cpp-0474/main.cpp b/0001-0500/0474-Ones-and-Zeroes/cpp-0474/main.cpp new file mode 100644 index 00000000..d6916872 --- /dev/null +++ b/0001-0500/0474-Ones-and-Zeroes/cpp-0474/main.cpp @@ -0,0 +1,65 @@ +/// Source : https://leetcode.com/problems/ones-and-zeroes/description/ +/// Author : liuyubobobo +/// Time : 2018-08-13 + +#include +#include +#include + +using namespace std; + +/// 0-1 backsack problem +/// Recursion Implimentation (Memory Search) +/// Time Complexity: O(sizeof(array)*m*n) +/// Space Complexity: O(sizeof(array)*m*n) +class Solution { + +public: + int findMaxForm(vector& strs, int m, int n) { + + vector mcost(strs.size(), 0), ncost(strs.size(), 0); + for(int i = 0 ; i < strs.size() ; i ++) + for(char c: strs[i]) + if(c == '0') + mcost[i] ++; + else + ncost[i] ++; + + vector>> dp(strs.size(), vector>(m + 1, vector(n + 1, -1))); + return findMaxForm(strs.size() - 1, m, n, dp, mcost, ncost); + } + +private: + int findMaxForm(int k, int m, int n, vector>>& dp, + const vector& mcost, const vector& ncost){ + + if(k < 0) + return 0; + + if(dp[k][m][n] != -1) + return dp[k][m][n]; + + dp[k][m][n] = findMaxForm(k - 1, m, n, dp, mcost, ncost); + if(m >= mcost[k] && n >= ncost[k]) + dp[k][m][n] = max(1 + findMaxForm(k - 1, m - mcost[k], n - ncost[k], dp, mcost, ncost), + dp[k][m][n]); + + return dp[k][m][n]; + } +}; + + +int main() { + + vector vec1 = {"10", "001", "111001", "1", "0"}; + int m1 = 5; + int n1 = 3; + cout << Solution().findMaxForm(vec1, m1, n1) << endl; + + vector vec2 = {"10", "0", "1"}; + int m2 = 1; + int n2 = 1; + cout << Solution().findMaxForm(vec2, m2, n2) << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0474-Ones-and-Zeroes/cpp-0474/main2.cpp b/0001-0500/0474-Ones-and-Zeroes/cpp-0474/main2.cpp new file mode 100644 index 00000000..1af6fa37 --- /dev/null +++ b/0001-0500/0474-Ones-and-Zeroes/cpp-0474/main2.cpp @@ -0,0 +1,59 @@ +/// Source : https://leetcode.com/problems/ones-and-zeroes/description/ +/// Author : liuyubobobo +/// Time : 2018-08-13 + +#include +#include +#include + +using namespace std; + +/// 0-1 backsack problem +/// Dynamic Programming +/// Time Complexity: O(sizeof(array)*m*n) +/// Space Complexity: O(sizeof(array)*m*n) +class Solution { + +public: + int findMaxForm(vector& strs, int m, int n) { + + vector mcost(strs.size(), 0), ncost(strs.size(), 0); + for(int i = 0 ; i < strs.size() ; i ++) + for(char c: strs[i]) + if(c == '0') + mcost[i] ++; + else + ncost[i] ++; + + vector>> dp(strs.size(), vector>(m + 1, vector(n + 1, 0))); + for(int u = mcost[0]; u <= m ; u ++) + for(int v = ncost[0] ; v <= n ; v ++) + dp[0][u][v] = 1; + + for(int i = 1 ; i < strs.size() ; i ++) + for(int u = 0 ; u <= m ; u ++) + for(int v = 0 ; v <= n ; v ++){ + dp[i][u][v] = dp[i - 1][u][v]; + if(u >= mcost[i] && v >= ncost[i]) + dp[i][u][v] = max(dp[i][u][v], 1 + dp[i - 1][u - mcost[i]][v - ncost[i]]); + } + + return dp[strs.size() - 1][m][n]; + } +}; + + +int main() { + + vector vec1 = {"10", "001", "111001", "1", "0"}; + int m1 = 5; + int n1 = 3; + cout << Solution().findMaxForm(vec1, m1, n1) << endl; + + vector vec2 = {"10", "0", "1"}; + int m2 = 1; + int n2 = 1; + cout << Solution().findMaxForm(vec2, m2, n2) << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0474-Ones-and-Zeroes/cpp-0474/main3.cpp b/0001-0500/0474-Ones-and-Zeroes/cpp-0474/main3.cpp new file mode 100644 index 00000000..916d8d99 --- /dev/null +++ b/0001-0500/0474-Ones-and-Zeroes/cpp-0474/main3.cpp @@ -0,0 +1,58 @@ +/// Source : https://leetcode.com/problems/ones-and-zeroes/description/ +/// Author : liuyubobobo +/// Time : 2018-08-13 + +#include +#include +#include + +using namespace std; + +/// Dynamic Programming with space optimization +/// Time Complexity: O(sizeof(array)*m*n) +/// Space Complexity: O(m*n) +class Solution { + +public: + int findMaxForm(vector& strs, int m, int n) { + + vector mcost(strs.size(), 0), ncost(strs.size(), 0); + for(int i = 0 ; i < strs.size() ; i ++) + for(char c: strs[i]) + if(c == '0') + mcost[i] ++; + else + ncost[i] ++; + + vector>> dp(2, vector>(m + 1, vector(n + 1, 0))); + for(int u = mcost[0]; u <= m ; u ++) + for(int v = ncost[0] ; v <= n ; v ++) + dp[0][u][v] = 1; + + for(int i = 1 ; i < strs.size() ; i ++) + for(int u = 0 ; u <= m ; u ++) + for(int v = 0 ; v <= n ; v ++){ + dp[i % 2][u][v] = dp[(i - 1) % 2][u][v]; + if(u >= mcost[i] && v >= ncost[i]) + dp[i % 2][u][v] = max(dp[i % 2][u][v] , 1 + dp[(i - 1) % 2][u - mcost[i]][v - ncost[i]]); + } + + return dp[(strs.size() - 1) % 2][m][n]; + } +}; + + +int main() { + + vector vec1 = {"10", "001", "111001", "1", "0"}; + int m1 = 5; + int n1 = 3; + cout << Solution().findMaxForm(vec1, m1, n1) << endl; + + vector vec2 = {"10", "0", "1"}; + int m2 = 1; + int n2 = 1; + cout << Solution().findMaxForm(vec2, m2, n2) << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0474-Ones-and-Zeroes/cpp-0474/main4.cpp b/0001-0500/0474-Ones-and-Zeroes/cpp-0474/main4.cpp new file mode 100644 index 00000000..3cf06550 --- /dev/null +++ b/0001-0500/0474-Ones-and-Zeroes/cpp-0474/main4.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/ones-and-zeroes/description/ +/// Author : liuyubobobo +/// Time : 2018-08-13 + +#include +#include +#include + +using namespace std; + +/// Dynamic Programming with space optimization +/// Time Complexity: O(sizeof(array)*m*n) +/// Space Complexity: O(m*n) +class Solution { + +public: + int findMaxForm(vector& strs, int m, int n) { + + vector> dp(m + 1 , vector(n + 1, 0)); + for(int i = 0 ; i < strs.size() ; i ++){ + int mcost = 0, ncost = 0; + for(char c: strs[i]) + if(c == '0') + mcost ++; + else + ncost ++; + + for(int u = m ; u >= mcost ; u --) + for(int v = n ; v >= ncost ; v --) + dp[u][v] = max(dp[u][v] , 1 + dp[u - mcost][v - ncost]); + } + return dp[m][n]; + } +}; + + +int main() { + + vector vec1 = {"10", "001", "111001", "1", "0"}; + int m1 = 5; + int n1 = 3; + cout << Solution().findMaxForm(vec1, m1, n1) << endl; + + vector vec2 = {"10", "0", "1"}; + int m2 = 1; + int n2 = 1; + cout << Solution().findMaxForm(vec2, m2, n2) << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0475-Heaters/cpp-0475/CMakeLists.txt b/0001-0500/0475-Heaters/cpp-0475/CMakeLists.txt new file mode 100644 index 00000000..ec7e7e06 --- /dev/null +++ b/0001-0500/0475-Heaters/cpp-0475/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0475) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0475 main.cpp) diff --git a/0001-0500/0475-Heaters/cpp-0475/main.cpp b/0001-0500/0475-Heaters/cpp-0475/main.cpp new file mode 100644 index 00000000..d053e7e2 --- /dev/null +++ b/0001-0500/0475-Heaters/cpp-0475/main.cpp @@ -0,0 +1,48 @@ +/// Source : https://leetcode.com/problems/heaters/ +/// Author : liuyubobobo +/// Time : 2021-12-19 + +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(nlog(max_pos)) +/// Space Complexity: O(1) +class Solution { +public: + int findRadius(vector& houses, vector& heaters) { + + sort(houses.begin(), houses.end()); + sort(heaters.begin(), heaters.end()); + + int l = 0, r = 1e9; + while(l < r){ + int mid = (l + r) / 2; + if(ok(houses, heaters, mid)) r = mid; + else l = mid + 1; + } + return l; + } + +private: + bool ok(const vector& houses, const vector& heaters, int r){ + + int i = 0, j = 0; + while(i < houses.size()){ + if(j >= heaters.size()) return false; + if(heaters[j] - r <= houses[i] && houses[i] <= heaters[j] + r) + i ++; + else j ++; + } + return true; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0476-Number-Complement/cpp-0476/CMakeLists.txt b/0001-0500/0476-Number-Complement/cpp-0476/CMakeLists.txt new file mode 100644 index 00000000..d68a2dec --- /dev/null +++ b/0001-0500/0476-Number-Complement/cpp-0476/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0476) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0476 main.cpp) diff --git a/0001-0500/0476-Number-Complement/cpp-0476/main.cpp b/0001-0500/0476-Number-Complement/cpp-0476/main.cpp new file mode 100644 index 00000000..15f92288 --- /dev/null +++ b/0001-0500/0476-Number-Complement/cpp-0476/main.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/number-complement/ +/// Author : liuyubobobo +/// Time : 2021-10-17 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(logn) +/// Space Complexity: O(logn) +class Solution { +public: + int findComplement(int num) { + + vector bin; + while(num){ + bin.push_back(num % 2); + num /= 2; + } + + reverse(bin.begin(), bin.end()); + + int res = 0; + for(int e: bin) + res = res * 2 + (1 - e); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0477-Total-Hamming-Distance/cpp-0477/CMakeLists.txt b/0001-0500/0477-Total-Hamming-Distance/cpp-0477/CMakeLists.txt new file mode 100644 index 00000000..ef66f177 --- /dev/null +++ b/0001-0500/0477-Total-Hamming-Distance/cpp-0477/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(cpp_0477) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0477 main2.cpp) \ No newline at end of file diff --git a/0001-0500/0477-Total-Hamming-Distance/cpp-0477/main.cpp b/0001-0500/0477-Total-Hamming-Distance/cpp-0477/main.cpp new file mode 100644 index 00000000..d7f0b938 --- /dev/null +++ b/0001-0500/0477-Total-Hamming-Distance/cpp-0477/main.cpp @@ -0,0 +1,43 @@ +/// Source : https://leetcode.com/problems/total-hamming-distance/ +/// Author : liuyubobobo +/// Time : 2020-05-25 + +#include +#include + +using namespace std; + + +/// Count one and zero for every bits position +/// Time Complexity: O(nlog(num)) +/// Space Complexity: O(1) +class Solution { +public: + int totalHammingDistance(vector& nums) { + + vector> cnt(32, vector(2, 0)); + for(int e: nums){ + int i = 0; + while(e) cnt[i ++][e % 2] ++, e /= 2; + while(i < 32) cnt[i ++][0] ++; + } + + int res = 0; + for(int i = 0; i < 32; i ++) res += cnt[i][0] * cnt[i][1]; + return res; + } +}; + + +int main() { + + vector nums1 = {4, 14, 2}; + cout << Solution().totalHammingDistance(nums1) << endl; + // 6 + + vector nums2 = {1337}; + cout << Solution().totalHammingDistance(nums2) << endl; + // 0 + + return 0; +} diff --git a/0001-0500/0477-Total-Hamming-Distance/cpp-0477/main2.cpp b/0001-0500/0477-Total-Hamming-Distance/cpp-0477/main2.cpp new file mode 100644 index 00000000..a1f9e0be --- /dev/null +++ b/0001-0500/0477-Total-Hamming-Distance/cpp-0477/main2.cpp @@ -0,0 +1,45 @@ +/// Source : https://leetcode.com/problems/total-hamming-distance/ +/// Author : liuyubobobo +/// Time : 2020-05-25 + +#include +#include + +using namespace std; + + +/// Count one for every bits position +/// Time Complexity: O(nlog(num)) +/// Space Complexity: O(1) +class Solution { +public: + int totalHammingDistance(vector& nums) { + + vector cnt(32, 0); + for(int e: nums){ + int i = 0; + while(e) { + if(e % 2) cnt[i] ++; + i ++, e /= 2; + } + } + + int res = 0; + for(int i = 0; i < 32; i ++) res += cnt[i] * (nums.size() - cnt[i]); + return res; + } +}; + + +int main() { + + vector nums1 = {4, 14, 2}; + cout << Solution().totalHammingDistance(nums1) << endl; + // 6 + + vector nums2 = {1337}; + cout << Solution().totalHammingDistance(nums2) << endl; + // 0 + + return 0; +} diff --git a/0001-0500/0478-Generate-Random-Point-in-a-Circle/cpp-0478/CMakeLists.txt b/0001-0500/0478-Generate-Random-Point-in-a-Circle/cpp-0478/CMakeLists.txt new file mode 100644 index 00000000..287f7476 --- /dev/null +++ b/0001-0500/0478-Generate-Random-Point-in-a-Circle/cpp-0478/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0478) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0478 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0478-Generate-Random-Point-in-a-Circle/cpp-0478/main.cpp b/0001-0500/0478-Generate-Random-Point-in-a-Circle/cpp-0478/main.cpp new file mode 100644 index 00000000..5a49989f --- /dev/null +++ b/0001-0500/0478-Generate-Random-Point-in-a-Circle/cpp-0478/main.cpp @@ -0,0 +1,49 @@ +/// Source : https://leetcode.com/problems/generate-random-point-in-a-circle/description/ +/// Author : liuyubobobo +/// Time : 2018-08-28 + +#include +#include +#include + +using namespace std; + + +/// Rejection Sampling +/// Time Complexity: O(1) +/// Space Complexity: O(1) +class Solution { + +private: + double x, y, r; + +public: + Solution(double radius, double x_center, double y_center): + x(x_center), y(y_center), r(radius){} + + vector randPoint() { + + double randx, randy; + do{ + randx = x - r + randDouble(0, 2 * r); + randy = y - r + randDouble(0, 2 * r); + }while(!inCircle(randx, randy)); + return {randx, randy}; + } + +private: + double randDouble(double minDouble, double maxDouble){ + double randNum = (double)rand() / INT_MAX; + return randNum * (maxDouble - minDouble) + minDouble; + } + + bool inCircle(double x0, double y0){ + return (x - x0) * (x - x0) + (y - y0) * (y - y0) <= r * r; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0478-Generate-Random-Point-in-a-Circle/cpp-0478/main2.cpp b/0001-0500/0478-Generate-Random-Point-in-a-Circle/cpp-0478/main2.cpp new file mode 100644 index 00000000..4b0f481a --- /dev/null +++ b/0001-0500/0478-Generate-Random-Point-in-a-Circle/cpp-0478/main2.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/generate-random-point-in-a-circle/description/ +/// Author : liuyubobobo +/// Time : 2018-08-28 + +#include +#include + +using namespace std; + + +/// Using Mathematics and Polar Coorinates +/// About Inverse Transform Sampling in this problem, please follow these links +/// +/// https://leetcode.com/problems/generate-random-point-in-a-circle/solution/ +/// https://stackoverflow.com/questions/5837572/generate-a-random-point-within-a-circle-uniformly/50746409#50746409 +/// +/// Time Complexity: O(1) +/// Space Complexity: O(1) +class Solution { + +private: + double x, y, r; + +public: + Solution(double radius, double x_center, double y_center): + x(x_center), y(y_center), r(radius){} + + vector randPoint() { + + double randR = sqrt(randDouble(0.0, 1.0)) * r; // CDF + double randAngle = randDouble(0.0, 2.0 * M_PI); + return {x + randR * cos(randAngle), y + randR * sin(randAngle)}; + } + +private: + double randDouble(double minDouble, double maxDouble){ + + double randNum = (double)rand() / INT_MAX; + return randNum * (maxDouble - minDouble) + minDouble; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0479-Largest-Palindrome-Product/cpp-0479/CMakeLists.txt b/0001-0500/0479-Largest-Palindrome-Product/cpp-0479/CMakeLists.txt new file mode 100644 index 00000000..ae545ca1 --- /dev/null +++ b/0001-0500/0479-Largest-Palindrome-Product/cpp-0479/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_0479) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0479 main2.cpp) diff --git a/0001-0500/0479-Largest-Palindrome-Product/cpp-0479/main.cpp b/0001-0500/0479-Largest-Palindrome-Product/cpp-0479/main.cpp new file mode 100644 index 00000000..b02dba2a --- /dev/null +++ b/0001-0500/0479-Largest-Palindrome-Product/cpp-0479/main.cpp @@ -0,0 +1,49 @@ +/// Source : https://leetcode.com/problems/largest-palindrome-product/ +/// Author : liuyubobobo +/// Time : 2022-04-15 + +#include +#include + +using namespace std; + + +/// Iterate Palindrome +/// Time Complexity: O(10^(2n)) in theory but in fact it is very fast +/// Space Complexity: O(n) +class Solution { +public: + int largestPalindrome(int n) { + + long long maxv = pow(10, n) - 1; + long long minv = pow(10, n - 1); + for(int a = maxv; a >= minv; a --){ + long long num = get_palindrome_num(a); + + for(long long d = maxv; d >= minv; d --){ + long long nd = num / d; + if(nd > d) break; + if(d * nd == num) return num % 1337ll; + } + } + return 9; + } + +private: + long long get_palindrome_num(int a){ + string left = to_string(a); + string right = left; + reverse(right.begin(), right.end()); + string res = left + right; + return atoll(res.c_str()); + } +}; + + +int main() { + + cout << Solution().largestPalindrome(2) << '\n'; + // 987 + + return 0; +} diff --git a/0001-0500/0479-Largest-Palindrome-Product/cpp-0479/main2.cpp b/0001-0500/0479-Largest-Palindrome-Product/cpp-0479/main2.cpp new file mode 100644 index 00000000..827be19d --- /dev/null +++ b/0001-0500/0479-Largest-Palindrome-Product/cpp-0479/main2.cpp @@ -0,0 +1,73 @@ +/// Source : https://leetcode.com/problems/largest-palindrome-product/ +/// Author : liuyubobobo +/// Time : 2022-04-15 + +#include +#include +#include +#include + +using namespace std; + + +/// Iterate Two numbers int length n +/// Time Complexity: O(10^(2n)) in theory but in fact it is very fast +/// Space Complexity: O(10^(2n)) in theory but in fact it is very small +class Solution { +public: + int largestPalindrome(int n) { + + priority_queue>> pq; + set> visited; + + long long base = pow(10, n) - 1; + + pq.push({(base - 9 + 9) * (base - 9 + 1), {base - 9 + 9, base - 9 + 1}}); + visited.insert({base - 9 + 9, base - 9 + 1}); + + pq.push({(base - 9 + 3) * (base - 9 + 3), {base - 9 + 3, base - 9 + 3}}); + visited.insert({base - 9 + 3, base - 9 + 3}); + + pq.push({(base - 9 + 7) * (base - 9 + 7), {base - 9 + 7, base - 9 + 7}}); + visited.insert({base - 9 + 7, base - 9 + 7}); + + while(!pq.empty()){ + long long num = pq.top().first; + long long a = pq.top().second.first, b = pq.top().second.second; + pq.pop(); + + if(is_palindrome(num)) return num % 1337; + + pair next1 = {max(a - 10, b), min(a - 10, b)}; + if(!visited.count(next1)){ + visited.insert(next1); + pq.push({next1.first * next1.second, next1}); + } + + pair next2 = {max(a, b - 10), min(a, b - 10)}; + if(!visited.count(next2)){ + visited.insert(next2); + pq.push({next2.first * next2.second, next2}); + } + } + return 9; + } + +private: + bool is_palindrome(long long num){ + + string s = to_string(num); + for(int i = 0, j = s.size() - 1; i < j; i ++, j --) + if(s[i] != s[j]) return false; + return true; + } +}; + + +int main() { + + cout << Solution().largestPalindrome(2) << '\n'; + // 987 + + return 0; +} diff --git a/0001-0500/0480-Sliding-Window-Median/cpp-0480/CMakeLists.txt b/0001-0500/0480-Sliding-Window-Median/cpp-0480/CMakeLists.txt new file mode 100644 index 00000000..3bc2ad5c --- /dev/null +++ b/0001-0500/0480-Sliding-Window-Median/cpp-0480/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(cpp_0480) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0480 main.cpp) \ No newline at end of file diff --git a/0001-0500/0480-Sliding-Window-Median/cpp-0480/main.cpp b/0001-0500/0480-Sliding-Window-Median/cpp-0480/main.cpp new file mode 100644 index 00000000..66a0f590 --- /dev/null +++ b/0001-0500/0480-Sliding-Window-Median/cpp-0480/main.cpp @@ -0,0 +1,117 @@ +/// Source : https://leetcode.com/problems/sliding-window-median/ +/// Author : liuyubobobo +/// Time : 2019-09-23 + +#include +#include +#include + +using namespace std; + + +/// One TreeSet +/// Time Complexity: O(nlogk) +/// Space Complexity: O(k) +class Solution { + +private: + map tree; + int count = 0; + + int index = -1; + map::iterator iter; + +public: + vector medianSlidingWindow(vector& nums, int k) { + + vector res; + for(int i = 0; i < k; i ++) + add(nums[i]); + + res.push_back(get_median()); +// cout << get_median() << endl; + for(int i = k; i < nums.size(); i ++){ + add(nums[i]); + remove(nums[i - k]); + res.push_back(get_median()); +// cout << get_median() << endl; + } + return res; + } + +private: + void add(int num){ + + if(!count){ + tree[num] ++; + index = 0; + iter = tree.begin(); + count ++; + return; + } + + tree[num] ++; + if(count % 2){ // odd + if(num < iter->first){ + if(index) index --; + else iter --, index = iter->second - 1; + } + } + else{ // even + if(num >= iter->first){ + if(index + 1 < iter->second) index ++; + else iter ++, index = 0; + } + } + count ++; + } + + void remove(int num){ + + if(count % 2){ // odd + if(num >= iter->first){ + if(index) index --; + else iter--, index = iter->second - 1; + } + } + else{ // even + if(num < iter->first){ + if(index + 1 < iter->second) index ++; + else iter ++, index = 0; + } + else if(num == iter->first && index + 1 == iter->second) + iter ++, index = 0; + } + + tree[num] --; + count --; + if(tree[num] == 0) tree.erase(num); + } + + double get_median(){ + if(count % 2) return iter->first; + if(index + 1 < iter->second) return iter->first; + + map::iterator iter2 = iter; + iter2 ++; + return ((double)iter->first + (double)iter2->first) / 2; + } +}; + + +void print_vec(const vector& vec){ + for(double e: vec) cout << e << " "; cout << endl; +} + +int main() { + + vector nums1 = {1, 3, -1, -3, 5, 3, 6, 7}; + print_vec(Solution().medianSlidingWindow(nums1, 3)); + // 1 -1 -1 3 5 6 + + vector nums2 = {1, 2, 3, 4, 2, 3, 1, 4, 2}; + print_vec(Solution().medianSlidingWindow(nums2, 3)); + // 2 3 3 3 2 3 2 + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0481-Magical-String/cpp-0481/CMakeLists.txt b/0001-0500/0481-Magical-String/cpp-0481/CMakeLists.txt new file mode 100644 index 00000000..e3158934 --- /dev/null +++ b/0001-0500/0481-Magical-String/cpp-0481/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_0481) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0481 main.cpp) diff --git a/0001-0500/0481-Magical-String/cpp-0481/main.cpp b/0001-0500/0481-Magical-String/cpp-0481/main.cpp new file mode 100644 index 00000000..a173e7aa --- /dev/null +++ b/0001-0500/0481-Magical-String/cpp-0481/main.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/magical-string/ +/// Author : liuyubobobo +/// Time : 2022-10-30 + +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int magicalString(int n) { + + string s = "122"; + int index = 2; + while(s.size() < n){ + s += string(s[index] - '0', s.back() == '1' ? '2' : '1'); + index ++; + } + + int res = 0; + for(int i = 0; i < n; i ++) + res += s[i] == '1'; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0482-License-Key-Formatting/cpp-0482/CMakeLists.txt b/0001-0500/0482-License-Key-Formatting/cpp-0482/CMakeLists.txt new file mode 100644 index 00000000..8cf761be --- /dev/null +++ b/0001-0500/0482-License-Key-Formatting/cpp-0482/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0482) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0482 main.cpp) diff --git a/0001-0500/0482-License-Key-Formatting/cpp-0482/main.cpp b/0001-0500/0482-License-Key-Formatting/cpp-0482/main.cpp new file mode 100644 index 00000000..4be918fc --- /dev/null +++ b/0001-0500/0482-License-Key-Formatting/cpp-0482/main.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/license-key-formatting/ +/// Author : liuyubobobo +/// Time : 2021-10-03 + +#include + +using namespace std; + + +/// String +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + string licenseKeyFormatting(string s, int k) { + + string t = ""; + for(char c: s) + if(c != '-') t += toupper(c); + + reverse(t.begin(), t.end()); + string res = t.substr(0, k); + for(int i = k; i < t.size(); i += k) + res += "-" + t.substr(i, k); + reverse(res.begin(), res.end()); + return res; + } +}; + + +int main() { + + cout << Solution().licenseKeyFormatting("5F3Z-2e-9-w", 4) << endl; + // "5F3Z-2E9W" + + return 0; +} diff --git a/0001-0500/0483-Smallest-Good-Base/cpp-0483/CMakeLists.txt b/0001-0500/0483-Smallest-Good-Base/cpp-0483/CMakeLists.txt new file mode 100644 index 00000000..9a9727f0 --- /dev/null +++ b/0001-0500/0483-Smallest-Good-Base/cpp-0483/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_0483) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0483 main.cpp) \ No newline at end of file diff --git a/0001-0500/0483-Smallest-Good-Base/cpp-0483/main.cpp b/0001-0500/0483-Smallest-Good-Base/cpp-0483/main.cpp new file mode 100644 index 00000000..6313aa11 --- /dev/null +++ b/0001-0500/0483-Smallest-Good-Base/cpp-0483/main.cpp @@ -0,0 +1,67 @@ +/// Source : https://leetcode.com/problems/smallest-good-base/ +/// Author : liuyubobobo +/// Time : 2021-06-17 + +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(log(n)^2 * log(LONG_LONG_MAX)) +/// Space Complexity: O(1) +class Solution { +public: + string smallestGoodBase(string n) { + + long long num = atoll(n.c_str()); + long long res = num - 1; + for(int one_num = 3; one_num <= 60; one_num ++){ + long long base = get_base(one_num, num); + res = min(res, base); + } + return to_string(res); + } + +private: + long long get_base(int one_num, long long num){ + + long long lbase = 2, rbase = num - 1; + while(lbase <= rbase){ + long long base = (lbase + rbase) / 2; + long long t = get_num(base, one_num); + if(t == num) return base; + else if(t < num) lbase = base + 1; + else rbase = base - 1; + } + return LONG_LONG_MAX; + } + + long long get_num(long long b, int one_num){ + + long long res = 1ll; + for(int i = 1; i < one_num; i ++){ + if((LONG_LONG_MAX - 1) / b < res) return LONG_LONG_MAX; + res = res * b + 1ll; + } + return res; + } +}; + + +int main() { + + cout << Solution().smallestGoodBase("13") << endl; + // 3 + + cout << Solution().smallestGoodBase("4681") << endl; + // 8 + + cout << Solution().smallestGoodBase("1000000000000000000") << endl; + // 999999999999999999 + + cout << Solution().smallestGoodBase("2251799813685247") << endl; + // 2 + + return 0; +} diff --git a/0001-0500/0484-Find-Permutation/cpp-0484/CMakeLists.txt b/0001-0500/0484-Find-Permutation/cpp-0484/CMakeLists.txt new file mode 100644 index 00000000..5e038615 --- /dev/null +++ b/0001-0500/0484-Find-Permutation/cpp-0484/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_0484) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0484 main.cpp) diff --git a/0001-0500/0484-Find-Permutation/cpp-0484/main.cpp b/0001-0500/0484-Find-Permutation/cpp-0484/main.cpp new file mode 100644 index 00000000..052b2ae8 --- /dev/null +++ b/0001-0500/0484-Find-Permutation/cpp-0484/main.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/find-permutation/ +/// Author : liuyubobobo +/// Time : 2022-05-30 + +#include +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + vector findPermutation(string s) { + + s += "I"; + int n = s.size(); + + vector res(n); + for(int i = 1; i <= n; i ++) res[i - 1] = i; + + for(int start = 0, i = 0; i < n; i ++) + if(i == n || s[i] != s[start]){ + if(s[start] == 'D') + reverse(res.begin() + start, res.begin() + i + 1); + start = i; + i = start; + } + return res; + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << ' '; cout << '\n'; +} + +int main() { + + print_vec(Solution().findPermutation("DI")); + // 2 1 3 + + return 0; +} diff --git a/0001-0500/0485-Max-Consecutive-Ones/cpp-0485/CMakeLists.txt b/0001-0500/0485-Max-Consecutive-Ones/cpp-0485/CMakeLists.txt new file mode 100644 index 00000000..11255042 --- /dev/null +++ b/0001-0500/0485-Max-Consecutive-Ones/cpp-0485/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0485) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0485 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0485-Max-Consecutive-Ones/cpp-0485/main.cpp b/0001-0500/0485-Max-Consecutive-Ones/cpp-0485/main.cpp new file mode 100644 index 00000000..6ae91604 --- /dev/null +++ b/0001-0500/0485-Max-Consecutive-Ones/cpp-0485/main.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/max-consecutive-ones/description/ +/// Author : liuyubobobo +/// Time : 2018-06-16 + +#include +#include + +using namespace std; + +/// Ad-Hoc +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int findMaxConsecutiveOnes(vector& nums) { + + int res = 0; + int start = firstOne(nums, 0); + for(int i = start + 1 ; i <= nums.size() ; ){ + if(i == nums.size() || nums[i] != 1){ + // cout << i - start << endl; + res = max(res, i - start); + start = firstOne(nums, i); + i = start + 1; + } + else + i ++; + } + return res; + } + +private: + int firstOne(const vector& nums, int startIndex){ + for(int i = startIndex ; i < nums.size() ; i ++) + if(nums[i] == 1) + return i; + return nums.size(); + } +}; + + +int main() { + + vector nums = {1, 1, 0, 1, 1, 1}; + cout << Solution().findMaxConsecutiveOnes(nums) << endl; + return 0; +} \ No newline at end of file diff --git a/0001-0500/0486-Predict-the-Winner/cpp-0486/CMakeLists.txt b/0001-0500/0486-Predict-the-Winner/cpp-0486/CMakeLists.txt new file mode 100644 index 00000000..635bf6a5 --- /dev/null +++ b/0001-0500/0486-Predict-the-Winner/cpp-0486/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_0486) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_0486 main.cpp) diff --git a/0001-0500/0486-Predict-the-Winner/cpp-0486/main.cpp b/0001-0500/0486-Predict-the-Winner/cpp-0486/main.cpp new file mode 100644 index 00000000..56a0a5d2 --- /dev/null +++ b/0001-0500/0486-Predict-the-Winner/cpp-0486/main.cpp @@ -0,0 +1,28 @@ +#include +#include +#include + +using namespace std; + + +class Solution { +public: + bool PredictTheWinner(vector& nums) { + + int n = nums.size(); + int p1 = 0, p2 = n - 1; + + vector> dp(n, vector(n, INT_MIN / 2)); + return dfs(nums, p1, p2, dp) >= 0; + } + +private: + int dfs(const vector& nums, int p1, int p2, vector>& dp) { + + if (p1 > p2) return 0; + if (dp[p1][p2] != INT_MIN / 2) return dp[p1][p2]; + int a = nums[p1] - dfs(nums, p1 + 1, p2, dp); + int b = nums[p2] - dfs(nums, p1, p2 - 1, dp); + return dp[p1][p2] = max(a, b); + } +}; diff --git a/0001-0500/0487-Max-Consecutive-Ones-II/cpp-0487/CMakeLists.txt b/0001-0500/0487-Max-Consecutive-Ones-II/cpp-0487/CMakeLists.txt new file mode 100644 index 00000000..d77c8dc8 --- /dev/null +++ b/0001-0500/0487-Max-Consecutive-Ones-II/cpp-0487/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_0487) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0487 main.cpp) diff --git a/0001-0500/0487-Max-Consecutive-Ones-II/cpp-0487/main.cpp b/0001-0500/0487-Max-Consecutive-Ones-II/cpp-0487/main.cpp new file mode 100644 index 00000000..0a1299a1 --- /dev/null +++ b/0001-0500/0487-Max-Consecutive-Ones-II/cpp-0487/main.cpp @@ -0,0 +1,49 @@ +/// Source : https://leetcode.com/problems/max-consecutive-ones-ii/ +/// Author : liuyubobobo +/// Time : 2022-10-29 + +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int findMaxConsecutiveOnes(vector& nums) { + + int n = nums.size(); + + int res = 0; + vector> v; + for(int start = 0, i = 1; i <= n; i ++) + if(i == n || nums[i] != nums[start]){ + v.push_back({nums[start], i - start}); + if(nums[start]) res = max(res, i - start); + else res = max(res, 1); + start = i; + } + + for(int i = 0; i < v.size(); i ++) + if(v[i].first == 1 && (i - 1 >= 0 || i + 1 < v.size())) + res = max(res, v[i].second + 1); + + for(int i = 0; i < v.size(); i ++) + if(v[i].first == 0 && v[i].second == 1){ + int t = 1; + if(i - 1 >= 0) t += v[i - 1].second; + if(i + 1 < v.size()) t += v[i + 1].second; + res = max(res, t); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0488-Zuma-Game/cpp-0488/CMakeLists.txt b/0001-0500/0488-Zuma-Game/cpp-0488/CMakeLists.txt new file mode 100644 index 00000000..f48255d9 --- /dev/null +++ b/0001-0500/0488-Zuma-Game/cpp-0488/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0488) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0488 main.cpp) diff --git a/0001-0500/0488-Zuma-Game/cpp-0488/main.cpp b/0001-0500/0488-Zuma-Game/cpp-0488/main.cpp new file mode 100644 index 00000000..4afc9717 --- /dev/null +++ b/0001-0500/0488-Zuma-Game/cpp-0488/main.cpp @@ -0,0 +1,116 @@ +/// Source : https://leetcode.com/problems/zuma-game/ +/// Author : liuyubobobo +/// Time : 2021-11-09 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n!) +/// Space Complexity: O(n!) +class Solution { + +private: + const map char2num = {{'R', 0}, {'Y', 1}, {'B', 2}, {'G', 3}, {'W', 4}}; + +public: + int findMinStep(string board_str, string hand_str){ + + string board = board_str; + for(int i = 0; i < board_str.size(); i ++) board[i] = ('0' + char2num.at(board_str[i])); + + string hand_f(5, '0'); + for(int i =0; i < hand_str.size(); i ++) hand_f[char2num.at(hand_str[i])] ++; + + int res = INT_MAX; + unordered_set visited; + dfs(board, hand_f, hand_str.size(), res, visited); + return res == INT_MAX ? -1 : res; + } + + +private: + void dfs(const string& s, string& hand_f, const int handnum, int& res, + unordered_set& visited){ + + string hash = s + "#" + hand_f; + if(visited.count(hash)) return; + + if(s == ""){ + int left = 0; + for(char c: hand_f) left += (c - '0'); + res = min(res, handnum - left); + visited.insert(hash); + return; + } + + for(int start = 0, i = start + 1; i <= s.size(); i ++) + if(i == s.size() || s[i] != s[start]){ + if(i - start >= 3){ + dfs(s.substr(0, start) + s.substr(i), hand_f, handnum, res, visited); + visited.insert(hash); + return; + } + start = i; + } + + for(int card = 0; card < hand_f.size(); card ++) + if(hand_f[card] > '0'){ + string news; + for(int start = 0, i = 1; i <= s.size(); i ++) + if(i == s.size() || s[i] != s[start]){ + if(card == s[start] - '0'){ + news = s.substr(0, i) + string(1, '0' + card) + s.substr(i); + hand_f[card] --; + dfs(news, hand_f, handnum, res, visited); + hand_f[card] ++; + } + else{ + news = s.substr(0, start) + string(1, '0' + card) + s.substr(start); + hand_f[card] --; + dfs(news, hand_f, handnum, res, visited); + hand_f[card] ++; + + news = s.substr(0, i) + string(1, '0' + card) + s.substr(i); + hand_f[card] --; + dfs(news, hand_f, handnum, res, visited); + hand_f[card] ++; + + if(i - start > 1){ + news = s.substr(0, start + 1) + string(1, '0' + card) + s.substr(start + 1); + hand_f[card] --; + dfs(news, hand_f, handnum, res, visited); + hand_f[card] ++; + } + } + start = i; + } + } + + visited.insert(hash); + } +}; + + +int main() { + + cout << Solution().findMinStep("WWRRBBWW", "WRBRW") << endl; + // 2 + + cout << Solution().findMinStep("RBYYBBRRB", "YRBGB") << endl; + // 3 + + cout << Solution().findMinStep("RRWWRRBBRR", "WB") << endl; + // 2 + + cout << Solution().findMinStep("WWBBWBBWW", "BB") << endl; + // -1 + + return 0; +} diff --git a/0001-0500/0489-Robot-Room-Cleaner/cpp-0489/CMakeLists.txt b/0001-0500/0489-Robot-Room-Cleaner/cpp-0489/CMakeLists.txt new file mode 100644 index 00000000..b754329a --- /dev/null +++ b/0001-0500/0489-Robot-Room-Cleaner/cpp-0489/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_0489) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0489 main.cpp) diff --git a/0001-0500/0489-Robot-Room-Cleaner/cpp-0489/main.cpp b/0001-0500/0489-Robot-Room-Cleaner/cpp-0489/main.cpp new file mode 100644 index 00000000..8856f127 --- /dev/null +++ b/0001-0500/0489-Robot-Room-Cleaner/cpp-0489/main.cpp @@ -0,0 +1,81 @@ +/// Source : https://leetcode.com/problems/robot-room-cleaner/ +/// Author : liuyubobobo +/// Time : 2022-05-24 + +#include +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(m * n) +/// Space Complexity: O(m * n) + +/// This is the robot's control interface. +/// You should not implement it, or speculate about its implementation +class Robot { +public: + // Returns true if the cell in front is open and robot moves into the cell. + // Returns false if the cell in front is blocked and robot stays in the current cell. + bool move(); + + // Robot will stay in the same cell after calling turnLeft/turnRight. + // Each turn will be 90 degrees. + void turnLeft(); + void turnRight(); + + // Clean the current cell. + void clean(); +}; + +class Solution { + +private: + set> visited; + const int dirs[4][2] = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}}; + +public: + void cleanRoom(Robot& robot) { + + int d = 0; + dfs(robot, 0, 0, d, visited); + } + +private: + void dfs(Robot& robot, int x, int y, int& d, set>& visited){ + + robot.clean(); + visited.insert({x, y}); + + robot.turnLeft(); + d = (d - 1 + 4) % 4; + + int L = ((x == 0 && y == 0) ? 4 : 3); + for(int i = 0; i < L; i ++){ + int nx = x + dirs[d][0], ny = y + dirs[d][1]; + if(visited.count({nx, ny})){ + robot.turnRight(); + d = (d + 1) % 4; + } + else if(!robot.move()){ + robot.turnRight(); + d = (d + 1) % 4; + } + else{ + dfs(robot, nx, ny, d, visited); + robot.turnLeft(); + d = (d - 1 + 4) % 4; + } + } + + robot.move(); + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0490-The-Maze/cpp-0490/CMakeLists.txt b/0001-0500/0490-The-Maze/cpp-0490/CMakeLists.txt new file mode 100644 index 00000000..dde99aba --- /dev/null +++ b/0001-0500/0490-The-Maze/cpp-0490/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0490) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0490 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0490-The-Maze/cpp-0490/main.cpp b/0001-0500/0490-The-Maze/cpp-0490/main.cpp new file mode 100644 index 00000000..ec34d691 --- /dev/null +++ b/0001-0500/0490-The-Maze/cpp-0490/main.cpp @@ -0,0 +1,114 @@ +/// Source : https://leetcode.com/problems/the-maze/description/ +/// Author : liuyubobobo +/// Time : 2018-07-11 + +#include +#include +#include +#include + +using namespace std; + +/// BFS +/// Time Complexity: O(mn) +/// Space Complexity: O(mn) +class Solution { + +private: + const int d[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; + int n, m; + +public: + bool hasPath(vector>& maze, vector& start, vector& destination) { + + n = maze.size(); + if(n == 0) return false; + m = maze[0].size(); + if(m == 0) return false; + + assert(start.size() == 2 && destination.size() == 2); + assert(inArea(start[0], start[1]) && maze[start[0]][start[1]] == 0); + assert(inArea(destination[0], destination[1]) && + maze[destination[0]][destination[1]] == 0); + + queue> q; + q.push(make_pair(start[0], start[1])); + + vector> visited(n, vector(m, false)); + visited[start[0]][start[1]] = true; + + while(!q.empty()){ + pair cur = q.front(); + q.pop(); + + for(int i = 0; i < 4 ; i ++){ + pair next = go(maze, cur, i); + if(!visited[next.first][next.second]){ + if(next.first == destination[0] && next.second == destination[1]) + return true; + + q.push(next); + visited[next.first][next.second] = true; + } + } + } + + return false; + } + +private: + pair go(const vector>& maze, + pair pos, int i){ + assert(maze[pos.first][pos.second] == 0); + while(true){ + int nextX = pos.first + d[i][0]; + int nextY = pos.second + d[i][1]; + if(inArea(nextX, nextY) && maze[nextX][nextY] == 0){ + pos.first = nextX; + pos.second = nextY; + } + else + return pos; + } + assert(false); + return make_pair(-1, -1); + } + + bool inArea(int x, int y){ + return x >= 0 && x < n && y >= 0 && y < m; + } +}; + + +void print_bool(bool res){ + cout << (res ? "True" : "False") << endl; +} + +int main() { + + vector> maze1 = { + {0, 0, 1, 0, 0}, + {0, 0, 0, 0, 0}, + {0, 0, 0, 1, 0}, + {1, 1, 0, 1, 1}, + {0, 0, 0, 0, 0} + }; + vector start1 = {0, 4}; + vector destination1 = {4, 4}; + print_bool(Solution().hasPath(maze1, start1, destination1)); + // True + + vector> maze2 = { + {0, 0, 1, 0, 0}, + {0, 0, 0, 0, 0}, + {0, 0, 0, 1, 0}, + {1, 1, 0, 1, 1}, + {0, 0, 0, 0, 0} + }; + vector start2 = {0, 4}; + vector destination2 = {3, 2}; + print_bool(Solution().hasPath(maze2, start2, destination2)); + // False + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0491-Non-decreasing-Subsequences/cpp-0491/CMakeLists.txt b/0001-0500/0491-Non-decreasing-Subsequences/cpp-0491/CMakeLists.txt new file mode 100644 index 00000000..77a0db9f --- /dev/null +++ b/0001-0500/0491-Non-decreasing-Subsequences/cpp-0491/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_0491) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_0491 main.cpp) diff --git a/0001-0500/0491-Non-decreasing-Subsequences/cpp-0491/main.cpp b/0001-0500/0491-Non-decreasing-Subsequences/cpp-0491/main.cpp new file mode 100644 index 00000000..7d170d85 --- /dev/null +++ b/0001-0500/0491-Non-decreasing-Subsequences/cpp-0491/main.cpp @@ -0,0 +1,49 @@ +/// Source : https://leetcode.com/problems/non-decreasing-subsequences/description/ +/// Author : liuyubobobo +/// Time : 2023-01-19 + +#include +#include +#include + +using namespace std; + + +/// Backtrack +/// Time Compelxity: O(2^n) +/// Space Compelxity: O(n) +class Solution { +public: + vector> findSubsequences(vector& nums) { + + int n = nums.size(); + set> res; + vector cur; + dfs(n, nums, 0, cur, res); + return vector>(res.begin(), res.end()); + } + +private: + void dfs(int n, const vector& nums, int start, + vector& cur, set>& res){ + + if(start == n){ + if(cur.size() >= 2) res.insert(cur); + return; + } + + dfs(n, nums, start + 1, cur, res); + + if(cur.empty() || nums[start] >= cur.back()){ + cur.push_back(nums[start]); + dfs(n, nums, start + 1, cur, res); + cur.pop_back(); + } + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0492-Construct-the-Rectangle/cpp-0492/CMakeLists.txt b/0001-0500/0492-Construct-the-Rectangle/cpp-0492/CMakeLists.txt new file mode 100644 index 00000000..13cb473e --- /dev/null +++ b/0001-0500/0492-Construct-the-Rectangle/cpp-0492/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0492) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0492 main.cpp) diff --git a/0001-0500/0492-Construct-the-Rectangle/cpp-0492/main.cpp b/0001-0500/0492-Construct-the-Rectangle/cpp-0492/main.cpp new file mode 100644 index 00000000..dfc5d5b4 --- /dev/null +++ b/0001-0500/0492-Construct-the-Rectangle/cpp-0492/main.cpp @@ -0,0 +1,31 @@ +/// Source : https://leetcode.com/problems/construct-the-rectangle/ +/// Author : liuyubobobo +/// Time : 2021-10-22 + +#include +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(sqrt(area)) +/// Space Complexity: O(1) +class Solution { +public: + vector constructRectangle(int area) { + + for(int i = (int)(sqrt(area) + 1e-6); i >= 1; i --){ + if(area % i == 0) return {area / i, i}; + } + assert(false); + return {-1, -1}; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0494-Target-Sum/cpp-0494/CMakeLists.txt b/0001-0500/0494-Target-Sum/cpp-0494/CMakeLists.txt new file mode 100644 index 00000000..0f9c11f5 --- /dev/null +++ b/0001-0500/0494-Target-Sum/cpp-0494/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0494) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main6.cpp) +add_executable(cpp_0494 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0494-Target-Sum/cpp-0494/main.cpp b/0001-0500/0494-Target-Sum/cpp-0494/main.cpp new file mode 100644 index 00000000..f5db1fd5 --- /dev/null +++ b/0001-0500/0494-Target-Sum/cpp-0494/main.cpp @@ -0,0 +1,41 @@ +/// Source : https://leetcode.com/problems/target-sum/description/ +/// Author : liuyubobobo +/// Time : 2018-09-14 + +#include +#include + +using namespace std; + + +/// Backtracking +/// Time Complexity: O(2^n) +/// Space Complexity: O(n) +class Solution { +public: + int findTargetSumWays(vector& nums, int S) { + + return dfs(nums, 0, 0, S); + } + +private: + int dfs(const vector& nums, int index, int res, int S){ + + if(index == nums.size()) + return res == S; + + int ret = 0; + ret += dfs(nums, index + 1, res - nums[index], S); + ret += dfs(nums, index + 1, res + nums[index], S); + return ret; + } +}; + + +int main() { + + vector nums = {1, 1, 1, 1, 1}; + cout << Solution().findTargetSumWays(nums, 3) << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0494-Target-Sum/cpp-0494/main2.cpp b/0001-0500/0494-Target-Sum/cpp-0494/main2.cpp new file mode 100644 index 00000000..9479a6c9 --- /dev/null +++ b/0001-0500/0494-Target-Sum/cpp-0494/main2.cpp @@ -0,0 +1,51 @@ +/// Source : https://leetcode.com/problems/target-sum/description/ +/// Author : liuyubobobo +/// Time : 2018-09-14 + +#include +#include +#include + +using namespace std; + + +/// Backtracking +/// Using Stack - Non-recursion solution +/// +/// Time Complexity: O(2^n) +/// Space Complexity: O(2^n) +class Solution { +public: + int findTargetSumWays(vector& nums, int S) { + + stack indexStack, sumStack; + indexStack.push(0); + sumStack.push(0); + int res = 0, index, sum; + while(!indexStack.empty()){ + index = indexStack.top(); + sum = sumStack.top(); + indexStack.pop(); + sumStack.pop(); + + if(index + 1 == nums.size()) + res += (sum + nums[index] == S) + (sum - nums[index] == S); + else{ + indexStack.push(index + 1); + sumStack.push(sum + nums[index]); + indexStack.push(index + 1); + sumStack.push(sum - nums[index]); + } + } + return res; + } +}; + + +int main() { + + vector nums = {1, 1, 1, 1, 1}; + cout << Solution().findTargetSumWays(nums, 3) << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0494-Target-Sum/cpp-0494/main3.cpp b/0001-0500/0494-Target-Sum/cpp-0494/main3.cpp new file mode 100644 index 00000000..a4d32de1 --- /dev/null +++ b/0001-0500/0494-Target-Sum/cpp-0494/main3.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/target-sum/description/ +/// Author : liuyubobobo +/// Time : 2018-09-14 + +#include +#include +#include + +using namespace std; + + +/// Memory Search +/// Using TreeSet +/// +/// Time Complexity: O(n * maxNum * log(n * maxNum)) +/// Space Complexity: O(n * maxNum) +class Solution { +public: + int findTargetSumWays(vector& nums, int S) { + + map, int> dp; + return dfs(nums, 0, S, dp); + } + +private: + int dfs(const vector& nums, int index, int S, + map, int>& dp){ + + if(index == nums.size()) + return S == 0; + + pair p = make_pair(index, S); + if(dp.count(p)) + return dp[p]; + + int ret = 0; + ret += dfs(nums, index + 1, S - nums[index], dp); + ret += dfs(nums, index + 1, S + nums[index], dp); + return dp[p] = ret; + } +}; + + +int main() { + + vector nums = {1, 1, 1, 1, 1}; + cout << Solution().findTargetSumWays(nums, 3) << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0494-Target-Sum/cpp-0494/main4.cpp b/0001-0500/0494-Target-Sum/cpp-0494/main4.cpp new file mode 100644 index 00000000..8cfd0f32 --- /dev/null +++ b/0001-0500/0494-Target-Sum/cpp-0494/main4.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/target-sum/description/ +/// Author : liuyubobobo +/// Time : 2018-09-14 + +#include +#include +#include + +using namespace std; + + +/// Memory Search +/// Using 2D-Array +/// +/// Time Complexity: O(n * maxNum) +/// Space Complexity: O(n * maxNum) +class Solution { +public: + int findTargetSumWays(vector& nums, int S) { + + vector> dp(nums.size(), vector(2001, -1)); + return dfs(nums, 0, S, dp); + } + +private: + int dfs(const vector& nums, int index, int S, + vector>& dp){ + + if(index == nums.size()) + return S == 0; + + if(S + 1000 < 0 || S + 1000 >= 2001) + return 0; + + if(dp[index][S + 1000] != -1) + return dp[index][S + 1000]; + + int ret = 0; + ret += dfs(nums, index + 1, S - nums[index], dp); + ret += dfs(nums, index + 1, S + nums[index], dp); + return dp[index][S + 1000] = ret; + } +}; + + +int main() { + + vector nums = {1, 1, 1, 1, 1}; + cout << Solution().findTargetSumWays(nums, 3) << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0494-Target-Sum/cpp-0494/main5.cpp b/0001-0500/0494-Target-Sum/cpp-0494/main5.cpp new file mode 100644 index 00000000..d7c9db72 --- /dev/null +++ b/0001-0500/0494-Target-Sum/cpp-0494/main5.cpp @@ -0,0 +1,45 @@ +/// Source : https://leetcode.com/problems/target-sum/description/ +/// Author : liuyubobobo +/// Time : 2018-09-14 + +#include +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Using 2D-Array +/// +/// Time Complexity: O(n * maxNum) +/// Space Complexity: O(n * maxNum) +class Solution { +public: + int findTargetSumWays(vector& nums, int S) { + + vector> dp(nums.size(), vector(2001, 0)); + dp[0][1000 - nums[0]] += 1; + dp[0][1000 + nums[0]] += 1; + for(int i = 1; i < nums.size(); i ++) + for(int j = 0; j < 2001; j ++){ + if(j - nums[i] >= 0 && j - nums[i] < 2001) + dp[i][j] += dp[i - 1][j - nums[i]]; + if(j + nums[i] >= 0 && j + nums[i] < 2001) + dp[i][j] += dp[i - 1][j + nums[i]]; + } + + if(1000 + S < 0 || 1000 + S >= 2001) + return 0; + return dp[nums.size() - 1][1000 + S]; + } +}; + + +int main() { + + vector nums = {1, 1, 1, 1, 1}; + cout << Solution().findTargetSumWays(nums, 3) << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0494-Target-Sum/cpp-0494/main6.cpp b/0001-0500/0494-Target-Sum/cpp-0494/main6.cpp new file mode 100644 index 00000000..ef5907b4 --- /dev/null +++ b/0001-0500/0494-Target-Sum/cpp-0494/main6.cpp @@ -0,0 +1,48 @@ +/// Source : https://leetcode.com/problems/target-sum/description/ +/// Author : liuyubobobo +/// Time : 2018-09-14 + +#include +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Using 1D Array +/// +/// Time Complexity: O(n * maxNum) +/// Space Complexity: O(maxNum) +class Solution { +public: + int findTargetSumWays(vector& nums, int S) { + + vector dp(2001, 0); + dp[1000 - nums[0]] += 1; + dp[1000 + nums[0]] += 1; + for(int i = 1; i < nums.size(); i ++){ + vector a(2001, 0); + for(int j = 0; j < 2001; j ++){ + if(j - nums[i] >= 0 && j - nums[i] < 2001) + a[j] += dp[j - nums[i]]; + if(j + nums[i] >= 0 && j + nums[i] < 2001) + a[j] += dp[j + nums[i]]; + } + dp = a; + } + + if(1000 + S < 0 || 1000 + S >= 2001) + return 0; + return dp[1000 + S]; + } +}; + + +int main() { + + vector nums = {1, 1, 1, 1, 1}; + cout << Solution().findTargetSumWays(nums, 3) << endl; + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0494-Target-Sum/java-0494/src/Solution.java b/0001-0500/0494-Target-Sum/java-0494/src/Solution.java new file mode 100644 index 00000000..729d77b6 --- /dev/null +++ b/0001-0500/0494-Target-Sum/java-0494/src/Solution.java @@ -0,0 +1,27 @@ +/// Source : https://leetcode.com/problems/target-sum/description/ +/// Author : liuyubobobo +/// Time : 2022-09-24 +class Solution { + public int findTargetSumWays(int[] nums, int target) { + + int sum = 0; + for(int num: nums) sum += num; + + if(target < -sum || target > sum) return 0; + + int n = nums.length; + int[][] dp = new int[n + 1][2 * sum + 1]; + + int offset = sum; + dp[0][0 + offset] = 1; + for(int i = 0; i < n; i ++){ + for(int s = -sum; s <= sum; s ++){ + if(-sum <= s + nums[i] && s + nums[i] <= sum) + dp[i + 1][s + offset] += dp[i][s + nums[i] + offset]; + if(-sum <= s - nums[i] && s - nums[i] <= sum) + dp[i + 1][s + offset] += dp[i][s - nums[i] + offset]; + } + } + return dp[n][target + offset]; + } +} \ No newline at end of file diff --git a/0001-0500/0495-Teemo-Attacking/cpp-0495/CMakeLists.txt b/0001-0500/0495-Teemo-Attacking/cpp-0495/CMakeLists.txt new file mode 100644 index 00000000..50d2431c --- /dev/null +++ b/0001-0500/0495-Teemo-Attacking/cpp-0495/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0495) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0495 main.cpp) diff --git a/0001-0500/0495-Teemo-Attacking/cpp-0495/main.cpp b/0001-0500/0495-Teemo-Attacking/cpp-0495/main.cpp new file mode 100644 index 00000000..cdf24563 --- /dev/null +++ b/0001-0500/0495-Teemo-Attacking/cpp-0495/main.cpp @@ -0,0 +1,39 @@ +/// Source : https://leetcode.com/problems/teemo-attacking/ +/// Author : liuyubobobo +/// Time : 2021-11-09 + +#include +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int findPoisonedDuration(vector& timeSeries, int duration) { + + int n = timeSeries.size(); + int start = timeSeries[0], end = timeSeries[0] + duration, res = 0; + for(int i = 1; i <= n; i ++) + if(i == n || timeSeries[i] > end){ + res += end - start; + if(i < n) start = timeSeries[i], end = timeSeries[i] + duration; + else break; + } + else end = timeSeries[i] + duration; + return res; + } +}; + + +int main() { + + vector t1 = {1, 2}; + cout << Solution().findPoisonedDuration(t1, 2) << endl; + // 3 + + return 0; +} diff --git a/0001-0500/0496-Next-Greater-Element-I/cpp-0496/CMakeLists.txt b/0001-0500/0496-Next-Greater-Element-I/cpp-0496/CMakeLists.txt new file mode 100644 index 00000000..a047531f --- /dev/null +++ b/0001-0500/0496-Next-Greater-Element-I/cpp-0496/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0496) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0496 main.cpp) \ No newline at end of file diff --git a/0001-0500/0496-Next-Greater-Element-I/cpp-0496/main.cpp b/0001-0500/0496-Next-Greater-Element-I/cpp-0496/main.cpp new file mode 100644 index 00000000..542440be --- /dev/null +++ b/0001-0500/0496-Next-Greater-Element-I/cpp-0496/main.cpp @@ -0,0 +1,44 @@ +/// Source : https://leetcode.com/problems/next-greater-element-i/ +/// Author : liuyubobobo +/// Time : 2021-03-08 + +#include +#include +#include +#include + +using namespace std; + + +/// Mono Stack +/// Time Complexity: O(|nums2| + |nums1|) +/// Space Complexity: O(|nums2|) +class Solution { +public: + vector nextGreaterElement(vector& nums1, vector& nums2) { + + unordered_map table; + + stack stack; + for(int e: nums2){ + + while(!stack.empty() && e > stack.top()){ + table[stack.top()] = e; + stack.pop(); + } + + stack.push(e); + } + + vector res(nums1.size(), -1); + for(int i = 0; i < nums1.size(); i ++) + if(table.count(nums1[i])) res[i] = table[nums1[i]]; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-0500/0497-Random-Point-in-Non-overlapping-Rectangles/cpp-0497/CMakeLists.txt b/0001-0500/0497-Random-Point-in-Non-overlapping-Rectangles/cpp-0497/CMakeLists.txt new file mode 100644 index 00000000..c20b72e5 --- /dev/null +++ b/0001-0500/0497-Random-Point-in-Non-overlapping-Rectangles/cpp-0497/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0497) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0497 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0497-Random-Point-in-Non-overlapping-Rectangles/cpp-0497/main.cpp b/0001-0500/0497-Random-Point-in-Non-overlapping-Rectangles/cpp-0497/main.cpp new file mode 100644 index 00000000..2bffe857 --- /dev/null +++ b/0001-0500/0497-Random-Point-in-Non-overlapping-Rectangles/cpp-0497/main.cpp @@ -0,0 +1,68 @@ +/// Source : https://leetcode.com/problems/random-point-in-non-overlapping-rectangles/description/ +/// Author : liuyubobobo +/// Time : 2018-08-28 + +#include +#include +#include +#include + +using namespace std; + + +/// PreSum and Binary Search +/// Time Complexity: init: O(n) +/// pick: O(logn) +/// Space Complexity: O(n) +class Solution { + +private: + vector> rects; + vector counts; + +public: + Solution(vector> rects): rects(rects.begin(), rects.end()) { + + counts.clear(); + counts.push_back(0); + for(const vector& rect: rects) + counts.push_back(counts.back() + (rect[2] - rect[0] + 1) * (rect[3] - rect[1] + 1)); + +// cout << "couts : "; Solution::print_vec(counts); + } + + vector pick() { + + int randNum = rand() % counts.back(); + int index = lower_bound(counts.begin(), counts.end(), randNum) - counts.begin(); + if(counts[index] != randNum) + index --; + + int offset = randNum - counts[index]; + + // int m = rects[index][3] - rects[index][1] + 1; + int n = rects[index][2] - rects[index][0] + 1; + +// cout << "rectangle : "; Solution::print_vec(rects[index]); +// cout << "offset = " << offset << "; n = " << n << endl; + + return {rects[index][0] + offset % n, rects[index][1] + offset / n}; + } + + static void print_vec(const vector& vec){ + for(int e: vec) + cout << e << " "; + cout << endl; + } +}; + + +int main() { + + vector> rects = {{-2, -2, -1, -1}, {1, 0, 3, 0}}; + Solution solution(rects); + for(int i = 0; i < 5; i ++) + Solution::print_vec(solution.pick()); + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0498-Diagonal-Traverse/cpp-0498/CMakeLists.txt b/0001-0500/0498-Diagonal-Traverse/cpp-0498/CMakeLists.txt new file mode 100644 index 00000000..31f90196 --- /dev/null +++ b/0001-0500/0498-Diagonal-Traverse/cpp-0498/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0498) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0498 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-0500/0498-Diagonal-Traverse/cpp-0498/main.cpp b/0001-0500/0498-Diagonal-Traverse/cpp-0498/main.cpp new file mode 100644 index 00000000..e8ae88b8 --- /dev/null +++ b/0001-0500/0498-Diagonal-Traverse/cpp-0498/main.cpp @@ -0,0 +1,85 @@ +/// Source : https://leetcode.com/problems/diagonal-traverse/description/ +/// Author : liuyubobobo +/// Time : 2018-06-03 + +#include +#include + +using namespace std; + +/// Simulation +/// Time Complexity: O(n * m) +/// Space Complexity: O(1) +class Solution { + +private: + int n, m; + +public: + vector findDiagonalOrder(vector>& matrix) { + + vector res; + + n = matrix.size(); + if(n == 0) + return res; + m = matrix[0].size(); + + int x = 0, y = 0; + int nextX, nextY; + bool up = true; + while(true){ + res.push_back(matrix[x][y]); + + if(up) + nextX = x - 1, nextY = y + 1; + else + nextX = x + 1, nextY = y - 1; + + if(inArea(nextX, nextY)) + x = nextX, y = nextY; + else if(up){ + if(inArea(x, y + 1)) + y ++; + else + x ++; + up = false; + } + else{ + if(inArea(x + 1, y)) + x ++; + else + y ++; + up = true; + } + + if(!inArea(x, y)) + break; + } + + return res; + } + +private: + bool inArea(int x, int y){ + return x >= 0 && x < n && y >= 0 && y < m; + } +}; + + +void print_vec(const vector& vec){ + for(int e: vec) + cout << e << " "; + cout << endl; +} + +int main() { + + vector> matrix = { + {1, 2, 3}, + {4, 5, 6}, + {7, 8, 9}}; + print_vec(Solution().findDiagonalOrder(matrix)); + + return 0; +} \ No newline at end of file diff --git a/0001-0500/0500-Keyboard-Row/cpp-0500/CMakeLists.txt b/0001-0500/0500-Keyboard-Row/cpp-0500/CMakeLists.txt new file mode 100644 index 00000000..0dccc892 --- /dev/null +++ b/0001-0500/0500-Keyboard-Row/cpp-0500/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0500) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0500 main.cpp) diff --git a/0001-0500/0500-Keyboard-Row/cpp-0500/main.cpp b/0001-0500/0500-Keyboard-Row/cpp-0500/main.cpp new file mode 100644 index 00000000..281aa3bb --- /dev/null +++ b/0001-0500/0500-Keyboard-Row/cpp-0500/main.cpp @@ -0,0 +1,44 @@ +/// Source : https://leetcode.com/problems/keyboard-row/ +/// Author : liuyubobobo +/// Time : 2021-10-30 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { + +public: + vector findWords(vector& words) { + + vector keyboard = {"qwertyuiop", "asdfghjkl", "zxcvbnm"}; + vector key(26); + for(int i = 0; i < 3; i ++) + for(char c: keyboard[i]) key[c - 'a'] = i; + + vector res; + for(const string& word: words) + if(ok(key, word)) res.push_back(word); + return res; + } + +private: + bool ok(const vector& key, const string& word){ + + int t = key[tolower(word[0]) - 'a']; + for(int i = 1; i < word.size(); i ++) + if(key[tolower(word[i]) - 'a'] != t) return false; + return true; + } +}; + + +int main() { + + return 0; +} diff --git a/0001-Two-Sum/cpp-0001/CMakeLists.txt b/0001-Two-Sum/cpp-0001/CMakeLists.txt deleted file mode 100644 index 7af49d30..00000000 --- a/0001-Two-Sum/cpp-0001/CMakeLists.txt +++ /dev/null @@ -1,7 +0,0 @@ -cmake_minimum_required(VERSION 3.5) -project(cpp_0001) - -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") - -set(SOURCE_FILES main2.cpp) -add_executable(cpp_0001 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0001-Two-Sum/cpp-0001/main.cpp b/0001-Two-Sum/cpp-0001/main.cpp deleted file mode 100644 index d6a79140..00000000 --- a/0001-Two-Sum/cpp-0001/main.cpp +++ /dev/null @@ -1,43 +0,0 @@ -/// Source : https://leetcode.com/problems/two-sum/description/ -/// Author : liuyubobobo -/// Time : 2017-11-15 - -#include -#include - -using namespace std; - -/// Brute Force -/// Time Complexity: O(n^2) -/// Space Complexity: O(1) -class Solution { -public: - vector twoSum(vector& nums, int target) { - - for(int i = 0 ; i < nums.size() ; i ++) - for(int j = i + 1 ; j < nums.size() ; j ++) - if(nums[i] + nums[j] == target){ - int res[] = {i, j}; - return vector(res, res + 2); - } - - throw invalid_argument("the input has no solution"); - } -}; - - -void printVec(const vector& vec){ - for(int e: vec) - cout << e << " "; - cout << endl; -} - -int main() { - - const int nums[] = {0,4,3,0}; - vector nums_vec( nums, nums + sizeof(nums)/sizeof(int) ); - int target = 0; - printVec(Solution().twoSum(nums_vec, target)); - - return 0; -} \ No newline at end of file diff --git a/0001-Two-Sum/cpp-0001/main2.cpp b/0001-Two-Sum/cpp-0001/main2.cpp deleted file mode 100644 index 8d1aedab..00000000 --- a/0001-Two-Sum/cpp-0001/main2.cpp +++ /dev/null @@ -1,50 +0,0 @@ -/// Source : https://leetcode.com/problems/two-sum/description/ -/// Author : liuyubobobo -/// Time : 2017-11-15 - -#include -#include -#include -#include - -using namespace std; - -/// Two-Pass Hash Table -/// Time Complexity: O(n) -/// Space Complexity: O(n) -class Solution { -public: - vector twoSum(vector& nums, int target) { - - unordered_map record; - for(int i = 0 ; i < nums.size() ; i ++) - record[nums[i]] = i; - - for(int i = 0 ; i < nums.size() ; i ++){ - unordered_map::iterator iter = record.find(target - nums[i]); - if(iter != record.end() && iter->second != i){ - int res[] = {i, iter->second}; - return vector(res, res + 2); - } - } - - throw invalid_argument("the input has no solution"); - } -}; - - -void printVec(const vector& vec){ - for(int e: vec) - cout << e << " "; - cout << endl; -} - -int main() { - - const int nums[] = {0,4,3,0}; - vector nums_vec( nums, nums + sizeof(nums)/sizeof(int) ); - int target = 0; - printVec(Solution().twoSum(nums_vec, target)); - - return 0; -} \ No newline at end of file diff --git a/0001-Two-Sum/cpp-0001/main3.cpp b/0001-Two-Sum/cpp-0001/main3.cpp deleted file mode 100644 index e4fd14b3..00000000 --- a/0001-Two-Sum/cpp-0001/main3.cpp +++ /dev/null @@ -1,50 +0,0 @@ -/// Source : https://leetcode.com/problems/two-sum/description/ -/// Author : liuyubobobo -/// Time : 2017-11-15 - -#include -#include -#include -#include - -using namespace std; - -/// One-Pass Hash Table -/// Time Complexity: O(n) -/// Space Complexity: O(n) -class Solution { -public: - vector twoSum(vector& nums, int target) { - - unordered_map record; - for(int i = 0 ; i < nums.size() ; i ++){ - - int complement = target - nums[i]; - if(record.find(complement) != record.end()){ - int res[] = {i, record[complement]}; - return vector(res, res + 2); - } - - record[nums[i]] = i; - } - - throw invalid_argument("the input has no solution"); - } -}; - - -void printVec(const vector& vec){ - for(int e: vec) - cout << e << " "; - cout << endl; -} - -int main() { - - const int nums[] = {0,4,3,0}; - vector nums_vec( nums, nums + sizeof(nums)/sizeof(int) ); - int target = 0; - printVec(Solution().twoSum(nums_vec, target)); - - return 0; -} \ No newline at end of file diff --git a/0001-Two-Sum/java-0001/src/Solution1.java b/0001-Two-Sum/java-0001/src/Solution1.java deleted file mode 100644 index f6ea5064..00000000 --- a/0001-Two-Sum/java-0001/src/Solution1.java +++ /dev/null @@ -1,36 +0,0 @@ -/// Source : https://leetcode.com/problems/two-sum/description/ -/// Author : liuyubobobo -/// Time : 2017-11-15 - -import java.util.HashMap; - -/// Brute Force -/// Time Complexity: O(n^2) -/// Space Complexity: O(1) -public class Solution1 { - - public int[] twoSum(int[] nums, int target) { - - for(int i = 0 ; i < nums.length; i ++) - for(int j = 0 ; j < nums.length ; j ++) - if(nums[i] + nums[j] == target){ - int[] res = {i, j}; - return res; - } - - throw new IllegalStateException("the input has no solution"); - } - - private static void printArr(int[] nums){ - for(int num: nums) - System.out.print(num + " "); - System.out.println(); - } - - public static void main(String[] args) { - - int[] nums = {0, 4, 3, 0}; - int target = 0; - printArr((new Solution1()).twoSum(nums, target)); - } -} diff --git a/0001-Two-Sum/java-0001/src/Solution2.java b/0001-Two-Sum/java-0001/src/Solution2.java deleted file mode 100644 index 4e7162ec..00000000 --- a/0001-Two-Sum/java-0001/src/Solution2.java +++ /dev/null @@ -1,44 +0,0 @@ -/// Source : https://leetcode.com/problems/two-sum/description/ -/// Author : liuyubobobo -/// Time : 2017-11-15 - -import java.util.HashMap; - -/// Two-Pass Hash Table -/// Time Complexity: O(n) -/// Space Complexity: O(n) -public class Solution2 { - - public int[] twoSum(int[] nums, int target) { - - HashMap record = new HashMap(); - for(int i = 0 ; i < nums.length ; i ++) - record.put(nums[i], i); - - for(int i = 0 ; i < nums.length; i ++){ - - Integer index = record.get(target - nums[i]); - if(index != null && index != i){ - int[] res = {i, index}; - return res; - } - - record.put(nums[i], i); - } - - throw new IllegalStateException("the input has no solution"); - } - - private static void printArr(int[] nums){ - for(int num: nums) - System.out.print(num + " "); - System.out.println(); - } - - public static void main(String[] args) { - - int[] nums = {0, 4, 3, 0}; - int target = 0; - printArr((new Solution2()).twoSum(nums, target)); - } -} diff --git a/0019-Remove-Nth-Node-From-End-of-List/cpp-0019/main.cpp b/0019-Remove-Nth-Node-From-End-of-List/cpp-0019/main.cpp deleted file mode 100644 index 1e187e28..00000000 --- a/0019-Remove-Nth-Node-From-End-of-List/cpp-0019/main.cpp +++ /dev/null @@ -1,108 +0,0 @@ -/// Source : https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/ -/// Author : liuyubobobo -/// Time : 2017-11-15 - -#include -#include - -using namespace std; - -///Definition for singly-linked list. -struct ListNode { - int val; - ListNode *next; - ListNode(int x) : val(x), next(NULL) {} -}; - -/// LinkedList Test Helper Functions -ListNode* createLinkedList(int arr[], int n){ - - if(n == 0) - return NULL; - - ListNode* head = new ListNode(arr[0]); - ListNode* curNode = head; - for(int i = 1 ; i < n ; i ++){ - curNode->next = new ListNode(arr[i]); - curNode = curNode->next; - } - - return head; -} - -void printLinkedList(ListNode* head){ - - if(head == NULL){ - cout<<"NULL"<val; - if(curNode->next != NULL) - cout << " -> "; - curNode = curNode->next; - } - - cout << endl; - - return; -} - -void deleteLinkedList(ListNode* head){ - - ListNode* curNode = head; - while(curNode != NULL){ - ListNode* delNode = curNode; - curNode = curNode->next; - delete delNode; - } - - return; -} - -// Time Complexity: O(n) -// Space Complexity: O(1) -class Solution { -public: - ListNode* removeNthFromEnd(ListNode* head, int n) { - - ListNode* dummyHead = new ListNode(0); - dummyHead->next = head; - - int length = 0; - for(ListNode* cur = dummyHead->next ; cur != NULL ; cur = cur->next) - length ++; - - int k = length - n; - assert(k >= 0); - ListNode* cur = dummyHead; - for(int i = 0 ; i < k ; i ++) - cur = cur->next; - - ListNode* delNode = cur->next; - cur->next = delNode->next; - delete delNode; - - ListNode* retNode = dummyHead->next; - delete dummyHead; - return retNode; - } -}; - -int main() { - - int arr[] = {1, 2, 3, 4, 5}; - int n = sizeof(arr)/sizeof(int); - - ListNode* head = createLinkedList(arr, n); - printLinkedList(head); - - head = Solution().removeNthFromEnd(head, 2); - printLinkedList(head); - - deleteLinkedList(head); - - return 0; -} \ No newline at end of file diff --git a/0019-Remove-Nth-Node-From-End-of-List/cpp-0019/main2.cpp b/0019-Remove-Nth-Node-From-End-of-List/cpp-0019/main2.cpp deleted file mode 100644 index 72731e17..00000000 --- a/0019-Remove-Nth-Node-From-End-of-List/cpp-0019/main2.cpp +++ /dev/null @@ -1,112 +0,0 @@ -/// Source : https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/ -/// Author : liuyubobobo -/// Time : 2017-11-15 - -#include -#include - -using namespace std; - -///Definition for singly-linked list. -struct ListNode { - int val; - ListNode *next; - ListNode(int x) : val(x), next(NULL) {} -}; - -/// LinkedList Test Helper Functions -ListNode* createLinkedList(int arr[], int n){ - - if(n == 0) - return NULL; - - ListNode* head = new ListNode(arr[0]); - ListNode* curNode = head; - for(int i = 1 ; i < n ; i ++){ - curNode->next = new ListNode(arr[i]); - curNode = curNode->next; - } - - return head; -} - -void printLinkedList(ListNode* head){ - - if( head == NULL ){ - cout << "NULL" << endl; - return; - } - - ListNode* curNode = head; - while(curNode != NULL){ - cout << curNode->val; - if( curNode->next != NULL ) - cout << " -> "; - curNode = curNode->next; - } - - cout << endl; - - return; -} - -void deleteLinkedList(ListNode* head){ - - ListNode* curNode = head; - while(curNode != NULL){ - ListNode* delNode = curNode; - curNode = curNode->next; - delete delNode; - } - - return; -} - -// Two Pointers - One Pass Algorithm -// Time Complexity: O(n) -// Space Complexity: O(1) -class Solution { -public: - ListNode* removeNthFromEnd(ListNode* head, int n) { - - ListNode* dummyHead = new ListNode(0); - dummyHead->next = head; - - ListNode* p = dummyHead; - ListNode* q = dummyHead; - for( int i = 0 ; i < n + 1 ; i ++ ){ - assert(q); - q = q->next; - } - - while(q){ - p = p->next; - q = q->next; - } - - ListNode* delNode = p->next; - p->next = delNode->next; - delete delNode; - - ListNode* retNode = dummyHead->next; - delete dummyHead; - - return retNode; - } -}; - -int main() { - - int arr[] = {1, 2, 3, 4, 5}; - int n = sizeof(arr)/sizeof(int); - - ListNode* head = createLinkedList(arr, n); - printLinkedList(head); - - head = Solution().removeNthFromEnd(head, 2); - printLinkedList(head); - - deleteLinkedList(head); - - return 0; -} \ No newline at end of file diff --git a/0034-Search-for-a-Range/cpp-0034/main.cpp b/0034-Search-for-a-Range/cpp-0034/main.cpp deleted file mode 100644 index d29bd4f5..00000000 --- a/0034-Search-for-a-Range/cpp-0034/main.cpp +++ /dev/null @@ -1,51 +0,0 @@ -/// Source : https://leetcode.com/problems/search-for-a-range/description/ -/// Author : liuyubobobo -/// Time : 2017-11-16 - -#include -#include -#include - -using namespace std; - -/// Linear Scan -/// Time Complexity: O(n) -/// Space Complexity: O(1) -class Solution { -public: - vector searchRange(vector& nums, int target) { - - int first = nums.size() + 1, last = -1; - for(int i = 0 ; i < nums.size() ; i ++) - if(nums[i] == target){ - first = min(first, i); - last = max(last, i); - } - - int res[2] = {first, last}; - if(first == nums.size() + 1){ - assert(last == -1); - res[0] = res[1] = -1; - } - - return vector(res, res + 2); - } -}; - - -void printVec(const vector& vec){ - for(int e: vec) - cout << e << " "; - cout << endl; -} - -int main() { - - int nums[6] = {5, 7, 7, 8, 8, 10}; - int target = 8; - vector vec(nums, nums + sizeof(nums) / sizeof(int)); - - printVec(Solution().searchRange(vec, target)); - - return 0; -} \ No newline at end of file diff --git a/0034-Search-for-a-Range/cpp-0034/main2.cpp b/0034-Search-for-a-Range/cpp-0034/main2.cpp deleted file mode 100644 index c76038ed..00000000 --- a/0034-Search-for-a-Range/cpp-0034/main2.cpp +++ /dev/null @@ -1,79 +0,0 @@ -/// Source : https://leetcode.com/problems/search-for-a-range/description/ -/// Author : liuyubobobo -/// Time : 2017-11-16 - -#include -#include -#include -#include - -using namespace std; - -/// Using STL lower_bounf and upper_bound -/// Time Complexity: O(n) -/// Space Complexity: O(1) -class Solution { -public: - vector searchRange(vector& nums, int target) { - - vector::iterator lowerIter = lower_bound(nums.begin(), nums.end(), target); - int first = -1; - if(lowerIter != nums.end() && *lowerIter == target) - first = lowerIter - nums.begin(); - - vector::iterator upperIter = upper_bound(nums.begin(), nums.end(), target); - int last = -1; - if(upperIter == nums.end() && nums.size() > 0 && nums.back() == target) - last = nums.size() - 1; - else if(upperIter != nums.end() && *(upperIter - 1) == target) - last = upperIter - nums.begin() - 1; - - if(first == -1) - assert(last == -1); - - int res[2] = {first, last}; - return vector(res, res + 2); - } -}; - - -void printVec(const vector& vec){ - for(int e: vec) - cout << e << " "; - cout << endl; -} - -int main() { - - int nums1[6] = {5, 7, 7, 8, 8, 10}; - int target1 = 8; - vector vec1(nums1, nums1 + sizeof(nums1) / sizeof(int)); - - printVec(Solution().searchRange(vec1, target1)); - // 3, 4 - - // --- - - int nums2[1] = {1}; - int target2 = 0; - vector vec2(nums2, nums2 + sizeof(nums2) / sizeof(int)); - - printVec(Solution().searchRange(vec2, target2)); - // -1, -1 - - // --- - - int nums3[1] = {1}; - int target3 = 1; - vector vec3(nums3, nums3 + sizeof(nums3) / sizeof(int)); - - printVec(Solution().searchRange(vec3, target3)); - // 0, 0 - - // --- - vector vec4; - printVec(Solution().searchRange(vec4, 0)); - // -1, -1 - - return 0; -} \ No newline at end of file diff --git a/0034-Search-for-a-Range/cpp-0034/main3.cpp b/0034-Search-for-a-Range/cpp-0034/main3.cpp deleted file mode 100644 index 3805efd4..00000000 --- a/0034-Search-for-a-Range/cpp-0034/main3.cpp +++ /dev/null @@ -1,107 +0,0 @@ -/// Source : https://leetcode.com/problems/search-for-a-range/description/ -/// Author : liuyubobobo -/// Time : 2017-11-16 - -#include -#include -#include - -using namespace std; - -/// Binary Search -/// Time Complexity: O(logn) -/// Space Complexity: O(1) -class Solution { - -public: - vector searchRange(vector& nums, int target) { - - int lowerIndex = firstOccurance(nums, target); - int first = -1; - if(lowerIndex != nums.size() && nums[lowerIndex] == target) - first = lowerIndex; - // cout << "first = " << first << endl; - - int upperIndex = lastOccurance(nums, target); - int last = -1; - if(upperIndex == nums.size() && nums.size() > 0 && nums.back() == target) - last = nums.size() - 1; - else if(upperIndex != nums.size() && nums[upperIndex - 1] == target) - last = upperIndex - 1; - // cout << "last = " << last << endl; - - int res[2] = {first, last}; - return vector(res, res + 2); - } - -private: - // same to lower_bound - int firstOccurance(const vector& nums, int target){ - - int l = 0, r = nums.size(); - while(l != r){ - int mid = l + (r - l) / 2; - if(nums[mid] < target) - l = mid + 1; - else // nums[mid] >= target - r = mid; - } - return l; - } - - // same to upper_bound - int lastOccurance(const vector& nums, int target){ - - int l = 0, r = nums.size(); - while(l != r){ - int mid = l + (r - l) / 2; - if(nums[mid] <= target) - l = mid + 1; - else // nums[mid] > target - r = mid; - } - return l; - } -}; - - -void printVec(const vector& vec){ - for(int e: vec) - cout << e << " "; - cout << endl; -} - -int main() { - - int nums1[6] = {5, 7, 7, 8, 8, 10}; - int target1 = 8; - vector vec1(nums1, nums1 + sizeof(nums1) / sizeof(int)); - - printVec(Solution().searchRange(vec1, target1)); - // 3, 4 - - // --- - - int nums2[1] = {1}; - int target2 = 0; - vector vec2(nums2, nums2 + sizeof(nums2) / sizeof(int)); - - printVec(Solution().searchRange(vec2, target2)); - // -1, -1 - - // --- - - int nums3[1] = {1}; - int target3 = 1; - vector vec3(nums3, nums3 + sizeof(nums3) / sizeof(int)); - - printVec(Solution().searchRange(vec3, target3)); - // 0, 0 - - // --- - vector vec4; - printVec(Solution().searchRange(vec4, 0)); - // -1, -1 - - return 0; -} \ No newline at end of file diff --git a/0046-Permutations/java-0046/src/Solution2.java b/0046-Permutations/java-0046/src/Solution2.java deleted file mode 100644 index d6dd823f..00000000 --- a/0046-Permutations/java-0046/src/Solution2.java +++ /dev/null @@ -1,62 +0,0 @@ -/// Source : https://leetcode.com/problems/permutations/description/ -/// Author : liuyubobobo -/// Time : 2017-11-18 - -import java.util.Arrays; -import java.util.List; -import java.util.ArrayList; - -/// Recursive get all the permutations in place -/// Time Complexity: O(n!) -/// Space Complexity: O(n) -public class Solution2 { - - private ArrayList> res; - - public List> permute(int[] nums) { - - res = new ArrayList>(); - if(nums == null || nums.length == 0) - return res; - - generatePermutation(nums, 0); - - return res; - } - - private void generatePermutation(int[] nums, int index){ - - if(index == nums.length){ - res.add(new ArrayList(Arrays.asList(nums))); - return; - } - - for(int i = 0 ; i < nums.length ; i ++){ - swap(nums, i, index); - generatePermutation(nums, index + 1); - swap(nums, i, index); - } - - return; - } - - private void swap(int[] nums, int i, int j){ - int t = nums[i]; - nums[i] = nums[j]; - nums[j] = t; - } - - private static void printList(List list){ - for(Integer e: list) - System.out.print(e + " "); - System.out.println(); - } - - public static void main(String[] args) { - - int[] nums = {1, 2, 3}; - List> res = (new Solution1()).permute(nums); - for(List list: res) - printList(list); - } -} diff --git a/0056-Merge-Intervals/cpp-0056/main.cpp b/0056-Merge-Intervals/cpp-0056/main.cpp deleted file mode 100644 index dc6f1e04..00000000 --- a/0056-Merge-Intervals/cpp-0056/main.cpp +++ /dev/null @@ -1,96 +0,0 @@ -/// Source : https://leetcode.com/problems/merge-intervals/description/ -/// Author : liuyubobobo -/// Time : 2017-11-15 - -#include -#include - -using namespace std; - -// Definition for an interval. -struct Interval { - int start; - int end; - Interval() : start(0), end(0) {} - Interval(int s, int e) : start(s), end(e) {} - - friend ostream& operator<<(ostream& os, const Interval& interval){ - os << "[" << interval.start << "," << interval.end << "]"; - return os; - } -}; - -bool intervalCmp(const Interval& interval1, const Interval& interval2){ - - if(interval1.start != interval2.start) - return interval1.start < interval2.start; - return interval1.end < interval2.end; -} - -/// Sorting -/// Time Complexity: O(nlogn) -/// Space Complexity: O(1) -class Solution { -public: - vector merge(vector& intervals) { - - if(intervals.size() <= 1) - return intervals; - - sort(intervals.begin(), intervals.end(), intervalCmp); - - vector res; - res.push_back(intervals[0]); - for(int i = 1 ; i < intervals.size() ; i ++){ - if(cross(res.back(), intervals[i])){ - Interval newInterval = mergeInterval(res.back(), intervals[i]); - res.pop_back(); - res.push_back(newInterval); - } - else - res.push_back(intervals[i]); - } - - return res; - } - -private: - bool cross(const Interval& interval1, const Interval& interval2){ - return interval2.start <= interval1.end; - } - - Interval mergeInterval(const Interval& interval1, const Interval& interval2){ - return Interval(min(interval1.start, interval2.start), - max(interval1.end, interval2.end)); - } -}; - - -void printIntervals(const vector& vec){ - for(Interval interval: vec) - cout << interval << " "; - cout << endl; -} - -int main() { - - vector vec1; - vec1.push_back(Interval(1, 3)); - vec1.push_back(Interval(2, 6)); - vec1.push_back(Interval(8, 10)); - vec1.push_back(Interval(15, 18)); - - printIntervals(Solution().merge(vec1)); - // [1,6] [8,10] [15,18] - - // --- - - vector vec2; - vec2.push_back(Interval(1, 4)); - vec2.push_back(Interval(0, 0)); - - printIntervals(Solution().merge(vec2)); - // [0,0] [1,4] - - return 0; -} \ No newline at end of file diff --git a/0064-Minimum-Path-Sum/cpp-0064/main2.cpp b/0064-Minimum-Path-Sum/cpp-0064/main2.cpp deleted file mode 100644 index cb4c69b8..00000000 --- a/0064-Minimum-Path-Sum/cpp-0064/main2.cpp +++ /dev/null @@ -1,52 +0,0 @@ -/// Source : https://leetcode.com/problems/minimum-path-sum/description/ -/// Author : liuyubobobo -/// Time : 2017-11-21 - -#include -#include -#include - -using namespace std; - -/// Dynamic Programming -/// with O(n) space, actually 2*n space -/// -/// Time Complexity: O(n^2) -/// Space Complexity: O(n) -class Solution { -public: - int minPathSum(vector>& grid) { - - int n = grid.size(); - assert(n > 0); - - int m = grid[0].size(); - assert(m > 0); - - vector> res(2, vector(m, 0)); - res[0][0] = grid[0][0]; - - for(int j = 1 ; j < m ; j ++) - res[0][j] = grid[0][j] + res[0][j-1]; - - res[1][0] = grid[0][0] + res[0][0]; - - for(int i = 1 ; i < n ; i ++){ - res[i%2][0] = grid[i][0] + res[(i-1)%2][0]; - for(int j = 1 ; j < m ; j ++) - res[i%2][j] = grid[i][j] + min(res[(i-1)%2][j], res[i%2][j-1]); - } - - return res[(n-1)%2][m-1]; - } -}; - -int main() { - - vector> grid = {{1, 3, 1}, - {1, 5, 1}, - {4, 2, 1}}; - cout << Solution().minPathSum(grid) << endl; - - return 0; -} \ No newline at end of file diff --git a/0075-Sort-Colors/cpp-0075/CMakeLists.txt b/0075-Sort-Colors/cpp-0075/CMakeLists.txt deleted file mode 100644 index 38f9ae75..00000000 --- a/0075-Sort-Colors/cpp-0075/CMakeLists.txt +++ /dev/null @@ -1,7 +0,0 @@ -cmake_minimum_required(VERSION 3.5) -project(cpp_0075) - -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") - -set(SOURCE_FILES main2.cpp) -add_executable(cpp_0075 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0075-Sort-Colors/cpp-0075/main.cpp b/0075-Sort-Colors/cpp-0075/main.cpp deleted file mode 100644 index bc40f6ee..00000000 --- a/0075-Sort-Colors/cpp-0075/main.cpp +++ /dev/null @@ -1,52 +0,0 @@ -/// Source : https://leetcode.com/problems/sort-colors/description/ -/// Author : liuyubobobo -/// Time : 2017-11-13 - -#include -#include -#include - -using namespace std; - -// Counting -// Time Complexity: O(n) -// Space Complexity: O(3) -class Solution { -public: - void sortColors(vector &nums) { - - int count[3] = {0}; - for(int i = 0 ; i < nums.size() ; i ++){ - assert(nums[i] >= 0 && nums[i] <= 2); - count[nums[i]] ++; - } - - int index = 0; - for(int i = 0 ; i < count[0] ; i ++) - nums[index++] = 0; - for(int i = 0 ; i < count[1] ; i ++) - nums[index++] = 1; - for(int i = 0 ; i < count[2] ; i ++) - nums[index++] = 2; - } -}; - - -void printArr(const vector& vec){ - for(int e: vec) - cout << e << " "; - cout << endl; -} - -int main() { - - vector vec1 = {2, 2, 2, 1, 1, 0}; - Solution().sortColors(vec1); - printArr(vec1); - - vector vec2 = {2}; - Solution().sortColors(vec2); - printArr(vec2); - - return 0; -} diff --git a/0075-Sort-Colors/cpp-0075/main2.cpp b/0075-Sort-Colors/cpp-0075/main2.cpp deleted file mode 100644 index 257a83aa..00000000 --- a/0075-Sort-Colors/cpp-0075/main2.cpp +++ /dev/null @@ -1,51 +0,0 @@ -/// Source : https://leetcode.com/problems/sort-colors/description/ -/// Author : liuyubobobo -/// Time : 2017-11-13 - -#include -#include -#include - -using namespace std; - -// Three Way Quick Sort -// Time Complexity: O(n) -// Space Complexity: O(1) -class Solution { -public: - void sortColors(vector &nums) { - - int zero = -1; // [0...zero] == 0 - int two = nums.size(); // [two...n-1] == 2 - for(int i = 0 ; i < two ; ){ - if(nums[i] == 1) - i ++; - else if (nums[i] == 2) - swap( nums[i] , nums[--two]); - else{ // nums[i] == 0 - assert(nums[i] == 0); - swap(nums[++zero] , nums[i++]); - } - } - } -}; - - -void printArr(const vector& vec){ - for(int e: vec) - cout << e << " "; - cout << endl; -} - -int main() { - - vector vec1 = {2, 2, 2, 1, 1, 0}; - Solution().sortColors(vec1); - printArr(vec1); - - vector vec2 = {2}; - Solution().sortColors(vec2); - printArr(vec2); - - return 0; -} diff --git a/0077-Combinations/cpp-0077/CMakeLists.txt b/0077-Combinations/cpp-0077/CMakeLists.txt deleted file mode 100644 index ef1b1abe..00000000 --- a/0077-Combinations/cpp-0077/CMakeLists.txt +++ /dev/null @@ -1,7 +0,0 @@ -cmake_minimum_required(VERSION 3.5) -project(cpp_0077) - -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") - -set(SOURCE_FILES main.cpp) -add_executable(cpp_0077 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0077-Combinations/cpp-0077/main.cpp b/0077-Combinations/cpp-0077/main.cpp deleted file mode 100644 index 576e629e..00000000 --- a/0077-Combinations/cpp-0077/main.cpp +++ /dev/null @@ -1,60 +0,0 @@ -/// Source : https://leetcode.com/problems/combinations/description/ -/// Author : liuyubobobo -/// Time : 2017-11-18 - -#include -#include - -using namespace std; - -/// Naive Recursive -/// Time Complexity: O(n^k) -/// Space Complexity: O(k) -class Solution { -private: - vector> res; - - void generateCombinations(int n, int k, int start, vector &c){ - - if(c.size() == k){ - res.push_back(c); - return; - } - - for(int i = start ; i <= n ; i ++){ - c.push_back( i ); - generateCombinations(n, k, i + 1, c); - c.pop_back(); - } - - return; - } -public: - vector> combine(int n, int k) { - - res.clear(); - if( n <= 0 || k <= 0 || k > n ) - return res; - - vector c; - generateCombinations(n, k, 1, c); - - return res; - } -}; - - -void printVec(const vector& vec){ - - for(int e: vec) - cout << e << " "; - cout << endl; -} - -int main() { - - vector> res = Solution().combine(4,2); - for( int i = 0 ; i < res.size() ; i ++ ) - printVec(res[i]); - return 0; -} \ No newline at end of file diff --git a/0077-Combinations/cpp-0077/main2.cpp b/0077-Combinations/cpp-0077/main2.cpp deleted file mode 100644 index dbae914b..00000000 --- a/0077-Combinations/cpp-0077/main2.cpp +++ /dev/null @@ -1,61 +0,0 @@ -/// Source : https://leetcode.com/problems/combinations/description/ -/// Author : liuyubobobo -/// Time : 2017-11-18 - -#include -#include - -using namespace std; - -/// Naive Recursive Optimized -/// Time Complexity: O(n^k) -/// Space Complexity: O(k) -class Solution { -private: - vector> res; - - void generateCombinations(int n, int k, int start, vector &c){ - - if(c.size() == k){ - res.push_back(c); - return; - } - - // i will at most be n - (k - c.size()) + 1 - for(int i = start; i <= n - (k - c.size()) + 1 ; i ++){ - c.push_back(i); - generateCombinations(n, k, i + 1 ,c); - c.pop_back(); - } - - return; - } -public: - vector> combine(int n, int k) { - - res.clear(); - if(n <= 0 || k <= 0 || k > n) - return res; - - vector c; - generateCombinations(n, k, 1, c); - - return res; - } -}; - - -void printVec(const vector& vec){ - - for(int e: vec) - cout << e << " "; - cout << endl; -} - -int main() { - - vector> res = Solution().combine(4,2); - for( int i = 0 ; i < res.size() ; i ++ ) - printVec(res[i]); - return 0; -} \ No newline at end of file diff --git a/0077-Combinations/java-0077/src/Solution2.java b/0077-Combinations/java-0077/src/Solution2.java deleted file mode 100644 index c07e90a6..00000000 --- a/0077-Combinations/java-0077/src/Solution2.java +++ /dev/null @@ -1,57 +0,0 @@ -/// Source : https://leetcode.com/problems/combinations/description/ -/// Author : liuyubobobo -/// Time : 2017-11-18 - -import java.util.List; -import java.util.ArrayList; -import java.util.LinkedList; - -/// Naive Recursive Optimized -/// Time Complexity: O(n^k) -/// Space Complexity: O(k) -public class Solution2 { - - private ArrayList> res; - - public List> combine(int n, int k) { - - res = new ArrayList>(); - if(n <= 0 || k <= 0 || k > n) - return res; - - LinkedList c = new LinkedList(); - generateCombinations(n, k, 1, c); - - return res; - } - - private void generateCombinations(int n, int k, int start, LinkedList c){ - - if(c.size() == k){ - res.add((List)c.clone()); - return; - } - - // i will at most be n - (k - c.size()) + 1 - for(int i = start ; i <= n - (k - c.size()) + 1 ; i ++){ - c.addLast(i); - generateCombinations(n, k, i + 1, c); - c.removeLast(); - } - - return; - } - - private static void printList(List list){ - for(Integer e: list) - System.out.print(e + " "); - System.out.println(); - } - - public static void main(String[] args) { - - List> res = (new Solution2()).combine(4, 2); - for(List list: res) - printList(list); - } -} diff --git a/0088-Merge-Sorted-Array/cpp-0088/CMakeLists.txt b/0088-Merge-Sorted-Array/cpp-0088/CMakeLists.txt deleted file mode 100644 index 7794d107..00000000 --- a/0088-Merge-Sorted-Array/cpp-0088/CMakeLists.txt +++ /dev/null @@ -1,7 +0,0 @@ -cmake_minimum_required(VERSION 3.5) -project(cpp_Merge_Sorted_Array) - -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") - -set(SOURCE_FILES main.cpp) -add_executable(cpp_Merge_Sorted_Array ${SOURCE_FILES}) \ No newline at end of file diff --git a/0088-Merge-Sorted-Array/cpp-0088/main.cpp b/0088-Merge-Sorted-Array/cpp-0088/main.cpp deleted file mode 100644 index 6fd1844c..00000000 --- a/0088-Merge-Sorted-Array/cpp-0088/main.cpp +++ /dev/null @@ -1,61 +0,0 @@ -/// Source : https://leetcode.com/problems/merge-sorted-array/ -/// Author : liuyubobobo -/// Time : 2016-12-06 - -#include -#include -#include - -using namespace std; - -/// Standard merge process in merge sort -/// Time Complexity: O(n) -/// Space Complexity: O(n) -class Solution { -public: - void merge(vector& nums1, int m, vector& nums2, int n) { - - assert(nums1.size() == m + n && nums2.size() == n); - - for(int i = n + m - 1 ; i >= n ; i -- ) - nums1[i] = nums1[i - n]; - - int i = n; // pointer for nums1 [n, n+m) - int j = 0; // pointer for nums2 [0, n) - int k = 0; // pointer merged nums1 [0, n+m) - while( k < n + m ){ - if( i >= n+m ) - nums1[k++] = nums2[j++]; - else if( j >= n ) - nums1[k++] = nums1[i++]; - else if( nums1[i] < nums2[j] ) - nums1[k++] = nums1[i++]; - else - nums1[k++] = nums2[j++]; - } - } -}; - - -void printVec(const vector& vec){ - for(int e: vec) - cout << e << " "; - cout << endl; -} - -int main() { - - vector nums1 = {1, 3, 5, 7}; - int m = nums1.size(); - - vector nums2 = {2, 4, 6}; - int n = nums2.size(); - - for( int i = 0 ; i < nums2.size() ; i ++ ) - nums1.push_back(0); - - Solution().merge(nums1, m, nums2, n); - printVec(nums1); - - return 0; -} \ No newline at end of file diff --git a/0094-Binary-Tree-Inorder-Traversal/cpp-0094/CMakeLists.txt b/0094-Binary-Tree-Inorder-Traversal/cpp-0094/CMakeLists.txt deleted file mode 100644 index a0fff8de..00000000 --- a/0094-Binary-Tree-Inorder-Traversal/cpp-0094/CMakeLists.txt +++ /dev/null @@ -1,7 +0,0 @@ -cmake_minimum_required(VERSION 3.5) -project(cpp_0094) - -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") - -set(SOURCE_FILES main.cpp) -add_executable(cpp_0094 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0094-Binary-Tree-Inorder-Traversal/cpp-0094/main.cpp b/0094-Binary-Tree-Inorder-Traversal/cpp-0094/main.cpp deleted file mode 100644 index e842668a..00000000 --- a/0094-Binary-Tree-Inorder-Traversal/cpp-0094/main.cpp +++ /dev/null @@ -1,45 +0,0 @@ -/// Source : https://leetcode.com/problems/binary-tree-inorder-traversal/solution/ -/// Author : liuyubobobo -/// Time : 2017-11-17 - -#include -#include - -using namespace std; - - -/// Definition for a binary tree node. -struct TreeNode { - int val; - TreeNode *left; - TreeNode *right; - TreeNode(int x) : val(x), left(NULL), right(NULL) {} -}; - -// Recursive -// Time Complexity: O(n), n is the node number in the tree -// Space Complexity: O(h), h is the height of the tree -class Solution { -public: - vector inorderTraversal(TreeNode* root) { - - vector res; - __inorderTraversal(root, res); - return res; - } - -private: - void __inorderTraversal(TreeNode* node, vector &res){ - - if( node ){ - __inorderTraversal(node->left, res); - res.push_back( node->val ); - __inorderTraversal(node->right, res); - } - } -}; - -int main() { - - return 0; -} diff --git a/0094-Binary-Tree-Inorder-Traversal/cpp-0094/main2.cpp b/0094-Binary-Tree-Inorder-Traversal/cpp-0094/main2.cpp deleted file mode 100644 index c4630672..00000000 --- a/0094-Binary-Tree-Inorder-Traversal/cpp-0094/main2.cpp +++ /dev/null @@ -1,63 +0,0 @@ -/// Source : https://leetcode.com/problems/binary-tree-inorder-traversal/solution/ -/// Author : liuyubobobo -/// Time : 2017-11-17 - -#include -#include - -using namespace std; - - -/// Definition for a binary tree node. -struct TreeNode { - int val; - TreeNode *left; - TreeNode *right; - TreeNode(int x) : val(x), left(NULL), right(NULL) {} -}; - - -// My Non-Recursive -// Time Complexity: O(n), n is the node number in the tree -// Space Complexity: O(h), h is the height of the tree -class Solution { - -private: - struct Command{ - string s; // go, print - TreeNode* node; - Command(string s, TreeNode* node): s(s), node(node){} - }; - -public: - vector inorderTraversal(TreeNode* root) { - - vector res; - if( root == NULL ) - return res; - - stack stack; - stack.push(Command("go", root)); - while( !stack.empty() ){ - Command command = stack.top(); - stack.pop(); - - if(command.s == "print") - res.push_back(command.node->val); - else{ - assert(command.s == "go"); - if(command.node->right) - stack.push(Command("go",command.node->right)); - stack.push(Command("print", command.node)); - if(command.node->left) - stack.push(Command("go",command.node->left)); - } - } - return res; - } -}; - -int main() { - - return 0; -} diff --git a/0094-Binary-Tree-Inorder-Traversal/java-0094/src/Solution1.java b/0094-Binary-Tree-Inorder-Traversal/java-0094/src/Solution1.java deleted file mode 100644 index 7d8e15a1..00000000 --- a/0094-Binary-Tree-Inorder-Traversal/java-0094/src/Solution1.java +++ /dev/null @@ -1,35 +0,0 @@ -/// Source : https://leetcode.com/problems/binary-tree-inorder-traversal/solution/ -/// Author : liuyubobobo -/// Time : 2017-11-17 - -import java.util.ArrayList; -import java.util.List; - -// Recursive -// Time Complexity: O(n), n is the node number in the tree -// Space Complexity: O(h), h is the height of the tree -public class Solution1 { - - // Definition for a binary tree node. - public class TreeNode { - int val; - TreeNode left; - TreeNode right; - TreeNode(int x) { val = x; } - } - - public List inorderTraversal(TreeNode root) { - - ArrayList res = new ArrayList(); - inorderTraversal(root, res); - return res; - } - - private void inorderTraversal(TreeNode node, List list){ - if(node != null){ - inorderTraversal(node.left, list); - list.add(node.val); - inorderTraversal(node.right, list); - } - } -} diff --git a/0094-Binary-Tree-Inorder-Traversal/java-0094/src/Solution2.java b/0094-Binary-Tree-Inorder-Traversal/java-0094/src/Solution2.java deleted file mode 100644 index deb6fa4b..00000000 --- a/0094-Binary-Tree-Inorder-Traversal/java-0094/src/Solution2.java +++ /dev/null @@ -1,56 +0,0 @@ -/// Source : https://leetcode.com/problems/binary-tree-inorder-traversal/solution/ -/// Author : liuyubobobo -/// Time : 2017-11-17 - -import java.util.ArrayList; -import java.util.List; -import java.util.Stack; - -// My Non-Recursive -// Time Complexity: O(n), n is the node number in the tree -// Space Complexity: O(h), h is the height of the tree -public class Solution2 { - - // Definition for a binary tree node. - public class TreeNode { - int val; - TreeNode left; - TreeNode right; - TreeNode(int x) { val = x; } - } - - private class Command{ - String s; // go, print - TreeNode node; - Command(String s, TreeNode node){ - this.s = s; - this.node = node; - } - }; - - public List inorderTraversal(TreeNode root) { - - ArrayList res = new ArrayList(); - if(root == null) - return res; - - Stack stack = new Stack(); - stack.push(new Command("go", root)); - while(!stack.empty()){ - Command command = stack.pop(); - - if(command.s.equals("print")) - res.add(command.node.val); - else{ - assert command.s.equals("go"); - if(command.node.right != null) - stack.push(new Command("go",command.node.right)); - stack.push(new Command("print", command.node)); - if(command.node.left != null) - stack.push(new Command("go",command.node.left)); - } - } - return res; - } - -} diff --git a/0102-Binary-Tree-Level-Order-Traversal/cpp-0102/CMakeLists.txt b/0102-Binary-Tree-Level-Order-Traversal/cpp-0102/CMakeLists.txt deleted file mode 100644 index 84104d8d..00000000 --- a/0102-Binary-Tree-Level-Order-Traversal/cpp-0102/CMakeLists.txt +++ /dev/null @@ -1,7 +0,0 @@ -cmake_minimum_required(VERSION 3.5) -project(cpp_0102) - -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") - -set(SOURCE_FILES main.cpp) -add_executable(cpp_0102 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0102-Binary-Tree-Level-Order-Traversal/cpp-0102/main.cpp b/0102-Binary-Tree-Level-Order-Traversal/cpp-0102/main.cpp deleted file mode 100644 index 0153babc..00000000 --- a/0102-Binary-Tree-Level-Order-Traversal/cpp-0102/main.cpp +++ /dev/null @@ -1,58 +0,0 @@ -/// Source : https://leetcode.com/problems/binary-tree-level-order-traversal/description/ -/// Author : liuyubobobo -/// Time : 2017-11-17 - -#include -#include -#include -#include - -using namespace std; - -/// Definition for a binary tree node. -struct TreeNode { - int val; - TreeNode *left; - TreeNode *right; - TreeNode(int x) : val(x), left(NULL), right(NULL) {} -}; - -/// BFS -/// Time Complexity: O(n), where n is the number of nodes in the tree -/// Space Complexity: O(n) -class Solution { -public: - vector> levelOrder(TreeNode* root) { - - vector> res; - if(root == NULL) - return res; - - queue> q; - q.push(make_pair(root, 0)); - - while(!q.empty()){ - - TreeNode* node = q.front().first; - int level = q.front().second; - q.pop(); - - if(level == res.size()) - res.push_back(vector()); - assert( level < res.size() ); - - res[level].push_back(node->val); - if(node->left) - q.push(make_pair(node->left, level + 1 )); - if(node->right) - q.push(make_pair(node->right, level + 1 )); - } - - return res; - } -}; - -int main() { - - return 0; -} \ No newline at end of file diff --git a/0102-Binary-Tree-Level-Order-Traversal/java-0102/src/Solution.java b/0102-Binary-Tree-Level-Order-Traversal/java-0102/src/Solution.java deleted file mode 100644 index 2c945ff1..00000000 --- a/0102-Binary-Tree-Level-Order-Traversal/java-0102/src/Solution.java +++ /dev/null @@ -1,51 +0,0 @@ -/// Source : https://leetcode.com/problems/binary-tree-level-order-traversal/description/ -/// Author : liuyubobobo -/// Time : 2017-11-17 - -import java.util.ArrayList; -import java.util.List; -import java.util.LinkedList; -import javafx.util.Pair; - -/// BFS -/// Time Complexity: O(n), where n is the number of nodes in the tree -/// Space Complexity: O(n) -class Solution { - - // Definition for a binary tree node. - public class TreeNode { - int val; - TreeNode left; - TreeNode right; - TreeNode(int x) { val = x; } - } - - public List> levelOrder(TreeNode root) { - - ArrayList> res = new ArrayList>(); - if(root == null) - return res; - - LinkedList> queue = new LinkedList>(); - queue.addLast(new Pair(root, 0)); - - while(!queue.isEmpty()){ - - Pair front = queue.removeFirst(); - TreeNode node = front.getKey(); - int level = front.getValue(); - - if(level == res.size()) - res.add(new ArrayList()); - assert level < res.size(); - - res.get(level).add(node.val); - if(node.left != null) - queue.addLast(new Pair(node.left, level + 1)); - if(node.right != null) - queue.addLast(new Pair(node.right, level + 1)); - } - - return res; - } -} diff --git a/0112-Path-Sum/cpp-0112/CMakeLists.txt b/0112-Path-Sum/cpp-0112/CMakeLists.txt deleted file mode 100644 index aefbd07c..00000000 --- a/0112-Path-Sum/cpp-0112/CMakeLists.txt +++ /dev/null @@ -1,7 +0,0 @@ -cmake_minimum_required(VERSION 3.5) -project(cpp_0112) - -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") - -set(SOURCE_FILES main.cpp) -add_executable(cpp_0112 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0112-Path-Sum/cpp-0112/main.cpp b/0112-Path-Sum/cpp-0112/main.cpp deleted file mode 100644 index 5314b5c2..00000000 --- a/0112-Path-Sum/cpp-0112/main.cpp +++ /dev/null @@ -1,38 +0,0 @@ -/// Source : https://leetcode.com/problems/path-sum/description/ -/// Author : liuyubobobo -/// Time : 2017-11-17 - -#include - -using namespace std; - -/// Definition for a binary tree node. -struct TreeNode { - int val; - TreeNode *left; - TreeNode *right; - TreeNode(int x) : val(x), left(NULL), right(NULL) {} -}; - -/// Recursive -/// Time Complexity: O(n), where n is the nodes' number of the tree -/// Space Complexity: O(h), where h is the height of the tree -class Solution { -public: - bool hasPathSum(TreeNode* root, int sum) { - - if(root == NULL) - return false; - - if(root->left == NULL && root->right == NULL) - return sum == root->val; - - return hasPathSum(root->left, sum - root->val) - || hasPathSum(root->right, sum - root->val); - } -}; - -int main() { - - return 0; -} \ No newline at end of file diff --git a/0112-Path-Sum/java-0112/src/Solution.java b/0112-Path-Sum/java-0112/src/Solution.java deleted file mode 100644 index 0fea2006..00000000 --- a/0112-Path-Sum/java-0112/src/Solution.java +++ /dev/null @@ -1,29 +0,0 @@ -/// Source : https://leetcode.com/problems/path-sum/description/ -/// Author : liuyubobobo -/// Time : 2017-11-17 - -/// Recursive -/// Time Complexity: O(n), where n is the nodes' number of the tree -/// Space Complexity: O(h), where h is the height of the tree -class Solution { - - // Definition for a binary tree node. - public class TreeNode { - int val; - TreeNode left; - TreeNode right; - TreeNode(int x) { val = x; } - } - - public boolean hasPathSum(TreeNode root, int sum) { - - if(root == null) - return false; - - if(root.left == null && root.right == null) - return sum == root.val; - - return hasPathSum(root.left, sum - root.val) - || hasPathSum(root.right, sum - root.val); - } -} \ No newline at end of file diff --git a/0120-Triangle/cpp-0120/CMakeLists.txt b/0120-Triangle/cpp-0120/CMakeLists.txt deleted file mode 100644 index 7fc333c8..00000000 --- a/0120-Triangle/cpp-0120/CMakeLists.txt +++ /dev/null @@ -1,7 +0,0 @@ -cmake_minimum_required(VERSION 3.5) -project(cpp_0120) - -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") - -set(SOURCE_FILES main.cpp) -add_executable(cpp_0120 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0120-Triangle/cpp-0120/main.cpp b/0120-Triangle/cpp-0120/main.cpp deleted file mode 100644 index ff99b36d..00000000 --- a/0120-Triangle/cpp-0120/main.cpp +++ /dev/null @@ -1,39 +0,0 @@ -/// Source : https://leetcode.com/problems/triangle/description/ -/// Author : liuyubobobo -/// Time : 2018-03-26 - -#include -#include - -using namespace std; - -/// Dynamic Programming -/// Time Complexity: O(n^2) -/// Space Complexity: O(1) -class Solution { -public: - int minimumTotal(vector>& triangle) { - - int n = triangle.size(); - for(int i = 1 ; i < n ; i ++){ - - triangle[i][0] += triangle[i-1][0]; - triangle[i][i] += triangle[i-1][i-1]; - for(int j = 1 ; j < i ; j ++) - triangle[i][j] += min(triangle[i-1][j-1], triangle[i-1][j]); - } - - return *min_element(triangle[n-1].begin(), triangle[n-1].end()); - } -}; - -int main() { - - vector> triangle = { {2}, - {3, 4}, - {6,5,7}, - {4,1,8,3}}; - cout << Solution().minimumTotal(triangle) << endl; - - return 0; -} \ No newline at end of file diff --git a/0144-Binary-Tree-Preorder-Traversal/cpp-0144/CMakeLists.txt b/0144-Binary-Tree-Preorder-Traversal/cpp-0144/CMakeLists.txt deleted file mode 100644 index 82de5eb2..00000000 --- a/0144-Binary-Tree-Preorder-Traversal/cpp-0144/CMakeLists.txt +++ /dev/null @@ -1,7 +0,0 @@ -cmake_minimum_required(VERSION 3.5) -project(cpp_0144) - -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") - -set(SOURCE_FILES main3.cpp) -add_executable(cpp_0144 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0144-Binary-Tree-Preorder-Traversal/java-0144/src/Solution1.java b/0144-Binary-Tree-Preorder-Traversal/java-0144/src/Solution1.java deleted file mode 100644 index 8782bdbb..00000000 --- a/0144-Binary-Tree-Preorder-Traversal/java-0144/src/Solution1.java +++ /dev/null @@ -1,34 +0,0 @@ -/// Source : https://leetcode.com/problems/binary-tree-preorder-traversal/description/ -/// Author : liuyubobobo -/// Time : 2017-11-17 -import java.util.ArrayList; -import java.util.List; - -// Recursive -// Time Complexity: O(n), n is the node number in the tree -// Space Complexity: O(h), h is the height of the tree -public class Solution1 { - - // Definition for a binary tree node. - public class TreeNode { - int val; - TreeNode left; - TreeNode right; - TreeNode(int x) { val = x; } - } - - public List preorderTraversal(TreeNode root) { - - ArrayList res = new ArrayList(); - preorderTraversal(root, res); - return res; - } - - private void preorderTraversal(TreeNode node, List list){ - if(node != null){ - list.add(node.val); - preorderTraversal(node.left, list); - preorderTraversal(node.right, list); - } - } -} diff --git a/0144-Binary-Tree-Preorder-Traversal/java-0144/src/Solution2.java b/0144-Binary-Tree-Preorder-Traversal/java-0144/src/Solution2.java deleted file mode 100644 index 8e1315c0..00000000 --- a/0144-Binary-Tree-Preorder-Traversal/java-0144/src/Solution2.java +++ /dev/null @@ -1,56 +0,0 @@ -/// Source : https://leetcode.com/problems/binary-tree-preorder-traversal/description/ -/// Author : liuyubobobo -/// Time : 2017-11-17 - -import java.util.ArrayList; -import java.util.List; -import java.util.Stack; - -// My Non-Recursive -// Time Complexity: O(n), n is the node number in the tree -// Space Complexity: O(h), h is the height of the tree -public class Solution2 { - - // Definition for a binary tree node. - public class TreeNode { - int val; - TreeNode left; - TreeNode right; - TreeNode(int x) { val = x; } - } - - private class Command{ - String s; // go, print - TreeNode node; - Command(String s, TreeNode node){ - this.s = s; - this.node = node; - } - }; - - public List preorderTraversal(TreeNode root) { - - ArrayList res = new ArrayList(); - if(root == null) - return res; - - Stack stack = new Stack(); - stack.push(new Command("go", root)); - while(!stack.empty()){ - Command command = stack.pop(); - - if(command.s.equals("print")) - res.add(command.node.val); - else{ - assert command.s.equals("go"); - if(command.node.right != null) - stack.push(new Command("go",command.node.right)); - if(command.node.left != null) - stack.push(new Command("go",command.node.left)); - stack.push(new Command("print", command.node)); - } - } - return res; - } - -} diff --git a/0144-Binary-Tree-Preorder-Traversal/java-0144/src/Solution3.java b/0144-Binary-Tree-Preorder-Traversal/java-0144/src/Solution3.java deleted file mode 100644 index c3082def..00000000 --- a/0144-Binary-Tree-Preorder-Traversal/java-0144/src/Solution3.java +++ /dev/null @@ -1,42 +0,0 @@ -/// Source : https://leetcode.com/problems/binary-tree-preorder-traversal/description/ -/// Author : liuyubobobo -/// Time : 2017-11-17 - -import java.util.ArrayList; -import java.util.List; -import java.util.Stack; - -// Classic Non-Recursive algorithm for preorder traversal -// Time Complexity: O(n), n is the node number in the tree -// Space Complexity: O(h), h is the height of the tree -public class Solution3 { - - // Definition for a binary tree node. - public class TreeNode { - int val; - TreeNode left; - TreeNode right; - TreeNode(int x) { val = x; } - } - - public List preorderTraversal(TreeNode root) { - - ArrayList res = new ArrayList(); - if(root == null) - return res; - - Stack stack = new Stack(); - stack.push(root); - while(!stack.empty()){ - TreeNode curNode = stack.pop(); - res.add(curNode.val); - - if(curNode.right != null) - stack.push(curNode.right); - if(curNode.left != null) - stack.push(curNode.left); - } - return res; - } - -} diff --git a/0145-Binary-Tree-Postorder-Traversal/cpp-0145/CMakeLists.txt b/0145-Binary-Tree-Postorder-Traversal/cpp-0145/CMakeLists.txt deleted file mode 100644 index 0cfeffda..00000000 --- a/0145-Binary-Tree-Postorder-Traversal/cpp-0145/CMakeLists.txt +++ /dev/null @@ -1,7 +0,0 @@ -cmake_minimum_required(VERSION 3.5) -project(cpp_0145) - -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") - -set(SOURCE_FILES main.cpp) -add_executable(cpp_0145 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0145-Binary-Tree-Postorder-Traversal/cpp-0145/main2.cpp b/0145-Binary-Tree-Postorder-Traversal/cpp-0145/main2.cpp deleted file mode 100644 index 3acdec3b..00000000 --- a/0145-Binary-Tree-Postorder-Traversal/cpp-0145/main2.cpp +++ /dev/null @@ -1,63 +0,0 @@ -/// Source : https://leetcode.com/problems/binary-tree-postorder-traversal/description/ -/// Author : liuyubobobo -/// Time : 2017-11-17 - -#include -#include - -using namespace std; - -/// Definition for a binary tree node. -struct TreeNode { - int val; - TreeNode *left; - TreeNode *right; - TreeNode(int x) : val(x), left(NULL), right(NULL) {} -}; - - -// Recursive -// Time Complexity: O(n), n is the node number in the tree -// Space Complexity: O(h), h is the height of the tree -class Solution { - -private: - struct Command{ - string s; // go, print - TreeNode* node; - Command(string s, TreeNode* node): s(s), node(node){} - }; - -public: - vector postorderTraversal(TreeNode* root) { - - vector res; - if(root == NULL) - return res; - - stack stack; - stack.push(Command("go", root) ); - while(!stack.empty()){ - Command command = stack.top(); - stack.pop(); - - if(command.s == "print") - res.push_back(command.node->val); - else{ - assert(command.s == "go"); - stack.push(Command("print", command.node)); - if(command.node->right) - stack.push(Command("go",command.node->right)); - if(command.node->left) - stack.push(Command("go",command.node->left)); - } - } - return res; - } -}; - -int main() { - - return 0; -} - diff --git a/0145-Binary-Tree-Postorder-Traversal/java-0145/src/Solution1.java b/0145-Binary-Tree-Postorder-Traversal/java-0145/src/Solution1.java deleted file mode 100644 index 646c778e..00000000 --- a/0145-Binary-Tree-Postorder-Traversal/java-0145/src/Solution1.java +++ /dev/null @@ -1,35 +0,0 @@ -/// Source : https://leetcode.com/problems/binary-tree-postorder-traversal/description/ -/// Author : liuyubobobo -/// Time : 2017-11-17 - -import java.util.ArrayList; -import java.util.List; - -// Recursive -// Time Complexity: O(n), n is the node number in the tree -// Space Complexity: O(h), h is the height of the tree -public class Solution1 { - - // Definition for a binary tree node. - public class TreeNode { - int val; - TreeNode left; - TreeNode right; - TreeNode(int x) { val = x; } - } - - public List postorderTraversal(TreeNode root) { - - ArrayList res = new ArrayList(); - postorderTraversal(root, res); - return res; - } - - private void postorderTraversal(TreeNode node, List list){ - if(node != null){ - postorderTraversal(node.left, list); - postorderTraversal(node.right, list); - list.add(node.val); - } - } -} diff --git a/0145-Binary-Tree-Postorder-Traversal/java-0145/src/Solution2.java b/0145-Binary-Tree-Postorder-Traversal/java-0145/src/Solution2.java deleted file mode 100644 index 62fd0fab..00000000 --- a/0145-Binary-Tree-Postorder-Traversal/java-0145/src/Solution2.java +++ /dev/null @@ -1,56 +0,0 @@ -/// Source : https://leetcode.com/problems/binary-tree-postorder-traversal/description/ -/// Author : liuyubobobo -/// Time : 2017-11-17 - -import java.util.ArrayList; -import java.util.List; -import java.util.Stack; - -// My Non-Recursive -// Time Complexity: O(n), n is the node number in the tree -// Space Complexity: O(h), h is the height of the tree -public class Solution2 { - - // Definition for a binary tree node. - public class TreeNode { - int val; - TreeNode left; - TreeNode right; - TreeNode(int x) { val = x; } - } - - private class Command{ - String s; // go, print - TreeNode node; - Command(String s, TreeNode node){ - this.s = s; - this.node = node; - } - }; - - public List postorderTraversal(TreeNode root) { - - ArrayList res = new ArrayList(); - if(root == null) - return res; - - Stack stack = new Stack(); - stack.push(new Command("go", root)); - while(!stack.empty()){ - Command command = stack.pop(); - - if(command.s.equals("print")) - res.add(command.node.val); - else{ - assert command.s.equals("go"); - stack.push(new Command("print", command.node)); - if(command.node.right != null) - stack.push(new Command("go",command.node.right)); - if(command.node.left != null) - stack.push(new Command("go",command.node.left)); - } - } - return res; - } - -} diff --git a/0149-Max-Points-on-a-Line/cpp-0149/CMakeLists.txt b/0149-Max-Points-on-a-Line/cpp-0149/CMakeLists.txt deleted file mode 100644 index abc7c3d6..00000000 --- a/0149-Max-Points-on-a-Line/cpp-0149/CMakeLists.txt +++ /dev/null @@ -1,7 +0,0 @@ -cmake_minimum_required(VERSION 3.5) -project(cpp_Max_Points_on_a_Line) - -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") - -set(SOURCE_FILES main2.cpp) -add_executable(cpp_Max_Points_on_a_Line ${SOURCE_FILES}) \ No newline at end of file diff --git a/0149-Max-Points-on-a-Line/cpp-0149/main.cpp b/0149-Max-Points-on-a-Line/cpp-0149/main.cpp deleted file mode 100644 index b8816ac3..00000000 --- a/0149-Max-Points-on-a-Line/cpp-0149/main.cpp +++ /dev/null @@ -1,100 +0,0 @@ -/// Source : https://leetcode.com/problems/max-points-on-a-line/ -/// Author : liuyubobobo -/// Time : 2017-07-17 - -#include -#include -#include - -using namespace std; - - -/// Definition for a point. -struct Point { - int x; - int y; - Point() : x(0), y(0) {} - Point(int a, int b) : x(a), y(b) {} -}; - - -/// Using Hash Map -/// Using string to record the slopes -/// Time Complexity: O(n^2) -/// Space Complexity: O(n) -class Solution { -public: - int maxPoints(vector& points) { - - if( points.size() <= 1 ) - return points.size(); - - int res = 1; - for( int i = 0 ; i < points.size() ; i ++ ){ - - unordered_map record; - int samePoint = 0; - for( int j = 0 ; j < points.size() ; j ++ ){ - - if( points[i].x == points[j].x && points[i].y == points[j].y ) - samePoint ++; - else - record[getPairStr(slope(points[j], points[i]))]++; - } - - res = max(res, samePoint); // In case the record is empty and all the points are in the same point. - for( unordered_map::iterator iter = record.begin() ; iter != record.end() ; iter ++ ) - res = max( res , iter->second + samePoint ); - } - - return res; - } - -private: - pair slope( const Point &pa, const Point &pb ){ - - int dy = pa.y - pb.y; - int dx = pa.x - pb.x; - if( dx == 0 ) - return make_pair(1,0); - if( dy == 0 ) - return make_pair(0,1); - - int g = gcd( abs(dy), abs(dx) ); - dy /= g; - dx /= g; - if( dx < 0 ){ - dy = -dy; - dx = -dx; - } - return make_pair( dy , dx ); - } - - int gcd( int a , int b ){ - - if( a < b ) - swap( a , b ); - - if( a % b == 0 ) - return b; - - return gcd( b , a%b ); - } - - string getPairStr( const pair p){ - return to_string(p.first) + "/" + to_string(p.second); - } -}; - -int main() { - - vector pvec1; - pvec1.push_back( Point(1, 1) ); - pvec1.push_back( Point(1, 1) ); - //pvec1.push_back( Point(2, 3) ); - //pvec1.push_back( Point(3, 3) ); - - cout< -#include -#include - -using namespace std; - - -/// Definition for a point. -struct Point { - int x; - int y; - Point() : x(0), y(0) {} - Point(int a, int b) : x(a), y(b) {} -}; - -/// Using Hash Map -/// Using pair directly to record the slopes -/// Time Complexity: O(n^2) -/// Space Complexity: O(n) -class Solution { -public: - int maxPoints(vector& points) { - - if( points.size() <= 1 ) - return points.size(); - - int res = 1; - for( int i = 0 ; i < points.size() ; i ++ ){ - - map, int> record; - int samePoint = 0; - for( int j = 0 ; j < points.size() ; j ++ ){ - - if( points[i].x == points[j].x && points[i].y == points[j].y ) - samePoint ++; - else - record[slope(points[j], points[i])]++; - } - - res = max(res, samePoint); // In case the record is empty and all the points are in the same point. - for( map,int>::iterator iter = record.begin() ; iter != record.end() ; iter ++ ) - res = max( res , iter->second + samePoint ); - } - - return res; - } - -private: - pair slope( const Point &pa, const Point &pb ){ - - int dy = pa.y - pb.y; - int dx = pa.x - pb.x; - if( dx == 0 ) - return make_pair(1,0); - if( dy == 0 ) - return make_pair(0,1); - - int g = gcd( abs(dy), abs(dx) ); - dy /= g; - dx /= g; - if( dx < 0 ){ - dy = -dy; - dx = -dx; - } - return make_pair( dy , dx ); - } - - int gcd( int a , int b ){ - - if( a < b ) - swap( a , b ); - - if( a % b == 0 ) - return b; - - return gcd( b , a%b ); - } -}; - -int main() { - - vector pvec1; - pvec1.push_back( Point(1, 1) ); - pvec1.push_back( Point(1, 1) ); - //pvec1.push_back( Point(2, 3) ); - //pvec1.push_back( Point(3, 3) ); - - cout< -#include -#include - -using namespace std; - -/// Floodfill -/// Time Complexity: O(n*m) -/// Space Complexity: O(n*m) -class Solution { - -private: - int d[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; - int m, n; - vector> visited; - - bool inArea(int x, int y){ - return x >= 0 && x < m && y >= 0 && y < n; - } - - void dfs(vector>& grid, int x, int y){ - - //assert(inArea(x,y)); - visited[x][y] = true; - for(int i = 0; i < 4; i ++){ - int newx = x + d[i][0]; - int newy = y + d[i][1]; - if(inArea(newx, newy) && !visited[newx][newy] && grid[newx][newy] == '1') - dfs(grid, newx, newy); - } - - return; - } - -public: - int numIslands(vector>& grid) { - - m = grid.size(); - if(m == 0) - return 0; - n = grid[0].size(); - if(n == 0) - return 0; - - for(int i = 0 ; i < m ; i ++) - visited.push_back(vector(n, false)); - - int res = 0; - for(int i = 0 ; i < m ; i ++) - for(int j = 0 ; j < n ; j ++) - if(grid[i][j] == '1' && !visited[i][j]){ - dfs(grid, i, j); - res ++; - } - return res; - } -}; - -int main() { - - char g1[4][5] = { - {'1','1','1','1','0'}, - {'1','1','0','1','0'}, - {'1','1','0','0','0'}, - {'0','0','0','0','0'} - }; - vector> grid1; - for(int i = 0 ; i < 4 ; i ++) - grid1.push_back( vector(g1[i], g1[i] + sizeof( g1[i])/sizeof(char))); - - cout << Solution().numIslands(grid1) << endl; - // 1 - - // --- - - char g2[4][5] = { - {'1','1','0','0','0'}, - {'1','1','0','0','0'}, - {'0','0','1','0','0'}, - {'0','0','0','1','1'} - }; - vector> grid2; - for(int i = 0 ; i < 4 ; i ++) - grid2.push_back(vector(g2[i], g2[i] + sizeof( g2[i])/sizeof(char))); - - cout << Solution().numIslands(grid2) << endl; - // 2 - - return 0; -} \ No newline at end of file diff --git a/0200-Number-of-Islands/java-0200/src/Solution.java b/0200-Number-of-Islands/java-0200/src/Solution.java deleted file mode 100644 index 85355074..00000000 --- a/0200-Number-of-Islands/java-0200/src/Solution.java +++ /dev/null @@ -1,75 +0,0 @@ -/// Source : https://leetcode.com/problems/number-of-islands/description/ -/// Author : liuyubobobo -/// Time : 2017-11-18 - -/// Floodfill -/// Time Complexity: O(n*m) -/// Space Complexity: O(n*m) -class Solution { - - private int d[][] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; - private int m, n; - private boolean visited[][]; - - public int numIslands(char[][] grid) { - - if(grid == null || grid.length == 0 || grid[0].length == 0) - return 0; - - m = grid.length; - n = grid[0].length; - - visited = new boolean[m][n]; - - int res = 0; - for(int i = 0 ; i < m ; i ++) - for(int j = 0 ; j < n ; j ++) - if(grid[i][j] == '1' && !visited[i][j]){ - dfs(grid, i, j); - res ++; - } - - return res; - } - - private void dfs(char[][] grid, int x, int y){ - - //assert(inArea(x,y)); - visited[x][y] = true; - for(int i = 0; i < 4; i ++){ - int newx = x + d[i][0]; - int newy = y + d[i][1]; - if(inArea(newx, newy) && !visited[newx][newy] && grid[newx][newy] == '1') - dfs(grid, newx, newy); - } - - return; - } - - private boolean inArea(int x, int y){ - return x >= 0 && x < m && y >= 0 && y < n; - } - - public static void main(String[] args) { - - char grid1[][] = { - {'1','1','1','1','0'}, - {'1','1','0','1','0'}, - {'1','1','0','0','0'}, - {'0','0','0','0','0'} - }; - System.out.println((new Solution()).numIslands(grid1)); - // 1 - - // --- - - char grid2[][] = { - {'1','1','0','0','0'}, - {'1','1','0','0','0'}, - {'0','0','1','0','0'}, - {'0','0','0','1','1'} - }; - System.out.println((new Solution()).numIslands(grid2)); - // 3 - } -} diff --git a/0203-Remove-Linked-List-Elements/cpp-0203/CMakeLists.txt b/0203-Remove-Linked-List-Elements/cpp-0203/CMakeLists.txt deleted file mode 100644 index 2711450b..00000000 --- a/0203-Remove-Linked-List-Elements/cpp-0203/CMakeLists.txt +++ /dev/null @@ -1,7 +0,0 @@ -cmake_minimum_required(VERSION 3.5) -project(cpp_0203) - -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") - -set(SOURCE_FILES main.cpp) -add_executable(cpp_0203 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0203-Remove-Linked-List-Elements/cpp-0203/main.cpp b/0203-Remove-Linked-List-Elements/cpp-0203/main.cpp deleted file mode 100644 index 0cd0fd31..00000000 --- a/0203-Remove-Linked-List-Elements/cpp-0203/main.cpp +++ /dev/null @@ -1,105 +0,0 @@ -/// Source : https://leetcode.com/problems/remove-linked-list-elements/description/ -/// Author : liuyubobobo -/// Time : 2017-11-15 - -#include - -using namespace std; - -///Definition for singly-linked list. -struct ListNode { - int val; - ListNode *next; - ListNode(int x) : val(x), next(NULL) {} -}; - -/// LinkedList Test Helper Functions -ListNode* createLinkedList(int arr[], int n){ - - if(n == 0) - return NULL; - - ListNode* head = new ListNode(arr[0]); - ListNode* curNode = head; - for(int i = 1 ; i < n ; i ++){ - curNode->next = new ListNode(arr[i]); - curNode = curNode->next; - } - - return head; -} - -void printLinkedList(ListNode* head){ - - if(head == NULL){ - cout << "NULL" << endl; - return; - } - - ListNode* curNode = head; - while(curNode != NULL){ - cout << curNode->val; - if(curNode->next != NULL) - cout << " -> "; - curNode = curNode->next; - } - - cout << endl; - - return; -} - -void deleteLinkedList(ListNode* head){ - - ListNode* curNode = head; - while(curNode != NULL){ - ListNode* delNode = curNode; - curNode = curNode->next; - delete delNode; - } - - return; -} - -// Time Complexity: O(n) -// Space Complexity: O(1) -class Solution { -public: - ListNode* removeElements(ListNode* head, int val) { - - ListNode* dummyHead = new ListNode(0); - dummyHead->next = head; - - ListNode* cur = dummyHead; - while(cur->next != NULL){ - if(cur->next->val == val){ - ListNode* delNode = cur->next; - cur->next = delNode->next; - delete delNode; - } - else - cur = cur->next; - } - - ListNode* retNode = dummyHead->next; - delete dummyHead; - - return retNode; - } -}; - -int main() { - - int arr[] = {1, 2, 6, 3, 4, 5, 6}; - int n = sizeof(arr) / sizeof(int); - - ListNode* head = createLinkedList(arr, n); - printLinkedList(head); - - Solution().removeElements(head, 6); - printLinkedList(head); - - deleteLinkedList(head); - - return 0; -} \ No newline at end of file diff --git a/0209-Minimum-Size-Subarray-Sum/cpp-0209/CMakeLists.txt b/0209-Minimum-Size-Subarray-Sum/cpp-0209/CMakeLists.txt deleted file mode 100644 index 986d9369..00000000 --- a/0209-Minimum-Size-Subarray-Sum/cpp-0209/CMakeLists.txt +++ /dev/null @@ -1,7 +0,0 @@ -cmake_minimum_required(VERSION 3.5) -project(cpp_0209) - -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") - -set(SOURCE_FILES main3.cpp) -add_executable(cpp_0209 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0209-Minimum-Size-Subarray-Sum/cpp-0209/main.cpp b/0209-Minimum-Size-Subarray-Sum/cpp-0209/main.cpp deleted file mode 100644 index 1299595e..00000000 --- a/0209-Minimum-Size-Subarray-Sum/cpp-0209/main.cpp +++ /dev/null @@ -1,46 +0,0 @@ -/// https://leetcode.com/problems/minimum-size-subarray-sum/description/ -/// Author : liuyubobobo -/// Time : 2017-11-13 - -#include -#include -#include - -using namespace std; - -// Sum Prefix -// Time Complexity: O(n^2) -// Space Complexity: O(n) -class Solution { -public: - int minSubArrayLen(int s, vector& nums) { - - assert(s > 0); - - vector sums(nums.size() + 1, 0); - for(int i = 1 ; i <= nums.size() ; i ++) - sums[i] = sums[i-1] + nums[i-1]; - - int res = nums.size() + 1; - for(int l = 0 ; l < nums.size() ; l ++) - for(int r = l ; r < nums.size() ; r ++) - if(sums[r+1] - sums[l] >= s) - res = min(res, r - l + 1); - - if(res == nums.size() + 1) - return 0; - - return res; - } -}; - -int main() { - - int nums[] = {2, 3, 1, 2, 4, 3}; - vector vec(nums, nums + sizeof(nums)/sizeof(int) ); - int s = 7; - - cout << Solution().minSubArrayLen(s, vec) << endl; - - return 0; -} \ No newline at end of file diff --git a/0209-Minimum-Size-Subarray-Sum/cpp-0209/main2.cpp b/0209-Minimum-Size-Subarray-Sum/cpp-0209/main2.cpp deleted file mode 100644 index ee74125f..00000000 --- a/0209-Minimum-Size-Subarray-Sum/cpp-0209/main2.cpp +++ /dev/null @@ -1,56 +0,0 @@ -/// https://leetcode.com/problems/minimum-size-subarray-sum/description/ -/// Author : liuyubobobo -/// Time : 2017-11-13 - -#include -#include -#include -#include - -using namespace std; - -// Sum Prefix + Binary Search -// Time Complexity: O(nlogn) -// Space Complexity: O(n) -class Solution { -public: - int minSubArrayLen(int s, vector& nums) { - - assert(s > 0); - - vector sums(nums.size() + 1, 0); - for(int i = 1 ; i <= nums.size() ; i ++) - sums[i] = sums[i-1] + nums[i-1]; - - int res = nums.size() + 1; - for(int l = 0 ; l < (int)nums.size() - 1 ; l ++){ - auto r_bound = lower_bound(sums.begin(), sums.end(), sums[l] + s); - if(r_bound != sums.end()){ - int r = r_bound - sums.begin(); - res = min(res, r - l); - } - } - - if(res == nums.size() + 1) - return 0; - - return res; - } -}; - -int main() { - - int nums1[] = {2, 3, 1, 2, 4, 3}; - vector vec1(nums1, nums1 + sizeof(nums1)/sizeof(int) ); - int s1 = 7; - cout << Solution().minSubArrayLen(s1, vec1) << endl; - // 2 - - // --- - - vector vec2; - int s2 = 100; - cout << Solution().minSubArrayLen(s2, vec2) << endl; - - return 0; -} \ No newline at end of file diff --git a/0209-Minimum-Size-Subarray-Sum/cpp-0209/main3.cpp b/0209-Minimum-Size-Subarray-Sum/cpp-0209/main3.cpp deleted file mode 100644 index 633df566..00000000 --- a/0209-Minimum-Size-Subarray-Sum/cpp-0209/main3.cpp +++ /dev/null @@ -1,50 +0,0 @@ -/// https://leetcode.com/problems/minimum-size-subarray-sum/description/ -/// Author : liuyubobobo -/// Time : 2017-11-13 - -#include -#include -#include - -using namespace std; - -// Sliding Window -// Time Complexity: O(n) -// Space Complexity: O(1) -class Solution { -public: - int minSubArrayLen(int s, vector& nums) { - - assert(s > 0); - - int l = 0 , r = -1; // sliding window: nums[l...r] - int sum = 0; - int res = nums.size() + 1; - - while(l < nums.size()){ - - if(r + 1 < nums.size() && sum < s) - sum += nums[++r]; - else - sum -= nums[l++]; - - if(sum >= s) - res = min(res, r - l + 1); - } - - if(res == nums.size() + 1) - return 0; - return res; - } -}; - -int main() { - - int nums[] = {2, 3, 1, 2, 4, 3}; - vector vec(nums, nums + sizeof(nums)/sizeof(int)); - int s = 7; - - cout << Solution().minSubArrayLen(s, vec) << endl; - - return 0; -} \ No newline at end of file diff --git a/0209-Minimum-Size-Subarray-Sum/cpp-0209/main4.cpp b/0209-Minimum-Size-Subarray-Sum/cpp-0209/main4.cpp deleted file mode 100644 index 8fff0d40..00000000 --- a/0209-Minimum-Size-Subarray-Sum/cpp-0209/main4.cpp +++ /dev/null @@ -1,55 +0,0 @@ -/// https://leetcode.com/problems/minimum-size-subarray-sum/description/ -/// Author : liuyubobobo -/// Time : 2017-11-13 - -#include -#include -#include - -using namespace std; - -// Sliding Window -// Another Implementation -// Time Complexity: O(n) -// Space Complexity: O(1) -class Solution { -public: - int minSubArrayLen(int s, vector& nums) { - - assert(s > 0); - - int l = 0 , r = -1; // sliding window: nums[l...r] - int sum = 0; - int res = nums.size() + 1; - - while(r + 1 < nums.size()){ - - while(r + 1 < nums.size() && sum < s) - sum += nums[++r]; - - if(sum >= s) - res = min(res, r - l + 1); - - while(l < nums.size() && sum >= s){ - sum -= nums[l++]; - if(sum >= s) - res = min(res, r - l + 1); - } - } - - if(res == nums.size() + 1) - return 0; - return res; - } -}; - -int main() { - - int nums[] = {2, 3, 1, 2, 4, 3}; - vector vec( nums, nums + sizeof(nums)/sizeof(int) ); - int s = 7; - - cout << Solution().minSubArrayLen(s, vec) << endl; - - return 0; -} \ No newline at end of file diff --git a/0209-Minimum-Size-Subarray-Sum/java-0209/src/Solution1.java b/0209-Minimum-Size-Subarray-Sum/java-0209/src/Solution1.java deleted file mode 100644 index 7fe0b65c..00000000 --- a/0209-Minimum-Size-Subarray-Sum/java-0209/src/Solution1.java +++ /dev/null @@ -1,38 +0,0 @@ -/// https://leetcode.com/problems/minimum-size-subarray-sum/description/ -/// Author : liuyubobobo -/// Time : 2017-11-13 - -// Sum Prefix -// Time Complexity: O(n^2) -// Space Complexity: O(n) -public class Solution1 { - - public int minSubArrayLen(int s, int[] nums) { - - if(s <= 0 || nums == null) - throw new IllegalArgumentException("Illigal Arguments"); - - int[] sums = new int[nums.length + 1]; - sums[0] = 0; - for(int i = 1 ; i <= nums.length ; i ++) - sums[i] = sums[i-1] + nums[i-1]; - - int res = nums.length + 1; - for(int l = 0 ; l < nums.length ; l ++) - for(int r = l ; r < nums.length ; r ++) - if(sums[r+1] - sums[l] >= s) - res = Math.min(res, r - l + 1); - - if(res == nums.length + 1) - return 0; - - return res; - } - - public static void main(String[] args) { - - int[] nums = {2, 3, 1, 2, 4, 3}; - int s = 7; - System.out.println((new Solution1()).minSubArrayLen(s, nums)); - } -} diff --git a/0209-Minimum-Size-Subarray-Sum/java-0209/src/Solution2.java b/0209-Minimum-Size-Subarray-Sum/java-0209/src/Solution2.java deleted file mode 100644 index bc3e16a1..00000000 --- a/0209-Minimum-Size-Subarray-Sum/java-0209/src/Solution2.java +++ /dev/null @@ -1,68 +0,0 @@ -/// https://leetcode.com/problems/minimum-size-subarray-sum/description/ -/// Author : liuyubobobo -/// Time : 2017-11-13 - -// Sum Prefix + Binary Search -// Time Complexity: O(nlogn) -// Space Complexity: O(n) -public class Solution2 { - - public int minSubArrayLen(int s, int[] nums) { - - if(s <= 0 || nums == null) - throw new IllegalArgumentException("Illigal Arguments"); - - int[] sums = new int[nums.length + 1]; - sums[0] = 0; - for(int i = 1 ; i <= nums.length ; i ++) - sums[i] = sums[i-1] + nums[i-1]; - - int res = nums.length + 1; - for(int l = 0 ; l < nums.length - 1 ; l ++){ - // Unfortunately, there's no lowerBound method in Java, - // We need to implement our own lowerBound :( - int r = lowerBound(sums, sums[l] + s); - if(r != sums.length) - res = Math.min(res, r - l); - } - - if(res == nums.length + 1) - return 0; - return res; - } - - // Find the smallest number index which is larger or equal to target - // in a sorted array nums - // If there's no such a number, in which all number in nums are smaller than target - // return nums.length - private int lowerBound(int[] nums, int target){ - - if(nums == null /*|| !isSorted(nums)*/) - throw new IllegalArgumentException("Illegal argument nums in lowerBound."); - - int l = 0, r = nums.length; - while(l != r){ - int mid = l + (r - l) / 2; - if(nums[mid] >= target) - r = mid; - else - l = mid + 1; - } - - return l; - } - - private boolean isSorted(int[] nums){ - for(int i = 1 ; i < nums.length ; i ++) - if(nums[i] < nums[i-1]) - return false; - return true; - } - - public static void main(String[] args) { - - int[] nums = {2, 3, 1, 2, 4, 3}; - int s = 7; - System.out.println((new Solution2()).minSubArrayLen(s, nums)); - } -} diff --git a/0209-Minimum-Size-Subarray-Sum/java-0209/src/Solution3.java b/0209-Minimum-Size-Subarray-Sum/java-0209/src/Solution3.java deleted file mode 100644 index 51fc8d18..00000000 --- a/0209-Minimum-Size-Subarray-Sum/java-0209/src/Solution3.java +++ /dev/null @@ -1,41 +0,0 @@ -/// https://leetcode.com/problems/minimum-size-subarray-sum/description/ -/// Author : liuyubobobo -/// Time : 2017-11-13 - -// Sliding Window -// Time Complexity: O(n) -// Space Complexity: O(1) -public class Solution3 { - - public int minSubArrayLen(int s, int[] nums) { - - if(s <= 0 || nums == null) - throw new IllegalArgumentException("Illigal Arguments"); - - int l = 0 , r = -1; // sliding window: nums[l...r] - int sum = 0; - int res = nums.length + 1; - - while(l < nums.length){ - - if(r + 1 < nums.length && sum < s) - sum += nums[++r]; - else - sum -= nums[l++]; - - if(sum >= s) - res = Math.min(res, r - l + 1); - } - - if(res == nums.length + 1) - return 0; - return res; - } - - public static void main(String[] args) { - - int[] nums = {2, 3, 1, 2, 4, 3}; - int s = 7; - System.out.println((new Solution3()).minSubArrayLen(s, nums)); - } -} diff --git a/0209-Minimum-Size-Subarray-Sum/java-0209/src/Solution4.java b/0209-Minimum-Size-Subarray-Sum/java-0209/src/Solution4.java deleted file mode 100644 index d6c024ee..00000000 --- a/0209-Minimum-Size-Subarray-Sum/java-0209/src/Solution4.java +++ /dev/null @@ -1,46 +0,0 @@ -/// https://leetcode.com/problems/minimum-size-subarray-sum/description/ -/// Author : liuyubobobo -/// Time : 2017-11-13 - -// Sliding Window -// Another Implementation -// Time Complexity: O(n) -// Space Complexity: O(1) -public class Solution4 { - - public int minSubArrayLen(int s, int[] nums) { - - if(s <= 0 || nums == null) - throw new IllegalArgumentException("Illigal Arguments"); - - int l = 0 , r = -1; // sliding window: nums[l...r] - int sum = 0; - int res = nums.length + 1; - - while(r + 1 < nums.length){ - - while(r + 1 < nums.length && sum < s) - sum += nums[++r]; - - if(sum >= s) - res = Math.min(res, r - l + 1); - - while(l < nums.length && sum >= s){ - sum -= nums[l++]; - if(sum >= s) - res = Math.min(res, r - l + 1); - } - } - - if(res == nums.length + 1) - return 0; - return res; - } - - public static void main(String[] args) { - - int[] nums = {2, 3, 1, 2, 4, 3}; - int s = 7; - System.out.println((new Solution4()).minSubArrayLen(s, nums)); - } -} diff --git a/0218-The-Skyline-Problem/cpp-0218/main.cpp b/0218-The-Skyline-Problem/cpp-0218/main.cpp deleted file mode 100644 index 66909474..00000000 --- a/0218-The-Skyline-Problem/cpp-0218/main.cpp +++ /dev/null @@ -1,163 +0,0 @@ -/// Source : https://leetcode.com/problems/the-skyline-problem/description/ -/// Author : liuyubobobo -/// Time : 2017-10-28 - -#include -#include -#include -#include -#include - -using namespace std; - -class SegmentTree{ - -private: - int n; - vector tree; - vector lazy; - -public: - SegmentTree(int n){ - - this->n = n; - - int size = 4*n; - for(int i = 0 ; i < size ; i ++){ - tree.push_back(0); - lazy.push_back(0); - } - } - - void add(int l, int r, int h){ - update(0, 0, n-1, l, r, h); - } - - int query(int index){ - return query(0, 0, n-1, index); - } - -private: - void update(int treeID, int treeL, int treeR, int l, int r, int h){ - - if(lazy[treeID] != 0){ - tree[treeID] = max(tree[treeID], lazy[treeID]); - if(treeL != treeR){ - lazy[2 * treeID + 1] = max(lazy[treeID], lazy[2 * treeID + 1]); - lazy[2 * treeID + 2] = max(lazy[treeID], lazy[2 * treeID + 2]); - } - lazy[treeID] = 0; - } - - if(treeL == l && treeR == r){ - tree[treeID] = max(tree[treeID], h); - if(treeL != treeR){ - lazy[2 * treeID + 1] = max(h, lazy[2 * treeID + 1]); - lazy[2 * treeID + 2] = max(h, lazy[2 * treeID + 2]); - } - return; - } - - int mid = (treeL + treeR) / 2; - - if(r <= mid) - update(2 * treeID + 1, treeL, mid, l, r, h); - else if(l >= mid + 1) - update(2 * treeID + 2, mid + 1, treeR, l, r, h); - else{ - update(2 * treeID + 1, treeL, mid, l, mid, h); - update(2 * treeID + 2, mid + 1, treeR, mid + 1, r, h); - } - - return; - } - - int query(int treeID, int treeL, int treeR, int index){ - - if(lazy[treeID] != 0){ - tree[treeID] = max(tree[treeID], lazy[treeID]); - if(treeL != treeR){ - lazy[2 * treeID + 1] = max(lazy[treeID], lazy[2 * treeID + 1]); - lazy[2 * treeID + 2] = max(lazy[treeID], lazy[2 * treeID + 2]); - } - lazy[treeID] = 0; - } - - if(treeL == treeR){ - assert(treeL == index); - return tree[treeID]; - } - - int mid = (treeL + treeR) / 2; - - if(index <= mid) - return query(2 * treeID + 1, treeL, mid, index); - - return query(2 * treeID + 2, mid + 1, treeR, index); - } -}; - -class Solution { -public: - vector> getSkyline(vector>& buildings) { - - // Coordinate compression - set unique_points; - for(vector info: buildings){ - unique_points.insert(info[0]); - unique_points.insert(info[1]-1); - unique_points.insert(info[1]); - } - - unordered_map indexes; - vector pos; - for(int p: unique_points){ - indexes[p] = pos.size(); - pos.push_back(p); - } - - // segment tree - SegmentTree stree(pos.size()); - for(vector info: buildings) - stree.add(indexes[info[0]], indexes[info[1]-1], info[2]); - - // get results - vector> res; - unique_points.clear(); - for(vector info: buildings){ - unique_points.insert(info[0]); - unique_points.insert(info[1]); - } - - int last = 0; - for(int p: unique_points){ - int h = stree.query(indexes[p]); - if(h != last) - res.push_back(make_pair(p, h)); - last = h; - } - - return res; - } -}; - -int main() { - - int n = 5; - int buildings[5][3] = { - {2, 9, 10}, - {3, 7, 15}, - {5, 12, 12}, - {15, 20, 10}, - {19, 24, 8} - }; - vector> vec; - for(int i = 0 ; i < n ; i ++) - vec.push_back(vector(buildings[i], buildings[i] + 3)); - - vector> res = Solution().getSkyline(vec); - for(pair p: res) - cout << p.first << " " << p.second << endl; - - return 0; -} \ No newline at end of file diff --git a/0219-Contains-Duplicate-II/cpp-0219/main.cpp b/0219-Contains-Duplicate-II/cpp-0219/main.cpp deleted file mode 100644 index 52338145..00000000 --- a/0219-Contains-Duplicate-II/cpp-0219/main.cpp +++ /dev/null @@ -1,56 +0,0 @@ -/// Source : https://leetcode.com/problems/contains-duplicate-ii/description/ -/// Author : liuyubobobo -/// Time : 2017-11-15 - -#include -#include -#include - -using namespace std; - -/// Using Hash Set -/// Time Complexity: O(n) -/// Space Complexity: O(k) -class Solution { -public: - bool containsNearbyDuplicate(vector& nums, int k) { - - if(nums.size() <= 1) - return false; - - if(k <= 0) - return false; - - unordered_set record; - for(int i = 0 ; i < nums.size() ; i ++){ - - if(record.find(nums[i]) != record.end()) - return true; - - record.insert(nums[i]); - - // 保持record中最多有k个元素 - // 因为在下一次循环中会添加一个新元素,使得总共考虑k+1个元素 - if(record.size() == k + 1) - record.erase(nums[i - k]); - } - - return false; - } -}; - - -void printBool(bool b){ - cout << (b ? "True" : "False") << endl; -} - -int main() { - - int nums[] = {1, 2, 1}; - vector vec(nums, nums + sizeof(nums)/sizeof(int)); - int k = 1; - - printBool(Solution().containsNearbyDuplicate(vec, k)); - - return 0; -} \ No newline at end of file diff --git a/0235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree/cpp-0235/main.cpp b/0235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree/cpp-0235/main.cpp deleted file mode 100644 index 416741de..00000000 --- a/0235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree/cpp-0235/main.cpp +++ /dev/null @@ -1,47 +0,0 @@ -/// Source : https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/description/ -/// Author : liuyubobobo -/// Time : 2017-11-18 - -#include -#include - -using namespace std; - - -/// Definition for a binary tree node. -struct TreeNode { - int val; - TreeNode *left; - TreeNode *right; - TreeNode(int x) : val(x), left(NULL), right(NULL) {} -}; - - -/// Recursive -/// Time Complexity: O(lgn), where n is the node's number of the tree -/// Space Complexity: O(h), where h is the height of the tree -class Solution { -public: - TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { - - assert(p != NULL && q != NULL); - - if(root == NULL) - return NULL; - - if(p->val < root->val && q->val < root->val) - return lowestCommonAncestor(root->left, p, q); - if(p->val > root->val && q->val > root->val) - return lowestCommonAncestor(root->right, p, q); - - assert(p->val == root->val || q->val == root->val - || (root->val - p->val) * (root->val - q->val) < 0); - - return root; - } -}; - -int main() { - - return 0; -} \ No newline at end of file diff --git a/0235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree/java-0235/src/Solution.java b/0235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree/java-0235/src/Solution.java deleted file mode 100644 index c3b28835..00000000 --- a/0235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree/java-0235/src/Solution.java +++ /dev/null @@ -1,36 +0,0 @@ -/// Source : https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/description/ -/// Author : liuyubobobo -/// Time : 2017-11-18 - -/// Recursive -/// Time Complexity: O(lgn), where n is the node's number of the tree -/// Space Complexity: O(h), where h is the height of the tree -class Solution { - - // Definition for a binary tree node. - public class TreeNode { - int val; - TreeNode left; - TreeNode right; - TreeNode(int x) { val = x; } - } - - public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { - - if(p == null || q == null) - throw new IllegalArgumentException("p or q can not be null."); - - if(root == null) - return null; - - if(p.val < root.val && q.val < root.val) - return lowestCommonAncestor(root.left, p, q); - if(p.val > root.val && q.val > root.val) - return lowestCommonAncestor(root.right, p, q); - - assert p.val == root.val || q.val == root.val - || (root.val - p.val) * (root.val - q.val) < 0; - - return root; - } -} diff --git a/0239-Sliding-Window-Maximum/cpp-0239/CMakeLists.txt b/0239-Sliding-Window-Maximum/cpp-0239/CMakeLists.txt deleted file mode 100644 index f5a5c3c5..00000000 --- a/0239-Sliding-Window-Maximum/cpp-0239/CMakeLists.txt +++ /dev/null @@ -1,7 +0,0 @@ -cmake_minimum_required(VERSION 3.5) -project(cpp_0239) - -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") - -set(SOURCE_FILES main2.cpp) -add_executable(cpp_0239 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0239-Sliding-Window-Maximum/cpp-0239/main.cpp b/0239-Sliding-Window-Maximum/cpp-0239/main.cpp deleted file mode 100644 index 0fe1e3f5..00000000 --- a/0239-Sliding-Window-Maximum/cpp-0239/main.cpp +++ /dev/null @@ -1,273 +0,0 @@ -/// Source : https://leetcode.com/problems/sliding-window-maximum/description/ -/// Author : liuyubobobo -/// Time : 2017-11-22 - -#include -#include -#include -#include - -using namespace std; - -/// Using Index Max Heap -/// Time Complexity: O(nlogn) -/// Space Complexity: O(n) - -// 最大索引堆 -template -class IndexMaxHeap{ - -private: - Item *data; // 最大索引堆中的数据 - int *indexes; // 最大索引堆中的索引, indexes[x] = i 表示索引i在x的位置 - int *reverse; // 最大索引堆中的反向索引, reverse[i] = x 表示索引i在x的位置 - - int count; - int capacity; - - // 索引堆中, 数据之间的比较根据data的大小进行比较, 但实际操作的是索引 - void shiftUp( int k ){ - - while( k > 1 && data[indexes[k/2]] < data[indexes[k]] ){ - swap( indexes[k/2] , indexes[k] ); - reverse[indexes[k/2]] = k/2; - reverse[indexes[k]] = k; - k /= 2; - } - } - - // 索引堆中, 数据之间的比较根据data的大小进行比较, 但实际操作的是索引 - void shiftDown( int k ){ - - while( 2*k <= count ){ - int j = 2*k; - if( j + 1 <= count && data[indexes[j+1]] > data[indexes[j]] ) - j += 1; - - if( data[indexes[k]] >= data[indexes[j]] ) - break; - - swap( indexes[k] , indexes[j] ); - reverse[indexes[k]] = k; - reverse[indexes[j]] = j; - k = j; - } - } - -public: - // 构造函数, 构造一个空的索引堆, 可容纳capacity个元素 - IndexMaxHeap(int capacity){ - - data = new Item[capacity+1]; - indexes = new int[capacity+1]; - reverse = new int[capacity+1]; - for( int i = 0 ; i <= capacity ; i ++ ) - reverse[i] = 0; - - count = 0; - this->capacity = capacity; - } - - ~IndexMaxHeap(){ - delete[] data; - delete[] indexes; - delete[] reverse; - } - - // 返回索引堆中的元素个数 - int size(){ - return count; - } - - // 返回一个布尔值, 表示索引堆中是否为空 - bool isEmpty(){ - return count == 0; - } - - // 向最大索引堆中插入一个新的元素, 新元素的索引为i, 元素为item - // 传入的i对用户而言,是从0索引的 - void insert(int i, Item item){ - assert( count + 1 <= capacity ); - assert( i + 1 >= 1 && i + 1 <= capacity ); - - // 再插入一个新元素前,还需要保证索引i所在的位置是没有元素的。 - assert( !contain(i) ); - - i += 1; - data[i] = item; - indexes[count+1] = i; - reverse[i] = count+1; - count++; - - shiftUp(count); - } - - // 从最大索引堆中取出堆顶元素, 即索引堆中所存储的最大数据 - Item extractMax(){ - assert( count > 0 ); - - Item ret = data[indexes[1]]; - swap( indexes[1] , indexes[count] ); - reverse[indexes[count]] = 0; - reverse[indexes[1]] = 1; - count--; - shiftDown(1); - return ret; - } - - // 从最大索引堆中取出堆顶元素的索引 - int extractMaxIndex(){ - assert( count > 0 ); - - int ret = indexes[1] - 1; - swap( indexes[1] , indexes[count] ); - reverse[indexes[count]] = 0; - reverse[indexes[1]] = 1; - count--; - shiftDown(1); - return ret; - } - - // 获取最大索引堆中的堆顶元素 - Item getMax(){ - assert( count > 0 ); - return data[indexes[1]]; - } - - // 获取最大索引堆中的堆顶元素的索引 - int getMaxIndex(){ - assert( count > 0 ); - return indexes[1]-1; - } - - // 看索引i所在的位置是否存在元素 - bool contain( int i ){ - assert( i + 1 >= 1 && i + 1 <= capacity ); - return reverse[i+1] != 0; - } - - // 获取最大索引堆中索引为i的元素 - Item getItem( int i ){ - assert( contain(i) ); - return data[i+1]; - } - - // 将最大索引堆中索引为i的元素修改为newItem - void change( int i , Item newItem ){ - - assert( contain(i) ); - i += 1; - data[i] = newItem; - - // 有了 reverse 之后, - // 我们可以非常简单的通过reverse直接定位索引i在indexes中的位置 - shiftUp( reverse[i] ); - shiftDown( reverse[i] ); - } - - void remove(int i){ - - change(i, INT_MIN); - - i += 1; - - int pos = reverse[i]; - swap( indexes[pos] , indexes[count] ); - reverse[indexes[count]] = count; - reverse[indexes[pos]] = pos; - - shiftDown( pos ); - shiftUp( pos ); - - assert(reverse[i] == count); - reverse[i] = 0; - count--; - } - - // 测试索引堆中的索引数组index和反向数组reverse - // 注意:这个测试在向堆中插入元素以后, 不进行extract操作有效 - bool testIndexesAndReverseIndexes(){ - - int *copyIndexes = new int[count+1]; - int *copyReverseIndexes = new int[count+1]; - - for( int i = 0 ; i <= count ; i ++ ){ - copyIndexes[i] = indexes[i]; - copyReverseIndexes[i] = reverse[i]; - } - - copyIndexes[0] = copyReverseIndexes[0] = 0; - std::sort(copyIndexes, copyIndexes + count + 1); - std::sort(copyReverseIndexes, copyReverseIndexes + count + 1); - - // 在对索引堆中的索引和反向索引进行排序后, - // 两个数组都应该正好是1...count这count个索引 - bool res = true; - for( int i = 1 ; i <= count ; i ++ ) - if( copyIndexes[i-1] + 1 != copyIndexes[i] || - copyReverseIndexes[i-1] + 1 != copyReverseIndexes[i] ){ - res = false; - break; - } - - delete[] copyIndexes; - delete[] copyReverseIndexes; - - if( !res ){ - cout<<"Error!"< maxSlidingWindow(vector& nums, int k) { - - if(k == 0 || nums.size() == 0) - return vector(); - - if(k == 1) - return nums; - - IndexMaxHeap ipq(nums.size()); - for(int i = 0 ; i < k - 1 ; i ++) - ipq.insert(i, nums[i]); - - vector res; - for(int i = k - 1 ; i < nums.size() ; i ++){ - ipq.insert(i, nums[i]); - res.push_back(ipq.getMax()); - - assert(ipq.size() == k); - ipq.remove(i - (k - 1)); - } - - return res; - } -}; - - -void printVec(const vector& vec){ - - for(int e: vec) - cout << e << " "; - cout << endl; -} - -int main() { - - vector nums = {1, 3, -1, -3, 5, 3, 6, 7}; - int k = 3; - printVec(Solution().maxSlidingWindow(nums, k)); - - return 0; -} \ No newline at end of file diff --git a/0239-Sliding-Window-Maximum/cpp-0239/main2.cpp b/0239-Sliding-Window-Maximum/cpp-0239/main2.cpp deleted file mode 100644 index 6bc260b1..00000000 --- a/0239-Sliding-Window-Maximum/cpp-0239/main2.cpp +++ /dev/null @@ -1,59 +0,0 @@ -/// Source : https://leetcode.com/problems/sliding-window-maximum/description/ -/// Author : liuyubobobo -/// Time : 2017-11-22 - -#include -#include -#include -#include - -using namespace std; - -/// Using Decreasing Queue -/// Time Complexity: O(n) -/// Space Complexity: O(n) -class Solution { -public: - vector maxSlidingWindow(vector& nums, int k) { - - if(k == 0 || nums.size() == 0) - return vector(); - - if(k == 1) - return nums; - - deque q; - vector res; - for(int i = 0 ; i < nums.size() ; i ++){ - - while(!q.empty() && q.back() < nums[i]) - q.pop_back(); - q.push_back(nums[i]); - - if(i >= k - 1){ - res.push_back(q.front()); - if(q.front() == nums[i - (k - 1)]) - q.pop_front(); - } - } - - return res; - } -}; - - -void printVec(const vector& vec){ - - for(int e: vec) - cout << e << " "; - cout << endl; -} - -int main() { - - vector nums = {1, 3, -1, -3, 5, 3, 6, 7}; - int k = 3; - printVec(Solution().maxSlidingWindow(nums, k)); - - return 0; -} \ No newline at end of file diff --git a/0257-Binary-Tree-Paths/cpp-0257/CMakeLists.txt b/0257-Binary-Tree-Paths/cpp-0257/CMakeLists.txt deleted file mode 100644 index 6800e5a8..00000000 --- a/0257-Binary-Tree-Paths/cpp-0257/CMakeLists.txt +++ /dev/null @@ -1,7 +0,0 @@ -cmake_minimum_required(VERSION 3.5) -project(cpp_0257) - -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") - -set(SOURCE_FILES main.cpp) -add_executable(cpp_0257 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0257-Binary-Tree-Paths/cpp-0257/main.cpp b/0257-Binary-Tree-Paths/cpp-0257/main.cpp deleted file mode 100644 index 0bcb85c9..00000000 --- a/0257-Binary-Tree-Paths/cpp-0257/main.cpp +++ /dev/null @@ -1,53 +0,0 @@ -/// Source : https://leetcode.com/problems/binary-tree-paths/description/ -/// Author : liuyubobobo -/// Time : 2017-11-17 - -#include -#include -#include - -using namespace std; - - -/// Definition for a binary tree node. -struct TreeNode { - int val; - TreeNode *left; - TreeNode *right; - TreeNode(int x) : val(x), left(NULL), right(NULL) {} -}; - - -/// Recursive -/// Time Complexity: O(n), where n is the node's number in the tree -/// Space Complexity: O(h), where h is the height of the tree -class Solution { -public: - vector binaryTreePaths(TreeNode* root) { - - vector res; - - if(root == NULL) - return res; - - if(root->left == NULL && root->right == NULL){ - res.push_back(to_string(root->val)); - return res; - } - - vector leftPaths = binaryTreePaths(root->left); - for(int i = 0 ; i < leftPaths.size() ; i ++) - res.push_back(to_string(root->val) + "->" + leftPaths[i]); - - vector rightPaths = binaryTreePaths(root->right); - for(int i = 0 ; i < rightPaths.size() ; i ++) - res.push_back(to_string(root->val) + "->" + rightPaths[i]); - - return res; - } -}; - -int main() { - - return 0; -} \ No newline at end of file diff --git a/0257-Binary-Tree-Paths/java-0257/src/Solution1.java b/0257-Binary-Tree-Paths/java-0257/src/Solution1.java deleted file mode 100644 index d1b89b7a..00000000 --- a/0257-Binary-Tree-Paths/java-0257/src/Solution1.java +++ /dev/null @@ -1,51 +0,0 @@ -/// Source : https://leetcode.com/problems/binary-tree-paths/description/ -/// Author : liuyubobobo -/// Time : 2017-11-17 - -import java.util.List; -import java.util.ArrayList; - -/// Recursive -/// Time Complexity: O(n), where n is the node's number in the tree -/// Space Complexity: O(h), where h is the height of the tree -public class Solution1 { - - // Definition for a binary tree node. - public class TreeNode { - int val; - TreeNode left; - TreeNode right; - TreeNode(int x) { val = x; } - } - - public List binaryTreePaths(TreeNode root) { - - ArrayList res = new ArrayList(); - - if(root == null) - return res; - - if(root.left == null && root.right == null){ - res.add(Integer.toString(root.val)); - return res; - } - - List leftPaths = binaryTreePaths(root.left); - for(String s: leftPaths){ - StringBuilder sb = new StringBuilder(Integer.toString(root.val)); - sb.append("->"); - sb.append(s); - res.add(sb.toString()); - } - - List rightPaths = binaryTreePaths(root.right); - for(String s: rightPaths) { - StringBuilder sb = new StringBuilder(Integer.toString(root.val)); - sb.append("->"); - sb.append(s); - res.add(sb.toString()); - } - - return res; - } -} diff --git a/0307-Range-Sum-Query-Mutable/cpp-0307/CMakeLists.txt b/0307-Range-Sum-Query-Mutable/cpp-0307/CMakeLists.txt deleted file mode 100644 index dd78c4fd..00000000 --- a/0307-Range-Sum-Query-Mutable/cpp-0307/CMakeLists.txt +++ /dev/null @@ -1,7 +0,0 @@ -cmake_minimum_required(VERSION 3.5) -project(cpp_0307) - -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") - -set(SOURCE_FILES main.cpp) -add_executable(cpp_0307 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0307-Range-Sum-Query-Mutable/cpp-0307/main.cpp b/0307-Range-Sum-Query-Mutable/cpp-0307/main.cpp deleted file mode 100644 index 2bc36231..00000000 --- a/0307-Range-Sum-Query-Mutable/cpp-0307/main.cpp +++ /dev/null @@ -1,144 +0,0 @@ -/// Source : https://leetcode.com/problems/range-sum-query-mutable/description/ -/// Author : liuyubobobo -/// Time : 2017-10-28 - -#include -#include -#include - -using namespace std; - -/// Segment Tree -class SegmentTree{ - -private: - vector tree; - vector nums; - -public: - SegmentTree(const vector& nums){ - - if(nums.size() == 0) - return; - - for(int num: nums) - (this->nums).push_back(num); - - int size = 4*nums.size(); - for(int i = 0 ; i < size ; i ++) - tree.push_back(-1); - - treeBuild(0, 0, nums.size()-1); - } - - void update(int index, int val){ - assert(index >= 0 && index < nums.size()); - nums[index] = val; - update(0, 0, nums.size()-1, index, val); - } - - int query(int l, int r){ - assert(l >= 0 && l < nums.size()); - assert(r >= 0 && r < nums.size()); - return query(0, 0, nums.size()-1, l, r); - } - - void print(){ - for(int e: tree) - cout << e << " "; - cout << endl; - } - -private: - void treeBuild(int treeID, int nodeLeftBound, int nodeRightBound){ - - assert(nodeLeftBound <= nodeRightBound); - if(nodeLeftBound == nodeRightBound){ - tree[treeID] = nums[nodeLeftBound]; - return; - } - - int mid = (nodeLeftBound + nodeRightBound) / 2; - treeBuild(treeID * 2 + 1, nodeLeftBound, mid); - treeBuild(treeID * 2 + 2, mid + 1, nodeRightBound); - - tree[treeID] = tree[treeID * 2 + 1] + tree[treeID * 2 + 2]; - } - - void update(int treeID, int nodeLeftBound, int nodeRightBound, int index, int val){ - - assert(nodeLeftBound <= nodeRightBound); - if(nodeLeftBound == nodeRightBound){ - assert(index == nodeLeftBound); - tree[treeID] = val; - return; - } - - int mid = (nodeLeftBound + nodeRightBound)/2; - if(index >= nodeLeftBound && index <= mid) - update(treeID * 2 + 1, nodeLeftBound, mid, index, val); - else - update(treeID * 2 + 2, mid+1, nodeRightBound, index, val); - - tree[treeID] = tree[treeID * 2 + 1] + tree[treeID * 2 + 2]; - } - - int query(int treeID, int nodeLeftBound, int nodeRightBound, int l, int r){ - - if(l == nodeLeftBound && r == nodeRightBound) - return tree[treeID]; - - int mid = (nodeLeftBound + nodeRightBound) / 2; - if(r <= mid) - return query(treeID * 2 + 1, nodeLeftBound, mid, l, r); - if(l >= mid + 1) - return query(treeID * 2 + 2, mid + 1, nodeRightBound, l, r); - - return query(treeID * 2 + 1, nodeLeftBound, mid, l, mid) + - query(treeID * 2 + 2, mid + 1, nodeRightBound, mid + 1, r); - } -}; - -class NumArray { - -private: - SegmentTree tree; - -public: - NumArray(vector nums):tree(SegmentTree(nums)) { - - tree.print(); - } - - void update(int i, int val) { - tree.update(i, val); - } - - int sumRange(int i, int j) { - return tree.query(i, j); - } -}; - -int main() { - - int nums1[] = {1, 3, 5}; - vector vec1(nums1, nums1 + sizeof(nums1)/sizeof(int)); - NumArray obj1(vec1); - - cout << obj1.sumRange(0, 2) << endl; - obj1.update(1, 2); - cout << obj1.sumRange(0, 2) << endl; - - cout << endl; - - // --- - - int nums2[] = {0, 9, 5, 7, 3}; - vector vec2(nums2, nums2 + sizeof(nums2)/sizeof(int)); - NumArray obj2(vec2); - - cout << obj2.sumRange(4, 4) << endl; - cout << obj2.sumRange(2, 4) << endl; - - return 0; -} \ No newline at end of file diff --git a/0309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown/cpp-0309/CMakeLists.txt b/0309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown/cpp-0309/CMakeLists.txt deleted file mode 100644 index e2481cd9..00000000 --- a/0309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown/cpp-0309/CMakeLists.txt +++ /dev/null @@ -1,7 +0,0 @@ -cmake_minimum_required(VERSION 3.5) -project(cpp_0309) - -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") - -set(SOURCE_FILES main2.cpp) -add_executable(cpp_0309 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown/cpp-0309/main.cpp b/0309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown/cpp-0309/main.cpp deleted file mode 100644 index c1748049..00000000 --- a/0309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown/cpp-0309/main.cpp +++ /dev/null @@ -1,42 +0,0 @@ -/// Source : https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/description/ -/// Author : liuyubobobo -/// Time : 2017-10-23 - -#include -#include - -using namespace std; - -/// Using hold and cash to trace the max money in different state -/// Time Complexity: O(n) -/// Space Complexity: O(n) -class Solution { -public: - int maxProfit(vector& prices) { - - if(prices.size() <= 1) - return 0; - - vector hold(prices.size(), INT_MIN); - vector cash(prices.size(), 0); - - hold[0] = -prices[0]; - hold[1] = max(hold[0], -prices[1]); - cash[1] = max(cash[0], hold[0] + prices[1]); - for(int i = 2 ; i < prices.size() ; i ++){ - cash[i] = max(cash[i-1], hold[i-1] + prices[i]); - hold[i] = max(hold[i-1], cash[i-2] - prices[i]); - } - - return cash.back(); - } -}; - -int main() { - - int prices1[] = {1, 2, 3, 0, 2}; - vector vec1(prices1, prices1 + sizeof(prices1)/sizeof(int)); - cout << Solution().maxProfit(vec1) << endl; - - return 0; -} \ No newline at end of file diff --git a/0309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown/cpp-0309/main2.cpp b/0309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown/cpp-0309/main2.cpp deleted file mode 100644 index 9dcb74e3..00000000 --- a/0309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown/cpp-0309/main2.cpp +++ /dev/null @@ -1,39 +0,0 @@ -/// Source : https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/description/ -/// Author : liuyubobobo -/// Time : 2017-10-24 - -#include -#include - -using namespace std; - -/// Using hold and cash to trace the max money in different state -/// Time Complexity: O(n) -/// Space Complexity: O(1) -class Solution { -public: - int maxProfit(vector& prices) { - - if(prices.size() <= 1) - return 0; - - int hold[3] = {-prices[0], max(hold[0], -prices[1]), INT_MIN}; - int cash[3] = {0, max(cash[0], hold[0] + prices[1]), 0}; - - for(int i = 2 ; i < prices.size() ; i ++){ - cash[i%3] = max(cash[(i-1)%3], hold[(i-1)%3] + prices[i]); - hold[i%3] = max(hold[(i-1)%3], cash[(i-2)%3] - prices[i]); - } - - return cash[(prices.size()-1)%3]; - } -}; - -int main() { - - int prices1[] = {1, 2, 3, 0, 2}; - vector vec1(prices1, prices1 + sizeof(prices1)/sizeof(int)); - cout << Solution().maxProfit(vec1) << endl; - - return 0; -} \ No newline at end of file diff --git a/0322-Coin-Change/cpp-0322/main.cpp b/0322-Coin-Change/cpp-0322/main.cpp deleted file mode 100644 index 79a3fbfb..00000000 --- a/0322-Coin-Change/cpp-0322/main.cpp +++ /dev/null @@ -1,82 +0,0 @@ -/// Source : https://leetcode.com/problems/coin-change/solution/ -/// Author : liuyubobobo -/// Time : 2018-03-08 - -#include -#include -#include - -using namespace std; - -/// Memory Search -/// -/// Time Complexity: O(coins_size * amount) -/// Space Complexity: O(amount) -class Solution { - -private: - vector dp; - int max_amount; - -public: - int coinChange(vector& coins, int amount) { - max_amount = amount + 1; - dp = vector(amount+1, -1); - int res = search(coins, amount); - return res == max_amount ? -1 : res; - } - -private: - int search(const vector& coins, int amount){ - - if(amount == 0) - return 0; - - if(dp[amount] != -1) - return dp[amount]; - - int res = max_amount; - for(int coin: coins) - if(amount - coin >= 0) - res = min(res, 1 + search(coins, amount -coin)); - return dp[amount] = res; - } -}; - -int main() { - - vector coins1 = {1, 2, 5}; - int amount1 = 11; - cout<< Solution().coinChange(coins1, amount1) << endl; - // 3 - - // --- - - vector coins2 = {2}; - int amount2 = 1; - cout << Solution().coinChange(coins2, amount2) << endl; - // -1 - - // --- - - vector coins3 = {2}; - int amount3 = 3; - cout << Solution().coinChange(coins3, amount3) << endl; - // -1 - - // --- - - vector coins4 = {2, 5, 10, 1}; - int amount4 = 27; - cout << Solution().coinChange(coins4, amount4) << endl; - // 4 - - // --- - - vector coins5 = {186, 419, 83, 408}; - int amount5 = 6249; - cout << Solution().coinChange(coins5, amount5) << endl; - // 20 - - return 0; -} \ No newline at end of file diff --git a/0322-Coin-Change/cpp-0322/main2.cpp b/0322-Coin-Change/cpp-0322/main2.cpp deleted file mode 100644 index 61eb3433..00000000 --- a/0322-Coin-Change/cpp-0322/main2.cpp +++ /dev/null @@ -1,67 +0,0 @@ -/// Source : https://leetcode.com/problems/coin-change/solution/ -/// Author : liuyubobobo -/// Time : 2018-03-08 - -#include -#include - -using namespace std; - -/// Dynamic Problem -/// 0-1 backpack problem -/// -/// Time Complexity: O(coins_size * amount) -/// Space Complexity: O(amount) -class Solution { -public: - int coinChange(vector& coins, int amount) { - - vector dp(amount+1, amount + 1); - dp[0] = 0; - - for(int coin: coins) - for( int j = coin ; j <= amount ; j ++ ) - if( dp[j - coin] != -1 ) - dp[j] = min( dp[j], dp[j-coin] + 1); - - return dp[amount] == amount + 1 ? -1 : dp[amount]; - } -}; - -int main() { - - vector coins1 = {1, 2, 5}; - int amount1 = 11; - cout<< Solution().coinChange(coins1, amount1) << endl; - // 3 - - // --- - - vector coins2 = {2}; - int amount2 = 1; - cout << Solution().coinChange(coins2, amount2) << endl; - // -1 - - // --- - - vector coins3 = {2}; - int amount3 = 3; - cout << Solution().coinChange(coins3, amount3) << endl; - // -1 - - // --- - - vector coins4 = {2, 5, 10, 1}; - int amount4 = 27; - cout << Solution().coinChange(coins4, amount4) << endl; - // 4 - - // --- - - vector coins5 = {186, 419, 83, 408}; - int amount5 = 6249; - cout << Solution().coinChange(coins5, amount5) << endl; - // 20 - - return 0; -} \ No newline at end of file diff --git a/0322-Coin-Change/cpp-0322/main3.cpp b/0322-Coin-Change/cpp-0322/main3.cpp deleted file mode 100644 index 528869d5..00000000 --- a/0322-Coin-Change/cpp-0322/main3.cpp +++ /dev/null @@ -1,67 +0,0 @@ -/// Source : https://leetcode.com/problems/coin-change/solution/ -/// Author : liuyubobobo -/// Time : 2018-03-08 - -#include -#include - -using namespace std; - -/// Dynamic Problem -/// 0-1 backpack problem -/// -/// Time Complexity: O(coins_size * amount) -/// Space Complexity: O(amount) -class Solution { -public: - int coinChange(vector& coins, int amount) { - - vector dp(amount + 1, amount + 1); - dp[0] = 0; - - for(int i = 1 ; i <= amount ; i ++) - for(int coin: coins) - if(i - coin >= 0) - dp[i] = min(dp[i], dp[i-coin] + 1); - - return dp[amount] == amount + 1 ? -1 : dp[amount]; - } -}; - -int main() { - - vector coins1 = {1, 2, 5}; - int amount1 = 11; - cout<< Solution().coinChange(coins1, amount1) << endl; - // 3 - - // --- - - vector coins2 = {2}; - int amount2 = 1; - cout << Solution().coinChange(coins2, amount2) << endl; - // -1 - - // --- - - vector coins3 = {2}; - int amount3 = 3; - cout << Solution().coinChange(coins3, amount3) << endl; - // -1 - - // --- - - vector coins4 = {2, 5, 10, 1}; - int amount4 = 27; - cout << Solution().coinChange(coins4, amount4) << endl; - // 4 - - // --- - - vector coins5 = {186, 419, 83, 408}; - int amount5 = 6249; - cout << Solution().coinChange(coins5, amount5) << endl; - // 20 - - return 0; -} \ No newline at end of file diff --git a/0343-Integer-Break/cpp-0343/CMakeLists.txt b/0343-Integer-Break/cpp-0343/CMakeLists.txt deleted file mode 100644 index d742267d..00000000 --- a/0343-Integer-Break/cpp-0343/CMakeLists.txt +++ /dev/null @@ -1,7 +0,0 @@ -cmake_minimum_required(VERSION 3.5) -project(cpp_0343) - -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") - -set(SOURCE_FILES main.cpp) -add_executable(cpp_0343 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0343-Integer-Break/cpp-0343/main.cpp b/0343-Integer-Break/cpp-0343/main.cpp deleted file mode 100644 index c6ee986f..00000000 --- a/0343-Integer-Break/cpp-0343/main.cpp +++ /dev/null @@ -1,53 +0,0 @@ -/// Source : https://leetcode.com/problems/integer-break/description/ -/// Author : liuyubobobo -/// Time : 2017-11-19 - -#include -#include -#include - -using namespace std; - -/// Memory Search -/// Time Complexity: O(n^2) -/// Space Complexity: O(n) -class Solution { -private: - vector memo; - - int max3(int a, int b, int c){ - return max(a, max(b, c)); - } - - int breakInteger(int n){ - - if(n == 1) - return 1; - - if(memo[n] != -1) - return memo[n]; - - int res = -1; - for(int i = 1 ; i <= n - 1 ; i ++) - res = max3(res, i * (n - i) , i * breakInteger(n - i)); - memo[n] = res; - return res; - } - -public: - int integerBreak(int n) { - assert(n >= 1); - memo.clear(); - for(int i = 0 ; i < n + 1 ; i ++) - memo.push_back(-1); - return breakInteger(n); - } -}; - -int main() { - - cout << Solution().integerBreak(2) << endl; - cout << Solution().integerBreak(10) << endl; - - return 0; -} \ No newline at end of file diff --git a/0343-Integer-Break/cpp-0343/main2.cpp b/0343-Integer-Break/cpp-0343/main2.cpp deleted file mode 100644 index 8e54728c..00000000 --- a/0343-Integer-Break/cpp-0343/main2.cpp +++ /dev/null @@ -1,44 +0,0 @@ -/// Source : https://leetcode.com/problems/integer-break/description/ -/// Author : liuyubobobo -/// Time : 2017-11-19 - -#include -#include - -using namespace std; - -/// Dynamic Programming -/// Time Complexity: O(n^2) -/// Space Complexity: O(n) -class Solution { - -private: - int max3(int a, int b, int c ){ - return max(max(a, b), c); - } - -public: - int integerBreak(int n) { - - assert(n >= 1); - - vector memo(n + 1, -1); - - memo[1] = 1; - for(int i = 2 ; i <= n ; i ++) - for(int j = 1 ; j <= i - 1 ; j ++) - memo[i] = max3(memo[i], j * (i - j), j * memo[i - j]); - - return memo[n]; - } -}; - -int main() { - - cout << Solution().integerBreak(2) << endl; - cout << Solution().integerBreak(3) << endl; - cout << Solution().integerBreak(4) << endl; - cout << Solution().integerBreak(10) << endl; - - return 0; -} \ No newline at end of file diff --git a/0347-Top-K-Frequent-Elements/cpp-0347/CMakeLists.txt b/0347-Top-K-Frequent-Elements/cpp-0347/CMakeLists.txt deleted file mode 100644 index 2dbbee57..00000000 --- a/0347-Top-K-Frequent-Elements/cpp-0347/CMakeLists.txt +++ /dev/null @@ -1,7 +0,0 @@ -cmake_minimum_required(VERSION 3.5) -project(cpp_0347) - -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") - -set(SOURCE_FILES main2.cpp) -add_executable(cpp_0347 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0347-Top-K-Frequent-Elements/cpp-0347/main.cpp b/0347-Top-K-Frequent-Elements/cpp-0347/main.cpp deleted file mode 100644 index 502636e1..00000000 --- a/0347-Top-K-Frequent-Elements/cpp-0347/main.cpp +++ /dev/null @@ -1,74 +0,0 @@ -/// Source : https://leetcode.com/problems/top-k-frequent-elements/description/ -/// Author : liuyubobobo -/// Time : 2017-11-17 - -#include -#include -#include -#include -#include - -using namespace std; - -/// Using Tree Set -/// Time Complexity: O(nlogn) -/// Space Complexity: O(n) -class Solution { - -public: - vector topKFrequent(vector& nums, int k) { - - assert(k > 0); - - unordered_map freq; - for(int num: nums) - freq[num] ++; - -// cout << "freq:" << endl; -// for(pairp: freq) -// cout << "v: " << p.first << " f: " << p.second << endl; -// cout << endl; - - assert(k <= freq.size()); - - set, greater>> record; - for(pair p: freq) - record.insert(make_pair(p.second, p.first)); - - vector res; - for(int i = 0 ; i < k ; i ++){ - set>::iterator iter = record.begin(); - advance(iter, i); - assert(iter != record.end()); - res.push_back(iter->second); - } - - return res; - } -}; - - -void printVec(const vector& vec){ - for(int e: vec) - cout << e << " "; - cout << endl; -} - -int main() { - - int nums1[] = {1, 1, 1, 2, 2, 3}; - vector vec1(nums1, nums1 + sizeof(nums1)/sizeof(int)); - int k1 = 2; - printVec(Solution().topKFrequent(vec1, k1)); - // 1, 2 - - // --- - - int nums2[] = {1, 2}; - vector vec2(nums2, nums2 + sizeof(nums2)/sizeof(int)); - int k2 = 2; - printVec(Solution().topKFrequent(vec2, k2)); - // 1, 2 - - return 0; -} \ No newline at end of file diff --git a/0347-Top-K-Frequent-Elements/cpp-0347/main2.cpp b/0347-Top-K-Frequent-Elements/cpp-0347/main2.cpp deleted file mode 100644 index 4c4b8205..00000000 --- a/0347-Top-K-Frequent-Elements/cpp-0347/main2.cpp +++ /dev/null @@ -1,58 +0,0 @@ -/// Source : https://leetcode.com/problems/top-k-frequent-elements/description/ -/// Author : liuyubobobo -/// Time : 2017-11-17 - -#include -#include -#include -#include -#include - -using namespace std; - -/// Sorting -/// Time Complexity: O(nlogn) -/// Space Complexity: O(n) -class Solution { - -private: - unordered_map freq; - -public: - vector topKFrequent(vector& nums, int k) { - - assert(k > 0); - - freq.clear(); - for(int i = 0 ; i < nums.size() ; i ++ ) - freq[nums[i]] ++; - - assert(k <= freq.size()); - - vector res; - for(pair p: freq) - res.push_back(p.first); - - sort(res.begin(), res.end(), [this](int a, int b){ - if(this->freq[a] != this->freq[b]) - return this->freq[a] > this->freq[b]; - return a < b; - }); - - return vector(res.begin(), res.begin() + k); - } -}; - -int main() { - - int nums[] = {1, 1, 1, 2, 2, 3}; - vector vec(nums, nums + sizeof(nums)/sizeof(int)); - int k = 2; - - vector res = Solution().topKFrequent(vec, 2); - for( int i = 0 ; i < res.size() ; i ++ ) - cout< -#include -#include -#include -#include - -using namespace std; - -/// Priority Queue -/// Time Complexity: O(nlogn) -/// Space Complexity: O(n) -class Solution { -public: - vector topKFrequent(vector& nums, int k) { - - assert(k > 0); - - // 统计每个元素出现的频率 - unordered_map freq; - for(int i = 0 ; i < nums.size() ; i ++ ) - freq[nums[i]] ++; - - assert(k <= freq.size()); - - // 扫描freq,维护当前出现频率最高的k个元素 - // 在优先队列中,按照频率排序,所以数据对是 (频率,元素) 的形式 - priority_queue, vector>, greater>> pq; - for(unordered_map::iterator iter = freq.begin(); - iter != freq.end(); iter ++ ){ - if(pq.size() == k){ - if(iter->second > pq.top().first){ - pq.pop(); - pq.push( make_pair(iter->second, iter->first)); - } - } - else - pq.push(make_pair(iter->second , iter->first)); - } - - vector res; - while(!pq.empty()){ - res.push_back(pq.top().second); - pq.pop(); - } - - return res; - } -}; - -int main() { - - int nums[] = {1, 1, 1, 2, 2, 3}; - vector vec(nums, nums + sizeof(nums)/sizeof(int)); - int k = 2; - - vector res = Solution().topKFrequent(vec, 2); - for( int i = 0 ; i < res.size() ; i ++ ) - cout<>{ - - @Override - public int compare(Pair p1, Pair p2){ - if(p1.getKey() != p2.getKey()) - return p1.getKey() - p2.getKey(); - return p1.getValue() - p2.getValue(); - } - } - - public List topKFrequent(int[] nums, int k) { - - if(k <= 0) - throw new IllegalArgumentException("k should be greater than 0"); - - HashMap freq = new HashMap(); - for(int i = 0 ; i < nums.length ; i ++) - if(freq.containsKey(nums[i])) - freq.put(nums[i], freq.get(nums[i]) + 1); - else - freq.put(nums[i], 1); - - if(k > freq.size()) - throw new IllegalArgumentException("k should be less than the number of unique numbers in nums"); - - PriorityQueue> pq = new PriorityQueue>(new PairComparator()); - for(Integer num: freq.keySet()){ - int numFreq = freq.get(num); - if(pq.size() == k){ - if(numFreq > pq.peek().getKey()){ - pq.poll(); - pq.add(new Pair(numFreq, num)); - } - } - else - pq.add(new Pair(numFreq, num)); - } - - ArrayList res = new ArrayList(); - while(!pq.isEmpty()) - res.add(pq.poll().getValue()); - - return res; - } - - private static void printList(List nums){ - for(Integer num: nums) - System.out.print(num + " "); - System.out.println(); - } - - public static void main(String[] args) { - - int[] nums = {1, 1, 1, 2, 2, 3}; - int k = 2; - printList((new Solution3()).topKFrequent(nums, k)); - } -} diff --git a/0350-Intersection-of-Two-Arrays-II/cpp-0350/CMakeLists.txt b/0350-Intersection-of-Two-Arrays-II/cpp-0350/CMakeLists.txt deleted file mode 100644 index 4a9a5821..00000000 --- a/0350-Intersection-of-Two-Arrays-II/cpp-0350/CMakeLists.txt +++ /dev/null @@ -1,7 +0,0 @@ -cmake_minimum_required(VERSION 3.5) -project(cpp_0350) - -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") - -set(SOURCE_FILES main.cpp) -add_executable(cpp_0350 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0350-Intersection-of-Two-Arrays-II/cpp-0350/main.cpp b/0350-Intersection-of-Two-Arrays-II/cpp-0350/main.cpp deleted file mode 100644 index ed790390..00000000 --- a/0350-Intersection-of-Two-Arrays-II/cpp-0350/main.cpp +++ /dev/null @@ -1,50 +0,0 @@ -/// Source : https://leetcode.com/problems/intersection-of-two-arrays-ii/description/ -/// Author : liuyubobobo -/// Time : 2017-11-14 - -#include -#include -#include -using namespace std; - -/// Using Hash Map -/// Time Complexity: O(len(nums1) + len(nums2)) -/// Space Complexity: O(len(nums1)) -class Solution { -public: - vector intersect(vector& nums1, vector& nums2) { - - unordered_map record; - for(int i = 0 ; i < nums1.size() ; i ++) - record[nums1[i]] += 1; - - vector resultVector; - for(int i = 0 ; i < nums2.size() ; i ++) - if(record[nums2[i]] > 0){ - resultVector.push_back(nums2[i]); - record[nums2[i]] --; - } - - return resultVector; - } -}; - - -void printVec(const vector& vec){ - for(int e: vec) - cout << e << " "; - cout << endl; -} - -int main() { - - int nums1[] = {1, 2, 2, 1}; - vector vec1(nums1, nums1 + sizeof(nums1)/sizeof(int)); - - int nums2[] = {2, 2}; - vector vec2(nums2, nums2 + sizeof(nums2)/sizeof(int)); - - printVec(Solution().intersect(vec1, vec2)); - - return 0; -} \ No newline at end of file diff --git a/0350-Intersection-of-Two-Arrays-II/cpp-0350/main2.cpp b/0350-Intersection-of-Two-Arrays-II/cpp-0350/main2.cpp deleted file mode 100644 index 2d4a9b5e..00000000 --- a/0350-Intersection-of-Two-Arrays-II/cpp-0350/main2.cpp +++ /dev/null @@ -1,46 +0,0 @@ -/// Source : https://leetcode.com/problems/intersection-of-two-arrays-ii/description/ -/// Author : liuyubobobo -/// Time : 2017-11-14 - -#include -#include -#include - -using namespace std; - -/// Using Hash Map -/// Time Complexity: O(len(nums1) + len(nums2)*log(len(nums1))) -/// Space Complexity: O(len(nums1)) -class Solution { -public: - vector intersect(vector& nums1, vector& nums2) { - - multiset record; - for(int num: nums1) - record.insert(num); - - multiset result; - for(int num: nums2){ - multiset::iterator iter = record.find(num); - if( iter != record.end()){ - result.insert(num); - record.erase(iter); - } - } - - return vector(result.begin(), result.end()); - } -}; - -int main() { - - int nums1[] = {1, 2, 2, 1}; - vector vec1(nums1, nums1 + sizeof(nums1)/sizeof(int)); - - int nums2[] = {2, 2}; - vector vec2(nums2, nums2 + sizeof(nums2)/sizeof(int)); - - printVec(Solution().intersect(vec1, vec2)); - - return 0; -} \ No newline at end of file diff --git a/0377-Combination-Sum-IV/cpp-0377/main.cpp b/0377-Combination-Sum-IV/cpp-0377/main.cpp deleted file mode 100644 index 11372f00..00000000 --- a/0377-Combination-Sum-IV/cpp-0377/main.cpp +++ /dev/null @@ -1,55 +0,0 @@ -/// Source : https://leetcode.com/problems/combination-sum-iv/description/ -/// Author : liuyubobobo -/// Time : 2018-03-04 - -#include -#include - -using namespace std; - -/// Memory Search -/// Time Complexity: O(n * target) -/// Space Complexity: O(n * target) -class Solution { - -private: - vector memo; - -public: - int combinationSum4(vector& nums, int target) { - - if(nums.size() == 0) - return 0; - - memo = vector(target + 1, -1); - solve(nums, target); - - return memo[target]; - } - -private: - int solve(const vector& nums, int target){ - - if(target == 0) - return 1; - - if(memo[target] != -1) - return memo[target]; - - int res = 0; - for(int i = 0; i < nums.size() ; i ++) - if(target >= nums[i]) - res += solve(nums, target - nums[i]); - - return memo[target] = res; - } -}; - -int main() { - - vector nums1 = {1, 2, 3}; - int target1 = 4; - cout << Solution().combinationSum4(nums1, target1) << endl; - - return 0; -} \ No newline at end of file diff --git a/0377-Combination-Sum-IV/cpp-0377/main2.cpp b/0377-Combination-Sum-IV/cpp-0377/main2.cpp deleted file mode 100644 index ed6bcc62..00000000 --- a/0377-Combination-Sum-IV/cpp-0377/main2.cpp +++ /dev/null @@ -1,40 +0,0 @@ -/// Source : https://leetcode.com/problems/combination-sum-iv/description/ -/// Author : liuyubobobo -/// Time : 2018-02-28 - -#include -#include - -using namespace std; - -/// Dynamic Programming -/// Time Complexity: O(n * target) -/// Space Complexity: O(target) -class Solution { -public: - int combinationSum4(vector& nums, int target) { - - int n = nums.size(); - if(n == 0) - return 0; - - vector memo(target + 1, 0); - memo[0] = 1; - - for(int i = 1; i <= target; i++) - for(int j = 0; j < n; j ++) - if(nums[j] <= i) - memo[i] = memo[i] + memo[i - nums[j]]; - - return memo[target]; - } -}; - -int main() { - - vector nums1 = {1, 2, 3}; - int target1 = 4; - cout << Solution().combinationSum4(nums1, target1) << endl; - - return 0; -} \ No newline at end of file diff --git a/0387-First-Unique-Character-in-a-String/cpp-0387/main.cpp b/0387-First-Unique-Character-in-a-String/cpp-0387/main.cpp deleted file mode 100644 index 580f53c0..00000000 --- a/0387-First-Unique-Character-in-a-String/cpp-0387/main.cpp +++ /dev/null @@ -1,32 +0,0 @@ -/// Source : https://leetcode.com/problems/first-unique-character-in-a-string/description/ -/// Author : liuyubobobo -/// Time : 2017-10-16 - -#include - -using namespace std; - -/// Time Complexity: O(len(s)) -/// Space Complexity: O(26) -class Solution { - -public: - int firstUniqChar(string s) { - int freq[26] = {0}; - for(char c: s) - freq[c-'a'] ++; - - for(int i = 0 ; i < s.size() ; i ++) - if(freq[s[i]-'a'] == 1) - return i; - - return -1; - } -}; - -int main() { - - cout << Solution().firstUniqChar("leetcode") << endl; - cout << Solution().firstUniqChar("loveleetcode") << endl; - return 0; -} \ No newline at end of file diff --git a/0435-Non-overlapping-Intervals/cpp-0435/main.cpp b/0435-Non-overlapping-Intervals/cpp-0435/main.cpp deleted file mode 100644 index e09ce1ba..00000000 --- a/0435-Non-overlapping-Intervals/cpp-0435/main.cpp +++ /dev/null @@ -1,68 +0,0 @@ -/// https://leetcode.com/problems/non-overlapping-intervals/description/ -/// Author : liuyubobobo -/// Time : 2017-11-19 - -#include -#include - -using namespace std; - - -/// Definition for an interval. -struct Interval { - int start; - int end; - Interval() : start(0), end(0) {} - Interval(int s, int e) : start(s), end(e) {} -}; - -bool compare(const Interval &a, const Interval &b){ - - if(a.start != b.start) - return a.start < b.start; - return a.end < b.end; -} - -/// Dynamic Programming based on starting point -/// Time Complexity: O(n^2) -/// Space Complexity: O(n) -class Solution { - -public: - int eraseOverlapIntervals(vector& intervals) { - - if(intervals.size() == 0) - return 0; - - sort(intervals.begin(), intervals.end(), compare); - - vector dp(intervals.size(), 1); - for(int i = 1 ; i < intervals.size() ; i ++) - for(int j = 0 ; j < i ; j ++) - if(intervals[i].start >= intervals[j].end) - dp[i] = max(dp[i], 1 + dp[j]); - - int res = 0; - for(int tres: dp) - res = max(res, tres); - - return intervals.size() - res; - } -}; - -int main() { - - Interval interval1[] = {Interval(1,2), Interval(2,3), Interval(3,4), Interval(1,3)}; - vector v1(interval1, interval1 + sizeof(interval1)/sizeof(Interval)); - cout << Solution().eraseOverlapIntervals(v1) << endl; - - Interval interval2[] = {Interval(1,2), Interval(1,2), Interval(1,2)}; - vector v2(interval2, interval2 + sizeof(interval2)/sizeof(Interval)); - cout << Solution().eraseOverlapIntervals(v2) << endl; - - Interval interval3[] = {Interval(1,2), Interval(2,3)}; - vector v3(interval3, interval3 + sizeof(interval3)/sizeof(Interval)); - cout << Solution().eraseOverlapIntervals(v3) << endl; - - return 0; -} \ No newline at end of file diff --git a/0435-Non-overlapping-Intervals/cpp-0435/main2.cpp b/0435-Non-overlapping-Intervals/cpp-0435/main2.cpp deleted file mode 100644 index 9cdc0e3f..00000000 --- a/0435-Non-overlapping-Intervals/cpp-0435/main2.cpp +++ /dev/null @@ -1,68 +0,0 @@ -/// https://leetcode.com/problems/non-overlapping-intervals/description/ -/// Author : liuyubobobo -/// Time : 2017-11-19 - -#include -#include - -using namespace std; - - -/// Definition for an interval. -struct Interval { - int start; - int end; - Interval() : start(0), end(0) {} - Interval(int s, int e) : start(s), end(e) {} -}; - -bool compare(const Interval &a, const Interval &b){ - - if(a.start != b.start) - return a.start < b.start; - return a.end < b.end; -} - -/// Greedy Algorithm based on starting point -/// Time Complexity: O(n) -/// Space Complexity: O(n) -class Solution { - -public: - int eraseOverlapIntervals(vector& intervals) { - - if(intervals.size() == 0) - return 0; - - sort(intervals.begin(), intervals.end(), compare); - - int res = 1; - int pre = 0; - for(int i = 1 ; i < intervals.size() ; i ++) - if(intervals[i].start >= intervals[pre].end){ - pre = i; - res ++; - } - else if(intervals[i].end < intervals[pre].end) - pre = i; - - return intervals.size() - res; - } -}; - -int main() { - - Interval interval1[] = {Interval(1,2), Interval(2,3), Interval(3,4), Interval(1,3)}; - vector v1(interval1, interval1 + sizeof(interval1)/sizeof(Interval)); - cout << Solution().eraseOverlapIntervals(v1) << endl; - - Interval interval2[] = {Interval(1,2), Interval(1,2), Interval(1,2)}; - vector v2(interval2, interval2 + sizeof(interval2)/sizeof(Interval)); - cout << Solution().eraseOverlapIntervals(v2) << endl; - - Interval interval3[] = {Interval(1,2), Interval(2,3)}; - vector v3(interval3, interval3 + sizeof(interval3)/sizeof(Interval)); - cout << Solution().eraseOverlapIntervals(v3) << endl; - - return 0; -} \ No newline at end of file diff --git a/0435-Non-overlapping-Intervals/cpp-0435/main3.cpp b/0435-Non-overlapping-Intervals/cpp-0435/main3.cpp deleted file mode 100644 index 41c3cf48..00000000 --- a/0435-Non-overlapping-Intervals/cpp-0435/main3.cpp +++ /dev/null @@ -1,67 +0,0 @@ -/// https://leetcode.com/problems/non-overlapping-intervals/description/ -/// Author : liuyubobobo -/// Time : 2017-11-19 - -#include -#include - -using namespace std; - - -/// Definition for an interval. -struct Interval { - int start; - int end; - Interval() : start(0), end(0) {} - Interval(int s, int e) : start(s), end(e) {} -}; - -bool compare(const Interval &a, const Interval &b){ - if(a.end != b.end) - return a.end < b.end; - return a.start < b.start; -} - -/// Dynamic Programming based on ending point -/// Time Complexity: O(n^2) -/// Space Complexity: O(n) -class Solution { - -public: - int eraseOverlapIntervals(vector& intervals) { - - if(intervals.size() == 0) - return 0; - - sort(intervals.begin(), intervals.end(), compare); - - vector dp(intervals.size(), 1); - for(int i = 1 ; i < intervals.size() ; i ++) - for(int j = 0 ; j < i ; j ++) - if(intervals[i].start >= intervals[j].end) - dp[i] = max(dp[i], 1 + dp[j]); - - int res = 0; - for(int tres: dp) - res = max(res, tres); - - return intervals.size() - res; - } -}; - -int main() { - - Interval interval1[] = {Interval(1,2), Interval(2,3), Interval(3,4), Interval(1,3)}; - vector v1(interval1, interval1 + sizeof(interval1)/sizeof(Interval)); - cout << Solution().eraseOverlapIntervals(v1) << endl; - - Interval interval2[] = {Interval(1,2), Interval(1,2), Interval(1,2)}; - vector v2(interval2, interval2 + sizeof(interval2)/sizeof(Interval)); - cout << Solution().eraseOverlapIntervals(v2) << endl; - - Interval interval3[] = {Interval(1,2), Interval(2,3)}; - vector v3(interval3, interval3 + sizeof(interval3)/sizeof(Interval)); - cout << Solution().eraseOverlapIntervals(v3) << endl; - - return 0; -} \ No newline at end of file diff --git a/0435-Non-overlapping-Intervals/cpp-0435/main4.cpp b/0435-Non-overlapping-Intervals/cpp-0435/main4.cpp deleted file mode 100644 index cfc80b51..00000000 --- a/0435-Non-overlapping-Intervals/cpp-0435/main4.cpp +++ /dev/null @@ -1,64 +0,0 @@ -/// https://leetcode.com/problems/non-overlapping-intervals/description/ -/// Author : liuyubobobo -/// Time : 2017-11-19 - -#include -#include - -using namespace std; - - -/// Definition for an interval. -struct Interval { - int start; - int end; - Interval() : start(0), end(0) {} - Interval(int s, int e) : start(s), end(e) {} -}; - -bool compare(const Interval &a, const Interval &b){ - if(a.end != b.end) - return a.end < b.end; - return a.start < b.start; -} - -/// Greedy Algorithm based on ending point -/// Time Complexity: O(n) -/// Space Complexity: O(n) -class Solution { -public: - int eraseOverlapIntervals(vector& intervals) { - - if(intervals.size() == 0) - return 0; - - sort(intervals.begin(), intervals.end(), compare); - - int res = 1; - int pre = 0; - for(int i = 1 ; i < intervals.size() ; i ++) - if(intervals[i].start >= intervals[pre].end){ - res ++; - pre = i; - } - - return intervals.size() - res; - } -}; - -int main() { - - Interval interval1[] = {Interval(1,2), Interval(2,3), Interval(3,4), Interval(1,3)}; - vector v1(interval1, interval1 + sizeof(interval1)/sizeof(Interval)); - cout << Solution().eraseOverlapIntervals(v1) << endl; - - Interval interval2[] = {Interval(1,2), Interval(1,2), Interval(1,2)}; - vector v2(interval2, interval2 + sizeof(interval2)/sizeof(Interval)); - cout << Solution().eraseOverlapIntervals(v2) << endl; - - Interval interval3[] = {Interval(1,2), Interval(2,3)}; - vector v3(interval3, interval3 + sizeof(interval3)/sizeof(Interval)); - cout << Solution().eraseOverlapIntervals(v3) << endl; - - return 0; -} \ No newline at end of file diff --git a/0437-Path-Sum-III/cpp-0437/main.cpp b/0437-Path-Sum-III/cpp-0437/main.cpp deleted file mode 100644 index 0d0c0e0e..00000000 --- a/0437-Path-Sum-III/cpp-0437/main.cpp +++ /dev/null @@ -1,91 +0,0 @@ -/// Source : https://leetcode.com/problems/path-sum-iii/description/ -/// Author : liuyubobobo -/// Time : 2017-11-18 - -#include - -using namespace std; - - -/// Definition for a binary tree node. -struct TreeNode { - int val; - TreeNode *left; - TreeNode *right; - TreeNode(int x) : val(x), left(NULL), right(NULL) {} -}; - - -/// Recursive -/// Time Complexity: O(n), where n is the node's number of the tree -/// Space Complexity: O(h), where h is the height of the tree -class Solution { - -public: - int pathSum(TreeNode* root, int sum) { - - if(root == NULL) - return 0; - - return findPath(root, sum) - + pathSum(root->left , sum) - + pathSum(root->right , sum); - } - -private: - int findPath(TreeNode* node, int num){ - - if(node == NULL) - return 0; - - int res = 0; - if(node->val == num) - res += 1; - - res += findPath(node->left , num - node->val); - res += findPath(node->right , num - node->val); - - return res; - } -}; - -int main() { - - /***************** - * Test case: - * - * 10 - * / \ - * 5 -3 - * / \ \ - * 3 2 11 - * / \ \ - * 3 -2 1 - *****************/ - TreeNode* node1 = new TreeNode(3); - TreeNode* node2 = new TreeNode(-2); - - TreeNode* node3 = new TreeNode(3); - node3->left = node1; - node3->right = node2; - - TreeNode* node4 = new TreeNode(1); - TreeNode* node5 = new TreeNode(2); - node5->right = node4; - - TreeNode* node6 = new TreeNode(5); - node6->left = node3; - node6->right = node5; - - TreeNode* node7 = new TreeNode(11); - TreeNode* node8 = new TreeNode(-3); - node8->right = node7; - - TreeNode* node9 = new TreeNode(10); - node9->left = node6; - node9->right = node8; - - cout << Solution().pathSum(node9, 8) << endl; - - return 0; -} \ No newline at end of file diff --git a/0437-Path-Sum-III/java-0437/src/Solution.java b/0437-Path-Sum-III/java-0437/src/Solution.java deleted file mode 100644 index 2353a0b5..00000000 --- a/0437-Path-Sum-III/java-0437/src/Solution.java +++ /dev/null @@ -1,81 +0,0 @@ -/// Source : https://leetcode.com/problems/path-sum-iii/description/ -/// Author : liuyubobobo -/// Time : 2017-11-18 - -/// Recursive -/// Time Complexity: O(n), where n is the node's number of the tree -/// Space Complexity: O(h), where h is the height of the tree -class Solution { - - /// Definition for a binary tree node. - public static class TreeNode { - int val; - TreeNode left; - TreeNode right; - TreeNode(int x) { val = x; } - } - - public int pathSum(TreeNode root, int sum) { - - if(root == null) - return 0; - - return findPath(root, sum) - + pathSum(root.left , sum) - + pathSum(root.right , sum); - } - - private int findPath(TreeNode node, int num){ - - if(node == null) - return 0; - - int res = 0; - if(node.val == num) - res += 1; - - res += findPath(node.left , num - node.val); - res += findPath(node.right , num - node.val); - - return res; - } - - public static void main(String[] args) { - - /***************** - * Test case: - * - * 10 - * / \ - * 5 -3 - * / \ \ - * 3 2 11 - * / \ \ - * 3 -2 1 - *****************/ - TreeNode node1 = new TreeNode(3); - TreeNode node2 = new TreeNode(-2); - - TreeNode node3 = new TreeNode(3); - node3.left = node1; - node3.right = node2; - - TreeNode node4 = new TreeNode(1); - TreeNode node5 = new TreeNode(2); - node5.right = node4; - - TreeNode node6 = new TreeNode(5); - node6.left = node3; - node6.right = node5; - - TreeNode node7 = new TreeNode(11); - TreeNode node8 = new TreeNode(-3); - node8.right = node7; - - TreeNode node9 = new TreeNode(10); - node9.left = node6; - node9.right = node8; - - System.out.println((new Solution()).pathSum(node9, 8)); - } -} diff --git a/0447-Number-of-Boomerangs/cpp-0447/main.cpp b/0447-Number-of-Boomerangs/cpp-0447/main.cpp deleted file mode 100644 index 9bba5f7a..00000000 --- a/0447-Number-of-Boomerangs/cpp-0447/main.cpp +++ /dev/null @@ -1,53 +0,0 @@ -/// Source : https://leetcode.com/problems/number-of-boomerangs/description/ -/// Author : liuyubobobo -/// Time : 2017-11-15 - -#include -#include -#include -#include -#include - -using namespace std; - -/// Using Hash Map -/// Time Complexity: O(n^2) -/// Space Complexity: O(n) -class Solution { -public: - int numberOfBoomerangs(vector>& points) { - - int res = 0; - for( int i = 0 ; i < points.size() ; i ++ ){ - - // record中存储 点i 到所有其他点的距离出现的频次 - unordered_map record; - for(int j = 0 ; j < points.size() ; j ++) - if(j != i) - // 计算距离时不进行开根运算, 以保证精度 - record[dis(points[i], points[j])] += 1; - - for(unordered_map::iterator iter = record.begin() ; iter != record.end() ; iter ++) - res += (iter->second) * (iter->second - 1); - } - return res; - } - -private: - int dis(const pair &pa, const pair &pb){ - return (pa.first - pb.first) * (pa.first - pb.first) + - (pa.second - pb.second) * (pa.second - pb.second); - } -}; - -int main() { - - vector> vec; - vec.push_back(make_pair(0, 0)); - vec.push_back(make_pair(1, 0)); - vec.push_back(make_pair(2, 0)); - - cout << Solution().numberOfBoomerangs(vec) << endl; - - return 0; -} \ No newline at end of file diff --git a/0501-1000/0501-Find-Mode-in-Binary-Search-Tree/cpp-0501/CMakeLists.txt b/0501-1000/0501-Find-Mode-in-Binary-Search-Tree/cpp-0501/CMakeLists.txt new file mode 100644 index 00000000..a158e6e7 --- /dev/null +++ b/0501-1000/0501-Find-Mode-in-Binary-Search-Tree/cpp-0501/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(cpp_0501) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0501 main2.cpp) \ No newline at end of file diff --git a/0501-1000/0501-Find-Mode-in-Binary-Search-Tree/cpp-0501/main.cpp b/0501-1000/0501-Find-Mode-in-Binary-Search-Tree/cpp-0501/main.cpp new file mode 100644 index 00000000..b95300f0 --- /dev/null +++ b/0501-1000/0501-Find-Mode-in-Binary-Search-Tree/cpp-0501/main.cpp @@ -0,0 +1,59 @@ +/// Source : https://leetcode.com/problems/find-mode-in-binary-search-tree/ +/// Author : liuyubobobo +/// Time : 2019-07-25 + +#include +#include +#include + +using namespace std; + + +/// Using HashMap +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// 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 { + +private: + unordered_map freq; + +public: + vector findMode(TreeNode* root) { + + dfs(root); + + int best = 0; + vector res; + for(const pair& p: freq) + if(p.second > best) + best = p.second, res = {p.first}; + else if(p.second == best) + res.push_back(p.first); + return res; + } + +private: + void dfs(TreeNode* node){ + + if(node){ + freq[node->val] ++; + dfs(node->left); + dfs(node->right); + } + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0501-Find-Mode-in-Binary-Search-Tree/cpp-0501/main2.cpp b/0501-1000/0501-Find-Mode-in-Binary-Search-Tree/cpp-0501/main2.cpp new file mode 100644 index 00000000..feaf1b11 --- /dev/null +++ b/0501-1000/0501-Find-Mode-in-Binary-Search-Tree/cpp-0501/main2.cpp @@ -0,0 +1,66 @@ +/// Source : https://leetcode.com/problems/find-mode-in-binary-search-tree/ +/// Author : liuyubobobo +/// Time : 2019-07-25 + +#include +#include +#include + +using namespace std; + + +/// Inorder Traversal +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// 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 { + +private: + vector inorder; + +public: + vector findMode(TreeNode* root) { + + dfs(root); + + vector res; + int best = 0; + for(int start = 0, i = 1; i <= inorder.size(); i ++) + if(i == inorder.size() || inorder[i] != inorder[start]){ + if(i - start > best) + best = i - start, res = {inorder[start]}; + else if(i - start == best) + res.push_back(inorder[start]); + start = i; + i = start; + } + + return res; + } + +private: + void dfs(TreeNode* node){ + + if(node){ + dfs(node->left); + inorder.push_back(node->val); + dfs(node->right); + } + } +}; + + +int main() { + + // [3,2,3,null,null,3,4,null,null,4,5,null,null,5,6] + // 3 + return 0; +} \ No newline at end of file diff --git a/0501-1000/0501-Find-Mode-in-Binary-Search-Tree/cpp-0501/main3.cpp b/0501-1000/0501-Find-Mode-in-Binary-Search-Tree/cpp-0501/main3.cpp new file mode 100644 index 00000000..9314acbe --- /dev/null +++ b/0501-1000/0501-Find-Mode-in-Binary-Search-Tree/cpp-0501/main3.cpp @@ -0,0 +1,68 @@ +/// Source : https://leetcode.com/problems/find-mode-in-binary-search-tree/ +/// Author : liuyubobobo +/// Time : 2019-07-25 + +#include +#include +#include + +using namespace std; + + +/// Inorder Traversal and record result online +/// Time Complexity: O(n) +/// Space Complexity: O(h) + +/// 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 { + +private: + vector res; + int best = 1; + int count = 0; + TreeNode* pre = NULL; + +public: + vector findMode(TreeNode* root) { + + if(!root) return {}; + dfs(root); + if(count > best) best = count, res = {pre->val}; + else if(count == best) res.push_back(pre->val); + + return res; + } + +private: + void dfs(TreeNode* node){ + + if(node){ + dfs(node->left); + + if(!pre || node->val == pre->val) count ++; + else{ + if(count > best) best = count, res = {pre->val}; + else if(count == best) res.push_back(pre->val); + count = 1; + } + pre = node; + + dfs(node->right); + } + } +}; + + +int main() { + + // [3,2,3,null,null,3,4,null,null,4,5,null,null,5,6] + // 3 + return 0; +} \ No newline at end of file diff --git a/0501-1000/0502-IPO/cpp-0502/CMakeLists.txt b/0501-1000/0502-IPO/cpp-0502/CMakeLists.txt new file mode 100644 index 00000000..c48495b5 --- /dev/null +++ b/0501-1000/0502-IPO/cpp-0502/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0502) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0502 main.cpp) diff --git a/0501-1000/0502-IPO/cpp-0502/main.cpp b/0501-1000/0502-IPO/cpp-0502/main.cpp new file mode 100644 index 00000000..2dca4e7b --- /dev/null +++ b/0501-1000/0502-IPO/cpp-0502/main.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/ipo/ +/// Author : liuyubobobo +/// Time : 2021-09-07 + +#include +#include +#include + +using namespace std; + + +/// Priority Queue +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + int findMaximizedCapital(int k, int w, vector& profits, vector& capital) { + + int n = profits.size(); + priority_queue> pq1; // profit, capital + priority_queue, vector>, greater>> pq2; // capital, profit + + for(int i = 0; i < n; i ++) + pq2.push({capital[i], profits[i]}); + + int cur = w; + while(k){ + while(!pq2.empty() && cur >= pq2.top().first) + pq1.push({pq2.top().second, pq2.top().first}), pq2.pop(); + + if(!pq1.empty() && pq1.top().first > 0){ + cur += pq1.top().first; + pq1.pop(); + k --; + } + else break; + } + return cur; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0503-Next-Greater-Element-II/cpp-0503/CMakeLists.txt b/0501-1000/0503-Next-Greater-Element-II/cpp-0503/CMakeLists.txt new file mode 100644 index 00000000..09e68482 --- /dev/null +++ b/0501-1000/0503-Next-Greater-Element-II/cpp-0503/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0503) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0503 main2.cpp) \ No newline at end of file diff --git a/0501-1000/0503-Next-Greater-Element-II/cpp-0503/main.cpp b/0501-1000/0503-Next-Greater-Element-II/cpp-0503/main.cpp new file mode 100644 index 00000000..bdb2091b --- /dev/null +++ b/0501-1000/0503-Next-Greater-Element-II/cpp-0503/main.cpp @@ -0,0 +1,38 @@ +/// Source : https://leetcode.com/problems/next-greater-element-ii/ +/// Author : liuyubobobo +/// Time : 2021-03-05 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { +public: + vector nextGreaterElements(vector& nums) { + + vector res(nums.size()); + for(int i = 0; i < nums.size(); i ++) + res[i] = next(nums, i); + return res; + } + +private: + int next(const vector& nums, int start){ + + for(int i = 1; i < nums.size(); i ++) + if(nums[(start + i) % nums.size()] > nums[start]) + return nums[(start + i) % nums.size()]; + return -1; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0503-Next-Greater-Element-II/cpp-0503/main2.cpp b/0501-1000/0503-Next-Greater-Element-II/cpp-0503/main2.cpp new file mode 100644 index 00000000..94fe147e --- /dev/null +++ b/0501-1000/0503-Next-Greater-Element-II/cpp-0503/main2.cpp @@ -0,0 +1,41 @@ +/// Source : https://leetcode.com/problems/next-greater-element-ii/ +/// Author : liuyubobobo +/// Time : 2021-03-05 + +#include +#include +#include + +using namespace std; + + +/// Mono Stack +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector nextGreaterElements(vector& nums) { + + int n = nums.size(); + vector res(n, -1); + + for(int i = 0; i < n; i ++) + nums.push_back(nums[i]); + + stack stack; + for(int i = 0; i < nums.size(); i ++){ + while(!stack.empty() && nums[i] > nums[stack.top()]){ + if(stack.top() < n) res[stack.top()] = nums[i]; + stack.pop(); + } + stack.push(i); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0504-Base-7/cpp-0504/CMakeLists.txt b/0501-1000/0504-Base-7/cpp-0504/CMakeLists.txt new file mode 100644 index 00000000..0234e019 --- /dev/null +++ b/0501-1000/0504-Base-7/cpp-0504/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_0504) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0504 main.cpp) diff --git a/0501-1000/0504-Base-7/cpp-0504/main.cpp b/0501-1000/0504-Base-7/cpp-0504/main.cpp new file mode 100644 index 00000000..ed637e32 --- /dev/null +++ b/0501-1000/0504-Base-7/cpp-0504/main.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/base-7/ +/// Author : liuyubobobo +/// Time : 2022-03-06 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(logn) +/// Space Complexity: O(1) +class Solution { +public: + string convertToBase7(int num) { + + bool pos = true; + if(num < 0) num = -num, pos = false; + + string res = ""; + while(num){ + res += (char)('0' + num % 7); + num /= 7; + } + reverse(res.begin(), res.end()); + if(res.empty()) res = "0"; + + return (pos ? "" : "-") + res; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0505-The-Maze-II/cpp-0505/CMakeLists.txt b/0501-1000/0505-The-Maze-II/cpp-0505/CMakeLists.txt new file mode 100644 index 00000000..f137cf1a --- /dev/null +++ b/0501-1000/0505-The-Maze-II/cpp-0505/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_0505) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0505 main.cpp) \ No newline at end of file diff --git a/0501-1000/0505-The-Maze-II/cpp-0505/main.cpp b/0501-1000/0505-The-Maze-II/cpp-0505/main.cpp new file mode 100644 index 00000000..de79624f --- /dev/null +++ b/0501-1000/0505-The-Maze-II/cpp-0505/main.cpp @@ -0,0 +1,74 @@ +/// Source : https://leetcode.com/problems/the-maze-ii/ +/// Author : liuyubobobo +/// Time : 2021-06-08 + +#include +#include +#include + +using namespace std; + + +/// Dijkstra +/// Time Complexity: O(nlogn) where n = R * C +/// Space Complexity: O(R * C) +class Solution { + +private: + int R, C; + const int dirs[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; + +public: + int shortestDistance(vector>& maze, vector& start, vector& destination) { + + R = maze.size(), C = maze[0].size(); + + vector> visited(R, vector(C, false)); + vector> dis(R, vector(C, INT_MAX)); + + priority_queue, vector>, greater>> pq; + pq.push({0, start[0] * C + start[1]}); + dis[start[0]][start[1]] = 0; + while(!pq.empty()){ + int x = pq.top().second / C, y = pq.top().second % C, d = pq.top().first; + pq.pop(); + + if(visited[x][y]) continue; + + visited[x][y] = true; + + if(x == destination[0] && y == destination[1]) + return dis[x][y]; + + for(int i = 0; i < 4; i ++){ + int nx, ny; + int dd = go(maze, x, y, nx, ny, i); + if(!visited[nx][ny] && dis[x][y] + dd < dis[nx][ny]){ + dis[nx][ny] = dis[x][y] + dd; + pq.push({dis[nx][ny], nx * C + ny}); + } + } + } + return -1; + } + +private: + int go(const vector>& maze, int cx, int cy, int& nx, int& ny, int d){ + + nx = cx, ny = cy; + int res = 0; + while(in_area(nx + dirs[d][0], ny + dirs[d][1]) && maze[nx + dirs[d][0]][ny + dirs[d][1]] == 0) + nx += dirs[d][0], ny += dirs[d][1], res ++; + return res; + } + + bool in_area(int x, int y){ + return x >= 0 && x < R && y >= 0 && y < C; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0506-Relative-Ranks/cpp-0506/CMakeLists.txt b/0501-1000/0506-Relative-Ranks/cpp-0506/CMakeLists.txt new file mode 100644 index 00000000..2caac2bc --- /dev/null +++ b/0501-1000/0506-Relative-Ranks/cpp-0506/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_0506) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0506 main.cpp) diff --git a/0501-1000/0506-Relative-Ranks/cpp-0506/main.cpp b/0501-1000/0506-Relative-Ranks/cpp-0506/main.cpp new file mode 100644 index 00000000..2f801764 --- /dev/null +++ b/0501-1000/0506-Relative-Ranks/cpp-0506/main.cpp @@ -0,0 +1,39 @@ +/// Source : https://leetcode.com/problems/relative-ranks/ +/// Author : liuyubobobo +/// Time : 2021-12-02 + +#include +#include + +using namespace std; + + +/// Sorting +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + vector findRelativeRanks(vector& score) { + + int n = score.size(); + vector> data(n); + for(int i = 0; i < n; i ++) + data[i] = {score[i], i}; + + sort(data.begin(), data.end(), greater>()); + + vector res(n); + + if(n >= 1) res[data[0].second] = "Gold Medal"; + if(n >= 2) res[data[1].second] = "Silver Medal"; + if(n >= 3) res[data[2].second] = "Bronze Medal"; + for(int i = 3; i < n; i ++) res[data[i].second] = to_string(i + 1); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0507-Perfect-Number/cpp-0507/CMakeLists.txt b/0501-1000/0507-Perfect-Number/cpp-0507/CMakeLists.txt new file mode 100644 index 00000000..86287a35 --- /dev/null +++ b/0501-1000/0507-Perfect-Number/cpp-0507/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_0507) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0507 main.cpp) diff --git a/0501-1000/0507-Perfect-Number/cpp-0507/main.cpp b/0501-1000/0507-Perfect-Number/cpp-0507/main.cpp new file mode 100644 index 00000000..4b694af1 --- /dev/null +++ b/0501-1000/0507-Perfect-Number/cpp-0507/main.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/perfect-number/ +/// Author : liuyubobobo +/// Time : 2021-12-30 + +#include +#include +#include + +using namespace std; + + +/// Scan all the divisors +/// Time Complexity: O(sqrt(n)) +/// Space Complexity: O(sqrt(n)) +class Solution { +public: + bool checkPerfectNumber(int num) { + + vector d; + for(int i = 1; i * i <= num; i ++){ + if(num % i == 0){ + if(i != num) d.push_back(i); + if(i * i != num && i != 1) d.push_back(num / i); + } + } + + return accumulate(d.begin(), d.end(), 0) == num; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0508-Most-Frequent-Subtree-Sum/cpp-0508/CMakeLists.txt b/0501-1000/0508-Most-Frequent-Subtree-Sum/cpp-0508/CMakeLists.txt new file mode 100644 index 00000000..2dc9e056 --- /dev/null +++ b/0501-1000/0508-Most-Frequent-Subtree-Sum/cpp-0508/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_0508) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0508 main.cpp) diff --git a/0501-1000/0508-Most-Frequent-Subtree-Sum/cpp-0508/main.cpp b/0501-1000/0508-Most-Frequent-Subtree-Sum/cpp-0508/main.cpp new file mode 100644 index 00000000..021f4992 --- /dev/null +++ b/0501-1000/0508-Most-Frequent-Subtree-Sum/cpp-0508/main.cpp @@ -0,0 +1,58 @@ +/// Source : https://leetcode.com/problems/most-frequent-subtree-sum/ +/// Author : liuyubobobo +/// Time : 2022-06-18 + +#include +#include +#include + +using namespace std; + + +/// DFS +/// Time Compelxity: O(n) +/// Space Complexity: O(n) + +/// 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 findFrequentTreeSum(TreeNode* root) { + + map f; + dfs(root, f); + + vector res; + int max_f = 0; + for(const pair& p: f) + if(p.second > max_f) res = {p.first}, max_f = p.second; + else if(p.second == max_f) res.push_back(p.first); + return res; + } + +private: + int dfs(TreeNode* node, map& f){ + + if(!node) return 0; + + int res = node->val; + res += dfs(node->left, f); + res += dfs(node->right, f); + f[res] ++; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0509-Fibonacci-Number/cpp-0509/CMakeLists.txt b/0501-1000/0509-Fibonacci-Number/cpp-0509/CMakeLists.txt new file mode 100644 index 00000000..3ee497f0 --- /dev/null +++ b/0501-1000/0509-Fibonacci-Number/cpp-0509/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(cpp_0509) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(cpp_0509 main5.cpp) \ No newline at end of file diff --git a/0501-1000/0509-Fibonacci-Number/cpp-0509/main.cpp b/0501-1000/0509-Fibonacci-Number/cpp-0509/main.cpp new file mode 100644 index 00000000..ab0cf5f4 --- /dev/null +++ b/0501-1000/0509-Fibonacci-Number/cpp-0509/main.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/fibonacci-number/ +/// Author : liuyubobobo +/// Time : 2019-01-09 + +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int fib(int N) { + + vector dp(N + 1, -1); + dp[0] = 0; + dp[1] = 1; + return dfs(N, dp); + } + +private: + int dfs(int N, vector& dp){ + + if(N <= 1) return N; + if(dp[N] >= 0) return dp[N]; + return dp[N] = dfs(N - 1, dp) + dfs(N - 2, dp); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0509-Fibonacci-Number/cpp-0509/main2.cpp b/0501-1000/0509-Fibonacci-Number/cpp-0509/main2.cpp new file mode 100644 index 00000000..18484cac --- /dev/null +++ b/0501-1000/0509-Fibonacci-Number/cpp-0509/main2.cpp @@ -0,0 +1,31 @@ +/// Source : https://leetcode.com/problems/fibonacci-number/ +/// Author : liuyubobobo +/// Time : 2019-01-09 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int fib(int N) { + + vector dp(N + 1, -1); + dp[0] = 0; + dp[1] = 1; + for(int i = 2; i <= N; i ++) + dp[i] = dp[i - 1] + dp[i - 2]; + return dp[N]; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0509-Fibonacci-Number/cpp-0509/main3.cpp b/0501-1000/0509-Fibonacci-Number/cpp-0509/main3.cpp new file mode 100644 index 00000000..22e62192 --- /dev/null +++ b/0501-1000/0509-Fibonacci-Number/cpp-0509/main3.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/fibonacci-number/ +/// Author : liuyubobobo +/// Time : 2019-01-09 + +#include +#include + +using namespace std; + + +/// Binets Method +/// | F(n+1) F(n) | = | 1 1 |^n +/// | F(n) F(n-1) | | 1 0 | +/// +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int fib(int N) { + + if(N <= 1) return N; + + int prev = 0, cur = 1; + for (int i = 2; i <= N; i++) { + int f = cur + prev; + prev = cur; + cur = f; + } + return cur; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0509-Fibonacci-Number/cpp-0509/main4.cpp b/0501-1000/0509-Fibonacci-Number/cpp-0509/main4.cpp new file mode 100644 index 00000000..447c9793 --- /dev/null +++ b/0501-1000/0509-Fibonacci-Number/cpp-0509/main4.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/fibonacci-number/ +/// Author : liuyubobobo +/// Time : 2019-01-09 + +#include +#include + +using namespace std; + + +/// Binets Method +/// | F(n+1) F(n) | = | 1 1 |^n +/// | F(n) F(n-1) | | 1 0 | +/// +/// Time Complexity: O(logn) +/// Space Complexity: O(logn) +class Solution { +public: + int fib(int N) { + + if(N <= 1) return N; + + vector> base = {{1, 1}, + {1, 0}}; + return matrix_pow(base, N - 1)[0][0]; + } + +private: + vector> matrix_pow(const vector> &m, int n) { + + if (n == 1) + return m; + + vector> t = matrix_pow(m, n / 2); + vector> res = matrix_multiply(t, t); + if (n % 2) + return matrix_multiply(res, m); + return res; + } + + vector> matrix_multiply(const vector> &m1, + const vector> &m2) { + + vector> res(2, vector(2, 0)); + res[0][0] = m1[0][0] * m2[0][0] + m1[0][1] * m2[1][0]; + res[0][1] = m1[0][0] * m2[0][1] + m1[0][1] * m2[1][1]; + res[1][0] = m1[1][0] * m2[0][0] + m1[1][1] * m2[1][0]; + res[1][1] = m1[1][0] * m2[0][1] + m1[1][1] * m2[1][1]; + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0509-Fibonacci-Number/cpp-0509/main5.cpp b/0501-1000/0509-Fibonacci-Number/cpp-0509/main5.cpp new file mode 100644 index 00000000..fe29e96c --- /dev/null +++ b/0501-1000/0509-Fibonacci-Number/cpp-0509/main5.cpp @@ -0,0 +1,31 @@ +/// Source : https://leetcode.com/problems/fibonacci-number/ +/// Author : liuyubobobo +/// Time : 2019-01-09 + +#include +#include +#include + +using namespace std; + + +/// Closed Form +/// https://en.wikipedia.org/wiki/Fibonacci_number +/// +/// Time Complexity: O(logn) +/// Space Complexity: O(logn) +class Solution { +public: + int fib(int N) { + + double a = (1. + sqrt(5.)) / 2.0; + double b = (1. - sqrt(5.)) / 2.0; + return (int)((pow(a, N) - pow(b, N)) / sqrt(5) + 0.5); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0510-Inorder-Successor-in-BST-II/cpp-0510/CMakeLists.txt b/0501-1000/0510-Inorder-Successor-in-BST-II/cpp-0510/CMakeLists.txt new file mode 100644 index 00000000..4dcc79c4 --- /dev/null +++ b/0501-1000/0510-Inorder-Successor-in-BST-II/cpp-0510/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_0510) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0510 main.cpp) diff --git a/0501-1000/0510-Inorder-Successor-in-BST-II/cpp-0510/main.cpp b/0501-1000/0510-Inorder-Successor-in-BST-II/cpp-0510/main.cpp new file mode 100644 index 00000000..f77f990b --- /dev/null +++ b/0501-1000/0510-Inorder-Successor-in-BST-II/cpp-0510/main.cpp @@ -0,0 +1,56 @@ +/// Source : https://leetcode.com/problems/inorder-successor-in-bst-ii/s +/// Author : liuyubobobo +/// Time : 2022-07-08 + +#include +#include + +using namespace std; + + +/// Tree Algorithm +/// Time Compelxity: O(h) +/// Space Compelxity: O(1) + +// Definition for a Node. +class Node { +public: + int val; + Node* left; + Node* right; + Node* parent; +}; + +class Solution { +public: + Node* inorderSuccessor(Node* node) { + + if(node->right){ + return minimum(node->right); + } + + Node* cur = node, *pre = node->parent; + while(pre){ + if(pre->left == cur){ + return pre; + } + else{ + cur = pre; + pre = cur->parent; + } + } + return nullptr; + } + +private: + Node* minimum(Node* node){ + while(node->left) node = node->left; + return node; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0513-Find-Bottom-Left-Tree-Value/cpp-0513/CMakeLists.txt b/0501-1000/0513-Find-Bottom-Left-Tree-Value/cpp-0513/CMakeLists.txt new file mode 100644 index 00000000..c91381e1 --- /dev/null +++ b/0501-1000/0513-Find-Bottom-Left-Tree-Value/cpp-0513/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_0513) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0513 main.cpp) diff --git a/0501-1000/0513-Find-Bottom-Left-Tree-Value/cpp-0513/main.cpp b/0501-1000/0513-Find-Bottom-Left-Tree-Value/cpp-0513/main.cpp new file mode 100644 index 00000000..71401a90 --- /dev/null +++ b/0501-1000/0513-Find-Bottom-Left-Tree-Value/cpp-0513/main.cpp @@ -0,0 +1,51 @@ +/// Source : https://leetcode.com/problems/find-bottom-left-tree-value/ +/// Author : liuyubobobo +/// Time : 2022-06-21 + +#include +#include +#include + +using namespace std; + + +/// BFS +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// 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: + int findBottomLeftValue(TreeNode* root) { + + int res = -1; + queue q; + q.push(root); + while(!q.empty()){ + res = q.front()->val; + queue tq; + while(!q.empty()){ + TreeNode* node = q.front(); q.pop(); + if(node->left) tq.push(node->left); + if(node->right) tq.push(node->right); + } + q = tq; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0515-Find-Largest-Value-in-Each-Tree-Row/cpp-0515/CMakeLists.txt b/0501-1000/0515-Find-Largest-Value-in-Each-Tree-Row/cpp-0515/CMakeLists.txt new file mode 100644 index 00000000..b2ad5a30 --- /dev/null +++ b/0501-1000/0515-Find-Largest-Value-in-Each-Tree-Row/cpp-0515/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_0515) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0515 main.cpp) diff --git a/0501-1000/0515-Find-Largest-Value-in-Each-Tree-Row/cpp-0515/main.cpp b/0501-1000/0515-Find-Largest-Value-in-Each-Tree-Row/cpp-0515/main.cpp new file mode 100644 index 00000000..0fe4f7b8 --- /dev/null +++ b/0501-1000/0515-Find-Largest-Value-in-Each-Tree-Row/cpp-0515/main.cpp @@ -0,0 +1,51 @@ +/// Source : https://leetcode.com/problems/find-largest-value-in-each-tree-row/ +/// Author : liuyubobobo +/// Time : 2022-06-23 + +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(depth) + +/// 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 largestValues(TreeNode* root) { + + vector res; + dfs(root, 0, res); + return res; + } + +private: + void dfs(TreeNode* node, int depth, vector& res){ + + if(!node) return; + + if(depth == res.size()) res.push_back(node->val); + else res[depth] = max(res[depth], node->val); + + dfs(node->left, depth + 1, res); + dfs(node->right, depth + 1, res); + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0516-Longest-Palindromic-Subsequence/cpp-0516/CMakeLists.txt b/0501-1000/0516-Longest-Palindromic-Subsequence/cpp-0516/CMakeLists.txt new file mode 100644 index 00000000..a34476ca --- /dev/null +++ b/0501-1000/0516-Longest-Palindromic-Subsequence/cpp-0516/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0516) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0516 main.cpp) \ No newline at end of file diff --git a/0501-1000/0516-Longest-Palindromic-Subsequence/cpp-0516/main.cpp b/0501-1000/0516-Longest-Palindromic-Subsequence/cpp-0516/main.cpp new file mode 100644 index 00000000..4f901299 --- /dev/null +++ b/0501-1000/0516-Longest-Palindromic-Subsequence/cpp-0516/main.cpp @@ -0,0 +1,44 @@ +/// Source : https://leetcode.com/problems/longest-palindromic-subsequence/ +/// Author : liuyubobobo +/// Time : 2020-12-12 + +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(n^2) +/// Space Complexity: O(n^2) +class Solution { +public: + int longestPalindromeSubseq(string s) { + + int n = s.size(); + vector> dp(n, vector(n, -1)); + return dfs(s, 0, n - 1, dp); + } + +private: + int dfs(const string& s, int l, int r, vector>& dp){ + + if(l > r) return 0; + if(l == r) return 1; + if(dp[l][r] != -1) return dp[l][r]; + + int res = dfs(s, l + 1, r, dp); + for(int i = r; i > l; i --) + if(s[i] == s[l]){ + res = max(res, 2 + dfs(s, l + 1, i - 1, dp)); + break; + } + return dp[l][r] = res; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0517-Super-Washing-Machines/cpp-0517/CMakeLists.txt b/0501-1000/0517-Super-Washing-Machines/cpp-0517/CMakeLists.txt new file mode 100644 index 00000000..bb7af594 --- /dev/null +++ b/0501-1000/0517-Super-Washing-Machines/cpp-0517/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(cpp_0517) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0517 main.cpp) \ No newline at end of file diff --git a/0501-1000/0517-Super-Washing-Machines/cpp-0517/main.cpp b/0501-1000/0517-Super-Washing-Machines/cpp-0517/main.cpp new file mode 100644 index 00000000..dea936ce --- /dev/null +++ b/0501-1000/0517-Super-Washing-Machines/cpp-0517/main.cpp @@ -0,0 +1,39 @@ +/// Source : https://leetcode.com/problems/super-washing-machines/ +/// Author : liuyubobobo +/// Time : 2020-04-07 + +#include +#include +#include + +using namespace std; + + +/// Mathematics +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int findMinMoves(vector& machines) { + + int sum = accumulate(machines.begin(), machines.end(), 0); + int n = machines.size(); + + if(sum % n) return -1; + int avg = sum / n; + for(int& e: machines) e -= avg; + + int res = *max_element(machines.begin(), machines.end()), cur = 0; + for(int e: machines){ + cur += e; + res = max(res, abs(cur)); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/0518-Coin-Change-2/cpp-0518/CMakeLists.txt b/0501-1000/0518-Coin-Change-2/cpp-0518/CMakeLists.txt similarity index 100% rename from 0518-Coin-Change-2/cpp-0518/CMakeLists.txt rename to 0501-1000/0518-Coin-Change-2/cpp-0518/CMakeLists.txt diff --git a/0518-Coin-Change-2/cpp-0518/main.cpp b/0501-1000/0518-Coin-Change-2/cpp-0518/main.cpp similarity index 100% rename from 0518-Coin-Change-2/cpp-0518/main.cpp rename to 0501-1000/0518-Coin-Change-2/cpp-0518/main.cpp diff --git a/0518-Coin-Change-2/cpp-0518/main2.cpp b/0501-1000/0518-Coin-Change-2/cpp-0518/main2.cpp similarity index 100% rename from 0518-Coin-Change-2/cpp-0518/main2.cpp rename to 0501-1000/0518-Coin-Change-2/cpp-0518/main2.cpp diff --git a/0518-Coin-Change-2/cpp-0518/main3.cpp b/0501-1000/0518-Coin-Change-2/cpp-0518/main3.cpp similarity index 100% rename from 0518-Coin-Change-2/cpp-0518/main3.cpp rename to 0501-1000/0518-Coin-Change-2/cpp-0518/main3.cpp diff --git a/0501-1000/0519-Random-Flip-Matrix/cpp-0519/CMakeLists.txt b/0501-1000/0519-Random-Flip-Matrix/cpp-0519/CMakeLists.txt new file mode 100644 index 00000000..8c667b7d --- /dev/null +++ b/0501-1000/0519-Random-Flip-Matrix/cpp-0519/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0519) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main4.cpp) +add_executable(cpp_0519 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0519-Random-Flip-Matrix/cpp-0519/main.cpp b/0501-1000/0519-Random-Flip-Matrix/cpp-0519/main.cpp new file mode 100644 index 00000000..5f536e88 --- /dev/null +++ b/0501-1000/0519-Random-Flip-Matrix/cpp-0519/main.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/random-flip-matrix/description/ +/// Author : liuyubobobo +/// Time : 2018-08-28 + +#include +#include +#include + +using namespace std; + + +/// Rejection Sampling +/// +/// Time Complexty: O(m*n) +/// Space Complexity: O(min(len(call of flip), m*n)) +class Solution { + +private: + int m, n; + unordered_set ones; + +public: + Solution(int n_rows, int n_cols): m(n_rows), n(n_cols) { + ones.clear(); + } + + vector flip() { + + int randNum; + do{ + randNum = rand() % (m * n); + }while(ones.find(randNum) != ones.end()); + ones.insert(randNum); + return {randNum / n, randNum % n}; + } + + void reset() { + ones.clear(); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0519-Random-Flip-Matrix/cpp-0519/main2.cpp b/0501-1000/0519-Random-Flip-Matrix/cpp-0519/main2.cpp new file mode 100644 index 00000000..f97f6724 --- /dev/null +++ b/0501-1000/0519-Random-Flip-Matrix/cpp-0519/main2.cpp @@ -0,0 +1,86 @@ +/// Source : https://leetcode.com/problems/random-flip-matrix/description/ +/// Author : liuyubobobo +/// Time : 2018-08-28 + +#include +#include +#include +#include +#include +#include + +using namespace std; + + +/// Using Buckets to find the kth unflipped position +/// +/// Time Complexty: O(sqrt(m*n)) +/// Space Complexity: O(min(len(call of flip), m*n)) +class Solution { + +private: + int m, n; + int bucket_sz; + vector> buckets; + int left; + +public: + Solution(int n_rows, int n_cols): m(n_rows), n(n_cols) { + + bucket_sz = sqrt(m * n); + reset(); + } + + vector flip() { + + int randNum = rand() % left; + left --; + + int index = 0, ret = -1; + for(int i = 0; i < buckets.size(); i ++){ + int left_in_bucket = min(bucket_sz, m * n - i * bucket_sz) - buckets[i].size(); + if(randNum >= index && randNum < index + left_in_bucket){ + int k = randNum - index; + for(int j = i * bucket_sz; j < min((i + 1) * bucket_sz, m * n); j ++) + if(buckets[i].find(j) == buckets[i].end()){ + if(!k){ + ret = j; + buckets[i].insert(j); + break; + } + k --; + } + if(ret != -1) + break; + } + else + index += left_in_bucket; + } + assert(ret != -1); + return {ret / n, ret % n}; + } + + void reset() { + + buckets.clear(); + for(int i = 0; i < m * n; i += bucket_sz) + buckets.push_back(unordered_set()); + left = m * n; + } + + static void print_vec(const vector& vec){ + for(int e: vec) + cout << e << " "; + cout << endl; + } +}; + + +int main() { + + Solution solution(2, 2); + for(int i = 0; i < 4; i ++) + Solution::print_vec(solution.flip()); + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0519-Random-Flip-Matrix/cpp-0519/main3.cpp b/0501-1000/0519-Random-Flip-Matrix/cpp-0519/main3.cpp new file mode 100644 index 00000000..6a7cfeca --- /dev/null +++ b/0501-1000/0519-Random-Flip-Matrix/cpp-0519/main3.cpp @@ -0,0 +1,88 @@ +/// Source : https://leetcode.com/problems/random-flip-matrix/description/ +/// Author : liuyubobobo +/// Time : 2018-08-28 + +#include +#include +#include +#include +#include +#include + +using namespace std; + + +/// Using Buckets to find the kth unflipped position +/// Using binary search:) +/// \ +/// Time Complexty: O(sqrt(m*n)) +/// Space Complexity: O(min(len(call of flip), m*n)) +class Solution { + +private: + int m, n; + int bucket_sz; + vector> buckets; + vector start; + +public: + Solution(int n_rows, int n_cols): m(n_rows), n(n_cols) { + + bucket_sz = sqrt(m * n); + reset(); + } + + vector flip() { + +// Solution::print_vec(start); + + int randNum = rand() % start.back(); + int index = upper_bound(start.begin(), start.end(), randNum) - start.begin(); + index --; +// cout << "find " << randNum << " in " << index << " bucket." << endl; + + int k = randNum - start[index]; + int ret = -1; + for(int i = index * bucket_sz; ; i ++) + if(buckets[index].find(i) == buckets[index].end()){ + if(!k){ + ret = i; + buckets[index].insert(i); + break; + } + k --; + } + + for(int i = index + 1; i < start.size(); i ++) + start[i] --; + return {ret / n, ret % n}; + } + + void reset() { + + buckets.clear(); + start.clear(); + + start.push_back(0); + for(int i = 0; i < m * n; i += bucket_sz){ + buckets.push_back(unordered_set()); + start.push_back(min(start.back() + bucket_sz, m * n)); + } + } + + static void print_vec(const vector& vec){ + for(int e: vec) + cout << e << " "; + cout << endl; + } +}; + + +int main() { + + Solution solution(2, 2); + for(int i = 0; i < 4; i ++) + Solution::print_vec(solution.flip()); + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0519-Random-Flip-Matrix/cpp-0519/main4.cpp b/0501-1000/0519-Random-Flip-Matrix/cpp-0519/main4.cpp new file mode 100644 index 00000000..9e74f8cc --- /dev/null +++ b/0501-1000/0519-Random-Flip-Matrix/cpp-0519/main4.cpp @@ -0,0 +1,65 @@ +/// Source : https://leetcode.com/problems/random-flip-matrix/description/ +/// Author : liuyubobobo +/// Time : 2018-08-28 + +#include +#include +#include +#include + +using namespace std; + + +/// Position redirection +/// Time Complexty: O(1) +/// Space Complexity: O(min(len(call of flip), m*n)) +class Solution { + +private: + int m, n; + int left; + unordered_map redirection; + +public: + Solution(int n_rows, int n_cols): m(n_rows), n(n_cols) { + reset(); + } + + vector flip() { + + int randNum = rand() % left; + left --; + + int ret = randNum; + if(redirection.find(randNum) != redirection.end()) + ret = redirection[randNum]; + + if(redirection.find(left) == redirection.end()) + redirection[randNum] = left; + else + redirection[randNum] = redirection[left]; + + return {ret / n, ret % n}; + } + + void reset() { + left = m * n; + redirection.clear(); + } +}; + + +void print_vec(const vector& vec){ + for(int e: vec) + cout << e << " "; + cout << endl; +} + +int main() { + + Solution solution(2, 2); + for(int i = 0; i < 4; i ++) + print_vec(solution.flip()); + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0520-Detect-Capital/cpp-0520/CMakeLists.txt b/0501-1000/0520-Detect-Capital/cpp-0520/CMakeLists.txt new file mode 100644 index 00000000..7aedab23 --- /dev/null +++ b/0501-1000/0520-Detect-Capital/cpp-0520/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0520) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0520 main.cpp) diff --git a/0501-1000/0520-Detect-Capital/cpp-0520/main.cpp b/0501-1000/0520-Detect-Capital/cpp-0520/main.cpp new file mode 100644 index 00000000..8b600cdf --- /dev/null +++ b/0501-1000/0520-Detect-Capital/cpp-0520/main.cpp @@ -0,0 +1,36 @@ +/// Source : https://leetcode.com/problems/detect-capital/ +/// Author : liuyubobobo +/// Time : 2021-11-12 + +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(|s|) +/// Space Complexity: O(1) +class Solution { +public: + bool detectCapitalUse(string word) { + + return all_upper(word) || all_lower(word) || (isupper(word[0]) && all_lower(word.substr(1))); + } + +private: + bool all_upper(const string& s){ + for(char c: s) if(islower(c)) return false; + return true; + } + + bool all_lower(const string& s){ + for(char c: s) if(isupper(c)) return false; + return true; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0521-Longest-Uncommon-Subsequence-I/cpp-0521/CMakeLists.txt b/0501-1000/0521-Longest-Uncommon-Subsequence-I/cpp-0521/CMakeLists.txt new file mode 100644 index 00000000..7f5c1a9c --- /dev/null +++ b/0501-1000/0521-Longest-Uncommon-Subsequence-I/cpp-0521/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0521) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0521 main.cpp) diff --git a/0501-1000/0521-Longest-Uncommon-Subsequence-I/cpp-0521/main.cpp b/0501-1000/0521-Longest-Uncommon-Subsequence-I/cpp-0521/main.cpp new file mode 100644 index 00000000..6b9d0c5f --- /dev/null +++ b/0501-1000/0521-Longest-Uncommon-Subsequence-I/cpp-0521/main.cpp @@ -0,0 +1,28 @@ +/// Source : https://leetcode.com/problems/longest-uncommon-subsequence-i/ +/// Author : liuyubobobo +/// Time : 2021-08-27 + +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int findLUSlength(string a, string b) { + + if(a.size() != b.size()) return max(a.size(), b.size()); + + return a == b ? -1 : a.size(); + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0522-Longest-Uncommon-Subsequence-II/cpp-0522/CMakeLists.txt b/0501-1000/0522-Longest-Uncommon-Subsequence-II/cpp-0522/CMakeLists.txt new file mode 100644 index 00000000..aac0994a --- /dev/null +++ b/0501-1000/0522-Longest-Uncommon-Subsequence-II/cpp-0522/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0522) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0522 main.cpp) diff --git a/0501-1000/0522-Longest-Uncommon-Subsequence-II/cpp-0522/main.cpp b/0501-1000/0522-Longest-Uncommon-Subsequence-II/cpp-0522/main.cpp new file mode 100644 index 00000000..dada72a1 --- /dev/null +++ b/0501-1000/0522-Longest-Uncommon-Subsequence-II/cpp-0522/main.cpp @@ -0,0 +1,49 @@ +/// Source : https://leetcode.com/problems/longest-uncommon-subsequence-ii/ +/// Author : liuyubobobo +/// Time : 2021-08-27 + +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(n^2 * |len|) +/// Space Complexity: O(1) +class Solution { +public: + int findLUSlength(vector& strs) { + + int res = 0; + for(int i = 0; i < strs.size(); i ++){ + int j = 0; + for(j = 0; j < strs.size(); j ++){ + if(i == j) continue; + if(is_subseq(strs[i], strs[j])) + break; + } + if(j == strs.size()) + res = max(res, (int)strs[i].size()); + } + return res == 0 ? - 1: res; + } + +private: + // see if a is b's sub seq + bool is_subseq(const string& a, const string& b){ + + if(a.size() > b.size()) return false; + + int i = 0; + for(int j = 0; j < b.size(); j ++) + if(a[i] == b[j]) i ++; + return i == a.size(); + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0523-Continuous-Subarray-Sum/cpp-0523/CMakeLists.txt b/0501-1000/0523-Continuous-Subarray-Sum/cpp-0523/CMakeLists.txt new file mode 100644 index 00000000..d791c6b2 --- /dev/null +++ b/0501-1000/0523-Continuous-Subarray-Sum/cpp-0523/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_0523) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0523 main.cpp) \ No newline at end of file diff --git a/0501-1000/0523-Continuous-Subarray-Sum/cpp-0523/main.cpp b/0501-1000/0523-Continuous-Subarray-Sum/cpp-0523/main.cpp new file mode 100644 index 00000000..a6bcd8e5 --- /dev/null +++ b/0501-1000/0523-Continuous-Subarray-Sum/cpp-0523/main.cpp @@ -0,0 +1,42 @@ +/// Source : https://leetcode.com/problems/continuous-subarray-sum/ +/// Author : liuyubobobo +/// Time : 2021-06-01 + +#include +#include +#include + +using namespace std; + + +/// Using HashSet +/// Time Complexity: O(n) +/// Space Complexity: O(k) +class Solution { +public: + bool checkSubarraySum(vector& nums, int k) { + + unordered_set table; + table.insert(0); + + int sum = 0; + for(int i = 1; i < nums.size(); i ++){ + if(table.count((sum + nums[i - 1] + nums[i]) % k)) + return true; + + sum += nums[i - 1]; + table.insert(sum % k); + } + return false; + } +}; + + +int main() { + + vector nums1 = {23,2,6,4,7}; + cout << Solution().checkSubarraySum(nums1, 13) << endl; + // 0 + + return 0; +} diff --git a/0501-1000/0524-Longest-Word-in-Dictionary-through-Deleting/cpp-0524/CMakeLists.txt b/0501-1000/0524-Longest-Word-in-Dictionary-through-Deleting/cpp-0524/CMakeLists.txt new file mode 100644 index 00000000..ce6a94ed --- /dev/null +++ b/0501-1000/0524-Longest-Word-in-Dictionary-through-Deleting/cpp-0524/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0524) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0524 main.cpp) \ No newline at end of file diff --git a/0501-1000/0524-Longest-Word-in-Dictionary-through-Deleting/cpp-0524/main.cpp b/0501-1000/0524-Longest-Word-in-Dictionary-through-Deleting/cpp-0524/main.cpp new file mode 100644 index 00000000..6a4c34e3 --- /dev/null +++ b/0501-1000/0524-Longest-Word-in-Dictionary-through-Deleting/cpp-0524/main.cpp @@ -0,0 +1,39 @@ +/// Source : https://leetcode.com/problems/longest-word-in-dictionary-through-deleting/ +/// Author : liuyubobobo +/// Time : 2021-02-22 + +#include +#include + +using namespace std; + + +/// Brute Force + Two Pointers +/// Time Complexity: O(n * |word|) +/// Space Complexity: O(1) +class Solution { +public: + string findLongestWord(string s, vector& d) { + + string res = ""; + for(const string& t: d) + if(ok(s, t) && (t.size() > res.size() || (t.size() == res.size() && t < res))) + res = t; + return res; + } + +private: + bool ok(const string& s, const string& t){ + + int j = 0; + for(int i = 0; i < s.size() && j < t.size(); i ++) + if(s[i] == t[j]) j ++; + return j == t.size(); + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0525-Contiguous-Array/cpp-0525/CMakeLists.txt b/0501-1000/0525-Contiguous-Array/cpp-0525/CMakeLists.txt new file mode 100644 index 00000000..9e69a849 --- /dev/null +++ b/0501-1000/0525-Contiguous-Array/cpp-0525/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(cpp_0525) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0525 main.cpp) \ No newline at end of file diff --git a/0501-1000/0525-Contiguous-Array/cpp-0525/main.cpp b/0501-1000/0525-Contiguous-Array/cpp-0525/main.cpp new file mode 100644 index 00000000..659dc516 --- /dev/null +++ b/0501-1000/0525-Contiguous-Array/cpp-0525/main.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/contiguous-array/ +/// Author : liuyubobobo +/// Time : 2020-05-26 + +#include +#include +#include + +using namespace std; + + +/// Linear Scan + HashMap +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int findMaxLength(vector& nums) { + + int cur = 0, res = 0; + unordered_map map; // key -> index + map[cur] = -1; + for(int i = 0; i < nums.size(); i ++){ + cur += nums[i] ? 1 : -1; + if(map.count(cur)) res = max(res, i - map[cur]); + else map[cur] = i; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0526-Beautiful-Arrangement/cpp-0526/CMakeLists.txt b/0501-1000/0526-Beautiful-Arrangement/cpp-0526/CMakeLists.txt new file mode 100644 index 00000000..6fea7d4f --- /dev/null +++ b/0501-1000/0526-Beautiful-Arrangement/cpp-0526/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0526) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0526 main.cpp) \ No newline at end of file diff --git a/0501-1000/0526-Beautiful-Arrangement/cpp-0526/main.cpp b/0501-1000/0526-Beautiful-Arrangement/cpp-0526/main.cpp new file mode 100644 index 00000000..6c8cd7da --- /dev/null +++ b/0501-1000/0526-Beautiful-Arrangement/cpp-0526/main.cpp @@ -0,0 +1,45 @@ +/// Source : https://leetcode.com/problems/beautiful-arrangement/ +/// Author : liuyubobobo +/// Time : 2020-01-03 + +#include +#include + +using namespace std; + + +/// Backtrack +/// Time Complexity: O(n^n) +/// Space Complexity: O(n) +class Solution { +public: + int countArrangement(int n) { + + vector used(n + 1, false); + return dfs(n, 1, used); + } + +private: + int dfs(int n, int index, vector& used){ + + if(index == n + 1) return 1; + + int res = 0; + for(int num = 1; num <= n; num ++) + if(!used[num] && (num % index == 0 || index % num == 0)){ + used[num] = true; + res += dfs(n, index + 1, used); + used[num] = false; + } + return res; + } +}; + + +int main() { + + cout << Solution().countArrangement(2) << endl; + // 2 + + return 0; +} diff --git a/0501-1000/0527-Word-Abbreviation/cpp-0527/CMakeLists.txt b/0501-1000/0527-Word-Abbreviation/cpp-0527/CMakeLists.txt new file mode 100644 index 00000000..575077dc --- /dev/null +++ b/0501-1000/0527-Word-Abbreviation/cpp-0527/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_0527) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0527 main.cpp) diff --git a/0501-1000/0527-Word-Abbreviation/cpp-0527/main.cpp b/0501-1000/0527-Word-Abbreviation/cpp-0527/main.cpp new file mode 100644 index 00000000..661a29c2 --- /dev/null +++ b/0501-1000/0527-Word-Abbreviation/cpp-0527/main.cpp @@ -0,0 +1,90 @@ +/// Source : https://leetcode.com/problems/word-abbreviation/ +/// Author : liuyubobobo +/// Time : 2022-06-14 + +#include +#include +#include + +using namespace std; + + +/// Hash Map + Simulation +/// Time Complexity: O(len * 26^2 + nlogn + n * len^2) +/// Space Compelxity: O(len * 26^2 + n) +class Solution { +public: + vector wordsAbbreviation(const vector& words) { + + int n = words.size(); + + vector res(n, ""); + + vector table[26][26][401]; + for(int i = 0; i < n; i ++){ + const string& word = words[i]; + table[word[0] - 'a'][word.back() - 'a'][word.size()].push_back(i); + } + + for(int first = 0; first < 26; first ++) + for(int last = 0; last < 26; last ++) + for(int len = 2; len <= 400; len ++){ + const vector& v = table[first][last][len]; + if(v.empty()) continue; + if(v.size() == 1){ + res[v[0]] = get_abbr(words[v[0]], 0); + continue; + } + + vector> data(v.size()); + for(int i = 0; i < v.size(); i ++) data[i] = {words[v[i]], v[i]}; + sort(data.begin(), data.end()); + + for(int i = 0; i < data.size(); i ++){ + const string& word = data[i].first; + int index = data[i].second; + + for(int prefix_len = 2;; prefix_len ++){ + bool ok1 = i - 1 < 0 || word.substr(0, prefix_len) != data[i - 1].first.substr(0, prefix_len); + bool ok2 = i + 1 >= data.size() || word.substr(0, prefix_len) != data[i + 1].first.substr(0, prefix_len); + if(ok1 && ok2){ + res[index] = get_abbr(word, prefix_len - 1); + break; + } + } + assert(res[index] != ""); + } + } + return res; + } + +private: + // [0...prefix_end_index] + num + last_character + string get_abbr(const string& s, int prefix_end_index){ + + string res = s.substr(0, prefix_end_index + 1); + int len = s.size() - (prefix_end_index + 2); + if(len) res += to_string(len); + res += s.back(); + + return res.size() < s.size() ? res : s; + } +}; + + +void print_vec(const vector& res){ + for(const string& e: res) cout << e << ' '; cout << '\n'; +} + +int main() { + + vector words1 = {"like","god","internal","me","internet","interval","intension","face","intrusion"}; + print_vec(Solution().wordsAbbreviation(words1)); + // ["l2e","god","internal","me","i6t","interval","inte4n","f2e","intr4n"] + + vector words2 = {"abcdefg","abccefg","abcckkg"}; + print_vec(Solution().wordsAbbreviation(words2)); + // ["abcd2g","abccefg","abcckkg"] + + return 0; +} diff --git a/0501-1000/0528-Random-Pick-with-Weight/cpp-0528/CMakeLists.txt b/0501-1000/0528-Random-Pick-with-Weight/cpp-0528/CMakeLists.txt new file mode 100644 index 00000000..cd595f01 --- /dev/null +++ b/0501-1000/0528-Random-Pick-with-Weight/cpp-0528/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0528) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0528 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0528-Random-Pick-with-Weight/cpp-0528/main.cpp b/0501-1000/0528-Random-Pick-with-Weight/cpp-0528/main.cpp new file mode 100644 index 00000000..0866a33f --- /dev/null +++ b/0501-1000/0528-Random-Pick-with-Weight/cpp-0528/main.cpp @@ -0,0 +1,43 @@ +/// Source : https://leetcode.com/problems/random-pick-with-weight/description/ +/// Author : liuyubobobo +/// Time : 2018-08-28 + +#include +#include +#include + +using namespace std; + + +/// Pre-Sum and Binary Search +/// Time Complexity: init: O(n) +/// pickIndex: O(logn) +/// Space Complexity: O(n) +class Solution { + +private: + vector sum; + +public: + Solution(vector w) { + sum.clear(); + sum.push_back(0); + for(int e: w) + sum.push_back(sum.back() + e); + } + + int pickIndex() { + + int randNum = rand() % sum.back(); + int index = lower_bound(sum.begin(), sum.end(), randNum) - sum.begin(); + if(sum[index] != randNum) + index --; + return index; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0529-Minesweeper/cpp-0529/CMakeLists.txt b/0501-1000/0529-Minesweeper/cpp-0529/CMakeLists.txt new file mode 100644 index 00000000..84ee9ce5 --- /dev/null +++ b/0501-1000/0529-Minesweeper/cpp-0529/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(cpp_0529) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0529 main.cpp) \ No newline at end of file diff --git a/0501-1000/0529-Minesweeper/cpp-0529/main.cpp b/0501-1000/0529-Minesweeper/cpp-0529/main.cpp new file mode 100644 index 00000000..d4f05694 --- /dev/null +++ b/0501-1000/0529-Minesweeper/cpp-0529/main.cpp @@ -0,0 +1,78 @@ +/// Source : https://leetcode.com/problems/minesweeper/ +/// Author : liuyubobobo +/// Time : 2019-09-07 + +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n * m) +/// Space Complexity: O(n * m) +class Solution { + +private: + int n, m; + +public: + vector> updateBoard(vector>& board, vector& click) { + + if(board[click[0]][click[1]] == 'M'){ + board[click[0]][click[1]] = 'X'; + return board; + } + + n = board.size(), m = board[0].size(); + go(board, click[0], click[1]); + return board; + } + +private: + void go(vector>& board, int x, int y){ + + int res = 0; + for(int dx = -1; dx <= 1; dx ++) + for(int dy = -1; dy <= 1; dy ++) + if((dx || dy) && in_area(x + dx, y + dy)) + res += (board[x + dx][y + dy] == 'M'); + + if(res){ + board[x][y] = '0' + res; + return; + } + + board[x][y] = 'B'; + for(int dx = -1; dx <= 1; dx ++) + for(int dy = -1; dy <= 1; dy ++) + if((dx || dy) && in_area(x + dx, y + dy) && board[x + dx][y + dy] == 'E') + go(board, x + dx, y + dy); + } + + bool in_area(int x, int y){ + return x >= 0 && x < n && y >= 0 && y < m; + } +}; + + +void print_board(const vector>& board){ + for(const vector& v: board){ + for(char c: v) cout << c << " "; + cout << endl; + } +} + +int main() { + + vector> board1 = { + {'E', 'E', 'E', 'E', 'E'}, + {'E', 'E', 'M', 'E', 'E'}, + {'E', 'E', 'E', 'E', 'E'}, + {'E', 'E', 'E', 'E', 'E'} + }; + vector click1 = {3, 0}; + print_board(Solution().updateBoard(board1, click1)); + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0530-Minimum-Absolute-Difference-in-BST/java-0530/src/Solution.java b/0501-1000/0530-Minimum-Absolute-Difference-in-BST/java-0530/src/Solution.java new file mode 100644 index 00000000..2050633b --- /dev/null +++ b/0501-1000/0530-Minimum-Absolute-Difference-in-BST/java-0530/src/Solution.java @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/minimum-absolute-difference-in-bst/description/ +/// Author : liuyubobobo +/// Time : 2018-04-30 + +import java.util.ArrayList; +import java.util.Collections; + +/// Traverse all nodes in BST and sort +/// +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { + + public int getMinimumDifference(TreeNode root) { + + ArrayList list = new ArrayList<>(); + preOrder(root, list); + + Collections.sort(list); + int res = Integer.MAX_VALUE; + for(int i = 1 ; i < list.size() ; i ++) + res = Math.min(res, list.get(i) - list.get(i - 1)); + return res; + } + + private void preOrder(TreeNode node, ArrayList list){ + + if(node == null) + return; + + list.add(node.val); + preOrder(node.left, list); + preOrder(node.right, list); + } +} diff --git a/0501-1000/0530-Minimum-Absolute-Difference-in-BST/java-0530/src/Solution2.java b/0501-1000/0530-Minimum-Absolute-Difference-in-BST/java-0530/src/Solution2.java new file mode 100644 index 00000000..cafc212d --- /dev/null +++ b/0501-1000/0530-Minimum-Absolute-Difference-in-BST/java-0530/src/Solution2.java @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/minimum-absolute-difference-in-bst/description/ +/// Author : liuyubobobo +/// Time : 2018-04-30 + +import java.util.ArrayList; +import java.util.Collections; + +/// Using inorder to traverse all nodes +/// +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution2 { + + public int getMinimumDifference(TreeNode root) { + + ArrayList list = new ArrayList<>(); + inOrder(root, list); + + int res = Integer.MAX_VALUE; + for(int i = 1 ; i < list.size() ; i ++) + res = Math.min(res, list.get(i) - list.get(i - 1)); + return res; + } + + private void inOrder(TreeNode node, ArrayList list){ + + if(node == null) + return; + + inOrder(node.left, list); + list.add(node.val); + inOrder(node.right, list); + } +} diff --git a/0501-1000/0530-Minimum-Absolute-Difference-in-BST/java-0530/src/Solution3.java b/0501-1000/0530-Minimum-Absolute-Difference-in-BST/java-0530/src/Solution3.java new file mode 100644 index 00000000..1ba25828 --- /dev/null +++ b/0501-1000/0530-Minimum-Absolute-Difference-in-BST/java-0530/src/Solution3.java @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/minimum-absolute-difference-in-bst/description/ +/// Author : liuyubobobo +/// Time : 2018-04-30 + +import java.util.ArrayList; +import java.util.Collections; + +/// Using inorder to traverse all nodes +/// and calculates the result during the inorder traverse +/// +/// Time Complexity: O(n) +/// Space Complexity: O(logn) +class Solution3 { + + private Integer prev = null; + + public int getMinimumDifference(TreeNode root) { + + prev = null; + return inOrder(root); + } + + private int inOrder(TreeNode node){ + + if(node == null) + return Integer.MAX_VALUE; + + int res = Integer.MAX_VALUE; + + res = Math.min(res, inOrder(node.left)); + + if(prev != null) + res = Math.min(res, node.val - prev); + prev = node.val; + + res = Math.min(res, inOrder(node.right)); + + return res; + } +} diff --git a/0501-1000/0530-Minimum-Absolute-Difference-in-BST/java-0530/src/TreeNode.java b/0501-1000/0530-Minimum-Absolute-Difference-in-BST/java-0530/src/TreeNode.java new file mode 100644 index 00000000..b7dbcf2e --- /dev/null +++ b/0501-1000/0530-Minimum-Absolute-Difference-in-BST/java-0530/src/TreeNode.java @@ -0,0 +1,7 @@ +/// Definition for a binary tree node. +public class TreeNode { + int val; + TreeNode left; + TreeNode right; + TreeNode(int x) { val = x; } +} diff --git a/0501-1000/0531-Lonely-Pixel-I/cpp-0531/CMakeLists.txt b/0501-1000/0531-Lonely-Pixel-I/cpp-0531/CMakeLists.txt new file mode 100644 index 00000000..58e2a42a --- /dev/null +++ b/0501-1000/0531-Lonely-Pixel-I/cpp-0531/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0531) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0531 main.cpp) \ No newline at end of file diff --git a/0501-1000/0531-Lonely-Pixel-I/cpp-0531/main.cpp b/0501-1000/0531-Lonely-Pixel-I/cpp-0531/main.cpp new file mode 100644 index 00000000..15fcb4c1 --- /dev/null +++ b/0501-1000/0531-Lonely-Pixel-I/cpp-0531/main.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/lonely-pixel-i/ +/// Author : liuyubobobo +/// Time : 2020-10-16 + +#include +#include + +using namespace std; + + +/// Two Passes +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { +public: + int findLonelyPixel(vector>& picture) { + + int R = picture.size(), C = picture[0].size(); + vector rows(R, 0), cols(C, 0); + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++) + if(picture[i][j] == 'B') rows[i] ++, cols[j] ++; + + int res = 0; + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++) + if(picture[i][j] == 'B' && rows[i] == 1 && cols[j] == 1) + res ++; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0532-K-diff-Pairs-in-an-Array/cpp-0532/CMakeLists.txt b/0501-1000/0532-K-diff-Pairs-in-an-Array/cpp-0532/CMakeLists.txt new file mode 100644 index 00000000..78a5c7dd --- /dev/null +++ b/0501-1000/0532-K-diff-Pairs-in-an-Array/cpp-0532/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_0532) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0532 main.cpp) diff --git a/0501-1000/0532-K-diff-Pairs-in-an-Array/cpp-0532/main.cpp b/0501-1000/0532-K-diff-Pairs-in-an-Array/cpp-0532/main.cpp new file mode 100644 index 00000000..ec29f8fb --- /dev/null +++ b/0501-1000/0532-K-diff-Pairs-in-an-Array/cpp-0532/main.cpp @@ -0,0 +1,49 @@ +/// Source : https://leetcode.com/problems/k-diff-pairs-in-an-array/ +/// Author : liuyubobobo +/// Time : 2022-02-08 + +#include +#include +#include + +using namespace std; + + +/// Using Map +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int findPairs(vector& nums, int k) { + + multiset left; + set> record; + for(int e: nums) left.insert(e); + + for(int i = (int)nums.size() - 1; i >= 0; i --){ + left.erase(left.find(nums[i])); + int a = nums[i] - k, b = nums[i], c = nums[i] + k; + if(left.count(a)) record.insert({min(a, b), max(a, b)}); + if(left.count(c)) record.insert({min(b, c), max(b, c)}); + } + return record.size(); + } +}; + + +int main() { + + vector nums1 = {3, 1, 4, 1, 5}; + cout << Solution().findPairs(nums1, 2) << endl; + // 2 + + vector nums2 = {1, 3, 1, 5, 4}; + cout << Solution().findPairs(nums2, 0) << endl; + // 1 + + vector nums3 = {1,2,4,4,3,3,0,9,2,3}; + cout << Solution().findPairs(nums3, 3) << endl; + // 2 + + return 0; +} diff --git a/0501-1000/0533-Lonely-Pixel-II/cpp-0533/CMakeLists.txt b/0501-1000/0533-Lonely-Pixel-II/cpp-0533/CMakeLists.txt new file mode 100644 index 00000000..f1277e33 --- /dev/null +++ b/0501-1000/0533-Lonely-Pixel-II/cpp-0533/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0533) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0533 main2.cpp) \ No newline at end of file diff --git a/0501-1000/0533-Lonely-Pixel-II/cpp-0533/main.cpp b/0501-1000/0533-Lonely-Pixel-II/cpp-0533/main.cpp new file mode 100644 index 00000000..b0365417 --- /dev/null +++ b/0501-1000/0533-Lonely-Pixel-II/cpp-0533/main.cpp @@ -0,0 +1,49 @@ +/// Source : https://leetcode.com/problems/lonely-pixel-ii/ +/// Author : liuyubobobo +/// Time : 2020-10-16 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n^4) +/// Space Complexity: O(n) +class Solution { +public: + int findBlackPixel(vector>& picture, int N) { + + int R = picture.size(), C = picture[0].size(); + vector rows(R, 0), cols(C, 0); + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++) + if(picture[i][j] == 'B') rows[i] ++, cols[j] ++; + + int res = 0; + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++) + if(ok(picture, i, j, rows, cols, N)) res ++; + return res; + } + +private: + bool ok(const vector>& picture, int x, int y, + const vector& rows, const vector& cols, int N){ + + if(picture[x][y] != 'B' ) return false; + if(rows[x] != N) return false; + if(cols[y] != N) return false; + + for(int i = 0; i < picture.size(); i ++) + if(picture[i][y] == 'B' && picture[i] != picture[x]) return false; + return true; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0533-Lonely-Pixel-II/cpp-0533/main2.cpp b/0501-1000/0533-Lonely-Pixel-II/cpp-0533/main2.cpp new file mode 100644 index 00000000..69cc0d1a --- /dev/null +++ b/0501-1000/0533-Lonely-Pixel-II/cpp-0533/main2.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/lonely-pixel-ii/ +/// Author : liuyubobobo +/// Time : 2020-10-16 + +#include +#include + +using namespace std; + + +/// Pre-calculate row's equality +/// Time Complexity: O(n^3) +/// Space Complexity: O(n^2) +class Solution { +public: + int findBlackPixel(vector>& picture, int N) { + + int R = picture.size(), C = picture[0].size(); + vector rows(R, 0), cols(C, 0); + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++) + if(picture[i][j] == 'B') rows[i] ++, cols[j] ++; + + vector> same(R, vector(R, false)); + for(int i = 0; i < R; i ++) + for(int j = i; j < R; j ++) + if(picture[i] == picture[j]) same[i][j] = same[j][i] = true; + + int res = 0; + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++) + if(ok(picture, i, j, N, rows, cols, same)) res ++; + return res; + } + +private: + bool ok(const vector>& picture, int x, int y, int N, + const vector& rows, const vector& cols, vector>& same){ + + if(picture[x][y] != 'B' ) return false; + if(rows[x] != N) return false; + if(cols[y] != N) return false; + + for(int i = 0; i < picture.size(); i ++) + if(picture[i][y] == 'B' && !same[i][x]) return false; + return true; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0536-Construct-Binary-Tree-from-String/cpp-0536/CMakeLists.txt b/0501-1000/0536-Construct-Binary-Tree-from-String/cpp-0536/CMakeLists.txt new file mode 100644 index 00000000..41a9afe3 --- /dev/null +++ b/0501-1000/0536-Construct-Binary-Tree-from-String/cpp-0536/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0536) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0536 main.cpp) \ No newline at end of file diff --git a/0501-1000/0536-Construct-Binary-Tree-from-String/cpp-0536/main.cpp b/0501-1000/0536-Construct-Binary-Tree-from-String/cpp-0536/main.cpp new file mode 100644 index 00000000..3fa404e1 --- /dev/null +++ b/0501-1000/0536-Construct-Binary-Tree-from-String/cpp-0536/main.cpp @@ -0,0 +1,73 @@ +/// Source : https://leetcode.com/problems/construct-binary-tree-from-string/ +/// Author : liuyubobobo +/// Time : 2021-03-15 + +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// 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* str2tree(string s) { + + return str2tree(s, 0, s.size() - 1); + } + +private: + TreeNode* str2tree(const string& s, int l, int r){ + + if(l > r) return NULL; + + if(s[l] == '('){ + assert(s[r] == ')'); + return str2tree(s, l + 1, r - 1); + } + + int start = -1; + for(int i = l; i <= r; i ++) + if(s[i] == '('){ + start = i; + break; + } + + if(start == -1) + return new TreeNode(atoi(s.substr(l, r - l + 1).c_str())); + + TreeNode* node = new TreeNode(atoi(s.substr(l, start - l).c_str())); + + int stack = 1; + for(int i = start + 1; i <= r; i ++){ + if(s[i] == '(') stack ++; + else if(s[i] == ')') stack --; + + if(stack == 0){ + assert(s[i] == ')'); + node->left = str2tree(s, start + 1, i - 1); + node->right = str2tree(s, i + 1, r); + + } + } + return node; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0537-Complex-Number-Multiplication/cpp-0537/CMakeLists.txt b/0501-1000/0537-Complex-Number-Multiplication/cpp-0537/CMakeLists.txt new file mode 100644 index 00000000..2aaf1acd --- /dev/null +++ b/0501-1000/0537-Complex-Number-Multiplication/cpp-0537/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0537) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0537 main.cpp) diff --git a/0501-1000/0537-Complex-Number-Multiplication/cpp-0537/main.cpp b/0501-1000/0537-Complex-Number-Multiplication/cpp-0537/main.cpp new file mode 100644 index 00000000..86441c42 --- /dev/null +++ b/0501-1000/0537-Complex-Number-Multiplication/cpp-0537/main.cpp @@ -0,0 +1,41 @@ +/// Source : https://leetcode.com/problems/complex-number-multiplication/ +/// Author : liuyubobobo +/// Time : 2021-08-24 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(|num1 + num2|) +/// Space Complexity: O(1) +class Solution { +public: + string complexNumberMultiply(string num1, string num2) { + + complex p1 = get_complex(num1); + complex p2 = get_complex(num2); + + complex res = p1 * p2; + return to_string(res.real()) + "+" + to_string(res.imag()) + "i"; + } + +private: + complex get_complex(const string& num){ + + int add = num.find('+'); + int real = atoi(num.substr(0, add).c_str()); + + int img = atoi(num.substr(add + 1, num.size() - (add + 1) - 1).c_str()); + + return complex(real, img); + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0538-Convert-BST-to-Greater-Tree/cpp-0538/CMakeLists.txt b/0501-1000/0538-Convert-BST-to-Greater-Tree/cpp-0538/CMakeLists.txt new file mode 100644 index 00000000..372f76a2 --- /dev/null +++ b/0501-1000/0538-Convert-BST-to-Greater-Tree/cpp-0538/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0538) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0538 main3.cpp) \ No newline at end of file diff --git a/0501-1000/0538-Convert-BST-to-Greater-Tree/cpp-0538/main.cpp b/0501-1000/0538-Convert-BST-to-Greater-Tree/cpp-0538/main.cpp new file mode 100644 index 00000000..41d3d909 --- /dev/null +++ b/0501-1000/0538-Convert-BST-to-Greater-Tree/cpp-0538/main.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/convert-bst-to-greater-tree/ +/// Author : liuyubobobo +/// Time : 2021-02-09 +/// Updated: 2021-08-09 + +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(h) + +/// 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* convertBST(TreeNode* root) { + + dfs(root, 0); + return root; + } + +private: + int dfs(TreeNode* node, int t){ + + if(!node) return 0; + + int rsum = dfs(node->right, t); + int lsum = dfs(node->left, node->val + rsum + t); + int ret = lsum + rsum + node->val; + node->val += rsum + t; + return ret; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0538-Convert-BST-to-Greater-Tree/cpp-0538/main2.cpp b/0501-1000/0538-Convert-BST-to-Greater-Tree/cpp-0538/main2.cpp new file mode 100644 index 00000000..3e2610fd --- /dev/null +++ b/0501-1000/0538-Convert-BST-to-Greater-Tree/cpp-0538/main2.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/convert-bst-to-greater-tree/ +/// Author : liuyubobobo +/// Updated: 2021-08-09 + +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(h) + +/// 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* convertBST(TreeNode* root) { + + pair res = dfs(root, 0); + root = res.first; + return res.first; + } + +private: + pair dfs(TreeNode* node, int t){ + + if(!node) return {nullptr, 0}; + + pair rres = dfs(node->right, t); + pair lres = dfs(node->left, node->val + rres.second + t); + + node->left = lres.first; + node->right = rres.first; + int sum = node->val + lres.second + rres.second; + node->val += rres.second + t; + + return {node, sum}; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0538-Convert-BST-to-Greater-Tree/cpp-0538/main3.cpp b/0501-1000/0538-Convert-BST-to-Greater-Tree/cpp-0538/main3.cpp new file mode 100644 index 00000000..b91678e5 --- /dev/null +++ b/0501-1000/0538-Convert-BST-to-Greater-Tree/cpp-0538/main3.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/convert-bst-to-greater-tree/ +/// Author : liuyubobobo +/// Updated: 2021-08-09 + +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(h) + +/// 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 { + +private: + int sum = 0; + +public: + TreeNode* convertBST(TreeNode* root) { + + sum = 0; + return dfs(root); + } + +private: + TreeNode* dfs(TreeNode* node){ + + if(!node) return node; + + node->right = dfs(node->right); + sum += node->val; + node->val = sum; + node->left = dfs(node->left); + + return node; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0539-Minimum-Time-Difference/cpp-0539/CMakeLists.txt b/0501-1000/0539-Minimum-Time-Difference/cpp-0539/CMakeLists.txt new file mode 100644 index 00000000..b99e8673 --- /dev/null +++ b/0501-1000/0539-Minimum-Time-Difference/cpp-0539/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_0539) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0539 main.cpp) diff --git a/0501-1000/0539-Minimum-Time-Difference/cpp-0539/main.cpp b/0501-1000/0539-Minimum-Time-Difference/cpp-0539/main.cpp new file mode 100644 index 00000000..d08cfa86 --- /dev/null +++ b/0501-1000/0539-Minimum-Time-Difference/cpp-0539/main.cpp @@ -0,0 +1,38 @@ +/// Source : https://leetcode.com/problems/minimum-time-difference/ +/// Author : liuyubobobo +/// Time : 2022-01-17 + +#include +#include + +using namespace std; + + +/// Sorting +/// Time Compelexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + int findMinDifference(vector& timePoints) { + + int n = timePoints.size(); + + vector t(n); + for(int i = 0; i < n; i ++) + t[i] = atoi(timePoints[i].substr(0, 2).c_str()) * 60 + atoi(timePoints[i].substr(3).c_str()); + + sort(t.begin(), t.end()); + + int res = INT_MAX; + for(int i = 1; i < timePoints.size(); i ++) + res = min(res, t[i] - t[i - 1]); + res = min(res, t[0] - t.back() + 24 * 60); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0540-Single-Element-in-a-Sorted-Array/cpp-0540/CMakeLists.txt b/0501-1000/0540-Single-Element-in-a-Sorted-Array/cpp-0540/CMakeLists.txt new file mode 100644 index 00000000..425badf6 --- /dev/null +++ b/0501-1000/0540-Single-Element-in-a-Sorted-Array/cpp-0540/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0540) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0540 main.cpp) diff --git a/0501-1000/0540-Single-Element-in-a-Sorted-Array/cpp-0540/main.cpp b/0501-1000/0540-Single-Element-in-a-Sorted-Array/cpp-0540/main.cpp new file mode 100644 index 00000000..b6d8a4f3 --- /dev/null +++ b/0501-1000/0540-Single-Element-in-a-Sorted-Array/cpp-0540/main.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/single-element-in-a-sorted-array/ +/// Author : liuyubobobo +/// Time : 2021-08-03 + +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(logn) +/// Space Complexity: O(1) +class Solution { +public: + int singleNonDuplicate(vector& nums) { + + nums.push_back(-1); + + int n = nums.size() / 2; + int l = 0, r = n - 1; + while(l < r){ + int mid = (l + r) / 2; + if(nums[2 * mid] != nums[2 * mid + 1]) + r = mid; + else + l = mid + 1; + } + return nums[2 * l]; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0541-Reverse-String-II/cpp-0541/CMakeLists.txt b/0501-1000/0541-Reverse-String-II/cpp-0541/CMakeLists.txt new file mode 100644 index 00000000..706be068 --- /dev/null +++ b/0501-1000/0541-Reverse-String-II/cpp-0541/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0541) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0541 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0541-Reverse-String-II/cpp-0541/main.cpp b/0501-1000/0541-Reverse-String-II/cpp-0541/main.cpp new file mode 100644 index 00000000..ce9ec0fa --- /dev/null +++ b/0501-1000/0541-Reverse-String-II/cpp-0541/main.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/reverse-string-ii/description/ +/// Author : liuyubobobo +/// Time : 2018-06-04 + +#include + +using namespace std; + +/// Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + string reverseStr(string s, int k) { + + for(int i = 0 ; i < s.size() ; i += 2 * k) + reverse(s, i, i + k); + return s; + } + +private: + void reverse(string& s, int i, int j){ + j = min(j, (int)s.size()); + j --; + while(i < j) + swap(s[i ++], s[j --]); + } +}; + +int main() { + + cout << Solution().reverseStr("abcdefg", 2) << endl; + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0542-01-Matrix/cpp-0542/CMakeLists.txt b/0501-1000/0542-01-Matrix/cpp-0542/CMakeLists.txt new file mode 100644 index 00000000..c370ce8e --- /dev/null +++ b/0501-1000/0542-01-Matrix/cpp-0542/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0542) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main4.cpp) +add_executable(cpp_0542 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0542-01-Matrix/cpp-0542/main.cpp b/0501-1000/0542-01-Matrix/cpp-0542/main.cpp new file mode 100644 index 00000000..8d7a31ce --- /dev/null +++ b/0501-1000/0542-01-Matrix/cpp-0542/main.cpp @@ -0,0 +1,76 @@ +/// Source : https://leetcode.com/problems/01-matrix/description/ +/// Author : liuyubobobo +/// Time : 2018-09-29 + +#include +#include +#include +#include + +using namespace std; + + +/// BFS +/// Time Complexity: O(m*n) +/// Space Complexity: O(m*n) +class Solution { + +private: + const int d[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; + int m, n; + +public: + vector> updateMatrix(vector>& matrix) { + + if(matrix.size() == 0 || matrix[0].size() == 0) + return matrix; + + m = matrix.size(); + n = matrix[0].size(); + + vector> res(m, vector(n, INT_MAX)); + for(int i = 0; i < m; i ++) + for(int j = 0; j < n; j ++) + if(matrix[i][j] == 0) + res[i][j] = 0; + + for(int i = 0; i < m; i ++) + for(int j = 0; j < n; j ++) + if(matrix[i][j] == 0) + bfs(matrix, i, j, res); + + return res; + } + + void bfs(const vector>& matrix, int sx, int sy, + vector>& res){ + + queue> q; + q.push(make_pair(sx * n + sy, 0)); + + while(!q.empty()){ + int x = q.front().first / n; + int y = q.front().first % n; + int step = q.front().second; + q.pop(); + + for(int k = 0; k < 4; k ++){ + int newX = x + d[k][0], newY = y + d[k][1]; + if(inArea(newX, newY) && step + 1 < res[newX][newY]){ + res[newX][newY] = step + 1; + q.push(make_pair(newX * n + newY, step + 1)); + } + } + } + } + + bool inArea(int x, int y){ + return x >= 0 && x < m && y >= 0 && y < n; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0542-01-Matrix/cpp-0542/main2.cpp b/0501-1000/0542-01-Matrix/cpp-0542/main2.cpp new file mode 100644 index 00000000..0cac62a3 --- /dev/null +++ b/0501-1000/0542-01-Matrix/cpp-0542/main2.cpp @@ -0,0 +1,77 @@ +/// Source : https://leetcode.com/problems/01-matrix/description/ +/// Author : liuyubobobo +/// Time : 2018-09-30 + +#include +#include +#include +#include + +using namespace std; + + +/// BFS +/// No need to store pair in the queue:) +/// +/// Time Complexity: O(m*n) +/// Space Complexity: O(m*n) +class Solution { + +private: + const int d[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; + int m, n; + +public: + vector> updateMatrix(vector>& matrix) { + + if(matrix.size() == 0 || matrix[0].size() == 0) + return matrix; + + m = matrix.size(); + n = matrix[0].size(); + + vector> res(m, vector(n, INT_MAX)); + for(int i = 0; i < m; i ++) + for(int j = 0; j < n; j ++) + if(matrix[i][j] == 0) + res[i][j] = 0; + + for(int i = 0; i < m; i ++) + for(int j = 0; j < n; j ++) + if(matrix[i][j] == 0) + bfs(matrix, i, j, res); + + return res; + } + + void bfs(const vector>& matrix, int sx, int sy, + vector>& res){ + + queue q; + q.push(sx * n + sy); + + while(!q.empty()){ + int x = q.front() / n; + int y = q.front() % n; + q.pop(); + + for(int k = 0; k < 4; k ++){ + int newX = x + d[k][0], newY = y + d[k][1]; + if(inArea(newX, newY) && res[x][y] + 1 < res[newX][newY]){ + res[newX][newY] = res[x][y] + 1; + q.push(newX * n + newY); + } + } + } + } + + bool inArea(int x, int y){ + return x >= 0 && x < m && y >= 0 && y < n; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0542-01-Matrix/cpp-0542/main3.cpp b/0501-1000/0542-01-Matrix/cpp-0542/main3.cpp new file mode 100644 index 00000000..8e697efd --- /dev/null +++ b/0501-1000/0542-01-Matrix/cpp-0542/main3.cpp @@ -0,0 +1,73 @@ +/// Source : https://leetcode.com/problems/01-matrix/description/ +/// Author : liuyubobobo +/// Time : 2018-09-30 + +#include +#include +#include +#include + +using namespace std; + + +/// BFS +/// Put all zero position in queue and only make one pass BFS :-) +/// +/// Time Complexity: O(m*n) +/// Space Complexity: O(m*n) +class Solution { + +private: + const int d[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; + int m, n; + +public: + vector> updateMatrix(vector>& matrix) { + + if(matrix.size() == 0 || matrix[0].size() == 0) + return matrix; + + m = matrix.size(); + n = matrix[0].size(); + + queue q; + vector> res(m, vector(n, INT_MAX)); + for(int i = 0; i < m; i ++) + for(int j = 0; j < n; j ++) + if(matrix[i][j] == 0){ + res[i][j] = 0; + q.push(i * n + j); + } + + bfs(matrix, q, res); + return res; + } + + void bfs(const vector>& matrix, queue& q, + vector>& res){ + + while(!q.empty()){ + int x = q.front() / n; + int y = q.front() % n; + q.pop(); + + for(int k = 0; k < 4; k ++){ + int newX = x + d[k][0], newY = y + d[k][1]; + if(inArea(newX, newY) && res[x][y] + 1 < res[newX][newY]){ + res[newX][newY] = res[x][y] + 1; + q.push(newX * n + newY); + } + } + } + } + + bool inArea(int x, int y){ + return x >= 0 && x < m && y >= 0 && y < n; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0542-01-Matrix/cpp-0542/main4.cpp b/0501-1000/0542-01-Matrix/cpp-0542/main4.cpp new file mode 100644 index 00000000..7b4aae88 --- /dev/null +++ b/0501-1000/0542-01-Matrix/cpp-0542/main4.cpp @@ -0,0 +1,60 @@ +/// Source : https://leetcode.com/problems/01-matrix/description/ +/// Author : liuyubobobo +/// Time : 2018-09-30 + +#include +#include +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(m*n) +/// Space Complexity: O(1) +class Solution { + +public: + vector> updateMatrix(vector>& matrix) { + + if(matrix.size() == 0 || matrix[0].size() == 0) + return matrix; + + int m = matrix.size(), n = matrix[0].size(); + + vector> res(m, vector(n, m + n + 1)); + for(int i = 0; i < m; i ++) + for(int j = 0; j < n; j ++) + if(matrix[i][j] == 0) + res[i][j] = 0; + + // top + for(int i = 1; i < m; i ++) + for(int j = 0; j < n; j ++) + res[i][j] = min(1 + res[i - 1][j], res[i][j]); + + // left + for(int i = 0; i < m; i ++) + for(int j = 1; j < n; j ++) + res[i][j] = min(1 + res[i][j - 1], res[i][j]); + + // bottom + for(int i = m - 2; i >= 0; i --) + for(int j = n - 1; j >= 0; j --) + res[i][j] = min(1 + res[i + 1][j], res[i][j]); + + // right + for(int i = m - 1; i >= 0; i --) + for(int j = n - 2; j >= 0; j --) + res[i][j] = min(1 + res[i][j + 1], res[i][j]); + + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0543-Diameter-of-Binary-Tree/cpp-0543/CMakeLists.txt b/0501-1000/0543-Diameter-of-Binary-Tree/cpp-0543/CMakeLists.txt new file mode 100644 index 00000000..064e5ad0 --- /dev/null +++ b/0501-1000/0543-Diameter-of-Binary-Tree/cpp-0543/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0543) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0543 main.cpp) \ No newline at end of file diff --git a/0501-1000/0543-Diameter-of-Binary-Tree/cpp-0543/main.cpp b/0501-1000/0543-Diameter-of-Binary-Tree/cpp-0543/main.cpp new file mode 100644 index 00000000..690ab05c --- /dev/null +++ b/0501-1000/0543-Diameter-of-Binary-Tree/cpp-0543/main.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/diameter-of-binary-tree/solution/ +/// Author : liuyubobobo +/// Time : 2020-10-15 + +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(h) + +/// 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 { + +private: + int res; + +public: + int diameterOfBinaryTree(TreeNode* root) { + + res = 0; + dfs(root); + return res; + } + +private: + int dfs(TreeNode* node){ + + if(!node) return 0; + + int l = node->left ? 1 + dfs(node->left) : 0; + int r = node->right ? 1 + dfs(node->right) : 0; + res = max(res, l + r); + return max(l, r); + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0546-Remove-Boxes/cpp-0546/CMakeLists.txt b/0501-1000/0546-Remove-Boxes/cpp-0546/CMakeLists.txt new file mode 100644 index 00000000..cc29328c --- /dev/null +++ b/0501-1000/0546-Remove-Boxes/cpp-0546/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0546) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0546 main.cpp) diff --git a/0501-1000/0546-Remove-Boxes/cpp-0546/main.cpp b/0501-1000/0546-Remove-Boxes/cpp-0546/main.cpp new file mode 100644 index 00000000..20a2b0e2 --- /dev/null +++ b/0501-1000/0546-Remove-Boxes/cpp-0546/main.cpp @@ -0,0 +1,55 @@ +/// Source : https://leetcode.com/problems/remove-boxes/ +/// Author : liuyubobobo +/// Time : 2021-08-15 + +#include +#include + +using namespace std; + + +/// Memoization +/// Time Complexity: O(n^4) +/// Space Complexity: O(n^3) +class Solution { +public: + int removeBoxes(vector& boxes) { + + int n = boxes.size(); + vector>> dp(n, vector>(n, vector(n + 1, -1))); + return dfs(boxes, 0, n - 1, 0, dp); + } + +private: + int dfs(const vector& boxes, int l, int r, int k, vector>>& dp){ + + if(l > r) return 0; + + if(dp[l][r][k] != -1) return dp[l][r][k]; + + int res = dfs(boxes, l, r - 1, 0, dp) + (k + 1) * (k + 1); + + for(int i = l; i < r; i ++) + if(boxes[i] == boxes[r]) + res = max(res, dfs(boxes, l, i, k + 1, dp) + dfs(boxes, i + 1, r - 1, 0, dp)); + return dp[l][r][k] = res; + } +}; + + +int main() { + + vector boxes1 = {1, 3, 2, 2, 2, 3, 4, 3, 1}; + cout << Solution().removeBoxes(boxes1) << endl; + // 23 + + vector boxes2 = {1, 1, 1}; + cout << Solution().removeBoxes(boxes2) << endl; + // 9 + + vector boxes3 = {1}; + cout << Solution().removeBoxes(boxes3) << endl; + // 1 + + return 0; +} diff --git a/0501-1000/0547-Number-of-Provinces/cpp-0547/CMakeLists.txt b/0501-1000/0547-Number-of-Provinces/cpp-0547/CMakeLists.txt new file mode 100644 index 00000000..ffda705a --- /dev/null +++ b/0501-1000/0547-Number-of-Provinces/cpp-0547/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0547) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0547 main2.cpp) \ No newline at end of file diff --git a/0501-1000/0547-Number-of-Provinces/cpp-0547/main.cpp b/0501-1000/0547-Number-of-Provinces/cpp-0547/main.cpp new file mode 100644 index 00000000..fe7cf297 --- /dev/null +++ b/0501-1000/0547-Number-of-Provinces/cpp-0547/main.cpp @@ -0,0 +1,49 @@ +/// Source : https://leetcode.com/problems/number-of-provinces/ +/// Author : liuyubobobo +/// Time : 2021-01-06 + +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { + +private: + int n; + +public: + int findCircleNum(vector>& M) { + + n = M.size(); + if(!n) return 0; + + int res = 0; + vector visited(n, false); + for(int i = 0; i < n; i ++) + if(!visited[i]){ + dfs(M, i, visited); + res ++; + } + return res; + } + +private: + void dfs(const vector>& M, int u, vector& visited){ + + visited[u] = true; + for(int i = 0; i < n; i ++) + if(M[u][i] && !visited[i]) + dfs(M, i, visited); + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0547-Number-of-Provinces/cpp-0547/main2.cpp b/0501-1000/0547-Number-of-Provinces/cpp-0547/main2.cpp new file mode 100644 index 00000000..680d869d --- /dev/null +++ b/0501-1000/0547-Number-of-Provinces/cpp-0547/main2.cpp @@ -0,0 +1,69 @@ +/// Source : https://leetcode.com/problems/number-of-provinces/ +/// Author : liuyubobobo +/// Time : 2021-01-06 + +#include +#include + +using namespace std; + + +/// UF +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class UF{ + +private: + vector parent; + int sz; + +public: + UF(int n) : parent(n), sz(n){ + for(int i = 0 ; i < n ; i ++) + parent[i] = i; + } + + int find(int p){ + if(p != parent[p]) + parent[p] = find(parent[p]); + return parent[p]; + } + + bool isConnected(int p, int q){ + return find(p) == find(q); + } + + void unionElements(int p, int q){ + + int pRoot = find(p), qRoot = find(q); + + if(pRoot == qRoot) return; + + parent[pRoot] = qRoot; + sz --; + } + + int size(){ + return sz; + } +}; + +class Solution { + +public: + int findCircleNum(vector>& M) { + + int n = M.size(); + UF uf(n); + for(int i = 0; i < n; i ++) + for(int j = 0; j < n; j ++) + if(M[i][j]) uf.unionElements(i, j); + return uf.size(); + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0549-Binary-Tree-Longest-Consecutive-Sequence-II/cpp-0549/CMakeLists.txt b/0501-1000/0549-Binary-Tree-Longest-Consecutive-Sequence-II/cpp-0549/CMakeLists.txt new file mode 100644 index 00000000..a04d028b --- /dev/null +++ b/0501-1000/0549-Binary-Tree-Longest-Consecutive-Sequence-II/cpp-0549/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_0549) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0549 main.cpp) \ No newline at end of file diff --git a/0501-1000/0549-Binary-Tree-Longest-Consecutive-Sequence-II/cpp-0549/main.cpp b/0501-1000/0549-Binary-Tree-Longest-Consecutive-Sequence-II/cpp-0549/main.cpp new file mode 100644 index 00000000..386422f4 --- /dev/null +++ b/0501-1000/0549-Binary-Tree-Longest-Consecutive-Sequence-II/cpp-0549/main.cpp @@ -0,0 +1,77 @@ +/// Source : https://leetcode.com/problems/binary-tree-longest-consecutive-sequence-ii/ +/// Author : liuyubobobo +/// Time : 2021-07-31 + +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(h) + +/// 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: + int longestConsecutive(TreeNode* root) { + + map inc, dec; + dfs1(root, inc); + dfs2(root, dec); + + int res = 0; + for(const pair& p: inc) + res = max(res, p.second + dec[p.first] - 1); + return res; + } + +private: + int dfs1(TreeNode* node, map& inc){ + + int res = 1, l = 0, r = 0; + if(node->left){ + l = dfs1(node->left, inc); + if(node->left->val == node->val + 1) res = max(res, l + 1); + } + if(node->right){ + r = dfs1(node->right, inc); + if(node->right->val == node->val + 1) res = max(res, r + 1); + } + + inc[node] = res; + return res; + } + + int dfs2(TreeNode* node, map& dec){ + + int res = 1, l = 0, r = 0; + if(node->left){ + l = dfs2(node->left, dec); + if(node->left->val == node->val - 1) res = max(res, l + 1); + } + if(node->right){ + r = dfs2(node->right, dec); + if(node->right->val == node->val - 1) res = max(res, r + 1); + } + + dec[node] = res; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0551-Student-Attendance-Record-I/cpp-0551/CMakeLists.txt b/0501-1000/0551-Student-Attendance-Record-I/cpp-0551/CMakeLists.txt new file mode 100644 index 00000000..90c1bfa9 --- /dev/null +++ b/0501-1000/0551-Student-Attendance-Record-I/cpp-0551/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0551) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0551 main.cpp) diff --git a/0501-1000/0551-Student-Attendance-Record-I/cpp-0551/main.cpp b/0501-1000/0551-Student-Attendance-Record-I/cpp-0551/main.cpp new file mode 100644 index 00000000..541bbfb3 --- /dev/null +++ b/0501-1000/0551-Student-Attendance-Record-I/cpp-0551/main.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/student-attendance-record-i/ +/// Author : liuyubobobo +/// Time : 2021-08-17 + +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + bool checkRecord(string s) { + + int absent = 0; + for(char c: s) + absent += (c == 'A'); + + if(absent >= 2) return false; + + for(int i = 0; i + 2 < s.size(); i ++) + if(s[i] == 'L' && s[i + 1] == 'L' && s[i + 2] == 'L') + return false; + + return true; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0552-Student-Attendance-Record-II/cpp-0552/CMakeLists.txt b/0501-1000/0552-Student-Attendance-Record-II/cpp-0552/CMakeLists.txt new file mode 100644 index 00000000..41a7fd7b --- /dev/null +++ b/0501-1000/0552-Student-Attendance-Record-II/cpp-0552/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0552) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0552 main.cpp) diff --git a/0501-1000/0552-Student-Attendance-Record-II/cpp-0552/main.cpp b/0501-1000/0552-Student-Attendance-Record-II/cpp-0552/main.cpp new file mode 100644 index 00000000..9640f45f --- /dev/null +++ b/0501-1000/0552-Student-Attendance-Record-II/cpp-0552/main.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/student-attendance-record-ii/ +/// Author : liuyubobobo +/// Time : 2021-08-17 + +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +private: + const long long MOD = 1e9 + 7; + +public: + int checkRecord(int n) { + + if(n == 1) return 3; + + vector> dp(n + 1, vector(3, 0)); + dp[1][0] = dp[1][1] = 1; + for(int i = 2; i <= n; i ++){ + dp[i][0] = (dp[i - 1][0] + dp[i - 1][1] + dp[i - 1][2]) % MOD; + dp[i][1] = dp[i - 1][0]; + dp[i][2] = dp[i - 1][1]; + } + + long long res = (dp[n][0] + dp[n][1] + dp[n][2]) % MOD; + res += (dp[n - 1][0] + dp[n - 1][1] + dp[n - 1][2]) * 2ll % MOD; + res %= MOD; + for(int i = 1; i + 1 < n; i ++) + res = (res + (dp[i][0] + dp[i][1] + dp[i][2]) * (dp[n - 1 - i][0] + dp[n - 1 - i][1] + dp[n - 1 - i][2])) % MOD; + return res; + } +}; + +int main() { + + cout << Solution().checkRecord(2) << endl; + // 8 + + cout << Solution().checkRecord(1) << endl; + // 3 + + cout << Solution().checkRecord(10101) << endl; + // 183236316 + + return 0; +} diff --git a/0501-1000/0553-Optimal-Division/cpp-0553/CMakeLists.txt b/0501-1000/0553-Optimal-Division/cpp-0553/CMakeLists.txt new file mode 100644 index 00000000..eda8775f --- /dev/null +++ b/0501-1000/0553-Optimal-Division/cpp-0553/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_0553) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0553 main.cpp) diff --git a/0501-1000/0553-Optimal-Division/cpp-0553/main.cpp b/0501-1000/0553-Optimal-Division/cpp-0553/main.cpp new file mode 100644 index 00000000..b14cbdd0 --- /dev/null +++ b/0501-1000/0553-Optimal-Division/cpp-0553/main.cpp @@ -0,0 +1,89 @@ +/// Source : https://leetcode.com/problems/optimal-division/ +/// Author : liuyubobobo +/// Time : 2022-02-27 + +#include +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(n^3) +/// Space Complexity: O(n^2) +class Solution { + +public: + string optimalDivision(vector& nums) { + + int n = nums.size(); + + vector> dp_max(n, vector(n, 0.0)); + vector> dp_max_sz(n, vector(n, 1)); + vector> dp_min(n, vector(n, 0.0)); + vector> dp_min_sz(n, vector(n, 1)); + for(int i = 0; i < n; i ++) + dp_max[i][i] = dp_min[i][i] = nums[i]; + for(int i = 0; i + 1 < n; i ++) + dp_max[i][i + 1] = dp_min[i][i + 1] = (long double)nums[i] / nums[i + 1]; + for(int sz = 2; sz <= n; sz ++) + for(int i = 0; i + sz <= n; i ++){ + // calc dp[i][i + sz - 1] + dp_max[i][i + sz - 1] = dp_max[i][i] / dp_min[i + 1][i + sz - 1]; + dp_min[i][i + sz - 1] = dp_min[i][i] / dp_max[i + 1][i + sz - 1]; + for(int sz1 = 2; sz1 < sz; sz1 ++){ + if(dp_max[i][i + sz1 - 1] / dp_min[i + sz1][i + sz - 1] > dp_max[i][i + sz - 1]) + dp_max[i][i + sz - 1] = dp_max[i][i + sz1 - 1] / dp_min[i + sz1][i + sz - 1], dp_max_sz[i][i + sz - 1] = sz1; + if(dp_min[i][i + sz1 - 1] / dp_max[i + sz1][i + sz - 1] < dp_min[i][i + sz - 1]) + dp_min[i][i + sz - 1] = dp_min[i][i + sz1 - 1] / dp_max[i + sz1][i + sz - 1], dp_min_sz[i][i + sz - 1] = sz1; + } + } + + return get_string(nums, 0, n - 1, "max", dp_max_sz, dp_min_sz); + } + +private: + string get_string(const vector& nums, int l, int r, const string& type, + const vector>& dp_max_sz, + const vector>& dp_min_sz){ + + if(l == r) return to_string(nums[l]); + if(l + 1 == r) return to_string(nums[l]) + "/" + to_string(nums[r]); + + if(type == "max"){ + int sz = r - l + 1, sz1 = dp_max_sz[l][r]; + string left_str = get_string(nums, l, l + sz1 - 1, "max", dp_max_sz, dp_min_sz); + string right_str = get_string(nums, l + sz1, l + sz - 1, "min", dp_max_sz, dp_min_sz); + if(l + sz1 == l + sz - 1) return left_str + "/" + right_str; + return left_str + "/(" + right_str + ")"; + } + else{ + assert(type == "min"); + + int sz = r - l + 1, sz1 = dp_min_sz[l][r]; + string left_str = get_string(nums, l, l + sz1 - 1, "min", dp_max_sz, dp_min_sz); + string right_str = get_string(nums, l + sz1, l + sz - 1, "max", dp_max_sz, dp_min_sz); + if(l + sz1 == l + sz - 1) return left_str + "/" + right_str; + return left_str + "/(" + right_str + ")"; + } + } +}; + + +int main() { + + vector nums1 = {1000, 100, 10, 2}; + cout << Solution().optimalDivision(nums1) << endl; + // 1000/(100/10/2) + + vector nums2 = {2, 3, 4}; + cout << Solution().optimalDivision(nums2) << endl; + // 2/(3/4) + + vector nums3 = {2}; + cout << Solution().optimalDivision(nums3) << endl; + // 2 + + return 0; +} diff --git a/0501-1000/0554-Brick-Wall/cpp-0554/CMakeLists.txt b/0501-1000/0554-Brick-Wall/cpp-0554/CMakeLists.txt new file mode 100644 index 00000000..7a6500c2 --- /dev/null +++ b/0501-1000/0554-Brick-Wall/cpp-0554/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_0554) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0554 main.cpp) \ No newline at end of file diff --git a/0501-1000/0554-Brick-Wall/cpp-0554/main.cpp b/0501-1000/0554-Brick-Wall/cpp-0554/main.cpp new file mode 100644 index 00000000..8ad60434 --- /dev/null +++ b/0501-1000/0554-Brick-Wall/cpp-0554/main.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/brick-wall/ +/// Author : liuyubobobo +/// Time : 2021-04-22 + +#include +#include +#include + +using namespace std; + + +/// Using HashMap +/// Time Complexity: O(R * C) +/// Space Complexity: O(R * C) +class Solution { +public: + int leastBricks(vector>& wall) { + + unordered_map map; + for(int i = 0; i < wall.size(); i ++){ + int sum = 0; + for(int j = 0; j < wall[i].size(); j ++){ + sum += wall[i][j]; + if(j != wall[i].size() - 1) + map[sum] ++; + } + } + + int maxf = 0; + for(const pair& p: map) + maxf = max(maxf, p.second); + return wall.size() - maxf; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0556-Next-Greater-Element-III/cpp-0556/CMakeLists.txt b/0501-1000/0556-Next-Greater-Element-III/cpp-0556/CMakeLists.txt new file mode 100644 index 00000000..5547a2ce --- /dev/null +++ b/0501-1000/0556-Next-Greater-Element-III/cpp-0556/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0556) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0556 main.cpp) \ No newline at end of file diff --git a/0501-1000/0556-Next-Greater-Element-III/cpp-0556/main.cpp b/0501-1000/0556-Next-Greater-Element-III/cpp-0556/main.cpp new file mode 100644 index 00000000..d6123598 --- /dev/null +++ b/0501-1000/0556-Next-Greater-Element-III/cpp-0556/main.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/next-greater-element-iii/submissions/ +/// Author : liuyubobobo +/// Time : 2020-12-24 + +#include +#include + +using namespace std; + + +/// next permutation +/// Time Complexity: O(logn) +/// Space Complexity: O(logn) +class Solution { +public: + int nextGreaterElement(int n) { + + vector v; + while(n) v.push_back(n % 10), n /= 10; + reverse(v.begin(), v.end()); + + if(!next_permutation(v.begin(), v.end())) return -1; + + long long x = 0ll; + for(int e: v) x = x * 10 + e; + return x <= INT_MAX ? x : -1; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0557-Reverse-Words-in-a-String-III/cpp-0557/CMakeLists.txt b/0501-1000/0557-Reverse-Words-in-a-String-III/cpp-0557/CMakeLists.txt new file mode 100644 index 00000000..78f42142 --- /dev/null +++ b/0501-1000/0557-Reverse-Words-in-a-String-III/cpp-0557/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0557) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main2.cpp) +add_executable(cpp_0557 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0557-Reverse-Words-in-a-String-III/cpp-0557/main.cpp b/0501-1000/0557-Reverse-Words-in-a-String-III/cpp-0557/main.cpp new file mode 100644 index 00000000..5de2021b --- /dev/null +++ b/0501-1000/0557-Reverse-Words-in-a-String-III/cpp-0557/main.cpp @@ -0,0 +1,44 @@ +/// Source : https://leetcode.com/problems/reverse-words-in-a-string-iii/description/ +/// Author : liuyubobobo +/// Time : 2018-08-12 + +#include +#include + +using namespace std; + +/// split and reverse +/// Time Complexity: O(len(s)) +/// Space Complexity: O(n) +class Solution { +public: + string reverseWords(string s) { + + vector words; + int start = 0; + for(int i = start + 1; i <= s.size(); ) + if(i == s.size() || s[i] == ' '){ + words.push_back(s.substr(start, i - start)); + reverse(words.back().begin(), words.back().end()); + start = i + 1; + i = start + 1; + } + else + i ++; + + if(words.size() == 0) + return ""; + + string res = words[0]; + for(int i = 1; i < words.size() ; i ++) + res += " " + words[i]; + + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0557-Reverse-Words-in-a-String-III/cpp-0557/main2.cpp b/0501-1000/0557-Reverse-Words-in-a-String-III/cpp-0557/main2.cpp new file mode 100644 index 00000000..40997c30 --- /dev/null +++ b/0501-1000/0557-Reverse-Words-in-a-String-III/cpp-0557/main2.cpp @@ -0,0 +1,39 @@ +/// Source : https://leetcode.com/problems/reverse-words-in-a-string-iii/description/ +/// Author : liuyubobobo +/// Time : 2018-08-12 + +#include + +using namespace std; + +/// Reverse in place +/// Time Complexity: O(len(s)) +/// Space Complexity: O(1) +class Solution { +public: + string reverseWords(string s) { + + int start = 0; + for(int i = start + 1; i <= s.size(); ) + if(i == s.size() || s[i] == ' '){ + reverse(s, start, i - 1); + start = i + 1; + i = start + 1; + } + else + i ++; + return s; + } + +private: + void reverse(string& s, int start, int end){ + for(int i = start, j = end; i < j; i ++, j --) + swap(s[i], s[j]); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0558-Logical-OR-of-Two-Binary-Grids-Represented-as-Quad-Trees/cpp-0558/CMakeLists.txt b/0501-1000/0558-Logical-OR-of-Two-Binary-Grids-Represented-as-Quad-Trees/cpp-0558/CMakeLists.txt new file mode 100644 index 00000000..802b7bb9 --- /dev/null +++ b/0501-1000/0558-Logical-OR-of-Two-Binary-Grids-Represented-as-Quad-Trees/cpp-0558/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_0558) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0558 main.cpp) diff --git a/0501-1000/0558-Logical-OR-of-Two-Binary-Grids-Represented-as-Quad-Trees/cpp-0558/main.cpp b/0501-1000/0558-Logical-OR-of-Two-Binary-Grids-Represented-as-Quad-Trees/cpp-0558/main.cpp new file mode 100644 index 00000000..4c5b4b6f --- /dev/null +++ b/0501-1000/0558-Logical-OR-of-Two-Binary-Grids-Represented-as-Quad-Trees/cpp-0558/main.cpp @@ -0,0 +1,94 @@ +/// Source : https://leetcode.com/problems/logical-or-of-two-binary-grids-represented-as-quad-trees/ +/// Author : liuyubobobo +/// Time : 2022-07-14 + +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(h) + +/// Definition for a QuadTree node. +class Node { +public: + bool val; + bool isLeaf; + Node* topLeft; + Node* topRight; + Node* bottomLeft; + Node* bottomRight; + + Node() { + val = false; + isLeaf = false; + topLeft = NULL; + topRight = NULL; + bottomLeft = NULL; + bottomRight = NULL; + } + + Node(bool _val, bool _isLeaf) { + val = _val; + isLeaf = _isLeaf; + topLeft = NULL; + topRight = NULL; + bottomLeft = NULL; + bottomRight = NULL; + } + + Node(bool _val, bool _isLeaf, Node* _topLeft, Node* _topRight, Node* _bottomLeft, Node* _bottomRight) { + val = _val; + isLeaf = _isLeaf; + topLeft = _topLeft; + topRight = _topRight; + bottomLeft = _bottomLeft; + bottomRight = _bottomRight; + } +}; + + +class Solution { +public: + Node* intersect(Node* quadTree1, Node* quadTree2) { + return dfs(quadTree1, quadTree2); + } + +private: + Node* dfs(Node* node1, Node* node2){ + + if(node1->isLeaf && node2->isLeaf){ + return new Node(node1->val | node2->val, true); + } + + Node* ret = new Node(0, false); + ret->topLeft = dfs(node1->topLeft ? node1->topLeft : new Node(node1->val, true), + node2->topLeft ? node2->topLeft : new Node(node2->val, true)); + ret->topRight = dfs(node1->topRight ? node1->topRight : new Node(node1->val, true), + node2->topRight ? node2->topRight : new Node(node2->val, true)); + ret->bottomLeft = dfs(node1->bottomLeft ? node1->bottomLeft : new Node(node1->val, true), + node2->bottomLeft ? node2->bottomLeft : new Node(node2->val, true)); + ret->bottomRight = dfs(node1->bottomRight ? node1->bottomRight : new Node(node1->val, true), + node2->bottomRight ? node2->bottomRight : new Node(node2->val, true)); + + if(ret->topLeft->isLeaf && ret->topRight->isLeaf && ret->bottomLeft->isLeaf && ret->bottomRight->isLeaf && + same(ret->topLeft->val, ret->topRight->val, ret->bottomLeft->val, ret->bottomRight->val)){ + ret->val = ret->topLeft->val; + ret->isLeaf = true; + ret->topLeft = ret->topRight = ret->bottomLeft = ret->bottomRight = nullptr; + } + return ret; + } + + bool same(bool a, bool b, bool c, bool d){ + return a == b && a == c && a == d; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0559-Maximum-Depth-of-N-ary-Tree/cpp-0559/CMakeLists.txt b/0501-1000/0559-Maximum-Depth-of-N-ary-Tree/cpp-0559/CMakeLists.txt new file mode 100644 index 00000000..939f336b --- /dev/null +++ b/0501-1000/0559-Maximum-Depth-of-N-ary-Tree/cpp-0559/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0559) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main3.cpp) +add_executable(cpp_0559 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0559-Maximum-Depth-of-N-ary-Tree/cpp-0559/main.cpp b/0501-1000/0559-Maximum-Depth-of-N-ary-Tree/cpp-0559/main.cpp new file mode 100644 index 00000000..ddb13838 --- /dev/null +++ b/0501-1000/0559-Maximum-Depth-of-N-ary-Tree/cpp-0559/main.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/maximum-depth-of-n-ary-tree/description/ +/// Author : liuyubobobo +/// Time : 2018-10-03 + +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// Definition for a Node. +class Node { +public: + int val; + vector children; + + Node() {} + + Node(int _val, vector _children) { + val = _val; + children = _children; + } +}; + +class Solution { +public: + int maxDepth(Node* root) { + + if(!root) + return 0; + + int res = 1; + for(Node* child: root->children) + res = max(res, 1 + maxDepth(child)); + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0559-Maximum-Depth-of-N-ary-Tree/cpp-0559/main2.cpp b/0501-1000/0559-Maximum-Depth-of-N-ary-Tree/cpp-0559/main2.cpp new file mode 100644 index 00000000..0b76f7de --- /dev/null +++ b/0501-1000/0559-Maximum-Depth-of-N-ary-Tree/cpp-0559/main2.cpp @@ -0,0 +1,59 @@ +/// Source : https://leetcode.com/problems/maximum-depth-of-n-ary-tree/description/ +/// Author : liuyubobobo +/// Time : 2018-10-03 + +#include +#include +#include + +using namespace std; + + +/// Using Stack - Non recursion +/// +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// Definition for a Node. +class Node { +public: + int val; + vector children; + + Node() {} + + Node(int _val, vector _children) { + val = _val; + children = _children; + } +}; + +class Solution { +public: + int maxDepth(Node* root) { + + if(!root) + return 0; + + stack> stack; + stack.push(make_pair(root, 1)); + int res = 1; + while(!stack.empty()){ + Node* cur = stack.top().first; + int depth = stack.top().second; + stack.pop(); + + res = max(res, depth); + + for(Node* node: cur->children) + stack.push(make_pair(node, depth + 1)); + } + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0559-Maximum-Depth-of-N-ary-Tree/cpp-0559/main3.cpp b/0501-1000/0559-Maximum-Depth-of-N-ary-Tree/cpp-0559/main3.cpp new file mode 100644 index 00000000..a27244a9 --- /dev/null +++ b/0501-1000/0559-Maximum-Depth-of-N-ary-Tree/cpp-0559/main3.cpp @@ -0,0 +1,58 @@ +/// Source : https://leetcode.com/problems/maximum-depth-of-n-ary-tree/description/ +/// Author : liuyubobobo +/// Time : 2018-10-03 + +#include +#include +#include + +using namespace std; + + +/// BFS +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// Definition for a Node. +class Node { +public: + int val; + vector children; + + Node() {} + + Node(int _val, vector _children) { + val = _val; + children = _children; + } +}; + +class Solution { +public: + int maxDepth(Node* root) { + + if(!root) + return 0; + + queue> q; + q.push(make_pair(root, 1)); + int res = 1; + while(!q.empty()){ + Node* cur = q.front().first; + int depth = q.front().second; + q.pop(); + + res = max(res, depth); + + for(Node* node: cur->children) + q.push(make_pair(node, depth + 1)); + } + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0560-Subarray-Sum-Equals-K/cpp-0560/CMakeLists.txt b/0501-1000/0560-Subarray-Sum-Equals-K/cpp-0560/CMakeLists.txt new file mode 100644 index 00000000..986141e3 --- /dev/null +++ b/0501-1000/0560-Subarray-Sum-Equals-K/cpp-0560/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_0560) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0560 main2.cpp) \ No newline at end of file diff --git a/0501-1000/0560-Subarray-Sum-Equals-K/cpp-0560/main.cpp b/0501-1000/0560-Subarray-Sum-Equals-K/cpp-0560/main.cpp new file mode 100644 index 00000000..49b05616 --- /dev/null +++ b/0501-1000/0560-Subarray-Sum-Equals-K/cpp-0560/main.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/subarray-sum-equals-k/ +/// Author : liuyubobobo +/// Time : 2021-04-17 + +#include +#include +#include + +using namespace std; + + +/// Presum + HashMap +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int subarraySum(vector& nums, int k) { + + vector presum(nums.size() + 1, 0); + for(int i = 0; i < nums.size(); i ++) + presum[i + 1] = presum[i] + nums[i]; + + unordered_map table; + table[0] ++; + + int res = 0; + for(int i = 0; i < nums.size(); i ++){ + res += table[presum[i + 1] - k]; + table[presum[i + 1]] ++; + } + return res; + } +}; + + +int main() { + +// vector nums1 = {-1, -1, 1}; +// cout << Solution().subarraySum(nums1, 0) << endl; +// // 1 + + vector nums2 = {1, -1, 0}; + cout << Solution().subarraySum(nums2, 0) << endl; + // 3 + + return 0; +} diff --git a/0501-1000/0560-Subarray-Sum-Equals-K/cpp-0560/main2.cpp b/0501-1000/0560-Subarray-Sum-Equals-K/cpp-0560/main2.cpp new file mode 100644 index 00000000..397bb4d2 --- /dev/null +++ b/0501-1000/0560-Subarray-Sum-Equals-K/cpp-0560/main2.cpp @@ -0,0 +1,44 @@ +/// Source : https://leetcode.com/problems/subarray-sum-equals-k/ +/// Author : liuyubobobo +/// Time : 2021-04-17 + +#include +#include +#include + +using namespace std; + + +/// Presum + HashMap +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int subarraySum(vector& nums, int k) { + + unordered_map table; + table[0] ++; + + int sum = 0, res = 0; + for(int i = 0; i < nums.size(); i ++){ + sum += nums[i]; + res += table[sum - k]; + table[sum] ++; + } + return res; + } +}; + + +int main() { + +// vector nums1 = {-1, -1, 1}; +// cout << Solution().subarraySum(nums1, 0) << endl; +// // 1 + + vector nums2 = {1, -1, 0}; + cout << Solution().subarraySum(nums2, 0) << endl; + // 3 + + return 0; +} diff --git a/0501-1000/0561-Array-Partition-I/cpp-0561/CMakeLists.txt b/0501-1000/0561-Array-Partition-I/cpp-0561/CMakeLists.txt new file mode 100644 index 00000000..e70a9df9 --- /dev/null +++ b/0501-1000/0561-Array-Partition-I/cpp-0561/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0561) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main2.cpp) +add_executable(cpp_0561 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0561-Array-Partition-I/cpp-0561/main.cpp b/0501-1000/0561-Array-Partition-I/cpp-0561/main.cpp new file mode 100644 index 00000000..789862b5 --- /dev/null +++ b/0501-1000/0561-Array-Partition-I/cpp-0561/main.cpp @@ -0,0 +1,32 @@ +/// Source : https://leetcode.com/problems/array-partition-i/solution/ +/// Author : liuyubobobo +/// Time : 2018-06-04 + +#include +#include + +using namespace std; + +/// Sort +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + int arrayPairSum(vector& nums) { + + sort(nums.begin(), nums.end()); + int sum = 0; + for(int i = 0 ; i < nums.size() ; i += 2) + sum += nums[i]; + return sum; + } +}; + + +int main() { + + vector nums = {1, 4, 3, 2}; + cout << Solution().arrayPairSum(nums) << endl; + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0561-Array-Partition-I/cpp-0561/main2.cpp b/0501-1000/0561-Array-Partition-I/cpp-0561/main2.cpp new file mode 100644 index 00000000..00784112 --- /dev/null +++ b/0501-1000/0561-Array-Partition-I/cpp-0561/main2.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/array-partition-i/solution/ +/// Author : liuyubobobo +/// Time : 2018-06-04 +/// Updated: 2022-06-15 + +#include +#include + +using namespace std; + + +/// Counting Sort based +/// Time Complexity: O(n + (maxv - minv)) +/// Space Complexity: O(maxv - minv) +class Solution { +public: + int arrayPairSum(vector& nums) { + + int maxv = *max_element(nums.begin(), nums.end()); + int minv = *min_element(nums.begin(), nums.end()); + + vector cnt(maxv - minv + 2, 0); + int offset = -minv; + + for(int num: nums) + cnt[num + offset] ++; + + int sum = 0; + bool minus = false; + for(int i = 0 ; i < cnt.size(); i ++) + if(cnt[i]){ + if(minus){ + cnt[i] --; + minus = false; + } + sum += cnt[i] / 2 * (i - offset); + if(cnt[i] % 2){ + sum += (i - offset); + minus = true; + } + } + return sum; + } +}; + + +int main() { + + vector nums = {1, 4, 3, 2}; + cout << Solution().arrayPairSum(nums) << endl; + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0563-Binary-Tree-Tilt/cpp-0563/CMakeLists.txt b/0501-1000/0563-Binary-Tree-Tilt/cpp-0563/CMakeLists.txt new file mode 100644 index 00000000..b9be05fb --- /dev/null +++ b/0501-1000/0563-Binary-Tree-Tilt/cpp-0563/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(cpp_0563) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0563 main2.cpp) \ No newline at end of file diff --git a/0501-1000/0563-Binary-Tree-Tilt/cpp-0563/main.cpp b/0501-1000/0563-Binary-Tree-Tilt/cpp-0563/main.cpp new file mode 100644 index 00000000..8a7d8041 --- /dev/null +++ b/0501-1000/0563-Binary-Tree-Tilt/cpp-0563/main.cpp @@ -0,0 +1,44 @@ +/// Source : https://leetcode.com/problems/binary-tree-tilt/ +/// Author : liuyubobobo +/// Time : 2019-02-23 + +#include + +using namespace std; + + +/// Recursive Simulation +/// Time Complexity: O(n^2) +/// Space Complexity: O(h) + +/// 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: + int findTilt(TreeNode* root) { + + if(!root) return 0; + return abs(sum(root->left) - sum(root->right)) + findTilt(root->left) + findTilt(root->right); + } + +private: + int sum(TreeNode* root){ + + if(!root) return 0; + return root->val + sum(root->left) + sum(root->right); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0563-Binary-Tree-Tilt/cpp-0563/main2.cpp b/0501-1000/0563-Binary-Tree-Tilt/cpp-0563/main2.cpp new file mode 100644 index 00000000..f47e9975 --- /dev/null +++ b/0501-1000/0563-Binary-Tree-Tilt/cpp-0563/main2.cpp @@ -0,0 +1,51 @@ +/// Source : https://leetcode.com/problems/binary-tree-tilt/ +/// Author : liuyubobobo +/// Time : 2019-02-23 + +#include + +using namespace std; + + +/// Recursive and use class variable to record the result +/// Time Complexity: O(n) +/// Space Complexity: O(h) + +/// 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 { + +private: + int result; + +public: + int findTilt(TreeNode* root) { + + result = 0; + dfs(root); + return result; + } + +private: + int dfs(TreeNode* root){ + + if(!root) return 0; + int left = dfs(root->left); + int right = dfs(root->right); + result += abs(left - right); + return root->val + left + right; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0564-Find-the-Closest-Palindrome/cpp-0564/CMakeLists.txt b/0501-1000/0564-Find-the-Closest-Palindrome/cpp-0564/CMakeLists.txt new file mode 100644 index 00000000..c229437c --- /dev/null +++ b/0501-1000/0564-Find-the-Closest-Palindrome/cpp-0564/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_0564) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0564 main.cpp) diff --git a/0501-1000/0564-Find-the-Closest-Palindrome/cpp-0564/main.cpp b/0501-1000/0564-Find-the-Closest-Palindrome/cpp-0564/main.cpp new file mode 100644 index 00000000..2fbb9938 --- /dev/null +++ b/0501-1000/0564-Find-the-Closest-Palindrome/cpp-0564/main.cpp @@ -0,0 +1,97 @@ +/// Source : https://leetcode.com/problems/find-the-closest-palindrome/ +/// Author : liuyubobobo +/// Time : 2022-03-03 + +#include +#include +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(|n|) +/// Space Complexity: O(|n|) +class Solution { +public: + string nearestPalindromic(string n) { + + long long num = atoll(n.c_str()); + + vector possible_res; + get_palindrome_number(n, possible_res); + get_palindrome_number(to_string(num + 2), possible_res); + if(num - 2 >= 0) + get_palindrome_number(to_string(num - 2), possible_res); + + int len = n.size(); + if(len % 2){ + int m = len / 2; + get_num(num, m, '+', possible_res); + get_num(num, m, '-', possible_res); + } + else{ + int m1 = len / 2 - 1, m2 = len / 2; + get_num(num, m1, '+', possible_res); + get_num(num, m1, '-', possible_res); + get_num(num, m2, '+', possible_res); + get_num(num, m2, '-', possible_res); + } + + long long res = -1, best_diff = LONG_LONG_MAX; + for(long long a: possible_res){ + if(a == num) continue; + long long diff = abs(a - num); + if(diff < best_diff) res = a, best_diff = diff; + else if(diff == best_diff) res = min(res, a); + } + assert(res != -1); + return to_string(res); + } + +private: + void get_num(long long num, int pos, char type, + vector& possible_res){ + + if(type == '+') + num += (long long)pow(10, pos); + else{ + num -= (long long)pow(10, pos); + assert(num >= 0); + } + + get_palindrome_number(to_string(num), possible_res); + } + + void get_palindrome_number(const string& n, vector& possible_res){ + + string n1 = n; + for(int i = 0, j = n1.size() - 1; i < j; i ++, j --) + n1[i] = n1[j]; + possible_res.push_back(atoll(n1.c_str())); + + string n2 = n; + for(int i = 0, j = n1.size() - 1; i < j; i ++, j --) + n2[j] = n2[i]; + possible_res.push_back(atoll(n2.c_str())); + } +}; + + +int main() { + + cout << Solution().nearestPalindromic("123") << '\n'; + // 121 + + cout << Solution().nearestPalindromic("1") << '\n'; + // 0 + + cout << Solution().nearestPalindromic("9") << '\n'; + // 8 + + cout << Solution().nearestPalindromic("11") << '\n'; + // 9 + + return 0; +} diff --git a/0501-1000/0565-Array-Nesting/cpp-0565/CMakeLists.txt b/0501-1000/0565-Array-Nesting/cpp-0565/CMakeLists.txt new file mode 100644 index 00000000..d7389237 --- /dev/null +++ b/0501-1000/0565-Array-Nesting/cpp-0565/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0565) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0565 main.cpp) diff --git a/0501-1000/0565-Array-Nesting/cpp-0565/main.cpp b/0501-1000/0565-Array-Nesting/cpp-0565/main.cpp new file mode 100644 index 00000000..761b0d7b --- /dev/null +++ b/0501-1000/0565-Array-Nesting/cpp-0565/main.cpp @@ -0,0 +1,39 @@ +/// Source : https://leetcode.com/problems/array-nesting/ +/// Author : liuyubobobo +/// Time : 2021-09-01 + +#include +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int arrayNesting(vector& nums) { + + int n = nums.size(); + vector visited(n, false); + int res = 0; + for(int i = 0; i < n; i ++) + if(!visited[i]){ + int cur = nums[i], len = 1; + visited[i] = true; + while(cur != i){ + cur = nums[cur], len ++; + visited[cur] = true; + } + res = max(res, len); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0566-Reshape-the-Matrix/cpp-0566/CMakeLists.txt b/0501-1000/0566-Reshape-the-Matrix/cpp-0566/CMakeLists.txt new file mode 100644 index 00000000..22c25db8 --- /dev/null +++ b/0501-1000/0566-Reshape-the-Matrix/cpp-0566/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0566) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0566 main.cpp) \ No newline at end of file diff --git a/0501-1000/0566-Reshape-the-Matrix/cpp-0566/main.cpp b/0501-1000/0566-Reshape-the-Matrix/cpp-0566/main.cpp new file mode 100644 index 00000000..3b04a35e --- /dev/null +++ b/0501-1000/0566-Reshape-the-Matrix/cpp-0566/main.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/reshape-the-matrix/ +/// Author : liuyubobobo +/// Time : 2021-02-16 + +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(R * C) +/// Space Complexity: O(1) +class Solution { +public: + vector> matrixReshape(vector>& nums, int r, int c) { + + int oR = nums.size(), oC = nums[0].size(); + if(r * c != oR * oC) return nums; + + vector> res(r, vector(c)); + for(int i = 0; i < oR; i ++) + for(int j = 0; j < oC; j ++) + res[(i * oC + j) / c][(i * oC + j) % c] = nums[i][j]; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0567-Permutation-in-String/cpp-0567/CMakeLists.txt b/0501-1000/0567-Permutation-in-String/cpp-0567/CMakeLists.txt new file mode 100644 index 00000000..a12cea82 --- /dev/null +++ b/0501-1000/0567-Permutation-in-String/cpp-0567/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(cpp_0567) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0567 main.cpp) \ No newline at end of file diff --git a/0501-1000/0567-Permutation-in-String/cpp-0567/main.cpp b/0501-1000/0567-Permutation-in-String/cpp-0567/main.cpp new file mode 100644 index 00000000..8ead10f9 --- /dev/null +++ b/0501-1000/0567-Permutation-in-String/cpp-0567/main.cpp @@ -0,0 +1,42 @@ +/// Source : https://leetcode.com/problems/permutation-in-string/ +/// Author : liuyubobobo +/// Time : 2020-05-21 + +#include +#include + +using namespace std; + + +/// Sliding Windows +/// Time Complexity: O(|s1| + |s2|) +/// Space Complexity: O(1) +class Solution { +public: + bool checkInclusion(string s1, string s2) { + + if(s1.size() > s2.size()) return false; + + vector f1(26, 0), f2(26, 0); + for(char c: s1) f1[c - 'a'] ++; + + int k = s1.size(); + for(int i = 0; i < k - 1; i ++) f2[s2[i] - 'a'] ++; + + for(int i = k - 1; i < s2.size(); i ++){ + f2[s2[i] - 'a'] ++; + if(f1 == f2) return true; + f2[s2[i - (k - 1)] - 'a'] --; + } + return false; + } +}; + + +int main() { + + cout << Solution().checkInclusion("ab", "eidbaooo") << endl; + // 1 + + return 0; +} diff --git a/0501-1000/0572-Subtree-of-Another-Tree/cpp-0572/CMakeLists.txt b/0501-1000/0572-Subtree-of-Another-Tree/cpp-0572/CMakeLists.txt new file mode 100644 index 00000000..904c5467 --- /dev/null +++ b/0501-1000/0572-Subtree-of-Another-Tree/cpp-0572/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0572) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0572 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0572-Subtree-of-Another-Tree/cpp-0572/main.cpp b/0501-1000/0572-Subtree-of-Another-Tree/cpp-0572/main.cpp new file mode 100644 index 00000000..cec11c8b --- /dev/null +++ b/0501-1000/0572-Subtree-of-Another-Tree/cpp-0572/main.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/subtree-of-another-tree/description/ +/// Author : liuyubobobo +/// Time : 2018-10-16 + +#include + +using namespace std; + + +/// Using String to represent a binary tree +/// Time Complexity: O(m + n + m * n) +/// Space Complexity: O(m + n) + +/// 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: + bool isSubtree(TreeNode* s, TreeNode* t) { + + string ss = "#"; + getTreeString(s, ss); + + string tt = "#"; + getTreeString(t, tt); + + return ss.find(tt) != string::npos; + } + +private: + void getTreeString(TreeNode* node, string& s){ + + if(!node){ + s += "NULL#"; + return; + } + + s += to_string(node->val) + "#"; + getTreeString(node->left, s); + getTreeString(node->right, s); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0572-Subtree-of-Another-Tree/cpp-0572/main2.cpp b/0501-1000/0572-Subtree-of-Another-Tree/cpp-0572/main2.cpp new file mode 100644 index 00000000..6f2f818e --- /dev/null +++ b/0501-1000/0572-Subtree-of-Another-Tree/cpp-0572/main2.cpp @@ -0,0 +1,55 @@ +/// Source : https://leetcode.com/problems/subtree-of-another-tree/description/ +/// Author : liuyubobobo +/// Time : 2018-10-16 + +#include + +using namespace std; + + +/// Recursion +/// Time Complexity: O(m * n) +/// Space Complexity: O(logm) + +/// 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: + bool isSubtree(TreeNode* s, TreeNode* t) { + + if(!s && !t) + return true; + + if(equal(s, t)) + return true; + + if(s && isSubtree(s->left, t)) + return true; + + if(s && isSubtree(s->right, t)) + return true; + + return false; + } + +private: + bool equal(TreeNode* a, TreeNode* b){ + + if(!a && !b) return true; + if(!a || !b) return false; + if(a->val != b->val) return false; + return equal(a->left, b->left) && equal(a->right, b->right); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0573-Squirrel-Simulation/cpp-0573/CMakeLists.txt b/0501-1000/0573-Squirrel-Simulation/cpp-0573/CMakeLists.txt new file mode 100644 index 00000000..fc785299 --- /dev/null +++ b/0501-1000/0573-Squirrel-Simulation/cpp-0573/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0573) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0573 main.cpp) \ No newline at end of file diff --git a/0501-1000/0573-Squirrel-Simulation/cpp-0573/main.cpp b/0501-1000/0573-Squirrel-Simulation/cpp-0573/main.cpp new file mode 100644 index 00000000..7a7c8b9a --- /dev/null +++ b/0501-1000/0573-Squirrel-Simulation/cpp-0573/main.cpp @@ -0,0 +1,38 @@ +/// Source : https://leetcode.com/problems/squirrel-simulation/ +/// Author : liuyubobobo +/// Time : 2021-02-01 + +#include +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int minDistance(int height, int width, vector& tree, vector& squirrel, vector>& nuts) { + + vector treeToNuts, squToNuts; + for(const vector& nut: nuts) { + treeToNuts.push_back(abs(nut[0] - tree[0]) + abs(nut[1] - tree[1])); + squToNuts.push_back(abs(nut[0] - squirrel[0]) + abs(nut[1] - squirrel[1])); + } + + int total = accumulate(treeToNuts.begin(), treeToNuts.end(), 0); + int res = INT_MAX; + for(int i = 0; i < nuts.size(); i ++){ + res = min(res, squToNuts[i] + treeToNuts[i] + total * 2 - 2 * treeToNuts[i]); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0575-Distribute-Candies/cpp-0575/CMakeLists.txt b/0501-1000/0575-Distribute-Candies/cpp-0575/CMakeLists.txt new file mode 100644 index 00000000..22d326f3 --- /dev/null +++ b/0501-1000/0575-Distribute-Candies/cpp-0575/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0575) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0575 main.cpp) \ No newline at end of file diff --git a/0501-1000/0575-Distribute-Candies/cpp-0575/main.cpp b/0501-1000/0575-Distribute-Candies/cpp-0575/main.cpp new file mode 100644 index 00000000..6dc74b47 --- /dev/null +++ b/0501-1000/0575-Distribute-Candies/cpp-0575/main.cpp @@ -0,0 +1,30 @@ +/// Source : https://leetcode.com/problems/distribute-candies/ +/// Author : liuyubobobo +/// Time : 2021-03-01 + +#include +#include +#include + +using namespace std; + + +/// Using HashMap +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int distributeCandies(vector& candyType) { + + unordered_map f; + for(int e: candyType) f[e] ++; + + return min(candyType.size() / 2, f.size()); + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0576-Out-of-Boundary-Paths/cpp-0576/CMakeLists.txt b/0501-1000/0576-Out-of-Boundary-Paths/cpp-0576/CMakeLists.txt new file mode 100644 index 00000000..afa1cbc0 --- /dev/null +++ b/0501-1000/0576-Out-of-Boundary-Paths/cpp-0576/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_0576) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0576 main.cpp) \ No newline at end of file diff --git a/0501-1000/0576-Out-of-Boundary-Paths/cpp-0576/main.cpp b/0501-1000/0576-Out-of-Boundary-Paths/cpp-0576/main.cpp new file mode 100644 index 00000000..e4f7c08a --- /dev/null +++ b/0501-1000/0576-Out-of-Boundary-Paths/cpp-0576/main.cpp @@ -0,0 +1,51 @@ +/// Source : https://leetcode.com/problems/out-of-boundary-paths/ +/// Author : liuyubobobo +/// Time : 2021-06-24 + +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(m * n * k) +/// Space Complexity: O(m * n * k) +class Solution { + +private: + const int dirs[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; + const int MOD = 1e9 + 7; + int R, C; + +public: + int findPaths(int m, int n, int maxMove, int startRow, int startColumn) { + + R = m, C = n; + vector>> dp(m, vector>(n, vector(maxMove + 1, -1))); + return dfs(dp, startRow, startColumn, maxMove); + } + +private: + int dfs(vector>>& dp, int x, int y, int k){ + + if(x < 0 || x >= R || y < 0 || y >= C) + return 1; + + if(k == 0) return 0; + + assert(x >= 0 && x < R && y >= 0 && y < C); + if(dp[x][y][k] != -1) return dp[x][y][k]; + + int res = 0; + for(int d = 0; d < 4; d ++) + res = (res + dfs(dp, x + dirs[d][0], y + dirs[d][1], k - 1)) % MOD; + return dp[x][y][k] = res; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0581-Shortest-Unsorted-Continuous-Subarray/cpp-0581/CMakeLists.txt b/0501-1000/0581-Shortest-Unsorted-Continuous-Subarray/cpp-0581/CMakeLists.txt new file mode 100644 index 00000000..d2662844 --- /dev/null +++ b/0501-1000/0581-Shortest-Unsorted-Continuous-Subarray/cpp-0581/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0581) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0581 main.cpp) \ No newline at end of file diff --git a/0501-1000/0581-Shortest-Unsorted-Continuous-Subarray/cpp-0581/main.cpp b/0501-1000/0581-Shortest-Unsorted-Continuous-Subarray/cpp-0581/main.cpp new file mode 100644 index 00000000..2d9fd07f --- /dev/null +++ b/0501-1000/0581-Shortest-Unsorted-Continuous-Subarray/cpp-0581/main.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/shortest-unsorted-continuous-subarray/ +/// Author : liuyubobobo +/// Time : 2021-02-25 + +#include +#include + +using namespace std; + + +/// Sorting and Two Pointers +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + int findUnsortedSubarray(vector& nums) { + + vector a = nums; + sort(a.begin(), a.end()); + + int l = 0; + while(l < nums.size() && nums[l] == a[l]) l ++; + + int r = nums.size() - 1; + while(r >= 0 && nums[r] == a[r]) r --; + + if(r < l) return 0; + return r - l + 1; + } +}; + + +int main() { + + vector nums1 = {2, 6, 4, 8, 10, 9, 15}; + cout << Solution().findUnsortedSubarray(nums1) << endl; + // 5 + + return 0; +} diff --git a/0501-1000/0582-Kill-Process/cpp-0582/CMakeLists.txt b/0501-1000/0582-Kill-Process/cpp-0582/CMakeLists.txt new file mode 100644 index 00000000..3d4ba872 --- /dev/null +++ b/0501-1000/0582-Kill-Process/cpp-0582/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0582) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0582 main.cpp) \ No newline at end of file diff --git a/0501-1000/0582-Kill-Process/cpp-0582/main.cpp b/0501-1000/0582-Kill-Process/cpp-0582/main.cpp new file mode 100644 index 00000000..b0f401b2 --- /dev/null +++ b/0501-1000/0582-Kill-Process/cpp-0582/main.cpp @@ -0,0 +1,51 @@ +/// Source : https://leetcode.com/problems/kill-process/ +/// Author : liuyubobobo +/// Time : 2021-02-15 + +#include +#include +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(h) +class Solution { + +public: + vector killProcess(vector& pid, vector& ppid, int kill) { + + unordered_map> tree; + for(int i = 0; i < pid.size(); i ++) + if(ppid[i] != 0) tree[ppid[i]].insert(pid[i]); + + vector res; + dfs(tree, kill, res); + return res; + } + +private: + void dfs(const unordered_map>& tree, int u, vector& res){ + + res.push_back(u); + if(tree.count(u)) + for(int v: tree.at(u)) + dfs(tree, v, res); + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << " "; cout << endl; +} + +int main() { + + vector pid = {1, 3, 10, 5}, ppid = {3, 0, 5, 3}; + print_vec(Solution().killProcess(pid, ppid, 5)); + + return 0; +} diff --git a/0583-Delete-Operation-for-Two-Strings/cpp-0583/CMakeLists.txt b/0501-1000/0583-Delete-Operation-for-Two-Strings/cpp-0583/CMakeLists.txt similarity index 100% rename from 0583-Delete-Operation-for-Two-Strings/cpp-0583/CMakeLists.txt rename to 0501-1000/0583-Delete-Operation-for-Two-Strings/cpp-0583/CMakeLists.txt diff --git a/0583-Delete-Operation-for-Two-Strings/cpp-0583/main.cpp b/0501-1000/0583-Delete-Operation-for-Two-Strings/cpp-0583/main.cpp similarity index 100% rename from 0583-Delete-Operation-for-Two-Strings/cpp-0583/main.cpp rename to 0501-1000/0583-Delete-Operation-for-Two-Strings/cpp-0583/main.cpp diff --git a/0583-Delete-Operation-for-Two-Strings/cpp-0583/main2.cpp b/0501-1000/0583-Delete-Operation-for-Two-Strings/cpp-0583/main2.cpp similarity index 100% rename from 0583-Delete-Operation-for-Two-Strings/cpp-0583/main2.cpp rename to 0501-1000/0583-Delete-Operation-for-Two-Strings/cpp-0583/main2.cpp diff --git a/0583-Delete-Operation-for-Two-Strings/cpp-0583/main3.cpp b/0501-1000/0583-Delete-Operation-for-Two-Strings/cpp-0583/main3.cpp similarity index 100% rename from 0583-Delete-Operation-for-Two-Strings/cpp-0583/main3.cpp rename to 0501-1000/0583-Delete-Operation-for-Two-Strings/cpp-0583/main3.cpp diff --git a/0583-Delete-Operation-for-Two-Strings/cpp-0583/main4.cpp b/0501-1000/0583-Delete-Operation-for-Two-Strings/cpp-0583/main4.cpp similarity index 100% rename from 0583-Delete-Operation-for-Two-Strings/cpp-0583/main4.cpp rename to 0501-1000/0583-Delete-Operation-for-Two-Strings/cpp-0583/main4.cpp diff --git a/0583-Delete-Operation-for-Two-Strings/cpp-0583/main5.cpp b/0501-1000/0583-Delete-Operation-for-Two-Strings/cpp-0583/main5.cpp similarity index 100% rename from 0583-Delete-Operation-for-Two-Strings/cpp-0583/main5.cpp rename to 0501-1000/0583-Delete-Operation-for-Two-Strings/cpp-0583/main5.cpp diff --git a/0583-Delete-Operation-for-Two-Strings/cpp-0583/main6.cpp b/0501-1000/0583-Delete-Operation-for-Two-Strings/cpp-0583/main6.cpp similarity index 100% rename from 0583-Delete-Operation-for-Two-Strings/cpp-0583/main6.cpp rename to 0501-1000/0583-Delete-Operation-for-Two-Strings/cpp-0583/main6.cpp diff --git a/0501-1000/0587-Erect-the-Fence/cpp-0587/CMakeLists.txt b/0501-1000/0587-Erect-the-Fence/cpp-0587/CMakeLists.txt new file mode 100644 index 00000000..edf32f40 --- /dev/null +++ b/0501-1000/0587-Erect-the-Fence/cpp-0587/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(cpp_0587) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0587 main3.cpp) \ No newline at end of file diff --git a/0501-1000/0587-Erect-the-Fence/cpp-0587/main.cpp b/0501-1000/0587-Erect-the-Fence/cpp-0587/main.cpp new file mode 100644 index 00000000..7ab9a7f5 --- /dev/null +++ b/0501-1000/0587-Erect-the-Fence/cpp-0587/main.cpp @@ -0,0 +1,80 @@ +/// Source : https://leetcode.com/problems/erect-the-fence/ +/// Author : liuyubobobo +/// Time : 2020-05-01 + +#include +#include + +using namespace std; + + +/// Graham Scan - One Pass +/// Time Complexity: O(nlogn + n) +/// Space Complexity: O(1) + +vector start; + +int cross_value(const vector& p1, const vector& p2, const vector& p3){ + int a = p2[0] - p1[0], b = p2[1] - p1[1]; + int c = p3[0] - p2[0], d = p3[1] - p2[1]; + return a * d - b * c; +} + +int distance_square(const vector& p1, const vector& p2){ + return (p1[0] - p2[0]) * (p1[0] - p2[0]) + (p1[1] - p2[1]) * (p1[1] - p2[1]); +} + +bool cmp(const vector& p1, const vector& p2){ + int det = cross_value(start, p1, p2); + if(det == 0) return distance_square(start, p1) < distance_square(start, p2); + return det > 0; +} + +class Solution { +public: + vector> outerTrees(vector>& points) { + + if(points.size() <= 3) return points; + + int leftmost = 0; + for(int i = 1; i < points.size(); i ++) + if(points[i][0] < points[leftmost][0] || + (points[i][0] == points[leftmost][0] && points[i][1] < points[leftmost][1])) + leftmost = i; + swap(points[0], points[leftmost]); + start = points[0]; + + sort(points.begin() + 1, points.end(), cmp); + +// for(const vector& p: points) +// cout << "(" << p[0] << "," << p[1] << ") "; cout << endl; + + for(int i = points.size() - 2; i >= 0; i --) + if(cross_value(points[0], points.back(), points[i]) != 0){ + for(int l = i + 1, r = points.size() - 1; l < r; l ++, r --) + swap(points[l], points[r]); + break; + } + + vector> res = {points[0], points[1]}; + for(int i = 2; i < points.size(); i ++){ + while(res.size() >= 2 && cross_value(res[res.size() - 2], res.back(), points[i]) < 0) + res.pop_back(); + res.push_back(points[i]); + } + return res; + } +}; + + +void print_vec(const vector>& vec){ + for(const vector& p: vec) cout << "(" << p[0] << "," << p[1] << ")"; cout << endl; +} + +int main() { + + vector> points = {{1,1},{2,2},{2,0},{2,4},{3,3},{4,2}}; + print_vec(Solution().outerTrees(points)); + + return 0; +} diff --git a/0501-1000/0587-Erect-the-Fence/cpp-0587/main2.cpp b/0501-1000/0587-Erect-the-Fence/cpp-0587/main2.cpp new file mode 100644 index 00000000..780a5240 --- /dev/null +++ b/0501-1000/0587-Erect-the-Fence/cpp-0587/main2.cpp @@ -0,0 +1,79 @@ +/// Source : https://leetcode.com/problems/erect-the-fence/ +/// Author : liuyubobobo +/// Time : 2020-05-01 + +#include +#include + +using namespace std; + + +/// Graham Scan - One Pass +/// Using (0, 0) as the base to avoid free functions +/// Time Complexity: O(nlogn + n) +/// Space Complexity: O(1) +class Solution { +public: + vector> outerTrees(vector>& points) { + + if(points.size() <= 3) return points; + + int leftmost = 0; + for(int i = 1; i < points.size(); i ++) + if(points[i][0] < points[leftmost][0] || + (points[i][0] == points[leftmost][0] && points[i][1] < points[leftmost][1])) + leftmost = i; + swap(points[0], points[leftmost]); + + vector start = points[0]; + for(vector& p: points) p[0] -= start[0], p[1] -= start[1]; + + sort(points.begin() + 1, points.end(), + [](const vector& p1, const vector& p2){ + + int det = p1[0] * (p2[1] - p1[1]) - (p2[0] - p1[0]) * p1[1]; + if(det == 0) return p1[0] * p1[0] + p1[1] * p1[1] < p2[0] * p2[0] + p2[1] * p2[1]; + return det > 0; + }); + +// for(const vector& p: points) +// cout << "(" << p[0] + start[0] << "," << p[1] + start[1] << ") "; cout << endl; + + for(int i = points.size() - 2; i >= 0; i --) + if(cross_value(points[0], points.back(), points[i]) != 0){ + for(int l = i + 1, r = points.size() - 1; l < r; l ++, r --) + swap(points[l], points[r]); + break; + } + + vector> res = {points[0], points[1]}; + for(int i = 2; i < points.size(); i ++){ + while(res.size() >= 2 && cross_value(res[res.size() - 2], res.back(), points[i]) < 0) + res.pop_back(); + res.push_back(points[i]); + } + for(vector& p: res) p[0] += start[0], p[1] += start[1]; + + return res; + } + +private: + int cross_value(const vector& p1, const vector& p2, const vector& p3){ +// int a = p2[0] - p1[0], b = p2[1] - p1[1]; +// int c = p3[0] - p2[0], d = p3[1] - p2[1]; + return (p2[0] - p1[0]) * (p3[1] - p2[1]) - (p2[1] - p1[1]) * (p3[0] - p2[0]); + } +}; + + +void print_vec(const vector>& vec){ + for(const vector& p: vec) cout << "(" << p[0] << "," << p[1] << ")"; cout << endl; +} + +int main() { + + vector> points = {{1,1},{2,2},{2,0},{2,4},{3,3},{4,2}}; + print_vec(Solution().outerTrees(points)); + + return 0; +} diff --git a/0501-1000/0587-Erect-the-Fence/cpp-0587/main3.cpp b/0501-1000/0587-Erect-the-Fence/cpp-0587/main3.cpp new file mode 100644 index 00000000..a81d0f53 --- /dev/null +++ b/0501-1000/0587-Erect-the-Fence/cpp-0587/main3.cpp @@ -0,0 +1,87 @@ +/// Source : https://leetcode.com/problems/erect-the-fence/ +/// Author : liuyubobobo +/// Time : 2022-04-22 + +#include +#include + +using namespace std; + + +/// Graham Scan +/// Using my template +/// Time Complexity: O(nlogn + n) +/// Space Complexity: O(1) +template +class ConvexHull { +public: + vector> solve(vector>& points) { + + if(points.size() <= 3) return points; + + int leftmost = 0; + for(int i = 1; i < points.size(); i ++){ + if(points[i][0] < points[leftmost][0] || + (points[i][0] == points[leftmost][0] && points[i][1] < points[leftmost][1])) + leftmost = i; + } + + swap(points[0], points[leftmost]); + + vector start = points[0]; + for(vector& p: points) p[0] -= start[0], p[1] -= start[1]; + + sort(points.begin() + 1, points.end(), [](const vector& p1, const vector& p2){ + T det = p1[0] * (p2[1] - p1[1]) - (p2[0] - p1[0]) * p1[1]; + if(det == 0) return p1[0] * p1[0] + p1[1] * p1[1] < p2[0] * p2[0] + p2[1] * p2[1]; + return det > 0; + }); + + for(int i = points.size() - 2; i >= 0; i --) + if(cross_value(points[0], points.back(), points[i]) != 0){ + for(int l = i + 1, r = points.size() - 1; l < r; l ++, r --) + swap(points[l], points[r]); + break; + } + + vector> res = {points[0], points[1]}; + for(int i = 2; i < points.size(); i ++){ + while(res.size() >= 2 && cross_value(res[res.size() - 2], res.back(), points[i]) < 0) + res.pop_back(); + res.push_back(points[i]); + } + + for(vector& p: res) p[0] += start[0], p[1] += start[1]; + + return res; + } + +private: + T cross_value(const vector& p1, const vector& p2, const vector& p3){ + // int a = p2[0] - p1[0], b = p2[1] - p1[1]; + // int c = p3[0] - p2[0], d = p3[1] - p2[1]; + return (p2[0] - p1[0]) * (p3[1] - p2[1]) - (p2[1] - p1[1]) * (p3[0] - p2[0]); + } +}; + +class Solution { +public: + vector> outerTrees(vector>& points) { + + ConvexHull solver; + return solver.solve(points); + } +}; + + +void print_vec(const vector>& vec){ + for(const vector& p: vec) cout << "(" << p[0] << "," << p[1] << ")"; cout << endl; +} + +int main() { + + vector> points = {{1,1},{2,2},{2,0},{2,4},{3,3},{4,2}}; + print_vec(Solution().outerTrees(points)); + + return 0; +} diff --git a/0501-1000/0589-N-ary-Tree-Preorder-Traversal/cpp-0589/CMakeLists.txt b/0501-1000/0589-N-ary-Tree-Preorder-Traversal/cpp-0589/CMakeLists.txt new file mode 100644 index 00000000..253d4dac --- /dev/null +++ b/0501-1000/0589-N-ary-Tree-Preorder-Traversal/cpp-0589/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0589) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main2.cpp) +add_executable(cpp_0589 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0589-N-ary-Tree-Preorder-Traversal/cpp-0589/main.cpp b/0501-1000/0589-N-ary-Tree-Preorder-Traversal/cpp-0589/main.cpp new file mode 100644 index 00000000..1db82c3e --- /dev/null +++ b/0501-1000/0589-N-ary-Tree-Preorder-Traversal/cpp-0589/main.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/n-ary-tree-preorder-traversal/ +/// Author : liuyubobobo +/// Time : 2018-10-29 + +#include +#include + +using namespace std; + + +/// Definition for a Node. +class Node { +public: + int val; + vector children; + + Node() {} + + Node(int _val, vector _children) { + val = _val; + children = _children; + } +}; + + +/// Recursion +/// Time Complexity: O(n) +/// Space Complexity: O(h) +class Solution { +public: + vector preorder(Node* root) { + + vector res; + dfs(root, res); + return res; + } + +private: + void dfs(Node* node, vector& res){ + + if(!node) + return; + + res.push_back(node->val); + for(Node* next: node->children) + dfs(next, res); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0589-N-ary-Tree-Preorder-Traversal/cpp-0589/main2.cpp b/0501-1000/0589-N-ary-Tree-Preorder-Traversal/cpp-0589/main2.cpp new file mode 100644 index 00000000..cfca3596 --- /dev/null +++ b/0501-1000/0589-N-ary-Tree-Preorder-Traversal/cpp-0589/main2.cpp @@ -0,0 +1,58 @@ +/// Source : https://leetcode.com/problems/n-ary-tree-preorder-traversal/ +/// Author : liuyubobobo +/// Time : 2018-10-29 + +#include +#include +#include + +using namespace std; + + +/// Definition for a Node. +class Node { +public: + int val; + vector children; + + Node() {} + + Node(int _val, vector _children) { + val = _val; + children = _children; + } +}; + + +/// Non-Recursion +/// Using stack +/// Time Complexity: O(n) +/// Space Complexity: O(h) +class Solution { +public: + vector preorder(Node* root) { + + vector res; + if(!root) + return res; + + stack stack; + stack.push(root); + while(!stack.empty()){ + Node* cur = stack.top(); + stack.pop(); + + res.push_back(cur->val); + for(vector::reverse_iterator iter = cur->children.rbegin(); + iter != cur->children.rend(); iter ++) + stack.push(*iter); + } + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0590-N-ary-Tree-Postorder-Transversal/cpp-0590/CMakeLists.txt b/0501-1000/0590-N-ary-Tree-Postorder-Transversal/cpp-0590/CMakeLists.txt new file mode 100644 index 00000000..4b7e8183 --- /dev/null +++ b/0501-1000/0590-N-ary-Tree-Postorder-Transversal/cpp-0590/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0590) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main2.cpp) +add_executable(cpp_0590 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0590-N-ary-Tree-Postorder-Transversal/cpp-0590/main.cpp b/0501-1000/0590-N-ary-Tree-Postorder-Transversal/cpp-0590/main.cpp new file mode 100644 index 00000000..c7432d9e --- /dev/null +++ b/0501-1000/0590-N-ary-Tree-Postorder-Transversal/cpp-0590/main.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/n-ary-tree-postorder-traversal/ +/// Author : liuyubobobo +/// Time : 2018-10-29 + +#include +#include + +using namespace std; + + +/// Definition for a Node. +class Node { +public: + int val; + vector children; + + Node() {} + + Node(int _val, vector _children) { + val = _val; + children = _children; + } +}; + +/// Recursion +/// Time Complexity: O(n) +/// Space Complexity: O(h) +class Solution { +public: + vector postorder(Node* root) { + + vector res; + dfs(root, res); + return res; + } + +private: + void dfs(Node* node, vector& res){ + + if(!node) + return; + + for(Node* next: node->children) + dfs(next, res); + res.push_back(node->val); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0590-N-ary-Tree-Postorder-Transversal/cpp-0590/main2.cpp b/0501-1000/0590-N-ary-Tree-Postorder-Transversal/cpp-0590/main2.cpp new file mode 100644 index 00000000..e1712322 --- /dev/null +++ b/0501-1000/0590-N-ary-Tree-Postorder-Transversal/cpp-0590/main2.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/n-ary-tree-postorder-traversal/ +/// Author : liuyubobobo +/// Time : 2018-10-29 + +#include +#include +#include + +using namespace std; + + +/// Definition for a Node. +class Node { +public: + int val; + vector children; + + Node() {} + + Node(int _val, vector _children) { + val = _val; + children = _children; + } +}; + +/// Non-Recursion +/// Using stack +/// +/// Time Complexity: O(n) +/// Space Complexity: O(h) +class Solution { +public: + vector postorder(Node* root) { + + vector res; + if(!root) + return res; + + stack stack; + stack.push(root); + while(!stack.empty()){ + Node* cur = stack.top(); + stack.pop(); + res.push_back(cur->val); + for(Node* next: cur->children) + stack.push(next); + } + reverse(res.begin(), res.end()); + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0591-Tag-Validator/cpp-0591/CMakeLists.txt b/0501-1000/0591-Tag-Validator/cpp-0591/CMakeLists.txt new file mode 100644 index 00000000..1028ffaf --- /dev/null +++ b/0501-1000/0591-Tag-Validator/cpp-0591/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_0591) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0591 main.cpp) diff --git a/0501-1000/0591-Tag-Validator/cpp-0591/main.cpp b/0501-1000/0591-Tag-Validator/cpp-0591/main.cpp new file mode 100644 index 00000000..f7eb4775 --- /dev/null +++ b/0501-1000/0591-Tag-Validator/cpp-0591/main.cpp @@ -0,0 +1,106 @@ +/// Source : https://leetcode.com/problems/tag-validator/ +/// Author : liuyubobobo +/// Time : 2022-05-03 + +#include +#include + +using namespace std; + + +/// Using Stack +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + bool isValid(string code) { + + vector tag_stack; + int i = 0; + while(i < code.size()){ + pair tag_pos = get_tag_pos(code, i); + int tag_start = tag_pos.first, tag_end = tag_pos.second; + + if(tag_start == -1) return false; + if(i == 0 && tag_start != 0) return false; + + // end tag + if(code[tag_start + 1] == '/'){ + string tag_name = code.substr(tag_start + 2, tag_end - (tag_start + 2)); + if(!is_valid_tag(tag_name)) return false; + + if(tag_stack.empty() || tag_stack.back() != tag_name) return false; + tag_stack.pop_back(); + i = tag_end + 1; + } + else if(code.find("", tag_start); + if(cdata_end == string::npos || cdata_end + 3 == code.size()) return false; + + i = cdata_end + 3; + } + else{ // start tag + string tag_name = code.substr(tag_start + 1, tag_end - (tag_start + 1)); + if(!is_valid_tag(tag_name)) return false; + + tag_stack.push_back(tag_name); + i = tag_end + 1; + } + + if(i < code.size() && tag_stack.empty()) return false; + } + + return i == code.size() && tag_stack.empty(); + } + +private: + bool is_valid_tag(const string& tag){ + if(tag.empty() || tag.size() > 9) return false; + for(char c: tag) + if(!isupper(c)) return false; + return true; + } + + pair get_tag_pos(const string& s, int index){ + + int start_pos = s.find('<', index); + if(start_pos == string::npos) return {-1, -1}; + + int end_pos = s.find('>', start_pos); + if(end_pos == string::npos) return {-1, -1}; + + return {start_pos, end_pos}; + } +}; + + +int main() { + + cout << Solution().isValid("
This is the first line ]]>
") << '\n'; + // 1 + + cout << Solution().isValid("
>> ![cdata[]] ]>]]>]]>>]
") << '\n'; + // 1 + + cout << Solution().isValid(" ") << '\n'; + // 0 + + cout << Solution().isValid(" wahaha]]>") << '\n'; + // 1 + + cout << Solution().isValid(" wahaha]]>") << '\n'; + // 0 + + cout << Solution().isValid("") << '\n'; + // 0 + + cout << Solution().isValid("sometext") << '\n'; + // 0 + + cout << Solution().isValid("sometextG>") << '\n'; + // 0 + + return 0; +} diff --git a/0501-1000/0592-Fraction-Addition-and-Subtraction/cpp-0592/CMakeLists.txt b/0501-1000/0592-Fraction-Addition-and-Subtraction/cpp-0592/CMakeLists.txt new file mode 100644 index 00000000..789ca250 --- /dev/null +++ b/0501-1000/0592-Fraction-Addition-and-Subtraction/cpp-0592/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_0592) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0592 main.cpp) diff --git a/0501-1000/0592-Fraction-Addition-and-Subtraction/cpp-0592/main.cpp b/0501-1000/0592-Fraction-Addition-and-Subtraction/cpp-0592/main.cpp new file mode 100644 index 00000000..1193ded4 --- /dev/null +++ b/0501-1000/0592-Fraction-Addition-and-Subtraction/cpp-0592/main.cpp @@ -0,0 +1,66 @@ +/// Source : https://leetcode.com/problems/fraction-addition-and-subtraction/ +/// Author : liuyubobobo +/// Time : 2022-07-26 + +#include + +using namespace std; + + +/// String Parse +/// Time Complexity: O(|exp|) +/// Space Complexity: O(1) +class Solution { +public: + string fractionAddition(string expression) { + + if(expression[0] != '-') expression = "+" + expression; + + long long upper = 0, lower = 1; + for(int start = 0, i = 1; i <= expression.size(); i ++) + if(i == expression.size() || (expression[i] == '+' || expression[i] == '-')){ + + string f = expression.substr(start, i - start); + char op = f[0]; + + f = f.substr(1); + int div = f.find('/'); + + long long a = atoll(f.substr(0, div).c_str()); + long long b = atoll(f.substr(div + 1).c_str()); + + if(op == '+'){ + long long new_a = upper * b + a * lower; + long long new_b = b * lower; + upper = new_a, lower = new_b; + } + else{ + long long new_a = upper * b - a * lower; + long long new_b = b * lower; + upper = new_a, lower = new_b; + } + + long long g = gcd(abs(upper), abs(lower)); + upper /= g, lower /= g; + + start = i; + } + + return to_string(upper) + "/" + to_string(lower); + } + +private: + int gcd(long long a, long long b){ + + if(a > b) swap(a, b); + + if (a == 0) return b; + return gcd(b % a, a); + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0593-Valid-Square/cpp-0593/CMakeLists.txt b/0501-1000/0593-Valid-Square/cpp-0593/CMakeLists.txt new file mode 100644 index 00000000..12ea5087 --- /dev/null +++ b/0501-1000/0593-Valid-Square/cpp-0593/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_0593) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0593 main2.cpp) diff --git a/0501-1000/0593-Valid-Square/cpp-0593/main.cpp b/0501-1000/0593-Valid-Square/cpp-0593/main.cpp new file mode 100644 index 00000000..c92b2d11 --- /dev/null +++ b/0501-1000/0593-Valid-Square/cpp-0593/main.cpp @@ -0,0 +1,60 @@ +/// Source : https://leetcode.com/problems/valid-square/ +/// Author : liuyubobobo +/// Time : 2022-07-28 + +#include +#include +#include + +using namespace std; + + +/// Brute Force + Math +/// Time Complexity: O(4!) +/// Space Complexity: O(1) +class Solution { +public: + bool validSquare(vector& p1, vector& p2, vector& p3, vector& p4) { + + vector> p ={p1, p2, p3, p4}; + for(int i = 0; i < 4; i ++) + for(int j = i + 1; j < 4; j ++) + if(p[i] == p[j]) return false; + + sort(p.begin(), p.end()); + do{ + if(valid_square(p)) return true; + }while(next_permutation(p.begin(), p.end())); + return false; + } + +private: + bool valid_square(const vector>& p){ + + int L2 = get_L2(p[0], p[1]); + for(int i = 1; i < 4; i ++) + if(get_L2(p[i], p[(i + 1) % 4]) != L2) return false; + + for(int i = 0; i < 4; i ++) + if(dot_product(p[i], p[(i + 1) % 4], p[(i + 2) % 4])) return false; + + return true; + } + + int dot_product(const vector& p1, const vector& p2, const vector& p3){ + + int a1 = p2[0] - p1[0], b1 = p2[1] - p1[1]; + int a2 = p3[0] - p2[0], b2 = p3[1] - p2[1]; + return a1 * b1 + a2 * b2; + } + + int get_L2(const vector& p1, const vector& p2){ + return (p1[0] - p2[0]) * (p1[0] - p2[0]) + (p1[1] - p2[1]) * (p1[1] - p2[1]); + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0593-Valid-Square/cpp-0593/main2.cpp b/0501-1000/0593-Valid-Square/cpp-0593/main2.cpp new file mode 100644 index 00000000..6894f216 --- /dev/null +++ b/0501-1000/0593-Valid-Square/cpp-0593/main2.cpp @@ -0,0 +1,43 @@ +/// Source : https://leetcode.com/problems/valid-square/ +/// Author : liuyubobobo +/// Time : 2022-07-28 + +#include +#include +#include + +using namespace std; + + +/// Only check points' distance +/// Time Complexity: O(6) +/// Space Complexity: O(1) +class Solution { +public: + bool validSquare(vector& p1, vector& p2, vector& p3, vector& p4) { + + vector> p ={p1, p2, p3, p4}; + map table; + for(int i = 0; i < 4; i ++) + for(int j = i + 1; j < 4; j ++){ + if(p[i] == p[j]) return false; + table[get_L2(p[i], p[j])] ++; + } + + if(table.size() != 2) return false; + if(table.begin()->second == 4 && table.rbegin()->second == 2 && table.begin()->first * 2 == table.rbegin()->first) + return true; + return false; + } + +private: + int get_L2(const vector& p1, const vector& p2){ + return (p1[0] - p2[0]) * (p1[0] - p2[0]) + (p1[1] - p2[1]) * (p1[1] - p2[1]); + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0594-Longest-Harmonious-Subsequence/cpp-0594/CMakeLists.txt b/0501-1000/0594-Longest-Harmonious-Subsequence/cpp-0594/CMakeLists.txt new file mode 100644 index 00000000..ae04e024 --- /dev/null +++ b/0501-1000/0594-Longest-Harmonious-Subsequence/cpp-0594/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0594) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0594 main.cpp) \ No newline at end of file diff --git a/0501-1000/0594-Longest-Harmonious-Subsequence/cpp-0594/main.cpp b/0501-1000/0594-Longest-Harmonious-Subsequence/cpp-0594/main.cpp new file mode 100644 index 00000000..b5458970 --- /dev/null +++ b/0501-1000/0594-Longest-Harmonious-Subsequence/cpp-0594/main.cpp @@ -0,0 +1,39 @@ +/// Source : https://leetcode.com/problems/longest-harmonious-subsequence/ +/// Author : liuyubobobo +/// Time : 2021-02-05 + +#include +#include +#include + +using namespace std; + + +/// Using HashMap +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int findLHS(vector& nums) { + + unordered_map f; + for(int e: nums) f[e] ++; + + int res = 0; + for(const pair& p: f) + if(f.count(p.first + 1)) + res = max(res, p.second + f[p.first + 1]); + + return res; + } +}; + + +int main() { + + vector nums1 = {1, 1, 1, 1}; + cout << Solution().findLHS(nums1) << endl; + // 4 + + return 0; +} diff --git a/0598-Range-Addition-II/cpp-0598/CMakeLists.txt b/0501-1000/0598-Range-Addition-II/cpp-0598/CMakeLists.txt similarity index 100% rename from 0598-Range-Addition-II/cpp-0598/CMakeLists.txt rename to 0501-1000/0598-Range-Addition-II/cpp-0598/CMakeLists.txt diff --git a/0598-Range-Addition-II/cpp-0598/main.cpp b/0501-1000/0598-Range-Addition-II/cpp-0598/main.cpp similarity index 100% rename from 0598-Range-Addition-II/cpp-0598/main.cpp rename to 0501-1000/0598-Range-Addition-II/cpp-0598/main.cpp diff --git a/0501-1000/0599-Minimum-Index-Sum-of-Two-Lists/cpp-0599/CMakeLists.txt b/0501-1000/0599-Minimum-Index-Sum-of-Two-Lists/cpp-0599/CMakeLists.txt new file mode 100644 index 00000000..a4fc2ddd --- /dev/null +++ b/0501-1000/0599-Minimum-Index-Sum-of-Two-Lists/cpp-0599/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0599) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0599 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0599-Minimum-Index-Sum-of-Two-Lists/cpp-0599/main.cpp b/0501-1000/0599-Minimum-Index-Sum-of-Two-Lists/cpp-0599/main.cpp new file mode 100644 index 00000000..1beca399 --- /dev/null +++ b/0501-1000/0599-Minimum-Index-Sum-of-Two-Lists/cpp-0599/main.cpp @@ -0,0 +1,58 @@ +/// Source : https://leetcode.com/problems/minimum-index-sum-of-two-lists/description/ +/// Author : liuyubobobo +/// Time : 2018-06-12 + +#include +#include +#include + +using namespace std; + +/// HashMap +/// Time Complexity: O(max(l1, l2) * s), where s is the average length of string +/// Space Complexity: O(l1 * s) +class Solution { +public: + vector findRestaurant(vector& list1, vector& list2) { + + unordered_map map; + for(int i = 0 ; i < list1.size() ; i ++) + map[list1[i]] = i; + + int min_sum = INT_MAX; + vector res; + for(int i = 0 ; i < list2.size() ; i ++) + if(map.find(list2[i]) != map.end()){ + if(map[list2[i]] + i < min_sum){ + res.clear(); + res.push_back(list2[i]); + min_sum = map[list2[i]] + i; + } + else if(map[list2[i]] + i == min_sum){ + res.push_back(list2[i]); + } + } + + return res; + } +}; + + +void print_vec(const vector& vec){ + for(const string& s: vec) + cout << s << " "; + cout << endl; +} + +int main() { + + vector list1_1 = {"Shogun", "Tapioca Express", "Burger King", "KFC"}; + vector list1_2 = {"Piatti", "The Grill at Torrey Pines", "Hungry Hunter Steakhouse", "Shogun"}; + print_vec(Solution().findRestaurant(list1_1, list1_2)); + + vector list2_1 = {"Shogun", "Tapioca Express", "Burger King", "KFC"}; + vector list2_2 = {"KFC", "Shogun", "Burger King"}; + print_vec(Solution().findRestaurant(list2_1, list2_2)); + + return 0; +} \ No newline at end of file diff --git a/0600-Non-negative-Integers-without-Consecutive-Ones/cpp-0600/CMakeLists.txt b/0501-1000/0600-Non-negative-Integers-without-Consecutive-Ones/cpp-0600/CMakeLists.txt similarity index 100% rename from 0600-Non-negative-Integers-without-Consecutive-Ones/cpp-0600/CMakeLists.txt rename to 0501-1000/0600-Non-negative-Integers-without-Consecutive-Ones/cpp-0600/CMakeLists.txt diff --git a/0600-Non-negative-Integers-without-Consecutive-Ones/cpp-0600/main.cpp b/0501-1000/0600-Non-negative-Integers-without-Consecutive-Ones/cpp-0600/main.cpp similarity index 100% rename from 0600-Non-negative-Integers-without-Consecutive-Ones/cpp-0600/main.cpp rename to 0501-1000/0600-Non-negative-Integers-without-Consecutive-Ones/cpp-0600/main.cpp diff --git a/0600-Non-negative-Integers-without-Consecutive-Ones/cpp-0600/main2.cpp b/0501-1000/0600-Non-negative-Integers-without-Consecutive-Ones/cpp-0600/main2.cpp similarity index 100% rename from 0600-Non-negative-Integers-without-Consecutive-Ones/cpp-0600/main2.cpp rename to 0501-1000/0600-Non-negative-Integers-without-Consecutive-Ones/cpp-0600/main2.cpp diff --git a/0501-1000/0605-Can-Place-Flowers/cpp-0605/CMakeLists.txt b/0501-1000/0605-Can-Place-Flowers/cpp-0605/CMakeLists.txt new file mode 100644 index 00000000..86609e80 --- /dev/null +++ b/0501-1000/0605-Can-Place-Flowers/cpp-0605/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0605) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0605 main.cpp) \ No newline at end of file diff --git a/0501-1000/0605-Can-Place-Flowers/cpp-0605/main.cpp b/0501-1000/0605-Can-Place-Flowers/cpp-0605/main.cpp new file mode 100644 index 00000000..69742d70 --- /dev/null +++ b/0501-1000/0605-Can-Place-Flowers/cpp-0605/main.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/can-place-flowers/ +/// Author : liuyubobobo +/// Time : 2020-12-05 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + bool canPlaceFlowers(vector& flowerbed, int n) { + + for(int i = 0; i < flowerbed.size() && n; i ++) + if(flowerbed[i] == 0){ + flowerbed[i] = 1; + if(i - 1 >= 0 && flowerbed[i - 1] == 1) + flowerbed[i] = 0; + else if(i + 1 < flowerbed.size() && flowerbed[i + 1] == 1) + flowerbed[i] = 0; + else n --; + } + return n == 0; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0606-Construct-String-from-Binary-Tree/cpp-0606/CMakeLists.txt b/0501-1000/0606-Construct-String-from-Binary-Tree/cpp-0606/CMakeLists.txt new file mode 100644 index 00000000..42e37b1f --- /dev/null +++ b/0501-1000/0606-Construct-String-from-Binary-Tree/cpp-0606/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0606) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0606 main.cpp) \ No newline at end of file diff --git a/0501-1000/0606-Construct-String-from-Binary-Tree/cpp-0606/main.cpp b/0501-1000/0606-Construct-String-from-Binary-Tree/cpp-0606/main.cpp new file mode 100644 index 00000000..d4ed785f --- /dev/null +++ b/0501-1000/0606-Construct-String-from-Binary-Tree/cpp-0606/main.cpp @@ -0,0 +1,42 @@ +/// Source : https://leetcode.com/problems/construct-string-from-binary-tree/ +/// Author : liuyubobobo +/// Time : 2021-03-15 + +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Coomplexity: O(h) + +/// 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: + string tree2str(TreeNode* t) { + + if(!t) return ""; + string res = to_string(t->val); + if(!t->left && !t->right) return res; + + res += "(" + tree2str(t->left) + ")"; + if(t->right) res += "(" + tree2str(t->right) + ")"; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0609-Find-Duplicate-File-in-System/cpp-0609/CMakeLists.txt b/0501-1000/0609-Find-Duplicate-File-in-System/cpp-0609/CMakeLists.txt new file mode 100644 index 00000000..6d70d7c8 --- /dev/null +++ b/0501-1000/0609-Find-Duplicate-File-in-System/cpp-0609/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_0609) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0609 main.cpp) \ No newline at end of file diff --git a/0501-1000/0609-Find-Duplicate-File-in-System/cpp-0609/main.cpp b/0501-1000/0609-Find-Duplicate-File-in-System/cpp-0609/main.cpp new file mode 100644 index 00000000..10e16197 --- /dev/null +++ b/0501-1000/0609-Find-Duplicate-File-in-System/cpp-0609/main.cpp @@ -0,0 +1,77 @@ +/// Source : https://leetcode.com/problems/find-duplicate-file-in-system/ +/// Author : liuyubobobo +/// Time : 2021-05-18 + +#include +#include +#include +#include + +using namespace std; + + +/// Using HashMap +/// Time Complexity: O(|all files|) +/// Space Complexity: O(|all files|) +class Solution { +public: + vector> findDuplicate(vector& paths) { + + unordered_map> table; + for(const string& path: paths){ + vector v = split(path); + + for(int i = 1; i < v.size(); i ++){ + vector file = parse(v[i]); + table[file[1]].push_back(v[0] + "/" + file[0]); + } + } + + vector> res; + for(const pair>& p: table) + if(p.second.size() > 1) + res.push_back(p.second); + return res; + } + +private: + vector parse(const string& s){ + + int l = s.find('('); + assert(l != string::npos); + + int r = s.find(')', l + 1); + assert(r != string::npos); + + return {s.substr(0, l), s.substr(l + 1, r - l - 1)}; + } + + vector split(const string& s){ + + vector res; + for(int start = 0, i = 1; i <= s.size(); i ++) + if(i == s.size() || s[i] == ' '){ + res.push_back(s.substr(start, i - start)); + + start = i + 1; + i = start; + } + return res; + } +}; + + +void print(const vector>& res){ + + for(const vector& v: res){ + for(const string& s: v) cout << s << " "; cout << endl; + } +} + +int main() { + + vector paths1 = {"root/a 1.txt(abcd) 2.txt(efgh)","root/c 3.txt(abcd)","root/c/d 4.txt(efgh)","root 4.txt(efgh)"}; + print(Solution().findDuplicate(paths1)); + + return 0; +} diff --git a/0501-1000/0611-Valid-Triangle-Number/cpp-0611/CMakeLists.txt b/0501-1000/0611-Valid-Triangle-Number/cpp-0611/CMakeLists.txt new file mode 100644 index 00000000..d0be7584 --- /dev/null +++ b/0501-1000/0611-Valid-Triangle-Number/cpp-0611/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_0611) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0611 main.cpp) \ No newline at end of file diff --git a/0501-1000/0611-Valid-Triangle-Number/cpp-0611/main.cpp b/0501-1000/0611-Valid-Triangle-Number/cpp-0611/main.cpp new file mode 100644 index 00000000..631b354f --- /dev/null +++ b/0501-1000/0611-Valid-Triangle-Number/cpp-0611/main.cpp @@ -0,0 +1,45 @@ +/// Source : https://leetcode.com/problems/valid-triangle-number/ +/// Author : liuyubobobo +/// Time : 2021-07-15 + +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(n^2 * logn) +/// Space Complexity: O(1) +class Solution { +public: + int triangleNumber(vector& nums) { + + sort(nums.begin(), nums.end()); + + int n = nums.size(), res = 0; + for(int i = 0; i < n; i ++) + for(int j = i + 1; j < n; j ++){ + int a = nums[i], b = nums[j]; + vector::iterator iter1 = upper_bound(nums.begin() + (j + 1), nums.end(), b - a); + int l = iter1 - nums.begin(); + + vector::iterator iter2 = lower_bound(nums.begin() + (j + 1), nums.end(), b + a); + iter2 --; + int r = iter2 - nums.begin(); + +// cout << i << ' ' << j << " : " << l << ' ' << r << endl; + if(l <= r) res += (r - l + 1); + } + return res; + } +}; + + +int main() { + + vector nums1 = {2, 2, 3, 4}; + cout << Solution().triangleNumber(nums1) << endl; + + return 0; +} diff --git a/0501-1000/0617-Merge-Two-Binary-Trees/cpp-0617/CMakeLists.txt b/0501-1000/0617-Merge-Two-Binary-Trees/cpp-0617/CMakeLists.txt new file mode 100644 index 00000000..f1895b9e --- /dev/null +++ b/0501-1000/0617-Merge-Two-Binary-Trees/cpp-0617/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_0617) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0617 main.cpp) \ No newline at end of file diff --git a/0501-1000/0617-Merge-Two-Binary-Trees/cpp-0617/main.cpp b/0501-1000/0617-Merge-Two-Binary-Trees/cpp-0617/main.cpp new file mode 100644 index 00000000..7f6391ef --- /dev/null +++ b/0501-1000/0617-Merge-Two-Binary-Trees/cpp-0617/main.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/merge-two-binary-trees/ +/// Author : liuyubobobo +/// Time : 2021-07-09 + +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// 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* mergeTrees(TreeNode* root1, TreeNode* root2) { + + return build(root1, root2); + } + +private: + TreeNode* build(TreeNode* node1, TreeNode* node2){ + + if(!node1 && !node2) return nullptr; + + TreeNode* node = new TreeNode((node1 ? node1->val : 0) + (node2 ? node2->val : 0)); + node->left = build((node1 ? node1->left : nullptr), (node2 ? node2->left : nullptr)); + node->right = build((node1 ? node1->right : nullptr), (node2 ? node2->right : nullptr)); + return node; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0621-Task-Scheduler/cpp-0621/CMakeLists.txt b/0501-1000/0621-Task-Scheduler/cpp-0621/CMakeLists.txt new file mode 100644 index 00000000..aec9d06b --- /dev/null +++ b/0501-1000/0621-Task-Scheduler/cpp-0621/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0621) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0621 main2.cpp) \ No newline at end of file diff --git a/0501-1000/0621-Task-Scheduler/cpp-0621/main.cpp b/0501-1000/0621-Task-Scheduler/cpp-0621/main.cpp new file mode 100644 index 00000000..85751421 --- /dev/null +++ b/0501-1000/0621-Task-Scheduler/cpp-0621/main.cpp @@ -0,0 +1,67 @@ +/// Source : https://leetcode.com/problems/task-scheduler/ +/// Author : liuyubobobo +/// Time : 2020-12-05 + +#include +#include +#include +#include + +using namespace std; + + +/// Simulation with Priority Queue +/// Time Complexity: O(n * |task| * log|task|) +/// Space Coomplexity: O(|task|) +class Solution { +public: + int leastInterval(vector& tasks, int n) { + + unordered_map freq; + for(char task: tasks) freq[task] ++; + + priority_queue, vector>, greater>> frozen_pq; // last, task + priority_queue> pq; // left, task + + for(const pair& p: freq) pq.push({p.second, p.first}); + + int t = 0; + while(!pq.empty() || !frozen_pq.empty()){ + + if(!pq.empty()){ + int task = pq.top().second; + pq.pop(); + freq[task] --; + if(freq[task]) frozen_pq.push({t, task}); + else freq.erase(task); + } + + t ++; + + while(!frozen_pq.empty() && t - frozen_pq.top().first - 1 == n){ + int task = frozen_pq.top().second; + pq.push({freq[task], task}); + frozen_pq.pop(); + } + } + return t; + } +}; + + +int main() { + + vector v1 = {'A', 'A', 'A', 'B', 'B', 'B'}; + cout << Solution().leastInterval(v1, 2) << endl; + // 8 + + vector v2 = {'A', 'A', 'A', 'B', 'B', 'B'}; + cout << Solution().leastInterval(v2, 0) << endl; + // 6 + + vector v3 = {'A', 'A', 'A', 'A', 'A', 'A', 'B', 'C', 'D', 'E', 'F', 'G'}; + cout << Solution().leastInterval(v3, 2) << endl; + // 16 + + return 0; +} diff --git a/0501-1000/0621-Task-Scheduler/cpp-0621/main2.cpp b/0501-1000/0621-Task-Scheduler/cpp-0621/main2.cpp new file mode 100644 index 00000000..6ed51162 --- /dev/null +++ b/0501-1000/0621-Task-Scheduler/cpp-0621/main2.cpp @@ -0,0 +1,48 @@ +/// Source : https://leetcode.com/problems/task-scheduler/ +/// Author : liuyubobobo +/// Time : 2020-12-05 + +#include +#include +#include +#include + +using namespace std; + + +/// Greedy and Mathematics +/// Time Complexity: O(|task|) +/// Space Coomplexity: O(|task|) +class Solution { +public: + int leastInterval(vector& tasks, int n) { + + int maxfreq = 0, maxcnt = 0; + unordered_map freq; + for(char task: tasks){ + freq[task] ++; + if(freq[task] > maxfreq) maxfreq = freq[task], maxcnt = 1; + else if(freq[task] == maxfreq) maxcnt ++; + } + + return max((int)tasks.size(), (maxfreq - 1) * (n + 1) + maxcnt); + } +}; + + +int main() { + + vector v1 = {'A', 'A', 'A', 'B', 'B', 'B'}; + cout << Solution().leastInterval(v1, 2) << endl; + // 8 + + vector v2 = {'A', 'A', 'A', 'B', 'B', 'B'}; + cout << Solution().leastInterval(v2, 0) << endl; + // 6 + + vector v3 = {'A', 'A', 'A', 'A', 'A', 'A', 'B', 'C', 'D', 'E', 'F', 'G'}; + cout << Solution().leastInterval(v3, 2) << endl; + // 16 + + return 0; +} diff --git a/0501-1000/0622-Design-Circular-Queue/cpp-0622/CMakeLists.txt b/0501-1000/0622-Design-Circular-Queue/cpp-0622/CMakeLists.txt new file mode 100644 index 00000000..3c602c49 --- /dev/null +++ b/0501-1000/0622-Design-Circular-Queue/cpp-0622/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0622) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main2.cpp) +add_executable(cpp_0622 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0622-Design-Circular-Queue/cpp-0622/main.cpp b/0501-1000/0622-Design-Circular-Queue/cpp-0622/main.cpp new file mode 100644 index 00000000..ab6d0689 --- /dev/null +++ b/0501-1000/0622-Design-Circular-Queue/cpp-0622/main.cpp @@ -0,0 +1,79 @@ +/// Source : https://leetcode.com/problems/design-circular-queue/description/ +/// Author : liuyubobobo +/// Time : 2018-08-24 + +#include +#include + +using namespace std; + + +/// One more space implementation +/// Time Complexity: O(1) +/// Space Complexity: O(n) +class MyCircularQueue { + +private: + int front, tail; + vector data; + +public: + /** Initialize your data structure here. Set the size of the queue to be k. */ + MyCircularQueue(int k) { + + front = tail = 0; + data.clear(); + for(int i = 0; i <= k; i ++) + data.push_back(-1); + } + + /** Insert an element into the circular queue. Return true if the operation is successful. */ + bool enQueue(int value) { + if(isFull()) + return false; + data[tail] = value; + tail = (tail + 1) % data.size(); + return true; + } + + /** Delete an element from the circular queue. Return true if the operation is successful. */ + bool deQueue() { + if(isEmpty()) + return false; + front = (front + 1) % data.size(); + return true; + } + + /** Get the front item from the queue. */ + int Front() { + if(isEmpty()) + return -1; + return data[front]; + } + + /** Get the last item from the queue. */ + int Rear() { + if(isEmpty()) + return -1; + int index = tail - 1; + if(index < 0) + index += data.size(); + return data[index]; + } + + /** Checks whether the circular queue is empty or not. */ + bool isEmpty() { + return front == tail; + } + + /** Checks whether the circular queue is full or not. */ + bool isFull() { + return (tail + 1) % data.size() == front; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0622-Design-Circular-Queue/cpp-0622/main2.cpp b/0501-1000/0622-Design-Circular-Queue/cpp-0622/main2.cpp new file mode 100644 index 00000000..e86786c9 --- /dev/null +++ b/0501-1000/0622-Design-Circular-Queue/cpp-0622/main2.cpp @@ -0,0 +1,82 @@ +/// Source : https://leetcode.com/problems/design-circular-queue/description/ +/// Author : liuyubobobo +/// Time : 2018-08-24 + +#include +#include + +using namespace std; + + +/// No need to use one more space :) +/// Time Complexity: O(1) +/// Space Complexity: O(n) +class MyCircularQueue { + +private: + int front, tail, size, capacity; + vector data; + +public: + /** Initialize your data structure here. Set the size of the queue to be k. */ + MyCircularQueue(int k) { + + front = tail = size = 0; + capacity = k; + data.clear(); + for(int i = 0; i < k; i ++) + data.push_back(-1); + } + + /** Insert an element into the circular queue. Return true if the operation is successful. */ + bool enQueue(int value) { + if(isFull()) + return false; + data[tail] = value; + tail = (tail + 1) % data.size(); + size ++; + return true; + } + + /** Delete an element from the circular queue. Return true if the operation is successful. */ + bool deQueue() { + if(isEmpty()) + return false; + front = (front + 1) % data.size(); + size --; + return true; + } + + /** Get the front item from the queue. */ + int Front() { + if(isEmpty()) + return -1; + return data[front]; + } + + /** Get the last item from the queue. */ + int Rear() { + if(isEmpty()) + return -1; + int index = tail - 1; + if(index < 0) + index += data.size(); + return data[index]; + } + + /** Checks whether the circular queue is empty or not. */ + bool isEmpty() { + return size == 0; + } + + /** Checks whether the circular queue is full or not. */ + bool isFull() { + return size == capacity; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0623-Add-One-Row-to-Tree/cpp-0623/CMakeLists.txt b/0501-1000/0623-Add-One-Row-to-Tree/cpp-0623/CMakeLists.txt new file mode 100644 index 00000000..adadd7db --- /dev/null +++ b/0501-1000/0623-Add-One-Row-to-Tree/cpp-0623/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0623) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0623 main.cpp) \ No newline at end of file diff --git a/0501-1000/0623-Add-One-Row-to-Tree/cpp-0623/main.cpp b/0501-1000/0623-Add-One-Row-to-Tree/cpp-0623/main.cpp new file mode 100644 index 00000000..8a6c93aa --- /dev/null +++ b/0501-1000/0623-Add-One-Row-to-Tree/cpp-0623/main.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/add-one-row-to-tree/ +/// Author : liuyubobobo +/// Time : 2021-03-09 + +#include + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(h) + +/// 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* addOneRow(TreeNode* root, int v, int d) { + + return dfs(root, v, d, true); + } + +private: + TreeNode* dfs(TreeNode* node, int v, int d, bool left){ + + if(d == 1){ + TreeNode* new_node = new TreeNode(v); + if(left) new_node->left = node; + else new_node->right = node; + return new_node; + } + + if(!node) return nullptr; + + node->left = dfs(node->left, v, d - 1, true); + node->right = dfs(node->right, v, d - 1, false); + return node; + } +}; + + +int main() { + + TreeNode* root = new TreeNode(4); + root->left = new TreeNode(2, new TreeNode(3), new TreeNode(1)); + Solution().addOneRow(root, 1, 3); + + return 0; +} diff --git a/0501-1000/0628-Maximum-Product-of-Three-Numbers/cpp-0628/CMakeLists.txt b/0501-1000/0628-Maximum-Product-of-Three-Numbers/cpp-0628/CMakeLists.txt new file mode 100644 index 00000000..0b3af9d6 --- /dev/null +++ b/0501-1000/0628-Maximum-Product-of-Three-Numbers/cpp-0628/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0628) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0628 main.cpp) \ No newline at end of file diff --git a/0501-1000/0628-Maximum-Product-of-Three-Numbers/cpp-0628/main.cpp b/0501-1000/0628-Maximum-Product-of-Three-Numbers/cpp-0628/main.cpp new file mode 100644 index 00000000..e235ea90 --- /dev/null +++ b/0501-1000/0628-Maximum-Product-of-Three-Numbers/cpp-0628/main.cpp @@ -0,0 +1,32 @@ +/// Source : https://leetcode.com/problems/maximum-product-of-three-numbers/ +/// Author : liuyubobobo +/// Time : 2021-01-19 + +#include +#include + +using namespace std; + + +/// Sorting +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + int maximumProduct(vector& nums) { + + sort(nums.begin(), nums.end()); + + int res = INT_MIN; + res = max(res, nums[0] * nums[1] * nums[2]); + res = max(res, nums.back() * nums[nums.size() - 2] * nums[nums.size() - 3]); + res = max(res, nums[0] * nums[1] * nums.back()); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0629-K-Inverse-Pairs-Array/cpp-0629/CMakeLists.txt b/0501-1000/0629-K-Inverse-Pairs-Array/cpp-0629/CMakeLists.txt new file mode 100644 index 00000000..92d9d646 --- /dev/null +++ b/0501-1000/0629-K-Inverse-Pairs-Array/cpp-0629/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_0629) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0629 main.cpp) \ No newline at end of file diff --git a/0501-1000/0629-K-Inverse-Pairs-Array/cpp-0629/main.cpp b/0501-1000/0629-K-Inverse-Pairs-Array/cpp-0629/main.cpp new file mode 100644 index 00000000..ff4e63a5 --- /dev/null +++ b/0501-1000/0629-K-Inverse-Pairs-Array/cpp-0629/main.cpp @@ -0,0 +1,43 @@ +/// Source : https://leetcode.com/problems/k-inverse-pairs-array/ +/// Author : liuyubobobo +/// Time : 2021-06-20 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(nk) +/// Space Complexity: O(nk) +class Solution { + +private: + const int MOD = 1e9 + 7; + +public: + int kInversePairs(int n, int k) { + + vector> dp(n + 1, vector(k + 1, 0)); + + dp[1][0] = 1; + for(int i = 2; i <= n; i ++){ + + vector presum(k + 2, 0); + for(int j = 0; j <= k; j ++) + presum[j + 1] = (presum[j] + dp[i - 1][j]) % MOD; + + dp[i][0] = 1; + for(int j = 1; j <= k; j ++) + dp[i][j] = (presum[j + 1] - presum[max(0, j - (i - 1))] + MOD) % MOD; + } + return dp[n][k]; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0630-Course-Schedule-III/cpp-0630/CMakeLists.txt b/0501-1000/0630-Course-Schedule-III/cpp-0630/CMakeLists.txt new file mode 100644 index 00000000..329fc481 --- /dev/null +++ b/0501-1000/0630-Course-Schedule-III/cpp-0630/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_0630) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0630 main.cpp) \ No newline at end of file diff --git a/0501-1000/0630-Course-Schedule-III/cpp-0630/main.cpp b/0501-1000/0630-Course-Schedule-III/cpp-0630/main.cpp new file mode 100644 index 00000000..d8782fa8 --- /dev/null +++ b/0501-1000/0630-Course-Schedule-III/cpp-0630/main.cpp @@ -0,0 +1,61 @@ +/// Source : https://leetcode.com/problems/course-schedule-iii/ +/// Author : liuyubobobo +/// Time : 2021-05-03 + +#include +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + int scheduleCourse(vector>& courses) { + + sort(courses.begin(), courses.end(), + [](const vector& a, const vector& b){ + return a[1] < b[1]; + }); + + priority_queue pq; + int t = 0; + for(vector& course: courses) + if(t + course[0] <= course[1]){ + t += course[0]; + pq.push(course[0]); + } + else if(!pq.empty() && t - pq.top() + course[0] <= course[1] && t - pq.top() + course[0] <= t){ + t -= pq.top(); + t += course[0]; + pq.pop(); + pq.push(course[0]); + } + return pq.size(); + } +}; + + +int main() { + + vector> courses1 = {{5,15},{3,19},{6,7},{2,10},{5,16},{8,14},{10,11},{2,19}}; + cout << Solution().scheduleCourse(courses1) << endl; + // 5 + + vector> courses2 = {{2,5},{2,19},{1,8},{1,3}}; + cout << Solution().scheduleCourse(courses2) << endl; + // 4 + + vector> courses3 = {{9,14},{7,12},{1,11},{4,7}}; + cout << Solution().scheduleCourse(courses3) << endl; + // 3 + + vector> courses4 = {{7,17},{3,12},{10,20},{9,10},{5,20},{10,19},{4,18}}; + cout << Solution().scheduleCourse(courses4) << endl; + // 4 + + return 0; +} diff --git a/0501-1000/0632-Smallest-Range-Covering-Elements-from-K-Lists/cpp-0632/CMakeLists.txt b/0501-1000/0632-Smallest-Range-Covering-Elements-from-K-Lists/cpp-0632/CMakeLists.txt new file mode 100644 index 00000000..837b99d4 --- /dev/null +++ b/0501-1000/0632-Smallest-Range-Covering-Elements-from-K-Lists/cpp-0632/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0632) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0632 main.cpp) \ No newline at end of file diff --git a/0501-1000/0632-Smallest-Range-Covering-Elements-from-K-Lists/cpp-0632/main.cpp b/0501-1000/0632-Smallest-Range-Covering-Elements-from-K-Lists/cpp-0632/main.cpp new file mode 100644 index 00000000..da9093d9 --- /dev/null +++ b/0501-1000/0632-Smallest-Range-Covering-Elements-from-K-Lists/cpp-0632/main.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/smallest-range-covering-elements-from-k-lists/ +/// Author : liuyubobobo +/// Time : 2020-11-30 + +#include +#include +#include + +using namespace std; + + +/// Min Heap for n pointers +/// Time Complexity: O(nlogn) +/// Space Compelxity: O(n) +class Solution { +public: + vector smallestRange(vector>& nums) { + + int n = nums.size(); + vector next(n, 0); + + priority_queue, vector>, greater>> pq; + int curmax = INT_MIN; + for(int i = 0; i < n; i ++) + pq.push({nums[i][0], i}), curmax = max(curmax, nums[i][0]); + + int resl = -1e9, resr = 1e9; + while(true){ + + if(curmax - pq.top().first < resr - resl) + resl = pq.top().first, resr = curmax; + + int index = pq.top().second; + pq.pop(); + + next[index] ++; + if(next[index] >= nums[index].size()) break; + + pq.push({nums[index][next[index]], index}); + curmax = max(curmax, nums[index][next[index]]); + } + return {resl, resr}; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0633-Sum-of-Square-Numbers/cpp-0633/CMakeLists.txt b/0501-1000/0633-Sum-of-Square-Numbers/cpp-0633/CMakeLists.txt new file mode 100644 index 00000000..c10ec75c --- /dev/null +++ b/0501-1000/0633-Sum-of-Square-Numbers/cpp-0633/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_0633) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0633 main.cpp) \ No newline at end of file diff --git a/0501-1000/0633-Sum-of-Square-Numbers/cpp-0633/main.cpp b/0501-1000/0633-Sum-of-Square-Numbers/cpp-0633/main.cpp new file mode 100644 index 00000000..ab380cf4 --- /dev/null +++ b/0501-1000/0633-Sum-of-Square-Numbers/cpp-0633/main.cpp @@ -0,0 +1,30 @@ +/// Source : https://leetcode.com/problems/sum-of-square-numbers/ +/// Author : liuyubobobo +/// Time : 2021-04-28 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(sqrt(c)) +/// Space Complexity: O(1) +class Solution { +public: + bool judgeSquareSum(int c) { + + for(int i = 0; i * i <= c - i * i; i ++){ + int x = (int)sqrt(c - i * i); + if(i * i + x * x == c) return true; + } + return false; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0636-Exclusive-Time-of-Functions/cpp-0636/CMakeLists.txt b/0501-1000/0636-Exclusive-Time-of-Functions/cpp-0636/CMakeLists.txt new file mode 100644 index 00000000..52e1eff9 --- /dev/null +++ b/0501-1000/0636-Exclusive-Time-of-Functions/cpp-0636/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_0636) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0636 main.cpp) diff --git a/0501-1000/0636-Exclusive-Time-of-Functions/cpp-0636/main.cpp b/0501-1000/0636-Exclusive-Time-of-Functions/cpp-0636/main.cpp new file mode 100644 index 00000000..da76e9f9 --- /dev/null +++ b/0501-1000/0636-Exclusive-Time-of-Functions/cpp-0636/main.cpp @@ -0,0 +1,78 @@ +/// Source : https://leetcode.com/problems/exclusive-time-of-functions/ +/// Author : liuyubobobo +/// Time : 2022-08-08 + +#include +#include +#include + +using namespace std; + + +/// Using Stack +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector exclusiveTime(int n, vector& logs) { + + vector res(n, 0); + + vector, char>> data; // id, ts, s or e + for(const string& log: logs) + data.push_back(parse(log)); + + vector> stack; // id, ts + for(const pair, char>& e: data){ + int id = e.first.first, ts = e.first.second; + char s_or_e = e.second; + + if(s_or_e == 's'){ + if(!stack.empty()){ + res[stack.back().first] += ts - stack.back().second; + stack.back().second = -1; + } + stack.push_back({id, ts}); + } + else{ + assert(!stack.empty() && stack.back().first == id); + res[stack.back().first] += ts - stack.back().second + 1; + stack.pop_back(); + + if(!stack.empty()){ + stack.back().second = ts + 1; + } + } + } + return res; + } + +private: + pair, char> parse(const string& log){ + + int c1 = log.find(':'), c2 = log.find(':', c1 + 1); + + int id = atoi(log.substr(0, c1).c_str()); + char s_or_e =log[c1 + 1]; + int ts = atoi(log.substr(c2 + 1).c_str()); + return {{id, ts}, s_or_e}; + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << ' '; cout << '\n'; +} + +int main() { + + vector logs1 = {"0:start:0","1:start:2","1:end:5","0:end:6"}; + print_vec(Solution().exclusiveTime(2, logs1)); + // 3 4 + + vector logs2 = {"0:start:0","0:start:2","0:end:5","0:start:6","0:end:6","0:end:7"}; + print_vec(Solution().exclusiveTime(1, logs2)); + // 8 + + return 0; +} diff --git a/0501-1000/0637-Average-of-Levels-in-Binary-Tree/cpp-0637/CMakeLists.txt b/0501-1000/0637-Average-of-Levels-in-Binary-Tree/cpp-0637/CMakeLists.txt new file mode 100644 index 00000000..2d8e75d8 --- /dev/null +++ b/0501-1000/0637-Average-of-Levels-in-Binary-Tree/cpp-0637/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0637) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main3.cpp) +add_executable(cpp_0637 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0637-Average-of-Levels-in-Binary-Tree/cpp-0637/main.cpp b/0501-1000/0637-Average-of-Levels-in-Binary-Tree/cpp-0637/main.cpp new file mode 100644 index 00000000..37367bd6 --- /dev/null +++ b/0501-1000/0637-Average-of-Levels-in-Binary-Tree/cpp-0637/main.cpp @@ -0,0 +1,67 @@ +/// Source : https://leetcode.com/problems/average-of-levels-in-binary-tree/description/ +/// Author : liuyubobobo +/// Time : 2018-06-03 + +#include +#include +#include + +using namespace std; + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +/// BFS, using pairs +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector averageOfLevels(TreeNode* root) { + + vector res; + if(root == NULL) + return res; + + queue> q; + q.push(make_pair(root, 0)); + + long long sum = 0; + int lastLevel = 0; + int num = 0; + while(!q.empty()){ + pair cur = q.front(); + q.pop(); + + if(cur.second == lastLevel){ + sum += (long long)cur.first->val; + num ++; + } + else{ + res.push_back((double)sum / num); + sum = (long long)cur.first->val; + num = 1; + lastLevel = cur.second; + } + + if(cur.first->left != NULL) + q.push(make_pair(cur.first->left, cur.second + 1)); + if(cur.first->right != NULL) + q.push(make_pair(cur.first->right, cur.second + 1)); + } + if(num != 0) + res.push_back((double)sum / num); + + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0637-Average-of-Levels-in-Binary-Tree/cpp-0637/main2.cpp b/0501-1000/0637-Average-of-Levels-in-Binary-Tree/cpp-0637/main2.cpp new file mode 100644 index 00000000..eeb34709 --- /dev/null +++ b/0501-1000/0637-Average-of-Levels-in-Binary-Tree/cpp-0637/main2.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/average-of-levels-in-binary-tree/description/ +/// Author : liuyubobobo +/// Time : 2018-06-03 + +#include +#include +#include + +using namespace std; + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +/// BFS, not use pairs +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector averageOfLevels(TreeNode* root) { + + vector res; + if(root == NULL) + return res; + + queue q; + q.push(root); + + while(!q.empty()){ + + int num = q.size(); + long long sum = 0; + for(int i = 0 ; i < num ; i ++){ + TreeNode* cur = q.front(); + q.pop(); + sum += (long long)cur->val; + if(cur->left != NULL) + q.push(cur->left); + if(cur->right != NULL) + q.push(cur->right); + } + res.push_back((double)sum / num); + } + + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0637-Average-of-Levels-in-Binary-Tree/cpp-0637/main3.cpp b/0501-1000/0637-Average-of-Levels-in-Binary-Tree/cpp-0637/main3.cpp new file mode 100644 index 00000000..a64126ce --- /dev/null +++ b/0501-1000/0637-Average-of-Levels-in-Binary-Tree/cpp-0637/main3.cpp @@ -0,0 +1,66 @@ +/// Source : https://leetcode.com/problems/average-of-levels-in-binary-tree/description/ +/// Author : liuyubobobo +/// Time : 2018-06-03 + +#include +#include +#include + +using namespace std; + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector averageOfLevels(TreeNode* root) { + + vector res; + if(root == NULL) + return res; + + vector count; + + dfs(root, 0, res, count); + assert(res.size() == count.size()); + for(int i = 0 ; i < res.size() ; i ++) + res[i] /= count[i]; + + return res; + } + +private: + void dfs(TreeNode* node, int level, vector& res, vector& count){ + + if(node == NULL) + return; + + if(level < res.size()){ + res[level] += (double)node->val; + assert(level < count.size()); + count[level] += 1; + } + else{ + res.push_back((double)node->val); + count.push_back(1); + assert(res.size() == count.size()); + } + + dfs(node->left, level + 1, res, count); + dfs(node->right, level + 1, res, count); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0638-Shopping-Offers/cpp-0638/CMakeLists.txt b/0501-1000/0638-Shopping-Offers/cpp-0638/CMakeLists.txt new file mode 100644 index 00000000..40b629c1 --- /dev/null +++ b/0501-1000/0638-Shopping-Offers/cpp-0638/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0638) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0638 main.cpp) diff --git a/0501-1000/0638-Shopping-Offers/cpp-0638/main.cpp b/0501-1000/0638-Shopping-Offers/cpp-0638/main.cpp new file mode 100644 index 00000000..e4133969 --- /dev/null +++ b/0501-1000/0638-Shopping-Offers/cpp-0638/main.cpp @@ -0,0 +1,77 @@ +/// Source : https://leetcode.com/problems/shopping-offers/ +/// Author : liuyubobobo +/// Time : 2021-10-23 + +#include +#include +#include + +using namespace std; + + +/// Backpack +/// Memoization +/// Time Complexity: O((price[i] ^ n) * m) +/// Space Complexity: O(price[i] ^ n) +class Solution { +public: + int shoppingOffers(vector& prices, vector>& specials, vector& needs) { + + int n = prices.size(); + int m = specials.size(); + map, int> dp; + return dfs(n, needs, m, specials, prices, dp); + } + +private: + int dfs(int n, const vector& need, int m, const vector>& specials, + const vector& prices, map, int>& dp){ + + if(dp.count(need)) return dp[need]; + + int res = 0; + for(int i = 0; i < n; i ++) res += need[i] * prices[i]; + + for(int i = 0; i < m; i ++) + if(less_or_equals(n, specials[i], need)) + res = min(res, specials[i].back() + dfs(n, minus(n, need, specials[i]), m, specials, prices, dp)); + + return dp[need] = res; + } + + bool less_or_equals(int n, const vector& a, const vector& b){ + for(int i = 0; i < n; i ++) + if(a[i] > b[i]) return false; + return true; + } + + vector minus(int n, const vector& a, const vector& b){ + vector res(n); + for(int i = 0; i < n; i ++) res[i] = a[i] - b[i]; + return res; + } +}; + + +int main() { + + vector prices1 = {2, 5}; + vector> specials1 = {{3, 0, 5}, {1, 2, 10}}; + vector needs1= {3, 2}; + cout << Solution().shoppingOffers(prices1, specials1, needs1) << endl; + // 14 + + vector prices2 = {2, 3, 4}; + vector> specials2 = {{1, 1, 0, 4}, {2, 2, 1, 9}}; + vector needs2 = {1, 2, 1}; + cout << Solution().shoppingOffers(prices2, specials2, needs2) << endl; + // 11 + + vector prices3 = {0, 0, 0}; + vector> specials3 = {{1, 1, 0, 4}, {2, 2, 1, 9}}; + vector needs3 = {1, 1, 1}; + cout << Solution().shoppingOffers(prices3, specials3, needs3) << endl; + // 0 + + return 0; +} diff --git a/0501-1000/0639-Decode-Ways-II/cpp-0639/CMakeLists.txt b/0501-1000/0639-Decode-Ways-II/cpp-0639/CMakeLists.txt new file mode 100644 index 00000000..4108d42c --- /dev/null +++ b/0501-1000/0639-Decode-Ways-II/cpp-0639/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_0639) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0639 main.cpp) \ No newline at end of file diff --git a/0501-1000/0639-Decode-Ways-II/cpp-0639/main.cpp b/0501-1000/0639-Decode-Ways-II/cpp-0639/main.cpp new file mode 100644 index 00000000..56e46388 --- /dev/null +++ b/0501-1000/0639-Decode-Ways-II/cpp-0639/main.cpp @@ -0,0 +1,85 @@ +/// Source : https://leetcode.com/problems/decode-ways-ii/ +/// Author : liuyubobobo +/// Time : 2021-07-09 + +#include +#include + +using namespace std; + + +/// Memoization +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +private: + const long long MOD = 1e9 + 7; + +public: + int numDecodings(string s) { + + vector dp(s.size(), -1); + return dfs(s, 0, dp); + } + +private: + long long dfs(const string& s, int index, vector& dp){ + + if(index == s.size()) return 1ll; + if(dp[index] != -1) return dp[index]; + + if(s[index] == '0') return dp[index] = 0ll; + + long long res = 0ll; + if(s[index] != '*'){ + res = (res + dfs(s, index + 1, dp)) % MOD; + + if(index + 1 < s.size()){ + if(s[index] == '1') + res = (res + (long long)(s[index + 1] == '*' ? 9 : 1) * dfs(s, index + 2, dp)) % MOD; + else if(s[index] == '2') { + if(s[index + 1] == '*') + res = (res + 6ll * dfs(s, index + 2, dp)) % MOD; + else if(s[index + 1] <= '6') + res = (res + dfs(s, index + 2, dp)) % MOD; + } + } + } + else{ // == '*' + res = (res + 9ll * dfs(s, index + 1, dp)) % MOD; + + if(index + 1 < s.size()){ + if(s[index + 1] != '*'){ + if(s[index + 1] <= '6') + res = (res + 2ll * dfs(s, index + 2, dp)) % MOD; + else + res = (res + dfs(s, index + 2, dp)) % MOD; + } + else res = (res + 15ll * dfs(s, index + 2, dp)) % MOD; + } + } + return dp[index] = res; + } +}; + + +int main() { + + cout << Solution().numDecodings("*") << endl; + // 9 + + cout << Solution().numDecodings("1*") << endl; + // 18 + + cout << Solution().numDecodings("2*") << endl; + // 15 + + cout << Solution().numDecodings("**") << endl; + // 96 + + cout << Solution().numDecodings("2839") << endl; + // 1 + + return 0; +} diff --git a/0501-1000/0640-Solve-the-Equation/cpp-0640/CMakeLists.txt b/0501-1000/0640-Solve-the-Equation/cpp-0640/CMakeLists.txt new file mode 100644 index 00000000..6e8e27a2 --- /dev/null +++ b/0501-1000/0640-Solve-the-Equation/cpp-0640/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_0640) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0640 main.cpp) diff --git a/0501-1000/0640-Solve-the-Equation/cpp-0640/main.cpp b/0501-1000/0640-Solve-the-Equation/cpp-0640/main.cpp new file mode 100644 index 00000000..084e8df1 --- /dev/null +++ b/0501-1000/0640-Solve-the-Equation/cpp-0640/main.cpp @@ -0,0 +1,72 @@ +/// Source : https://leetcode.com/problems/solve-the-equation/ +/// Author : liuyubobobo +/// Time : 2022-08-10 + +#include +#include + +using namespace std; + + +/// Parse +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + string solveEquation(string equation) { + + char equal_pos = equation.find('='); + string left = equation.substr(0, equal_pos); + string right = equation.substr(equal_pos + 1); + + vector l_res = get_res(left); +// for(int e: l_res) cout << e << ' '; cout << '\n'; + vector r_res = get_res(right); +// for(int e: r_res) cout << e << ' '; cout << '\n'; + + int k = l_res[1] - r_res[1]; + int b = r_res[0] - l_res[0]; + + if(k == 0) + return b == 0 ? "Infinite solutions" : "No solution"; + + return "x=" + to_string(b / k); + } + +private: + vector get_res(const string& s){ + + vector res(2, 0); + for(int start = 0, i = 1; i <= s.size(); i ++) + if(i == s.size() || (s[i] == '+' || s[i] == '-')){ + string t = s.substr(start, i - start); + if(t[0] == '+') t = t.substr(1); + + if(t.back() == 'x'){ + if(t == "x") res[1] += 1; + else if(t == "-x") res[1] += -1; + else res[1] += atoi(t.substr(0, t.size() - 1).c_str()); + } + else + res[0] += atoi(t.c_str()); + + start = i; + } + return res; + } +}; + + +int main() { + + cout << Solution().solveEquation("x+5-3+x=6+x-2") << '\n'; + // x = 2 + + cout << Solution().solveEquation("2x=x") << '\n'; + // x = 0 + + cout << Solution().solveEquation("-x=-1") << '\n'; + // x = 1 + + return 0; +} diff --git a/0501-1000/0642-Design-Search-Autocomplete-System/cpp-0642/CMakeLists.txt b/0501-1000/0642-Design-Search-Autocomplete-System/cpp-0642/CMakeLists.txt new file mode 100644 index 00000000..2f7a38a1 --- /dev/null +++ b/0501-1000/0642-Design-Search-Autocomplete-System/cpp-0642/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(cpp_0642) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0642 main2.cpp) \ No newline at end of file diff --git a/0501-1000/0642-Design-Search-Autocomplete-System/cpp-0642/main.cpp b/0501-1000/0642-Design-Search-Autocomplete-System/cpp-0642/main.cpp new file mode 100644 index 00000000..f774f54f --- /dev/null +++ b/0501-1000/0642-Design-Search-Autocomplete-System/cpp-0642/main.cpp @@ -0,0 +1,73 @@ +/// Source : https://leetcode.com/problems/design-search-autocomplete-system/ +/// Author : liuyubobobo +/// Time : 2019-07-30 + +#include +#include +#include + +using namespace std; + + +/// Two level HashMap +/// Time Complexity: init: O(n) +/// input: O(n * l + nlogn) where l is len(cur) +/// Space Complexity: O(n + num_of_#) +class AutocompleteSystem { + +private: + vector> map; + string cur = ""; + +public: + AutocompleteSystem(vector& sentences, vector& times) { + + map.resize(26); + for(int i = 0; i < sentences.size(); i ++) + map[sentences[i][0] - 'a'][sentences[i]] = times[i]; + } + + vector input(char c) { + + if(c == '#'){ + map[cur[0] - 'a'][cur] ++; + cur = ""; + return {}; + } + + cur += c; + vector> candidates; + for(const pair& p: map[cur[0] - 'a']){ +// cout << p.first.find(cur) << endl; + if(p.first.find(cur) == 0) + candidates.push_back(make_pair(p.second, p.first)); + } + sort(candidates.begin(), candidates.end(), + [](const pair& p1, const pair& p2){ + if(p1.first != p2.first) return p1.first > p2.first; + return p1.second < p2.second; + }); + + vector res; + for(int i = 0; i < min((int)candidates.size(), 3); i ++) + res.push_back(candidates[i].second); + return res; + } +}; + + +void print_vec(const vector& vec){ + for(const string& e: vec) cout << e << endl; +} + +int main() { + + vector sentences = {"i love you","island","iroman","i love leetcode"}; + vector times = {5, 3, 2, 2}; + AutocompleteSystem sys(sentences, times); + print_vec(sys.input('i')); + print_vec(sys.input(' ')); + print_vec(sys.input('a')); + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0642-Design-Search-Autocomplete-System/cpp-0642/main2.cpp b/0501-1000/0642-Design-Search-Autocomplete-System/cpp-0642/main2.cpp new file mode 100644 index 00000000..5eca5cf5 --- /dev/null +++ b/0501-1000/0642-Design-Search-Autocomplete-System/cpp-0642/main2.cpp @@ -0,0 +1,117 @@ +/// Source : https://leetcode.com/problems/design-search-autocomplete-system/ +/// Author : liuyubobobo +/// Time : 2019-07-30 + +#include +#include +#include + +using namespace std; + + +/// Trie +/// Time Complexity: init: O(total_letters) +/// input: O(total_letters_in_trie + nlogn) +/// Space Complexity: O(total_letters_in_trie + num_of_input) +class Trie { + +private: + struct Node{ + unordered_map next; + int freq = 0; + }; + Node* root = new Node; + +public: + Trie(){} + + void insert(const string& word, int f){ + + Node* cur = root; + for(char c: word){ + if(cur->next.find(c) == cur->next.end()){ + cur->next[c] = new Node(); + } + + cur = cur->next[c]; + } + cur->freq += f; + } + + vector> startsWith(const string& prefix) { + + Node* cur = root; + for(char c: prefix){ + if(cur->next.find(c) == cur->next.end()) + return {}; + cur = cur->next[c]; + } + + vector> res; + dfs(cur, prefix, res); + return res; + } + +private: + void dfs(Node* cur, const string& s, vector>& res){ + + if(cur->freq) + res.push_back(make_pair(cur->freq, s)); + + for(const pair& p: cur->next) + dfs(p.second, s + p.first, res); + } +}; + + +class AutocompleteSystem { + + Trie trie; + string cur = ""; + +public: + AutocompleteSystem(vector& sentences, vector& times) { + + for(int i = 0; i < sentences.size(); i ++) + trie.insert(sentences[i], times[i]); + } + + vector input(char c) { + + if(c == '#'){ + trie.insert(cur, 1); + cur = ""; + return {}; + } + + cur += c; + vector> candidates = trie.startsWith(cur); + sort(candidates.begin(), candidates.end(), + [](const pair& p1, const pair& p2){ + if(p1.first != p2.first) return p1.first > p2.first; + return p1.second < p2.second; + }); + + vector res; + for(int i = 0; i < min((int)candidates.size(), 3); i ++) + res.push_back(candidates[i].second); + return res; + } +}; + + +void print_vec(const vector& vec){ + for(const string& e: vec) cout << e << endl; +} + +int main() { + + vector sentences = {"i love you","island","iroman","i love leetcode"}; + vector times = {5, 3, 2, 2}; + AutocompleteSystem sys(sentences, times); + print_vec(sys.input('i')); + print_vec(sys.input(' ')); + print_vec(sys.input('a')); + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0643-Maximum-Average-Subarray-I/cpp-0643/CMakeLists.txt b/0501-1000/0643-Maximum-Average-Subarray-I/cpp-0643/CMakeLists.txt new file mode 100644 index 00000000..18bf5ea9 --- /dev/null +++ b/0501-1000/0643-Maximum-Average-Subarray-I/cpp-0643/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0643) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0643 main.cpp) \ No newline at end of file diff --git a/0501-1000/0643-Maximum-Average-Subarray-I/cpp-0643/main.cpp b/0501-1000/0643-Maximum-Average-Subarray-I/cpp-0643/main.cpp new file mode 100644 index 00000000..e2098efc --- /dev/null +++ b/0501-1000/0643-Maximum-Average-Subarray-I/cpp-0643/main.cpp @@ -0,0 +1,38 @@ +/// Source : https://leetcode.com/problems/maximum-average-subarray-i/ +/// Author : liuyubobobo +/// Time : 2021-02-03 + +#include +#include +#include + +using namespace std; + + +/// Sliding Window +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + double findMaxAverage(vector& nums, int k) { + + int sum = accumulate(nums.begin(), nums.begin() + (k - 1), 0); + int maxsum = INT_MIN; + for(int i = k - 1; i < nums.size(); i ++){ + sum += nums[i]; + maxsum = max(maxsum, sum); + sum -= nums[i - (k - 1)]; + } + return (double)maxsum / k; + } +}; + + +int main() { + + vector nums1 = {8860,-853,6534,4477,-4589,8646,-6155,-5577,-1656,-5779,-2619,-8604,-1358,-8009,4983,7063,3104,-1560,4080,2763,5616,-2375,2848,1394,-7173,-5225,-8244,-809,8025,-4072,-4391,-9579,1407,6700,2421,-6685,5481,-1732,-8892,-6645,3077,3287,-4149,8701,-4393,-9070,-1777,2237,-3253,-506,-4931,-7366,-8132,5406,-6300,-275,-1908,67,3569,1433,-7262,-437,8303,4498,-379,3054,-6285,4203,6908,4433,3077,2288,9733,-8067,3007,9725,9669,1362,-2561,-4225,5442,-9006,-429,160,-9234,-4444,3586,-5711,-9506,-79,-4418,-4348,-5891}; + cout << Solution().findMaxAverage(nums1, 93) << endl; + // -594.58065 + + return 0; +} diff --git a/0501-1000/0644-Maximum-Average-Subarray-II/cpp-0644/CMakeLists.txt b/0501-1000/0644-Maximum-Average-Subarray-II/cpp-0644/CMakeLists.txt new file mode 100644 index 00000000..f1f0717d --- /dev/null +++ b/0501-1000/0644-Maximum-Average-Subarray-II/cpp-0644/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0644) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0644 main.cpp) \ No newline at end of file diff --git a/0501-1000/0644-Maximum-Average-Subarray-II/cpp-0644/main.cpp b/0501-1000/0644-Maximum-Average-Subarray-II/cpp-0644/main.cpp new file mode 100644 index 00000000..6f0d602a --- /dev/null +++ b/0501-1000/0644-Maximum-Average-Subarray-II/cpp-0644/main.cpp @@ -0,0 +1,67 @@ +/// Source : https://leetcode.com/problems/maximum-average-subarray-ii/ +/// Author : liuyubobobo +/// Time : 2021-02-05 + +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(nlog(maxv * 10^5)) +/// Space Complexity: O(1) +class Solution { +public: + double findMaxAverage(vector& nums, int k) { + + int minv = *min_element(nums.begin(), nums.end()); + int maxv = *max_element(nums.begin(), nums.end()); + + double l = minv, r = maxv; + while(r - l >= 1e-5){ +// cout << l << " " << r << endl; + double mid = (l + r) / 2.0; + if(ok(nums, k, mid)) l = mid; + else r = mid; + } + return l; + } + +private: + bool ok(const vector& nums, int k, double average){ + + double sum = 0.0; + for(int i = 0; i < k; i ++) + sum += nums[i] - average; + + if(sum >= 0) return true; + double premin = 0, presum = 0.0; + for(int i = k; i < nums.size(); i ++){ + sum += nums[i] - average; + presum += (nums[i - k] - average); + + premin = min(premin, presum); + if(sum - premin >= 0) return true; + } + return false; + } +}; + + +int main() { + + vector nums1 = {1,12,-5,-6,50,3}; + cout << Solution().findMaxAverage(nums1, 4) << endl; + // 12.75 + + vector nums2 = {5}; + cout << Solution().findMaxAverage(nums2, 1) << endl; + // 5 + + vector nums3 = {8,9,3,1,8,3,0,6,9,2}; + cout << Solution().findMaxAverage(nums3, 8) << endl; + // 5.22222 + + return 0; +} diff --git a/0501-1000/0645-Set-Mismatch/cpp-0645/CMakeLists.txt b/0501-1000/0645-Set-Mismatch/cpp-0645/CMakeLists.txt new file mode 100644 index 00000000..1686815f --- /dev/null +++ b/0501-1000/0645-Set-Mismatch/cpp-0645/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0645) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0645 main.cpp) \ No newline at end of file diff --git a/0501-1000/0645-Set-Mismatch/cpp-0645/main.cpp b/0501-1000/0645-Set-Mismatch/cpp-0645/main.cpp new file mode 100644 index 00000000..d3b3c9bd --- /dev/null +++ b/0501-1000/0645-Set-Mismatch/cpp-0645/main.cpp @@ -0,0 +1,39 @@ +/// Source : https://leetcode.com/problems/set-mismatch/ +/// Author : liuyubobobo +/// Time : 2021-03-02 + +#include +#include +#include + +using namespace std; + + +/// Using Hash Map +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector findErrorNums(vector& nums) { + + int n = nums.size(); + + vector res(2); + unordered_map f; + for(int e: nums){ + f[e] ++; + if(f[e] == 2) res[0] = e; + } + + for(int i = 1; i <= n; i ++) + if(!f.count(i)) res[1] = i; + + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0646-Maximum-Length-of-Pair-Chain/cpp-0646/CMakeLists.txt b/0501-1000/0646-Maximum-Length-of-Pair-Chain/cpp-0646/CMakeLists.txt new file mode 100644 index 00000000..97af3683 --- /dev/null +++ b/0501-1000/0646-Maximum-Length-of-Pair-Chain/cpp-0646/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_0646) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0646 main.cpp) diff --git a/0501-1000/0646-Maximum-Length-of-Pair-Chain/cpp-0646/main.cpp b/0501-1000/0646-Maximum-Length-of-Pair-Chain/cpp-0646/main.cpp new file mode 100644 index 00000000..d7582acc --- /dev/null +++ b/0501-1000/0646-Maximum-Length-of-Pair-Chain/cpp-0646/main.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/maximum-length-of-pair-chain/submissions/ +/// Author : liuyubobobo +/// Time : 2022-09-02 + +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(nlogn + n^2) +/// Space Complexity: O(n) +class Solution { +public: + int findLongestChain(vector>& pairs) { + + int n = pairs.size(); + sort(pairs.begin(), pairs.end()); + + vector dp(n, 1); + for(int i = n - 2; i >= 0; i --){ + for(int j = i + 1; j < n; j ++) + if(pairs[i][1] < pairs[j][0]) + dp[i] = max(dp[i], 1 + dp[j]); + } + return *max_element(dp.begin(), dp.end()); + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0647-Palindromic-Substrings/cpp-0647/CMakeLists.txt b/0501-1000/0647-Palindromic-Substrings/cpp-0647/CMakeLists.txt new file mode 100644 index 00000000..2a140eeb --- /dev/null +++ b/0501-1000/0647-Palindromic-Substrings/cpp-0647/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0647) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0647 main.cpp) \ No newline at end of file diff --git a/0501-1000/0647-Palindromic-Substrings/cpp-0647/main.cpp b/0501-1000/0647-Palindromic-Substrings/cpp-0647/main.cpp new file mode 100644 index 00000000..8e44dab0 --- /dev/null +++ b/0501-1000/0647-Palindromic-Substrings/cpp-0647/main.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/palindromic-substrings/ +/// Author : liuyubobobo +/// Time : 2021-03-27 + +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(n^2) +/// Space Complexity: O(n^2) +class Solution { +public: + int countSubstrings(string s) { + + vector> dp(s.size(), vector(s.size() + 1, true)); + + int res = s.size(); + for(int len = 2; len <= s.size(); len ++) + for(int i = 0; i + len <= s.size(); i ++) + if(s[i] == s[i + len - 1] && dp[i + 1][len - 2]) + res ++; + else dp[i][len] = false; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/0648-Replace-Words/cpp-0648/CMakeLists.txt b/0501-1000/0648-Replace-Words/cpp-0648/CMakeLists.txt similarity index 100% rename from 0648-Replace-Words/cpp-0648/CMakeLists.txt rename to 0501-1000/0648-Replace-Words/cpp-0648/CMakeLists.txt diff --git a/0648-Replace-Words/cpp-0648/main.cpp b/0501-1000/0648-Replace-Words/cpp-0648/main.cpp similarity index 100% rename from 0648-Replace-Words/cpp-0648/main.cpp rename to 0501-1000/0648-Replace-Words/cpp-0648/main.cpp diff --git a/0648-Replace-Words/cpp-0648/main2.cpp b/0501-1000/0648-Replace-Words/cpp-0648/main2.cpp similarity index 100% rename from 0648-Replace-Words/cpp-0648/main2.cpp rename to 0501-1000/0648-Replace-Words/cpp-0648/main2.cpp diff --git a/0501-1000/0649-Dota2-Senate/cpp-0649/CMakeLists.txt b/0501-1000/0649-Dota2-Senate/cpp-0649/CMakeLists.txt new file mode 100644 index 00000000..b8c58a4d --- /dev/null +++ b/0501-1000/0649-Dota2-Senate/cpp-0649/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0649) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0649 main.cpp) \ No newline at end of file diff --git a/0501-1000/0649-Dota2-Senate/cpp-0649/main.cpp b/0501-1000/0649-Dota2-Senate/cpp-0649/main.cpp new file mode 100644 index 00000000..8b42b706 --- /dev/null +++ b/0501-1000/0649-Dota2-Senate/cpp-0649/main.cpp @@ -0,0 +1,54 @@ +#include +#include +#include + +using namespace std; + + +class Solution { +public: + string predictPartyVictory(string senate) { + + int n = senate.size(); + vector ban(n, false); + + set R, D; + for(int i = 0; i < n; i ++) + if(senate[i] == 'R') R.insert(i); + else D.insert(i); + + int index = 0; + while(!R.empty() && !D.empty()){ + + if(!ban[index]){ + int banid; + if(senate[index] == 'R'){ + set::iterator iter = D.lower_bound(index); + if(iter == D.end()) iter = D.begin(); + banid = *iter; + D.erase(iter); + } + else{ + set::iterator iter = R.lower_bound(index); + if(iter == R.end()) iter = R.begin(); + banid = *iter; + R.erase(iter); + } + + ban[banid] = true; + } + + index = (index + 1) % n; + } + return R.empty() ? "Dire" : "Radiant"; + } +}; + + +int main() { + + cout << Solution().predictPartyVictory("DRRDRDRDRDDRDRDR") << endl; + // R + + return 0; +} diff --git a/0501-1000/0650-2-Keys-Keyboard/cpp-0650/CMakeLists.txt b/0501-1000/0650-2-Keys-Keyboard/cpp-0650/CMakeLists.txt new file mode 100644 index 00000000..1bac5779 --- /dev/null +++ b/0501-1000/0650-2-Keys-Keyboard/cpp-0650/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0650) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0650 main.cpp) diff --git a/0501-1000/0650-2-Keys-Keyboard/cpp-0650/main.cpp b/0501-1000/0650-2-Keys-Keyboard/cpp-0650/main.cpp new file mode 100644 index 00000000..27b7b2ee --- /dev/null +++ b/0501-1000/0650-2-Keys-Keyboard/cpp-0650/main.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/2-keys-keyboard/ +/// Author : liuyubobobo +/// Time : 2021-09-18 + +#include +#include + +using namespace std; + + +/// Memoization +/// Time Complexity: O(n^2) +/// Space Complexity: O(n^2) +class Solution { +public: + int minSteps(int n) { + + if(n == 1) return 0; + + vector> dp(n + 1, vector(n + 1, -1)); + return 1 + dfs(1, 1, n, dp); + } + +private: + int dfs(int cur, int copy, int n, vector>& dp){ + + if(cur == n) return 0; + if(cur > n) return INT_MAX / 2; + if(dp[cur][copy] != -1) return dp[cur][copy]; + + int res = INT_MAX / 2; + if(cur + copy <= n) + res = min(res, 1 + dfs(cur + copy, copy, n, dp)); + if(cur + cur <= n) + res = min(res, 2 + dfs(cur + cur, cur, n, dp)); + return dp[cur][copy] = res; + } +}; + + +int main() { + + cout << Solution().minSteps(3) << endl; + // 3 + + cout << Solution().minSteps(1) << endl; + // 1 + + return 0; +} diff --git a/0501-1000/0652-Find-Duplicate-Subtrees/cpp-0652/CMakeLists.txt b/0501-1000/0652-Find-Duplicate-Subtrees/cpp-0652/CMakeLists.txt new file mode 100644 index 00000000..a46fc24d --- /dev/null +++ b/0501-1000/0652-Find-Duplicate-Subtrees/cpp-0652/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0652) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main3.cpp) +add_executable(cpp_0652 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0652-Find-Duplicate-Subtrees/cpp-0652/main.cpp b/0501-1000/0652-Find-Duplicate-Subtrees/cpp-0652/main.cpp new file mode 100644 index 00000000..c0581bff --- /dev/null +++ b/0501-1000/0652-Find-Duplicate-Subtrees/cpp-0652/main.cpp @@ -0,0 +1,56 @@ +/// Source : https://leetcode.com/problems/find-duplicate-subtrees/description/ +/// Author : liuyubobobo +/// Time : 2018-10-05 + +#include +#include +#include + +using namespace std; + + +/// Serializae Binary Tree +/// Time Complexity: O(n^2) +/// Space Complexity: O(n^2) + +/// 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: + vector findDuplicateSubtrees(TreeNode* root) { + + vector res; + unordered_map map; + dfs(root, map, res); + return res; + } + +private: + string dfs(TreeNode* root, unordered_map& map, + vector& res){ + + if(!root) + return "(null)"; + + string left = dfs(root->left, map, res); + string right = dfs(root->right, map, res); + string hashcode = "(" + left + ")" + to_string(root->val) + "(" + right + ")"; + + if(map[hashcode] == 1) + res.push_back(root); + map[hashcode] ++; + return hashcode; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0652-Find-Duplicate-Subtrees/cpp-0652/main2.cpp b/0501-1000/0652-Find-Duplicate-Subtrees/cpp-0652/main2.cpp new file mode 100644 index 00000000..13f7157d --- /dev/null +++ b/0501-1000/0652-Find-Duplicate-Subtrees/cpp-0652/main2.cpp @@ -0,0 +1,58 @@ +/// Source : https://leetcode.com/problems/find-duplicate-subtrees/description/ +/// Author : liuyubobobo +/// Time : 2018-10-05 + +#include +#include +#include + +using namespace std; + + +/// Serializae Binary Tree +/// Using another easier hashcode +/// +/// Time Complexity: O(n^2) +/// Space Complexity: O(n^2) + +/// 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: + vector findDuplicateSubtrees(TreeNode* root) { + + vector res; + unordered_map map; + dfs(root, map, res); + return res; + } + +private: + string dfs(TreeNode* root, unordered_map& map, + vector& res){ + + if(!root) + return "#"; + + string left = dfs(root->left, map, res); + string right = dfs(root->right, map, res); + string hashcode = to_string(root->val) + "," + left + "," + right; + + if(map[hashcode] == 1) + res.push_back(root); + map[hashcode] ++; + return hashcode; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0652-Find-Duplicate-Subtrees/cpp-0652/main3.cpp b/0501-1000/0652-Find-Duplicate-Subtrees/cpp-0652/main3.cpp new file mode 100644 index 00000000..4e6a4e8b --- /dev/null +++ b/0501-1000/0652-Find-Duplicate-Subtrees/cpp-0652/main3.cpp @@ -0,0 +1,68 @@ +/// Source : https://leetcode.com/problems/find-duplicate-subtrees/description/ +/// Author : liuyubobobo +/// Time : 2018-10-05 + +#include +#include +#include + +using namespace std; + + +/// Serializae Binary Tree +/// Using global id key to mark each subtree +/// +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// 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 { + +private: + int id = 1; + +public: + vector findDuplicateSubtrees(TreeNode* root) { + + id = 1; + vector res; + unordered_map map; + unordered_map freq; + dfs(root, map, freq, res); + return res; + } + +private: + int dfs(TreeNode* root, unordered_map& map, + unordered_map& freq, vector& res){ + + if(!root) + return 0; + + int lid = dfs(root->left, map, freq, res); + int rid = dfs(root->right, map, freq, res); + + string hashcode = to_string(lid) + "#" + to_string(root->val) + "#" + to_string(rid); + if(!map.count(hashcode)) + map[hashcode] = id ++; + + int rootID = map[hashcode]; + if(freq[rootID] == 1) + res.push_back(root); + freq[rootID] ++; + return rootID; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0653-Two-Sum-IV-Input-is-a-BST/cpp-0653/CMakeLists.txt b/0501-1000/0653-Two-Sum-IV-Input-is-a-BST/cpp-0653/CMakeLists.txt new file mode 100644 index 00000000..f3eaf285 --- /dev/null +++ b/0501-1000/0653-Two-Sum-IV-Input-is-a-BST/cpp-0653/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_0653) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0653 main.cpp) diff --git a/0501-1000/0653-Two-Sum-IV-Input-is-a-BST/cpp-0653/main.cpp b/0501-1000/0653-Two-Sum-IV-Input-is-a-BST/cpp-0653/main.cpp new file mode 100644 index 00000000..6b2fe3b7 --- /dev/null +++ b/0501-1000/0653-Two-Sum-IV-Input-is-a-BST/cpp-0653/main.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/two-sum-iv-input-is-a-bst/ +/// Author : liuyubobobo +/// Time : 2022-03-20 + +#include +#include + +using namespace std; + + +/// Using Set +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// 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 { + +private: + unordered_set table; + +public: + bool findTarget(TreeNode* root, int k) { + + table.clear(); + return dfs(root, k); + } + +private: + bool dfs(TreeNode* node, int t){ + + if(!node) return false; + + if(table.count(t - node->val)) return true; + table.insert(node->val); + return dfs(node->left, t) || dfs(node->right, t); + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0654-Maximum-Binary-Tree/cpp-0654/CMakeLists.txt b/0501-1000/0654-Maximum-Binary-Tree/cpp-0654/CMakeLists.txt new file mode 100644 index 00000000..c30d7ed3 --- /dev/null +++ b/0501-1000/0654-Maximum-Binary-Tree/cpp-0654/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_0654) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0654 main.cpp) diff --git a/0501-1000/0654-Maximum-Binary-Tree/cpp-0654/main.cpp b/0501-1000/0654-Maximum-Binary-Tree/cpp-0654/main.cpp new file mode 100644 index 00000000..bc6d84b7 --- /dev/null +++ b/0501-1000/0654-Maximum-Binary-Tree/cpp-0654/main.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/maximum-binary-tree/ +/// Author : liuyubobobo +/// Time : 2022-08-19 + +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) + +/// 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* constructMaximumBinaryTree(vector& nums) { + + int n = nums.size(); + return construct(nums, 0, n - 1); + } + +private: + TreeNode* construct(const vector& nums, int l, int r){ + + if(l > r) return nullptr; + + int max_index = max_element(nums.begin() + l, nums.begin() + (r + 1)) - nums.begin(); + TreeNode* ret = new TreeNode(nums[max_index]); + ret->left = construct(nums, l, max_index - 1); + ret->right = construct(nums, max_index + 1, r); + return ret; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0655-Print-Binary-Tree/cpp-0655/CMakeLists.txt b/0501-1000/0655-Print-Binary-Tree/cpp-0655/CMakeLists.txt new file mode 100644 index 00000000..91a702f6 --- /dev/null +++ b/0501-1000/0655-Print-Binary-Tree/cpp-0655/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_0655) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0655 main.cpp) diff --git a/0501-1000/0655-Print-Binary-Tree/cpp-0655/main.cpp b/0501-1000/0655-Print-Binary-Tree/cpp-0655/main.cpp new file mode 100644 index 00000000..1af87ef6 --- /dev/null +++ b/0501-1000/0655-Print-Binary-Tree/cpp-0655/main.cpp @@ -0,0 +1,63 @@ +/// Source : https://leetcode.com/problems/print-binary-tree/ +/// Author : liuyubobobo +/// Time : 2022-08-21 + +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(h) + +/// 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> printTree(TreeNode* root) { + + int d = dfs_depth(root); + + vector> res(d, vector((1 << d) - 1, "")); + dfs(root, 0, 0, (1 << d) - 1, res); + return res; + } + +private: + void dfs(TreeNode* node, int d, int l, int r, vector>& res){ + + if(!node) return; + + int mid = l + (r - l) / 2; + res[d][mid] = to_string(node->val); + + dfs(node->left, d + 1, l, mid - 1, res); + dfs(node->right, d + 1, mid + 1, r, res); + } + + int dfs_depth(TreeNode* node){ + + if(!node) return 0; + + int res = 0; + res = max(res, dfs_depth(node->left)); + res = max(res, dfs_depth(node->right)); + return res + 1; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0658-Find-K-Closest-Elements/cpp-0658/CMakeLists.txt b/0501-1000/0658-Find-K-Closest-Elements/cpp-0658/CMakeLists.txt new file mode 100644 index 00000000..318c0082 --- /dev/null +++ b/0501-1000/0658-Find-K-Closest-Elements/cpp-0658/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_0658) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0658 main.cpp) \ No newline at end of file diff --git a/0501-1000/0658-Find-K-Closest-Elements/cpp-0658/main.cpp b/0501-1000/0658-Find-K-Closest-Elements/cpp-0658/main.cpp new file mode 100644 index 00000000..4755560f --- /dev/null +++ b/0501-1000/0658-Find-K-Closest-Elements/cpp-0658/main.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/find-k-closest-elements/ +/// Author : liuyubobobo +/// Time : 2021-07-01 + +#include +#include + +using namespace std; + + +/// Sorting +/// Time Complexity: O(nlogn + klogk) +/// Space Complexity: O(1) +class Solution { +public: + vector findClosestElements(vector& arr, int k, int x) { + + sort(arr.begin(), arr.end(), [&](int a, int b){ + if(abs(a - x) != abs(b - x)) return abs(a - x) < abs(b - x); + return a < b; + }); + + vector res = vector(arr.begin(), arr.begin() + k); + sort(res.begin(), res.end()); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0659-Split-Array-into-Consecutive-Subsequences/cpp-0659/CMakeLists.txt b/0501-1000/0659-Split-Array-into-Consecutive-Subsequences/cpp-0659/CMakeLists.txt new file mode 100644 index 00000000..108157f1 --- /dev/null +++ b/0501-1000/0659-Split-Array-into-Consecutive-Subsequences/cpp-0659/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0659) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0659 main2.cpp) \ No newline at end of file diff --git a/0501-1000/0659-Split-Array-into-Consecutive-Subsequences/cpp-0659/main.cpp b/0501-1000/0659-Split-Array-into-Consecutive-Subsequences/cpp-0659/main.cpp new file mode 100644 index 00000000..a689d9b6 --- /dev/null +++ b/0501-1000/0659-Split-Array-into-Consecutive-Subsequences/cpp-0659/main.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/split-array-into-consecutive-subsequences/ +/// Author : liuyubobobo +/// Time : 2020-12-03 + +#include +#include +#include +#include + +using namespace std; + + +/// HashTable + Priority Queue +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + bool isPossible(vector& nums) { + + unordered_map, greater>> table; + for(int e: nums) + if(!table.count(e - 1)) table[e].push(1); + else{ + int len = table[e - 1].top(); + table[e - 1].pop(); + if(table[e - 1].empty()) table.erase(e - 1); + table[e].push(len + 1); + } + + for(const pair, greater>>& p: table){ + priority_queue, greater> pq = p.second; + while(!pq.empty()){ + if(pq.top() < 3) return false; + pq.pop(); + } + } + return true; + } +}; + + +int main() { + + vector nums1 = {1, 2, 3, 3, 4, 5}; + cout << Solution().isPossible(nums1) << endl; + // 1 + + vector nums2 = {1,2,3,3,4,4,5,5}; + cout << Solution().isPossible(nums2) << endl; + // 1 + + vector nums3 = {1,2,3,4,4,5}; + cout << Solution().isPossible(nums3) << endl; + // 0 + + return 0; +} diff --git a/0501-1000/0659-Split-Array-into-Consecutive-Subsequences/cpp-0659/main2.cpp b/0501-1000/0659-Split-Array-into-Consecutive-Subsequences/cpp-0659/main2.cpp new file mode 100644 index 00000000..79f8142a --- /dev/null +++ b/0501-1000/0659-Split-Array-into-Consecutive-Subsequences/cpp-0659/main2.cpp @@ -0,0 +1,56 @@ +/// Source : https://leetcode.com/problems/split-array-into-consecutive-subsequences/ +/// Author : liuyubobobo +/// Time : 2020-12-03 + +#include +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + bool isPossible(vector& nums) { + + unordered_map left; + for(int e: nums) left[e] ++; + + unordered_map ending; + for(int e: nums) + if(left[e]){ + if(ending[e - 1] > 0){ + ending[e - 1] --; + ending[e] ++; + left[e] --; + } + else{ + if(!left[e + 1] || !left[e + 2]) return false; + left[e] --, left[e + 1] --, left[e + 2] --; + ending[e + 2] ++; + } + } + return true; + } +}; + + +int main() { + + vector nums1 = {1, 2, 3, 3, 4, 5}; + cout << Solution().isPossible(nums1) << endl; + // 1 + + vector nums2 = {1,2,3,3,4,4,5,5}; + cout << Solution().isPossible(nums2) << endl; + // 1 + + vector nums3 = {1,2,3,4,4,5}; + cout << Solution().isPossible(nums3) << endl; + // 0 + + return 0; +} diff --git a/0501-1000/0661-Image-Smoother/cpp-0661/CMakeLists.txt b/0501-1000/0661-Image-Smoother/cpp-0661/CMakeLists.txt new file mode 100644 index 00000000..f8279eac --- /dev/null +++ b/0501-1000/0661-Image-Smoother/cpp-0661/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_0661) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0661 main.cpp) diff --git a/0501-1000/0661-Image-Smoother/cpp-0661/main.cpp b/0501-1000/0661-Image-Smoother/cpp-0661/main.cpp new file mode 100644 index 00000000..6538ee30 --- /dev/null +++ b/0501-1000/0661-Image-Smoother/cpp-0661/main.cpp @@ -0,0 +1,45 @@ +/// Source : https://leetcode.com/problems/image-smoother/ +/// Author : liuyubobobo +/// Time : 2022-03-23 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(R * C) +/// Space Complexity: O(1) +class Solution { +private: + int R, C; + +public: + vector> imageSmoother(vector>& img) { + + R = img.size(), C = img[0].size(); + vector> res(R, vector(C)); + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++){ + int sum = 0, cnt = 0; + for(int r = -1; r <= 1; r ++) + for(int c = -1; c <= 1; c ++) + if(in_area(i + r, j + c)) + sum += img[i + r][j + c], cnt ++; + res[i][j] = sum / cnt; + } + return res; + } + +private: + bool in_area(int x, int y){ + return 0 <= x && x < R && 0 <= y && y < C; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0662-Maximum-Width-of-Binary-Tree/cpp-0662/CMakeLists.txt b/0501-1000/0662-Maximum-Width-of-Binary-Tree/cpp-0662/CMakeLists.txt new file mode 100644 index 00000000..8e5f9d1f --- /dev/null +++ b/0501-1000/0662-Maximum-Width-of-Binary-Tree/cpp-0662/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_0662) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0662 main2.cpp) diff --git a/0501-1000/0662-Maximum-Width-of-Binary-Tree/cpp-0662/main.cpp b/0501-1000/0662-Maximum-Width-of-Binary-Tree/cpp-0662/main.cpp new file mode 100644 index 00000000..b7da22b3 --- /dev/null +++ b/0501-1000/0662-Maximum-Width-of-Binary-Tree/cpp-0662/main.cpp @@ -0,0 +1,68 @@ +/// Source : https://leetcode.com/problems/maximum-width-of-binary-tree/ +/// Author : liuyubobobo +/// Time : 2022-02-27 + +#include +#include +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// 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: + int widthOfBinaryTree(TreeNode* root) { + + int max_depth = get_depth(root); + + vector left(max_depth, ULONG_LONG_MAX), right(max_depth,0); + dfs(root, 0, 0, left, right); + + long long res = 0; + for(int i = 0; i < max_depth; i ++){ + res = max(res, (long long)(right[i] - left[i] + 1)); + } + return res; + } + +private: + void dfs(TreeNode* node, int d, unsigned long long num, + vector& left, vector& right){ + + if(!node) return; + + left[d] = min(left[d], num); + right[d] = max(right[d], num); + + dfs(node->left, d + 1, num * 2, left, right); + dfs(node->right, d + 1, num * 2 + 1, left, right); + } + + int get_depth(TreeNode* node){ + + if(!node) return 0; + + return 1 + max(get_depth(node->left), get_depth(node->right)); + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0662-Maximum-Width-of-Binary-Tree/cpp-0662/main2.cpp b/0501-1000/0662-Maximum-Width-of-Binary-Tree/cpp-0662/main2.cpp new file mode 100644 index 00000000..8e471089 --- /dev/null +++ b/0501-1000/0662-Maximum-Width-of-Binary-Tree/cpp-0662/main2.cpp @@ -0,0 +1,68 @@ +/// Source : https://leetcode.com/problems/maximum-width-of-binary-tree/ +/// Author : liuyubobobo +/// Time : 2022-08-26 + +#include +#include +#include +#include + +using namespace std; + + +/// BFS +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// 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: + int widthOfBinaryTree(TreeNode* root) { + + queue> q; + q.push({root, 0}); + vector list; + + unsigned long long res = 0; + while(!q.empty()){ + + vector> v; + while(!q.empty()){ + TreeNode* node = q.front().first; + unsigned long long seq = q.front().second; + q.pop(); + v.push_back({node, seq}); + } + + res = max(res, v.back().second - v.begin()->second + 1); + + for(const pair& p: v){ + TreeNode* node = p.first; + unsigned long long seq = p.second; + + if(node->left) + q.push({node->left, seq * 2}); + + if(node->right) + q.push({node->right, seq * 2 + 1}); + } + + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0663-Equal-Tree-Partition/cpp-0663/CMakeLists.txt b/0501-1000/0663-Equal-Tree-Partition/cpp-0663/CMakeLists.txt new file mode 100644 index 00000000..3af9913e --- /dev/null +++ b/0501-1000/0663-Equal-Tree-Partition/cpp-0663/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0663) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0663 main.cpp) diff --git a/0501-1000/0663-Equal-Tree-Partition/cpp-0663/main.cpp b/0501-1000/0663-Equal-Tree-Partition/cpp-0663/main.cpp new file mode 100644 index 00000000..cf02d5c5 --- /dev/null +++ b/0501-1000/0663-Equal-Tree-Partition/cpp-0663/main.cpp @@ -0,0 +1,54 @@ +#include +#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 checkEqualTree(TreeNode* root) { + + unordered_map map; + dfs_sum(root, map); + + return dfs(root, map, map[root]); + } + +private: + bool dfs(TreeNode* node, const unordered_map& map, int sum){ + + if(node == nullptr) return false; + + if(node->left && map.find(node->left)->second * 2 == sum) return true; + if(node->right && map.find(node->right)->second * 2 == sum) return true; + + return dfs(node->left, map, sum) || dfs(node->right, map, sum); + } + + int dfs_sum(TreeNode* node, unordered_map& map){ + + if(node == nullptr) return 0; + + int res = node->val; + res += dfs_sum(node->left, map); + res += dfs_sum(node->right, map); + map[node] = res; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0664-Strange-Printer/cpp-0664/CMakeLists.txt b/0501-1000/0664-Strange-Printer/cpp-0664/CMakeLists.txt new file mode 100644 index 00000000..97d79c19 --- /dev/null +++ b/0501-1000/0664-Strange-Printer/cpp-0664/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0664) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0664 main.cpp) \ No newline at end of file diff --git a/0501-1000/0664-Strange-Printer/cpp-0664/main.cpp b/0501-1000/0664-Strange-Printer/cpp-0664/main.cpp new file mode 100644 index 00000000..70895703 --- /dev/null +++ b/0501-1000/0664-Strange-Printer/cpp-0664/main.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/strange-printer/ +/// Author : liuyubobobo +/// Time : 2020-10-16 + +#include +#include + +using namespace std; + + +/// Interval DP +/// Time Complexity: O(n^3) +/// Space Complexity: O(n^2) +class Solution { +public: + int strangePrinter(string s) { + + vector> dp(s.size(), vector(s.size(), -1)); + return dfs(s, 0, s.size() - 1, dp); + } + +private: + int dfs(const string& s, int l, int r, vector>& dp){ + + if(l > r) return 0; + if(l == r) return 1; + + if(dp[l][r] != -1) return dp[l][r]; + + int res = 1 + dfs(s, l + 1, r, dp); + for(int i = l + 1; i <= r; i ++) + if(s[i] == s[l]) + res = min(res, dfs(s, l, i - 1, dp) + dfs(s, i + 1, r, dp)); + return dp[l][r] = res; + } +}; + + +int main() { + + cout << Solution().strangePrinter("aaabbb") << endl; + // 2 + + cout << Solution().strangePrinter("aba") << endl; + // 2 + + cout << Solution().strangePrinter("aaaaaaaaaaaaaaaaaaaaa") << endl; + // 1 + + cout << Solution().strangePrinter("baacdddaaddaaaaccbddbcabdaabdbbcdcbbbacbddcabcaaa") << endl; + // 19 + + cout << Solution().strangePrinter("dddccbdbababaddcbcaabdbdddcccddbbaabddb") << endl; + // 15 + + return 0; +} diff --git a/0501-1000/0665-Non-decreasing-Array/cpp-0665/CMakeLists.txt b/0501-1000/0665-Non-decreasing-Array/cpp-0665/CMakeLists.txt new file mode 100644 index 00000000..66a38682 --- /dev/null +++ b/0501-1000/0665-Non-decreasing-Array/cpp-0665/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0665) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0665 main.cpp) \ No newline at end of file diff --git a/0501-1000/0665-Non-decreasing-Array/cpp-0665/main.cpp b/0501-1000/0665-Non-decreasing-Array/cpp-0665/main.cpp new file mode 100644 index 00000000..f8f938e6 --- /dev/null +++ b/0501-1000/0665-Non-decreasing-Array/cpp-0665/main.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/non-decreasing-array/ +/// Author : liuyubobobo +/// Time : 2021-02-06 + +#include +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + bool checkPossibility(vector& nums) { + + int i = 0; + for(i = 1; i < nums.size(); i ++) + if(nums[i] < nums[i - 1]) break; + + if(i == nums.size()) return true; + + for(int j = i + 1; j < nums.size(); j ++) + if(nums[j] < nums[j - 1]) return false; + + return i - 1 == 0 || + i + 1 == nums.size() || + nums[i - 1] <= nums[i + 1] || + (i - 2 >= 0 && nums[i - 2] <= nums[i]); + } +}; + + +int main() { + + vector nums1 = {4, 2, 1}; + cout << Solution().checkPossibility(nums1) << endl; + // 0 + + vector nums2 = {-1, 4, 2, 3}; + cout << Solution().checkPossibility(nums2) << endl; + // 1 + + return 0; +} diff --git a/0501-1000/0666-Path-Sum-IV/cpp-0666/CMakeLists.txt b/0501-1000/0666-Path-Sum-IV/cpp-0666/CMakeLists.txt new file mode 100644 index 00000000..49dda4fa --- /dev/null +++ b/0501-1000/0666-Path-Sum-IV/cpp-0666/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_0666) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0666 main.cpp) \ No newline at end of file diff --git a/0501-1000/0666-Path-Sum-IV/cpp-0666/main.cpp b/0501-1000/0666-Path-Sum-IV/cpp-0666/main.cpp new file mode 100644 index 00000000..1b586b36 --- /dev/null +++ b/0501-1000/0666-Path-Sum-IV/cpp-0666/main.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/path-sum-iv/ +/// Author : liuyubobobo +/// Time : 2021-05-19 + +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(8 * 4) +/// Space Complexity: O(8 * 4) +class Solution { +public: + int pathSum(vector& nums) { + + vector> tree(4, vector(8, -1)); + for(int e: nums){ + int d = e / 100 - 1; + int p = (e % 100) / 10 - 1; + int v = e % 10; + tree[d][p] = v; + } + + int cur = 0; + return dfs(0, 0, tree, cur); + } + +private: + int dfs(int r, int c, vector>& tree, int cur){ + + if(r == 3 || tree[r + 1][2 * c] == -1 && tree[r + 1][2 * c + 1] == -1) + return tree[r][c] + cur; + + int res = 0; + if(tree[r + 1][2 * c] != -1) + res += dfs(r + 1, 2 * c, tree, cur + tree[r][c]); + if(tree[r + 1][2 * c + 1] != -1) + res += dfs(r + 1, 2 * c + 1, tree, cur + tree[r][c]); + return res; + } +}; + + +int main() { + + vector nums1 = {113,229,330,466}; + cout << Solution().pathSum(nums1) << endl; + // 18 + + vector nums2 = {113,229,349,470,485}; + cout << Solution().pathSum(nums2) << endl; + // 47 + + return 0; +} diff --git a/0501-1000/0667-Beautiful-Arrangement-II/cpp-0667/CMakeLists.txt b/0501-1000/0667-Beautiful-Arrangement-II/cpp-0667/CMakeLists.txt new file mode 100644 index 00000000..ca09fce9 --- /dev/null +++ b/0501-1000/0667-Beautiful-Arrangement-II/cpp-0667/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0667) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0667 main.cpp) \ No newline at end of file diff --git a/0501-1000/0667-Beautiful-Arrangement-II/cpp-0667/main.cpp b/0501-1000/0667-Beautiful-Arrangement-II/cpp-0667/main.cpp new file mode 100644 index 00000000..570ba596 --- /dev/null +++ b/0501-1000/0667-Beautiful-Arrangement-II/cpp-0667/main.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/beautiful-arrangement-ii/ +/// Author : liuyubobobo +/// Time : 2021-01-03 + +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + vector constructArray(int n, int k) { + + vector arr(n); + + int l = 1, r = n; + for(int i = 0; i < k; i += 2){ + arr[i] = l ++; + if(i + 1 == k){ + for(int j = k; j < n; j ++) arr[j] = l ++; + break; + } + + arr[i + 1] = r --; + if(i + 2 == k){ + for(int j = k; j < n; j ++) arr[j] = r --; + break; + } + } + + return arr; + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << " "; cout << endl; +} + +int main() { + + print_vec(Solution().constructArray(3, 1)); + // 1 2 3 + + print_vec(Solution().constructArray(3, 2)); + // 1 3 2 + + return 0; +} diff --git a/0501-1000/0668-Kth-Smallest-Number-in-Multiplication-Table/cpp-0668/CMakeLists.txt b/0501-1000/0668-Kth-Smallest-Number-in-Multiplication-Table/cpp-0668/CMakeLists.txt new file mode 100644 index 00000000..bdeec7ff --- /dev/null +++ b/0501-1000/0668-Kth-Smallest-Number-in-Multiplication-Table/cpp-0668/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(cpp_0668) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0668 main.cpp) \ No newline at end of file diff --git a/0501-1000/0668-Kth-Smallest-Number-in-Multiplication-Table/cpp-0668/main.cpp b/0501-1000/0668-Kth-Smallest-Number-in-Multiplication-Table/cpp-0668/main.cpp new file mode 100644 index 00000000..32221ff7 --- /dev/null +++ b/0501-1000/0668-Kth-Smallest-Number-in-Multiplication-Table/cpp-0668/main.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/kth-smallest-number-in-multiplication-table/ +/// Author : liuyubobobo +/// Time : 2020-04-24 + +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(m * log(m * n)) +/// Space Complexity: O(1) +class Solution { +public: + int findKthNumber(int m, int n, int k) { + + int l = 1, r = m * n + 1; + while(l < r){ + int mid = (l + r) / 2; + int rank = get(mid, m, n); + if(rank < k) l = mid + 1; + else r = mid; + } + return l; + } + +private: + int get(int x, int m, int n){ + + int res = 0; + for(int i = 1; i <= m; i ++) + res += min(x / i, n); + return res; + } +}; + + +int main() { + + cout << Solution().findKthNumber(3, 3, 5) << endl; + // 3 + + cout << Solution().findKthNumber(2, 3, 6) << endl; + // 6 + + cout << Solution().findKthNumber(42, 34, 401) << endl; + // 126 + + return 0; +} diff --git a/0501-1000/0669-Trim-a-Binary-Search-Tree/cpp-0669/CMakeLists.txt b/0501-1000/0669-Trim-a-Binary-Search-Tree/cpp-0669/CMakeLists.txt new file mode 100644 index 00000000..4fb6e393 --- /dev/null +++ b/0501-1000/0669-Trim-a-Binary-Search-Tree/cpp-0669/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0669) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0669 main.cpp) \ No newline at end of file diff --git a/0501-1000/0669-Trim-a-Binary-Search-Tree/cpp-0669/main.cpp b/0501-1000/0669-Trim-a-Binary-Search-Tree/cpp-0669/main.cpp new file mode 100644 index 00000000..199fef42 --- /dev/null +++ b/0501-1000/0669-Trim-a-Binary-Search-Tree/cpp-0669/main.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/two-sum/description/ +/// Author : liuyubobobo +/// Time : 2017-11-15 + +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(h) + +/// 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* trimBST(TreeNode* root, int low, int high) { + + root = trim(root, low, high); + return root; + } + +private: + TreeNode* trim(TreeNode* node, int low, int high){ + + if(!node) return NULL; + if(node->val < low) return trim(node->right, low, high); + if(node->val > high) return trim(node->left, low, high); + + node->left = trim(node->left, low, high); + node->right = trim(node->right, low, high); + return node; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0670-Maximum-Swap/cpp-0670/CMakeLists.txt b/0501-1000/0670-Maximum-Swap/cpp-0670/CMakeLists.txt new file mode 100644 index 00000000..c33ca0a9 --- /dev/null +++ b/0501-1000/0670-Maximum-Swap/cpp-0670/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_0670) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0670 main.cpp) diff --git a/0501-1000/0670-Maximum-Swap/cpp-0670/main.cpp b/0501-1000/0670-Maximum-Swap/cpp-0670/main.cpp new file mode 100644 index 00000000..e32a7b13 --- /dev/null +++ b/0501-1000/0670-Maximum-Swap/cpp-0670/main.cpp @@ -0,0 +1,36 @@ +/// Source : https://leetcode.com/problems/maximum-swap/ +/// Author : liuyubobobo +/// Time : 2022-09-12 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O((log(num))^2) +/// Space Complexity: O(log(num)) +class Solution { +public: + int maximumSwap(int num) { + + if(num < 10) return num; + + string num_s = to_string(num); + for(int i = 0; i < num_s.size(); i ++) + for(int j = i + 1; j < num_s.size(); j ++){ + swap(num_s[i], num_s[j]); + int x = atoi(num_s.c_str()); + num = max(num, x); + swap(num_s[i], num_s[j]); + } + return num; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0671-Second-Minimum-Node-In-a-Binary-Tree/cpp-0671/CMakeLists.txt b/0501-1000/0671-Second-Minimum-Node-In-a-Binary-Tree/cpp-0671/CMakeLists.txt new file mode 100644 index 00000000..f483cecf --- /dev/null +++ b/0501-1000/0671-Second-Minimum-Node-In-a-Binary-Tree/cpp-0671/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_0671) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0671 main.cpp) \ No newline at end of file diff --git a/0501-1000/0671-Second-Minimum-Node-In-a-Binary-Tree/cpp-0671/main.cpp b/0501-1000/0671-Second-Minimum-Node-In-a-Binary-Tree/cpp-0671/main.cpp new file mode 100644 index 00000000..661bde5e --- /dev/null +++ b/0501-1000/0671-Second-Minimum-Node-In-a-Binary-Tree/cpp-0671/main.cpp @@ -0,0 +1,46 @@ +#include +#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: + int findSecondMinimumValue(TreeNode* root) { + + set set; + dfs(root, set); + + if(set.size() == 1) return -1; + + auto iter = set.begin(); + iter ++; + return *iter; + } + +private: + void dfs(TreeNode* node, set& set){ + + if(!node) return; + + set.insert(node->val); + dfs(node->left, set); + dfs(node->right, set); + } +}; + + +int main() { + + return 0; +} diff --git a/0672-Bulb-Switcher-II/cpp-0672/CMakeLists.txt b/0501-1000/0672-Bulb-Switcher-II/cpp-0672/CMakeLists.txt similarity index 100% rename from 0672-Bulb-Switcher-II/cpp-0672/CMakeLists.txt rename to 0501-1000/0672-Bulb-Switcher-II/cpp-0672/CMakeLists.txt diff --git a/0672-Bulb-Switcher-II/cpp-0672/main.cpp b/0501-1000/0672-Bulb-Switcher-II/cpp-0672/main.cpp similarity index 100% rename from 0672-Bulb-Switcher-II/cpp-0672/main.cpp rename to 0501-1000/0672-Bulb-Switcher-II/cpp-0672/main.cpp diff --git a/0672-Bulb-Switcher-II/cpp-0672/main2.cpp b/0501-1000/0672-Bulb-Switcher-II/cpp-0672/main2.cpp similarity index 100% rename from 0672-Bulb-Switcher-II/cpp-0672/main2.cpp rename to 0501-1000/0672-Bulb-Switcher-II/cpp-0672/main2.cpp diff --git a/0673-Number-of-Longest-Increasing-Subsequence/cpp-0673/CMakeLists.txt b/0501-1000/0673-Number-of-Longest-Increasing-Subsequence/cpp-0673/CMakeLists.txt similarity index 100% rename from 0673-Number-of-Longest-Increasing-Subsequence/cpp-0673/CMakeLists.txt rename to 0501-1000/0673-Number-of-Longest-Increasing-Subsequence/cpp-0673/CMakeLists.txt diff --git a/0673-Number-of-Longest-Increasing-Subsequence/cpp-0673/main.cpp b/0501-1000/0673-Number-of-Longest-Increasing-Subsequence/cpp-0673/main.cpp similarity index 100% rename from 0673-Number-of-Longest-Increasing-Subsequence/cpp-0673/main.cpp rename to 0501-1000/0673-Number-of-Longest-Increasing-Subsequence/cpp-0673/main.cpp diff --git a/0674-Longest-Continuous-Increasing-Subsequence/cpp-0674/CMakeLists.txt b/0501-1000/0674-Longest-Continuous-Increasing-Subsequence/cpp-0674/CMakeLists.txt similarity index 100% rename from 0674-Longest-Continuous-Increasing-Subsequence/cpp-0674/CMakeLists.txt rename to 0501-1000/0674-Longest-Continuous-Increasing-Subsequence/cpp-0674/CMakeLists.txt diff --git a/0674-Longest-Continuous-Increasing-Subsequence/cpp-0674/main.cpp b/0501-1000/0674-Longest-Continuous-Increasing-Subsequence/cpp-0674/main.cpp similarity index 100% rename from 0674-Longest-Continuous-Increasing-Subsequence/cpp-0674/main.cpp rename to 0501-1000/0674-Longest-Continuous-Increasing-Subsequence/cpp-0674/main.cpp diff --git a/0675-Cut-Off-Trees-for-Golf-Event/cpp-0675/CMakeLists.txt b/0501-1000/0675-Cut-Off-Trees-for-Golf-Event/cpp-0675/CMakeLists.txt similarity index 100% rename from 0675-Cut-Off-Trees-for-Golf-Event/cpp-0675/CMakeLists.txt rename to 0501-1000/0675-Cut-Off-Trees-for-Golf-Event/cpp-0675/CMakeLists.txt diff --git a/0675-Cut-Off-Trees-for-Golf-Event/cpp-0675/main.cpp b/0501-1000/0675-Cut-Off-Trees-for-Golf-Event/cpp-0675/main.cpp similarity index 100% rename from 0675-Cut-Off-Trees-for-Golf-Event/cpp-0675/main.cpp rename to 0501-1000/0675-Cut-Off-Trees-for-Golf-Event/cpp-0675/main.cpp diff --git a/0676-Implement-Magic-Dictionary/cpp-0676/CMakeLists.txt b/0501-1000/0676-Implement-Magic-Dictionary/cpp-0676/CMakeLists.txt similarity index 100% rename from 0676-Implement-Magic-Dictionary/cpp-0676/CMakeLists.txt rename to 0501-1000/0676-Implement-Magic-Dictionary/cpp-0676/CMakeLists.txt diff --git a/0676-Implement-Magic-Dictionary/cpp-0676/main.cpp b/0501-1000/0676-Implement-Magic-Dictionary/cpp-0676/main.cpp similarity index 100% rename from 0676-Implement-Magic-Dictionary/cpp-0676/main.cpp rename to 0501-1000/0676-Implement-Magic-Dictionary/cpp-0676/main.cpp diff --git a/0676-Implement-Magic-Dictionary/cpp-0676/main2.cpp b/0501-1000/0676-Implement-Magic-Dictionary/cpp-0676/main2.cpp similarity index 100% rename from 0676-Implement-Magic-Dictionary/cpp-0676/main2.cpp rename to 0501-1000/0676-Implement-Magic-Dictionary/cpp-0676/main2.cpp diff --git a/0676-Implement-Magic-Dictionary/cpp-0676/main3.cpp b/0501-1000/0676-Implement-Magic-Dictionary/cpp-0676/main3.cpp similarity index 100% rename from 0676-Implement-Magic-Dictionary/cpp-0676/main3.cpp rename to 0501-1000/0676-Implement-Magic-Dictionary/cpp-0676/main3.cpp diff --git a/0676-Implement-Magic-Dictionary/cpp-0676/main4.cpp b/0501-1000/0676-Implement-Magic-Dictionary/cpp-0676/main4.cpp similarity index 100% rename from 0676-Implement-Magic-Dictionary/cpp-0676/main4.cpp rename to 0501-1000/0676-Implement-Magic-Dictionary/cpp-0676/main4.cpp diff --git a/0501-1000/0677-Map-Sum-Pairs/cpp-0677/CMakeLists.txt b/0501-1000/0677-Map-Sum-Pairs/cpp-0677/CMakeLists.txt new file mode 100644 index 00000000..40a12f9e --- /dev/null +++ b/0501-1000/0677-Map-Sum-Pairs/cpp-0677/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0677) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main3.cpp) +add_executable(cpp_0677 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0677-Map-Sum-Pairs/cpp-0677/main.cpp b/0501-1000/0677-Map-Sum-Pairs/cpp-0677/main.cpp new file mode 100644 index 00000000..914c5c25 --- /dev/null +++ b/0501-1000/0677-Map-Sum-Pairs/cpp-0677/main.cpp @@ -0,0 +1,49 @@ +/// Source : https://leetcode.com/problems/map-sum-pairs/description/ +/// Author : liuyubobobo +/// Time : 2017-11-05 + +#include +#include + +using namespace std; + + +/// HashMap + Brute Force +/// Time Complexity: insert: O(1) +/// sum: O(n * len(prefix)) +/// Space Complexity: O(sum(len(wi))) where wi is the length of the ith word. +class MapSum { + +private: + unordered_map mapsum; + +public: + /** Initialize your data structure here. */ + MapSum() { + mapsum.clear(); + } + + void insert(string key, int val) { + mapsum[key] = val; + } + + int sum(string prefix) { + int ret = 0; + for(pair e: mapsum) + if(e.first.substr(0, prefix.size()) == prefix) + ret += e.second; + return ret; + } +}; + + +int main() { + + MapSum obj; + obj.insert("apple", 3); + cout << obj.sum("ap") << endl; // 3 + obj.insert("app", 2); + cout << obj.sum("ap") << endl; // 5 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0677-Map-Sum-Pairs/cpp-0677/main2.cpp b/0501-1000/0677-Map-Sum-Pairs/cpp-0677/main2.cpp new file mode 100644 index 00000000..85ab9d0f --- /dev/null +++ b/0501-1000/0677-Map-Sum-Pairs/cpp-0677/main2.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/map-sum-pairs/description/ +/// Author : liuyubobobo +/// Time : 2017-11-05 + +#include +#include + +using namespace std; + +/// Prefix HashMap + Brute Force +/// Time Complexity: insert: O(len(prefix)^2) +/// sum: O(len(prefix)) +/// Space Complexity: O(sum(len(wi)^2)) where wi is the length of the ith word. +class MapSum { + +private: + unordered_map prefixScore; + unordered_map summap; + +public: + /** Initialize your data structure here. */ + MapSum() { + summap.clear(); + prefixScore.clear(); + } + + void insert(string key, int val) { + + if(summap.find(key) == summap.end()){ + for(int i = 1 ; i <= key.size() ; i ++) + prefixScore[key.substr(0, i)] += val; + } + else{ + int old_value = summap[key]; + for(int i = 1 ; i <= key.size() ; i ++) + prefixScore[key.substr(0, i)] += val - old_value; + } + + summap[key] = val; + } + + int sum(string prefix) { + return prefixScore[prefix]; + } +}; + + +int main() { + + MapSum obj; + obj.insert("apple", 3); + cout << obj.sum("ap") << endl; // 3 + obj.insert("app", 2); + cout << obj.sum("ap") << endl; // 5 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0677-Map-Sum-Pairs/cpp-0677/main3.cpp b/0501-1000/0677-Map-Sum-Pairs/cpp-0677/main3.cpp new file mode 100644 index 00000000..903260ca --- /dev/null +++ b/0501-1000/0677-Map-Sum-Pairs/cpp-0677/main3.cpp @@ -0,0 +1,104 @@ +/// Source : https://leetcode.com/problems/map-sum-pairs/description/ +/// Author : liuyubobobo +/// Time : 2017-11-05 + +#include +#include +#include + +using namespace std; + + +/// Trie +/// Time Complexity: insert: O(len(prefix)) +/// sum: O(sum(len(wi))) +/// Space Complexity: O(sum(len(wi))) where wi is the length of the ith word. +class Trie{ + +private: + struct Node{ + map next; + int val = 0; + }; + vector trie; + +public: + Trie(){ + trie.clear(); + trie.push_back(Node()); + } + + void insert(const string& word, int val){ + insert(0, word, 0, val); + } + + int sum(const string& prefix){ + int treeID = findTreeID(0, prefix, 0); + if(treeID == -1) + return 0; + return dfs(treeID); + } + +private: + void insert(int treeID, const string& word, int index, int val){ + + if(index == word.size()) { + trie[treeID].val = val; + return; + } + + if(trie[treeID].next.find(word[index]) == trie[treeID].next.end()){ + trie[treeID].next[word[index]] = trie.size(); + trie.push_back(Node()); + } + + insert(trie[treeID].next[word[index]], word, index + 1, val); + } + + int findTreeID(int treeID, const string& word, int index){ + + if(index == word.size()) + return treeID; + + if(trie[treeID].next.find(word[index]) == trie[treeID].next.end()) + return -1; + + return findTreeID(trie[treeID].next[word[index]], word, index + 1); + } + + int dfs(int treeID){ + + int res = trie[treeID].val; + for(pair next: trie[treeID].next) + res += dfs(next.second); + return res; + } +}; + +class MapSum { + +private: + Trie trie; + +public: + + void insert(string key, int val) { + trie.insert(key, val); + } + + int sum(string prefix) { + return trie.sum(prefix); + } +}; + + +int main() { + + MapSum obj; + obj.insert("apple", 3); + cout << obj.sum("ap") << endl; // 3 + obj.insert("app", 2); + cout << obj.sum("ap") << endl; // 5 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0678-Valid-Parenthesis-String/cpp-0678/CMakeLists.txt b/0501-1000/0678-Valid-Parenthesis-String/cpp-0678/CMakeLists.txt new file mode 100644 index 00000000..bebec8f9 --- /dev/null +++ b/0501-1000/0678-Valid-Parenthesis-String/cpp-0678/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0678) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0678 main.cpp) diff --git a/0501-1000/0678-Valid-Parenthesis-String/cpp-0678/main.cpp b/0501-1000/0678-Valid-Parenthesis-String/cpp-0678/main.cpp new file mode 100644 index 00000000..40d9d034 --- /dev/null +++ b/0501-1000/0678-Valid-Parenthesis-String/cpp-0678/main.cpp @@ -0,0 +1,58 @@ +/// Source : https://leetcode.com/problems/valid-parenthesis-string/ +/// Author : liuyubobobo +/// Time : 2021-09-11 + +#include +#include + +using namespace std; + + +/// Memoization +/// Time Complexity: O(n^3) +/// Space Complexity: O(n^2) +class Solution { +public: + bool checkValidString(string s) { + + int n = s.size(); + vector> dp(n, vector(n, -1)); + return dfs(s, 0, n - 1, dp); + } + +private: + bool dfs(const string& s, int l, int r, vector>& dp){ + + if(l > r) return true; + if(l == r) return s[l] == '*'; + if(dp[l][r] != -1) return dp[l][r]; + + if(s[l] == ')' || s[r] == '(') return dp[l][r] = false; + + if(s[l] == '*' && dfs(s, l + 1, r, dp)) + return dp[l][r] = true; + + if(s[r] == '*' && dfs(s, l, r - 1, dp)) + return dp[l][r] = true; + + if(dfs(s, l + 1, r - 1, dp)) return dp[l][r] = true; + + for(int i = l + 1; i < r; i ++) + if(dfs(s, l, i, dp) && dfs(s, i + 1, r, dp)) + return dp[l][r] = true; + + return dp[l][r] = false; + } +}; + + +int main() { + + cout << Solution().checkValidString("()") << endl; + // 1 + + cout << Solution().checkValidString("(((((*(()((((*((**(((()()*)()()()*((((**)())*)*)))))))(())(()))())((*()()(((()((()*(())*(()**)()(())") << endl; + // 0 + + return 0; +} diff --git a/0501-1000/0679-24-Game/cpp-0679/CMakeLists.txt b/0501-1000/0679-24-Game/cpp-0679/CMakeLists.txt new file mode 100644 index 00000000..c05257b6 --- /dev/null +++ b/0501-1000/0679-24-Game/cpp-0679/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(cpp_0679) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0679 main.cpp) \ No newline at end of file diff --git a/0501-1000/0679-24-Game/cpp-0679/main.cpp b/0501-1000/0679-24-Game/cpp-0679/main.cpp new file mode 100644 index 00000000..ec8080fb --- /dev/null +++ b/0501-1000/0679-24-Game/cpp-0679/main.cpp @@ -0,0 +1,79 @@ +/// Source : https://leetcode.com/problems/24-game/ +/// Author : liuyubobobo +/// Time : 2020-03-02 + +#include +#include +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(4! * 4^3 * 3) +/// Space Complexity: O(1) +class Solution { +public: + bool judgePoint24(vector& nums) { + + sort(nums.begin(), nums.end()); + do{ + if(ok(nums[0], nums[1], nums[2], nums[3])) return true; + }while(next_permutation(nums.begin(), nums.end())); + + return false; + } + +private: + bool ok(int a, int b, int c, int d){ + + vector ops = {'+', '-', '*', '/'}; + for(char op1: ops) + for(char op2: ops) + for(char op3: ops){ + try{ + if(equals(op(op(op(a, b, op1), c, op2), d, op3), 24.0)) return true; + }catch(invalid_argument& e){} + + try{ + if(equals(op(op(a, b, op1), op(c, d, op3), op2), 24.0)) return true; + }catch(invalid_argument& e){} + + try{ + if(equals(op(op(a, op(b, c, op2), op1), d, op3), 24.0)) return true; + }catch(invalid_argument& e){} + + try{ + if(equals(op(a, op(op(b, c, op2), d, op3), op1), 24.0)) return true; + }catch(invalid_argument& e){} + + try{ + if(equals(op(a, op(b, op(c, d, op3), op2), op1), 24.0)) return true; + }catch(invalid_argument& e){} + } + return false; + } + + double op(double a, double b, char op){ + if(op == '+') return a + b; + if(op == '-') return a - b; + if(op == '*') return a * b; + if(equals(b, 0.0)) throw invalid_argument("error"); + return a / b; + } + + bool equals(double a, double b){ + return abs(a - b) <= 1e-6; + } +}; + + +int main() { + + vector nums1 = {1, 2, 1, 2}; + cout << Solution().judgePoint24(nums1) << endl; + // 0 + + return 0; +} diff --git a/0501-1000/0680-Valid-Palindrome-II/cpp-0680/CMakeLists.txt b/0501-1000/0680-Valid-Palindrome-II/cpp-0680/CMakeLists.txt new file mode 100644 index 00000000..dc6a47c8 --- /dev/null +++ b/0501-1000/0680-Valid-Palindrome-II/cpp-0680/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_0680) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0680 main.cpp) diff --git a/0501-1000/0680-Valid-Palindrome-II/cpp-0680/main.cpp b/0501-1000/0680-Valid-Palindrome-II/cpp-0680/main.cpp new file mode 100644 index 00000000..9db57f7d --- /dev/null +++ b/0501-1000/0680-Valid-Palindrome-II/cpp-0680/main.cpp @@ -0,0 +1,39 @@ +/// Source : https://leetcode.com/problems/valid-palindrome-ii/ +/// Author : liuyubobobo +/// Time : 2022-04-01 + +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + bool validPalindrome(string s) { + + int n = s.size(); + if(is_palindrome(s, 0, n - 1)) return true; + + int i = 0, j = n - 1; + while(s[i] == s[j]) i ++, j --; + return is_palindrome(s, i + 1, j) || is_palindrome(s, i, j - 1); + } + +private: + bool is_palindrome(const string& s, int l, int r){ + for(int i = l, j = r; i < j; i ++, j --) + if(s[i] != s[j]) return false; + return true; + } +}; + + +int main() { + + cout << Solution().validPalindrome("abca") << '\n'; + + return 0; +} diff --git a/0501-1000/0682-Baseball-Game/cpp-0682/CMakeLists.txt b/0501-1000/0682-Baseball-Game/cpp-0682/CMakeLists.txt new file mode 100644 index 00000000..e011de9f --- /dev/null +++ b/0501-1000/0682-Baseball-Game/cpp-0682/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_0682) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0682 main.cpp) diff --git a/0501-1000/0682-Baseball-Game/cpp-0682/main.cpp b/0501-1000/0682-Baseball-Game/cpp-0682/main.cpp new file mode 100644 index 00000000..75f4016d --- /dev/null +++ b/0501-1000/0682-Baseball-Game/cpp-0682/main.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/baseball-game/ +/// Author : liuyubobobo +/// Time : 2022-03-25 + +#include +#include +#include + +using namespace std; + + +/// Using Stack +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int calPoints(vector& ops) { + + vector v; + for(const string& e: ops) + if(isdigit(e[0]) || e[0] == '-'){ + int x = atoi(e.c_str()); + v.push_back(x); + } + else if(e == "+") + v.push_back(v.back() + v[v.size() - 2]); + else if(e == "D") + v.push_back(2 * v.back()); + else + v.pop_back(); + + return accumulate(v.begin(), v.end(), 0); + } +}; + + +int main() { + + return 0; +} diff --git a/0684-Redundant-Connection/cpp-0684/CMakeLists.txt b/0501-1000/0684-Redundant-Connection/cpp-0684/CMakeLists.txt similarity index 100% rename from 0684-Redundant-Connection/cpp-0684/CMakeLists.txt rename to 0501-1000/0684-Redundant-Connection/cpp-0684/CMakeLists.txt diff --git a/0684-Redundant-Connection/cpp-0684/main.cpp b/0501-1000/0684-Redundant-Connection/cpp-0684/main.cpp similarity index 100% rename from 0684-Redundant-Connection/cpp-0684/main.cpp rename to 0501-1000/0684-Redundant-Connection/cpp-0684/main.cpp diff --git a/0684-Redundant-Connection/cpp-0684/main2.cpp b/0501-1000/0684-Redundant-Connection/cpp-0684/main2.cpp similarity index 100% rename from 0684-Redundant-Connection/cpp-0684/main2.cpp rename to 0501-1000/0684-Redundant-Connection/cpp-0684/main2.cpp diff --git a/0684-Redundant-Connection/cpp-0684/main3.cpp b/0501-1000/0684-Redundant-Connection/cpp-0684/main3.cpp similarity index 100% rename from 0684-Redundant-Connection/cpp-0684/main3.cpp rename to 0501-1000/0684-Redundant-Connection/cpp-0684/main3.cpp diff --git a/0685-Redundant-Connection-II/cpp-0685/CMakeLists.txt b/0501-1000/0685-Redundant-Connection-II/cpp-0685/CMakeLists.txt similarity index 100% rename from 0685-Redundant-Connection-II/cpp-0685/CMakeLists.txt rename to 0501-1000/0685-Redundant-Connection-II/cpp-0685/CMakeLists.txt diff --git a/0685-Redundant-Connection-II/cpp-0685/main.cpp b/0501-1000/0685-Redundant-Connection-II/cpp-0685/main.cpp similarity index 100% rename from 0685-Redundant-Connection-II/cpp-0685/main.cpp rename to 0501-1000/0685-Redundant-Connection-II/cpp-0685/main.cpp diff --git a/0501-1000/0686-Repeated-String-Match/cpp-0686/CMakeLists.txt b/0501-1000/0686-Repeated-String-Match/cpp-0686/CMakeLists.txt new file mode 100644 index 00000000..75c46141 --- /dev/null +++ b/0501-1000/0686-Repeated-String-Match/cpp-0686/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0686) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0686 main.cpp) diff --git a/0501-1000/0686-Repeated-String-Match/cpp-0686/main.cpp b/0501-1000/0686-Repeated-String-Match/cpp-0686/main.cpp new file mode 100644 index 00000000..12cabdcc --- /dev/null +++ b/0501-1000/0686-Repeated-String-Match/cpp-0686/main.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/repeated-string-match/ +/// Author : liuyubobobo +/// Time : 2021-12-21 + +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int repeatedStringMatch(string a, string b) { + + string s = ""; + int t = 0; + while(s.size() < b.size()) s += a, t ++; + + if(s.find(b) != string::npos) return t; + s += a, t ++; + if(s.find(b) != string::npos) return t; + + return -1; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0687-Longest-Univalue-Path/cpp-0687/CMakeLists.txt b/0501-1000/0687-Longest-Univalue-Path/cpp-0687/CMakeLists.txt new file mode 100644 index 00000000..13a03786 --- /dev/null +++ b/0501-1000/0687-Longest-Univalue-Path/cpp-0687/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_0687) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0687 main.cpp) \ No newline at end of file diff --git a/0501-1000/0687-Longest-Univalue-Path/cpp-0687/main.cpp b/0501-1000/0687-Longest-Univalue-Path/cpp-0687/main.cpp new file mode 100644 index 00000000..285bd332 --- /dev/null +++ b/0501-1000/0687-Longest-Univalue-Path/cpp-0687/main.cpp @@ -0,0 +1,60 @@ +/// Source : https://leetcode.com/problems/longest-univalue-path/ +/// Author : liuyubobobo +/// Time : 2021-05-21 + +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(1) + +/// 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 { + +private: + int res = 0; + +public: + int longestUnivaluePath(TreeNode* root) { + + res = 1; + dfs(root); + return res - 1; + } + +private: + int dfs(TreeNode* node){ + + if(!node) return 0; + + int l = dfs(node->left); + int r = dfs(node->right); + + int tres = 1, ret = 1; + if(node->left && node->left->val == node->val) + tres += l, ret = max(ret, 1 + l); + if(node->right && node->right->val == node->val) + tres += r, ret = max(ret, 1 + r); + res = max(res, tres); + + return ret; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0688-Knight-Probability-in-Chessboard/cpp-0688/CMakeLists.txt b/0501-1000/0688-Knight-Probability-in-Chessboard/cpp-0688/CMakeLists.txt new file mode 100644 index 00000000..aa925335 --- /dev/null +++ b/0501-1000/0688-Knight-Probability-in-Chessboard/cpp-0688/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_0688) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0688 main.cpp) diff --git a/0501-1000/0688-Knight-Probability-in-Chessboard/cpp-0688/main.cpp b/0501-1000/0688-Knight-Probability-in-Chessboard/cpp-0688/main.cpp new file mode 100644 index 00000000..848a14f7 --- /dev/null +++ b/0501-1000/0688-Knight-Probability-in-Chessboard/cpp-0688/main.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/knight-probability-in-chessboard/ +/// Author : liuyubobobo +/// Time : 2022-02-16 + +#include +#include + +using namespace std; + + +/// Memoization +/// Time Complexity: O(k * n^2) +/// Space Complexity: O(k * n^2) +class Solution { + +private: + const int dirs[8][2] = {{1, 2}, {2, 1}, {2, -1}, {1, -2}, + {-1, -2}, {-2, -1}, {-2, 1}, {-1, 2}}; +public: + double knightProbability(int n, int k, int r, int c) { + + vector>> dp(k + 1, vector>(n, vector(n, -1))); + return dfs(n, k, r, c, dp); + } + +private: + double dfs(int n, int k, int r, int c, + vector>>& dp) { + + if(k == 0) return 1; + if(dp[k][r][c] >= 0.0) return dp[k][r][c]; + + double res = 0.0; + for(int d = 0; d < 8; d ++){ + int nr = r + dirs[d][0], nc = c + dirs[d][1]; + if(in_area(nr, nc, n)) + res += 0.125 * dfs(n, k - 1, nr, nc, dp); + } + return dp[k][r][c] = res; + } + + bool in_area(int x, int y, int n){ + return 0 <= x && x < n && 0 <= y && y < n; + } +}; + + +int main() { + + cout << Solution().knightProbability(8, 30, 6, 4) << endl; + + return 0; +} diff --git a/0501-1000/0689-Maximum-Sum-of-3-Non-Overlapping-Subarrays/cpp-0689/CMakeLists.txt b/0501-1000/0689-Maximum-Sum-of-3-Non-Overlapping-Subarrays/cpp-0689/CMakeLists.txt new file mode 100644 index 00000000..ef9add75 --- /dev/null +++ b/0501-1000/0689-Maximum-Sum-of-3-Non-Overlapping-Subarrays/cpp-0689/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_0689) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0689 main.cpp) diff --git a/0501-1000/0689-Maximum-Sum-of-3-Non-Overlapping-Subarrays/cpp-0689/main.cpp b/0501-1000/0689-Maximum-Sum-of-3-Non-Overlapping-Subarrays/cpp-0689/main.cpp new file mode 100644 index 00000000..481a93b4 --- /dev/null +++ b/0501-1000/0689-Maximum-Sum-of-3-Non-Overlapping-Subarrays/cpp-0689/main.cpp @@ -0,0 +1,55 @@ +/// Source : https://leetcode.com/problems/maximum-sum-of-3-non-overlapping-subarrays/ +/// Author : liuyubobobo +/// Time : 2021-12-07 + +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector maxSumOfThreeSubarrays(vector& nums, int k) { + + int n = nums.size(); + vector presum(n + 1, 0ll); + for(int i = 0; i < n; i ++) presum[i + 1] = presum[i] + nums[i]; + + vector max1(n, presum[n] - presum[n - k]); + vector max1_index(n, n - k); + for(int i = n - k - 1; i >= 0; i --){ + max1[i] = max1[i + 1], max1_index[i] = max1_index[i + 1]; + if(presum[i + k] - presum[i] >= max1[i + 1]) + max1[i] = presum[i + k] - presum[i], + max1_index[i] = i; + } + + vector max2(n, presum[n] - presum[n - 2 * k]); + vector> max2_index(n, {n - 2 * k, n - k}); + for(int i = n - 2 * k - 1; i >= 0; i --){ + max2[i] = max2[i + 1], max2_index[i] = max2_index[i + 1]; + if(presum[i + k] - presum[i] + max1[i + k] >= max2[i + 1]) + max2[i] = presum[i + k] - presum[i] + max1[i + k], + max2_index[i] = {i, max1_index[i + k]}; + } + + long long cur_max = presum[n] - presum[n - 3 * k]; + vector max3_index = {n - 3 * k, n - 2 * k, n - k}; + for(int i = n - 3 * k - 1; i >= 0; i --){ + if(presum[i + k] - presum[i] + max2[i + k] >= cur_max) + cur_max = presum[i + k] - presum[i] + max2[i + k], + max3_index = {i, max2_index[i + k].first, max2_index[i + k].second}; + } + return max3_index; + }; +}; + + +int main() { + + return 0; +} diff --git a/0690-Employee-Importance/cpp-0690/CMakeLists.txt b/0501-1000/0690-Employee-Importance/cpp-0690/CMakeLists.txt similarity index 100% rename from 0690-Employee-Importance/cpp-0690/CMakeLists.txt rename to 0501-1000/0690-Employee-Importance/cpp-0690/CMakeLists.txt diff --git a/0690-Employee-Importance/cpp-0690/main.cpp b/0501-1000/0690-Employee-Importance/cpp-0690/main.cpp similarity index 100% rename from 0690-Employee-Importance/cpp-0690/main.cpp rename to 0501-1000/0690-Employee-Importance/cpp-0690/main.cpp diff --git a/0501-1000/0691-Stickers-to-Spell-Word/cpp-0691/CMakeLists.txt b/0501-1000/0691-Stickers-to-Spell-Word/cpp-0691/CMakeLists.txt new file mode 100644 index 00000000..fb9992e5 --- /dev/null +++ b/0501-1000/0691-Stickers-to-Spell-Word/cpp-0691/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_0691) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0691 main.cpp) diff --git a/0501-1000/0691-Stickers-to-Spell-Word/cpp-0691/main.cpp b/0501-1000/0691-Stickers-to-Spell-Word/cpp-0691/main.cpp new file mode 100644 index 00000000..66a2eb5f --- /dev/null +++ b/0501-1000/0691-Stickers-to-Spell-Word/cpp-0691/main.cpp @@ -0,0 +1,74 @@ +/// Source : https://leetcode.com/problems/stickers-to-spell-word/ +/// Author : liuyubobobo +/// Time : 2022-05-24 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// Memoization +/// Time Complexity: O(C(26, 15)?) +/// Space Complexity: O(C(26, 15)?) +class Solution { +public: + int minStickers(vector& stickers, string target) { + + int n = stickers.size(); + + vector> f(n, vector(26, 0)); + for(int i = 0; i < n; i ++) + for(char c: stickers[i]) f[i][c - 'a'] ++; + + vector tf(26, 0); + for(char c: target) tf[c - 'a'] ++; + + map, int> dp; + int res = dfs(n, f, tf, dp); + return res >= INT_MAX / 2 ? -1 : res; + } + +private: + int dfs(int n, const vector>& f, const vector& tf, + map, int>& dp){ + + if(accumulate(tf.begin(), tf.end(), 0) == 0) + return 0; + + auto iter = dp.find(tf); + if(iter != dp.end()) return iter->second; + + int first_need = 0; + for(;first_need < 26 && tf[first_need] == 0; first_need ++); + + int res = INT_MAX / 2; + for(int index = 0; index < n; index ++) + if(f[index][first_need]){ + vector next_f = tf; + for(int i = 0; i < 26; i ++) + next_f[i] = max(next_f[i] - f[index][i], 0); + res = min(res, 1 + dfs(n, f, next_f, dp)); + } + return dp[tf] = res; + } +}; + + +int main() { + + vector stickers1 = {"with","example","science"}; + string target1 = "thehat"; + cout << Solution().minStickers(stickers1, target1) << '\n'; + // 3 + + vector stickers2 = {"notice","possible"}; + string target2 = "basicbasic"; + cout << Solution().minStickers(stickers2, target2) << '\n'; + // -1 + + return 0; +} diff --git a/0692-Top-K-Frequent-Words/cpp-0692/CMakeLists.txt b/0501-1000/0692-Top-K-Frequent-Words/cpp-0692/CMakeLists.txt similarity index 100% rename from 0692-Top-K-Frequent-Words/cpp-0692/CMakeLists.txt rename to 0501-1000/0692-Top-K-Frequent-Words/cpp-0692/CMakeLists.txt diff --git a/0692-Top-K-Frequent-Words/cpp-0692/main.cpp b/0501-1000/0692-Top-K-Frequent-Words/cpp-0692/main.cpp similarity index 100% rename from 0692-Top-K-Frequent-Words/cpp-0692/main.cpp rename to 0501-1000/0692-Top-K-Frequent-Words/cpp-0692/main.cpp diff --git a/0692-Top-K-Frequent-Words/cpp-0692/main2.cpp b/0501-1000/0692-Top-K-Frequent-Words/cpp-0692/main2.cpp similarity index 100% rename from 0692-Top-K-Frequent-Words/cpp-0692/main2.cpp rename to 0501-1000/0692-Top-K-Frequent-Words/cpp-0692/main2.cpp diff --git a/0692-Top-K-Frequent-Words/cpp-0692/main3.cpp b/0501-1000/0692-Top-K-Frequent-Words/cpp-0692/main3.cpp similarity index 100% rename from 0692-Top-K-Frequent-Words/cpp-0692/main3.cpp rename to 0501-1000/0692-Top-K-Frequent-Words/cpp-0692/main3.cpp diff --git a/0501-1000/0693-Binary-Number-with-Alternating-Bits/cpp-0693/CMakeLists.txt b/0501-1000/0693-Binary-Number-with-Alternating-Bits/cpp-0693/CMakeLists.txt new file mode 100644 index 00000000..1ba37285 --- /dev/null +++ b/0501-1000/0693-Binary-Number-with-Alternating-Bits/cpp-0693/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_0693) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0693 main.cpp) diff --git a/0501-1000/0693-Binary-Number-with-Alternating-Bits/cpp-0693/main.cpp b/0501-1000/0693-Binary-Number-with-Alternating-Bits/cpp-0693/main.cpp new file mode 100644 index 00000000..50d18d24 --- /dev/null +++ b/0501-1000/0693-Binary-Number-with-Alternating-Bits/cpp-0693/main.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/binary-number-with-alternating-bits/ +/// Author : liuyubobobo +/// Time : 2022-03-27 + +#include +#include + +using namespace std; + + +/// int to binary +/// Time Complexity: O(logn) +/// Space Complexity: O(logn) +class Solution { +public: + bool hasAlternatingBits(int n) { + + vector binary; + while(n) + binary.push_back(n & 1), n >>= 1; + + for(int i = 1; i < binary.size(); i ++) + if(binary[i] == binary[i - 1]) return false; + return true; + } +}; + + +int main() { + + + return 0; +} diff --git a/0694-Number-of-Distinct-Islands/cpp-0694/CMakeLists.txt b/0501-1000/0694-Number-of-Distinct-Islands/cpp-0694/CMakeLists.txt similarity index 100% rename from 0694-Number-of-Distinct-Islands/cpp-0694/CMakeLists.txt rename to 0501-1000/0694-Number-of-Distinct-Islands/cpp-0694/CMakeLists.txt diff --git a/0694-Number-of-Distinct-Islands/cpp-0694/main.cpp b/0501-1000/0694-Number-of-Distinct-Islands/cpp-0694/main.cpp similarity index 100% rename from 0694-Number-of-Distinct-Islands/cpp-0694/main.cpp rename to 0501-1000/0694-Number-of-Distinct-Islands/cpp-0694/main.cpp diff --git a/0694-Number-of-Distinct-Islands/cpp-0694/main2.cpp b/0501-1000/0694-Number-of-Distinct-Islands/cpp-0694/main2.cpp similarity index 100% rename from 0694-Number-of-Distinct-Islands/cpp-0694/main2.cpp rename to 0501-1000/0694-Number-of-Distinct-Islands/cpp-0694/main2.cpp diff --git a/0695-Max-Area-of-Island/cpp-0695/CMakeLists.txt b/0501-1000/0695-Max-Area-of-Island/cpp-0695/CMakeLists.txt similarity index 100% rename from 0695-Max-Area-of-Island/cpp-0695/CMakeLists.txt rename to 0501-1000/0695-Max-Area-of-Island/cpp-0695/CMakeLists.txt diff --git a/0695-Max-Area-of-Island/cpp-0695/main.cpp b/0501-1000/0695-Max-Area-of-Island/cpp-0695/main.cpp similarity index 100% rename from 0695-Max-Area-of-Island/cpp-0695/main.cpp rename to 0501-1000/0695-Max-Area-of-Island/cpp-0695/main.cpp diff --git a/0696-Count-Binary-Substrings/cpp-0696/CMakeLists.txt b/0501-1000/0696-Count-Binary-Substrings/cpp-0696/CMakeLists.txt similarity index 100% rename from 0696-Count-Binary-Substrings/cpp-0696/CMakeLists.txt rename to 0501-1000/0696-Count-Binary-Substrings/cpp-0696/CMakeLists.txt diff --git a/0696-Count-Binary-Substrings/cpp-0696/main.cpp b/0501-1000/0696-Count-Binary-Substrings/cpp-0696/main.cpp similarity index 100% rename from 0696-Count-Binary-Substrings/cpp-0696/main.cpp rename to 0501-1000/0696-Count-Binary-Substrings/cpp-0696/main.cpp diff --git a/0697-Degree-of-an-Array/cpp-0697/CMakeLists.txt b/0501-1000/0697-Degree-of-an-Array/cpp-0697/CMakeLists.txt similarity index 100% rename from 0697-Degree-of-an-Array/cpp-0697/CMakeLists.txt rename to 0501-1000/0697-Degree-of-an-Array/cpp-0697/CMakeLists.txt diff --git a/0697-Degree-of-an-Array/cpp-0697/main.cpp b/0501-1000/0697-Degree-of-an-Array/cpp-0697/main.cpp similarity index 100% rename from 0697-Degree-of-an-Array/cpp-0697/main.cpp rename to 0501-1000/0697-Degree-of-an-Array/cpp-0697/main.cpp diff --git a/0698-Partition-to-K-Equal-Sum-Subsets/cpp-0698/CMakeLists.txt b/0501-1000/0698-Partition-to-K-Equal-Sum-Subsets/cpp-0698/CMakeLists.txt similarity index 100% rename from 0698-Partition-to-K-Equal-Sum-Subsets/cpp-0698/CMakeLists.txt rename to 0501-1000/0698-Partition-to-K-Equal-Sum-Subsets/cpp-0698/CMakeLists.txt diff --git a/0698-Partition-to-K-Equal-Sum-Subsets/cpp-0698/main.cpp b/0501-1000/0698-Partition-to-K-Equal-Sum-Subsets/cpp-0698/main.cpp similarity index 100% rename from 0698-Partition-to-K-Equal-Sum-Subsets/cpp-0698/main.cpp rename to 0501-1000/0698-Partition-to-K-Equal-Sum-Subsets/cpp-0698/main.cpp diff --git a/0698-Partition-to-K-Equal-Sum-Subsets/cpp-0698/main2.cpp b/0501-1000/0698-Partition-to-K-Equal-Sum-Subsets/cpp-0698/main2.cpp similarity index 100% rename from 0698-Partition-to-K-Equal-Sum-Subsets/cpp-0698/main2.cpp rename to 0501-1000/0698-Partition-to-K-Equal-Sum-Subsets/cpp-0698/main2.cpp diff --git a/0698-Partition-to-K-Equal-Sum-Subsets/cpp-0698/main3.cpp b/0501-1000/0698-Partition-to-K-Equal-Sum-Subsets/cpp-0698/main3.cpp similarity index 100% rename from 0698-Partition-to-K-Equal-Sum-Subsets/cpp-0698/main3.cpp rename to 0501-1000/0698-Partition-to-K-Equal-Sum-Subsets/cpp-0698/main3.cpp diff --git a/0698-Partition-to-K-Equal-Sum-Subsets/java-0698/src/Solution.java b/0501-1000/0698-Partition-to-K-Equal-Sum-Subsets/java-0698/src/Solution.java similarity index 100% rename from 0698-Partition-to-K-Equal-Sum-Subsets/java-0698/src/Solution.java rename to 0501-1000/0698-Partition-to-K-Equal-Sum-Subsets/java-0698/src/Solution.java diff --git a/0698-Partition-to-K-Equal-Sum-Subsets/java-0698/src/Solution2.java b/0501-1000/0698-Partition-to-K-Equal-Sum-Subsets/java-0698/src/Solution2.java similarity index 100% rename from 0698-Partition-to-K-Equal-Sum-Subsets/java-0698/src/Solution2.java rename to 0501-1000/0698-Partition-to-K-Equal-Sum-Subsets/java-0698/src/Solution2.java diff --git a/0698-Partition-to-K-Equal-Sum-Subsets/java-0698/src/Solution3.java b/0501-1000/0698-Partition-to-K-Equal-Sum-Subsets/java-0698/src/Solution3.java similarity index 100% rename from 0698-Partition-to-K-Equal-Sum-Subsets/java-0698/src/Solution3.java rename to 0501-1000/0698-Partition-to-K-Equal-Sum-Subsets/java-0698/src/Solution3.java diff --git a/0699-Falling-Squares/cpp-0699/CMakeLists.txt b/0501-1000/0699-Falling-Squares/cpp-0699/CMakeLists.txt similarity index 100% rename from 0699-Falling-Squares/cpp-0699/CMakeLists.txt rename to 0501-1000/0699-Falling-Squares/cpp-0699/CMakeLists.txt diff --git a/0501-1000/0699-Falling-Squares/cpp-0699/main.cpp b/0501-1000/0699-Falling-Squares/cpp-0699/main.cpp new file mode 100644 index 00000000..562c5929 --- /dev/null +++ b/0501-1000/0699-Falling-Squares/cpp-0699/main.cpp @@ -0,0 +1,67 @@ +/// Source : https://leetcode.com/contest/leetcode-weekly-contest-54/problems/falling-squares/ +/// Author : liuyubobobo +/// Time : 2017-10-21 +/// Updated: 2022-05-25 + +#include +#include +using namespace std; + + +/// Using heights to record all the falling squares +/// Time Complexity: O(len(position)^2) +/// Space Complexity: O(len(position)) +class Solution { + +public: + vector fallingSquares(vector>& positions) { + + int n = positions.size(); + vector heights(n, 0); + for(int i = 0 ; i < positions.size() ; i ++){ + + heights[i] = positions[i][1]; + for(int j = 0 ; j < i ; j ++) + if(intersection(positions[j], positions[i])) + heights[i] = max(heights[i], heights[j] + positions[i][1]); + } + + vector res(n, 0); + res[0] = heights[0]; + for(int i = 1 ; i < n ; i ++) + res[i] = max(heights[i], res[i-1]); + + return res; + } + +private: + bool intersection(const vector& a, const vector& b){ + int l1 = a[0]; + int r1 = a[0] + a[1] - 1; + int l2 = b[0]; + int r2 = b[0] + b[1] - 1; + + if(l1 > r2 || l2 > r1) + return false; + + return true; + } +}; + + +void print_vec(const vector& vec){ + for(int e: vec) cout << e << ' '; cout << '\n'; +} + +int main() { + + vector> va = {{1, 2}, {2, 3}, {6, 1}}; + vector res1 = Solution().fallingSquares(va); + print_vec(res1); + + vector> vb = {{100, 100}, {200, 100}}; + vector res2 = Solution().fallingSquares(vb); + print_vec(res2); + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0699-Falling-Squares/cpp-0699/main2.cpp b/0501-1000/0699-Falling-Squares/cpp-0699/main2.cpp new file mode 100644 index 00000000..66fef0c0 --- /dev/null +++ b/0501-1000/0699-Falling-Squares/cpp-0699/main2.cpp @@ -0,0 +1,79 @@ +/// Source : https://leetcode.com/contest/leetcode-weekly-contest-54/problems/falling-squares/ +/// Author : liuyubobobo +/// Time : 2017-10-28 +/// Uopdted: 2022-05-25 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// Coordinates compression and simulation +/// Time Complexity: O(len(position)^2) +/// Space Complexity: O(len(position)) +class Solution { + +public: + vector fallingSquares(vector>& positions) { + + int n = positions.size(); + set unique_pos; + for(const vector& position: positions){ + unique_pos.insert(position[0]); + unique_pos.insert(position[0] + position[1] - 1); + } + + map indexes; // pos -> index + vector pos; // index -> pos + for(int p: unique_pos){ + indexes[p] = pos.size(); + pos.push_back(p); + } + + assert(indexes.size() == pos.size()); + vector heights(indexes.size(), 0); + vector res; + for(const vector& position: positions){ + + int startIndex = indexes[position[0]]; + int rightBound = position[0] + position[1] - 1; + + int best = 0; + for(int i = startIndex ; i < pos.size() && pos[i] <= rightBound ; i ++) + best = max(best, heights[i]); + + for(int i = startIndex ; i < pos.size() && pos[i] <= rightBound ; i ++) + heights[i] = best + position[1]; + + best = 0; + for(int i = 0 ; i < heights.size() ; i ++) + best = max(best, heights[i]); + + res.push_back(best); + } + + return res; + } +}; + + +void print_vec(const vector& vec){ + for(int e: vec) cout << e << ' '; cout << '\n'; +} + +int main() { + + vector> va = {{1, 2}, {2, 3}, {6, 1}}; + vector res1 = Solution().fallingSquares(va); + print_vec(res1); + + vector> vb = {{100, 100}, {200, 100}}; + vector res2 = Solution().fallingSquares(vb); + print_vec(res2); + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0700-Search-in-a-Binary-Search-Tree/cpp-0700/CMakeLists.txt b/0501-1000/0700-Search-in-a-Binary-Search-Tree/cpp-0700/CMakeLists.txt new file mode 100644 index 00000000..43715e63 --- /dev/null +++ b/0501-1000/0700-Search-in-a-Binary-Search-Tree/cpp-0700/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0700) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0700 main.cpp) diff --git a/0501-1000/0700-Search-in-a-Binary-Search-Tree/cpp-0700/main.cpp b/0501-1000/0700-Search-in-a-Binary-Search-Tree/cpp-0700/main.cpp new file mode 100644 index 00000000..aeb1e417 --- /dev/null +++ b/0501-1000/0700-Search-in-a-Binary-Search-Tree/cpp-0700/main.cpp @@ -0,0 +1,39 @@ +/// Source : https://leetcode.com/problems/search-in-a-binary-search-tree/ +/// Author : liuyubobobo +/// Time : 2021-08-15 + +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(h) +/// Space Complexity: O(h) + +/// 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* searchBST(TreeNode* root, int val) { + + if(!root) return nullptr; + if(root->val == val) return root; + + return val < root->val ? searchBST(root->left, val) : searchBST(root->right, val); + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0701-Insert-into-a-Binary-Search-Tree/cpp-0701/CMakeLists.txt b/0501-1000/0701-Insert-into-a-Binary-Search-Tree/cpp-0701/CMakeLists.txt new file mode 100644 index 00000000..2e74a3e7 --- /dev/null +++ b/0501-1000/0701-Insert-into-a-Binary-Search-Tree/cpp-0701/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(cpp_0701) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0701 main.cpp) \ No newline at end of file diff --git a/0501-1000/0701-Insert-into-a-Binary-Search-Tree/cpp-0701/main.cpp b/0501-1000/0701-Insert-into-a-Binary-Search-Tree/cpp-0701/main.cpp new file mode 100644 index 00000000..eaa180a0 --- /dev/null +++ b/0501-1000/0701-Insert-into-a-Binary-Search-Tree/cpp-0701/main.cpp @@ -0,0 +1,39 @@ +/// Source : https://leetcode.com/problems/insert-into-a-binary-search-tree/ +/// Author : liuyubobobo +/// Time : 2019-04-30 + +#include + +using namespace std; + + +/// Recursive +/// Time Complexity: O(h) +/// Space Complexity: O(h) + +/// 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* insertIntoBST(TreeNode* root, int val) { + + if(!root) return new TreeNode(val); + + if(val < root->val) root->left = insertIntoBST(root->left, val); + else root->right = insertIntoBST(root->right, val); + return root; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0701-Insert-into-a-Binary-Search-Tree/cpp-0701/main2.cpp b/0501-1000/0701-Insert-into-a-Binary-Search-Tree/cpp-0701/main2.cpp new file mode 100644 index 00000000..3e19003a --- /dev/null +++ b/0501-1000/0701-Insert-into-a-Binary-Search-Tree/cpp-0701/main2.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/insert-into-a-binary-search-tree/ +/// Author : liuyubobobo +/// Time : 2019-04-30 + +#include + +using namespace std; + + +/// Iterative +/// Time Complexity: O(h) +/// Space Complexity: O(h) + +/// 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* insertIntoBST(TreeNode* root, int val) { + + if(!root) return new TreeNode(val); + + TreeNode* p = root; + while(true){ + if(val < p->val){ + if(!p->left){ + p->left = new TreeNode(val); + break; + } + p = p->left; + } + else{ + if(!p->right){ + p->right = new TreeNode(val); + break; + } + p = p->right; + } + } + return root; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0703-Kth-Largest-Element-in-a-Stream/cpp-0703/CMakeLists.txt b/0501-1000/0703-Kth-Largest-Element-in-a-Stream/cpp-0703/CMakeLists.txt new file mode 100644 index 00000000..416bc34a --- /dev/null +++ b/0501-1000/0703-Kth-Largest-Element-in-a-Stream/cpp-0703/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0703) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0703 main.cpp) \ No newline at end of file diff --git a/0501-1000/0703-Kth-Largest-Element-in-a-Stream/cpp-0703/main.cpp b/0501-1000/0703-Kth-Largest-Element-in-a-Stream/cpp-0703/main.cpp new file mode 100644 index 00000000..0acfd7de --- /dev/null +++ b/0501-1000/0703-Kth-Largest-Element-in-a-Stream/cpp-0703/main.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/kth-largest-element-in-a-stream/ +/// Author : liuyubobobo +/// Time : 2021-02-10 + +#include +#include +#include + +using namespace std; + + +/// Priority Queue +/// Time Complexity: init: O(nlogk) +/// add: O(logk) +/// Space Complexity: O(k) +class KthLargest { + +private: + int k; + priority_queue, greater> pq; + +public: + KthLargest(int k, vector& nums) : k(k) { + + for(int e: nums) + if(pq.size() < k) + pq.push(e); + else if(e > pq.top()){ + pq.pop(); + pq.push(e); + } + } + + int add(int val) { + + if(pq.size() < k) + pq.push(val); + else if(val > pq.top()){ + pq.pop(); + pq.push(val); + } + return pq.top(); + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0704-Binary-Search/cpp-0704/CMakeLists.txt b/0501-1000/0704-Binary-Search/cpp-0704/CMakeLists.txt new file mode 100644 index 00000000..6a2557ad --- /dev/null +++ b/0501-1000/0704-Binary-Search/cpp-0704/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main2.cpp) +add_executable(cpp ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0704-Binary-Search/cpp-0704/main.cpp b/0501-1000/0704-Binary-Search/cpp-0704/main.cpp new file mode 100644 index 00000000..99d45c04 --- /dev/null +++ b/0501-1000/0704-Binary-Search/cpp-0704/main.cpp @@ -0,0 +1,43 @@ +/// Source : https://leetcode.com/problems/binary-search/description/ +/// Author : liuyubobobo +/// Time : 2018-06-17 + +#include +#include + +using namespace std; + +/// Binary Search +/// Time Complexity: O(logn) +/// Space Complexity: O(1) +class Solution { +public: + int search(vector& nums, int target) { + + int l = 0, r = nums.size() - 1; + while(l <= r){ + int mid = l + (r - l) / 2; + if(nums[mid] == target) + return mid; + else if(nums[mid] < target) + l = mid + 1; + else + r = mid - 1; + } + return -1; + } +}; + + +int main() { + + vector nums1 = {-1, 0, 3, 5, 9, 12}; + int target1 = 9; + cout << Solution().search(nums1, target1) << endl; + + vector nums2 = {-1, 0, 3, 5, 9, 12}; + int target2 = 2; + cout << Solution().search(nums2, target2) << endl; + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0704-Binary-Search/cpp-0704/main2.cpp b/0501-1000/0704-Binary-Search/cpp-0704/main2.cpp new file mode 100644 index 00000000..e1c088ad --- /dev/null +++ b/0501-1000/0704-Binary-Search/cpp-0704/main2.cpp @@ -0,0 +1,45 @@ +/// Source : https://leetcode.com/problems/binary-search/description/ +/// Author : liuyubobobo +/// Time : 2018-06-17 + +#include +#include + +using namespace std; + +/// Binary Search +/// with only one compare in each iterations:) +/// +/// Time Complexity: O(logn) +/// Space Complexity: O(1) +class Solution { +public: + int search(vector& nums, int target) { + + int l = 0, r = nums.size() - 1; + while(l < r){ + int mid = l + (r - l + 1) / 2; + if(nums[mid] <= target) + l = mid; + else + r = mid - 1; + } + + if(nums[l] == target) + return l; + return -1; + } +}; + +int main() { + + vector nums1 = {-1, 0, 3, 5, 9, 12}; + int target1 = 9; + cout << Solution().search(nums1, target1) << endl; + + vector nums2 = {-1, 0, 3, 5, 9, 12}; + int target2 = 2; + cout << Solution().search(nums2, target2) << endl; + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0705-Design-HashSet/cpp-0705/CMakeLists.txt b/0501-1000/0705-Design-HashSet/cpp-0705/CMakeLists.txt new file mode 100644 index 00000000..ac59efd5 --- /dev/null +++ b/0501-1000/0705-Design-HashSet/cpp-0705/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(01_Design_HashSet) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(01_Design_HashSet ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0705-Design-HashSet/cpp-0705/main.cpp b/0501-1000/0705-Design-HashSet/cpp-0705/main.cpp new file mode 100644 index 00000000..e4e33195 --- /dev/null +++ b/0501-1000/0705-Design-HashSet/cpp-0705/main.cpp @@ -0,0 +1,45 @@ +/// Source : https://leetcode.com/problems/design-hashset/description/ +/// Author : liuyubobobo +/// Time : 2018-06-07 + +#include +#include + +using namespace std; + +#define N 100000 + + +/// Using set(which is RBTree) to construct HashSet +/// Time Complexity: O(1) +/// Space Complexity: O(n) +class MyHashSet { + +private: + set data[N]; + +public: + /** Initialize your data structure here. */ + MyHashSet() { + + } + + void add(int key) { + data[key % N].insert(key); + } + + void remove(int key) { + data[key % N].erase(key); + } + + /** Returns true if this set did not already contain the specified element */ + bool contains(int key) { + return data[key % N].find(key) != data[key % N].end(); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0706-Design-HashMap/cpp-0706/CMakeLists.txt b/0501-1000/0706-Design-HashMap/cpp-0706/CMakeLists.txt new file mode 100644 index 00000000..cef78cdf --- /dev/null +++ b/0501-1000/0706-Design-HashMap/cpp-0706/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0706-Design-HashMap/cpp-0706/main.cpp b/0501-1000/0706-Design-HashMap/cpp-0706/main.cpp new file mode 100644 index 00000000..91c3123f --- /dev/null +++ b/0501-1000/0706-Design-HashMap/cpp-0706/main.cpp @@ -0,0 +1,49 @@ +/// Source : https://leetcode.com/problems/design-hashmap/description/ +/// Author : liuyubobobo +/// Time : 2018-06-07 + +#include +#include + +using namespace std; + +#define N 100000 + +/// Using map(which is RBTree) to construct HashMap +/// Time Complexity: O(1) +/// Space Complexity: O(n) +class MyHashMap { + +private: + map data[N]; + +public: + /** Initialize your data structure here. */ + MyHashMap() { + + } + + /** value will always be positive. */ + void put(int key, int value) { + data[key % N][key] = value; + } + + /** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */ + int get(int key) { + map::iterator iter = data[key % N].find(key); + if(iter == data[key % N].end()) + return -1; + return data[key % N][key]; + } + + /** Removes the mapping of the specified value key if this map contains a mapping for the key */ + void remove(int key) { + data[key % N].erase(key); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0707-Design-Linked-List/cpp-0707/CMakeLists.txt b/0501-1000/0707-Design-Linked-List/cpp-0707/CMakeLists.txt new file mode 100644 index 00000000..b06000ce --- /dev/null +++ b/0501-1000/0707-Design-Linked-List/cpp-0707/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0707) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main4.cpp) +add_executable(cpp_0707 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0707-Design-Linked-List/cpp-0707/main.cpp b/0501-1000/0707-Design-Linked-List/cpp-0707/main.cpp new file mode 100644 index 00000000..bf3a7eea --- /dev/null +++ b/0501-1000/0707-Design-Linked-List/cpp-0707/main.cpp @@ -0,0 +1,110 @@ +/// Source : https://leetcode.com/problems/design-linked-list/description/ +/// Author : liuyubobobo +/// Time : 2018-10-01 + +#include + +using namespace std; + + +/// Singly Linked List +/// Without dummyhead; +/// Time Complexity: init: O(1) +/// get: O(n) +/// addAtHead: O(1) +/// addAtTail: O(n) +/// addAtIndex: O(n) +/// deleteAtIndex: O(n) +/// Space Complexity: O(n) +class MyLinkedList { + +private: + class Node{ + public: + int val; + Node* next; + + Node(int val, Node* next): val(val), next(next){} + Node(int val): Node(val, NULL){} + }; + + Node* head; + +public: + /** Initialize your data structure here. */ + MyLinkedList() { + head = NULL; + } + + /** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */ + int get(int index) { + + Node* cur = head; + for(int i = 0; i < index && cur; i ++) + cur = cur->next; + + if(!cur) return -1; + return cur->val; + } + + /** Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. */ + void addAtHead(int val) { + head = new Node(val, head); + } + + /** Append a node of value val to the last element of the linked list. */ + void addAtTail(int val) { + + if(head == NULL) + head = new Node(val); + else{ + Node* pre = head; + while(pre->next) + pre = pre->next; + pre->next = new Node(val); + } + } + + /** Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. */ + void addAtIndex(int index, int val) { + + if(index == 0) + addAtHead(val); + else{ + Node* pre = head; + for(int i = 1; i < index && pre; i ++) + pre = pre->next; + + if(pre) + pre->next = new Node(val, pre->next); + } + } + + /** Delete the index-th node in the linked list, if the index is valid. */ + void deleteAtIndex(int index) { + if(index == 0){ + if(head){ + Node* delNode = head; + head = head->next; + delete delNode; + } + } + else{ + Node* pre = head; + for(int i = 1; i < index && pre; i ++) + pre = pre->next; + + if(pre && pre->next){ + Node* delNode = pre->next; + pre->next = delNode->next; + delete delNode; + } + } + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0707-Design-Linked-List/cpp-0707/main2.cpp b/0501-1000/0707-Design-Linked-List/cpp-0707/main2.cpp new file mode 100644 index 00000000..73a23e1d --- /dev/null +++ b/0501-1000/0707-Design-Linked-List/cpp-0707/main2.cpp @@ -0,0 +1,94 @@ +/// Source : https://leetcode.com/problems/design-linked-list/description/ +/// Author : liuyubobobo +/// Time : 2018-10-01 + +#include + +using namespace std; + + +/// Singly Linked List +/// Using dummyhead; +/// Time Complexity: init: O(1) +/// get: O(n) +/// addAtHead: O(1) +/// addAtTail: O(n) +/// addAtIndex: O(n) +/// deleteAtIndex: O(n) +/// Space Complexity: O(n) +class MyLinkedList { + +private: + class Node{ + public: + int val; + Node* next; + + Node(int val, Node* next): val(val), next(next){} + Node(int val): Node(val, NULL){} + }; + + Node* dummyHead; + +public: + /** Initialize your data structure here. */ + MyLinkedList() { + dummyHead = new Node(-1); + } + + /** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */ + int get(int index) { + + Node* cur = dummyHead->next; + for(int i = 0; i < index && cur; i ++) + cur = cur->next; + + if(!cur) return -1; + return cur->val; + } + + /** Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. */ + void addAtHead(int val) { + dummyHead->next = new Node(val, dummyHead->next); + } + + /** Append a node of value val to the last element of the linked list. */ + void addAtTail(int val) { + + Node* pre = dummyHead; + while(pre->next) + pre = pre->next; + pre->next = new Node(val); + } + + /** Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. */ + void addAtIndex(int index, int val) { + + Node* pre = dummyHead; + for(int i = 0; i < index && pre; i ++) + pre = pre->next; + + if(pre) + pre->next = new Node(val, pre->next); + } + + /** Delete the index-th node in the linked list, if the index is valid. */ + void deleteAtIndex(int index) { + + Node* pre = dummyHead; + for(int i = 0; i < index && pre; i ++) + pre = pre->next; + + if(pre && pre->next){ + Node* delNode = pre->next; + pre->next = delNode->next; + delete delNode; + } + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0707-Design-Linked-List/cpp-0707/main3.cpp b/0501-1000/0707-Design-Linked-List/cpp-0707/main3.cpp new file mode 100644 index 00000000..af8cf007 --- /dev/null +++ b/0501-1000/0707-Design-Linked-List/cpp-0707/main3.cpp @@ -0,0 +1,117 @@ +/// Source : https://leetcode.com/problems/design-linked-list/description/ +/// Author : liuyubobobo +/// Time : 2018-10-01 + +#include + +using namespace std; + + +/// Doubly Linked List +/// Without dummyhead; +/// Time Complexity: init: O(1) +/// get: O(n) +/// addAtHead: O(1) +/// addAtTail: O(n) +/// addAtIndex: O(n) +/// deleteAtIndex: O(n) +/// Space Complexity: O(n) +class MyLinkedList { + +private: + class Node{ + public: + int val; + Node* next; + Node* prev; + + Node(int val, Node* prev, Node* next): val(val), prev(prev), next(next){} + Node(int val): Node(val, NULL, NULL){} + }; + + Node* head; + +public: + /** Initialize your data structure here. */ + MyLinkedList() { + head = NULL; + } + + /** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */ + int get(int index) { + + Node* cur = head; + for(int i = 0; i < index && cur; i ++) + cur = cur->next; + + if(!cur) return -1; + return cur->val; + } + + /** Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. */ + void addAtHead(int val) { + head = new Node(val, NULL, head); + if(head->next) + head->next->prev = head; + } + + /** Append a node of value val to the last element of the linked list. */ + void addAtTail(int val) { + + if(head == NULL) + head = new Node(val); + else{ + Node* pre = head; + while(pre->next) + pre = pre->next; + pre->next = new Node(val, pre, NULL); + } + } + + /** Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. */ + void addAtIndex(int index, int val) { + + if(index == 0) + addAtHead(val); + else{ + Node* pre = head; + for(int i = 1; i < index && pre; i ++) + pre = pre->next; + + if(pre) + pre->next = new Node(val, pre, pre->next); + } + } + + /** Delete the index-th node in the linked list, if the index is valid. */ + void deleteAtIndex(int index) { + if(index == 0){ + if(head){ + Node* delNode = head; + head = head->next; + if(head) + head->prev = NULL; + delete delNode; + } + } + else{ + Node* pre = head; + for(int i = 1; i < index && pre; i ++) + pre = pre->next; + + if(pre && pre->next){ + Node* delNode = pre->next; + pre->next = delNode->next; + if(pre->next) + pre->next->prev = pre; + delete delNode; + } + } + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0707-Design-Linked-List/cpp-0707/main4.cpp b/0501-1000/0707-Design-Linked-List/cpp-0707/main4.cpp new file mode 100644 index 00000000..cf863a2c --- /dev/null +++ b/0501-1000/0707-Design-Linked-List/cpp-0707/main4.cpp @@ -0,0 +1,97 @@ +/// Source : https://leetcode.com/problems/design-linked-list/description/ +/// Author : liuyubobobo +/// Time : 2018-10-01 + +#include + +using namespace std; + + +/// Doubly Linked List +/// Using dummyhead; +/// Time Complexity: init: O(1) +/// get: O(n) +/// addAtHead: O(1) +/// addAtTail: O(n) +/// addAtIndex: O(n) +/// deleteAtIndex: O(n) +/// Space Complexity: O(n) +class MyLinkedList { + +private: + class Node{ + public: + int val; + Node* prev; + Node* next; + + Node(int val, Node* prev, Node* next): val(val), prev(prev), next(next){} + Node(int val): Node(val, NULL, NULL){} + }; + + Node* dummyHead; + +public: + /** Initialize your data structure here. */ + MyLinkedList() { + dummyHead = new Node(-1); + } + + /** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */ + int get(int index) { + + Node* cur = dummyHead->next; + for(int i = 0; i < index && cur; i ++) + cur = cur->next; + + if(!cur) return -1; + return cur->val; + } + + /** Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. */ + void addAtHead(int val) { + dummyHead->next = new Node(val, dummyHead, dummyHead->next); + } + + /** Append a node of value val to the last element of the linked list. */ + void addAtTail(int val) { + + Node* pre = dummyHead; + while(pre->next) + pre = pre->next; + pre->next = new Node(val, pre, NULL); + } + + /** Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. */ + void addAtIndex(int index, int val) { + + Node* pre = dummyHead; + for(int i = 0; i < index && pre; i ++) + pre = pre->next; + + if(pre) + pre->next = new Node(val, pre, pre->next); + } + + /** Delete the index-th node in the linked list, if the index is valid. */ + void deleteAtIndex(int index) { + + Node* pre = dummyHead; + for(int i = 0; i < index && pre; i ++) + pre = pre->next; + + if(pre && pre->next){ + Node* delNode = pre->next; + pre->next = delNode->next; + if(pre->next) + pre->next->prev = pre; + delete delNode; + } + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0708-Insert-into-a-Cyclic-Sorted-List/cpp-0708/CMakeLists.txt b/0501-1000/0708-Insert-into-a-Cyclic-Sorted-List/cpp-0708/CMakeLists.txt new file mode 100644 index 00000000..9025c11e --- /dev/null +++ b/0501-1000/0708-Insert-into-a-Cyclic-Sorted-List/cpp-0708/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0708) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0708 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0708-Insert-into-a-Cyclic-Sorted-List/cpp-0708/main.cpp b/0501-1000/0708-Insert-into-a-Cyclic-Sorted-List/cpp-0708/main.cpp new file mode 100644 index 00000000..ad706389 --- /dev/null +++ b/0501-1000/0708-Insert-into-a-Cyclic-Sorted-List/cpp-0708/main.cpp @@ -0,0 +1,67 @@ +/// Source : https://leetcode.com/problems/insert-into-a-cyclic-sorted-list/description/ +/// Author : liuyubobobo +/// Time : 2018-10-02 + +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(n) +/// Space Complexity: O(1) + +/// Definition for a Node. +class Node { +public: + int val; + Node* next; + + Node() {} + + Node(int _val, Node* _next) { + val = _val; + next = _next; + } +}; + +class Solution { +public: + Node* insert(Node* head, int insertVal) { + + if(head == NULL){ + Node* ret = new Node(insertVal, NULL); + ret->next = ret; + return ret; + } + + Node* pre = head; + while(pre->next != head){ + if((insertVal >= pre->val && insertVal <= pre->next->val) || + (pre->next->val < pre->val && + (insertVal < pre->next->val || insertVal >= pre->val))) + break; + + pre = pre->next; + } + pre->next = new Node(insertVal, pre->next); + return head; + } +}; + + +int main() { + + Node* head = new Node(1, NULL); + + Node* node2 = new Node(2, NULL); + head->next = node2; + + Node* node3 = new Node(3, NULL); + node2->next = node3; + node3->next = head; + + Solution().insert(head, 0); + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0709-To-Lower-Case/cpp-0709/CMakeLists.txt b/0501-1000/0709-To-Lower-Case/cpp-0709/CMakeLists.txt new file mode 100644 index 00000000..be8457d0 --- /dev/null +++ b/0501-1000/0709-To-Lower-Case/cpp-0709/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_0709) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0709 main.cpp) \ No newline at end of file diff --git a/0501-1000/0709-To-Lower-Case/cpp-0709/main.cpp b/0501-1000/0709-To-Lower-Case/cpp-0709/main.cpp new file mode 100644 index 00000000..c3d85448 --- /dev/null +++ b/0501-1000/0709-To-Lower-Case/cpp-0709/main.cpp @@ -0,0 +1,27 @@ +/// Source : https://leetcode.com/problems/to-lower-case/ +/// Author : liuyubobobo +/// Time : 2021-05-24 + +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + string toLowerCase(string s) { + + for(char& c: s) + c = tolower(c); + return s; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0710-Random-Pick-with-Blacklist/cpp-0710/CMakeLists.txt b/0501-1000/0710-Random-Pick-with-Blacklist/cpp-0710/CMakeLists.txt new file mode 100644 index 00000000..e8d4c77d --- /dev/null +++ b/0501-1000/0710-Random-Pick-with-Blacklist/cpp-0710/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0864) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main2.cpp) +add_executable(cpp_0864 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0710-Random-Pick-with-Blacklist/cpp-0710/main.cpp b/0501-1000/0710-Random-Pick-with-Blacklist/cpp-0710/main.cpp new file mode 100644 index 00000000..f3f89f49 --- /dev/null +++ b/0501-1000/0710-Random-Pick-with-Blacklist/cpp-0710/main.cpp @@ -0,0 +1,73 @@ +/// Source : https://leetcode.com/problems/random-pick-with-blacklist/description/ +/// Author : liuyubobobo +/// Time : 2018-07-08 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// Remap all blacklist number to a legal number +/// Time Complexity: init: O(BlogB), where B is len(blacklist) +/// pick: O(1) +/// Space Complexity: O(B) +class Solution { + +private: + int limit; + unordered_map trans; + +public: + Solution(int N, vector blacklist) { + + sort(blacklist.begin(), blacklist.end()); + unordered_set bset(blacklist.begin(), blacklist.end()); + + limit = N - 1; + trans.clear(); + for(int i = 0 ; i < blacklist.size() ; ){ + + if(blacklist[i] == limit){ + limit --; + break; + } + + if(blacklist[i] > limit) + break; + + if(bset.find(limit) != bset.end()){ + limit --; + continue; + } + + trans[blacklist[i]] = limit; + limit --; + i ++; + } + + srand(time(NULL)); + } + + int pick() { + int res = rand() % (limit + 1); + if(trans.find(res) != trans.end()) + return trans[res]; + return res; + } +}; + + +int main() { + + Solution solution1(2, {1}); + cout << solution1.pick() << endl; + + Solution solution2(3, {1, 2}); + cout << solution2.pick() << endl; + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0710-Random-Pick-with-Blacklist/cpp-0710/main2.cpp b/0501-1000/0710-Random-Pick-with-Blacklist/cpp-0710/main2.cpp new file mode 100644 index 00000000..44c74dad --- /dev/null +++ b/0501-1000/0710-Random-Pick-with-Blacklist/cpp-0710/main2.cpp @@ -0,0 +1,82 @@ +/// Source : https://leetcode.com/problems/random-pick-with-blacklist/description/ +/// Author : liuyubobobo +/// Time : 2018-07-08 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// Binary Search the answer +/// Time Complexity: init: O(BlogB), where B is len(blacklist) +/// pick: O(logB) +/// Space Complexity: O(B) +class Solution { + +private: + vector b; + unordered_set bset; + int N; + +public: + Solution(int N, vector blacklist): b(blacklist) { + + sort(b.begin(), b.end()); + this->N = N; + + bset.clear(); + for(int num: b) + bset.insert(num); + + srand(time(NULL)); + } + + int pick() { + int limit = N - b.size(); + int res = rand() % limit; + + int l = 0, r = N - 1; + while(l <= r){ + int mid = l + (r - l) / 2; + int rb = b.end() - lower_bound(b.begin(), b.end(), mid); + int lb = b.size() - rb; + + if(bset.find(mid) != bset.end()){ + if(mid - lb > res) + r = mid - 1; + else + l = mid + 1; + } + else{ + if(mid - lb == res) + return mid; + else if(mid - lb < res) + l = mid + 1; + else + r = mid - 1; + } + } + return res; + } +}; + + +int main() { + + Solution solution1(2, {1}); + cout << solution1.pick() << endl; // 0 + + Solution solution2(3, {1, 2}); + cout << solution2.pick() << endl; // 0 + + Solution solution3(2, {}); + for(int i = 0 ; i < 20 ; i ++) + cout << solution3.pick() << " "; // half 0, half 1 + cout << endl; + + return 0; +} \ No newline at end of file diff --git a/0711-Number-of-Distinct-Islands-II/cpp-0711/CMakeLists.txt b/0501-1000/0711-Number-of-Distinct-Islands-II/cpp-0711/CMakeLists.txt similarity index 100% rename from 0711-Number-of-Distinct-Islands-II/cpp-0711/CMakeLists.txt rename to 0501-1000/0711-Number-of-Distinct-Islands-II/cpp-0711/CMakeLists.txt diff --git a/0711-Number-of-Distinct-Islands-II/cpp-0711/main.cpp b/0501-1000/0711-Number-of-Distinct-Islands-II/cpp-0711/main.cpp similarity index 100% rename from 0711-Number-of-Distinct-Islands-II/cpp-0711/main.cpp rename to 0501-1000/0711-Number-of-Distinct-Islands-II/cpp-0711/main.cpp diff --git a/0712-Minimum-ASCII-Delete-Sum-for-Two-Strings/cpp-0712/CMakeLists.txt b/0501-1000/0712-Minimum-ASCII-Delete-Sum-for-Two-Strings/cpp-0712/CMakeLists.txt similarity index 100% rename from 0712-Minimum-ASCII-Delete-Sum-for-Two-Strings/cpp-0712/CMakeLists.txt rename to 0501-1000/0712-Minimum-ASCII-Delete-Sum-for-Two-Strings/cpp-0712/CMakeLists.txt diff --git a/0712-Minimum-ASCII-Delete-Sum-for-Two-Strings/cpp-0712/main.cpp b/0501-1000/0712-Minimum-ASCII-Delete-Sum-for-Two-Strings/cpp-0712/main.cpp similarity index 100% rename from 0712-Minimum-ASCII-Delete-Sum-for-Two-Strings/cpp-0712/main.cpp rename to 0501-1000/0712-Minimum-ASCII-Delete-Sum-for-Two-Strings/cpp-0712/main.cpp diff --git a/0712-Minimum-ASCII-Delete-Sum-for-Two-Strings/cpp-0712/main2.cpp b/0501-1000/0712-Minimum-ASCII-Delete-Sum-for-Two-Strings/cpp-0712/main2.cpp similarity index 100% rename from 0712-Minimum-ASCII-Delete-Sum-for-Two-Strings/cpp-0712/main2.cpp rename to 0501-1000/0712-Minimum-ASCII-Delete-Sum-for-Two-Strings/cpp-0712/main2.cpp diff --git a/0712-Minimum-ASCII-Delete-Sum-for-Two-Strings/cpp-0712/main3.cpp b/0501-1000/0712-Minimum-ASCII-Delete-Sum-for-Two-Strings/cpp-0712/main3.cpp similarity index 100% rename from 0712-Minimum-ASCII-Delete-Sum-for-Two-Strings/cpp-0712/main3.cpp rename to 0501-1000/0712-Minimum-ASCII-Delete-Sum-for-Two-Strings/cpp-0712/main3.cpp diff --git a/0712-Minimum-ASCII-Delete-Sum-for-Two-Strings/cpp-0712/main4.cpp b/0501-1000/0712-Minimum-ASCII-Delete-Sum-for-Two-Strings/cpp-0712/main4.cpp similarity index 100% rename from 0712-Minimum-ASCII-Delete-Sum-for-Two-Strings/cpp-0712/main4.cpp rename to 0501-1000/0712-Minimum-ASCII-Delete-Sum-for-Two-Strings/cpp-0712/main4.cpp diff --git a/0713-Subarray-Product-Less-Than-K/cpp-0713/CMakeLists.txt b/0501-1000/0713-Subarray-Product-Less-Than-K/cpp-0713/CMakeLists.txt similarity index 100% rename from 0713-Subarray-Product-Less-Than-K/cpp-0713/CMakeLists.txt rename to 0501-1000/0713-Subarray-Product-Less-Than-K/cpp-0713/CMakeLists.txt diff --git a/0713-Subarray-Product-Less-Than-K/cpp-0713/main.cpp b/0501-1000/0713-Subarray-Product-Less-Than-K/cpp-0713/main.cpp similarity index 100% rename from 0713-Subarray-Product-Less-Than-K/cpp-0713/main.cpp rename to 0501-1000/0713-Subarray-Product-Less-Than-K/cpp-0713/main.cpp diff --git a/0713-Subarray-Product-Less-Than-K/cpp-0713/main2.cpp b/0501-1000/0713-Subarray-Product-Less-Than-K/cpp-0713/main2.cpp similarity index 100% rename from 0713-Subarray-Product-Less-Than-K/cpp-0713/main2.cpp rename to 0501-1000/0713-Subarray-Product-Less-Than-K/cpp-0713/main2.cpp diff --git a/0714-Best-Time-to-Buy-and-Sell-Stock-with-Transaction-Fee/cpp-0714/CMakeLists.txt b/0501-1000/0714-Best-Time-to-Buy-and-Sell-Stock-with-Transaction-Fee/cpp-0714/CMakeLists.txt similarity index 100% rename from 0714-Best-Time-to-Buy-and-Sell-Stock-with-Transaction-Fee/cpp-0714/CMakeLists.txt rename to 0501-1000/0714-Best-Time-to-Buy-and-Sell-Stock-with-Transaction-Fee/cpp-0714/CMakeLists.txt diff --git a/0714-Best-Time-to-Buy-and-Sell-Stock-with-Transaction-Fee/cpp-0714/main.cpp b/0501-1000/0714-Best-Time-to-Buy-and-Sell-Stock-with-Transaction-Fee/cpp-0714/main.cpp similarity index 100% rename from 0714-Best-Time-to-Buy-and-Sell-Stock-with-Transaction-Fee/cpp-0714/main.cpp rename to 0501-1000/0714-Best-Time-to-Buy-and-Sell-Stock-with-Transaction-Fee/cpp-0714/main.cpp diff --git a/0715-Range-Module/cpp-0715/CMakeLists.txt b/0501-1000/0715-Range-Module/cpp-0715/CMakeLists.txt similarity index 100% rename from 0715-Range-Module/cpp-0715/CMakeLists.txt rename to 0501-1000/0715-Range-Module/cpp-0715/CMakeLists.txt diff --git a/0715-Range-Module/cpp-0715/main.cpp b/0501-1000/0715-Range-Module/cpp-0715/main.cpp similarity index 100% rename from 0715-Range-Module/cpp-0715/main.cpp rename to 0501-1000/0715-Range-Module/cpp-0715/main.cpp diff --git a/0501-1000/0716-Max-Stack/cpp-0716/CMakeLists.txt b/0501-1000/0716-Max-Stack/cpp-0716/CMakeLists.txt new file mode 100644 index 00000000..ecac7975 --- /dev/null +++ b/0501-1000/0716-Max-Stack/cpp-0716/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0716) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0716 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0716-Max-Stack/cpp-0716/main.cpp b/0501-1000/0716-Max-Stack/cpp-0716/main.cpp new file mode 100644 index 00000000..fe295a10 --- /dev/null +++ b/0501-1000/0716-Max-Stack/cpp-0716/main.cpp @@ -0,0 +1,92 @@ +/// Source : https://leetcode.com/problems/max-stack/description/ +/// Author : liuyubobobo +/// Time : 2017-11-16 + +#include +#include +#include + +using namespace std; + + +/// Using two sets +/// Time Complexity: push: O(logn) +/// pop: O(logn) +/// top: O(logn) +/// peekMax: O(logn) +/// popMax: O(logn) +/// Space Complexity: O(n) +class MaxStack { + +private: + int index = 0; + set> vi; // value - index + set> iv; // index - value + +public: + /** initialize your data structure here. */ + MaxStack() { + vi.clear(); + iv.clear(); + index = 0; + } + + void push(int x) { + vi.insert(make_pair(x, index)); + iv.insert(make_pair(index, x)); + index ++; + } + + int pop() { + + assert(iv.size() > 0); + + pair e_iv = *iv.rbegin(); + iv.erase(e_iv); + + pair e_vi = make_pair(e_iv.second, e_iv.first); + vi.erase(e_vi); + + return e_iv.second; + } + + int top() { + assert(iv.size() > 0); + return iv.rbegin()->second; + } + + int peekMax() { + assert(vi.size() > 0); + return vi.rbegin()->first; + } + + int popMax() { + + assert(vi.size() > 0); + + pair e_vi = *vi.rbegin(); + vi.erase(e_vi); + + pair e_iv = make_pair(e_vi.second, e_vi.first); + iv.erase(e_iv); + + return e_vi.first; + } +}; + + +int main() { + + MaxStack stack; + stack.push(5); + stack.push(1); + stack.push(5); + cout << stack.top() << endl; // -> 5 + cout << stack.popMax() << endl; // -> 5 + cout << stack.top() << endl; // -> 1 + cout << stack.peekMax() << endl; // -> 5 + cout << stack.pop() << endl; // -> 1 + cout << stack.top() << endl; // -> 5 + + return 0; +} \ No newline at end of file diff --git a/0717-1-bit-and-2-bit-Characters/cpp-0717/CMakeLists.txt b/0501-1000/0717-1-bit-and-2-bit-Characters/cpp-0717/CMakeLists.txt similarity index 100% rename from 0717-1-bit-and-2-bit-Characters/cpp-0717/CMakeLists.txt rename to 0501-1000/0717-1-bit-and-2-bit-Characters/cpp-0717/CMakeLists.txt diff --git a/0717-1-bit-and-2-bit-Characters/cpp-0717/main.cpp b/0501-1000/0717-1-bit-and-2-bit-Characters/cpp-0717/main.cpp similarity index 100% rename from 0717-1-bit-and-2-bit-Characters/cpp-0717/main.cpp rename to 0501-1000/0717-1-bit-and-2-bit-Characters/cpp-0717/main.cpp diff --git a/0717-1-bit-and-2-bit-Characters/cpp-0717/main2.cpp b/0501-1000/0717-1-bit-and-2-bit-Characters/cpp-0717/main2.cpp similarity index 100% rename from 0717-1-bit-and-2-bit-Characters/cpp-0717/main2.cpp rename to 0501-1000/0717-1-bit-and-2-bit-Characters/cpp-0717/main2.cpp diff --git a/0718-Maximum-Length-of-Repeated-Subarray/cpp-0718/CMakeLists.txt b/0501-1000/0718-Maximum-Length-of-Repeated-Subarray/cpp-0718/CMakeLists.txt similarity index 100% rename from 0718-Maximum-Length-of-Repeated-Subarray/cpp-0718/CMakeLists.txt rename to 0501-1000/0718-Maximum-Length-of-Repeated-Subarray/cpp-0718/CMakeLists.txt diff --git a/0718-Maximum-Length-of-Repeated-Subarray/cpp-0718/main.cpp b/0501-1000/0718-Maximum-Length-of-Repeated-Subarray/cpp-0718/main.cpp similarity index 100% rename from 0718-Maximum-Length-of-Repeated-Subarray/cpp-0718/main.cpp rename to 0501-1000/0718-Maximum-Length-of-Repeated-Subarray/cpp-0718/main.cpp diff --git a/0718-Maximum-Length-of-Repeated-Subarray/cpp-0718/main2.cpp b/0501-1000/0718-Maximum-Length-of-Repeated-Subarray/cpp-0718/main2.cpp similarity index 100% rename from 0718-Maximum-Length-of-Repeated-Subarray/cpp-0718/main2.cpp rename to 0501-1000/0718-Maximum-Length-of-Repeated-Subarray/cpp-0718/main2.cpp diff --git a/0719-Find-K-th-Smallest-Pair-Distance/cpp-0719/CMakeLists.txt b/0501-1000/0719-Find-K-th-Smallest-Pair-Distance/cpp-0719/CMakeLists.txt similarity index 100% rename from 0719-Find-K-th-Smallest-Pair-Distance/cpp-0719/CMakeLists.txt rename to 0501-1000/0719-Find-K-th-Smallest-Pair-Distance/cpp-0719/CMakeLists.txt diff --git a/0501-1000/0719-Find-K-th-Smallest-Pair-Distance/cpp-0719/main.cpp b/0501-1000/0719-Find-K-th-Smallest-Pair-Distance/cpp-0719/main.cpp new file mode 100644 index 00000000..1b10ca51 --- /dev/null +++ b/0501-1000/0719-Find-K-th-Smallest-Pair-Distance/cpp-0719/main.cpp @@ -0,0 +1,59 @@ +/// Source : https://leetcode.com/problems/find-k-th-smallest-pair-distance/description/ +/// Author : liuyubobobo +/// Time : 2022-06-14 + +#include +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(log(max_dis) * nlogn) +/// Space Complexity: O(1) +class Solution { +public: + int smallestDistancePair(vector& nums, int k) { + + int n = nums.size(); + + sort(nums.begin(), nums.end()); + int l = 0, r = nums.back() - nums[0]; + while(l < r){ + int d = (l + r) / 2; + if(dis_cnt_less_than_or_equal_to(n, nums, d) >= k) r = d; + else l = d + 1; + } + return l; + } + +private: + int dis_cnt_less_than_or_equal_to(int n, const vector& nums, int d){ + + int cnt = 0; + for(int i = 0; i < n; i ++){ + auto iter = upper_bound(nums.begin(), nums.end(), nums[i] + d); + cnt += iter - nums.begin() - i - 1; + } + return cnt; + } +}; + + +int main() { + + vector nums1 = {1, 3, 1}; + cout << Solution().smallestDistancePair(nums1, 1) << endl; + // 0 + + vector nums2 = {1, 1, 1}; + cout << Solution().smallestDistancePair(nums2, 2) << endl; + // 0 + + vector nums3 = {1, 6, 1}; + cout << Solution().smallestDistancePair(nums3, 3) << endl; + // 5 + + return 0; +} \ No newline at end of file diff --git a/0720-Longest-Word-in-Dictionary/cpp-0720/CMakeLists.txt b/0501-1000/0720-Longest-Word-in-Dictionary/cpp-0720/CMakeLists.txt similarity index 100% rename from 0720-Longest-Word-in-Dictionary/cpp-0720/CMakeLists.txt rename to 0501-1000/0720-Longest-Word-in-Dictionary/cpp-0720/CMakeLists.txt diff --git a/0720-Longest-Word-in-Dictionary/cpp-0720/main.cpp b/0501-1000/0720-Longest-Word-in-Dictionary/cpp-0720/main.cpp similarity index 100% rename from 0720-Longest-Word-in-Dictionary/cpp-0720/main.cpp rename to 0501-1000/0720-Longest-Word-in-Dictionary/cpp-0720/main.cpp diff --git a/0720-Longest-Word-in-Dictionary/cpp-0720/main2.cpp b/0501-1000/0720-Longest-Word-in-Dictionary/cpp-0720/main2.cpp similarity index 100% rename from 0720-Longest-Word-in-Dictionary/cpp-0720/main2.cpp rename to 0501-1000/0720-Longest-Word-in-Dictionary/cpp-0720/main2.cpp diff --git a/0721-Accounts-Merge/cpp-0721/CMakeLists.txt b/0501-1000/0721-Accounts-Merge/cpp-0721/CMakeLists.txt similarity index 100% rename from 0721-Accounts-Merge/cpp-0721/CMakeLists.txt rename to 0501-1000/0721-Accounts-Merge/cpp-0721/CMakeLists.txt diff --git a/0721-Accounts-Merge/cpp-0721/main.cpp b/0501-1000/0721-Accounts-Merge/cpp-0721/main.cpp similarity index 100% rename from 0721-Accounts-Merge/cpp-0721/main.cpp rename to 0501-1000/0721-Accounts-Merge/cpp-0721/main.cpp diff --git a/0721-Accounts-Merge/cpp-0721/main2.cpp b/0501-1000/0721-Accounts-Merge/cpp-0721/main2.cpp similarity index 100% rename from 0721-Accounts-Merge/cpp-0721/main2.cpp rename to 0501-1000/0721-Accounts-Merge/cpp-0721/main2.cpp diff --git a/0722-Remove-Comments/cpp-0722/CMakeLists.txt b/0501-1000/0722-Remove-Comments/cpp-0722/CMakeLists.txt similarity index 100% rename from 0722-Remove-Comments/cpp-0722/CMakeLists.txt rename to 0501-1000/0722-Remove-Comments/cpp-0722/CMakeLists.txt diff --git a/0722-Remove-Comments/cpp-0722/main.cpp b/0501-1000/0722-Remove-Comments/cpp-0722/main.cpp similarity index 100% rename from 0722-Remove-Comments/cpp-0722/main.cpp rename to 0501-1000/0722-Remove-Comments/cpp-0722/main.cpp diff --git a/0723-Candy-Crush/cpp-0723/CMakeLists.txt b/0501-1000/0723-Candy-Crush/cpp-0723/CMakeLists.txt similarity index 100% rename from 0723-Candy-Crush/cpp-0723/CMakeLists.txt rename to 0501-1000/0723-Candy-Crush/cpp-0723/CMakeLists.txt diff --git a/0723-Candy-Crush/cpp-0723/main.cpp b/0501-1000/0723-Candy-Crush/cpp-0723/main.cpp similarity index 100% rename from 0723-Candy-Crush/cpp-0723/main.cpp rename to 0501-1000/0723-Candy-Crush/cpp-0723/main.cpp diff --git a/0724-Find-Pivot-Index/cpp-0724/CMakeLists.txt b/0501-1000/0724-Find-Pivot-Index/cpp-0724/CMakeLists.txt similarity index 100% rename from 0724-Find-Pivot-Index/cpp-0724/CMakeLists.txt rename to 0501-1000/0724-Find-Pivot-Index/cpp-0724/CMakeLists.txt diff --git a/0724-Find-Pivot-Index/cpp-0724/main.cpp b/0501-1000/0724-Find-Pivot-Index/cpp-0724/main.cpp similarity index 100% rename from 0724-Find-Pivot-Index/cpp-0724/main.cpp rename to 0501-1000/0724-Find-Pivot-Index/cpp-0724/main.cpp diff --git a/0724-Find-Pivot-Index/cpp-0724/main2.cpp b/0501-1000/0724-Find-Pivot-Index/cpp-0724/main2.cpp similarity index 100% rename from 0724-Find-Pivot-Index/cpp-0724/main2.cpp rename to 0501-1000/0724-Find-Pivot-Index/cpp-0724/main2.cpp diff --git a/0725-Split-Linked-List-in-Parts/cpp-0725/CMakeLists.txt b/0501-1000/0725-Split-Linked-List-in-Parts/cpp-0725/CMakeLists.txt similarity index 100% rename from 0725-Split-Linked-List-in-Parts/cpp-0725/CMakeLists.txt rename to 0501-1000/0725-Split-Linked-List-in-Parts/cpp-0725/CMakeLists.txt diff --git a/0725-Split-Linked-List-in-Parts/cpp-0725/main.cpp b/0501-1000/0725-Split-Linked-List-in-Parts/cpp-0725/main.cpp similarity index 100% rename from 0725-Split-Linked-List-in-Parts/cpp-0725/main.cpp rename to 0501-1000/0725-Split-Linked-List-in-Parts/cpp-0725/main.cpp diff --git a/0725-Split-Linked-List-in-Parts/cpp-0725/main2.cpp b/0501-1000/0725-Split-Linked-List-in-Parts/cpp-0725/main2.cpp similarity index 100% rename from 0725-Split-Linked-List-in-Parts/cpp-0725/main2.cpp rename to 0501-1000/0725-Split-Linked-List-in-Parts/cpp-0725/main2.cpp diff --git a/0501-1000/0726-Number-of-Atoms/cpp-0726/CMakeLists.txt b/0501-1000/0726-Number-of-Atoms/cpp-0726/CMakeLists.txt new file mode 100644 index 00000000..8bdd5234 --- /dev/null +++ b/0501-1000/0726-Number-of-Atoms/cpp-0726/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_0726) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0726 main.cpp) \ No newline at end of file diff --git a/0501-1000/0726-Number-of-Atoms/cpp-0726/main.cpp b/0501-1000/0726-Number-of-Atoms/cpp-0726/main.cpp new file mode 100644 index 00000000..05b2b089 --- /dev/null +++ b/0501-1000/0726-Number-of-Atoms/cpp-0726/main.cpp @@ -0,0 +1,117 @@ +/// Source : https://leetcode.com/problems/number-of-atoms/ +/// Author : liuyubobobo +/// Time : 2021-07-03 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { +public: + string countOfAtoms(string formula) { + + int n = formula.size(); + + vector right(n, -1); + stack stack; + for(int i = 0; i < n; i ++) + if(formula[i] == '(') stack.push(i); + else if(formula[i] == ')'){ + assert(!stack.empty()); + right[stack.top()] = i; + stack.pop(); + } + assert(stack.empty()); + + map res = dfs(formula, 0, n - 1, right); + + string ret = ""; + for(const pair& p: res){ + ret += p.first; + if(p.second > 1) ret += to_string(p.second); + } + return ret; + } + + map dfs(const string& s, int l, int r, const vector& right){ + + if(l > r) return {}; + + map res; + for(int i = l; i <= r; ){ + if(s[i] == '('){ + map tres = dfs(s, i + 1, right[i] - 1, right); + i = right[i] + 1; + + int a = 1; + if(i < s.size() && isdigit(s[i])){ + int next_non_digit = get_next_non_digit(s, i); + a = atoi(s.substr(i, next_non_digit - i).c_str()); + + i = next_non_digit; + } + + for(const pair& p: tres) + res[p.first] += p.second * a; + } + else{ + int next_pos = get_next_e_char(s, i); + string e = s.substr(i, next_pos - i); + + i = next_pos; + if(i < s.size() && isdigit(s[i])){ + int next_non_digit = get_next_non_digit(s, i); + int v = atoi(s.substr(i, next_non_digit - i).c_str()); + + res[e] += v; + i = next_non_digit; + } + else{ + res[e] += 1; + } + } + } + return res; + } + +private: + int get_next_e_char(const string& s, int start){ + + for(int i = start + 1; i < s.size(); i ++) + if(!islower(s[i])) return i; + return s.size(); + } + + int get_next_non_digit(const string& s, int start){ + + for(int i = start; i < s.size(); i ++) + if(!isdigit(s[i])) return i; + return s.size(); + } +}; + + +int main() { + + cout << Solution().countOfAtoms("H2O") << endl; + // H2O + + cout << Solution().countOfAtoms("Mg(OH)2") << endl; + // H2MgO2 + + cout << Solution().countOfAtoms("K4(ON(SO3)2)2") << endl; + // K4N2O14S4 + + cout << Solution().countOfAtoms("Be32") << endl; + // Be32 + + return 0; +} diff --git a/0736-Parse-Lisp-Expression/cpp-0736/CMakeLists.txt b/0501-1000/0727-Minimum-Window-Subsequence/cpp-0727/CMakeLists.txt similarity index 100% rename from 0736-Parse-Lisp-Expression/cpp-0736/CMakeLists.txt rename to 0501-1000/0727-Minimum-Window-Subsequence/cpp-0727/CMakeLists.txt diff --git a/0501-1000/0727-Minimum-Window-Subsequence/cpp-0727/main.cpp b/0501-1000/0727-Minimum-Window-Subsequence/cpp-0727/main.cpp new file mode 100644 index 00000000..d41f3ca2 --- /dev/null +++ b/0501-1000/0727-Minimum-Window-Subsequence/cpp-0727/main.cpp @@ -0,0 +1,93 @@ +/// Source : https://leetcode.com/contest/weekly-contest-58/problems/minimum-window-subsequence/ +/// Author : liuyubobobo +/// Time : 2017-11-12 +/// Updated: 2023-04-22 + +#include +#include +#include +#include + +using namespace std; + + +/// Dynamic Programming with Rolling 1-D Array +/// dp[i][j] - the minimum length W for subsequence in S[i...end) to satify T[j...end) +/// the result is the minimum value for all dp[i][0] where len(S[i...end)) > len(T) +/// +/// Time Complexity: O(len(S)*len(T)) +/// Space Complexity: O(len(T)) +class Solution { + +private: + int MY_MAX_INT = 20001; + +public: + string minWindow(string S, string T) { + + vector> dp(2, vector(T.size(), MY_MAX_INT)); + + int min_length = MY_MAX_INT; + int start = -1; + + dp[(S.size()-1)%2][T.size()-1] = (S.back() == T.back() ? 1 : MY_MAX_INT); + if(dp[(S.size()-1)%2][0] == 1 && T.size() == 1){ + min_length = 1; + start = S.size()-1; + } + else + for(int j = T.size()-2 ; j >= 0 ; j --) + dp[(S.size()-1)%2][j] = MY_MAX_INT; + + for(int i = S.size()-2 ; i >= 0 ; i --){ + dp[i%2][T.size()-1] = dp[(i+1)%2][T.size()-1] + 1; + if(S[i] == T.back()) + dp[i%2][T.size()-1] = 1; + + for(int j = T.size() - 2 ; j >= 0 ; j --){ + dp[i%2][j] = min(MY_MAX_INT, 1 + dp[(i+1)%2][j]); + if(S[i] == T[j]) + dp[i%2][j] = min(dp[i%2][j], 1 + dp[(i+1)%2][j+1]); + } + + if(i + T.size() <= S.size() && dp[i%2][0] <= min_length){ + min_length = dp[i%2][0]; + start = i; + } + } + + return (start != -1 && min_length < MY_MAX_INT) ? + S.substr(start, min_length) : ""; + } +}; + + +int main() { + + string S1 = "abcdebdde"; + string T1 = "bde"; + cout << Solution().minWindow(S1, T1) << endl; + // bcde + + string S2 = "ab"; + string T2 = "b"; + cout << Solution().minWindow(S2, T2) << endl; + // b + + string S3 = "cnhczmccqouqadqtmjjzl"; + string T3 = "mm"; + cout << Solution().minWindow(S3, T3) << endl; + // mccqouqadqtm + + string S4 = "clgkckxqhqojiroohcudeyhlylicvafvpbubcjictifyoshucybzswblioaflxaoxdjbjejvzgqiuedmzgmqbhpkjlwxvobrcgqhzzelxppwdkwqlplflnldxpkwobqyqhqbfcxolrmrllmzpgjemzhscagqxhyuqquopquyyxwcuetxnxebbrgsbiwtkqdpqmvsprrnyficfxagfsssvppwqdsqesz"; + string T4 = "cihfrleqav"; + cout << Solution().minWindow(S4, T4) << endl; + // cybzswblioaflxaoxdjbjejvzgqiuedmzgmqbhpkjlwxvobrcgqhzzelxppwdkwqlplflnldxpkwobqyqhqbfcxolrmrllmzpgjemzhscagqxhyuqquopquyyxwcuetxnxebbrgsbiwtkqdpqmvsprrnyficfxagfsssv + + string S5 = "aaa"; + string T5 = "aaaaaaaa"; + cout << Solution().minWindow(S5, T5) << endl; + // mccqouqadqtm + + return 0; +} \ No newline at end of file diff --git a/0728-Self-Dividing-Numbers/cpp-0728/CMakeLists.txt b/0501-1000/0728-Self-Dividing-Numbers/cpp-0728/CMakeLists.txt similarity index 100% rename from 0728-Self-Dividing-Numbers/cpp-0728/CMakeLists.txt rename to 0501-1000/0728-Self-Dividing-Numbers/cpp-0728/CMakeLists.txt diff --git a/0501-1000/0728-Self-Dividing-Numbers/cpp-0728/main.cpp b/0501-1000/0728-Self-Dividing-Numbers/cpp-0728/main.cpp new file mode 100644 index 00000000..186385ac --- /dev/null +++ b/0501-1000/0728-Self-Dividing-Numbers/cpp-0728/main.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/longest-increasing-subsequence/description/ +/// Author : liuyubobobo +/// Time : 2017-11-18 +/// Updated: 2022-03-30 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O((right-left+1) * log(right)) +/// Space Complexity: O(1) +class Solution { + +public: + vector selfDividingNumbers(int left, int right) { + + vector res; + for(int i = left ; i <= right ; i ++) + if(is_self_dividing(i)) + res.push_back(i); + return res; + } + +private: + bool is_self_dividing(int num){ + int t = num; + while(t){ + int x = t % 10; + t /= 10; + if(x == 0 || num % x != 0) + return false; + } + return true; + } +}; + + +void print_vec(const vector& vec){ + for(int e: vec) + cout << e << ' '; + cout << endl; +} + +int main() { + + print_vec(Solution().selfDividingNumbers(1, 22)); + + return 0; +} \ No newline at end of file diff --git a/0729-My Calendar-I/cpp-0729/CMakeLists.txt b/0501-1000/0729-My Calendar-I/cpp-0729/CMakeLists.txt similarity index 100% rename from 0729-My Calendar-I/cpp-0729/CMakeLists.txt rename to 0501-1000/0729-My Calendar-I/cpp-0729/CMakeLists.txt diff --git a/0729-My Calendar-I/cpp-0729/main.cpp b/0501-1000/0729-My Calendar-I/cpp-0729/main.cpp similarity index 100% rename from 0729-My Calendar-I/cpp-0729/main.cpp rename to 0501-1000/0729-My Calendar-I/cpp-0729/main.cpp diff --git a/0729-My Calendar-I/cpp-0729/main2.cpp b/0501-1000/0729-My Calendar-I/cpp-0729/main2.cpp similarity index 100% rename from 0729-My Calendar-I/cpp-0729/main2.cpp rename to 0501-1000/0729-My Calendar-I/cpp-0729/main2.cpp diff --git a/0729-My Calendar-I/cpp-0729/main3.cpp b/0501-1000/0729-My Calendar-I/cpp-0729/main3.cpp similarity index 100% rename from 0729-My Calendar-I/cpp-0729/main3.cpp rename to 0501-1000/0729-My Calendar-I/cpp-0729/main3.cpp diff --git a/0729-My Calendar-I/cpp-0729/main4.cpp b/0501-1000/0729-My Calendar-I/cpp-0729/main4.cpp similarity index 100% rename from 0729-My Calendar-I/cpp-0729/main4.cpp rename to 0501-1000/0729-My Calendar-I/cpp-0729/main4.cpp diff --git a/0501-1000/0730-Count-Different-Palindromic-Subsequences/cpp-0730/CMakeLists.txt b/0501-1000/0730-Count-Different-Palindromic-Subsequences/cpp-0730/CMakeLists.txt new file mode 100644 index 00000000..941370ff --- /dev/null +++ b/0501-1000/0730-Count-Different-Palindromic-Subsequences/cpp-0730/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_0730) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0730 main.cpp) diff --git a/0501-1000/0730-Count-Different-Palindromic-Subsequences/cpp-0730/main.cpp b/0501-1000/0730-Count-Different-Palindromic-Subsequences/cpp-0730/main.cpp new file mode 100644 index 00000000..f02d9639 --- /dev/null +++ b/0501-1000/0730-Count-Different-Palindromic-Subsequences/cpp-0730/main.cpp @@ -0,0 +1,72 @@ +/// Source : https://leetcode.com/problems/count-different-palindromic-subsequences/ +/// Author : liuyubobobo +/// Time : 2022-06-09 + +#include +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(n^2) +/// Space Complexity: O(n^2) +class Solution { + +private: + const long long MOD = 1e9 + 7; + +public: + int countPalindromicSubsequences(const string& s) { + + int n = s.size(); + + vector>> dp(4, vector>(n, vector(n, 0))); + for(int i = 0; i < n; i ++) dp[s[i] - 'a'][i][i] = 1; + for(int i = 0; i + 1 < n; i ++){ + if(s[i] == s[i + 1]) dp[s[i] - 'a'][i][i + 1] = 2; + else{ + dp[s[i] - 'a'][i][i + 1] = dp[s[i + 1] - 'a'][i][i + 1] = 1; + } + } + + for(int len = 3; len <= n; len ++){ + for(int l = 0; l + len - 1 < n; l ++){ + int r = l + len - 1; + + for(char border = 0; border < 4; border ++){ + if(s[l] == s[r] && s[l] == 'a' + border){ + dp[border][l][r] = 2; + for(char c = 0; c < 4; c ++) + dp[border][l][r] += dp[c][l + 1][r - 1]; + dp[border][l][r] %= MOD; + } + else{ + dp[border][l][r] = dp[border][l][r - 1] + dp[border][l + 1][r] - dp[border][l + 1][r - 1] + MOD; + dp[border][l][r] %= MOD; + } + } + } + } + + long long res = 0; + for(int border = 0; border < 4; border ++) + res += dp[border][0][n - 1]; + return res % MOD; + } +}; + + +int main() { + + cout << Solution().countPalindromicSubsequences("bccb") << '\n'; + // 6 + + cout << Solution().countPalindromicSubsequences("abcdabcdabcdabcdabcdabcdabcdabcddcbadcbadcbadcbadcbadcbadcbadcba") << '\n'; + // 104860361 + + cout << Solution().countPalindromicSubsequences("baccdabbccbdbbbcdbbcdbacdabaaddcdbcabdbddadbdaaadbbdaabbdaccdabbddaaccdbbcdbcdbbaaababdddbdccbbaddabdbdabddbaccddabaccadacddbbbdacacaaddaccbabcbcbbcbcadccbccddcddccdabdabaddacdcdcbdadabbcddacbbbbacbcadbccacddddacbdcddbddbddbcabcbdacadbdccabddaacadddbadbccdacbaabababcababccddacabadbcaacbadcbacaadabbadabaabdbcabdabaddabdcacbdbacbcdcacdcaaccadabacbadcdabddccaaacdaadacbbcadcbbccaccbbbdcbcaabbbddcdaaddbdbbdacdaabacbacdabbbdbdaaddbddadbabcdabaddbbadcaadcddcaaddcdbbbbddcccaacdbdbcccccddadbacbdbcacabddaabcbbbbcadbbcabbabcbcdccdcaddabbbddbbdadbbbdadbbdaaacbbbbdbbcadcbbcddddcacdcbddcaacbaccacaddcdacbadccaabdabadbbcccabddcbbcdaacddaacccbacccacbddbcdcdaabbbacdcbabaaaaaacdabcddbcbaccabacddaccadaaddddaaaccbccdbdcdcdbdccdcbdbddbcdbcbdaacaccdabdbabcdbdbadcbcbbaabaccbbababdbbddbcacadbaaadbcccadaddbccddbcadaccbaddcdacaabbbbdbcddacbdccddaadabbbaccddbcbacbbbcbbbbcbbccdbaccdddaddaaacdababcdabdacdbaacdadbaabcadcddccabcccadabbdbbadbcadbdbaddaabbbcdbbbddcdbddbabcdccddccbaccbabcdcddddabbabdccbaddccacdddadcaadd") << endl; + + return 0; +} diff --git a/0731-My-Calendar-II/cpp-0731/CMakeLists.txt b/0501-1000/0731-My-Calendar-II/cpp-0731/CMakeLists.txt similarity index 100% rename from 0731-My-Calendar-II/cpp-0731/CMakeLists.txt rename to 0501-1000/0731-My-Calendar-II/cpp-0731/CMakeLists.txt diff --git a/0731-My-Calendar-II/cpp-0731/main.cpp b/0501-1000/0731-My-Calendar-II/cpp-0731/main.cpp similarity index 100% rename from 0731-My-Calendar-II/cpp-0731/main.cpp rename to 0501-1000/0731-My-Calendar-II/cpp-0731/main.cpp diff --git a/0731-My-Calendar-II/cpp-0731/main2.cpp b/0501-1000/0731-My-Calendar-II/cpp-0731/main2.cpp similarity index 100% rename from 0731-My-Calendar-II/cpp-0731/main2.cpp rename to 0501-1000/0731-My-Calendar-II/cpp-0731/main2.cpp diff --git a/0731-My-Calendar-II/cpp-0731/main3.cpp b/0501-1000/0731-My-Calendar-II/cpp-0731/main3.cpp similarity index 100% rename from 0731-My-Calendar-II/cpp-0731/main3.cpp rename to 0501-1000/0731-My-Calendar-II/cpp-0731/main3.cpp diff --git a/0731-My-Calendar-II/cpp-0731/main4.cpp b/0501-1000/0731-My-Calendar-II/cpp-0731/main4.cpp similarity index 100% rename from 0731-My-Calendar-II/cpp-0731/main4.cpp rename to 0501-1000/0731-My-Calendar-II/cpp-0731/main4.cpp diff --git a/0732-My-Calendar-III/cpp-0732/CMakeLists.txt b/0501-1000/0732-My-Calendar-III/cpp-0732/CMakeLists.txt similarity index 100% rename from 0732-My-Calendar-III/cpp-0732/CMakeLists.txt rename to 0501-1000/0732-My-Calendar-III/cpp-0732/CMakeLists.txt diff --git a/0732-My-Calendar-III/cpp-0732/main.cpp b/0501-1000/0732-My-Calendar-III/cpp-0732/main.cpp similarity index 100% rename from 0732-My-Calendar-III/cpp-0732/main.cpp rename to 0501-1000/0732-My-Calendar-III/cpp-0732/main.cpp diff --git a/0732-My-Calendar-III/cpp-0732/main2.cpp b/0501-1000/0732-My-Calendar-III/cpp-0732/main2.cpp similarity index 100% rename from 0732-My-Calendar-III/cpp-0732/main2.cpp rename to 0501-1000/0732-My-Calendar-III/cpp-0732/main2.cpp diff --git a/0783-Minimum-Distance-Between-BST-Nodes/cpp-0783/CMakeLists.txt b/0501-1000/0733-Flood-Fill/cpp-0733/CMakeLists.txt similarity index 100% rename from 0783-Minimum-Distance-Between-BST-Nodes/cpp-0783/CMakeLists.txt rename to 0501-1000/0733-Flood-Fill/cpp-0733/CMakeLists.txt diff --git a/0733-Flood-Fill/cpp-0733/main.cpp b/0501-1000/0733-Flood-Fill/cpp-0733/main.cpp similarity index 100% rename from 0733-Flood-Fill/cpp-0733/main.cpp rename to 0501-1000/0733-Flood-Fill/cpp-0733/main.cpp diff --git a/0733-Flood-Fill/cpp-0733/main2.cpp b/0501-1000/0733-Flood-Fill/cpp-0733/main2.cpp similarity index 100% rename from 0733-Flood-Fill/cpp-0733/main2.cpp rename to 0501-1000/0733-Flood-Fill/cpp-0733/main2.cpp diff --git a/0501-1000/0733-Flood-Fill/cpp-0733/main3.cpp b/0501-1000/0733-Flood-Fill/cpp-0733/main3.cpp new file mode 100644 index 00000000..bb72f7c9 --- /dev/null +++ b/0501-1000/0733-Flood-Fill/cpp-0733/main3.cpp @@ -0,0 +1,71 @@ +/// Source : https://leetcode.com/problems/flood-fill/description/ +/// Author : liuyubobobo +/// Time : 2018-09-29 + +#include +#include +#include + +using namespace std; + +/// BFS +/// +/// Time Complexity: O(n*m) +/// Space Complexity: O(n*m) +class Solution { + +private: + int d[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; + int n, m; + +public: + vector> floodFill(vector>& image, + int sr, int sc, int newColor) { + + n = image.size(); + m = image[0].size(); + int oldColor = image[sr][sc]; + + vector> visited(n, vector(m, false)); + queue> q; + q.push(make_pair(sr, sc)); + visited[sr][sc] = true; + while(!q.empty()){ + int x = q.front().first, y = q.front().second; + q.pop(); + + image[x][y] = newColor; + for(int i = 0; i < 4; i ++){ + int newX = x + d[i][0], newY = y + d[i][1]; + if(inArea(newX, newY) && !visited[newX][newY] && image[newX][newY] == oldColor){ + visited[newX][newY] = true; + q.push(make_pair(newX, newY)); + } + } + } + + return image; + } + +private: + bool inArea(int x, int y){ + return x >= 0 && x < n && y >= 0 && y < m; + } +}; + + +void printImage(const vector>& image){ + for(vector row: image){ + for(int pixel: row) + cout << pixel << "\t"; + cout << endl; + } +} + +int main() { + + vector> image = {{1, 1, 1}, {1, 1, 0}, {1, 0, 1}}; + printImage(Solution().floodFill(image, 1, 1, 2)); + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0733-Flood-Fill/cpp-0733/main4.cpp b/0501-1000/0733-Flood-Fill/cpp-0733/main4.cpp new file mode 100644 index 00000000..ebe2b993 --- /dev/null +++ b/0501-1000/0733-Flood-Fill/cpp-0733/main4.cpp @@ -0,0 +1,71 @@ +/// Source : https://leetcode.com/problems/flood-fill/description/ +/// Author : liuyubobobo +/// Time : 2018-09-29 + +#include +#include +#include + +using namespace std; + +/// DFS - Using Stack +/// +/// Time Complexity: O(n*m) +/// Space Complexity: O(n*m) +class Solution { + +private: + int d[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; + int n, m; + +public: + vector> floodFill(vector>& image, + int sr, int sc, int newColor) { + + n = image.size(); + m = image[0].size(); + int oldColor = image[sr][sc]; + + vector> visited(n, vector(m, false)); + stack> stack; + stack.push(make_pair(sr, sc)); + visited[sr][sc] = true; + while(!stack.empty()){ + int x = stack.top().first, y = stack.top().second; + stack.pop(); + + image[x][y] = newColor; + for(int i = 0; i < 4; i ++){ + int newX = x + d[i][0], newY = y + d[i][1]; + if(inArea(newX, newY) && !visited[newX][newY] && image[newX][newY] == oldColor){ + visited[newX][newY] = true; + stack.push(make_pair(newX, newY)); + } + } + } + + return image; + } + +private: + bool inArea(int x, int y){ + return x >= 0 && x < n && y >= 0 && y < m; + } +}; + + +void printImage(const vector>& image){ + for(vector row: image){ + for(int pixel: row) + cout << pixel << "\t"; + cout << endl; + } +} + +int main() { + + vector> image = {{1, 1, 1}, {1, 1, 0}, {1, 0, 1}}; + printImage(Solution().floodFill(image, 1, 1, 2)); + + return 0; +} \ No newline at end of file diff --git a/0734-Sentence-Similarity/cpp-0734/CMakeLists.txt b/0501-1000/0734-Sentence-Similarity/cpp-0734/CMakeLists.txt similarity index 100% rename from 0734-Sentence-Similarity/cpp-0734/CMakeLists.txt rename to 0501-1000/0734-Sentence-Similarity/cpp-0734/CMakeLists.txt diff --git a/0501-1000/0734-Sentence-Similarity/cpp-0734/main.cpp b/0501-1000/0734-Sentence-Similarity/cpp-0734/main.cpp new file mode 100644 index 00000000..832225d2 --- /dev/null +++ b/0501-1000/0734-Sentence-Similarity/cpp-0734/main.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/sentence-similarity/solution/ +/// Author : liuyubobobo +/// Time : 2017-11-25 + +#include +#include +#include + +using namespace std; + +/// Using Set +/// Saving Pairs +/// Time Complexity: O(len(pairs) + len(s)) +/// Space Complexity: O(len(pairs)) +class Solution { +public: + bool areSentencesSimilar(vector& words1, vector& words2, vector> pairs) { + + if(words1.size() != words2.size()) + return false; + + if(words1.size() == 0) + return true; + + set> similarity; + for(const vector& p: pairs) { + similarity.insert(make_pair(p[0], p[1])); + similarity.insert(make_pair(p[1], p[0])); + } + + for(int i = 0 ; i < words1.size() ; i ++) + if(words1[i] != words2[i] && similarity.find(make_pair(words1[i], words2[i])) == similarity.end()) + return false; + + return true; + } +}; + + +void printBool(bool res){ + cout << (res ? "True" : "False") << endl; +} + +int main() { + + vector words1 = {"great", "acting", "skills"}; + vector words2 = {"fine", "drama", "talent"}; + + vector> pairs; + pairs.push_back(make_pair("great", "fine")); + pairs.push_back(make_pair("acting", "drama")); + pairs.push_back(make_pair("skills", "talent")); + + printBool(Solution().areSentencesSimilar(words1, words2, pairs)); + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0734-Sentence-Similarity/cpp-0734/main2.cpp b/0501-1000/0734-Sentence-Similarity/cpp-0734/main2.cpp new file mode 100644 index 00000000..7e2bd6c3 --- /dev/null +++ b/0501-1000/0734-Sentence-Similarity/cpp-0734/main2.cpp @@ -0,0 +1,59 @@ +/// Source : https://leetcode.com/problems/sentence-similarity/solution/ +/// Author : liuyubobobo +/// Time : 2017-11-25 + +#include +#include +#include + +using namespace std; + +/// Using Set +/// Saving Pairs String +/// Time Complexity: O(len(pairs) + len(s)) +/// Space Complexity: O(len(pairs)) +class Solution { +public: + bool areSentencesSimilar(vector& words1, vector& words2, vector> pairs) { + + if(words1.size() != words2.size()) + return false; + + if(words1.size() == 0) + return true; + + set similarity; + for(const vector& p: pairs) { + string hashcode1 = p[0] + "#" + p[1]; + string hashcode2 = p[1] + "#" + p[0]; + similarity.insert(hashcode1); + similarity.insert(hashcode2); + } + + for(int i = 0 ; i < words1.size() ; i ++) + if(words1[i] != words2[i] && similarity.find(words1[i] + "#" + words2[i]) == similarity.end()) + return false; + + return true; + } +}; + + +void printBool(bool res){ + cout << (res ? "True" : "False") << endl; +} + +int main() { + + vector words1 = {"great", "acting", "skills"}; + vector words2 = {"fine", "drama", "talent"}; + + vector> pairs; + pairs.push_back(make_pair("great", "fine")); + pairs.push_back(make_pair("acting", "drama")); + pairs.push_back(make_pair("skills", "talent")); + + printBool(Solution().areSentencesSimilar(words1, words2, pairs)); + + return 0; +} \ No newline at end of file diff --git a/0735-Asteroid-Collision/cpp-0735/CMakeLists.txt b/0501-1000/0735-Asteroid-Collision/cpp-0735/CMakeLists.txt similarity index 100% rename from 0735-Asteroid-Collision/cpp-0735/CMakeLists.txt rename to 0501-1000/0735-Asteroid-Collision/cpp-0735/CMakeLists.txt diff --git a/0735-Asteroid-Collision/cpp-0735/main.cpp b/0501-1000/0735-Asteroid-Collision/cpp-0735/main.cpp similarity index 100% rename from 0735-Asteroid-Collision/cpp-0735/main.cpp rename to 0501-1000/0735-Asteroid-Collision/cpp-0735/main.cpp diff --git a/0793-Preimage-Size-of-Factorial-Zeroes-Function/cpp-0793/CMakeLists.txt b/0501-1000/0736-Parse-Lisp-Expression/cpp-0736/CMakeLists.txt similarity index 100% rename from 0793-Preimage-Size-of-Factorial-Zeroes-Function/cpp-0793/CMakeLists.txt rename to 0501-1000/0736-Parse-Lisp-Expression/cpp-0736/CMakeLists.txt diff --git a/0736-Parse-Lisp-Expression/cpp-0736/main.cpp b/0501-1000/0736-Parse-Lisp-Expression/cpp-0736/main.cpp similarity index 100% rename from 0736-Parse-Lisp-Expression/cpp-0736/main.cpp rename to 0501-1000/0736-Parse-Lisp-Expression/cpp-0736/main.cpp diff --git a/0737-Sentence-Similarity-II/cpp-0737/CMakeLists.txt b/0501-1000/0737-Sentence-Similarity-II/cpp-0737/CMakeLists.txt similarity index 100% rename from 0737-Sentence-Similarity-II/cpp-0737/CMakeLists.txt rename to 0501-1000/0737-Sentence-Similarity-II/cpp-0737/CMakeLists.txt diff --git a/0737-Sentence-Similarity-II/cpp-0737/main.cpp b/0501-1000/0737-Sentence-Similarity-II/cpp-0737/main.cpp similarity index 100% rename from 0737-Sentence-Similarity-II/cpp-0737/main.cpp rename to 0501-1000/0737-Sentence-Similarity-II/cpp-0737/main.cpp diff --git a/0737-Sentence-Similarity-II/cpp-0737/main2.cpp b/0501-1000/0737-Sentence-Similarity-II/cpp-0737/main2.cpp similarity index 100% rename from 0737-Sentence-Similarity-II/cpp-0737/main2.cpp rename to 0501-1000/0737-Sentence-Similarity-II/cpp-0737/main2.cpp diff --git a/0766-Toeplitz-Matrix/cpp-0766/CMakeLists.txt b/0501-1000/0739-Daily-Temperatures/cpp-0739/CMakeLists.txt similarity index 100% rename from 0766-Toeplitz-Matrix/cpp-0766/CMakeLists.txt rename to 0501-1000/0739-Daily-Temperatures/cpp-0739/CMakeLists.txt diff --git a/0501-1000/0739-Daily-Temperatures/cpp-0739/main.cpp b/0501-1000/0739-Daily-Temperatures/cpp-0739/main.cpp new file mode 100644 index 00000000..0737913a --- /dev/null +++ b/0501-1000/0739-Daily-Temperatures/cpp-0739/main.cpp @@ -0,0 +1,67 @@ +/// Source : https://leetcode.com/problems/daily-temperatures/description/ +/// Author : liuyubobobo +/// Time : 2018-08-28 + +#include +#include + +using namespace std; + + +/// Binary Search the higher temperature +/// Time Complexity: O(n*t*logn) where n is the number of data and t is the max temperature +/// Space Complexity: O(n) +class Solution { +public: + vector dailyTemperatures(vector& temperatures) { + + vector> records; + for(int i = 0 ; i <= 100 ; i ++){ + vector empty_vec; + records.push_back(empty_vec); + } + + for(int i = 0 ; i < temperatures.size() ; i ++) + records[temperatures[i]].push_back(i); + + vector res; + for(int i = 0 ; i < temperatures.size() ; i ++){ + int future = getWarmerDay(temperatures[i], i, records); + if(future == -1) + res.push_back(0); + else + res.push_back(future - i); + } + + return res; + } + +private: + int getWarmerDay(int t, int curDay, const vector>& records){ + + int res = INT_MAX; + for(int i = t + 1 ; i <= 100 ; i ++){ + vector::const_iterator iter = upper_bound(records[i].begin(), records[i].end(), curDay); + if(iter != records[i].end()) + res = min(res, *iter); + } + + return res == INT_MAX ? -1 : res; + } +}; + + +void printVec(const vector& vec){ + for(int e: vec) + cout << e << " "; + cout << endl; +} + +int main() { + + vector vec = {73, 74, 75, 71, 69, 72, 76, 73}; + printVec(Solution().dailyTemperatures(vec)); + // 1 1 4 2 1 1 0 0 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0739-Daily-Temperatures/cpp-0739/main2.cpp b/0501-1000/0739-Daily-Temperatures/cpp-0739/main2.cpp new file mode 100644 index 00000000..90d9f248 --- /dev/null +++ b/0501-1000/0739-Daily-Temperatures/cpp-0739/main2.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/daily-temperatures/description/ +/// Author : liuyubobobo +/// Time : 2018-08-28 + +#include +#include + +using namespace std; + + +/// Reverse Process +/// Time Complexity: O(n*t) where n is the number of data and t is the max temperature +/// Space Complexity: O(t) +class Solution { +public: + vector dailyTemperatures(vector& temperatures) { + + vector next(101, -1); + vector res(temperatures.size(), -1); + for(int i = temperatures.size() - 1; i >= 0 ; i --){ + int ret = INT_MAX; + for(int j = temperatures[i] + 1; j <= 100; j ++) + if(next[j] != -1 && next[j] < ret) + ret = next[j]; + res[i] = ret == INT_MAX ? 0 : ret - i; + next[temperatures[i]] = i; + } + + return res; + } +}; + + +void printVec(const vector& vec){ + for(int e: vec) + cout << e << " "; + cout << endl; +} + +int main() { + + vector vec = {73, 74, 75, 71, 69, 72, 76, 73}; + printVec(Solution().dailyTemperatures(vec)); + // 1 1 4 2 1 1 0 0 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0739-Daily-Temperatures/cpp-0739/main3.cpp b/0501-1000/0739-Daily-Temperatures/cpp-0739/main3.cpp new file mode 100644 index 00000000..f408a696 --- /dev/null +++ b/0501-1000/0739-Daily-Temperatures/cpp-0739/main3.cpp @@ -0,0 +1,48 @@ +/// Source : https://leetcode.com/problems/daily-temperatures/description/ +/// Author : liuyubobobo +/// Time : 2018-08-28 + +#include +#include +#include + +using namespace std; + + +/// Using Stack +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector dailyTemperatures(vector& temperatures) { + + vector res(temperatures.size(), 0); + stack stack; + for(int i = temperatures.size() - 1; i >= 0 ; i --){ + while(!stack.empty() && temperatures[stack.top()] <= temperatures[i]) + stack.pop(); + + if(!stack.empty()) + res[i] = stack.top() - i; + stack.push(i); + } + + return res; + } +}; + + +void printVec(const vector& vec){ + for(int e: vec) + cout << e << " "; + cout << endl; +} + +int main() { + + vector vec = {73, 74, 75, 71, 69, 72, 76, 73}; + printVec(Solution().dailyTemperatures(vec)); + // 1 1 4 2 1 1 0 0 + + return 0; +} \ No newline at end of file diff --git a/0740-Delete-and-Earn/cpp-0740/CMakeLists.txt b/0501-1000/0740-Delete-and-Earn/cpp-0740/CMakeLists.txt similarity index 100% rename from 0740-Delete-and-Earn/cpp-0740/CMakeLists.txt rename to 0501-1000/0740-Delete-and-Earn/cpp-0740/CMakeLists.txt diff --git a/0740-Delete-and-Earn/cpp-0740/main.cpp b/0501-1000/0740-Delete-and-Earn/cpp-0740/main.cpp similarity index 100% rename from 0740-Delete-and-Earn/cpp-0740/main.cpp rename to 0501-1000/0740-Delete-and-Earn/cpp-0740/main.cpp diff --git a/0740-Delete-and-Earn/cpp-0740/main2.cpp b/0501-1000/0740-Delete-and-Earn/cpp-0740/main2.cpp similarity index 100% rename from 0740-Delete-and-Earn/cpp-0740/main2.cpp rename to 0501-1000/0740-Delete-and-Earn/cpp-0740/main2.cpp diff --git a/0741-Cherry-Pickup/cpp-0741/CMakeLists.txt b/0501-1000/0741-Cherry-Pickup/cpp-0741/CMakeLists.txt similarity index 100% rename from 0741-Cherry-Pickup/cpp-0741/CMakeLists.txt rename to 0501-1000/0741-Cherry-Pickup/cpp-0741/CMakeLists.txt diff --git a/0741-Cherry-Pickup/cpp-0741/main.cpp b/0501-1000/0741-Cherry-Pickup/cpp-0741/main.cpp similarity index 100% rename from 0741-Cherry-Pickup/cpp-0741/main.cpp rename to 0501-1000/0741-Cherry-Pickup/cpp-0741/main.cpp diff --git a/0741-Cherry-Pickup/cpp-0741/main2.cpp b/0501-1000/0741-Cherry-Pickup/cpp-0741/main2.cpp similarity index 100% rename from 0741-Cherry-Pickup/cpp-0741/main2.cpp rename to 0501-1000/0741-Cherry-Pickup/cpp-0741/main2.cpp diff --git a/0501-1000/0745-Prefix-and-Suffix-Search/cpp-0745/CMakeLists.txt b/0501-1000/0745-Prefix-and-Suffix-Search/cpp-0745/CMakeLists.txt new file mode 100644 index 00000000..c1d818ce --- /dev/null +++ b/0501-1000/0745-Prefix-and-Suffix-Search/cpp-0745/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_0745) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0745 main2.cpp) diff --git a/0501-1000/0745-Prefix-and-Suffix-Search/cpp-0745/main.cpp b/0501-1000/0745-Prefix-and-Suffix-Search/cpp-0745/main.cpp new file mode 100644 index 00000000..6ed918e8 --- /dev/null +++ b/0501-1000/0745-Prefix-and-Suffix-Search/cpp-0745/main.cpp @@ -0,0 +1,86 @@ +/// Source : https://leetcode.com/problems/prefix-and-suffix-search/ +/// Author : liuyubobobo +/// Time : 2022-07-14 + +#include +#include +#include +#include + +using namespace std; + + +/// Suffix + Prefix +/// Time Complexity: init: O(sum_of_characters) +/// query: O(|prefix| + |suffix|) +/// Space Complexity: O(sum_of_characters) +class Trie { + +private: + struct Node{ + map next; + int index = -1; + }; + Node* root; + +public: + Trie(){ + root = new Node(); + } + + /** Inserts a word into the trie. */ + void insert(const string& word, int index){ + + Node* cur = root; + bool flag = false; + for(char c: word){ + if(cur->next.find(c) == cur->next.end()){ + cur->next[c] = new Node(); + } + cur = cur->next[c]; + + if(c == '#') flag = true; + if(flag) cur->index = index; + } + } + + int get(const string& s) { + + Node* cur = root; + for(char c: s){ + if(cur->next.find(c) == cur->next.end()) + return -1; + + cur = cur->next[c]; + } + return cur->index; + } +}; + +class WordFilter { + +private: + Trie trie; + +public: + WordFilter(vector words) { + for(int i = 0 ; i < words.size() ; i ++){ + string s = words[i]; + for(int j = s.size() - 1; j >= 0; j --){ + string suf = s.substr(j); + trie.insert(suf + "#" + s, i); + } + } + + } + + int f(string prefix, string suffix) { + return trie.get(suffix + "#" + prefix); + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0745-Prefix-and-Suffix-Search/cpp-0745/main2.cpp b/0501-1000/0745-Prefix-and-Suffix-Search/cpp-0745/main2.cpp new file mode 100644 index 00000000..5c0089ad --- /dev/null +++ b/0501-1000/0745-Prefix-and-Suffix-Search/cpp-0745/main2.cpp @@ -0,0 +1,64 @@ +/// Source : https://leetcode.com/problems/prefix-and-suffix-search/ +/// Author : liuyubobobo +/// Time : 2022-07-14 + +#include +#include +#include +#include + +using namespace std; + + +/// Using Hash + Map +/// Time Complexity: init: O(|words| * len^2) +/// query: O(|prefix| + |suffix|) +/// Space Complexity: O(|words| * len^2) +class WordFilter { + +private: + map, int> table; + +public: + WordFilter(vector words) { + + for(int i = 0 ; i < words.size() ; i ++) + insert(words[i], i); + + } + + int f(string prefix, string suffix) { + + long long pre_hash = 0; + for(int i = 0; i < prefix.size(); i ++) + pre_hash = pre_hash * 27 + (prefix[i] - 'a' + 1); + + long long suf_hash = 0; + for(int i = suffix.size() - 1; i >= 0; i --) + suf_hash = suf_hash * 27 + (suffix[i] - 'a' + 1); + + auto iter = table.find({pre_hash, suf_hash}); + return iter == table.end() ? -1 : iter->second; + } + +private: + void insert(const string& s, int index){ + + long long pre_hash = 0; + for(int i = 0; i < s.size(); i ++){ + pre_hash = pre_hash * 27 + (s[i] - 'a' + 1); + + long long suf_hash = 0; + for(int i = s.size() - 1; i >= 0; i --){ + suf_hash = suf_hash * 27 + (s[i] - 'a' + 1); + table[{pre_hash, suf_hash}] = index; + } + } + } +}; + + +int main() { + + return 0; +} diff --git a/0794-Valid-Tic-Tac-Toe-State/cpp-0794/CMakeLists.txt b/0501-1000/0746-Min-Cost-Climbing-Stairs/cpp-0746/CMakeLists.txt similarity index 100% rename from 0794-Valid-Tic-Tac-Toe-State/cpp-0794/CMakeLists.txt rename to 0501-1000/0746-Min-Cost-Climbing-Stairs/cpp-0746/CMakeLists.txt diff --git a/0501-1000/0746-Min-Cost-Climbing-Stairs/cpp-0746/main.cpp b/0501-1000/0746-Min-Cost-Climbing-Stairs/cpp-0746/main.cpp new file mode 100644 index 00000000..e4079ec1 --- /dev/null +++ b/0501-1000/0746-Min-Cost-Climbing-Stairs/cpp-0746/main.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/min-cost-climbing-stairs/ +/// Author : liuyubobobo +/// Time : 2017-12-16 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int minCostClimbingStairs(vector& cost) { + + vector dp(cost.size() + 1, 0); + for(int i = 2 ; i <= cost.size() ; i ++) + dp[i] = min(dp[i-1] + cost[i-1], dp[i-2] + cost[i - 2]); + return dp.back(); + } +}; + + +int main() { + + vector vec1 = {10, 15, 20}; + cout << Solution().minCostClimbingStairs(vec1) << endl; + + vector vec2 = {1, 100, 1, 1, 1, 100, 1, 1, 100, 1}; + cout << Solution().minCostClimbingStairs(vec2) << endl; + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0746-Min-Cost-Climbing-Stairs/cpp-0746/main2.cpp b/0501-1000/0746-Min-Cost-Climbing-Stairs/cpp-0746/main2.cpp new file mode 100644 index 00000000..eb002215 --- /dev/null +++ b/0501-1000/0746-Min-Cost-Climbing-Stairs/cpp-0746/main2.cpp @@ -0,0 +1,38 @@ +/// Source : https://leetcode.com/problems/min-cost-climbing-stairs/ +/// Author : liuyubobobo +/// Time : 2017-12-16 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int minCostClimbingStairs(vector& cost) { + + cost.push_back(0); + vector dp(cost.size(), 0); + dp[0] = cost[0]; + dp[1] = cost[1]; + for(int i = 2 ; i < cost.size() ; i ++) + dp[i] = min(dp[i-1], dp[i-2]) + cost[i]; + return dp.back(); + } +}; + + +int main() { + + vector vec1 = {10, 15, 20}; + cout << Solution().minCostClimbingStairs(vec1) << endl; + + vector vec2 = {1, 100, 1, 1, 1, 100, 1, 1, 100, 1}; + cout << Solution().minCostClimbingStairs(vec2) << endl; + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0746-Min-Cost-Climbing-Stairs/cpp-0746/main3.cpp b/0501-1000/0746-Min-Cost-Climbing-Stairs/cpp-0746/main3.cpp new file mode 100644 index 00000000..6c3c8747 --- /dev/null +++ b/0501-1000/0746-Min-Cost-Climbing-Stairs/cpp-0746/main3.cpp @@ -0,0 +1,42 @@ +/// Source : https://leetcode.com/problems/min-cost-climbing-stairs/ +/// Author : liuyubobobo +/// Time : 2018-10-29 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Space Complexity Optimized +/// +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int minCostClimbingStairs(vector& cost) { + + cost.push_back(0); + int a = cost[0]; + int b = cost[1]; + for(int i = 2 ; i < cost.size() ; i ++){ + int c = min(a, b) + cost[i]; + a = b; + b = c; + } + return b; + } +}; + + +int main() { + + vector vec1 = {10, 15, 20}; + cout << Solution().minCostClimbingStairs(vec1) << endl; + + vector vec2 = {1, 100, 1, 1, 1, 100, 1, 1, 100, 1}; + cout << Solution().minCostClimbingStairs(vec2) << endl; + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0746-Min-Cost-Climbing-Stairs/cpp-0746/main4.cpp b/0501-1000/0746-Min-Cost-Climbing-Stairs/cpp-0746/main4.cpp new file mode 100644 index 00000000..e6411694 --- /dev/null +++ b/0501-1000/0746-Min-Cost-Climbing-Stairs/cpp-0746/main4.cpp @@ -0,0 +1,41 @@ +/// Source : https://leetcode.com/problems/min-cost-climbing-stairs/ +/// Author : liuyubobobo +/// Time : 2018-10-29 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Little optimizing without changing cost array :-) +/// +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int minCostClimbingStairs(vector& cost) { + + int a = cost[0]; + int b = cost[1]; + for(int i = 2 ; i < cost.size() ; i ++){ + int c = min(a, b) + cost[i]; + a = b; + b = c; + } + return min(a, b); + } +}; + + +int main() { + + vector vec1 = {10, 15, 20}; + cout << Solution().minCostClimbingStairs(vec1) << endl; + + vector vec2 = {1, 100, 1, 1, 1, 100, 1, 1, 100, 1}; + cout << Solution().minCostClimbingStairs(vec2) << endl; + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0746-Min-Cost-Climbing-Stairs/cpp-0746/main5.cpp b/0501-1000/0746-Min-Cost-Climbing-Stairs/cpp-0746/main5.cpp new file mode 100644 index 00000000..b027b9ac --- /dev/null +++ b/0501-1000/0746-Min-Cost-Climbing-Stairs/cpp-0746/main5.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/min-cost-climbing-stairs/ +/// Author : liuyubobobo +/// Time : 2018-10-29 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Reverse order to dp :-) +/// +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int minCostClimbingStairs(vector& cost) { + + int a = 0, b = 0; + for(int i = cost.size() - 1 ; i >= 0 ; i --){ + int c = min(a, b) + cost[i]; + a = b; + b = c; + } + return min(a, b); + } +}; + + +int main() { + + vector vec1 = {10, 15, 20}; + cout << Solution().minCostClimbingStairs(vec1) << endl; + + vector vec2 = {1, 100, 1, 1, 1, 100, 1, 1, 100, 1}; + cout << Solution().minCostClimbingStairs(vec2) << endl; + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0747-Largest-Number-At-Least-Twice-of-Others/cpp-0747/CMakeLists.txt b/0501-1000/0747-Largest-Number-At-Least-Twice-of-Others/cpp-0747/CMakeLists.txt new file mode 100644 index 00000000..76d7bbd5 --- /dev/null +++ b/0501-1000/0747-Largest-Number-At-Least-Twice-of-Others/cpp-0747/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0747) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0747 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0747-Largest-Number-At-Least-Twice-of-Others/cpp-0747/main.cpp b/0501-1000/0747-Largest-Number-At-Least-Twice-of-Others/cpp-0747/main.cpp new file mode 100644 index 00000000..37e8c9c5 --- /dev/null +++ b/0501-1000/0747-Largest-Number-At-Least-Twice-of-Others/cpp-0747/main.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/largest-number-at-least-twice-of-others/description/ +/// Author : liuyubobobo +/// Time : 2018-06-03 + +#include +#include + +using namespace std; + +/// Linear Scan +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int dominantIndex(vector& nums) { + + int maxNum = *max_element(nums.begin(), nums.end()); + int res = -1; + for(int i = 0 ; i < nums.size() ; i ++) + if(nums[i] != maxNum){ + if(maxNum < 2 * nums[i]) + return -1; + } + else + res = i; + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0749-Contain-Virus/cpp-0749/CMakeLists.txt b/0501-1000/0749-Contain-Virus/cpp-0749/CMakeLists.txt new file mode 100644 index 00000000..a3245e37 --- /dev/null +++ b/0501-1000/0749-Contain-Virus/cpp-0749/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_0749) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0749 main.cpp) diff --git a/0501-1000/0749-Contain-Virus/cpp-0749/main.cpp b/0501-1000/0749-Contain-Virus/cpp-0749/main.cpp new file mode 100644 index 00000000..b5e2c228 --- /dev/null +++ b/0501-1000/0749-Contain-Virus/cpp-0749/main.cpp @@ -0,0 +1,141 @@ +/// Source : https://leetcode.com/problems/contain-virus/ +/// Author : liuyubobobo +/// Time : 2022-07-19 + +#include +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O((R * C) ^ 2) +/// Space Compelxity: O(R * C) +class Solution { + +private: + const int dirs[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; + int R, C; + +public: + int containVirus(vector>& isInfected) { + + R = isInfected.size(), C = isInfected[0].size(); + + // 0 - not infected, 1 - virus + int res = 0; + while(true){ + vector> visited(R, vector(C, -1)); + int cc_num = 0; + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++) + if(isInfected[i][j] == 1 && visited[i][j] == -1){ + dfs(isInfected, i, j, cc_num ++, visited); + } + + if(cc_num == 0) break; + + vector walls(cc_num, 0); + vector> threaten(cc_num); + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++){ + int cc = visited[i][j]; + if(cc == -1) continue; + + for(int d = 0; d < 4; d ++){ + int nx = i + dirs[d][0], ny = j + dirs[d][1]; + if(in_area(nx, ny) && isInfected[nx][ny] == 0) + threaten[cc].insert(nx * C + ny), walls[cc] ++; + } + } + + int max_threatens = 0, max_cc = -1; + for(int cc = 0; cc < cc_num; cc ++) + if(threaten[cc].size() > max_threatens) + max_threatens = threaten[cc].size(), max_cc = cc; + + if(max_threatens == 0) break; + + res += walls[max_cc]; + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++) + if(visited[i][j] == max_cc) isInfected[i][j] = 2; + + vector> next(R, vector(C, 0)); + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++){ + if(isInfected[i][j] != 1) continue; + for(int d = 0; d < 4; d ++){ + int nx = i + dirs[d][0], ny = j + dirs[d][1]; + if(in_area(nx, ny) && !isInfected[nx][ny]) next[nx][ny] = 1; + } + } + + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++) + if(isInfected[i][j] == 0 && next[i][j]) + isInfected[i][j] = 1; + } + return res; + } + +private: + void dfs(const vector>& isInfected, int x, int y, int cc, + vector>& visited){ + visited[x][y] = cc; + for(int d = 0; d < 4; d ++){ + int nx = x + dirs[d][0], ny = y + dirs[d][1]; + if(in_area(nx, ny) && isInfected[nx][ny] == 1 && visited[nx][ny] == -1) + dfs(isInfected, nx, ny, cc, visited); + } + } + + bool in_area(int x, int y){ + return 0 <= x && x < R && 0 <= y && y < C; + } +}; + + +int main() { + + vector> isInfected1 = { + {0,1,0,0,0,0,0,1}, + {0,1,0,0,0,0,0,1}, + {0,0,0,0,0,0,0,1}, + {0,0,0,0,0,0,0,0} + }; + cout << Solution().containVirus(isInfected1) << '\n'; + // 10 + + vector> isInfected2 = { + {1,1,1,0,0,0,0,0,0}, + {1,0,1,0,1,1,1,1,1}, + {1,1,1,0,0,0,0,0,0} + }; + cout << Solution().containVirus(isInfected2) << '\n'; + // 13 + + vector> isInfected3 = { + {1} + }; + cout << Solution().containVirus(isInfected3) << '\n'; + // 0 + + vector> isInfected4 = { + {0,1,0,1,1,1,1,1,1,0}, + {0,0,0,1,0,0,0,0,0,0}, + {0,0,1,1,1,0,0,0,1,0}, + {0,0,0,1,1,0,0,1,1,0}, + {0,1,0,0,1,0,1,1,0,1}, + {0,0,0,1,0,1,0,1,1,1}, + {0,1,0,0,1,0,0,1,1,0}, + {0,1,0,1,0,0,0,1,1,0}, + {0,1,1,0,0,1,1,0,0,1}, + {1,0,1,1,0,1,0,1,0,1} + }; + cout << Solution().containVirus(isInfected4) << '\n'; + // 38 + + return 0; +} diff --git a/0791-Custom-Sort-String/cpp-0791/CMakeLists.txt b/0501-1000/0752-Open-the-Lock/cpp-0752/CMakeLists.txt similarity index 100% rename from 0791-Custom-Sort-String/cpp-0791/CMakeLists.txt rename to 0501-1000/0752-Open-the-Lock/cpp-0752/CMakeLists.txt diff --git a/0501-1000/0752-Open-the-Lock/cpp-0752/main.cpp b/0501-1000/0752-Open-the-Lock/cpp-0752/main.cpp new file mode 100644 index 00000000..42e6f36d --- /dev/null +++ b/0501-1000/0752-Open-the-Lock/cpp-0752/main.cpp @@ -0,0 +1,94 @@ +/// Source : https://leetcode.com/problems/open-the-lock/description/ +/// Author : liuyubobobo +/// Time : 2017-12-23 + +#include +#include +#include +#include +#include + +using namespace std; + +/// BFS +/// Time Complexity: O(charset^N) +/// Space Complexity: O(charset^N) +class Solution { +public: + int openLock(vector& deadends, string target) { + + set dead; + for(string s: deadends) + dead.insert(s); + + if(dead.find(target) != dead.end() || dead.find("0000") != dead.end()) + return -1; + + set visited; + queue> q; + q.push(make_pair("0000", 0)); + visited.insert("0000"); + while(!q.empty()){ + string cur = q.front().first; + int step = q.front().second; + q.pop(); + + vector next = getNext(cur, dead); + for(string next_s: next) + if(visited.find(next_s) == visited.end()){ + if(next_s == target) + return step + 1; + + visited.insert(next_s); + q.push(make_pair(next_s, step + 1)); + } + } + return -1; + } + +private: + vector getNext(const string& s, const set& dead){ + vector res; + assert(s.size() == 4); + for(int i = 0 ; i < 4 ; i ++){ + int num = s[i] - '0'; + + int d = num + 1; + if(d > 9) d = 0; + string t = s; + t[i] = ('0' + d); + if(dead.find(t) == dead.end()) + res.push_back(t); + + d = num - 1; + if(d < 0) d = 9; + t = s; + t[i] = ('0' + d); + if(dead.find(t) == dead.end()) + res.push_back(t); + } + return res; + } +}; + + +int main() { + + vector dead1 = {"0201","0101","0102","1212","2002"}; + string target1 = "0202"; + cout << Solution().openLock(dead1, target1) << endl; + + vector dead2 = {"8888"}; + string target2 = "0009"; + cout << Solution().openLock(dead2, target2) << endl; + + vector dead3 = {"8887","8889","8878","8898","8788","8988","7888","9888"}; + string target3 = "8888"; + cout << Solution().openLock(dead3, target3) << endl; + + vector dead4 = {"1002","1220","0122","0112","0121"}; + string target4 = "1200"; + cout << Solution().openLock(dead4, target4) << endl; + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0753-Cracking-the-Safe/cpp-0753/CMakeLists.txt b/0501-1000/0753-Cracking-the-Safe/cpp-0753/CMakeLists.txt new file mode 100644 index 00000000..273afbca --- /dev/null +++ b/0501-1000/0753-Cracking-the-Safe/cpp-0753/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_0753) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0753 main.cpp) \ No newline at end of file diff --git a/0501-1000/0753-Cracking-the-Safe/cpp-0753/main.cpp b/0501-1000/0753-Cracking-the-Safe/cpp-0753/main.cpp new file mode 100644 index 00000000..7212ebc3 --- /dev/null +++ b/0501-1000/0753-Cracking-the-Safe/cpp-0753/main.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/cracking-the-safe/ +/// Author : liuyubobobo +/// Time : 2021-07-16 + +#include +#include +#include + +using namespace std; + + +/// De Bruijn sequence +/// Time Complexity: O(k^n) +/// Space Complexity: O(n) +class Solution { +public: + string crackSafe(int n, int k) { + + string res = ""; + if(n == 1){ + for(int i = 0; i < k; i ++) + res += to_string(i); + return res; + } + + vector power = {1}; + for(int i = 1; i <= n; i ++) power.push_back(power[i - 1] * k); + + vector g(power[n - 1], k - 1); + stack> stack; + stack.push({0, 0}); + while(!stack.empty()){ + if(g[stack.top().first] != -1){ + int u = stack.top().first; + int next = u; + next -= next / power[n - 2] * power[n - 2]; + next = next * k + g[u]; + stack.push({next, g[u]}); + g[u] --; + } + else{ + res += ('0' + stack.top().second); + stack.pop(); + } + } + + while((int)res.size() < power[n] + n - 1) res += "0"; + return res; + } +}; + +int main() { + + cout << Solution().crackSafe(2, 3) << endl; + + return 0; +} diff --git a/0501-1000/0754-Reach-a-Number/cpp-0754/CMakeLists.txt b/0501-1000/0754-Reach-a-Number/cpp-0754/CMakeLists.txt new file mode 100644 index 00000000..f4721a3b --- /dev/null +++ b/0501-1000/0754-Reach-a-Number/cpp-0754/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(cpp_0754) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0754 main.cpp) \ No newline at end of file diff --git a/0501-1000/0754-Reach-a-Number/cpp-0754/main.cpp b/0501-1000/0754-Reach-a-Number/cpp-0754/main.cpp new file mode 100644 index 00000000..95de32d3 --- /dev/null +++ b/0501-1000/0754-Reach-a-Number/cpp-0754/main.cpp @@ -0,0 +1,42 @@ +/// Source : https://leetcode.com/problems/reach-a-number/ +/// Author : liuyubobobo +/// Time : 2020-04-23 + +#include + +using namespace std; + + +/// Mathematics +/// See here for details: https://leetcode.com/problems/reach-a-number/solution/ +/// Time Complexity: O(sqrt(n)) +/// Space Complexity: O(1) +class Solution { +public: + int reachNumber(int target) { + + if(target < 0) target = -target; + + int sum = 0, k = 1; + while(sum < target) sum += k ++; + + if(sum == target || (sum - target) % 2 == 0) return k - 1; + for(;;){ + sum += k ++; + if((sum - target) % 2 == 0) return k - 1; + } + return -1; + } +}; + + +int main() { + + cout << Solution().reachNumber(4) << endl; + // 3 + + cout << Solution().reachNumber(5) << endl; + // 5 + + return 0; +} diff --git a/0501-1000/0757-Set-Intersection-Size-At-Least-Two/cpp-0757/CMakeLists.txt b/0501-1000/0757-Set-Intersection-Size-At-Least-Two/cpp-0757/CMakeLists.txt new file mode 100644 index 00000000..0bdb2d89 --- /dev/null +++ b/0501-1000/0757-Set-Intersection-Size-At-Least-Two/cpp-0757/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_0757) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0757 main.cpp) diff --git a/0501-1000/0757-Set-Intersection-Size-At-Least-Two/cpp-0757/main.cpp b/0501-1000/0757-Set-Intersection-Size-At-Least-Two/cpp-0757/main.cpp new file mode 100644 index 00000000..7ea8eeb6 --- /dev/null +++ b/0501-1000/0757-Set-Intersection-Size-At-Least-Two/cpp-0757/main.cpp @@ -0,0 +1,49 @@ +#include +#include +#include +#include + +using namespace std; + + +class Solution { +public: + int intersectionSizeTwo(vector>& intervals) { + + sort(intervals.begin(), intervals.end(), + [](const vector& interval1, const vector& interval2){ + + if(interval1[1] != interval2[1]) return interval1[1] < interval2[1]; + return interval1[0] >= interval2[0]; + }); + + int res = 2, largest1 = intervals[0][1], largest2 = intervals[0][1] - 1; + for(int i = 1; i < intervals.size(); i ++){ + int a = intervals[i][0], b = intervals[i][1]; + if(a <= largest2 && largest1 <= b){ + continue; + } + else if(largest1 >= a){ + res ++; + largest2 = largest1; + largest1 = b; + } + else{ + res += 2; + largest1 = b; + largest2 = b - 1; + } + } + return res; + } +}; + + +int main() { + + vector> intervals1 = {{1,3},{1,4},{2,5},{3,5}}; + cout << Solution().intersectionSizeTwo(intervals1) << '\n'; + // 3 + + return 0; +} diff --git a/0501-1000/0761-Special-Binary-String/cpp-0761/CMakeLists.txt b/0501-1000/0761-Special-Binary-String/cpp-0761/CMakeLists.txt new file mode 100644 index 00000000..5b57e348 --- /dev/null +++ b/0501-1000/0761-Special-Binary-String/cpp-0761/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(cpp_0761) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0761 main.cpp) \ No newline at end of file diff --git a/0501-1000/0761-Special-Binary-String/cpp-0761/main.cpp b/0501-1000/0761-Special-Binary-String/cpp-0761/main.cpp new file mode 100644 index 00000000..e18c1539 --- /dev/null +++ b/0501-1000/0761-Special-Binary-String/cpp-0761/main.cpp @@ -0,0 +1,44 @@ +/// Source : https://leetcode.com/problems/special-binary-string/ +/// Author : liuyubobobo +/// Time : 2020-04-24 + +#include +#include + +using namespace std; + + +/// Recursion +/// Time Complexity: O(n^2) +/// Space Complexity: O(n^2) +class Solution { +public: + string makeLargestSpecial(string S) { + + if(S == "") return ""; + + vector v; + int cnt = 0; + for(int start = 0, i = 0; i < S.size(); i ++){ + cnt += (S[i] == '1' ? 1 : -1); + if(!cnt){ + v.push_back("1" + makeLargestSpecial(S.substr(start + 1, i - start - 1)) + "0"); + start = i + 1; + } + } + + sort(v.begin(), v.end(), greater()); + string res = ""; + for(const string& e: v) res += e; + return res; + } +}; + + +int main() { + + cout << Solution().makeLargestSpecial("11011000") << endl; + // 11100100 + + return 0; +} diff --git a/0501-1000/0762-Prime-Number-of-Set-Bits-in-Binary-Representation/cpp-0762/CMakeLists.txt b/0501-1000/0762-Prime-Number-of-Set-Bits-in-Binary-Representation/cpp-0762/CMakeLists.txt new file mode 100644 index 00000000..01ffd5e7 --- /dev/null +++ b/0501-1000/0762-Prime-Number-of-Set-Bits-in-Binary-Representation/cpp-0762/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_0762) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0762 main.cpp) diff --git a/0501-1000/0762-Prime-Number-of-Set-Bits-in-Binary-Representation/cpp-0762/main.cpp b/0501-1000/0762-Prime-Number-of-Set-Bits-in-Binary-Representation/cpp-0762/main.cpp new file mode 100644 index 00000000..30b306ae --- /dev/null +++ b/0501-1000/0762-Prime-Number-of-Set-Bits-in-Binary-Representation/cpp-0762/main.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/prime-number-of-set-bits-in-binary-representation/ +/// Author : liuyubobobo +/// Time : 2022-04-04 + +#include +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(right - left) +/// Space Complexity: O(1) +class Solution { +public: + int countPrimeSetBits(int left, int right) { + + set primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31}; + int res = 0; + for(int e = left; e <= right; e ++){ + int b = __builtin_popcount(e); + res += primes.count(b); + } + return res; + } +}; + + +int main() { + + + return 0; +} diff --git a/0501-1000/0763-Partition-Labels/cpp-0763/CMakeLists.txt b/0501-1000/0763-Partition-Labels/cpp-0763/CMakeLists.txt new file mode 100644 index 00000000..8828aec5 --- /dev/null +++ b/0501-1000/0763-Partition-Labels/cpp-0763/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_0763) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0763 main.cpp) diff --git a/0501-1000/0763-Partition-Labels/cpp-0763/main.cpp b/0501-1000/0763-Partition-Labels/cpp-0763/main.cpp new file mode 100644 index 00000000..43b23e3d --- /dev/null +++ b/0501-1000/0763-Partition-Labels/cpp-0763/main.cpp @@ -0,0 +1,55 @@ +/// Source : https://leetcode.com/problems/partition-labels/ +/// Author : liuyubobobo +/// Time : 2022-03-20 + +#include +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + vector partitionLabels(string s) { + + vector f(26, 0); + for(char c: s) f[c - 'a'] ++; + + vector res; + vector curf(26, 0); + int l = 0; + for(int i = 0; i < s.size(); i ++){ + curf[s[i] - 'a'] ++; + if(ok(curf, f)){ + res.push_back(i - l + 1); + l = i + 1; + fill(curf.begin(), curf.end(), 0); + } + } + return res; + } + +private: + bool ok(const vector& curf, const vector& f){ + + for(int i = 0; i < 26; i ++) + if(curf[i] && curf[i] != f[i]) return false; + return true; + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << ' '; cout << '\n'; +} + +int main() { + + print_vec(Solution().partitionLabels("ababcbacadefegdehijhklij")); + // 9 7 8 + + return 0; +} diff --git a/0501-1000/0764-Largest-Plus-Sign/cpp-0764/CMakeLists.txt b/0501-1000/0764-Largest-Plus-Sign/cpp-0764/CMakeLists.txt new file mode 100644 index 00000000..fb52cbff --- /dev/null +++ b/0501-1000/0764-Largest-Plus-Sign/cpp-0764/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0764) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0764 main.cpp) diff --git a/0501-1000/0764-Largest-Plus-Sign/cpp-0764/main.cpp b/0501-1000/0764-Largest-Plus-Sign/cpp-0764/main.cpp new file mode 100644 index 00000000..5a0d1a39 --- /dev/null +++ b/0501-1000/0764-Largest-Plus-Sign/cpp-0764/main.cpp @@ -0,0 +1,61 @@ +/// Source : https://leetcode.com/problems/largest-plus-sign/ +/// Author : liuyubobobo +/// Time : 2021-09-09 + +#include +#include + +using namespace std; + + +/// Presum +/// Time Complexity: O(n^2) +/// Space Complexity: O(n^2) +class Solution { +public: + int orderOfLargestPlusSign(int n, vector>& mines) { + + vector> g(n, vector(n, 1)); + for(const vector& mine: mines) + g[mine[0]][mine[1]] = 0; + + vector> top(n, vector(n, 0)); + top[0] = g[0]; + for(int i = 1; i < n; i ++) + for(int j = 0; j < n; j ++) + if(g[i][j]) top[i][j] = top[i - 1][j] + 1; + + vector> bottom(n, vector(n, 0)); + bottom[n - 1] = g[n - 1]; + for(int i = n - 2; i >= 0; i --) + for(int j = 0; j < n; j ++) + if(g[i][j]) bottom[i][j] = bottom[i + 1][j] + 1; + + vector> left(n, vector(n, 0)); + for(int i = 0; i < n; i ++) left[i][0] = g[i][0]; + for(int j = 1; j < n; j ++) + for(int i = 0; i < n; i ++) + if(g[i][j]) left[i][j] = left[i][j - 1] + 1; + + vector> right(n, vector(n, 0)); + for(int i = 0; i < n; i ++) right[i][n - 1] = g[i][n - 1]; + for(int j = n - 2; j >= 0; j --) + for(int i = 0; i < n; i ++) + if(g[i][j]) right[i][j] = right[i][j + 1] + 1; + + int res = 0; + for(int i = 0; i < n; i ++) + for(int j = 0; j < n; j ++) + if(g[i][j]){ + int a = top[i][j], b = bottom[i][j], c = left[i][j], d = right[i][j]; + res = max(res, min(min(a, b), min(c, d))); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0765-Couples-Holding-Hands/cpp-0765/CMakeLists.txt b/0501-1000/0765-Couples-Holding-Hands/cpp-0765/CMakeLists.txt new file mode 100644 index 00000000..ef34026f --- /dev/null +++ b/0501-1000/0765-Couples-Holding-Hands/cpp-0765/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0765) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main2.cpp) +add_executable(cpp_0765 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0765-Couples-Holding-Hands/cpp-0765/main.cpp b/0501-1000/0765-Couples-Holding-Hands/cpp-0765/main.cpp new file mode 100644 index 00000000..a03b65bf --- /dev/null +++ b/0501-1000/0765-Couples-Holding-Hands/cpp-0765/main.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/couples-holding-hands/description/ +/// Author : liuyubobobo +/// Time : 2018-06-17 + +#include +#include + +using namespace std; + +/// Greedy Algorithm +/// Time Complexity: O(n^2) +/// Space Complexity: O(1) +class Solution { +public: + int minSwapsCouples(vector& row) { + + for(int i = 0 ; i < row.size() ; i ++) + row[i] = row[i] / 2; + // print_vec(row); + + int res = 0; + for(int i = 1 ; i < row.size() ; i += 2) + if(row[i] != row[i - 1]){ + for(int j = i + 1 ; j < row.size() ; j ++) + if(row[j] == row[i - 1]){ + swap(row[j], row[i]); + res ++; + } + } + return res; + } + +private: + void print_vec(const vector& vec){ + for(int e: vec) + cout << e << " "; + cout << endl; + } +}; + +int main() { + + vector row1 = {0, 2, 1, 3}; + cout << Solution().minSwapsCouples(row1) << endl; + + vector row2 = {3, 2, 0, 1}; + cout << Solution().minSwapsCouples(row2) << endl; + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0765-Couples-Holding-Hands/cpp-0765/main2.cpp b/0501-1000/0765-Couples-Holding-Hands/cpp-0765/main2.cpp new file mode 100644 index 00000000..0c3df6c9 --- /dev/null +++ b/0501-1000/0765-Couples-Holding-Hands/cpp-0765/main2.cpp @@ -0,0 +1,66 @@ +/// Source : https://leetcode.com/problems/couples-holding-hands/description/ +/// Author : liuyubobobo +/// Time : 2018-06-17 + +#include +#include +#include +#include +#include + +using namespace std; + +/// Graph Solution +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int minSwapsCouples(vector& row) { + + assert(row.size() % 2 == 0); + for(int i = 0 ; i < row.size() ; i ++) + row[i] = row[i] / 2; + // print_vec(row); + + unordered_map> node_map; + for(int i = 0 ; i < row.size() ; i ++) + node_map[row[i]].push_back(i / 2); + + vector> g(row.size() / 2); + for(const pair>& p: node_map){ + g[p.second[0]].insert(p.second[1]); + g[p.second[1]].insert(p.second[0]); + } + + int component_num = 0; + vector visited(g.size(), false); + for(int i = 0 ; i < g.size() ; i ++) + if(!visited[i]){ + component_num ++; + dfs(g, i, visited); + } + return g.size() - component_num; + } + +private: + void dfs(const vector>& g, int index, vector& visited){ + + visited[index] = true; + for(int node: g[index]) + if(!visited[node]) + dfs(g, node, visited); + return; + } +}; + + +int main() { + + vector row1 = {0, 2, 1, 3}; + cout << Solution().minSwapsCouples(row1) << endl; + + vector row2 = {3, 2, 0, 1}; + cout << Solution().minSwapsCouples(row2) << endl; + + return 0; +} \ No newline at end of file diff --git a/0796-Rotate-String/cpp-0796/CMakeLists.txt b/0501-1000/0766-Toeplitz-Matrix/cpp-0766/CMakeLists.txt similarity index 100% rename from 0796-Rotate-String/cpp-0796/CMakeLists.txt rename to 0501-1000/0766-Toeplitz-Matrix/cpp-0766/CMakeLists.txt diff --git a/0766-Toeplitz-Matrix/cpp-0766/main.cpp b/0501-1000/0766-Toeplitz-Matrix/cpp-0766/main.cpp similarity index 100% rename from 0766-Toeplitz-Matrix/cpp-0766/main.cpp rename to 0501-1000/0766-Toeplitz-Matrix/cpp-0766/main.cpp diff --git a/0766-Toeplitz-Matrix/cpp-0766/main2.cpp b/0501-1000/0766-Toeplitz-Matrix/cpp-0766/main2.cpp similarity index 100% rename from 0766-Toeplitz-Matrix/cpp-0766/main2.cpp rename to 0501-1000/0766-Toeplitz-Matrix/cpp-0766/main2.cpp diff --git a/0766-Toeplitz-Matrix/cpp-0766/main3.cpp b/0501-1000/0766-Toeplitz-Matrix/cpp-0766/main3.cpp similarity index 100% rename from 0766-Toeplitz-Matrix/cpp-0766/main3.cpp rename to 0501-1000/0766-Toeplitz-Matrix/cpp-0766/main3.cpp diff --git a/0806-Number-of-Lines-To-Write-String/cpp-0806/CMakeLists.txt b/0501-1000/0771-Jewels-and-Stones/cpp-0771/CMakeLists.txt similarity index 100% rename from 0806-Number-of-Lines-To-Write-String/cpp-0806/CMakeLists.txt rename to 0501-1000/0771-Jewels-and-Stones/cpp-0771/CMakeLists.txt diff --git a/0501-1000/0771-Jewels-and-Stones/cpp-0771/main.cpp b/0501-1000/0771-Jewels-and-Stones/cpp-0771/main.cpp new file mode 100644 index 00000000..a60c56cd --- /dev/null +++ b/0501-1000/0771-Jewels-and-Stones/cpp-0771/main.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/jewels-and-stones/description/ +/// Author : liuyubobobo +/// Time : 2018-10-06 + +#include +#include +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(len(J) * len(S)) +/// Space Complxity: O(1) +class Solution { +public: + int numJewelsInStones(string J, string S) { + + int res = 0; + for(char c: S) + if(J.find(c) != string::npos) + res ++; + return res; + } +}; + + +int main() { + + cout << Solution().numJewelsInStones("aA", "aAAbbbb") << endl; + cout << Solution().numJewelsInStones("z", "ZZ") << endl; + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0771-Jewels-and-Stones/cpp-0771/main2.cpp b/0501-1000/0771-Jewels-and-Stones/cpp-0771/main2.cpp new file mode 100644 index 00000000..85aa5950 --- /dev/null +++ b/0501-1000/0771-Jewels-and-Stones/cpp-0771/main2.cpp @@ -0,0 +1,39 @@ +/// Source : https://leetcode.com/problems/jewels-and-stones/description/ +/// Author : liuyubobobo +/// Time : 2018-01-27 + +#include +#include +#include +#include + +using namespace std; + + +/// Using Hash Set +/// Time Complexity: O(len(J) + len(S)) +/// Space Complxity: O(len(J)) +class Solution { +public: + int numJewelsInStones(string J, string S) { + + unordered_set jewels; + for(char c: J) + jewels.insert(c); + + int res = 0; + for(char c: S) + if(jewels.find(c) != jewels.end()) + res ++; + return res; + } +}; + + +int main() { + + cout << Solution().numJewelsInStones("aA", "aAAbbbb") << endl; + cout << Solution().numJewelsInStones("z", "ZZ") << endl; + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0772-Basic-Calculator-III/cpp-0772/CMakeLists.txt b/0501-1000/0772-Basic-Calculator-III/cpp-0772/CMakeLists.txt new file mode 100644 index 00000000..823d0334 --- /dev/null +++ b/0501-1000/0772-Basic-Calculator-III/cpp-0772/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0772) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0772 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0772-Basic-Calculator-III/cpp-0772/main.cpp b/0501-1000/0772-Basic-Calculator-III/cpp-0772/main.cpp new file mode 100644 index 00000000..02030a23 --- /dev/null +++ b/0501-1000/0772-Basic-Calculator-III/cpp-0772/main.cpp @@ -0,0 +1,133 @@ +/// Source : https://leetcode.com/problems/basic-calculator-iii/description/ +/// Author : liuyubobobo +/// Time : 2018-09-07 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// Two Stacks +/// Shunting-Yard Algorithms: https://en.wikipedia.org/wiki/Shunting-yard_algorithm +/// +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +private: + unordered_set opset = {'+', '-', '*', '/', '(', ')'}; + +public: + int calculate(string s) { + + if(s == "") + return 0; + + vector nums; + vector ops; + + for(int i = 0; i < s.size(); i ++) { + if(s[i] == ' ') + continue; + + if(opset.count(s[i])){ + if(s[i] == ')'){ + vector tnums = {nums.back()}; + nums.pop_back(); + vector tops; + while(ops.back() != '('){ + tnums.push_back(nums.back()); + nums.pop_back(); + tops.push_back(ops.back()); + ops.pop_back(); + } + reverse(tnums.begin(), tnums.end()); + reverse(tops.begin(), tops.end()); + nums.push_back(order_calc(tnums, tops)); + + assert(ops.back() == '('); + ops.pop_back(); + if(!ops.empty() && (ops.back() == '*' || ops.back() == '/')) + calcTwo(nums, ops); + assert(ops.empty() || ops.back() == '+' || ops.back() == '-' || ops.back() == '('); + } + else + ops.push_back(s[i]); + } + else{ + int num = s[i] - '0'; + int j; + for(j = i + 1; j < s.size() && isdigit(s[j]); j ++) + num = num * 10 + (s[j] - '0'); + i = j - 1; + + nums.push_back(num); + if(!ops.empty() && (ops.back() == '*' || ops.back() == '/')) + calcTwo(nums, ops); + } + } + + return order_calc(nums, ops); + } + +private: + void calcTwo(vector& nums, vector& ops){ + assert(nums.size() >= 2); + int second = nums.back(); + nums.pop_back(); + int first = nums.back(); + nums.pop_back(); + + char op = ops.back(); + ops.pop_back(); + nums.push_back(calc(first, second, op)); + return; + } + + int calc(int a, int b, char op){ + switch(op){ + case '+': return a + b; + case '-': return a - b; + case '*': return a * b; + case '/': return a / b; + default: assert(false); return -1; + } + } + + int order_calc(const vector& nums, const vector& ops){ + + assert(nums.size() == ops.size() + 1); + int res = nums[0]; + for(int i = 0; i < ops.size(); i ++) + res = calc(res, nums[i + 1], ops[i]); + return res; + } +}; + + +int main() { + + cout << Solution().calculate("1 + 1") << endl; + // 2 + + cout << Solution().calculate(" 6-4 / 2 ") << endl; + // 4 + + cout << Solution().calculate("2*(5+5*2)/3+(6/2+8)") << endl; + // 21 + + cout << Solution().calculate("(2+6* 3+5- (3*14/7+2)*5)+3") << endl; + // -12 + + cout << Solution().calculate("(( ( ( 1 * 10 ) -( 3 * 8) ) * 3 ) * 1 )") << endl; + // -42 + + cout << Solution().calculate("2-4-(8+2-6+(8+4-(1)+8-10))") << endl; + // -15 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0774-Minimize-Max-Distance-to-Gas-Station/cpp-0774/CMakeLists.txt b/0501-1000/0774-Minimize-Max-Distance-to-Gas-Station/cpp-0774/CMakeLists.txt new file mode 100644 index 00000000..55d41fbc --- /dev/null +++ b/0501-1000/0774-Minimize-Max-Distance-to-Gas-Station/cpp-0774/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(cpp_0774) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0774 main.cpp) \ No newline at end of file diff --git a/0501-1000/0774-Minimize-Max-Distance-to-Gas-Station/cpp-0774/main.cpp b/0501-1000/0774-Minimize-Max-Distance-to-Gas-Station/cpp-0774/main.cpp new file mode 100644 index 00000000..b057a2d8 --- /dev/null +++ b/0501-1000/0774-Minimize-Max-Distance-to-Gas-Station/cpp-0774/main.cpp @@ -0,0 +1,49 @@ +/// Source : https://leetcode.com/problems/minimize-max-distance-to-gas-station/ +/// Author : liuyubobobo +/// Time : 2020-04-24 + +#include +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(n * log(1e14)) +/// Space Complexity: O(n) +class Solution { +public: + double minmaxGasDist(vector& stations, int K) { + + vector seg; + for(int i = 1; i < stations.size(); i ++) + seg.push_back(stations[i] - stations[i - 1]); + + double l = 0.0, r = 1e8; + while(r - l >= 1e-6){ + double mid = (l + r) / 2; + if(ok(seg, K, mid)) r = mid; + else l = mid; + } + return l; + } + +private: + bool ok(const vector& seg, int K, double gap){ + + int x = 0; + for(double e: seg) + x += (ceil(e / gap) - 1); + return x <= K; + } +}; + + +int main() { + + vector stations = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; + cout << Solution().minmaxGasDist(stations, 9) << endl; + + return 0; +} diff --git a/0501-1000/0775-Global-and-Local-Inversions/cpp-0775/CMakeLists.txt b/0501-1000/0775-Global-and-Local-Inversions/cpp-0775/CMakeLists.txt new file mode 100644 index 00000000..073258ca --- /dev/null +++ b/0501-1000/0775-Global-and-Local-Inversions/cpp-0775/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_0775) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0775 main.cpp) diff --git a/0501-1000/0775-Global-and-Local-Inversions/cpp-0775/main.cpp b/0501-1000/0775-Global-and-Local-Inversions/cpp-0775/main.cpp new file mode 100644 index 00000000..3d057512 --- /dev/null +++ b/0501-1000/0775-Global-and-Local-Inversions/cpp-0775/main.cpp @@ -0,0 +1,84 @@ +/// Source : https://leetcode.com/problems/global-and-local-inversions/ +/// Author : liuyubobobo +/// Time : 2022-11-15 + +#include +#include + +using namespace std; + + +/// Merge Sort +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + bool isIdealPermutation(vector& A) { + + vector A_copy(A.begin(), A.end()); + long long global_inverse_count = globalInversionCount(A_copy); + + long long local_inverse_count = 0; + for(int i = 1 ; i < A.size() ; i ++) + if(A[i-1] > A[i]) + local_inverse_count ++; + + return global_inverse_count == local_inverse_count; + } + +private: + int globalInversionCount(vector& vec){ + + return globalInversionCount(vec, 0, vec.size()-1); + } + + long long globalInversionCount(vector& vec, int l, int r){ + + if( l >= r ) + return 0; + + int mid = l + (r-l)/2; + + long long res1 = globalInversionCount(vec, l, mid); + long long res2 = globalInversionCount(vec, mid + 1, r); + + return res1 + res2 + merge(vec, l, mid, r); + } + + long long merge(vector& vec, int l, int mid, int r){ + + vector aux; + for(int i = l ; i <= r ; i ++ ) + aux.push_back(vec[i]); + + long long res = 0; + int j = l, k = mid + 1; + for( int i = l ; i <= r ; i ++ ){ + if( j > mid ){ + vec[i] = aux[k-l]; + k ++; + } + else if( k > r ){ + vec[i] = aux[j-l]; + j ++; + } + else if( aux[j-l] <= aux[k-l] ){ + vec[i] = aux[j-l]; + j ++; + } + else{ + vec[i] = aux[k-l]; + k ++; + res += (mid - j + 1); + } + } + + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0779-K-th-Symbol-in-Grammar/cpp-0779/CMakeLists.txt b/0501-1000/0779-K-th-Symbol-in-Grammar/cpp-0779/CMakeLists.txt new file mode 100644 index 00000000..5f29590d --- /dev/null +++ b/0501-1000/0779-K-th-Symbol-in-Grammar/cpp-0779/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_0779) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0779 main.cpp) diff --git a/0501-1000/0779-K-th-Symbol-in-Grammar/cpp-0779/main.cpp b/0501-1000/0779-K-th-Symbol-in-Grammar/cpp-0779/main.cpp new file mode 100644 index 00000000..286e4dae --- /dev/null +++ b/0501-1000/0779-K-th-Symbol-in-Grammar/cpp-0779/main.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/k-th-symbol-in-grammar/ +/// Author : liuyubobobo +/// Time : 2022-10-20 + +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int kthGrammar(int n, int k) { + return solve(0, n - 1, k - 1); + } + +private: + int solve(int parent, int n, int k){ + if(n == 0) return parent; + + int mid = 1 << (n - 1); + if(k < mid) return solve(parent == 0 ? 0 : 1, n - 1, k); + return solve(parent == 0 ? 1 : 0, n - 1, k - mid); + } +}; + + +int main() { + + return 0; +} diff --git a/0780-Reaching-Points/cpp-0780/CMakeLists.txt b/0501-1000/0780-Reaching-Points/cpp-0780/CMakeLists.txt similarity index 100% rename from 0780-Reaching-Points/cpp-0780/CMakeLists.txt rename to 0501-1000/0780-Reaching-Points/cpp-0780/CMakeLists.txt diff --git a/0780-Reaching-Points/cpp-0780/main.cpp b/0501-1000/0780-Reaching-Points/cpp-0780/main.cpp similarity index 100% rename from 0780-Reaching-Points/cpp-0780/main.cpp rename to 0501-1000/0780-Reaching-Points/cpp-0780/main.cpp diff --git a/0781-Rabbits-in-Forest/cpp-0781/CMakeLists.txt b/0501-1000/0781-Rabbits-in-Forest/cpp-0781/CMakeLists.txt similarity index 100% rename from 0781-Rabbits-in-Forest/cpp-0781/CMakeLists.txt rename to 0501-1000/0781-Rabbits-in-Forest/cpp-0781/CMakeLists.txt diff --git a/0781-Rabbits-in-Forest/cpp-0781/main.cpp b/0501-1000/0781-Rabbits-in-Forest/cpp-0781/main.cpp similarity index 100% rename from 0781-Rabbits-in-Forest/cpp-0781/main.cpp rename to 0501-1000/0781-Rabbits-in-Forest/cpp-0781/main.cpp diff --git a/0501-1000/0782-Transform-to-Chessboard/cpp-0782/CMakeLists.txt b/0501-1000/0782-Transform-to-Chessboard/cpp-0782/CMakeLists.txt new file mode 100644 index 00000000..6364604d --- /dev/null +++ b/0501-1000/0782-Transform-to-Chessboard/cpp-0782/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0782) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0782 main.cpp) diff --git a/0501-1000/0782-Transform-to-Chessboard/cpp-0782/main.cpp b/0501-1000/0782-Transform-to-Chessboard/cpp-0782/main.cpp new file mode 100644 index 00000000..03e57d9f --- /dev/null +++ b/0501-1000/0782-Transform-to-Chessboard/cpp-0782/main.cpp @@ -0,0 +1,120 @@ +/// Source : https://leetcode.com/problems/transform-to-chessboard/ +/// Author : liuyubobobo +/// Time : 2021-09-26 + +#include +#include +#include + +using namespace std; + + +/// Mathematics +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { +public: + int movesToChessboard(vector>& board) { + + int n = board.size(); + + vector total(2, 0); + vector> row(n, vector(2, 0)), col(n, vector(2, 0)); + for(int i = 0; i < n; i ++) + for(int j = 0; j < n; j ++){ + if(board[0][0] ^ board[0][j] ^ board[i][0] ^ board[i][j]) + return -1; + total[board[i][j]] ++; + row[i][board[i][j]] ++; + col[j][board[i][j]] ++; + } + + if(n % 2 == 0 && total[0] != total[1]) return -1; + if(n % 2 == 1 && abs(total[0] - total[1]) > 1) return -1; + + if(n % 2 == 0){ + for(int i = 0; i < n; i ++) + if(row[i][0] != row[i][1] || col[i][0] != col[i][1]) + return -1; + } + else{ + for(int i = 0; i < n; i ++) + if(abs(row[i][0] - row[i][1]) > 1 || abs(col[i][0] - col[i][1]) > 1) + return -1; + } + + vector a(n), b(n); + a = board[0]; + for(int i = 0; i < n; i ++) b[i] = board[i][0]; + + return check(n, a, b); + } + +private: + int check(int n, const vector& a, const vector& b){ + + int ares = 0; + for(int i = 0; i < n; i += 2){ + if(a[i] != 0) ares ++; + if(i + 1 < n && a[i + 1] != 1) ares ++; + } + + int bres = 0; + for(int i = 0; i < n; i += 2){ + if(b[i] != 0) bres ++; + if(i + 1 < n && b[i + 1] != 1) bres ++; + } + + if(ares % 2 || (n % 2 == 0 && n - ares < ares)) ares = n - ares; + if(bres % 2 || (n % 2 == 0 && n - bres < bres)) bres = n - bres; + return (ares + bres) / 2; + } +}; + + +int main() { + + vector> board1 = { + {0,1,1,0},{0,1,1,0},{1,0,0,1},{1,0,0,1} + }; + cout << Solution().movesToChessboard(board1) << endl; + // 2 + + vector> board2 = { + {1,1,0},{0,0,1},{0,0,1} + }; + cout << Solution().movesToChessboard(board2) << endl; + // 2 + + vector> board3 = { + {1,0,0},{0,1,1},{1,0,0} + }; + cout << Solution().movesToChessboard(board3) << endl; + // 1 + + vector> board4 = { + {0,0,1,0,1,0,1,1}, + {1,1,0,1,0,1,0,0}, + {0,0,1,0,1,0,1,1}, + {1,1,0,1,0,1,0,0}, + {1,1,0,1,0,1,0,0}, + {0,0,1,0,1,0,1,1}, + {0,0,1,0,1,0,1,1}, + {1,1,0,1,0,1,0,0} + }; + cout << Solution().movesToChessboard(board4) << endl; + // 2 + + vector> board5 = { + {0,0,1,0,1,1}, + {1,1,0,1,0,0}, + {1,1,0,1,0,0}, + {0,0,1,0,1,1}, + {1,1,0,1,0,0}, + {0,0,1,0,1,1} + }; + cout << Solution().movesToChessboard(board5) << endl; + // 2 + + return 0; +} diff --git a/0501-1000/0783-Minimum-Distance-Between-BST-Nodes/cpp-0783/CMakeLists.txt b/0501-1000/0783-Minimum-Distance-Between-BST-Nodes/cpp-0783/CMakeLists.txt new file mode 100644 index 00000000..651ecc24 --- /dev/null +++ b/0501-1000/0783-Minimum-Distance-Between-BST-Nodes/cpp-0783/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(A) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main4.cpp) +add_executable(A ${SOURCE_FILES}) \ No newline at end of file diff --git a/0783-Minimum-Distance-Between-BST-Nodes/cpp-0783/main.cpp b/0501-1000/0783-Minimum-Distance-Between-BST-Nodes/cpp-0783/main.cpp similarity index 100% rename from 0783-Minimum-Distance-Between-BST-Nodes/cpp-0783/main.cpp rename to 0501-1000/0783-Minimum-Distance-Between-BST-Nodes/cpp-0783/main.cpp diff --git a/0783-Minimum-Distance-Between-BST-Nodes/cpp-0783/main2.cpp b/0501-1000/0783-Minimum-Distance-Between-BST-Nodes/cpp-0783/main2.cpp similarity index 100% rename from 0783-Minimum-Distance-Between-BST-Nodes/cpp-0783/main2.cpp rename to 0501-1000/0783-Minimum-Distance-Between-BST-Nodes/cpp-0783/main2.cpp diff --git a/0783-Minimum-Distance-Between-BST-Nodes/cpp-0783/main3.cpp b/0501-1000/0783-Minimum-Distance-Between-BST-Nodes/cpp-0783/main3.cpp similarity index 100% rename from 0783-Minimum-Distance-Between-BST-Nodes/cpp-0783/main3.cpp rename to 0501-1000/0783-Minimum-Distance-Between-BST-Nodes/cpp-0783/main3.cpp diff --git a/0783-Minimum-Distance-Between-BST-Nodes/cpp-0783/main4.cpp b/0501-1000/0783-Minimum-Distance-Between-BST-Nodes/cpp-0783/main4.cpp similarity index 100% rename from 0783-Minimum-Distance-Between-BST-Nodes/cpp-0783/main4.cpp rename to 0501-1000/0783-Minimum-Distance-Between-BST-Nodes/cpp-0783/main4.cpp diff --git a/0784-Letter-Case-Permutation/cpp-0784/CMakeLists.txt b/0501-1000/0784-Letter-Case-Permutation/cpp-0784/CMakeLists.txt similarity index 100% rename from 0784-Letter-Case-Permutation/cpp-0784/CMakeLists.txt rename to 0501-1000/0784-Letter-Case-Permutation/cpp-0784/CMakeLists.txt diff --git a/0784-Letter-Case-Permutation/cpp-0784/main.cpp b/0501-1000/0784-Letter-Case-Permutation/cpp-0784/main.cpp similarity index 100% rename from 0784-Letter-Case-Permutation/cpp-0784/main.cpp rename to 0501-1000/0784-Letter-Case-Permutation/cpp-0784/main.cpp diff --git a/0784-Letter-Case-Permutation/cpp-0784/main2.cpp b/0501-1000/0784-Letter-Case-Permutation/cpp-0784/main2.cpp similarity index 100% rename from 0784-Letter-Case-Permutation/cpp-0784/main2.cpp rename to 0501-1000/0784-Letter-Case-Permutation/cpp-0784/main2.cpp diff --git a/0785-Is-Graph-Bipartite/cpp-0785/CMakeLists.txt b/0501-1000/0785-Is-Graph-Bipartite/cpp-0785/CMakeLists.txt similarity index 100% rename from 0785-Is-Graph-Bipartite/cpp-0785/CMakeLists.txt rename to 0501-1000/0785-Is-Graph-Bipartite/cpp-0785/CMakeLists.txt diff --git a/0785-Is-Graph-Bipartite/cpp-0785/main.cpp b/0501-1000/0785-Is-Graph-Bipartite/cpp-0785/main.cpp similarity index 100% rename from 0785-Is-Graph-Bipartite/cpp-0785/main.cpp rename to 0501-1000/0785-Is-Graph-Bipartite/cpp-0785/main.cpp diff --git a/0501-1000/0785-Is-Graph-Bipartite/java-0785/src/Solution.java b/0501-1000/0785-Is-Graph-Bipartite/java-0785/src/Solution.java new file mode 100644 index 00000000..47913ef0 --- /dev/null +++ b/0501-1000/0785-Is-Graph-Bipartite/java-0785/src/Solution.java @@ -0,0 +1,125 @@ +import java.util.Arrays; +import java.util.TreeSet; + +public class Solution { + + public class Graph { + + private int V; + private int E; + private TreeSet[] adj; + + public Graph(int V){ + + this.V = V; + adj = new TreeSet[V]; + for(int i = 0; i < V + ; i ++) + adj[i] = new TreeSet(); + } + + public void addEdge(int a, int b){ + + if(a == b) throw new IllegalArgumentException(); + + adj[a].add(b); + adj[b].add(a); + this.E ++; + } + + public void validateVertex(int v){ + if(v < 0 || v >= V) + throw new IllegalArgumentException("vertex " + v + "is invalid"); + } + + public int V(){ + return V; + } + + public int E(){ + return E; + } + + public boolean hasEdge(int v, int w){ + validateVertex(v); + validateVertex(w); + return adj[v].contains(w); + } + + public Iterable adj(int v){ + validateVertex(v); + return adj[v]; + } + + public int degree(int v){ + validateVertex(v); + return adj[v].size(); + } + + @Override + public String toString(){ + StringBuilder sb = new StringBuilder(); + + sb.append(String.format("V = %d, E = %d\n", V, E)); + for(int v = 0; v < V; v ++){ + sb.append(String.format("%d : ", v)); + for(int w : adj[v]) + sb.append(String.format("%d ", w)); + sb.append('\n'); + } + return sb.toString(); + } + } + + public class BipartitionDetection { + + private Graph G; + + private boolean[] visited; + private int[] colors; + private boolean isBipartite = true; + + public BipartitionDetection(Graph G){ + + this.G = G; + visited = new boolean[G.V()]; + colors = new int[G.V()]; + for(int i = 0; i < G.V(); i ++) + colors[i] = -1; + + for(int v = 0; v < G.V(); v ++) + if(!visited[v]) + if(!dfs(v, 0)){ + isBipartite = false; + break; + } + } + + private boolean dfs(int v, int color){ + + visited[v] = true; + colors[v] = color; + for(int w: G.adj(v)) + if(!visited[w]){ + if(!dfs(w, 1 - color)) return false; + } + else if(colors[w] == colors[v]) + return false; + return true; + } + + public boolean isBipartite(){ + return isBipartite; + } + } + + public boolean isBipartite(int[][] graph){ + + int n = graph.length; + Graph g = new Graph(n); + for(int i = 0; i < n; i ++) + for(int j: graph[i]) g.addEdge(i, j); + + return new BipartitionDetection(g).isBipartite(); + } +} \ No newline at end of file diff --git a/0786-K-th-Smallest-Prime-Fraction/cpp-0786/CMakeLists.txt b/0501-1000/0786-K-th-Smallest-Prime-Fraction/cpp-0786/CMakeLists.txt similarity index 100% rename from 0786-K-th-Smallest-Prime-Fraction/cpp-0786/CMakeLists.txt rename to 0501-1000/0786-K-th-Smallest-Prime-Fraction/cpp-0786/CMakeLists.txt diff --git a/0786-K-th-Smallest-Prime-Fraction/cpp-0786/main.cpp b/0501-1000/0786-K-th-Smallest-Prime-Fraction/cpp-0786/main.cpp similarity index 100% rename from 0786-K-th-Smallest-Prime-Fraction/cpp-0786/main.cpp rename to 0501-1000/0786-K-th-Smallest-Prime-Fraction/cpp-0786/main.cpp diff --git a/0786-K-th-Smallest-Prime-Fraction/cpp-0786/main2.cpp b/0501-1000/0786-K-th-Smallest-Prime-Fraction/cpp-0786/main2.cpp similarity index 100% rename from 0786-K-th-Smallest-Prime-Fraction/cpp-0786/main2.cpp rename to 0501-1000/0786-K-th-Smallest-Prime-Fraction/cpp-0786/main2.cpp diff --git a/0786-K-th-Smallest-Prime-Fraction/cpp-0786/main3.cpp b/0501-1000/0786-K-th-Smallest-Prime-Fraction/cpp-0786/main3.cpp similarity index 100% rename from 0786-K-th-Smallest-Prime-Fraction/cpp-0786/main3.cpp rename to 0501-1000/0786-K-th-Smallest-Prime-Fraction/cpp-0786/main3.cpp diff --git a/0786-K-th-Smallest-Prime-Fraction/cpp-0786/main4.cpp b/0501-1000/0786-K-th-Smallest-Prime-Fraction/cpp-0786/main4.cpp similarity index 100% rename from 0786-K-th-Smallest-Prime-Fraction/cpp-0786/main4.cpp rename to 0501-1000/0786-K-th-Smallest-Prime-Fraction/cpp-0786/main4.cpp diff --git a/0787-Cheapest-Flights-Within-K-Stops/cpp-0787/CMakeLists.txt b/0501-1000/0787-Cheapest-Flights-Within-K-Stops/cpp-0787/CMakeLists.txt similarity index 100% rename from 0787-Cheapest-Flights-Within-K-Stops/cpp-0787/CMakeLists.txt rename to 0501-1000/0787-Cheapest-Flights-Within-K-Stops/cpp-0787/CMakeLists.txt diff --git a/0787-Cheapest-Flights-Within-K-Stops/cpp-0787/main.cpp b/0501-1000/0787-Cheapest-Flights-Within-K-Stops/cpp-0787/main.cpp similarity index 100% rename from 0787-Cheapest-Flights-Within-K-Stops/cpp-0787/main.cpp rename to 0501-1000/0787-Cheapest-Flights-Within-K-Stops/cpp-0787/main.cpp diff --git a/0787-Cheapest-Flights-Within-K-Stops/cpp-0787/main2.cpp b/0501-1000/0787-Cheapest-Flights-Within-K-Stops/cpp-0787/main2.cpp similarity index 100% rename from 0787-Cheapest-Flights-Within-K-Stops/cpp-0787/main2.cpp rename to 0501-1000/0787-Cheapest-Flights-Within-K-Stops/cpp-0787/main2.cpp diff --git a/0788-Rotated-Digits/cpp-0788/CMakeLists.txt b/0501-1000/0788-Rotated-Digits/cpp-0788/CMakeLists.txt similarity index 100% rename from 0788-Rotated-Digits/cpp-0788/CMakeLists.txt rename to 0501-1000/0788-Rotated-Digits/cpp-0788/CMakeLists.txt diff --git a/0788-Rotated-Digits/cpp-0788/main.cpp b/0501-1000/0788-Rotated-Digits/cpp-0788/main.cpp similarity index 100% rename from 0788-Rotated-Digits/cpp-0788/main.cpp rename to 0501-1000/0788-Rotated-Digits/cpp-0788/main.cpp diff --git a/0788-Rotated-Digits/cpp-0788/main2.cpp b/0501-1000/0788-Rotated-Digits/cpp-0788/main2.cpp similarity index 100% rename from 0788-Rotated-Digits/cpp-0788/main2.cpp rename to 0501-1000/0788-Rotated-Digits/cpp-0788/main2.cpp diff --git a/0788-Rotated-Digits/cpp-0788/main3.cpp b/0501-1000/0788-Rotated-Digits/cpp-0788/main3.cpp similarity index 100% rename from 0788-Rotated-Digits/cpp-0788/main3.cpp rename to 0501-1000/0788-Rotated-Digits/cpp-0788/main3.cpp diff --git a/0788-Rotated-Digits/cpp-0788/main4.cpp b/0501-1000/0788-Rotated-Digits/cpp-0788/main4.cpp similarity index 100% rename from 0788-Rotated-Digits/cpp-0788/main4.cpp rename to 0501-1000/0788-Rotated-Digits/cpp-0788/main4.cpp diff --git a/0788-Rotated-Digits/cpp-0788/main5.cpp b/0501-1000/0788-Rotated-Digits/cpp-0788/main5.cpp similarity index 100% rename from 0788-Rotated-Digits/cpp-0788/main5.cpp rename to 0501-1000/0788-Rotated-Digits/cpp-0788/main5.cpp diff --git a/0789-Escape-The-Ghosts/cpp-0789/CMakeLists.txt b/0501-1000/0789-Escape-The-Ghosts/cpp-0789/CMakeLists.txt similarity index 100% rename from 0789-Escape-The-Ghosts/cpp-0789/CMakeLists.txt rename to 0501-1000/0789-Escape-The-Ghosts/cpp-0789/CMakeLists.txt diff --git a/0789-Escape-The-Ghosts/cpp-0789/main.cpp b/0501-1000/0789-Escape-The-Ghosts/cpp-0789/main.cpp similarity index 100% rename from 0789-Escape-The-Ghosts/cpp-0789/main.cpp rename to 0501-1000/0789-Escape-The-Ghosts/cpp-0789/main.cpp diff --git a/0727-Minimum-Window-Subsequence/cpp-0727/CMakeLists.txt b/0501-1000/0790-Domino-and-Tromino-Tiling/cpp-0790/CMakeLists.txt similarity index 100% rename from 0727-Minimum-Window-Subsequence/cpp-0727/CMakeLists.txt rename to 0501-1000/0790-Domino-and-Tromino-Tiling/cpp-0790/CMakeLists.txt diff --git a/0790-Domino-and-Tromino-Tiling/cpp-0790/main.cpp b/0501-1000/0790-Domino-and-Tromino-Tiling/cpp-0790/main.cpp similarity index 100% rename from 0790-Domino-and-Tromino-Tiling/cpp-0790/main.cpp rename to 0501-1000/0790-Domino-and-Tromino-Tiling/cpp-0790/main.cpp diff --git a/0790-Domino-and-Tromino-Tiling/cpp-0790/main2.cpp b/0501-1000/0790-Domino-and-Tromino-Tiling/cpp-0790/main2.cpp similarity index 100% rename from 0790-Domino-and-Tromino-Tiling/cpp-0790/main2.cpp rename to 0501-1000/0790-Domino-and-Tromino-Tiling/cpp-0790/main2.cpp diff --git a/0790-Domino-and-Tromino-Tiling/cpp-0790/main3.cpp b/0501-1000/0790-Domino-and-Tromino-Tiling/cpp-0790/main3.cpp similarity index 100% rename from 0790-Domino-and-Tromino-Tiling/cpp-0790/main3.cpp rename to 0501-1000/0790-Domino-and-Tromino-Tiling/cpp-0790/main3.cpp diff --git a/0799-Champagne-Tower/cpp-0799/CMakeLists.txt b/0501-1000/0791-Custom-Sort-String/cpp-0791/CMakeLists.txt similarity index 100% rename from 0799-Champagne-Tower/cpp-0799/CMakeLists.txt rename to 0501-1000/0791-Custom-Sort-String/cpp-0791/CMakeLists.txt diff --git a/0791-Custom-Sort-String/cpp-0791/main.cpp b/0501-1000/0791-Custom-Sort-String/cpp-0791/main.cpp similarity index 100% rename from 0791-Custom-Sort-String/cpp-0791/main.cpp rename to 0501-1000/0791-Custom-Sort-String/cpp-0791/main.cpp diff --git a/0792-Number-of-Matching-Subsequences/cpp-0792/CMakeLists.txt b/0501-1000/0792-Number-of-Matching-Subsequences/cpp-0792/CMakeLists.txt similarity index 100% rename from 0792-Number-of-Matching-Subsequences/cpp-0792/CMakeLists.txt rename to 0501-1000/0792-Number-of-Matching-Subsequences/cpp-0792/CMakeLists.txt diff --git a/0792-Number-of-Matching-Subsequences/cpp-0792/main.cpp b/0501-1000/0792-Number-of-Matching-Subsequences/cpp-0792/main.cpp similarity index 100% rename from 0792-Number-of-Matching-Subsequences/cpp-0792/main.cpp rename to 0501-1000/0792-Number-of-Matching-Subsequences/cpp-0792/main.cpp diff --git a/0501-1000/0793-Preimage-Size-of-Factorial-Zeroes-Function/cpp-0793/CMakeLists.txt b/0501-1000/0793-Preimage-Size-of-Factorial-Zeroes-Function/cpp-0793/CMakeLists.txt new file mode 100644 index 00000000..1c3e7bb6 --- /dev/null +++ b/0501-1000/0793-Preimage-Size-of-Factorial-Zeroes-Function/cpp-0793/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(D) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(D ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0793-Preimage-Size-of-Factorial-Zeroes-Function/cpp-0793/main.cpp b/0501-1000/0793-Preimage-Size-of-Factorial-Zeroes-Function/cpp-0793/main.cpp new file mode 100644 index 00000000..799c3061 --- /dev/null +++ b/0501-1000/0793-Preimage-Size-of-Factorial-Zeroes-Function/cpp-0793/main.cpp @@ -0,0 +1,62 @@ +/// Source : https://leetcode.com/problems/preimage-size-of-factorial-zeroes-function/description/ +/// Author : liuyubobobo +/// Time : 2018-03-03 +/// Updated: 2022-08-28 + +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(logK * logK) +/// Space Complexity: O(1) +class Solution { +public: + int preimageSizeFZF(int K) { + + if(K == 0) + return 5; + + long long l = 0ll, r = 5ll * K; + while(l < r){ + long long mid = (l + r) / 2; + long long f_res = f(mid); + if(f_res >= K) + r = mid; + else + l = mid + 1; + } + + if(f(l) == K){ + return 5 - l % 5; + } + return 0; + } + +private: + long long f(long long x){ + long long res = 0; + long long factor = 5; + while(factor <= x){ + res += x / factor; + factor *= 5; + } + return res; + } +}; + + +int main() { + + cout << Solution().preimageSizeFZF(0) << endl; + // 5 + + cout << Solution().preimageSizeFZF(5) << endl; + // 0 + + cout << Solution().preimageSizeFZF(1000000000) << endl; + // 5 + + return 0; +} \ No newline at end of file diff --git a/0811-Subdomain-Visit-Count/cpp-0811/CMakeLists.txt b/0501-1000/0794-Valid-Tic-Tac-Toe-State/cpp-0794/CMakeLists.txt similarity index 100% rename from 0811-Subdomain-Visit-Count/cpp-0811/CMakeLists.txt rename to 0501-1000/0794-Valid-Tic-Tac-Toe-State/cpp-0794/CMakeLists.txt diff --git a/0794-Valid-Tic-Tac-Toe-State/cpp-0794/main.cpp b/0501-1000/0794-Valid-Tic-Tac-Toe-State/cpp-0794/main.cpp similarity index 100% rename from 0794-Valid-Tic-Tac-Toe-State/cpp-0794/main.cpp rename to 0501-1000/0794-Valid-Tic-Tac-Toe-State/cpp-0794/main.cpp diff --git a/0795-Number-of-Subarrays-with-Bounded-Maximum/cpp-0795/CMakeLists.txt b/0501-1000/0795-Number-of-Subarrays-with-Bounded-Maximum/cpp-0795/CMakeLists.txt similarity index 100% rename from 0795-Number-of-Subarrays-with-Bounded-Maximum/cpp-0795/CMakeLists.txt rename to 0501-1000/0795-Number-of-Subarrays-with-Bounded-Maximum/cpp-0795/CMakeLists.txt diff --git a/0795-Number-of-Subarrays-with-Bounded-Maximum/cpp-0795/main.cpp b/0501-1000/0795-Number-of-Subarrays-with-Bounded-Maximum/cpp-0795/main.cpp similarity index 100% rename from 0795-Number-of-Subarrays-with-Bounded-Maximum/cpp-0795/main.cpp rename to 0501-1000/0795-Number-of-Subarrays-with-Bounded-Maximum/cpp-0795/main.cpp diff --git a/0795-Number-of-Subarrays-with-Bounded-Maximum/cpp-0795/main2.cpp b/0501-1000/0795-Number-of-Subarrays-with-Bounded-Maximum/cpp-0795/main2.cpp similarity index 100% rename from 0795-Number-of-Subarrays-with-Bounded-Maximum/cpp-0795/main2.cpp rename to 0501-1000/0795-Number-of-Subarrays-with-Bounded-Maximum/cpp-0795/main2.cpp diff --git a/0501-1000/0796-Rotate-String/cpp-0796/CMakeLists.txt b/0501-1000/0796-Rotate-String/cpp-0796/CMakeLists.txt new file mode 100644 index 00000000..5cc31b93 --- /dev/null +++ b/0501-1000/0796-Rotate-String/cpp-0796/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(A) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main3.cpp) +add_executable(A ${SOURCE_FILES}) \ No newline at end of file diff --git a/0796-Rotate-String/cpp-0796/main.cpp b/0501-1000/0796-Rotate-String/cpp-0796/main.cpp similarity index 100% rename from 0796-Rotate-String/cpp-0796/main.cpp rename to 0501-1000/0796-Rotate-String/cpp-0796/main.cpp diff --git a/0796-Rotate-String/cpp-0796/main2.cpp b/0501-1000/0796-Rotate-String/cpp-0796/main2.cpp similarity index 100% rename from 0796-Rotate-String/cpp-0796/main2.cpp rename to 0501-1000/0796-Rotate-String/cpp-0796/main2.cpp diff --git a/0796-Rotate-String/cpp-0796/main3.cpp b/0501-1000/0796-Rotate-String/cpp-0796/main3.cpp similarity index 100% rename from 0796-Rotate-String/cpp-0796/main3.cpp rename to 0501-1000/0796-Rotate-String/cpp-0796/main3.cpp diff --git a/0797-All-Paths-From-Source-to-Target/cpp-0797/CMakeLists.txt b/0501-1000/0797-All-Paths-From-Source-to-Target/cpp-0797/CMakeLists.txt similarity index 100% rename from 0797-All-Paths-From-Source-to-Target/cpp-0797/CMakeLists.txt rename to 0501-1000/0797-All-Paths-From-Source-to-Target/cpp-0797/CMakeLists.txt diff --git a/0797-All-Paths-From-Source-to-Target/cpp-0797/main.cpp b/0501-1000/0797-All-Paths-From-Source-to-Target/cpp-0797/main.cpp similarity index 100% rename from 0797-All-Paths-From-Source-to-Target/cpp-0797/main.cpp rename to 0501-1000/0797-All-Paths-From-Source-to-Target/cpp-0797/main.cpp diff --git a/0501-1000/0798-Smallest-Rotation-with-Highest-Score/cpp-0798/CMakeLists.txt b/0501-1000/0798-Smallest-Rotation-with-Highest-Score/cpp-0798/CMakeLists.txt new file mode 100644 index 00000000..6055682b --- /dev/null +++ b/0501-1000/0798-Smallest-Rotation-with-Highest-Score/cpp-0798/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_0798) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0798 main3.cpp) diff --git a/0501-1000/0798-Smallest-Rotation-with-Highest-Score/cpp-0798/main.cpp b/0501-1000/0798-Smallest-Rotation-with-Highest-Score/cpp-0798/main.cpp new file mode 100644 index 00000000..e3350b46 --- /dev/null +++ b/0501-1000/0798-Smallest-Rotation-with-Highest-Score/cpp-0798/main.cpp @@ -0,0 +1,334 @@ +/// Source : https://leetcode.com/problems/smallest-rotation-with-highest-score/ +/// Author : liuyubobobo +/// Time : 2022-03-08 + +#include +#include + +using namespace std; + + +/// Using AVLTree (as Sort List) +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +template +class AVLTreeMultiSet{ + +private: + class Node{ + public: + Key key; + Node *left = nullptr, *right = nullptr; + int height = 1, size = 1; + + Node(const Key& key): key(key){} + }; + + Node* root = nullptr; + +public: + AVLTreeMultiSet(){} + + int size(){ + return size(root); + } + + void add(const Key& key){ + root = add(root, key); + } + + void remove(const Key& key){ + root = remove(root, key); + } + + bool contains(const Key& key){ + return get_node(root, key) != nullptr; + } + + // 0-based rank + int get_index(const Key& key){ + + Node* node = get_node(root, key); +// assert(node); + + return size_less_than(key); + } + + // 0-based select + Key select(int index){ + +// assert(index < size(root)); + return select(root, index); + } + + // < key 的元素有几个? + int size_less_than(const Key& key){ + return size_less_than(root, key); + } + + // <= key 的元素有几个? + int size_less_than_or_equal_to(const Key& key){ + return size_less_than_or_equal_to(root, key); + } + + // > key 的元素有几个? + int size_larger_than(const Key& key){ + return size_larger_than(root, key); + } + + // >= key 的元素有几个? + int size_larger_than_or_equal_to(const Key& key){ + return size_larger_than_or_equal_to(root, key); + } + +private: + int size(Node* node){ + return node ? node->size : 0; + } + + int height(Node* node){ + return node ? node->height : 0; + } + + int get_balance_factor(Node* node){ + return height(node->left) - height(node->right); + } + + Node* right_rotate(Node* y) { + Node* x = y->left; + Node* T3 = x->right; + + // 向右旋转过程 + x->right = y; + y->left = T3; + + // 更新 height 和 size + y->height = max(height(y->left), height(y->right)) + 1; + x->height = max(height(x->left), height(x->right)) + 1; + + y->size = size(y->left) + size(y->right) + 1; + x->size = size(x->left) + size(x->right) + 1; + + return x; + } + + Node* left_rotate(Node* y) { + Node* x = y->right; + Node* T2 = x->left; + + // 向左旋转过程 + x->left = y; + y->right = T2; + + // 更新 height 和 size + y->height = max(height(y->left), height(y->right)) + 1; + x->height = max(height(x->left), height(x->right)) + 1; + + y->size = size(y->left) + size(y->right) + 1; + x->size = size(x->left) + size(x->right) + 1; + + return x; + } + + // 向以node为根的二分搜索树中插入元素(key, value),递归算法 + // 返回插入新节点后二分搜索树的根 + Node* add(Node* node, const Key& key){ + + if(node == nullptr) + return new Node(key); + + if(key <= node->key) + node->left = add(node->left, key); + else if(key > node->key) + node->right = add(node->right, key); + + return keep_balance(node); + } + + Node* remove(Node* node, const Key& key){ + + if(node == nullptr) + return nullptr; + + Node* ret_node; + if(key < node->key){ + node->left = remove(node->left, key); + ret_node = node; + } + else if(key > node->key){ + node->right = remove(node->right, key); + ret_node = node; + } + else{ + + // 待删除节点左子树为空的情况 + if(node->left == nullptr){ + Node* right_node = node->right; + node->right = nullptr; + ret_node = right_node; + } + // 待删除节点右子树为空的情况 + else if(node->right == nullptr){ + Node* left_node = node->left; + node->left = nullptr; + ret_node = left_node; + } + // 待删除节点左右子树均不为空的情况 + else{ + // 找到比待删除节点大的最小节点, 即待删除节点右子树的最小节点 + // 用这个节点顶替待删除节点的位置 + Node* min_node = get_min_node(node->right); +// assert(min_node); + node->key = min_node->key; + + node->right = remove_min(node->right); + ret_node = node; + } + } + + return keep_balance(ret_node); + } + + Node* remove_min(Node* node){ + + if(node == nullptr) + return nullptr; + + Node* ret_node; + if(node->left) { + node->left = remove_min(node->left); + ret_node = node; + } + else + ret_node = node->right; + + return keep_balance(ret_node); + } + + Node* get_min_node(Node* node){ + + if(!node) return nullptr; + + if(node->left) return get_min_node(node->left); + return node; + } + + Node* keep_balance(Node* node){ + + if(!node) return nullptr; + + // 更新 height 和 size + node->height = 1 + max(height(node->left), height(node->right)); + node->size = 1 + size(node->left) + size(node->right); + + // 计算平衡因子 + int balance_factor = get_balance_factor(node); + + // 平衡维护 + // LL + if (balance_factor > 1 && get_balance_factor(node->left) >= 0) + return right_rotate(node); + + // RR + if (balance_factor < -1 && get_balance_factor(node->right) <= 0) + return left_rotate(node); + + // LR + if (balance_factor > 1 && get_balance_factor(node->left) < 0) { + node->left = left_rotate(node->left); + return right_rotate(node); + } + + // RL + if (balance_factor < -1 && get_balance_factor(node->right) > 0) { + node->right = right_rotate(node->right); + return left_rotate(node); + } + + return node; + } + + Node* get_node(Node* node, const Key& key){ + + if(node == nullptr) + return nullptr; + + if(key == node->key) + return node; + else if(key < node->key) + return get_node(node->left, key); + else + return get_node(node->right, key); + } + + Key select(Node* node, int index){ + + if(index < size(node->left)) return select(node->left, index); + + if(index == size(node->left)) return node->key; + + return select(node->right, index - size(node->left) - 1); + } + + // < key 的元素有几个 + int size_less_than(Node* node, const Key& key){ + if(!node) return 0; + if(key <= node->key) return size_less_than(node->left, key); + return size(node->left) + 1 + size_less_than(node->right, key); + } + + // <= key 的元素有几个 + int size_less_than_or_equal_to(Node* node, const Key& key){ + if(!node) return 0; + if(key < node->key) return size_less_than_or_equal_to(node->left, key); + return size(node->left) + 1 + size_less_than_or_equal_to(node->right, key); + } + + // > key 的元素有几个 + int size_larger_than(Node* node, const Key& key){ + if(!node) return 0; + if(key >= node->key) return size_larger_than(node->right, key); + return size_larger_than(node->left, key) + 1 + size(node->right); + } + + // >= key 的元素有几个 + int size_larger_than_or_equal_to(Node* node, const Key& key){ + if(!node) return 0; + if(key > node->key) return size_larger_than_or_equal_to(node->right, key); + return size_larger_than_or_equal_to(node->left, key) + 1 + size(node->right); + } +}; + +class Solution { +public: + int bestRotation(vector& nums) { + + AVLTreeMultiSet tree; + + int n = nums.size(); + for(int i = 0; i < n; i ++) + tree.add(nums[i] - i); + + int best_score = 0, k = 0; + for(int i = 0; i < n; i ++){ + int score = tree.size_less_than_or_equal_to(-i); +// cout << "k : " << i << " score : " << score << '\n'; + + if(score > best_score) best_score = score, k = i; + + tree.remove(nums[i] - i); + tree.add(nums[i] - (n - 1) - (i + 1)); + } + return k; + } +}; + + +int main() { + + vector nums1 = {2, 3, 1, 4, 0}; + cout << Solution().bestRotation(nums1) << '\n'; + // 3 + + return 0; +} diff --git a/0501-1000/0798-Smallest-Rotation-with-Highest-Score/cpp-0798/main2.cpp b/0501-1000/0798-Smallest-Rotation-with-Highest-Score/cpp-0798/main2.cpp new file mode 100644 index 00000000..46cb5a5b --- /dev/null +++ b/0501-1000/0798-Smallest-Rotation-with-Highest-Score/cpp-0798/main2.cpp @@ -0,0 +1,135 @@ +/// Source : https://leetcode.com/problems/smallest-rotation-with-highest-score/ +/// Author : liuyubobobo +/// Time : 2022-03-08 + +#include +#include + +using namespace std; + + +/// Using Segment Tree (as Sort List) +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +template +class SegmentTree{ + +private: + int n; + vector data, tree; + T (*combine)(T a, T b); + +public: + SegmentTree(const vector& data, T (*combine)(T a, T b)): n(data.size()), data(data), tree(4 * n, 0){ + this->combine = combine; + buildSegTree(0, 0, n - 1); + } + + SegmentTree(int n, T (*combine)(T a, T b)): n(n), data(n, 0), tree(4 * n, 0){ + this->combine = combine; + } + + void update(int index, T value){ + if(data[index] == value) return; + data[index] = value; + update(0, 0, n - 1, index, value); + } + + void add(int index, T v){ + if(index < 0) return; + data[index] += v; + update(0, 0, n - 1, index, data[index]); + } + + T query(int index){ +// assert(0 <= index && index < n); + return data[index]; + } + + T query(int l, int r){ +// assert(l <= r); +// assert(0 <= l && l < n); +// assert(0 <= r && r < n); + return query(0, 0, n - 1, l, r); + } + +private: + void buildSegTree(int treeID, int l, int r){ + + if(l == r){ + tree[treeID] = data[l]; + return; + } + + int mid = (l + r) / 2; + buildSegTree(treeID * 2 + 1, l, mid); + buildSegTree(treeID * 2 + 2, mid + 1, r); + tree[treeID] = combine(tree[treeID * 2 + 1], tree[treeID * 2 + 2]); + return; + } + + void update(int treeID, int l, int r, int index, T value){ + + if(l == r){ +// assert(l == index); + tree[treeID] = value; + return; + } + + int mid = (l + r) / 2; + if(index <= mid) update(treeID * 2 + 1, l, mid, index, value); + else update(treeID * 2 + 2, mid + 1, r, index, value); + + tree[treeID] = combine(tree[treeID * 2 + 1], tree[treeID * 2 + 2]); + return; + } + + T query(int treeID, int l, int r, int ql, int qr){ + + if(ql == l && qr == r) + return tree[treeID]; + + int mid = (l + r) / 2; + if(qr <= mid) return query(treeID * 2 + 1, l, mid, ql, qr); + else if(ql > mid) return query(treeID * 2 + 2, mid + 1, r, ql, qr); + + T resl = query(treeID * 2 + 1, l, mid, ql, mid); + T resr = query(treeID * 2 + 2, mid + 1, r, mid + 1, qr); + return combine(resl, resr); + } +}; + +class Solution { +public: + int bestRotation(vector& nums) { + + const int MAXN = 2e5; + SegmentTree tree(MAXN, [](int a, int b){return a + b;}); + + int n = nums.size(); + for(int i = 0; i < n; i ++) + tree.add(-(nums[i] - i), 1); + + int best_score = 0, k = 0; + for(int i = 0; i < n; i ++){ + int score = tree.query(i, MAXN - 1); +// cout << "k : " << i << " score : " << score << '\n'; + + if(score > best_score) best_score = score, k = i; + + tree.add(-(nums[i] - i), -1); + tree.add(-(nums[i] - (n - 1) - (i + 1)), 1); + } + return k; + } +}; + + +int main() { + + vector nums1 = {2, 3, 1, 4, 0}; + cout << Solution().bestRotation(nums1) << '\n'; + // 3 + + return 0; +} diff --git a/0501-1000/0798-Smallest-Rotation-with-Highest-Score/cpp-0798/main3.cpp b/0501-1000/0798-Smallest-Rotation-with-Highest-Score/cpp-0798/main3.cpp new file mode 100644 index 00000000..58b51aab --- /dev/null +++ b/0501-1000/0798-Smallest-Rotation-with-Highest-Score/cpp-0798/main3.cpp @@ -0,0 +1,101 @@ +/// Source : https://leetcode.com/problems/smallest-rotation-with-highest-score/ +/// Author : liuyubobobo +/// Time : 2022-03-08 + +#include +#include + +using namespace std; + + +/// Using BIT (as Sort List) +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +template +class BIT{ + +private: + int n; + vector data; + vector tree; + +public: + BIT(const vector& arr) : n(arr.size()), data(arr.begin(), arr.end()), tree(n + 1){ + + for(int i = 0; i < n; i ++) + tree[i + 1]= data[i]; + + for(int i = 1; i <= n; i ++){ + int parent = i + (i & -i); + if(parent <= n) tree[parent] += tree[i]; + } + } + + void add(int index, T v){ +// assert(0 <= index && index < n); + + if(index < 0) return; + data[index] += v; + + index ++; + for(;index <= n; index += (index & -index)) + tree[index] += v; + } + + T query(int l, int r){ +// assert(0 <= l && l < n); +// assert(0 <= r && r < n); +// assert(l <= r); + return prefix_sum(r + 1) - prefix_sum(l); + } + + void set(int index, T v){ +// assert(0 <= index && index < n); + add(index, v - data[index]); + } + +private: + // r is 1-based + T prefix_sum(int r){ + + T res = 0; + for(; r; r -= (r & -r)) + res += tree[r]; + return res; + } +}; + +class Solution { +public: + int bestRotation(vector& nums) { + + const int MAXN = 2e5; + BIT bit(vector(MAXN, 0)); + + int n = nums.size(); + for(int i = 0; i < n; i ++) + bit.add(-(nums[i] - i), 1); + + int best_score = 0, k = 0; + for(int i = 0; i < n; i ++){ + int score = bit.query(i, MAXN - 1); +// cout << "k : " << i << " score : " << score << '\n'; + + if(score > best_score) best_score = score, k = i; + + bit.add(-(nums[i] - i), -1); + bit.add(-(nums[i] - (n - 1) - (i + 1)), 1); + } + return k; + } +}; + + +int main() { + + vector nums1 = {2, 3, 1, 4, 0}; + cout << Solution().bestRotation(nums1) << '\n'; + // 3 + + return 0; +} diff --git a/0807-Max-Increase-to-Keep-City-Skyline/cpp-0807/CMakeLists.txt b/0501-1000/0799-Champagne-Tower/cpp-0799/CMakeLists.txt similarity index 100% rename from 0807-Max-Increase-to-Keep-City-Skyline/cpp-0807/CMakeLists.txt rename to 0501-1000/0799-Champagne-Tower/cpp-0799/CMakeLists.txt diff --git a/0799-Champagne-Tower/cpp-0799/main.cpp b/0501-1000/0799-Champagne-Tower/cpp-0799/main.cpp similarity index 100% rename from 0799-Champagne-Tower/cpp-0799/main.cpp rename to 0501-1000/0799-Champagne-Tower/cpp-0799/main.cpp diff --git a/0800-Similar-RGB-Color/cpp-0800/CMakeLists.txt b/0501-1000/0800-Similar-RGB-Color/cpp-0800/CMakeLists.txt similarity index 100% rename from 0800-Similar-RGB-Color/cpp-0800/CMakeLists.txt rename to 0501-1000/0800-Similar-RGB-Color/cpp-0800/CMakeLists.txt diff --git a/0800-Similar-RGB-Color/cpp-0800/main.cpp b/0501-1000/0800-Similar-RGB-Color/cpp-0800/main.cpp similarity index 100% rename from 0800-Similar-RGB-Color/cpp-0800/main.cpp rename to 0501-1000/0800-Similar-RGB-Color/cpp-0800/main.cpp diff --git a/0800-Similar-RGB-Color/cpp-0800/main2.cpp b/0501-1000/0800-Similar-RGB-Color/cpp-0800/main2.cpp similarity index 100% rename from 0800-Similar-RGB-Color/cpp-0800/main2.cpp rename to 0501-1000/0800-Similar-RGB-Color/cpp-0800/main2.cpp diff --git a/0800-Similar-RGB-Color/cpp-0800/main3.cpp b/0501-1000/0800-Similar-RGB-Color/cpp-0800/main3.cpp similarity index 100% rename from 0800-Similar-RGB-Color/cpp-0800/main3.cpp rename to 0501-1000/0800-Similar-RGB-Color/cpp-0800/main3.cpp diff --git a/0501-1000/0802-Find-Eventual-Safe-States/cpp-0802/CMakeLists.txt b/0501-1000/0802-Find-Eventual-Safe-States/cpp-0802/CMakeLists.txt new file mode 100644 index 00000000..d8aaa813 --- /dev/null +++ b/0501-1000/0802-Find-Eventual-Safe-States/cpp-0802/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0802) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0802 main2.cpp) diff --git a/0501-1000/0802-Find-Eventual-Safe-States/cpp-0802/main.cpp b/0501-1000/0802-Find-Eventual-Safe-States/cpp-0802/main.cpp new file mode 100644 index 00000000..20efab4f --- /dev/null +++ b/0501-1000/0802-Find-Eventual-Safe-States/cpp-0802/main.cpp @@ -0,0 +1,92 @@ +/// Source : https://leetcode.com/problems/find-eventual-safe-states/ +/// Author : liuyubobobo +/// Time : 2021-08-05 + +#include +#include + +using namespace std; + + +/// 有向图寻环 modified +/// Time Complexity: O(n) +/// Space Compexity: O(n) +class Solution { +public: + vector eventualSafeNodes(vector>& g) { + + int n = g.size(); + vector visited(n, false), instack(n, false), in_circle(n, false); + vector from(n, -1); + for(int i = 0; i < n; i ++) + if(!visited[i]) + dfs(g, i, -1, visited, instack, from, in_circle); + + vector res; + for(int v = 0; v < n; v ++) + if(!in_circle[v]) res.push_back(v); + return res; + } + +private: + bool dfs(const vector>& g, int u, int p, + vector& visited, vector& instack, vector& from, vector& in_circle){ + + visited[u] = true; + instack[u] = true; + + from[u] = p; + + bool ret = false; + for(int v: g[u]) + if(!visited[v]){ + if(dfs(g, v, u, visited, instack, from, in_circle)) + ret = true; + } + else if(instack[v]){ + in_circle[v] = true; + int cur = u; + while(cur != v){ + in_circle[cur] = true; + cur = from[cur]; + } + ret = true; + } + else if(in_circle[v]){ + ret = true; + } + + instack[u] = false; + + if(ret) in_circle[u] = true; + return ret; + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << ' '; cout << endl; +} + +int main() { + + vector> g1 = { + {1,2},{2,3},{5},{0},{5},{},{} + }; + print_vec(Solution().eventualSafeNodes(g1)); + // 2 4 5 6 + + vector> g2 = { + {1,2,3,4},{1,2},{3,4},{0,4},{} + }; + print_vec(Solution().eventualSafeNodes(g2)); + // 4 + + vector> g3 = { + {0},{2,3,4},{3,4},{0,4},{} + }; + print_vec(Solution().eventualSafeNodes(g3)); + // 4 + + return 0; +} diff --git a/0501-1000/0802-Find-Eventual-Safe-States/cpp-0802/main2.cpp b/0501-1000/0802-Find-Eventual-Safe-States/cpp-0802/main2.cpp new file mode 100644 index 00000000..f35b3606 --- /dev/null +++ b/0501-1000/0802-Find-Eventual-Safe-States/cpp-0802/main2.cpp @@ -0,0 +1,84 @@ +/// Source : https://leetcode.com/problems/find-eventual-safe-states/ +/// Author : liuyubobobo +/// Time : 2021-08-05 + +#include +#include +#include + +using namespace std; + + +/// 反图拓扑排序 +/// Time Complexity: O(n) +/// Space Compexity: O(n) +class Solution { +public: + vector eventualSafeNodes(vector>& g) { + + int n = g.size(); + + vector> rg(n); + vector indegrees(n, 0); + for(int u = 0; u < n; u ++) + for(int v: g[u]){ + rg[v].push_back(u); + indegrees[u] ++; + } + + queue q; + vector visited(n, false); + for(int u = 0; u < n; u ++) + if(indegrees[u] == 0){ + q.push(u); + visited[u] = true; + } + + vector res; + while(!q.empty()){ + int u = q.front(); q.pop(); + + res.push_back(u); + + for(int v: rg[u]) + if(!visited[v]){ + indegrees[v] --; + if(indegrees[v] == 0){ + q.push(v); + visited[v] = true; + } + } + } + + sort(res.begin(), res.end()); + return res; + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << ' '; cout << endl; +} + +int main() { + + vector> g1 = { + {1,2},{2,3},{5},{0},{5},{},{} + }; + print_vec(Solution().eventualSafeNodes(g1)); + // 2 4 5 6 + + vector> g2 = { + {1,2,3,4},{1,2},{3,4},{0,4},{} + }; + print_vec(Solution().eventualSafeNodes(g2)); + // 4 + + vector> g3 = { + {0},{2,3,4},{3,4},{0,4},{} + }; + print_vec(Solution().eventualSafeNodes(g3)); + // 4 + + return 0; +} diff --git a/0501-1000/0803-Bricks-Falling-When-Hit/cpp-0803/CMakeLists.txt b/0501-1000/0803-Bricks-Falling-When-Hit/cpp-0803/CMakeLists.txt new file mode 100644 index 00000000..b667167c --- /dev/null +++ b/0501-1000/0803-Bricks-Falling-When-Hit/cpp-0803/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0803) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0803 main.cpp) \ No newline at end of file diff --git a/0501-1000/0803-Bricks-Falling-When-Hit/cpp-0803/main.cpp b/0501-1000/0803-Bricks-Falling-When-Hit/cpp-0803/main.cpp new file mode 100644 index 00000000..1b2af720 --- /dev/null +++ b/0501-1000/0803-Bricks-Falling-When-Hit/cpp-0803/main.cpp @@ -0,0 +1,139 @@ +/// Source : https://leetcode.com/problems/bricks-falling-when-hit/ +/// Author : liuyubobobo +/// Time : 2021-01-15 + +#include +#include + +using namespace std; + + +/// UF +/// Time Complexity: O(R * C) +/// Space Complexity: O(R * C) +class UF{ + +private: + vector parent, sz; + +public: + UF(int n) : parent(n), sz(n, 1){ + for(int i = 0 ; i < n ; i ++) + parent[i] = i; + } + + int find(int p){ + if(p != parent[p]) + parent[p] = find(parent[p]); + return parent[p]; + } + + bool isConnected(int p , int q){ + return find(p) == find(q); + } + + void unionElements(int p, int q){ + + int pRoot = find(p), qRoot = find(q); + + if(pRoot == qRoot) return; + + parent[pRoot] = qRoot; + sz[qRoot] += sz[pRoot]; + } + + int size(int p){ + return sz[find(p)]; + } +}; + +class Solution { + +private: + const int dirs[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; + int R, C; + +public: + vector hitBricks(vector>& grid, vector>& hits) { + + C = grid[0].size(); + grid.insert(grid.begin(), vector(C, 1)); + R = grid.size(); + + for(vector& hit: hits){ + hit[0] ++; + if(grid[hit[0]][hit[1]] == 1) + grid[hit[0]][hit[1]] = -1; + } + + UF uf(R * C); + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++) + if(grid[i][j] == 1){ + for(int d = 0; d < 4; d ++){ + int x = i + dirs[d][0], y = j + dirs[d][1]; + if(in_area(x, y) && grid[x][y] == 1) + uf.unionElements(i * C + j, x * C + y); + } + } + + vector res(hits.size()); + int pre = uf.size(0); + for(int i = (int)hits.size() - 1; i >= 0; i --) + if(grid[hits[i][0]][hits[i][1]] == -1){ + grid[hits[i][0]][hits[i][1]] = 1; + for(int d = 0; d < 4; d ++){ + int x = hits[i][0] + dirs[d][0], y = hits[i][1] + dirs[d][1]; + if(in_area(x, y) && grid[x][y] == 1) + uf.unionElements(hits[i][0] * C + hits[i][1], x * C + y); + } + int cur = uf.size(0); + if(cur > pre){ + res[i] = cur - pre - 1; + pre = cur; + } + } + else + res[i] = 0; + + return res; + } + +private: + bool in_area(int x, int y){ + return x >= 0 && x < R && y >= 0 && y < C; + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << " "; cout << endl; +} + +int main() { + + vector> grid1 = { + {1, 0, 0, 0}, + {1, 1, 1, 0} + }; + vector> hits1 = {{1, 0}}; + print_vec(Solution().hitBricks(grid1, hits1)); + // 2 + + vector> grid2 = { + {1, 0, 0, 0}, + {1, 1, 0, 0} + }; + vector> hits2 = {{1, 1}, {1, 0}}; + print_vec(Solution().hitBricks(grid2, hits2)); + // 0 0 + + vector> grid3 = { + {1}, {1}, {1}, {1}, {1} + }; + vector> hits3 = {{3, 0}, {4, 0}, {1, 0}, {2, 0}, {0, 0}}; + print_vec(Solution().hitBricks(grid3, hits3)); + // 1 0 1 0 0 + + return 0; +} diff --git a/0804-Unique-Morse-Code-Words/cpp-0804/CMakeLists.txt b/0501-1000/0804-Unique-Morse-Code-Words/cpp-0804/CMakeLists.txt similarity index 100% rename from 0804-Unique-Morse-Code-Words/cpp-0804/CMakeLists.txt rename to 0501-1000/0804-Unique-Morse-Code-Words/cpp-0804/CMakeLists.txt diff --git a/0804-Unique-Morse-Code-Words/cpp-0804/main.cpp b/0501-1000/0804-Unique-Morse-Code-Words/cpp-0804/main.cpp similarity index 100% rename from 0804-Unique-Morse-Code-Words/cpp-0804/main.cpp rename to 0501-1000/0804-Unique-Morse-Code-Words/cpp-0804/main.cpp diff --git a/0501-1000/0805-Split-Array-With-Same-Average/cpp-0805/CMakeLists.txt b/0501-1000/0805-Split-Array-With-Same-Average/cpp-0805/CMakeLists.txt new file mode 100644 index 00000000..1c3e7bb6 --- /dev/null +++ b/0501-1000/0805-Split-Array-With-Same-Average/cpp-0805/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(D) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(D ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0805-Split-Array-With-Same-Average/cpp-0805/main.cpp b/0501-1000/0805-Split-Array-With-Same-Average/cpp-0805/main.cpp new file mode 100644 index 00000000..4c038299 --- /dev/null +++ b/0501-1000/0805-Split-Array-With-Same-Average/cpp-0805/main.cpp @@ -0,0 +1,81 @@ +/// Source : https://leetcode.com/problems/split-array-with-same-average/description/ +/// Author : liuyubobobo +/// Time : 2018-03-24 + +#include +#include +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// +/// Suppose the same average is ave, then ave = sum(A) / len(A) +/// Try how many items B contains from 1 to len(A)/2 +/// Suppose B contains i items, then sum(B) = i * ave +/// This sub-problem can be solved by dynamic programming +/// +/// Time Complexity: O(len(A) * len(A) * sum(A)) +/// Space Complexity: O(len(A) * sum(A)) +class Solution { + +public: + bool splitArraySameAverage(vector& A) { + + int m = A.size(); + int sum = accumulate(A.begin(), A.end(), 0); + + for(int i = 1 ; i <= m/2 ; i ++) + if((sum * i) % m == 0 && ok(A, (sum * i) / m, i)) + return true; + + return false; + } + +private: + bool ok(const vector& A, int c, int num){ + + vector> dp(c + 1, unordered_set()); + dp[0].insert(0); + + for(int a: A) + for(int i = c ; i >= a ; i --) + if(dp[i - a].size() != 0) + if(a == 0) { // dp[i-a] is dp[i] + vector tmp(dp[i].begin(), dp[i].end()); + for(int i = 0 ; i < tmp.size() ; i ++) + tmp[i] ++; + for(int e: tmp) + dp[i].insert(e); + } + else{ + for(int x: dp[i - a]) + dp[i].insert(x + 1); + } + return dp[c].find(num) != dp[c].end(); + } +}; + + +int main() { + + vector A1 = {1,2,3,4,5,6,7,8}; + cout << Solution().splitArraySameAverage(A1) << '\n'; + // true + + vector A2 = {3, 1}; + cout << Solution().splitArraySameAverage(A2) << '\n'; + // false + + vector A3 = {18, 10, 5, 3}; + cout << Solution().splitArraySameAverage(A3) << '\n'; + // false + + vector A4 = {2,0,5,6,16,12,15,12,4}; + cout << Solution().splitArraySameAverage(A4) << '\n'; + // true + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0806-Number-of-Lines-To-Write-String/cpp-0806/CMakeLists.txt b/0501-1000/0806-Number-of-Lines-To-Write-String/cpp-0806/CMakeLists.txt new file mode 100644 index 00000000..b3fafe13 --- /dev/null +++ b/0501-1000/0806-Number-of-Lines-To-Write-String/cpp-0806/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(A) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(A ${SOURCE_FILES}) \ No newline at end of file diff --git a/0806-Number-of-Lines-To-Write-String/cpp-0806/main.cpp b/0501-1000/0806-Number-of-Lines-To-Write-String/cpp-0806/main.cpp similarity index 100% rename from 0806-Number-of-Lines-To-Write-String/cpp-0806/main.cpp rename to 0501-1000/0806-Number-of-Lines-To-Write-String/cpp-0806/main.cpp diff --git a/0501-1000/0807-Max-Increase-to-Keep-City-Skyline/cpp-0807/CMakeLists.txt b/0501-1000/0807-Max-Increase-to-Keep-City-Skyline/cpp-0807/CMakeLists.txt new file mode 100644 index 00000000..85e27b1b --- /dev/null +++ b/0501-1000/0807-Max-Increase-to-Keep-City-Skyline/cpp-0807/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(C) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(C ${SOURCE_FILES}) \ No newline at end of file diff --git a/0807-Max-Increase-to-Keep-City-Skyline/cpp-0807/main.cpp b/0501-1000/0807-Max-Increase-to-Keep-City-Skyline/cpp-0807/main.cpp similarity index 100% rename from 0807-Max-Increase-to-Keep-City-Skyline/cpp-0807/main.cpp rename to 0501-1000/0807-Max-Increase-to-Keep-City-Skyline/cpp-0807/main.cpp diff --git a/0809-Expressive-Words/cpp-0809/CMakeLists.txt b/0501-1000/0809-Expressive-Words/cpp-0809/CMakeLists.txt similarity index 100% rename from 0809-Expressive-Words/cpp-0809/CMakeLists.txt rename to 0501-1000/0809-Expressive-Words/cpp-0809/CMakeLists.txt diff --git a/0809-Expressive-Words/cpp-0809/main.cpp b/0501-1000/0809-Expressive-Words/cpp-0809/main.cpp similarity index 100% rename from 0809-Expressive-Words/cpp-0809/main.cpp rename to 0501-1000/0809-Expressive-Words/cpp-0809/main.cpp diff --git a/0501-1000/0810-Chalkboard-XOR-Game/cpp-0810/CMakeLists.txt b/0501-1000/0810-Chalkboard-XOR-Game/cpp-0810/CMakeLists.txt new file mode 100644 index 00000000..033ac023 --- /dev/null +++ b/0501-1000/0810-Chalkboard-XOR-Game/cpp-0810/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_0810) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0810 main.cpp) \ No newline at end of file diff --git a/0501-1000/0810-Chalkboard-XOR-Game/cpp-0810/main.cpp b/0501-1000/0810-Chalkboard-XOR-Game/cpp-0810/main.cpp new file mode 100644 index 00000000..70a0c644 --- /dev/null +++ b/0501-1000/0810-Chalkboard-XOR-Game/cpp-0810/main.cpp @@ -0,0 +1,30 @@ +/// Source : https://leetcode.com/problems/chalkboard-xor-game/ +/// Author : liuyubobobo +/// Time : 2021-05-21 + +#include +#include + +using namespace std; + + +/// Mathematics +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + bool xorGame(vector& nums) { + + if(nums.size() % 2 == 0) return true; + + int x = 0; + for(int e: nums) x ^= e; + return x == 0; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0811-Subdomain-Visit-Count/cpp-0811/CMakeLists.txt b/0501-1000/0811-Subdomain-Visit-Count/cpp-0811/CMakeLists.txt new file mode 100644 index 00000000..b3fafe13 --- /dev/null +++ b/0501-1000/0811-Subdomain-Visit-Count/cpp-0811/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(A) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(A ${SOURCE_FILES}) \ No newline at end of file diff --git a/0811-Subdomain-Visit-Count/cpp-0811/main.cpp b/0501-1000/0811-Subdomain-Visit-Count/cpp-0811/main.cpp similarity index 100% rename from 0811-Subdomain-Visit-Count/cpp-0811/main.cpp rename to 0501-1000/0811-Subdomain-Visit-Count/cpp-0811/main.cpp diff --git a/0501-1000/0813-Largest-Sum-of-Averages/cpp-0813/CMakeLists.txt b/0501-1000/0813-Largest-Sum-of-Averages/cpp-0813/CMakeLists.txt new file mode 100644 index 00000000..91dd3d6f --- /dev/null +++ b/0501-1000/0813-Largest-Sum-of-Averages/cpp-0813/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_0813) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0813 main.cpp) diff --git a/0501-1000/0813-Largest-Sum-of-Averages/cpp-0813/main.cpp b/0501-1000/0813-Largest-Sum-of-Averages/cpp-0813/main.cpp new file mode 100644 index 00000000..3c239dd1 --- /dev/null +++ b/0501-1000/0813-Largest-Sum-of-Averages/cpp-0813/main.cpp @@ -0,0 +1,51 @@ +/// Source : https://leetcode.com/problems/largest-sum-of-averages/ +/// Author : liuyubobobo +/// Time : 2022-11-27 + +#include +#include + +using namespace std; + + +/// DP +/// Time Compleixty: O(n^2 * k) +/// Space Complexity: O(nk) +class Solution { +public: + double largestSumOfAverages(vector& nums, int k) { + + int n = nums.size(); + vector> dp(k + 1, vector(n, 0.0)); + + int sum = 0; + for(int i = n - 1; i >= 0; i --){ + sum += nums[i]; + dp[1][i] = (double)sum / (n - i); + } + + for(int seg = 2; seg <= k; seg ++){ + for(int l = 0; n - l >= seg; l ++){ + int sum = 0; + for(int r = l; n - r >= seg; r ++){ + sum += nums[r]; + dp[seg][l] = max(dp[seg][l], (double)sum / (r - l + 1) + dp[seg - 1][r + 1]); + } + } + } + + double res = dp[1][0]; + for(int seg = 2; seg <= k; seg ++) res = max(res, dp[seg][0]); + return res; + } +}; + + +int main() { + + vector nums1 = {9,1,2,3,9}; + cout << Solution().largestSumOfAverages(nums1, 3) << '\n'; + // 20 + + return 0; +} diff --git a/0501-1000/0814-Binary-Tree-Pruning/CMakeLists.txt b/0501-1000/0814-Binary-Tree-Pruning/CMakeLists.txt new file mode 100644 index 00000000..c30005eb --- /dev/null +++ b/0501-1000/0814-Binary-Tree-Pruning/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(0814_Binary_Tree_Pruning) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(0814_Binary_Tree_Pruning main.cpp) \ No newline at end of file diff --git a/0501-1000/0814-Binary-Tree-Pruning/main.cpp b/0501-1000/0814-Binary-Tree-Pruning/main.cpp new file mode 100644 index 00000000..dbdcad84 --- /dev/null +++ b/0501-1000/0814-Binary-Tree-Pruning/main.cpp @@ -0,0 +1,56 @@ +/// Source : https://cses.fi/problemset/task/1666/ +/// Author : liuyubobobo +/// Time : 2021-07-12 + +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(h) + +/// 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* pruneTree(TreeNode* root) { + + bool contain_one; + return pruneTree(root, contain_one); + } + +private: + TreeNode* pruneTree(TreeNode* root, bool& contain_one){ + + if(root == NULL){ + contain_one = false; + return NULL; + } + + bool left_contain_one = true; + root->left = pruneTree(root->left, left_contain_one); + + bool right_contain_one = true; + root->right = pruneTree(root->right, right_contain_one); + + contain_one = (root->val == 1 || left_contain_one || right_contain_one); + if(contain_one) + return root; + return NULL; + } +}; + +int main() { + + return 0; +} diff --git a/0501-1000/0815-Bus-Routes/cpp-0815/CMakeLists.txt b/0501-1000/0815-Bus-Routes/cpp-0815/CMakeLists.txt new file mode 100644 index 00000000..66671e52 --- /dev/null +++ b/0501-1000/0815-Bus-Routes/cpp-0815/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_0815) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0815 main.cpp) \ No newline at end of file diff --git a/0501-1000/0815-Bus-Routes/cpp-0815/main.cpp b/0501-1000/0815-Bus-Routes/cpp-0815/main.cpp new file mode 100644 index 00000000..7e60121a --- /dev/null +++ b/0501-1000/0815-Bus-Routes/cpp-0815/main.cpp @@ -0,0 +1,76 @@ +/// Source : https://leetcode.com/problems/bus-routes/ +/// Author : liuyubobobo +/// Time : 2021-06-27 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// BFS +/// Time Complexity: O(V + E) +/// Space Complexity: O(V + E) +class Solution { +public: + int numBusesToDestination(vector>& routes, int source, int target) { + + if(source == target) return 0; + + int n = routes.size(); + + unordered_map> stop2route; + for(int route = 0; route < n; route ++) + for(int stop : routes[route]) + stop2route[stop].insert(route); + + vector> g(n); + for(int r1 = 0; r1 < n; r1 ++) + for(int stop: routes[r1]) + for(int r2: stop2route[stop]) + if(r1 != r2) + g[r1].insert(r2), g[r2].insert(r1); + + queue q; + vector visited(n, -1); + for(int route: stop2route[source]){ + q.push(route); + visited[route] = 1; + } + + while(!q.empty()){ + int cur = q.front(); + q.pop(); + + if(stop2route[target].count(cur)) return visited[cur]; + + for(int next: g[cur]) + if(visited[next] == -1){ + q.push(next); + visited[next] = visited[cur] + 1; + } + } + return -1; + } +}; + + +int main() { + + vector> route1 = {{1, 2, 7}, {3, 6, 7}}; + cout << Solution().numBusesToDestination(route1, 1, 6) << endl; + // 2 + + vector> route2 = {{7, 12}, {4, 5, 15}, {6}, {15, 19}, {9, 12, 13}}; + cout << Solution().numBusesToDestination(route2, 15, 12) << endl; + // -1 + + vector> route3 = {{1, 7}, {3, 5}}; + cout << Solution().numBusesToDestination(route3, 5, 5) << endl; + // 0 + + return 0; +} diff --git a/0501-1000/0817-Linked-List-Components/cpp-0817/CMakeLists.txt b/0501-1000/0817-Linked-List-Components/cpp-0817/CMakeLists.txt new file mode 100644 index 00000000..ae89e070 --- /dev/null +++ b/0501-1000/0817-Linked-List-Components/cpp-0817/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(B) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(B ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0817-Linked-List-Components/cpp-0817/main.cpp b/0501-1000/0817-Linked-List-Components/cpp-0817/main.cpp new file mode 100644 index 00000000..5b84f911 --- /dev/null +++ b/0501-1000/0817-Linked-List-Components/cpp-0817/main.cpp @@ -0,0 +1,82 @@ +/// Source : https://leetcode.com/problems/linked-list-components/description/ +/// Author : liuyubobobo +/// Time : 2018-04-14 + +#include +#include +#include + +using namespace std; + +// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} +}; + +ListNode* createLinkedList(int arr[], int n){ + + if(n == 0) + return NULL; + + ListNode* head = new ListNode(arr[0]); + ListNode* curNode = head; + for(int i = 1 ; i < n ; i ++){ + curNode->next = new ListNode(arr[i]); + curNode = curNode->next; + } + + return head; +} + +void printLinkedList(ListNode* head){ + + ListNode* curNode = head; + while(curNode != NULL){ + cout << curNode->val << " -> "; + curNode = curNode->next; + } + + cout << "NULL" << endl; + + return; +} + +/// Grouping +/// Time Complexity: O(len(head) + len(g)) +/// Space Complexity: O(len(g)) +class Solution { +public: + int numComponents(ListNode* head, vector& G) { + + unordered_set gSet; + for(int num: G) + gSet.insert(num); + + int res = 0, cur = 0; + ListNode *curNode = head; + while(curNode != NULL){ + if(gSet.find(curNode->val) != gSet.end()){ + if(cur == 0) + res ++; + cur ++; + } + else + cur = 0; + + curNode = curNode->next; + } + return res; + } +}; + +int main() { + + int list1[4] = {0, 1, 2, 3}; + ListNode* head1 = createLinkedList(list1, 4); + vector G1 = {0, 1, 3}; + cout << Solution().numComponents(head1, G1) << endl; + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0819-Most-Common-Word/cpp-0819/CMakeLists.txt b/0501-1000/0819-Most-Common-Word/cpp-0819/CMakeLists.txt new file mode 100644 index 00000000..b3fafe13 --- /dev/null +++ b/0501-1000/0819-Most-Common-Word/cpp-0819/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(A) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(A ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0819-Most-Common-Word/cpp-0819/main.cpp b/0501-1000/0819-Most-Common-Word/cpp-0819/main.cpp new file mode 100644 index 00000000..7958b05d --- /dev/null +++ b/0501-1000/0819-Most-Common-Word/cpp-0819/main.cpp @@ -0,0 +1,67 @@ +/// Source : https://leetcode.com/problems/most-common-word/description/ +/// Author : liuyubobobo +/// Time : 2018-04-14 + +#include +#include +#include +#include +#include + +using namespace std; + +/// Counting +/// +/// Time Complexity: O(len(paragraph) + len(banned)) +/// Space Complexity: O(len(banned)) +class Solution { +public: + string mostCommonWord(string paragraph, vector& banned) { + + transform(paragraph.begin(), paragraph.end(), paragraph.begin(), ::tolower); + unordered_set banned_set; + for(const string& word: banned) + banned_set.insert(word); + + unordered_map freq; + int start = firstLetter(paragraph, 0); + for(int i = start + 1 ; i <= paragraph.size() ;){ + if(i == paragraph.size() || !islower(paragraph[i])){ + string word = paragraph.substr(start, i - start); + if(banned_set.find(word) == banned_set.end()) + freq[word] += 1; + start = firstLetter(paragraph, i + 1); + i = start + 1; + } + else + i ++; + } + + int max_freq = 0; + string res = ""; + for(const pair& p: freq) + if(p.second > max_freq){ + res = p.first; + max_freq = p.second; + } + return res; + } + +private: + int firstLetter(const string& s, int start){ + + for(int i = start ; i < s.size() ; i ++) + if(islower(s[i])) + return i; + return s.size(); + } +}; + +int main() { + + string paragraph = "Bob hit a ball, the hit BALL flew far after it was hit."; + vector banned = {"hit"}; + cout << Solution().mostCommonWord(paragraph, banned) << endl; + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0822-Card-Flipping-Game/cpp-0822/CMakeLists.txt b/0501-1000/0822-Card-Flipping-Game/cpp-0822/CMakeLists.txt new file mode 100644 index 00000000..9df7dd2d --- /dev/null +++ b/0501-1000/0822-Card-Flipping-Game/cpp-0822/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.26) +project(cpp_0822) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_0822 main.cpp) diff --git a/0501-1000/0822-Card-Flipping-Game/cpp-0822/main.cpp b/0501-1000/0822-Card-Flipping-Game/cpp-0822/main.cpp new file mode 100644 index 00000000..e0a44312 --- /dev/null +++ b/0501-1000/0822-Card-Flipping-Game/cpp-0822/main.cpp @@ -0,0 +1,44 @@ +/// Source : https://leetcode.com/problems/card-flipping-game/description/ +/// Author : liuyubobobo +/// Time : 2023-08-01 + +#include +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n^2) +/// Space Complexity: O(1) +class Solution { +public: + int flipgame(vector& fronts, vector& backs) { + + int n = fronts.size(), res = INT_MAX; + for(int i = 0; i < n; i ++){ + int x = fronts[i], y = backs[i]; + if(x == y) continue; + if(x < res && ok(x, n, fronts, backs, i)) res = min(res, x); + if(y < res && ok(y, n, fronts, backs, i)) res = min(res, y); + } + return res == INT_MAX ? 0 : res; + } + +private: + bool ok(int x, int n, const vector& fronts, const vector& backs, + int del_idx){ + + for(int i = 0; i < fronts.size(); i ++) + if(i != del_idx && fronts[i] == x && backs[i] == x) + return false; + return true; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0823-Binary-Trees-With-Factors/cpp-0823/CMakeLists.txt b/0501-1000/0823-Binary-Trees-With-Factors/cpp-0823/CMakeLists.txt new file mode 100644 index 00000000..1c81e0c4 --- /dev/null +++ b/0501-1000/0823-Binary-Trees-With-Factors/cpp-0823/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0823) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0823 main.cpp) \ No newline at end of file diff --git a/0501-1000/0823-Binary-Trees-With-Factors/cpp-0823/main.cpp b/0501-1000/0823-Binary-Trees-With-Factors/cpp-0823/main.cpp new file mode 100644 index 00000000..a7b9cde2 --- /dev/null +++ b/0501-1000/0823-Binary-Trees-With-Factors/cpp-0823/main.cpp @@ -0,0 +1,59 @@ +/// Source : https://leetcode.com/problems/binary-trees-with-factors/ +/// Author : liuyubobobo +/// Time : 2021-01-16 + +#include +#include +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { +public: + int numFactoredBinaryTrees(vector& A) { + + const long long MOD = 1e9 + 7; + + sort(A.begin(), A.end()); + unordered_map map; + for(int i = 0; i < A.size(); i ++) map[A[i]] = i; + + vector dp(A.size(), 1); + for(int i = 1; i < A.size(); i ++){ + long long res = 1ll; + for(int j = 0; j < i; j ++) + if(A[i] % A[j] == 0 && map.count(A[i] / A[j])) + res = (res + (long long)dp[j] * dp[map[A[i] / A[j]]]) % MOD; + dp[i] = res; + } + + return accumulate(dp.begin(), dp.end(), 0ll) % MOD; + } +}; + + +int main() { + + vector arr1 = {2, 4}; + cout << Solution().numFactoredBinaryTrees(arr1) << endl; + // 3 + + vector arr2 = {2, 4, 5, 10}; + cout << Solution().numFactoredBinaryTrees(arr2) << endl; + // 7 + + vector arr3 = {15, 13, 22, 7, 11}; + cout << Solution().numFactoredBinaryTrees(arr3) << endl; + // 5 + + vector arr4 = {2, 3, 6, 18}; + cout << Solution().numFactoredBinaryTrees(arr4) << endl; + // 12 + + return 0; +} diff --git a/0501-1000/0824-Goat-Latin/cpp-0824/CMakeLists.txt b/0501-1000/0824-Goat-Latin/cpp-0824/CMakeLists.txt new file mode 100644 index 00000000..2afd100a --- /dev/null +++ b/0501-1000/0824-Goat-Latin/cpp-0824/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_0824) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0824 main.cpp) diff --git a/0501-1000/0824-Goat-Latin/cpp-0824/main.cpp b/0501-1000/0824-Goat-Latin/cpp-0824/main.cpp new file mode 100644 index 00000000..5094a988 --- /dev/null +++ b/0501-1000/0824-Goat-Latin/cpp-0824/main.cpp @@ -0,0 +1,48 @@ +/// Source : https://leetcode.com/problems/goat-latin/ +/// Author : liuyubobobo +/// Time : 2022-04-20 + +#include +#include +#include + +using namespace std; + + +/// Simulation +/// Time Compelxity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + string toGoatLatin(string sentence) { + + vector v; + for(int start = 0, i = 1; i <= sentence.size(); i ++) + if(i == sentence.size() || sentence[i] == ' '){ + v.push_back(sentence.substr(start, i - start)); + start = i + 1; + i = start; + } + + set vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}; + + string res = ""; + for(int i = 0; i < v.size(); i ++){ + if(vowels.count(v[i][0])) + res += v[i] + "ma"; + else + res += v[i].substr(1) + v[i][0] + "ma"; + + res += string(i + 1, 'a'); + res += ' '; + } + res.pop_back(); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0825-Friends-Of-Appropriate-Ages/cpp-0825/CMakeLists.txt b/0501-1000/0825-Friends-Of-Appropriate-Ages/cpp-0825/CMakeLists.txt new file mode 100644 index 00000000..c612dd24 --- /dev/null +++ b/0501-1000/0825-Friends-Of-Appropriate-Ages/cpp-0825/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0825) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0825 main.cpp) diff --git a/0501-1000/0825-Friends-Of-Appropriate-Ages/cpp-0825/main.cpp b/0501-1000/0825-Friends-Of-Appropriate-Ages/cpp-0825/main.cpp new file mode 100644 index 00000000..3012585b --- /dev/null +++ b/0501-1000/0825-Friends-Of-Appropriate-Ages/cpp-0825/main.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/friends-of-appropriate-ages/ +/// Author : liuyubobobo +/// Time : 2021-12-26 + +#include +#include + +using namespace std; + + +/// Presum +/// Time Complexity: O(n + max_age) +/// Space Complexity: O(max_age) +class Solution { +public: + int numFriendRequests(vector& ages) { + + vector presum(121, 0); + for(int age: ages) presum[age] ++; + for(int i = 1; i <= 120; i ++) presum[i] += presum[i - 1]; + + int res = 0; + for(int age = 1; age <= 120; age ++){ + int l = age / 2 + 7 + 1, r = age; + if(age < 100) r = min(100, r); + if(l > r) continue; + + int t = presum[r] - presum[l - 1]; + if(l <= age && age <= r) t --; + res += (presum[age] - presum[age - 1]) * t; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0827-Making-A-Large-Island/cpp-0827/CMakeLists.txt b/0501-1000/0827-Making-A-Large-Island/cpp-0827/CMakeLists.txt new file mode 100644 index 00000000..876a7216 --- /dev/null +++ b/0501-1000/0827-Making-A-Large-Island/cpp-0827/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(cpp_0827) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0827 main.cpp) \ No newline at end of file diff --git a/0501-1000/0827-Making-A-Large-Island/cpp-0827/main.cpp b/0501-1000/0827-Making-A-Large-Island/cpp-0827/main.cpp new file mode 100644 index 00000000..10e249d9 --- /dev/null +++ b/0501-1000/0827-Making-A-Large-Island/cpp-0827/main.cpp @@ -0,0 +1,84 @@ +/// Source : https://leetcode.com/problems/two-sum/description/ +/// Author : liuyubobobo +/// Time : 2017-11-15 + +#include +#include +#include + +using namespace std; + + +/// DFS + HashMap +/// Time Complexity: O(n * m) +/// Space Complexity: O(n * m) +class Solution { + +private: + int dirs[4][2] = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}}; + int n, m; + +public: + int largestIsland(vector>& grid) { + + n = grid.size(), m = grid[0].size(); + vector sz = {0, 0}; + for(int i = 0; i < n; i ++) + for(int j = 0; j < m; j ++) + if(grid[i][j] == 1) + sz.push_back(dfs(grid, i, j, sz.size())); + +// cout << "sz : "; for(int e: sz) cout << e << " "; cout << endl; +// cout << "grrid : " << endl; +// for(int i = 0; i < grid.size(); i ++){ +// for(int e: grid[i]) cout << e << " "; cout << endl; +// } + + int res = 0; + for(int x = 0; x < n; x ++) + for(int y = 0; y < m; y ++) + if(grid[x][y] == 0){ + int tres = 1; + unordered_set set; + for(int d = 0; d < 4; d ++){ + int nextx = x + dirs[d][0], nexty = y + dirs[d][1]; + if(in_area(nextx, nexty) && !set.count(grid[nextx][nexty])) + tres += sz[grid[nextx][nexty]], + set.insert(grid[nextx][nexty]); + } + res = max(res, tres); + } + return res == 0 ? *max_element(sz.begin(), sz.end()) : res; + } + +private: + int dfs(vector>& grid, int x, int y, int ccid){ + + grid[x][y] = ccid; + int res = 1; + for(int d = 0; d < 4; d ++){ + int nextx = x + dirs[d][0], nexty = y + dirs[d][1]; + if(in_area(nextx, nexty) && grid[nextx][nexty] == 1) + res += dfs(grid, nextx, nexty, ccid); + } + return res; + } + + bool in_area(int x, int y){ + return x >= 0 && x < n && y >= 0 && y < m; + } +}; + + +int main() { + + vector> grid1 = {{1, 0}, {0, 1}}; + cout << Solution().largestIsland(grid1) << endl; + // 3 + + vector> grid2 = {{1, 1}, {1, 0}}; + cout << Solution().largestIsland(grid2) << endl; + // 4 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0828-Count-Unique-Characters-of-All-Substrings-of-a-Given-String/cpp-0828/CMakeLists.txt b/0501-1000/0828-Count-Unique-Characters-of-All-Substrings-of-a-Given-String/cpp-0828/CMakeLists.txt new file mode 100644 index 00000000..946dcfd2 --- /dev/null +++ b/0501-1000/0828-Count-Unique-Characters-of-All-Substrings-of-a-Given-String/cpp-0828/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_0828) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0828 main.cpp) diff --git a/0501-1000/0828-Count-Unique-Characters-of-All-Substrings-of-a-Given-String/cpp-0828/main.cpp b/0501-1000/0828-Count-Unique-Characters-of-All-Substrings-of-a-Given-String/cpp-0828/main.cpp new file mode 100644 index 00000000..81df2c5b --- /dev/null +++ b/0501-1000/0828-Count-Unique-Characters-of-All-Substrings-of-a-Given-String/cpp-0828/main.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/count-unique-characters-of-all-substrings-of-a-given-string/ +/// Author : liuyubobobo +/// Time : 2022-09-05 + +#include +#include +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(n) +/// Space Compelxity: O(n) +class Solution { +public: + int uniqueLetterString(string s) { + + vector> pos(26); + for(int i = 0; i < s.size(); i ++) + pos[s[i] - 'A'].push_back(i); + + vector indexes(26, 0); + + int res = 0; + for(int start = 0; start < s.size(); start ++){ + for(int c = 0; c < 26; c ++){ + int a = indexes[c]; + if(a >= pos[c].size()) continue; + + if(a + 1 >= pos[c].size()) res += (s.size() - pos[c][a]); + else res += pos[c][a + 1] - pos[c][a]; + + if(pos[c][a] == start) indexes[c] ++; + } + } + return res; + } +}; + +int main() { + + cout << Solution().uniqueLetterString("ABC") << '\n'; + // 10 + + cout << Solution().uniqueLetterString("ABA") << '\n'; + // 8 + + cout << Solution().uniqueLetterString("LEETCODE") << '\n'; + // 92 + + return 0; +} diff --git a/0501-1000/0829-Consecutive-Numbers-Sum/cpp-0829/CMakeLists.txt b/0501-1000/0829-Consecutive-Numbers-Sum/cpp-0829/CMakeLists.txt new file mode 100644 index 00000000..b2b892e3 --- /dev/null +++ b/0501-1000/0829-Consecutive-Numbers-Sum/cpp-0829/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_0829) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0829 main.cpp) diff --git a/0501-1000/0829-Consecutive-Numbers-Sum/cpp-0829/main.cpp b/0501-1000/0829-Consecutive-Numbers-Sum/cpp-0829/main.cpp new file mode 100644 index 00000000..ad78bb31 --- /dev/null +++ b/0501-1000/0829-Consecutive-Numbers-Sum/cpp-0829/main.cpp @@ -0,0 +1,49 @@ +/// Source : https://leetcode.com/problems/consecutive-numbers-sum/ +/// Author : liuyubobobo +/// Time : 2022-06-02 + +#include + +using namespace std; + + +/// Math +/// Time Complexity: O(sqrt(2 * n)) +/// Space Complexity: O(1) +class Solution { +public: + int consecutiveNumbersSum(int n) { + + int A = 2 * n, res = 0; + for(int i = 1; i * i <= A; i ++) + if(A % i == 0){ + int x = i, y = - A / i; + res += ok(x, y); + + x = -i, y = A / i; + res += ok(x, y); + } + return res; + } + +private: + bool ok(int x, int y){ + int t = x + y + 1; + return t > 0 && t % 2 == 0; + } +}; + + +int main() { + + cout << Solution().consecutiveNumbersSum(5) << '\n'; + // 2 + + cout << Solution().consecutiveNumbersSum(9) << '\n'; + // 3 + + cout << Solution().consecutiveNumbersSum(15) << '\n'; + // 4 + + return 0; +} diff --git a/0501-1000/0830-Positions-of-Large-Groups/cpp-0830/CMakeLists.txt b/0501-1000/0830-Positions-of-Large-Groups/cpp-0830/CMakeLists.txt new file mode 100644 index 00000000..497352db --- /dev/null +++ b/0501-1000/0830-Positions-of-Large-Groups/cpp-0830/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0830) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0830 main.cpp) \ No newline at end of file diff --git a/0501-1000/0830-Positions-of-Large-Groups/cpp-0830/main.cpp b/0501-1000/0830-Positions-of-Large-Groups/cpp-0830/main.cpp new file mode 100644 index 00000000..e7839f51 --- /dev/null +++ b/0501-1000/0830-Positions-of-Large-Groups/cpp-0830/main.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/positions-of-large-groups/ +/// Author : liuyubobobo +/// Time : 2020-01-04 + +#include +#include + +using namespace std; + + +/// Split +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + vector> largeGroupPositions(string s) { + + vector> res; + for(int start = 0, i = start + 1; i <= s.size(); i ++) + if(i == s.size() || s[i] != s[start]){ + + if(i - start >= 3) res.push_back({start, i - 1}); + start = i; + i = start; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0831-Masking-Personal-Information/cpp-0831/CMakeLists.txt b/0501-1000/0831-Masking-Personal-Information/cpp-0831/CMakeLists.txt new file mode 100644 index 00000000..faae20b0 --- /dev/null +++ b/0501-1000/0831-Masking-Personal-Information/cpp-0831/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_0831) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_0831 main.cpp) diff --git a/0501-1000/0831-Masking-Personal-Information/cpp-0831/main.cpp b/0501-1000/0831-Masking-Personal-Information/cpp-0831/main.cpp new file mode 100644 index 00000000..cb3af39b --- /dev/null +++ b/0501-1000/0831-Masking-Personal-Information/cpp-0831/main.cpp @@ -0,0 +1,48 @@ +/// Source : https://leetcode.com/problems/masking-personal-information/ +/// Author : liuyubobobo +/// Time : 2023-03-31 + +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(|s|) +/// Space Complexity: O(|s|) +class Solution { +public: + string maskPII(string s) { + + if(s.find('@') != string::npos) return solve_email(s); + return solve_phone(s); + } + +private: + string solve_phone(string& s){ + + string number; + for(char c: s) if(isdigit(c)) number += c; + + int n = number.size(); + + if(n == 10) return "***-***-" + number.substr(n - 4); + return "+" + string(n - 10, '*') + "-***-***-" + number.substr(n - 4); + } + + string solve_email(string& s){ + + for(char& c: s) if(isupper(c)) c = tolower(c); + + int pos = s.find('@'); + string name = s.substr(0, pos), domain = s.substr(pos + 1); + + return string(1, name[0]) + "*****" + string(1, name.back()) + "@" + domain; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0832-Flipping-an-Image/cpp-0832/CMakeLists.txt b/0501-1000/0832-Flipping-an-Image/cpp-0832/CMakeLists.txt new file mode 100644 index 00000000..f8249e61 --- /dev/null +++ b/0501-1000/0832-Flipping-an-Image/cpp-0832/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0832) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0832 main.cpp) \ No newline at end of file diff --git a/0501-1000/0832-Flipping-an-Image/cpp-0832/main.cpp b/0501-1000/0832-Flipping-an-Image/cpp-0832/main.cpp new file mode 100644 index 00000000..fe52da94 --- /dev/null +++ b/0501-1000/0832-Flipping-an-Image/cpp-0832/main.cpp @@ -0,0 +1,39 @@ +/// Source : https://leetcode.com/problems/flipping-an-image/ +/// Author : liuyubobobo +/// Time : 2021-02-23 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(R * C) +/// Space Complexity: O(1) +class Solution { +public: + vector> flipAndInvertImage(vector>& A) { + + int R = A.size(); + if(R == 0) return A; + + int C = A[0].size(); + if(C == 0) return A; + + for(int i = 0; i < R; i ++){ + + int l = 0, r = C - 1; + while(l < r) swap(A[i][l ++], A[i][r --]); + + for(int& e: A[i]) e = !e; + } + return A; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0833-Find-And-Replace-in-String/cpp-0833/CMakeLists.txt b/0501-1000/0833-Find-And-Replace-in-String/cpp-0833/CMakeLists.txt new file mode 100644 index 00000000..331f9989 --- /dev/null +++ b/0501-1000/0833-Find-And-Replace-in-String/cpp-0833/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_0833) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_0833 main.cpp) diff --git a/0501-1000/0833-Find-And-Replace-in-String/cpp-0833/main.cpp b/0501-1000/0833-Find-And-Replace-in-String/cpp-0833/main.cpp new file mode 100644 index 00000000..96bf96a6 --- /dev/null +++ b/0501-1000/0833-Find-And-Replace-in-String/cpp-0833/main.cpp @@ -0,0 +1,39 @@ +/// Source : https://leetcode.com/problems/find-and-replace-in-string/ +/// Author : liuyubobobo +/// Time : 2023-08-14 + +#include +#include +#include +#include + +using namespace std; + + +class Solution { +public: + string findReplaceString(string s, vector& indices, vector& sources, vector& targets) { + + int n = indices.size(); + vector> v(n); + for(int i = 0; i < n; i ++) v[i] = make_tuple(indices[i], sources[i], targets[i]); + sort(v.begin(), v.end()); + + int offset = 0; + for(int i = 0; i < n; i ++){ + int index = get<0>(v[i]); + string a = get<1>(v[i]), b = get<2>(v[i]); + if(s.find(a, index + offset) == index + offset){ + s.replace(index + offset, a.size(), b); + offset += b.size() - a.size(); + } + } + return s; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0834-Sum-of-Distances-in-Tree/cpp-0834/CMakeLists.txt b/0501-1000/0834-Sum-of-Distances-in-Tree/cpp-0834/CMakeLists.txt new file mode 100644 index 00000000..24230b6d --- /dev/null +++ b/0501-1000/0834-Sum-of-Distances-in-Tree/cpp-0834/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0834) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0834 main.cpp) diff --git a/0501-1000/0834-Sum-of-Distances-in-Tree/cpp-0834/main.cpp b/0501-1000/0834-Sum-of-Distances-in-Tree/cpp-0834/main.cpp new file mode 100644 index 00000000..4f99932f --- /dev/null +++ b/0501-1000/0834-Sum-of-Distances-in-Tree/cpp-0834/main.cpp @@ -0,0 +1,91 @@ +/// Source : https://leetcode.com/problems/sum-of-distances-in-tree/ +/// Author : liuyubobobo +/// Time : 2021-09-05 + +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector sumOfDistancesInTree(int n, vector>& edges) { + + vector> tree(n); + for(const vector& e: edges) + tree[e[0]].push_back(e[1]), tree[e[1]].push_back(e[0]); + + vector subnodes(n, 0); + dfs_subnodes(tree, 0, -1, subnodes); + + vector subnodes_dis(n, 0); + dfs_subnodes_dis(tree, 0, -1, subnodes, subnodes_dis); + + vector ret(n, 0); + dfs_res(n, tree, 0, -1, subnodes, subnodes_dis, ret); + return ret; + } + +private: + void dfs_res(int n, const vector>& tree, int u, int p, + const vector& subnodes, const vector& subnodes_dis, + vector& ret){ + + if(p == -1){ + ret[u] = subnodes_dis[u]; + for(int v: tree[u]) dfs_res(n, tree, v, u, subnodes, subnodes_dis, ret); + return; + } + + ret[u] = subnodes_dis[u] + ret[p] - (subnodes_dis[u] + subnodes[u]) + n - subnodes[u]; + for(int v: tree[u]) + if(v != p) + dfs_res(n, tree, v, u, subnodes, subnodes_dis, ret); + return; + } + + int dfs_subnodes_dis(const vector>& tree, int u, int p, + const vector& subnodes, vector& subnodes_dis){ + + int res = 0; + for(int v: tree[u]) + if(v != p){ + res += dfs_subnodes_dis(tree, v, u, subnodes, subnodes_dis) + subnodes[v]; + } + subnodes_dis[u] = res; + return res; + } + + int dfs_subnodes(const vector>& tree, int u, int p, vector& subnodes){ + + int res = 1; + for(int v: tree[u]) + if(v != p){ + res += dfs_subnodes(tree, v, u, subnodes); + } + subnodes[u] = res; + return res; + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << ' '; cout << endl; +} + +int main() { + + vector> edges1 = {{0, 1}, {0, 2}, {2, 3}, {2, 4}, {2, 5}}; + print_vec(Solution().sumOfDistancesInTree(6, edges1)); + // 8 12 6 10 10 10 + + vector> edges2 = {}; + print_vec(Solution().sumOfDistancesInTree(1, edges2)); + // 0 + + return 0; +} diff --git a/0501-1000/0835-Image-Overlap/cpp-0835/CMakeLists.txt b/0501-1000/0835-Image-Overlap/cpp-0835/CMakeLists.txt new file mode 100644 index 00000000..93467fbd --- /dev/null +++ b/0501-1000/0835-Image-Overlap/cpp-0835/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_0835) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0835 main.cpp) diff --git a/0501-1000/0835-Image-Overlap/cpp-0835/main.cpp b/0501-1000/0835-Image-Overlap/cpp-0835/main.cpp new file mode 100644 index 00000000..c35d61d0 --- /dev/null +++ b/0501-1000/0835-Image-Overlap/cpp-0835/main.cpp @@ -0,0 +1,48 @@ +/// Source : https://leetcode.com/problems/image-overlap/ +/// Author : liuyubobobo +/// Time : 2022-10-26 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n^4) +/// Space Complexity: O(n^2) +class Solution { +public: + int largestOverlap(vector>& img1, vector>& img2) { + + int n = img1.size(); + int m = n * 3; + + vector> back(m, vector(m, 0)); + for(int i = 0; i < n; i ++) + for(int j = 0; j < n; j ++) back[i + n][j + n] = img1[i][j]; + + int res = 0; + for(int i = 0; i + n <= m; i ++) + for(int j = 0; j + n <= m; j ++) + res = max(res, match(back, i, j, img2, n)); + return res; + } + +private: + int match(const vector>& back, int sx, int sy, + const vector>& img, int n){ + + int res = 0; + for(int i = 0; i < n; i ++) + for(int j = 0; j < n; j ++) + res += (img[i][j] && back[i + sx][j + sy]); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0837-New-21-Game/cpp-0837/CMakeLists.txt b/0501-1000/0837-New-21-Game/cpp-0837/CMakeLists.txt new file mode 100644 index 00000000..c98a11cf --- /dev/null +++ b/0501-1000/0837-New-21-Game/cpp-0837/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_0837) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_0837 main.cpp) diff --git a/0501-1000/0837-New-21-Game/cpp-0837/main.cpp b/0501-1000/0837-New-21-Game/cpp-0837/main.cpp new file mode 100644 index 00000000..1ab2bd11 --- /dev/null +++ b/0501-1000/0837-New-21-Game/cpp-0837/main.cpp @@ -0,0 +1,43 @@ +/// Source : https://leetcode.com/problems/new-21-game/description/ +/// Author : liuyubobobo +/// Time : 2023-05-25 + +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(k + maxPts) +/// Space Complexity: O(k + maxPts) +class Solution { +public: + double new21Game(int n, int k, int maxPts) { + + if(k == 0) return 1.0; + + vector p(k + maxPts, 0), presum(k + maxPts + 1, 0); + p[0] = 1.0; + presum[1] = 1.0; + for(int i = 1; i < p.size(); i ++){ + int r = min(i - 1, k - 1), l = max(i - maxPts, 0); + long double sum = presum[r + 1] - presum[l]; + p[i] = sum / maxPts; + presum[i + 1] = presum[i] + p[i]; + } + + long double res = 0.0; + for(int i = k; i <= n && i < p.size(); i ++) res += p[i]; + return res; + } +}; + + +int main() { + + cout << Solution().new21Game(10, 1, 10) << '\n'; + // 1.0 + + return 0; +} diff --git a/0501-1000/0838-Push-Dominoes/cpp-0838/CMakeLists.txt b/0501-1000/0838-Push-Dominoes/cpp-0838/CMakeLists.txt new file mode 100644 index 00000000..8d6c6e4d --- /dev/null +++ b/0501-1000/0838-Push-Dominoes/cpp-0838/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_0838) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0838 main.cpp) \ No newline at end of file diff --git a/0501-1000/0838-Push-Dominoes/cpp-0838/main.cpp b/0501-1000/0838-Push-Dominoes/cpp-0838/main.cpp new file mode 100644 index 00000000..e4840c78 --- /dev/null +++ b/0501-1000/0838-Push-Dominoes/cpp-0838/main.cpp @@ -0,0 +1,70 @@ +/// Source : https://leetcode.com/problems/push-dominoes/ +/// Author : liuyubobobo +/// Time : 2021-07-21 + +#include +#include + +using namespace std; + + +/// String split +/// Time Complexity: O(n) +/// Space Complexity O(1) +class Solution { +public: + string pushDominoes(string dominoes) { + + int n = dominoes.size(); + for(int start = -1, i = 0; i <= n; i ++){ + if(i == n || dominoes[i] != '.'){ + if(start != -1) { + process(dominoes, start, i - 1); + start = -1; + } + } + else if(start == -1) start = i; + } + return dominoes; + } + +private: + void process(string& s, int l, int r){ + + if(l == 0){ + if(r + 1 < s.size() && s[r + 1] == 'L') + for(int i = l; i <= r; i ++) s[i] = 'L'; + return; + } + + if(r == (int)s.size() - 1){ + if(l - 1 >= 0 && s[l - 1] == 'R') + for(int i = l; i <= r; i ++) s[i] = 'R'; + return; + } + + if(s[l - 1] == s[r + 1]) + for(int i = l; i <= r; i ++) s[i] = s[l - 1]; + else if(s[l - 1] == 'R' && s[r + 1] == 'L'){ + int d = (r - l + 1) / 2; + for(int i = l; i < l + d; i ++) s[i] = 'R'; + for(int i = r; i > r - d; i --) s[i] = 'L'; + } + return; + } +}; + + +int main() { + + cout << Solution().pushDominoes("RR.L") << endl; + // RR.L + + cout << Solution().pushDominoes(".L.R...LR..L..") << endl; + // LL.RR.LLRRLL.. + + cout << Solution().pushDominoes("R.R.L") << endl; + // RRR.L + + return 0; +} diff --git a/0501-1000/0839-Similar-String-Groups/cpp-0839/CMakeLists.txt b/0501-1000/0839-Similar-String-Groups/cpp-0839/CMakeLists.txt new file mode 100644 index 00000000..141f5082 --- /dev/null +++ b/0501-1000/0839-Similar-String-Groups/cpp-0839/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0839) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0839 main2.cpp) \ No newline at end of file diff --git a/0501-1000/0839-Similar-String-Groups/cpp-0839/main.cpp b/0501-1000/0839-Similar-String-Groups/cpp-0839/main.cpp new file mode 100644 index 00000000..f7d3a65f --- /dev/null +++ b/0501-1000/0839-Similar-String-Groups/cpp-0839/main.cpp @@ -0,0 +1,65 @@ +/// Source : https://leetcode.com/problems/similar-string-groups/solution/ +/// Author : liuyubobobo +/// Time : 2021-01-30 + +#include +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n^2 * |str|) +/// Space Complexity: O(n^2) +class Solution { +public: + int numSimilarGroups(vector& strs) { + + int n = strs.size(); + vector> g(n); + for(int i = 0; i < n; i ++) + for(int j = i + 1; j < n; j ++) + if(similar(strs[i], strs[j])) + g[i].insert(j), g[j].insert(i); + + vector visited(n, false); + int res = 0; + for(int i = 0; i < n; i ++) + if(!visited[i]){ + res ++; + dfs(g, i, visited); + } + return res; + } + +private: + void dfs(const vector>& g, int u, vector& visited){ + + visited[u] = true; + for(int v: g.at(u)) + if(!visited[v]) + dfs(g, v, visited); + } + + bool similar(string& a, string& b){ + + if(a == b) return true; + + int i = -1, j = -1; + for(int k = 0; k < a.size(); k ++) + if(a[k] != b[k]){ + if(i == -1) i = k; + else if(j == -1) j = k; + else return false; + } + + return a[i] == b[j] && a[j] == b[i]; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0839-Similar-String-Groups/cpp-0839/main2.cpp b/0501-1000/0839-Similar-String-Groups/cpp-0839/main2.cpp new file mode 100644 index 00000000..49a9eb41 --- /dev/null +++ b/0501-1000/0839-Similar-String-Groups/cpp-0839/main2.cpp @@ -0,0 +1,88 @@ +/// Source : https://leetcode.com/problems/similar-string-groups/solution/ +/// Author : liuyubobobo +/// Time : 2021-01-30 + +#include +#include +#include + +using namespace std; + + +/// UF +/// Time Complexity: O(n^2 * |str|) +/// Space Complexity: O(n^2) +class UF{ + +private: + vector parent; + int sz; + +public: + UF(int n) : parent(n), sz(n){ + for(int i = 0 ; i < n ; i ++) + parent[i] = i; + } + + int find(int p){ + if(p != parent[p]) + parent[p] = find(parent[p]); + return parent[p]; + } + + bool isConnected(int p, int q){ + return find(p) == find(q); + } + + void unionElements(int p, int q){ + + int pRoot = find(p), qRoot = find(q); + + if(pRoot == qRoot) return; + + parent[pRoot] = qRoot; + sz --; + } + + int size(){ + return sz; + } +}; + +class Solution { +public: + int numSimilarGroups(vector& strs) { + + int n = strs.size(); + + UF uf(n); + for(int i = 0; i < n; i ++) + for(int j = i + 1; j < n; j ++) + if(similar(strs[i], strs[j])) + uf.unionElements(i, j); + + return uf.size(); + } + +private: + bool similar(string& a, string& b){ + + if(a == b) return true; + + int i = -1, j = -1; + for(int k = 0; k < a.size(); k ++) + if(a[k] != b[k]){ + if(i == -1) i = k; + else if(j == -1) j = k; + else return false; + } + + return a[i] == b[j] && a[j] == b[i]; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0841-Keys-and-Rooms/cpp-0841/CMakeLists.txt b/0501-1000/0841-Keys-and-Rooms/cpp-0841/CMakeLists.txt new file mode 100644 index 00000000..53e4951d --- /dev/null +++ b/0501-1000/0841-Keys-and-Rooms/cpp-0841/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0841) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0841 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0841-Keys-and-Rooms/cpp-0841/main.cpp b/0501-1000/0841-Keys-and-Rooms/cpp-0841/main.cpp new file mode 100644 index 00000000..82a9fddb --- /dev/null +++ b/0501-1000/0841-Keys-and-Rooms/cpp-0841/main.cpp @@ -0,0 +1,41 @@ +/// Source : https://leetcode.com/problems/keys-and-rooms/description/ +/// Author : liuyubobobo +/// Time : 2018-09-30 + +#include +#include + +using namespace std; + + +/// DFS +/// Time Compexity: O(V + E) +/// Space Complexity: O(V) +class Solution { + +public: + bool canVisitAllRooms(vector>& rooms) { + + int V = rooms.size(); + vector visited(V, false); + return dfs(rooms, 0, visited) == V; + } + +private: + int dfs(const vector>& rooms, int v, vector& visited){ + + visited[v] = true; + + int res = 1; + for(int next: rooms[v]) + if(!visited[next]) + res += dfs(rooms, next, visited); + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0841-Keys-and-Rooms/cpp-0841/main2.cpp b/0501-1000/0841-Keys-and-Rooms/cpp-0841/main2.cpp new file mode 100644 index 00000000..c63aec4a --- /dev/null +++ b/0501-1000/0841-Keys-and-Rooms/cpp-0841/main2.cpp @@ -0,0 +1,48 @@ +/// Source : https://leetcode.com/problems/keys-and-rooms/description/ +/// Author : liuyubobobo +/// Time : 2018-09-30 + +#include +#include +#include + +using namespace std; + + +/// BFS +/// Time Compexity: O(V + E) +/// Space Complexity: O(V) +class Solution { + +public: + bool canVisitAllRooms(vector>& rooms) { + + int V = rooms.size(); + vector visited(V, false); + + int res = 0; + queue q; + q.push(0); + visited[0] = true; + while(!q.empty()){ + int cur = q.front(); + q.pop(); + + res ++; + + for(int next: rooms[cur]) + if(!visited[next]){ + visited[next] = true; + q.push(next); + } + } + + return res == V; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0841-Keys-and-Rooms/cpp-0841/main3.cpp b/0501-1000/0841-Keys-and-Rooms/cpp-0841/main3.cpp new file mode 100644 index 00000000..58e2b0d0 --- /dev/null +++ b/0501-1000/0841-Keys-and-Rooms/cpp-0841/main3.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/keys-and-rooms/description/ +/// Author : liuyubobobo +/// Time : 2018-09-30 + +#include +#include +#include + +using namespace std; + + +/// DFS +/// Using Stack - non recursion algorithm +/// +/// Time Compexity: O(V + E) +/// Space Complexity: O(V) +class Solution { + +public: + bool canVisitAllRooms(vector>& rooms) { + + int V = rooms.size(); + vector visited(V, false); + + int res = 0; + stack stack; + stack.push(0); + visited[0] = true; + while(!stack.empty()){ + int cur = stack.top(); + stack.pop(); + + res ++; + + for(int next: rooms[cur]) + if(!visited[next]){ + visited[next] = true; + stack.push(next); + } + } + + return res == V; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0842-Split-Array-into-Fibonacci-Sequence/cpp-0842/CMakeLists.txt b/0501-1000/0842-Split-Array-into-Fibonacci-Sequence/cpp-0842/CMakeLists.txt new file mode 100644 index 00000000..fa4abcac --- /dev/null +++ b/0501-1000/0842-Split-Array-into-Fibonacci-Sequence/cpp-0842/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_0842) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0842 main.cpp) \ No newline at end of file diff --git a/0501-1000/0842-Split-Array-into-Fibonacci-Sequence/cpp-0842/main.cpp b/0501-1000/0842-Split-Array-into-Fibonacci-Sequence/cpp-0842/main.cpp new file mode 100644 index 00000000..9fd79403 --- /dev/null +++ b/0501-1000/0842-Split-Array-into-Fibonacci-Sequence/cpp-0842/main.cpp @@ -0,0 +1,66 @@ +/// Source : https://leetcode.com/problems/split-array-into-fibonacci-sequence/submissions/ +/// Author : liuyubobobo +/// Time : 2020-12-08 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +private: + const long long LIMIT = 2147483647ll; + +public: + vector splitIntoFibonacci(const string& s) { + + for(int sz1 = 1; sz1 <= 10; sz1 ++) + for(int sz2 = 1; sz2 <= 10; sz2 ++){ + vector res = ok(s, sz1, sz2); + if(!res.empty()) return res; + } + + return {}; + } + +private: + vector ok(const string& s, int sz1, int sz2){ + + if(sz1 + sz2 >= s.size()) return {}; + + if(s[0] == '0' && sz1 > 1) return {}; + long long a = atoll(s.substr(0, sz1).c_str()); + if(a > LIMIT) return {}; + + if(s[sz1] == '0' && sz2 > 1) return {}; + long long b = atoll(s.substr(sz1, sz2).c_str()); + if(b > LIMIT) return {}; + + vector res = {(int)a, (int)b}; + int p = sz1 + sz2; + while(p < s.size()){ + long long c = a + b; + if(c > LIMIT) return {}; + + string cstr = to_string(c); + int next = s.find(cstr, p); + if(next != p) return {}; + + a = b, b = c; + res.push_back((int) c); + p +=cstr.size(); + } + return res; + }; +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0844-Backspace-String-Compare/cpp-0844/CMakeLists.txt b/0501-1000/0844-Backspace-String-Compare/cpp-0844/CMakeLists.txt new file mode 100644 index 00000000..aad9fdab --- /dev/null +++ b/0501-1000/0844-Backspace-String-Compare/cpp-0844/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_0844) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0844 main.cpp) \ No newline at end of file diff --git a/0501-1000/0844-Backspace-String-Compare/cpp-0844/main.cpp b/0501-1000/0844-Backspace-String-Compare/cpp-0844/main.cpp new file mode 100644 index 00000000..2073af77 --- /dev/null +++ b/0501-1000/0844-Backspace-String-Compare/cpp-0844/main.cpp @@ -0,0 +1,36 @@ +/// Source : https://leetcode.com/problems/backspace-string-compare/ +/// Author : liuyubobobo +/// Time : 2021-07-17 + +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(|s| + |t|) +/// Space Complexity: O(1) +class Solution { +public: + bool backspaceCompare(string s, string t) { + + string a = get_input(s), b = get_input(t); + return a == b; + } + +private: + string get_input(const string& s){ + + string res = ""; + for(char c: s) + if(c != '#') res += c; + else if(res.size()) res.pop_back(); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0846-Hand-of-Straights/cpp-0846/CMakeLists.txt b/0501-1000/0846-Hand-of-Straights/cpp-0846/CMakeLists.txt new file mode 100644 index 00000000..1ff68d96 --- /dev/null +++ b/0501-1000/0846-Hand-of-Straights/cpp-0846/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_0846) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0846 main.cpp) diff --git a/0501-1000/0846-Hand-of-Straights/cpp-0846/main.cpp b/0501-1000/0846-Hand-of-Straights/cpp-0846/main.cpp new file mode 100644 index 00000000..3d82b2ee --- /dev/null +++ b/0501-1000/0846-Hand-of-Straights/cpp-0846/main.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/hand-of-straights/ +/// Author : liuyubobobo +/// Time : 2021-12-29 + +#include +#include +#include + +using namespace std; + + +/// Using Multiset +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + bool isNStraightHand(vector& hand, int groupSize) { + + multiset set; + for(int e: hand) set.insert(e); + + while(!set.empty()){ + int start = *set.begin(); + for(int e = start; e < start + groupSize; e ++) { + if (!set.count(e)) return false; + set.erase(set.find(e)); + } + } + return true; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0847-Shortest-Path-Visiting-All-Nodes/cpp-0847/CMakeLists.txt b/0501-1000/0847-Shortest-Path-Visiting-All-Nodes/cpp-0847/CMakeLists.txt new file mode 100644 index 00000000..45258e33 --- /dev/null +++ b/0501-1000/0847-Shortest-Path-Visiting-All-Nodes/cpp-0847/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0847) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0847 main.cpp) diff --git a/0501-1000/0847-Shortest-Path-Visiting-All-Nodes/cpp-0847/main.cpp b/0501-1000/0847-Shortest-Path-Visiting-All-Nodes/cpp-0847/main.cpp new file mode 100644 index 00000000..d434992b --- /dev/null +++ b/0501-1000/0847-Shortest-Path-Visiting-All-Nodes/cpp-0847/main.cpp @@ -0,0 +1,82 @@ +/// Source : https://leetcode.com/problems/shortest-path-visiting-all-nodes/ +/// Author : liuyubobobo +/// Time : 2021-08-06 + +#include +#include +#include + +using namespace std; + + +/// Memoization +/// Time Complexity: O(n^2 + O(n * 2^n)) +/// Space Complexity: O(n^2 + O(n * 2^n)) +class Solution { +public: + int shortestPathLength(vector>& g) { + + int n = g.size(); + vector> dis(n, vector(n, 0)); + for(int s = 0; s < n; s ++) + bfs(n, g, s, dis[s]); + +// for(const vector& d: dis){ +// for(int e: d) cout << e << ' '; +// cout << '\n'; +// } + + int res = INT_MAX; + vector> dp(n, vector(1 << n, -1)); + for(int s = 0; s < n; s ++) + res = min(res, dfs(n, g, s, 1 << s, dis, dp)); + return res; + } + +private: + int dfs(int n, vector>& g, int u, int state, + const vector>& dis, vector>& dp){ + + if(state + 1 == (1 << n)) return 0; + if(dp[u][state] != -1) return dp[u][state]; + + int res = INT_MAX; + for(int i = 0; i < n; i ++) + if((state & (1 << i)) == 0) + res = min(res, dis[u][i] + dfs(n, g, i, state + (1 << i), dis, dp)); + return dp[u][state] = res; + } + + void bfs(int n, const vector>& g, int s, vector& dis){ + + vector visited(n, false); + queue q; + q.push(s); + visited[s] = true; + dis[s] = 0; + while(!q.empty()){ + int u = q.front(); q.pop(); + for(int v: g[u]) + if(!visited[v]){ + q.push(v); + visited[v] = true; + dis[v] = dis[u] + 1; + } + } + } +}; + + +int main() { + + vector> g1 = {{1,2,3},{0},{0},{0}}; + cout << Solution().shortestPathLength(g1) << endl; + // 4 + + vector> g2 = {{1},{0, 2, 4},{1, 3, 4},{2}, {1, 2}}; + cout << Solution().shortestPathLength(g2) << endl; + // 4 + + + return 0; +} diff --git a/0501-1000/0848-Shifting-Letters/cpp-0848/CMakeLists.txt b/0501-1000/0848-Shifting-Letters/cpp-0848/CMakeLists.txt new file mode 100644 index 00000000..9e036ccf --- /dev/null +++ b/0501-1000/0848-Shifting-Letters/cpp-0848/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0848) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0848 main.cpp) diff --git a/0501-1000/0848-Shifting-Letters/cpp-0848/main.cpp b/0501-1000/0848-Shifting-Letters/cpp-0848/main.cpp new file mode 100644 index 00000000..561e01b9 --- /dev/null +++ b/0501-1000/0848-Shifting-Letters/cpp-0848/main.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/shifting-letters/ +/// Author : liuyubobobo +/// Time : 2021-09-08 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + string shiftingLetters(string s, vector& shifts) { + + int n = s.size(); + vector v(n, shifts.back()); + for(int i = n - 2; i >= 0; i --) + v[i] = v[i + 1] + shifts[i]; + + for(int i = 0; i < s.size(); i ++) + s[i] = 'a' + (v[i] + s[i] - 'a') % 26ll; + return s; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0849-Maximize-Distance-to-Closest-Person/cpp-0849/CMakeLists.txt b/0501-1000/0849-Maximize-Distance-to-Closest-Person/cpp-0849/CMakeLists.txt new file mode 100644 index 00000000..a34e7a62 --- /dev/null +++ b/0501-1000/0849-Maximize-Distance-to-Closest-Person/cpp-0849/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_0849) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0849 main.cpp) diff --git a/0501-1000/0849-Maximize-Distance-to-Closest-Person/cpp-0849/main.cpp b/0501-1000/0849-Maximize-Distance-to-Closest-Person/cpp-0849/main.cpp new file mode 100644 index 00000000..752ede5b --- /dev/null +++ b/0501-1000/0849-Maximize-Distance-to-Closest-Person/cpp-0849/main.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/maximize-distance-to-closest-person/ +/// Author : liuyubobobo +/// Time : 2022-01-16 + +#include +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int maxDistToClosest(vector& seats) { + + vector pos; + for(int i = 0; i < seats.size(); i ++) + if(seats[i]) pos.push_back(i); + + int res = max(pos[0], (int)seats.size() - 1 - pos.back()); + for(int i = 0; i + 1 < pos.size(); i ++) + res = max(res, (pos[i + 1] - pos[i]) / 2); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0850-Rectangle-Area-II/cpp-0850/CMakeLists.txt b/0501-1000/0850-Rectangle-Area-II/cpp-0850/CMakeLists.txt new file mode 100644 index 00000000..ba58982f --- /dev/null +++ b/0501-1000/0850-Rectangle-Area-II/cpp-0850/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0850) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0850 main2.cpp) diff --git a/0501-1000/0850-Rectangle-Area-II/cpp-0850/main.cpp b/0501-1000/0850-Rectangle-Area-II/cpp-0850/main.cpp new file mode 100644 index 00000000..5e83b86a --- /dev/null +++ b/0501-1000/0850-Rectangle-Area-II/cpp-0850/main.cpp @@ -0,0 +1,97 @@ +/// Source : https://leetcode.com/problems/rectangle-area-ii/ +/// Author : liuyubobobo +/// Time : 2021-08-22 + +#include +#include +#include +#include + +using namespace std; + + +/// Coordinates Compression +/// Time Complexity: O(n^2) +/// Space Complexity: O(n^2) +class Solution { + +private: + long long MOD = 1e9 + 7; + +public: + int rectangleArea(vector>& rectangles) { + + set xset, yset; + for(const vector& rec: rectangles){ + int x1 = rec[0], y1 = rec[1], x2 = rec[2], y2 = rec[3]; + xset.insert(x1), xset.insert(x2); + yset.insert(y1), yset.insert(y2); + } + + map x2c, y2c; + vector c2x(xset.size()), c2y(yset.size()); + int maxx = 0, maxy = 0; + for(int x: xset){ + x2c[x] = maxx; + c2x[maxx] = x; + maxx ++; + } + for(int y: yset){ + y2c[y] = maxy; + c2y[maxy] = y; + maxy ++; + } + + vector> table(maxx, vector(maxy, false)); + for(const vector& rec: rectangles){ + int x1 = x2c[rec[0]], y1 = y2c[rec[1]], x2 = x2c[rec[2]], y2 = y2c[rec[3]]; + assert(0 <= x1 && x1 < maxx); + assert(0 <= y1 && y1 < maxy); + assert(0 <= x2 && x2 < maxx); + assert(0 <= y2 && y2 < maxy); + for(int i = x1; i < x2; i ++) + for(int j = y1; j < y2; j ++) + table[i][j] = true; + } + + long long res = 0ll; + for(int i = 0; i + 1 < maxx; i ++) + for(int j = 0; j + 1 < maxy; j ++) + if(table[i][j]){ + int x1 = c2x[i], y1 = c2y[j], x2 = c2x[i + 1], y2 = c2y[j + 1]; + res += (long long)(x2 - x1) * abs(y2 - y1); + res %= MOD; + } + return res; + } +}; + + +int main() { + + vector> rec1 = { + {0,0,2,2},{1,0,2,3},{1,0,3,1} + }; + cout << Solution().rectangleArea(rec1) << endl; + // 6 + + vector> rec2 = { + {0,0,1000000000,1000000000} + }; + cout << Solution().rectangleArea(rec2) << endl; + // 49 + + vector> rec3 = { + {25,20,70,27},{68,80,79,100},{37,41,66,76} + }; + cout << Solution().rectangleArea(rec3) << endl; + // 1550 + + vector> rec4 = { + {0,0,3,3},{2,0,5,3},{1,1,4,4} + }; + cout << Solution().rectangleArea(rec4) << endl; + // 18 + + return 0; +} diff --git a/0501-1000/0850-Rectangle-Area-II/cpp-0850/main2.cpp b/0501-1000/0850-Rectangle-Area-II/cpp-0850/main2.cpp new file mode 100644 index 00000000..3462b5a5 --- /dev/null +++ b/0501-1000/0850-Rectangle-Area-II/cpp-0850/main2.cpp @@ -0,0 +1,108 @@ +/// Source : https://leetcode.com/problems/rectangle-area-ii/ +/// Author : liuyubobobo +/// Time : 2021-08-22 + +#include +#include +#include +#include + +using namespace std; + + +/// Sweep lines +/// Using multiset to optimize +/// +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { + +private: + const int OPEN = 0, CLOSE = 1; + long long MOD = 1e9 + 7; + +public: + int rectangleArea(vector>& rectangles) { + + vector> events; // x, open or close, y1, y2 + for(const vector& rec: rectangles){ + int x1 = rec[0], y1 = rec[1], x2 = rec[2], y2 = rec[3]; + events.push_back({x1, OPEN, y1, y2}); + events.push_back({x2, CLOSE, y1, y2}); + } + + sort(events.begin(), events.end()); + + int px = events[0][0]; + multiset> activey = {{events[0][2], events[0][3]}}; + long long res = 0ll; + for(int i = 1; i < events.size(); i ++){ + int x = events[i][0], type = events[i][1], y1 = events[i][2], y2 = events[i][3]; + + long long y = 0; + if(!activey.empty()){ + pair cur = {-1, -1}; + for(const pair& p: activey){ + if(cur.first == -1) cur = p; + else if(p.first <= cur.second) cur.second = max(cur.second, p.second); + else{ + y += cur.second - cur.first; + cur = p; + } + } + if(cur.first != -1) y += cur.second - cur.first; + + res += y * (x - px); + res %= MOD; + } + + if(type == OPEN){ + activey.insert({y1, y2}); + } + else{ + assert(type == CLOSE); + assert(activey.count({y1, y2})); + activey.erase(activey.find(make_pair(y1, y2))); + } + + px = x; + } + return res; + } +}; + + +int main() { + + vector> rec1 = { + {0,0,2,2},{1,0,2,3},{1,0,3,1} + }; + cout << Solution().rectangleArea(rec1) << endl; + // 6 + + vector> rec2 = { + {0,0,1000000000,1000000000} + }; + cout << Solution().rectangleArea(rec2) << endl; + // 49 + + vector> rec3 = { + {25,20,70,27},{68,80,79,100},{37,41,66,76} + }; + cout << Solution().rectangleArea(rec3) << endl; + // 1550 + + vector> rec4 = { + {0,0,3,3},{2,0,5,3},{1,1,4,4} + }; + cout << Solution().rectangleArea(rec4) << endl; + // 18 + + vector> rec5 = { + {22,24,67,34},{23,18,39,41},{10,63,80,98} + }; + cout << Solution().rectangleArea(rec5) << endl; + // 3108 + + return 0; +} diff --git a/0501-1000/0851-Loud-and-Rich/cpp-0851/CMakeLists.txt b/0501-1000/0851-Loud-and-Rich/cpp-0851/CMakeLists.txt new file mode 100644 index 00000000..3373d497 --- /dev/null +++ b/0501-1000/0851-Loud-and-Rich/cpp-0851/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_0851) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0851 main.cpp) diff --git a/0501-1000/0851-Loud-and-Rich/cpp-0851/main.cpp b/0501-1000/0851-Loud-and-Rich/cpp-0851/main.cpp new file mode 100644 index 00000000..c1a5664b --- /dev/null +++ b/0501-1000/0851-Loud-and-Rich/cpp-0851/main.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/loud-and-rich/ +/// Author : liuyubobobo +/// Time : 2021-12-14 + +#include +#include + +using namespace std; + + +/// DAG DP +/// Time Complexity: O(V + E) +/// Space Complexity: O(V + E) +class Solution { +public: + vector loudAndRich(vector>& richer, vector& quiet) { + + int n = quiet.size(); + + vector> g(n); + for(const vector& e: richer) g[e[1]].push_back(e[0]); + + vector visited(n, false); + vector> res(n, {-1, -1}); // value, index + for(int i = 0; i < n; i ++) + if(!visited[i]) + dfs(g, i, quiet, visited, res); + + vector ret(n); + for(int i = 0; i < n; i ++) ret[i] = res[i].second; + return ret; + } + +private: + void dfs(const vector>& g, int u, const vector& quiet, + vector& visited, vector>& res){ + + visited[u] = true; + res[u] = {quiet[u], u}; + for(int v: g[u]){ + if(!visited[v]) + dfs(g, v, quiet, visited, res); + if(res[v].first < res[u].first) res[u] = res[v]; + } + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0852-Peak-Index-in-a-Mountain-Array/cpp-0852/CMakeLists.txt b/0501-1000/0852-Peak-Index-in-a-Mountain-Array/cpp-0852/CMakeLists.txt new file mode 100644 index 00000000..651ecc24 --- /dev/null +++ b/0501-1000/0852-Peak-Index-in-a-Mountain-Array/cpp-0852/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(A) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main4.cpp) +add_executable(A ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0852-Peak-Index-in-a-Mountain-Array/cpp-0852/main.cpp b/0501-1000/0852-Peak-Index-in-a-Mountain-Array/cpp-0852/main.cpp new file mode 100644 index 00000000..8c753174 --- /dev/null +++ b/0501-1000/0852-Peak-Index-in-a-Mountain-Array/cpp-0852/main.cpp @@ -0,0 +1,40 @@ +/// https://leetcode.com/problems/peak-index-in-a-mountain-array/description/ +/// Author : liuyubobobo +/// Time : 2018-06-17 + +#include +#include +#include + +using namespace std; + +/// Two Linear Scans +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int peakIndexInMountainArray(vector& A) { + + int maxValue = A[0]; + for(int a: A) + maxValue = max(maxValue, a); + + for(int i = 0 ; i < A.size() ; i ++) + if(A[i] == maxValue) + return i; + + assert(false); + return -1; + } +}; + +int main() { + + vector nums1 = {0, 1, 0}; + cout << Solution().peakIndexInMountainArray(nums1) << endl; + + vector nums2 = {0, 2, 1, 0}; + cout << Solution().peakIndexInMountainArray(nums2) << endl; + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0852-Peak-Index-in-a-Mountain-Array/cpp-0852/main2.cpp b/0501-1000/0852-Peak-Index-in-a-Mountain-Array/cpp-0852/main2.cpp new file mode 100644 index 00000000..58d01807 --- /dev/null +++ b/0501-1000/0852-Peak-Index-in-a-Mountain-Array/cpp-0852/main2.cpp @@ -0,0 +1,33 @@ +/// https://leetcode.com/problems/peak-index-in-a-mountain-array/description/ +/// Author : liuyubobobo +/// Time : 2018-06-16 + +#include +#include + +using namespace std; + +/// One Linear Scan +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int peakIndexInMountainArray(vector& A) { + + for(int i = 1 ; i < A.size() ; i ++) + if(A[i - 1] > A[i]) + return i - 1; + return A.size() - 1; + } +}; + +int main() { + + vector nums1 = {0, 1, 0}; + cout << Solution().peakIndexInMountainArray(nums1) << endl; + + vector nums2 = {0, 2, 1, 0}; + cout << Solution().peakIndexInMountainArray(nums2) << endl; + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0852-Peak-Index-in-a-Mountain-Array/cpp-0852/main3.cpp b/0501-1000/0852-Peak-Index-in-a-Mountain-Array/cpp-0852/main3.cpp new file mode 100644 index 00000000..272ea4a6 --- /dev/null +++ b/0501-1000/0852-Peak-Index-in-a-Mountain-Array/cpp-0852/main3.cpp @@ -0,0 +1,45 @@ +/// https://leetcode.com/problems/peak-index-in-a-mountain-array/description/ +/// Author : liuyubobobo +/// Time : 2018-06-17 + +#include +#include + +using namespace std; + +/// Binary Search +/// Make an array of [True, True, ... , True, False, False, ... , False] +/// Find the largest index which is True +/// +/// Time Complexity: O(logn) +/// Space Complexity: O(n) +class Solution { +public: + int peakIndexInMountainArray(vector& A) { + + vector vec; + for(int i = 1 ; i < A.size() ; i ++) + vec.push_back(A[i-1] < A[i]); + + int l = 0, r = vec.size() - 1; + while(l < r){ + int mid = (l + r + 1) / 2; + if(vec[mid]) + l = mid; + else + r = mid - 1; + } + return l + 1; + } +}; + +int main() { + + vector nums1 = {0, 1, 0}; + cout << Solution().peakIndexInMountainArray(nums1) << endl; + + vector nums2 = {0, 2, 1, 0}; + cout << Solution().peakIndexInMountainArray(nums2) << endl; + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0852-Peak-Index-in-a-Mountain-Array/cpp-0852/main4.cpp b/0501-1000/0852-Peak-Index-in-a-Mountain-Array/cpp-0852/main4.cpp new file mode 100644 index 00000000..408f2502 --- /dev/null +++ b/0501-1000/0852-Peak-Index-in-a-Mountain-Array/cpp-0852/main4.cpp @@ -0,0 +1,38 @@ +/// https://leetcode.com/problems/peak-index-in-a-mountain-array/description/ +/// Author : liuyubobobo +/// Time : 2018-06-17 + +#include +#include + +using namespace std; + +/// Binary Search in A directly +/// Time Complexity: O(logn) +/// Space Complexity: O(n) +class Solution { +public: + int peakIndexInMountainArray(vector& A) { + + int l = 0, r = A.size() - 1; + while(l < r){ + int mid = (l + r + 1) / 2; + if(A[mid - 1] < A[mid]) + l = mid; + else + r = mid - 1; + } + return l; + } +}; + +int main() { + + vector nums1 = {0, 1, 0}; + cout << Solution().peakIndexInMountainArray(nums1) << endl; + + vector nums2 = {0, 2, 1, 0}; + cout << Solution().peakIndexInMountainArray(nums2) << endl; + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0853-Car-Fleet/cpp-0853/CMakeLists.txt b/0501-1000/0853-Car-Fleet/cpp-0853/CMakeLists.txt new file mode 100644 index 00000000..ae89e070 --- /dev/null +++ b/0501-1000/0853-Car-Fleet/cpp-0853/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(B) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(B ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0853-Car-Fleet/cpp-0853/main.cpp b/0501-1000/0853-Car-Fleet/cpp-0853/main.cpp new file mode 100644 index 00000000..f6697e22 --- /dev/null +++ b/0501-1000/0853-Car-Fleet/cpp-0853/main.cpp @@ -0,0 +1,75 @@ +/// https://leetcode.com/problems/car-fleet/description/ +/// Author : liuyubobobo +/// Time : 2018-06-17 + +#include +#include +#include + +using namespace std; + + +/// Sort and Scan +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Car{ +public: + int position; + double time; + + Car(int position, double time){ + this->position = position; + this->time = time; + } + + friend bool operator<(const Car& carA, const Car& carB){ + return carA.position > carB.position; + } + + friend ostream& operator<<(ostream& os, const Car& car){ + os << "position: " << car.position << " time: " << car.time; + return os; + } +}; + + +class Solution { +public: + int carFleet(int target, vector& position, vector& speed) { + + assert(position.size() == speed.size()); + + if(position.size() == 0) + return 0; + + if(position.size() == 1) + return 1; + + vector cars; + for(int i = 0 ; i < position.size() ; i ++) + cars.push_back(Car(position[i], (double)(target - position[i]) / speed[i])); + sort(cars.begin(), cars.end()); +// for(const Car& car: cars) +// cout << car << endl; + + int res = 1; + for(int i = 1 ; i < cars.size() ; i ++) + if(cars[i].time <= cars[i-1].time) + cars[i].time = cars[i-1].time; + else + res ++; + + return res; + } +}; + + +int main() { + + int target1 = 12; + vector position1 = {10, 8, 0, 5, 3}; + vector speed1 = {2, 4, 1, 1, 3}; + cout << Solution().carFleet(target1, position1, speed1) << endl; + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0854-K-Similar-Strings/cpp-0854/CMakeLists.txt b/0501-1000/0854-K-Similar-Strings/cpp-0854/CMakeLists.txt new file mode 100644 index 00000000..3cab6b4e --- /dev/null +++ b/0501-1000/0854-K-Similar-Strings/cpp-0854/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0854) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main4.cpp) +add_executable(cpp_0854 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0854-K-Similar-Strings/cpp-0854/main.cpp b/0501-1000/0854-K-Similar-Strings/cpp-0854/main.cpp new file mode 100644 index 00000000..86453683 --- /dev/null +++ b/0501-1000/0854-K-Similar-Strings/cpp-0854/main.cpp @@ -0,0 +1,164 @@ +/// Source : https://leetcode.com/problems/k-similar-strings/description/ +/// Author : liuyubobobo +/// Time : 2018-06-21 + +#include +#include +#include +#include + +using namespace std; + + +/// Enumerate all circle combinations and using Memory Search +/// There're 55 different circle combinations in total! +/// +/// Time Complexity: O(2^6 * 2^n) +/// Space Complexity: O(2^6 * 2^n) +class Solution { + +private: + unordered_map dp; + string empty_g; + +public: + int kSimilarity(string A, string B) { + + assert(A.size() == B.size()); + assert(A.size() > 0); + if(A.size() == 1){ + assert(A[0] == B[0]); + return 0; + } + + vector g(36, 0); + empty_g = hash(g); + int total_edge = 0; + for(int i = 0 ; i < A.size() ; i ++) + if(B[i] != A[i]) { + g[(B[i] - 'a') * 6 + (A[i] - 'a')]++; + total_edge ++; + } + + vector circles; + for(int circle_length = 2 ; circle_length <= min(6, (int)A.size()) ; circle_length ++){ + vector char_sets = pick(circle_length); + for(string& p: char_sets){ + do{ + bool ok = true; + for(int i = 1 ; i < p.size() ; i ++) + if(p[i] < p[0]){ + ok = false; + break; + } + + if(ok) + circles.push_back(p); + }while(next_permutation(p.begin(), p.end())); + } + } + // cout << "circles size : " << circles.size() << endl; + // 55 + + dp.clear(); + return total_edge - max_circle_num(g, circles); + } + +private: + string hash(const vector& g){ + string res = ""; + for(int i = 0 ; i < g.size() ; i ++) + res += to_string(g[i]) + "#"; + return res; + } + + int max_circle_num(vector& g, const vector& circles){ + + string hashcode = hash(g); + if(hashcode == empty_g) + return 0; + + unordered_map::iterator iter = dp.find(hashcode); + if(iter != dp.end()) + return iter->second; + + int res = 0; + for(const string& circle: circles) + if(contains_circle(g, circle)){ + for(int i = 0 ; i < circle.size() ; i ++){ + int u = circle[i] - 'a'; + int v = circle[(i+1)%circle.size()] - 'a'; + g[u * 6 + v] --; + } + + res = max(res, 1 + max_circle_num(g, circles)); + + for(int i = 0 ; i < circle.size() ; i ++){ + int u = circle[i] - 'a'; + int v = circle[(i+1)%circle.size()] - 'a'; + g[u * 6 + v] ++; + } + } + + dp[hashcode] = res; + return res; + } + + bool contains_circle(const vector g, const string& circle){ + for(int i = 0 ; i < circle.size() ; i ++){ + int u = circle[i] - 'a'; + int v = circle[(i + 1) % circle.size()] - 'a'; + if(g[u * 6 + v] == 0) + return false; + } + return true; + } + + vector pick(int num){ + vector res; + pick("abcdef", num, res, 0, ""); + return res; + } + + void pick(const string& s, int num, vector& res, int start, const string& cur){ + if(num == 0){ + res.push_back(cur); + return; + } + + for(int i = start ; i <= (int)s.size() - num ; i ++) + pick(s, num - 1, res, i + 1, cur + s[i]); + + return; + } +}; + +int main() { + + string A1 = "ab"; + string B1 = "ba"; + cout << Solution().kSimilarity(A1, B1) << endl; + // 1 + + string A2 = "abc"; + string B2 = "bca"; + cout << Solution().kSimilarity(A2, B2) << endl; + // 2 + + string A3 = "abac"; + string B3 = "baca"; + cout << Solution().kSimilarity(A3, B3) << endl; + // 2 + + string A4 = "aabc"; + string B4 = "abca"; + cout << Solution().kSimilarity(A4, B4) << endl; + // 2 + + string A5 = "abcdefabcdefabcdef"; + string B5 = "edcfbebceafcfdabad"; + cout << Solution().kSimilarity(A5, B5) << endl; + // 10 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0854-K-Similar-Strings/cpp-0854/main2.cpp b/0501-1000/0854-K-Similar-Strings/cpp-0854/main2.cpp new file mode 100644 index 00000000..f3fcd65b --- /dev/null +++ b/0501-1000/0854-K-Similar-Strings/cpp-0854/main2.cpp @@ -0,0 +1,165 @@ +/// Source : https://leetcode.com/problems/k-similar-strings/description/ +/// Author : liuyubobobo +/// Time : 2018-06-21 + +#include +#include +#include +#include + +using namespace std; + + +/// Enumerate all circle combinations and using Memory Search +/// There're 55 different circle combinations in total! +/// In this code, I optimized the contains_circle function and get the circle number as returns:) +/// +/// Time Complexity: O(2^6 * 2^n) +/// Space Complexity: O(2^6 * 2^n) +class Solution { + +private: + unordered_map dp; + string empty_g; + +public: + int kSimilarity(string A, string B) { + + assert(A.size() == B.size()); + assert(A.size() > 0); + if(A.size() == 1){ + assert(A[0] == B[0]); + return 0; + } + + vector g(36, 0); + empty_g = hash(g); + int total_edge = 0; + for(int i = 0 ; i < A.size() ; i ++) + if(B[i] != A[i]) { + g[(B[i] - 'a') * 6 + (A[i] - 'a')]++; + total_edge ++; + } + + vector circles; + for(int circle_length = 2 ; circle_length <= min(6, (int)A.size()) ; circle_length ++){ + vector char_sets = pick(circle_length); + for(string& p: char_sets){ + do{ + bool ok = true; + for(int i = 1 ; i < p.size() ; i ++) + if(p[i] < p[0]){ + ok = false; + break; + } + + if(ok) + circles.push_back(p); + }while(next_permutation(p.begin(), p.end())); + } + } + // cout << "circles size : " << circles.size() << endl; + // 55 + + dp.clear(); + return total_edge - max_circle_num(g, circles); + } + +private: + string hash(const vector& g){ + string res = ""; + for(int i = 0 ; i < g.size() ; i ++) + res += to_string(g[i]) + "#"; + return res; + } + + int max_circle_num(vector& g, const vector& circles){ + + string hashcode = hash(g); + if(hashcode == empty_g) + return 0; + + unordered_map::iterator iter = dp.find(hashcode); + if(iter != dp.end()) + return iter->second; + + int res = 0; + for(const string& circle: circles) + if(int k = contains_circle(g, circle)){ + for(int i = 0 ; i < circle.size() ; i ++){ + int u = circle[i] - 'a'; + int v = circle[(i+1)%circle.size()] - 'a'; + g[u * 6 + v] -= k; + } + + res = max(res, k + max_circle_num(g, circles)); + + for(int i = 0 ; i < circle.size() ; i ++){ + int u = circle[i] - 'a'; + int v = circle[(i+1)%circle.size()] - 'a'; + g[u * 6 + v] += k; + } + } + + dp[hashcode] = res; + return res; + } + + int contains_circle(const vector g, const string& circle){ + int res = INT_MAX; + for(int i = 0 ; i < circle.size() ; i ++){ + int u = circle[i] - 'a'; + int v = circle[(i + 1) % circle.size()] - 'a'; + res = min(res, g[u * 6 + v]); + } + return res; + } + + vector pick(int num){ + vector res; + pick("abcdef", num, res, 0, ""); + return res; + } + + void pick(const string& s, int num, vector& res, int start, const string& cur){ + if(num == 0){ + res.push_back(cur); + return; + } + + for(int i = start ; i <= (int)s.size() - num ; i ++) + pick(s, num - 1, res, i + 1, cur + s[i]); + + return; + } +}; + +int main() { + + string A1 = "ab"; + string B1 = "ba"; + cout << Solution().kSimilarity(A1, B1) << endl; + // 1 + + string A2 = "abc"; + string B2 = "bca"; + cout << Solution().kSimilarity(A2, B2) << endl; + // 2 + + string A3 = "abac"; + string B3 = "baca"; + cout << Solution().kSimilarity(A3, B3) << endl; + // 2 + + string A4 = "aabc"; + string B4 = "abca"; + cout << Solution().kSimilarity(A4, B4) << endl; + // 2 + + string A5 = "abcdefabcdefabcdef"; + string B5 = "edcfbebceafcfdabad"; + cout << Solution().kSimilarity(A5, B5) << endl; + // 10 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0854-K-Similar-Strings/cpp-0854/main3.cpp b/0501-1000/0854-K-Similar-Strings/cpp-0854/main3.cpp new file mode 100644 index 00000000..04ac53f9 --- /dev/null +++ b/0501-1000/0854-K-Similar-Strings/cpp-0854/main3.cpp @@ -0,0 +1,92 @@ +/// Source : https://leetcode.com/problems/k-similar-strings/description/ +/// Author : liuyubobobo +/// Time : 2018-06-21 + +#include +#include +#include +#include + +using namespace std; + + +/// Greedy + BFS +/// Time Complexity: O(2^n) +/// Space Complexity: O(2^n) +class Solution { + +public: + int kSimilarity(string A, string B) { + + assert(A.size() == B.size()); + assert(A.size() > 0); + if(A.size() == 1){ + assert(A[0] == B[0]); + return 0; + } + + queue> q; + q.push(make_pair(A, 0)); + + unordered_set visited; + visited.insert(A); + + while(!q.empty()){ + string curS = q.front().first; + int curStep = q.front().second; + + if(curS == B) + return curStep; + + q.pop(); + + int start = 0; + for( ; start < curS.size() ; start ++) + if(curS[start] != B[start]) + break; + + for(int i = start + 1 ; i < curS.size() ; i ++) + if(curS[i] == B[start]){ + swap(curS[start], curS[i]); + if(visited.find(curS) == visited.end()){ + visited.insert(curS); + q.push(make_pair(curS, curStep + 1)); + } + swap(curS[start], curS[i]); + } + } + + assert(false); + return -1; + } +}; + +int main() { + + string A1 = "ab"; + string B1 = "ba"; + cout << Solution().kSimilarity(A1, B1) << endl; + // 1 + + string A2 = "abc"; + string B2 = "bca"; + cout << Solution().kSimilarity(A2, B2) << endl; + // 2 + + string A3 = "abac"; + string B3 = "baca"; + cout << Solution().kSimilarity(A3, B3) << endl; + // 2 + + string A4 = "aabc"; + string B4 = "abca"; + cout << Solution().kSimilarity(A4, B4) << endl; + // 2 + + string A5 = "abcdefabcdefabcdef"; + string B5 = "edcfbebceafcfdabad"; + cout << Solution().kSimilarity(A5, B5) << endl; + // 10 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0854-K-Similar-Strings/cpp-0854/main4.cpp b/0501-1000/0854-K-Similar-Strings/cpp-0854/main4.cpp new file mode 100644 index 00000000..280dc09f --- /dev/null +++ b/0501-1000/0854-K-Similar-Strings/cpp-0854/main4.cpp @@ -0,0 +1,103 @@ +/// Source : https://leetcode.com/problems/k-similar-strings/description/ +/// Author : liuyubobobo +/// Time : 2018-06-21 + +#include +#include +#include +#include + +using namespace std; + + +/// Greedy + BFS +/// BFS process optimized :) +/// +/// Time Complexity: O(2^n) +/// Space Complexity: O(2^n) +class Solution { + +public: + int kSimilarity(string A, string B) { + + assert(A.size() == B.size()); + assert(A.size() > 0); + if(A.size() == 1){ + assert(A[0] == B[0]); + return 0; + } + + if(A == B) + return 0; + + int start = next_start(A, B, 0); + + queue>> q; + q.push(make_pair(A, make_pair(start, 0))); + + unordered_set visited; + visited.insert(A); + + while(!q.empty()){ + string curS = q.front().first; + start = q.front().second.first; + int curStep = q.front().second.second; + q.pop(); + + for(int i = start + 1 ; i < curS.size() ; i ++) + if(curS[i] == B[start]){ + swap(curS[start], curS[i]); + if(visited.find(curS) == visited.end()){ + if(curS == B) + return curStep + 1; + + visited.insert(curS); + q.push(make_pair(curS, make_pair(next_start(curS, B, start + 1), curStep + 1))); + } + swap(curS[start], curS[i]); + } + } + + assert(false); + return -1; + } + +private: + int next_start(const string& A, const string& B, int start){ + for(int i = start ; i < A.size() ; i ++) + if(A[i] != B[i]) + return i; + assert(false); + return A.size(); + } +}; + +int main() { + + string A1 = "ab"; + string B1 = "ba"; + cout << Solution().kSimilarity(A1, B1) << endl; + // 1 + + string A2 = "abc"; + string B2 = "bca"; + cout << Solution().kSimilarity(A2, B2) << endl; + // 2 + + string A3 = "abac"; + string B3 = "baca"; + cout << Solution().kSimilarity(A3, B3) << endl; + // 2 + + string A4 = "aabc"; + string B4 = "abca"; + cout << Solution().kSimilarity(A4, B4) << endl; + // 2 + + string A5 = "abcdefabcdefabcdef"; + string B5 = "edcfbebceafcfdabad"; + cout << Solution().kSimilarity(A5, B5) << endl; + // 10 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0855-Exam-Room/cpp-0855/CMakeLists.txt b/0501-1000/0855-Exam-Room/cpp-0855/CMakeLists.txt new file mode 100644 index 00000000..2a554b67 --- /dev/null +++ b/0501-1000/0855-Exam-Room/cpp-0855/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0855) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0855 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0855-Exam-Room/cpp-0855/main.cpp b/0501-1000/0855-Exam-Room/cpp-0855/main.cpp new file mode 100644 index 00000000..575b47f2 --- /dev/null +++ b/0501-1000/0855-Exam-Room/cpp-0855/main.cpp @@ -0,0 +1,75 @@ +/// Source : https://leetcode.com/problems/exam-room/description/ +/// Author : liuyubobobo +/// Time : 2018-06-17 + +#include +#include + +using namespace std; + +/// Using TreeSet +/// +/// Time Complexity: seat - O(N) +/// leave - O(logN) +/// Space Compexity: O(N) +class ExamRoom { + +private: + set seats; + int N; + +public: + ExamRoom(int N) { + this->N = N; + seats.clear(); + } + + int seat() { + + if(seats.empty()){ + seats.insert(0); + return 0; + } + + int maxDis = *seats.begin(); + int res = 0; + + set::iterator last_iter = seats.begin(); + set::iterator iter = seats.begin(); + iter ++; + for(; iter != seats.end() ; last_iter++, iter ++){ + int dis = (*iter - *last_iter) / 2; + if(dis > maxDis){ + maxDis = dis; + res = *last_iter + dis; + } + } + + if(N - 1 - *last_iter > maxDis){ + maxDis = N - 1 - *last_iter; + res = N - 1; + } + + seats.insert(res); + return res; + } + + void leave(int p) { + seats.erase(p); + } +}; + + +int main() { + + int N = 10; + ExamRoom examRoom(N); + cout << examRoom.seat() << endl; // 0 + cout << examRoom.seat() << endl; // 9 + cout << examRoom.seat() << endl; // 4 + cout << examRoom.seat() << endl; // 2 + examRoom.leave(4); + cout << examRoom.seat() << endl; // 5 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0856-Score-of-Parentheses/cpp-0856/CMakeLists.txt b/0501-1000/0856-Score-of-Parentheses/cpp-0856/CMakeLists.txt new file mode 100644 index 00000000..45cd0786 --- /dev/null +++ b/0501-1000/0856-Score-of-Parentheses/cpp-0856/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(B) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main4.cpp) +add_executable(B ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0856-Score-of-Parentheses/cpp-0856/main.cpp b/0501-1000/0856-Score-of-Parentheses/cpp-0856/main.cpp new file mode 100644 index 00000000..8e4ea3dc --- /dev/null +++ b/0501-1000/0856-Score-of-Parentheses/cpp-0856/main.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/score-of-parentheses/description/ +/// Author : liuyubobobo +/// Time : 2018-06-23 + +#include +#include +#include + +using namespace std; + +/// Recursive +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { +public: + int scoreOfParentheses(string S) { + + int res = 0; + + int left = 0; + int start = 0; + for(int i = 0 ; i < S.size() ; i ++){ + if(S[i] == '(') + left ++; + else{ + left --; + if(left == 0){ + res += score(S, start, i); + start = i + 1; + } + } + } + return res; + } + +private: + int score(const string& s, int l, int r){ + + if(l + 1 == r){ + assert(s[l] == '(' && s[r] == ')'); + return 1; + } + + return 2 * scoreOfParentheses(s.substr(l + 1, r - l + 1 - 2)); + } +}; + + +int main() { + + cout << Solution().scoreOfParentheses("()") << endl; + cout << Solution().scoreOfParentheses("(())") << endl; + cout << Solution().scoreOfParentheses("()()") << endl; + cout << Solution().scoreOfParentheses("(()(()))") << endl; + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0856-Score-of-Parentheses/cpp-0856/main2.cpp b/0501-1000/0856-Score-of-Parentheses/cpp-0856/main2.cpp new file mode 100644 index 00000000..0fba07e7 --- /dev/null +++ b/0501-1000/0856-Score-of-Parentheses/cpp-0856/main2.cpp @@ -0,0 +1,56 @@ +/// Source : https://leetcode.com/problems/score-of-parentheses/description/ +/// Author : liuyubobobo +/// Time : 2018-06-25 + +#include +#include +#include + +using namespace std; + +/// Recursive Optimized +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { +public: + int scoreOfParentheses(string S) { + + return score(S, 0, S.size() - 1); + } + +private: + int score(const string& s, int l, int r){ + + int res = 0; + + int balance = 0; + int start = l; + for(int i = l ; i <= r ; i ++){ + if(s[i] == '(') + balance ++; + else{ + balance --; + + if(balance == 0){ + if(l + 1 == i) + res += 1; + else + res += 2 * score(s, l + 1, i - 1); + l = i + 1; + } + } + } + return res; + } +}; + + +int main() { + + cout << Solution().scoreOfParentheses("()") << endl; // 1 + cout << Solution().scoreOfParentheses("(())") << endl; // 2 + cout << Solution().scoreOfParentheses("()()") << endl; // 2 + cout << Solution().scoreOfParentheses("(()(()))") << endl; // 6 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0856-Score-of-Parentheses/cpp-0856/main3.cpp b/0501-1000/0856-Score-of-Parentheses/cpp-0856/main3.cpp new file mode 100644 index 00000000..7feee0ca --- /dev/null +++ b/0501-1000/0856-Score-of-Parentheses/cpp-0856/main3.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/score-of-parentheses/description/ +/// Author : liuyubobobo +/// Time : 2018-06-25 + +#include +#include +#include + +using namespace std; + +/// Using a Stack +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int scoreOfParentheses(string S) { + + stack stack; + stack.push(0); + for(char c: S){ + if(c == '(') + stack.push(0); + else{ + int v = stack.top(); + stack.pop(); + int w = stack.top(); + stack.pop(); + + stack.push(w + max(2 * v, 1)); + } + } + + return stack.top(); + } +}; + + +int main() { + + cout << Solution().scoreOfParentheses("()") << endl; // 1 + cout << Solution().scoreOfParentheses("(())") << endl; // 2 + cout << Solution().scoreOfParentheses("()()") << endl; // 2 + cout << Solution().scoreOfParentheses("(()(()))") << endl; // 6 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0856-Score-of-Parentheses/cpp-0856/main4.cpp b/0501-1000/0856-Score-of-Parentheses/cpp-0856/main4.cpp new file mode 100644 index 00000000..ba11b08f --- /dev/null +++ b/0501-1000/0856-Score-of-Parentheses/cpp-0856/main4.cpp @@ -0,0 +1,42 @@ +/// Source : https://leetcode.com/problems/score-of-parentheses/description/ +/// Author : liuyubobobo +/// Time : 2018-06-25 + +#include +#include +#include + +using namespace std; + +/// Calculating Cores +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int scoreOfParentheses(string S) { + + int balance = 0; + int res = 0; + for(int i = 0 ; i < S.size() ; i ++) + if(S[i] == '(') + balance ++; + else{ + balance --; + if(S[i - 1] == '(') + res += (1 << balance); + } + + return res; + } +}; + + +int main() { + + cout << Solution().scoreOfParentheses("()") << endl; // 1 + cout << Solution().scoreOfParentheses("(())") << endl; // 2 + cout << Solution().scoreOfParentheses("()()") << endl; // 2 + cout << Solution().scoreOfParentheses("(()(()))") << endl; // 6 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0857-Minimum-Cost-to-Hire-K-Workers/cpp-0857/CMakeLists.txt b/0501-1000/0857-Minimum-Cost-to-Hire-K-Workers/cpp-0857/CMakeLists.txt new file mode 100644 index 00000000..754344ba --- /dev/null +++ b/0501-1000/0857-Minimum-Cost-to-Hire-K-Workers/cpp-0857/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0857) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0857 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0857-Minimum-Cost-to-Hire-K-Workers/cpp-0857/main.cpp b/0501-1000/0857-Minimum-Cost-to-Hire-K-Workers/cpp-0857/main.cpp new file mode 100644 index 00000000..841a33ea --- /dev/null +++ b/0501-1000/0857-Minimum-Cost-to-Hire-K-Workers/cpp-0857/main.cpp @@ -0,0 +1,93 @@ +/// Source : https://leetcode.com/problems/minimum-cost-to-hire-k-workers/description/ +/// Author : liuyubobobo +/// Time : 2010-06-25 + +#include +#include +#include +#include + +using namespace std; + + +/// Greedy + Priority Queue +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Worker{ + +private: + int q, w; + double ratio; + +public: + Worker(int q, int w){ + this->q = q; + this->w = w; + this->ratio = (double)w / q; + } + + double getRatio() const{ + return ratio; + } + + int getQuality() const{ + return q; + } +}; + + +bool cmpWorkers (const Worker& w1, const Worker& w2){ + return w1.getRatio() < w2.getRatio(); +} + +class Solution { +public: + double mincostToHireWorkers(vector& quality, vector& wage, int K) { + + assert(K <= quality.size()); + + vector workers; + for(int i = 0 ; i < quality.size() ; i ++) + workers.push_back(Worker(quality[i], wage[i])); + + sort(workers.begin(), workers.end(), cmpWorkers); + + priority_queue pq; + int sumq = 0; + for(int i = 0 ; i < K ; i ++){ + pq.push(workers[i].getQuality()); + sumq += workers[i].getQuality(); + } + + double res = sumq * workers[K-1].getRatio(); + for(int i = K ; i < workers.size() ; i ++){ + int maxq = pq.top(); + pq.pop(); + sumq -= maxq; + + pq.push(workers[i].getQuality()); + sumq += workers[i].getQuality(); + res = min(res, sumq * workers[i].getRatio()); + } + + return res; + } +}; + + +int main() { + + vector quality1 = {10, 20, 5}; + vector wage1 = {70, 50, 30}; + int K1 = 2; + cout << Solution().mincostToHireWorkers(quality1, wage1, K1) << endl; + // 105.00000 + + vector quality2 = {3, 1, 10, 10, 1}; + vector wage2 = {4, 8, 2, 2, 7}; + int K2 = 3; + cout << Solution().mincostToHireWorkers(quality2, wage2, K2) << endl; + // 30.66667 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0858-Mirror-Reflection/cpp-0858/CMakeLists.txt b/0501-1000/0858-Mirror-Reflection/cpp-0858/CMakeLists.txt new file mode 100644 index 00000000..10d4db6b --- /dev/null +++ b/0501-1000/0858-Mirror-Reflection/cpp-0858/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(C) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main2.cpp) +add_executable(C ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0858-Mirror-Reflection/cpp-0858/main.cpp b/0501-1000/0858-Mirror-Reflection/cpp-0858/main.cpp new file mode 100644 index 00000000..75491b51 --- /dev/null +++ b/0501-1000/0858-Mirror-Reflection/cpp-0858/main.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/mirror-reflection/description/ +/// Author : liuyubobobo +/// Time : 2018-06-25 + +#include +#include + +using namespace std; + +/// Simulation +/// Time Complexity: O(p) +/// Space Complexity: O(1) +class Solution { +public: + int mirrorReflection(int p, int q) { + + int d = 1; + bool left = true; + int y = 0; + while(true){ + + y += d * q; + left = !left; + if(y == p && left) + return 2; + else if(y == p && !left) + return 1; + else if(y == 0) + return 0; + + if(y > p){ + assert(d == 1); + y = p - (y - p); + d = -1; + } + else if(y < 0){ + assert(d == -1); + y = -y; + d = 1; + } + } + + assert(false); + return -1; + } +}; + + +int main() { + + cout << Solution().mirrorReflection(2, 1) << endl; // 2 + cout << Solution().mirrorReflection(4, 3) << endl; // 2 + cout << Solution().mirrorReflection(3, 2) << endl; // 0 + cout << Solution().mirrorReflection(3, 1) << endl; // 1 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0858-Mirror-Reflection/cpp-0858/main2.cpp b/0501-1000/0858-Mirror-Reflection/cpp-0858/main2.cpp new file mode 100644 index 00000000..8c88baa1 --- /dev/null +++ b/0501-1000/0858-Mirror-Reflection/cpp-0858/main2.cpp @@ -0,0 +1,56 @@ +/// Source : https://leetcode.com/problems/mirror-reflection/description/ +/// Author : liuyubobobo +/// Time : 2018-06-23 + +#include +#include + +using namespace std; + +/// Mathematics +/// Time Complexity: O(log(max(p, q))) +/// Space Complexity: O(1) +class Solution { +public: + int mirrorReflection(int p, int q) { + + int g = gcd(p, q); + int k = p / g; + + int x = p * k; + int y = q * k; + assert(y % p == 0); + + if(isEven(y / p)) + return 0; + + if(isEven(x / p)) + return 2; + return 1; + } + +private: + bool isEven(int x){ + return x % 2 == 0; + } + + int gcd(int a, int b){ + if(a > b) + swap(a, b); + + if(b % a == 0) + return a; + return gcd(b % a, a); + } +}; + + +int main() { + + cout << Solution().mirrorReflection(2, 1) << endl; // 2 + cout << Solution().mirrorReflection(4, 3) << endl; // 2 + cout << Solution().mirrorReflection(3, 2) << endl; // 0 + cout << Solution().mirrorReflection(3, 1) << endl; // 1 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0859-Buddy-Strings/cpp-0859/CMakeLists.txt b/0501-1000/0859-Buddy-Strings/cpp-0859/CMakeLists.txt new file mode 100644 index 00000000..b3fafe13 --- /dev/null +++ b/0501-1000/0859-Buddy-Strings/cpp-0859/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(A) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(A ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0859-Buddy-Strings/cpp-0859/main.cpp b/0501-1000/0859-Buddy-Strings/cpp-0859/main.cpp new file mode 100644 index 00000000..af70697f --- /dev/null +++ b/0501-1000/0859-Buddy-Strings/cpp-0859/main.cpp @@ -0,0 +1,70 @@ +/// Source : https://leetcode.com/problems/buddy-strings/description/ +/// Author : liuyubobobo +/// Time : 2018-06-25 +/// Updated: 2021-11-22 + +#include +#include + +using namespace std; + + +/// Scan and Compare +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + bool buddyStrings(string A, string B) { + + if(A.size() != B.size()) + return false; + + if(A == B) + return atLeastTwoSame(A); + + int first = -1, second = -1; + for(int i = 0 ; i < A.size(); i++) + if(A[i] != B[i]){ + if(first == -1) + first = i; + else if(second == -1) + second = i; + else + return false; + } + + return second != -1 && A[first] == B[second] && A[second] == B[first]; + } + +private: + bool atLeastTwoSame(const string& s){ + vector freq(26, 0); + for(char c: s){ + freq[c - 'a'] ++; + if(freq[c - 'a'] >= 2) + return true; + } + return false; + } +}; + + +int main() { + + cout << Solution().buddyStrings("ab", "ba") << endl; + // 1 + + cout << Solution().buddyStrings("ab", "ab") << endl; + // 0 + + cout << Solution().buddyStrings("ab", "ba") << endl; + // 1 + + cout << Solution().buddyStrings("aaaaaaabc", "aaaaaaacb") << endl; + // 1 + + cout << Solution().buddyStrings("", "aa") << endl; + // 0 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0860-Lemonade-Change/cpp-0860/CMakeLists.txt b/0501-1000/0860-Lemonade-Change/cpp-0860/CMakeLists.txt new file mode 100644 index 00000000..de90c405 --- /dev/null +++ b/0501-1000/0860-Lemonade-Change/cpp-0860/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0860) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0860 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0860-Lemonade-Change/cpp-0860/main.cpp b/0501-1000/0860-Lemonade-Change/cpp-0860/main.cpp new file mode 100644 index 00000000..9c602b91 --- /dev/null +++ b/0501-1000/0860-Lemonade-Change/cpp-0860/main.cpp @@ -0,0 +1,64 @@ +/// Source : https://leetcode.com/problems/lemonade-change/description/ +/// Author : liuyubobobo +/// Time : 2018-06-30 + +#include +#include + +using namespace std; + + +/// Simulation and Greedy +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + bool lemonadeChange(vector& bills) { + + int five = 0, ten = 0, twenty = 0; + for(int bill: bills){ + if(bill == 5) + five ++; + else if(bill == 10){ + ten ++; + if(five == 0) + return false; + else + five --; + } + else{ + twenty ++; + if(ten > 0 && five > 0) + ten --, five --; + else if(five >= 3) + five -= 3; + else + return false; + } + } + + return true; + } +}; + + +void print_bool(bool res){ + cout << (res ? "True" : "False") << endl; +} + +int main() { + + vector bills1 = {5, 5, 5, 10, 20}; + print_bool(Solution().lemonadeChange(bills1)); + + vector bills2 = {5, 5, 10}; + print_bool(Solution().lemonadeChange(bills2)); + + vector bills3 = {10, 10}; + print_bool(Solution().lemonadeChange(bills3)); + + vector bills4 = {5, 5, 10, 10, 20}; + print_bool(Solution().lemonadeChange(bills4)); + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0861-Score-After-Flipping-Matrix/cpp-0861/CMakeLists.txt b/0501-1000/0861-Score-After-Flipping-Matrix/cpp-0861/CMakeLists.txt new file mode 100644 index 00000000..9177dc49 --- /dev/null +++ b/0501-1000/0861-Score-After-Flipping-Matrix/cpp-0861/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0861) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main2.cpp) +add_executable(cpp_0861 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0861-Score-After-Flipping-Matrix/cpp-0861/main.cpp b/0501-1000/0861-Score-After-Flipping-Matrix/cpp-0861/main.cpp new file mode 100644 index 00000000..7d43304e --- /dev/null +++ b/0501-1000/0861-Score-After-Flipping-Matrix/cpp-0861/main.cpp @@ -0,0 +1,75 @@ +/// Source : https://leetcode.com/problems/score-after-flipping-matrix/description/ +/// Author : liuyubobobo +/// Time : 2018-06-30 + +#include +#include + +using namespace std; + +/// Greedy +/// Time Complexity: O(n^2) +/// Space Complexity: O(n^2) +class Solution { + +public: + int matrixScore(vector>& A) { + + for(int i = 0 ; i < A.size() ; i ++) + if(A[i][0] == 0) + flipRow(A, i); + + for(int j = 1 ; j < A[0].size() ; j ++){ + + int zeros = zeroNumInCol(A, j); + if(zeros > A.size() / 2) + flipCol(A, j); + } + +// for(int i = 0 ; i < A.size() ; i ++) +// for(int j = 0 ; j < A[i].size() ; j ++) +// cout << A[i][j] << (j == A[i].size() - 1 ? '\n' : ' '); + + return score(A); + } + +private: + int score(const vector>& A){ + int res = 0; + for(int i = 0 ; i < A.size() ; i ++) + for(int j = 0 ; j < A[i].size() ; j ++) + if(A[i][j]) + res += (1 << (A[i].size() - 1 - j)); + return res; + } + + void flipRow(vector>& A, int row){ + for(int j = 0 ; j < A[row].size() ; j ++) + A[row][j] = 1 - A[row][j]; + } + + void flipCol(vector>& A, int col){ + for(int i = 0 ; i < A.size() ; i ++) + A[i][col] = 1 - A[i][col]; + } + + int zeroNumInCol(const vector>& A, int col){ + int zeros = 0; + for(int i = 0 ; i < A.size() ; i ++) + zeros += (A[i][col] == 0 ? 1 : 0); + return zeros; + } +}; + + +int main() { + + vector> A1 = { + {0, 0, 1, 1}, + {1, 0, 1, 0}, + {1, 1, 0, 0} + }; + cout << Solution().matrixScore(A1) << endl; + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0861-Score-After-Flipping-Matrix/cpp-0861/main2.cpp b/0501-1000/0861-Score-After-Flipping-Matrix/cpp-0861/main2.cpp new file mode 100644 index 00000000..4705d607 --- /dev/null +++ b/0501-1000/0861-Score-After-Flipping-Matrix/cpp-0861/main2.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/score-after-flipping-matrix/description/ +/// Author : liuyubobobo +/// Time : 2018-06-30 + +#include +#include + +using namespace std; + +/// Greedy +/// +/// An unbelievable concise implementation to the same concept of this problem +/// +/// We make the left most digit of every row into 0 by xor A[r][0], +/// After that, we can of course toggling the entire column to get all the left most digit to 1, +/// +/// Since we make every left most digit is 0, it means we need to toggle every row if the original left most digit is 1 +/// We make every element to xor the original leftmost digit in the same row, +/// If the leftmost digit is 1, we need to toggle it, A[r][c] ^ 1 means toggle it! Since 0^1 = 1 and 1^1 = 0; +/// If the leftmost digit is 0, we don't need to toggle it, A[r][c] ^ 0 means stick to the original digit. +/// The col variable record the one number if we don't toggle the column, just toggle the needed rows if we want to keep all the leftmost digits zero; +/// The R - col variable record the one number if we toggle the column:) +/// +/// Time Complexity: O(n^2) +/// Space Complexity: O(n^2) +class Solution { + +public: + int matrixScore(vector>& A) { + + int R = A.size(), C = A[0].size(); + int ans = 0; + for (int c = 0; c < C; c ++) { + int col = 0; + for (int r = 0; r < R; r ++) + col += A[r][c] ^ A[r][0]; + ans += max(col, R - col) * (1 << (C - 1 - c)); + } + return ans; + } +}; + + +int main() { + + vector> A1 = { + {0, 0, 1, 1}, + {1, 0, 1, 0}, + {1, 1, 0, 0} + }; + cout << Solution().matrixScore(A1) << endl; + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0863-All-Nodes-Distance-K-in-Binary-Tree/cpp-0863/CMakeLists.txt b/0501-1000/0863-All-Nodes-Distance-K-in-Binary-Tree/cpp-0863/CMakeLists.txt new file mode 100644 index 00000000..004fec0e --- /dev/null +++ b/0501-1000/0863-All-Nodes-Distance-K-in-Binary-Tree/cpp-0863/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0863) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main3.cpp) +add_executable(cpp_0863 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0863-All-Nodes-Distance-K-in-Binary-Tree/cpp-0863/main.cpp b/0501-1000/0863-All-Nodes-Distance-K-in-Binary-Tree/cpp-0863/main.cpp new file mode 100644 index 00000000..5d605329 --- /dev/null +++ b/0501-1000/0863-All-Nodes-Distance-K-in-Binary-Tree/cpp-0863/main.cpp @@ -0,0 +1,91 @@ +/// Source : https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/description/ +/// Author : liuyubobobo +/// Time : 2018-07-01 + +#include +#include +#include +#include + +using namespace std; + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +/// Construct a Graph and Using BFS +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector distanceK(TreeNode* root, TreeNode* target, int K) { + + if(K == 0) + return {target->val}; + + vector> g; + vector value; + + int targetIndex = -1; + constructG(g, value, root, -1, target, targetIndex); + assert(targetIndex >= 0); + + int n = value.size(); + assert(n == g.size()); + + vector res; + vector visited(n, false); + queue> q; + q.push(make_pair(targetIndex, 0)); + visited[targetIndex] = true; + while(!q.empty()){ + int curIndex = q.front().first; + int curDis = q.front().second; + q.pop(); + if(curDis == K) + res.push_back(value[curIndex]); + + for(int nextIndex: g[curIndex]) + if(!visited[nextIndex]){ + q.push(make_pair(nextIndex, curDis + 1)); + visited[nextIndex] = true; + } + } + return res; + } + +private: + void constructG(vector>& g, vector& value, + TreeNode* root, int parent, TreeNode* target, int& targetIndex){ + + value.push_back(root->val); + g.push_back(vector()); + int index = value.size() - 1; + + if(parent != -1) + g[index].push_back(parent); + + if(root->left != NULL){ + g[index].push_back(value.size()); + constructG(g, value, root->left, index, target, targetIndex); + } + + if(root->right != NULL){ + g[index].push_back(value.size()); + constructG(g, value, root->right, index, target, targetIndex); + } + + if(target == root) + targetIndex = index; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0863-All-Nodes-Distance-K-in-Binary-Tree/cpp-0863/main2.cpp b/0501-1000/0863-All-Nodes-Distance-K-in-Binary-Tree/cpp-0863/main2.cpp new file mode 100644 index 00000000..04e2b079 --- /dev/null +++ b/0501-1000/0863-All-Nodes-Distance-K-in-Binary-Tree/cpp-0863/main2.cpp @@ -0,0 +1,88 @@ +/// Source : https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/description/ +/// Author : liuyubobobo +/// Time : 2018-07-01 + +#include +#include +#include +#include +#include +#include + +using namespace std; + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +/// Construct a Graph and Using BFS +/// An mch easier way to construct the Graph :) +/// +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector distanceK(TreeNode* root, TreeNode* target, int K) { + + if(K == 0) + return {target->val}; + + unordered_map parents; + dfs(root, NULL, parents); + + vector res; + unordered_set visited; + + queue> q; + q.push(make_pair(target, 0)); + visited.insert(target); + while(!q.empty()){ + TreeNode* curNode = q.front().first; + int curDis = q.front().second; + q.pop(); + if(curDis == K) + res.push_back(curNode->val); + + unordered_map::iterator piter = parents.find(curNode); + if(piter != parents.end() && visited.find(piter->second) == visited.end()){ + q.push(make_pair(piter->second, curDis + 1)); + visited.insert(piter->second); + } + + if(curNode->left != NULL && visited.find(curNode->left) == visited.end()){ + q.push(make_pair(curNode->left, curDis + 1)); + visited.insert(curNode->left); + } + + if(curNode->right != NULL && visited.find(curNode->right) == visited.end()){ + q.push(make_pair(curNode->right, curDis + 1)); + visited.insert(curNode->right); + } + } + return res; + } + +private: + void dfs(TreeNode* root, TreeNode* parent, + unordered_map& parents){ + + if(root == NULL) + return; + + if(parent != NULL) + parents[root] = parent; + + dfs(root->left, root, parents); + dfs(root->right, root, parents); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0863-All-Nodes-Distance-K-in-Binary-Tree/cpp-0863/main3.cpp b/0501-1000/0863-All-Nodes-Distance-K-in-Binary-Tree/cpp-0863/main3.cpp new file mode 100644 index 00000000..093146d0 --- /dev/null +++ b/0501-1000/0863-All-Nodes-Distance-K-in-Binary-Tree/cpp-0863/main3.cpp @@ -0,0 +1,89 @@ +/// Source : https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/description/ +/// Author : liuyubobobo +/// Time : 2018-07-01 + +#include +#include +#include +#include +#include +#include + +using namespace std; + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +/// DFS and get the results during the recursion +/// +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector distanceK(TreeNode* root, TreeNode* target, int K) { + + if(K == 0) + return {target->val}; + + vector res; + assert(dfs(root, target, K, res) != -1); + return res; + } + +private: + int dfs(TreeNode* root, TreeNode* target, int K, vector& res){ + + if(root == NULL) + return -1; + + if(root == target){ + addRes(root, K, res); + return 0; + } + + int L = dfs(root->left, target, K, res); + if(L != -1){ + if(L + 1 == K) + addRes(root, 0, res); + else + addRes(root->right, K - L - 2, res); + return L + 1; + } + + int R = dfs(root->right, target, K, res); + if(R != -1){ + if(R + 1 == K) + addRes(root, 0, res); + else + addRes(root->left, K - R - 2, res); + return R + 1; + } + + return -1; + } + + void addRes(TreeNode* root, int dis, vector& res){ + + if(root == NULL) + return; + + if(dis == 0){ + res.push_back(root->val); + return; + } + + addRes(root->left, dis - 1, res); + addRes(root->right, dis - 1, res); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0864-Shortest-Path-to-Get-All-Keys/cpp-0864/CMakeLists.txt b/0501-1000/0864-Shortest-Path-to-Get-All-Keys/cpp-0864/CMakeLists.txt new file mode 100644 index 00000000..03d4a44d --- /dev/null +++ b/0501-1000/0864-Shortest-Path-to-Get-All-Keys/cpp-0864/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_D) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_D ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0864-Shortest-Path-to-Get-All-Keys/cpp-0864/main.cpp b/0501-1000/0864-Shortest-Path-to-Get-All-Keys/cpp-0864/main.cpp new file mode 100644 index 00000000..d9545fb0 --- /dev/null +++ b/0501-1000/0864-Shortest-Path-to-Get-All-Keys/cpp-0864/main.cpp @@ -0,0 +1,95 @@ +/// Source : https://leetcode.com/problems/shortest-path-to-get-all-keys/description/ +/// Author : liuyubobobo +/// Time : 2018-07-09 +/// Updated: 2022-11-09 + +#include +#include +#include +#include + +using namespace std; + +/// BFS +/// Time Complexity: O(R * C * (2 ^ key_cnt)) +/// Space Complexity:O(R * C * (2 ^ key_cnt)) +class Solution { + +private: + const int dirs[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; + +public: + int shortestPathAllKeys(vector& grid) { + + int R = grid.size(), C = grid[0].size(); + + int sx = -1, sy = -1, key_cnt = 0; + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++){ + if(grid[i][j] == '@'){ + sx = i, sy = j; + } + else if(islower(grid[i][j])){ + key_cnt ++; + } + } + assert(sx != -1 && sy != -1); + + vector> dis(R * C, vector((1 << key_cnt), -1)); + dis[sx * C + sy][0] = 0; + queue> q; + q.push({sx * C + sy, 0}); + while(!q.empty()){ + int cpos = q.front().first, key_state = q.front().second; + int cx = cpos / C, cy = cpos % C; + q.pop(); + + if(key_state == (1 << key_cnt) - 1) return dis[cpos][key_state]; + + for(int d = 0; d < 4; d ++){ + int nx = cx + dirs[d][0], ny = cy + dirs[d][1]; + if(!in_area(R, C, nx, ny) || grid[nx][ny] == '#') continue; + + if(isupper(grid[nx][ny]) && ((1 << (grid[nx][ny] - 'A')) & key_state) == 0) + continue; + + int npos = nx * C + ny; + int next_key_state = key_state; + if(islower(grid[nx][ny])) next_key_state |= (1 << (grid[nx][ny] - 'a')); + + if(dis[npos][next_key_state] != -1) continue; + + dis[npos][next_key_state] = dis[cpos][key_state] + 1; + q.push({npos, next_key_state}); + } + } + return -1; + } + +private: + bool in_area(int R, int C, int x, int y){ + return x >= 0 && x < R && y >= 0 && y < C; + } +}; + + +int main() { + + vector grid1 = {"@.a.#", + "###.#", + "b.A.B"}; + cout << Solution().shortestPathAllKeys(grid1) << endl; + // 8 + + vector grid2 = {"@..aA", + "..B#.", + "....b"}; + cout << Solution().shortestPathAllKeys(grid2) << endl; + // 6 + + vector grid3 = {"@Aa"}; + cout << Solution().shortestPathAllKeys(grid3) << endl; + // -1 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0865-Smallest-Subtree-with-all-the-Deepest-Nodes/cpp-0865/CMakeLists.txt b/0501-1000/0865-Smallest-Subtree-with-all-the-Deepest-Nodes/cpp-0865/CMakeLists.txt new file mode 100644 index 00000000..ae89e070 --- /dev/null +++ b/0501-1000/0865-Smallest-Subtree-with-all-the-Deepest-Nodes/cpp-0865/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(B) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(B ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0865-Smallest-Subtree-with-all-the-Deepest-Nodes/cpp-0865/main.cpp b/0501-1000/0865-Smallest-Subtree-with-all-the-Deepest-Nodes/cpp-0865/main.cpp new file mode 100644 index 00000000..15928be2 --- /dev/null +++ b/0501-1000/0865-Smallest-Subtree-with-all-the-Deepest-Nodes/cpp-0865/main.cpp @@ -0,0 +1,62 @@ +/// Source : https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/description/ +/// Author : liuyubobobo +/// Time : 2018-07-07 + +#include + +using namespace std; + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +/// Recursion +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +private: + int deepest; + TreeNode* res; + +public: + TreeNode* subtreeWithAllDeepest(TreeNode* root) { + + res = NULL; + deepest = -1; + getRes(root, 0); + return res; + } + +private: + int getRes(TreeNode* node, int depth){ + + if(node == NULL) + return depth - 1; + + if(depth > deepest){ + res = node; + deepest = depth; + } + + int dl = getRes(node->left, depth + 1); + int dr = getRes(node->right, depth + 1); + + if(dl == dr && dl == deepest) + res = node; + + return max(dl, dr); + } +}; + + +int main() { + + cout << Solution().subtreeWithAllDeepest(new TreeNode(1))->val << endl; + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0865-Smallest-Subtree-with-all-the-Deepest-Nodes/cpp-0865/main2.cpp b/0501-1000/0865-Smallest-Subtree-with-all-the-Deepest-Nodes/cpp-0865/main2.cpp new file mode 100644 index 00000000..73ad001d --- /dev/null +++ b/0501-1000/0865-Smallest-Subtree-with-all-the-Deepest-Nodes/cpp-0865/main2.cpp @@ -0,0 +1,76 @@ +/// Source : https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/description/ +/// Author : liuyubobobo +/// Time : 2018-07-07 + +#include +#include + +using namespace std; + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +/// Using a Two Phase Recursion +/// Which lead to a longer code, but more easy to understand:) +/// Besides, this method doesn't use any class member variables:) +/// +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +public: + TreeNode* subtreeWithAllDeepest(TreeNode* root) { + + unordered_map depth; + getDepth(root, 0, depth); + + int max_depth = -1; + for(const pair& p: depth) + max_depth = max(max_depth, p.second); + + return getRes(root, depth, max_depth); + } + +private: + void getDepth(TreeNode* node, int d, unordered_map& depth){ + + if(node == NULL) + return; + + depth[node] = d; + getDepth(node->left, d + 1, depth); + getDepth(node->right, d + 1, depth); + } + + TreeNode* getRes(TreeNode* node, unordered_map& depth, + int max_depth){ + + if(node == NULL) + return NULL; + + if(depth[node] == max_depth) + return node; + + TreeNode* L = getRes(node->left, depth, max_depth); + TreeNode* R = getRes(node->right, depth, max_depth); + + if(L && R) return node; + if(L) return L; + if(R) return R; + + return NULL; + } +}; + + +int main() { + + cout << Solution().subtreeWithAllDeepest(new TreeNode(1))->val << endl; + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0866-Prime-Palindrome/cpp-0866/CMakeLists.txt b/0501-1000/0866-Prime-Palindrome/cpp-0866/CMakeLists.txt new file mode 100644 index 00000000..62f938f1 --- /dev/null +++ b/0501-1000/0866-Prime-Palindrome/cpp-0866/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(C) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main4.cpp) +add_executable(C ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0866-Prime-Palindrome/cpp-0866/main.cpp b/0501-1000/0866-Prime-Palindrome/cpp-0866/main.cpp new file mode 100644 index 00000000..af8e473a --- /dev/null +++ b/0501-1000/0866-Prime-Palindrome/cpp-0866/main.cpp @@ -0,0 +1,77 @@ +/// Source : https://leetcode.com/problems/prime-palindrome/solution/ +/// Author : liuyubobobo +/// Time : 2018-07-07 + +#include +#include +#include + +using namespace std; + + +/// Recursively generate all prime palindrome number +/// Time Complexity: O(maxN) +/// Space Complexity: O(?)* +/// +/// * It is not even known whether there are infinitely many prime palindromes, +/// Basically, it's an open mathematical problem +/// But we can roughly say the time and space complexity is O(n) :) +class Solution { +public: + int primePalindrome(int N) { + + vector nums = {2, 3, 5, 7}; + for(int d = 2; d <= 8 ; d ++) + generatePalindromePrimes(d, nums); + nums.push_back(100030001); + sort(nums.begin(), nums.end()); + + return *lower_bound(nums.begin(), nums.end(), N); + } + +private: + void generatePalindromePrimes(int d, vector& nums){ + + string s(d, '-'); + generatePalindromePrimes(0, s, nums); + } + + void generatePalindromePrimes(int index, string& s, vector& nums){ + + if(s[index] != '-'){ + int num = atoi(s.c_str()); + if(isPrime(num)) + nums.push_back(num); + return; + } + + int start = 0; + if(index == 0) + start = 1; + for(int d = start ; d <= 9 ; d ++){ + s[index] = s[s.size() - 1 - index] = ('0' + d); + generatePalindromePrimes(index + 1, s, nums); + s[index] = s[s.size() - 1 - index] = '-'; + } + } + + bool isPrime(int x){ + + if(x % 2 == 0) + return false; + + for(int i = 3 ; i * i <= x ; i ++) + if(x % i == 0) + return false; + return true; + } +}; + +int main() { + + cout << Solution().primePalindrome(6) << endl; + cout << Solution().primePalindrome(8) << endl; + cout << Solution().primePalindrome(13) << endl; + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0866-Prime-Palindrome/cpp-0866/main2.cpp b/0501-1000/0866-Prime-Palindrome/cpp-0866/main2.cpp new file mode 100644 index 00000000..46d705cd --- /dev/null +++ b/0501-1000/0866-Prime-Palindrome/cpp-0866/main2.cpp @@ -0,0 +1,82 @@ +/// Source : https://leetcode.com/problems/prime-palindrome/solution/ +/// Author : liuyubobobo +/// Time : 2018-07-07 + +#include +#include +#include + +using namespace std; + + +/// Recursively generate all prime palindrome number +/// Ignore all even-digit palindrome number +/// Because, interestingly, all even-digit palindrome number is not prime, except 11 :) +/// The proof is in the official solution of this problem: +/// https://leetcode.com/problems/prime-palindrome/solution/ +/// +/// Time Complexity: O(maxN) +/// Space Complexity: O(?)* +/// +/// * It is not even known whether there are infinitely many prime palindromes, +/// Basically, it's an open mathematical problem +/// But we can roughly say the time and space complexity is O(n) :) +class Solution { +public: + int primePalindrome(int N) { + + vector nums = {2, 3, 5, 7, 11}; + for(int d = 3; d <= 8 ; d += 2) + generatePalindromePrimes(d, nums); + nums.push_back(100030001); + sort(nums.begin(), nums.end()); + + return *lower_bound(nums.begin(), nums.end(), N); + } + +private: + void generatePalindromePrimes(int d, vector& nums){ + + string s(d, '-'); + generatePalindromePrimes(0, s, nums); + } + + void generatePalindromePrimes(int index, string& s, vector& nums){ + + if(s[index] != '-'){ + int num = atoi(s.c_str()); + if(isPrime(num)) + nums.push_back(num); + return; + } + + int start = 0; + if(index == 0) + start = 1; + for(int d = start ; d <= 9 ; d ++){ + s[index] = s[s.size() - 1 - index] = ('0' + d); + generatePalindromePrimes(index + 1, s, nums); + s[index] = s[s.size() - 1 - index] = '-'; + } + } + + bool isPrime(int x){ + + if(x % 2 == 0) + return false; + + for(int i = 3 ; i * i <= x ; i ++) + if(x % i == 0) + return false; + return true; + } +}; + +int main() { + + cout << Solution().primePalindrome(6) << endl; + cout << Solution().primePalindrome(8) << endl; + cout << Solution().primePalindrome(13) << endl; + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0866-Prime-Palindrome/cpp-0866/main3.cpp b/0501-1000/0866-Prime-Palindrome/cpp-0866/main3.cpp new file mode 100644 index 00000000..3afa83cf --- /dev/null +++ b/0501-1000/0866-Prime-Palindrome/cpp-0866/main3.cpp @@ -0,0 +1,91 @@ +/// Source : https://leetcode.com/problems/prime-palindrome/solution/ +/// Author : liuyubobobo +/// Time : 2018-07-07 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// Generate all prime palindrome number according to "root" +/// We can based on number X = abc, +/// generate odd-digit palindrome P1 = abcba, and even-digit palindrome P1 = abccba, +/// X is the root of P1 and P2 +/// +/// We can ignore all even-digit palindrome number in this problem, +/// Since, interestingly, all even-digit palindrome number is not prime, except 11 :) +/// The proof is in the official solution of this problem: +/// https://leetcode.com/problems/prime-palindrome/solution/ +/// +/// Time Complexity: O(maxN) +/// Space Complexity: O(N)* +/// +/// * It is not even known whether there are infinitely many prime palindromes, +/// Basically, it's an open mathematical problem +/// But we can roughly say the time and space complexity is O(n) :) +class Solution { +public: + int primePalindrome(int N) { + + vector nums = {2, 3, 5, 7, 11}; + for(int d = 3; d <= 8 ; d += 2) + generatePalindromePrimes(d, nums); + nums.push_back(100030001); + sort(nums.begin(), nums.end()); + + return *lower_bound(nums.begin(), nums.end(), N); + } + +private: + void generatePalindromePrimes(int d, vector& nums){ + + assert(d % 2 == 1); + int start = (int)pow(10, d / 2); + int limit = (int)pow(10, d / 2 + 1); + for(int root = start; root < limit; root ++){ + int num = generatePalindrome(root); + if(isPrime(num)) + nums.push_back(num); + } + return; + } + + int generatePalindrome(int root){ + + int num = root; + vector nums; + while(num){ + nums.push_back(num % 10); + num /= 10; + } + + int res = root; + for(int i = 1 ; i < nums.size() ; i ++) + res = res * 10 + nums[i]; + return res; + } + + bool isPrime(int x){ + + if(x % 2 == 0) + return false; + + for(int i = 3 ; i * i <= x ; i ++) + if(x % i == 0) + return false; + return true; + } +}; + +int main() { + + cout << Solution().primePalindrome(6) << endl; + cout << Solution().primePalindrome(8) << endl; + cout << Solution().primePalindrome(13) << endl; + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0866-Prime-Palindrome/cpp-0866/main4.cpp b/0501-1000/0866-Prime-Palindrome/cpp-0866/main4.cpp new file mode 100644 index 00000000..acea40a1 --- /dev/null +++ b/0501-1000/0866-Prime-Palindrome/cpp-0866/main4.cpp @@ -0,0 +1,99 @@ +/// Source : https://leetcode.com/problems/prime-palindrome/solution/ +/// Author : liuyubobobo +/// Time : 2018-07-07 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// Generate all prime palindrome number according to "root" +/// We can based on number X = abc, +/// generate odd-digit palindrome P1 = abcba, and even-digit palindrome P1 = abccba, +/// X is the root of P1 and P2 +/// +/// Since in this process, we generate palindrome number from small to large, +/// We can terminate the process whenever we found the first result >= N :) +/// +/// We can ignore all even-digit palindrome number in this problem, +/// Since, interestingly, all even-digit palindrome number is not prime, except 11 :) +/// The proof is in the official solution of this problem: +/// https://leetcode.com/problems/prime-palindrome/solution/ +/// +/// Time Complexity: O(maxN) +/// Space Complexity: O(N)* +/// +/// * It is not even known whether there are infinitely many prime palindromes, +/// Basically, it's an open mathematical problem +/// But we can roughly say the time and space complexity is O(n) :) +class Solution { +public: + int primePalindrome(int N) { + + vector nums = {2, 3, 5, 7, 11}; + if(N <= 11) + return *lower_bound(nums.begin(), nums.end(), N); + + int res = 0; + for(int d = 3; d <= 9 ; d += 2) { + res = generatePalindromePrimes(d, N); + if(res) + return res; + } + assert(false); + return -1; + } + +private: + int generatePalindromePrimes(int d, int N){ + + assert(d % 2 == 1); + int start = (int)pow(10, d / 2); + int limit = (int)pow(10, d / 2 + 1); + for(int root = start; root < limit; root ++){ + int num = generatePalindrome(root); + if(num >= N && isPrime(num)) + return num; + } + return 0; + } + + int generatePalindrome(int root){ + + int num = root; + vector nums; + while(num){ + nums.push_back(num % 10); + num /= 10; + } + + int res = root; + for(int i = 1 ; i < nums.size() ; i ++) + res = res * 10 + nums[i]; + return res; + } + + bool isPrime(int x){ + + if(x % 2 == 0) + return false; + + for(int i = 3 ; i * i <= x ; i ++) + if(x % i == 0) + return false; + return true; + } +}; + +int main() { + + cout << Solution().primePalindrome(6) << endl; + cout << Solution().primePalindrome(8) << endl; + cout << Solution().primePalindrome(13) << endl; + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0867-Transpose-Matrix/cpp-0867/CMakeLists.txt b/0501-1000/0867-Transpose-Matrix/cpp-0867/CMakeLists.txt new file mode 100644 index 00000000..b3fafe13 --- /dev/null +++ b/0501-1000/0867-Transpose-Matrix/cpp-0867/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(A) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(A ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0867-Transpose-Matrix/cpp-0867/main.cpp b/0501-1000/0867-Transpose-Matrix/cpp-0867/main.cpp new file mode 100644 index 00000000..4dd23425 --- /dev/null +++ b/0501-1000/0867-Transpose-Matrix/cpp-0867/main.cpp @@ -0,0 +1,32 @@ +/// Source : https://leetcode.com/problems/transpose-matrix/description/ +/// Author : liuyubobobo +/// Time : 2018-07-07 + +#include +#include + +using namespace std; + +/// Ad-Hoc +/// Time Complexity: O(m*n) +/// Space Complexity: O(1) +class Solution { +public: + vector> transpose(vector>& A) { + + int m = A.size(); + int n = A[0].size(); + + vector> res(n, vector(m, 0)); + for(int i = 0 ; i < m ; i ++) + for(int j = 0 ; j < n ; j ++) + res[j][i] = A[i][j]; + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0868-Binary-Gap/cpp-0868/CMakeLists.txt b/0501-1000/0868-Binary-Gap/cpp-0868/CMakeLists.txt new file mode 100644 index 00000000..b3fafe13 --- /dev/null +++ b/0501-1000/0868-Binary-Gap/cpp-0868/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(A) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(A ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0868-Binary-Gap/cpp-0868/main.cpp b/0501-1000/0868-Binary-Gap/cpp-0868/main.cpp new file mode 100644 index 00000000..fe4770fa --- /dev/null +++ b/0501-1000/0868-Binary-Gap/cpp-0868/main.cpp @@ -0,0 +1,44 @@ +/// Source : https://leetcode.com/problems/binary-gap/description/ +/// Author : liuyubobobo +/// Time : 2018-07-14 + +#include +#include + +using namespace std; + + +/// Store all the '1''s index +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int binaryGap(int N) { + + vector indexes; + int index = 0; + while(N){ + if(N & 1) + indexes.push_back(index); + index ++; + N >>= 1; + } + + int res = 0; + for(int i = 1 ; i < indexes.size() ; i ++) + res = max(res, indexes[i] - indexes[i - 1]); + + return res; + } +}; + + +int main() { + + cout << Solution().binaryGap(22) << endl; + cout << Solution().binaryGap(5) << endl; + cout << Solution().binaryGap(6) << endl; + cout << Solution().binaryGap(8) << endl; + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0868-Binary-Gap/cpp-0868/main2.cpp b/0501-1000/0868-Binary-Gap/cpp-0868/main2.cpp new file mode 100644 index 00000000..5781957f --- /dev/null +++ b/0501-1000/0868-Binary-Gap/cpp-0868/main2.cpp @@ -0,0 +1,44 @@ +/// Source : https://leetcode.com/problems/binary-gap/description/ +/// Author : liuyubobobo +/// Time : 2018-07-14 + +#include + +using namespace std; + + +/// One Pass without store all the 'a''s index +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int binaryGap(int N) { + + int last = -1; + int res = 0, index = 0; + while(N){ + int bit = N & 1; + if(bit){ + if(last != -1) + res = max(res, index - last); + last = index; + } + + index ++; + N >>= 1; + } + + return res; + } +}; + + +int main() { + + cout << Solution().binaryGap(22) << endl; + cout << Solution().binaryGap(5) << endl; + cout << Solution().binaryGap(6) << endl; + cout << Solution().binaryGap(8) << endl; + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0869-Reordered-Power-of-2/cpp-0869/CMakeLists.txt b/0501-1000/0869-Reordered-Power-of-2/cpp-0869/CMakeLists.txt new file mode 100644 index 00000000..0d12d141 --- /dev/null +++ b/0501-1000/0869-Reordered-Power-of-2/cpp-0869/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(B) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main3.cpp) +add_executable(B ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0869-Reordered-Power-of-2/cpp-0869/main.cpp b/0501-1000/0869-Reordered-Power-of-2/cpp-0869/main.cpp new file mode 100644 index 00000000..4a0dda6d --- /dev/null +++ b/0501-1000/0869-Reordered-Power-of-2/cpp-0869/main.cpp @@ -0,0 +1,73 @@ +/// Source : https://leetcode.com/problems/reordered-power-of-2/description/ +/// Author : liuyubobobo +/// Time : 2018-07-14 + +#include +#include +#include + +using namespace std; + + +/// Permutation all possibility and check +/// Using next_permutation:) +/// +/// Time Complexity: O((logN)! * logN) +/// Space Complexity: O(logN) +class Solution { +public: + bool reorderedPowerOf2(int N) { + + vector digits = getDigits(N); + sort(digits.begin(), digits.end()); + do{ + if(digits[0] == 0) + continue; + if(isPower2(digits)) + return true; + }while(next_permutation(digits.begin(), digits.end())); + + return false; + } + +private: + bool isPower2(const vector& digits){ + + int num = 0; + for(int digit: digits) + num = num * 10 + digit; + return isPower2(num); + } + + bool isPower2(int x){ + for(int i = 0 ; i <= 30 ; i ++) + if(x == (1< getDigits(int N){ + vector res; + while(N){ + res.push_back(N % 10); + N /= 10; + } + return res; + } +}; + + +void print_bool(bool res){ + cout << (res ? "True" : "False") << endl; +} + +int main() { + + print_bool(Solution().reorderedPowerOf2(1)); + print_bool(Solution().reorderedPowerOf2(10)); + print_bool(Solution().reorderedPowerOf2(16)); + print_bool(Solution().reorderedPowerOf2(24)); + print_bool(Solution().reorderedPowerOf2(46)); + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0869-Reordered-Power-of-2/cpp-0869/main2.cpp b/0501-1000/0869-Reordered-Power-of-2/cpp-0869/main2.cpp new file mode 100644 index 00000000..e52d4ba3 --- /dev/null +++ b/0501-1000/0869-Reordered-Power-of-2/cpp-0869/main2.cpp @@ -0,0 +1,79 @@ +/// Source : https://leetcode.com/problems/reordered-power-of-2/description/ +/// Author : liuyubobobo +/// Time : 2018-07-14 + +#include +#include +#include + +using namespace std; + +/// Permutation all possibility and check +/// Generate permutation by myself and skip the first zero case quickly +/// +/// Time Complexity: O((logN)! * logN) +/// Space Complexity: O(logN) +class Solution { +public: + bool reorderedPowerOf2(int N) { + + vector digits = getDigits(N); + return generatePermutation(digits, 0); + } + +private: + bool generatePermutation(vector& digits, int index){ + + if(index == digits.size()) + return isPower2(digits); + + for(int i = index ; i < digits.size() ; i ++) + if(index || digits[i]){ + swap(digits[index], digits[i]); + if(generatePermutation(digits, index + 1)) + return true; + swap(digits[index], digits[i]); + } + return false; + } + + bool isPower2(const vector& digits){ + + int num = 0; + for(int digit: digits) + num = num * 10 + digit; + return isPower2(num); + } + + bool isPower2(int x){ + for(int i = 0 ; i <= 30 ; i ++) + if(x == (1< getDigits(int N){ + vector res; + while(N){ + res.push_back(N % 10); + N /= 10; + } + return res; + } +}; + + +void print_bool(bool res){ + cout << (res ? "True" : "False") << endl; +} + +int main() { + + print_bool(Solution().reorderedPowerOf2(1)); + print_bool(Solution().reorderedPowerOf2(10)); + print_bool(Solution().reorderedPowerOf2(16)); + print_bool(Solution().reorderedPowerOf2(24)); + print_bool(Solution().reorderedPowerOf2(46)); + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0869-Reordered-Power-of-2/cpp-0869/main3.cpp b/0501-1000/0869-Reordered-Power-of-2/cpp-0869/main3.cpp new file mode 100644 index 00000000..b1033f35 --- /dev/null +++ b/0501-1000/0869-Reordered-Power-of-2/cpp-0869/main3.cpp @@ -0,0 +1,51 @@ +/// Source : https://leetcode.com/problems/reordered-power-of-2/description/ +/// Author : liuyubobobo +/// Time : 2018-07-14 + +#include +#include +#include + +using namespace std; + +/// Counting the digit +/// +/// Time Complexity: O((logN)^2) +/// Space Complexity: O(logN) +class Solution { +public: + bool reorderedPowerOf2(int N) { + + vector freq = getDigitsFreq(N); + for(int i = 0 ; i <= 30 ; i ++) + if(freq == getDigitsFreq(1< getDigitsFreq(int N){ + vector res(10, 0); + while(N){ + res[N % 10] ++; + N /= 10; + } + return res; + } +}; + + +void print_bool(bool res){ + cout << (res ? "True" : "False") << endl; +} + +int main() { + + print_bool(Solution().reorderedPowerOf2(1)); + print_bool(Solution().reorderedPowerOf2(10)); + print_bool(Solution().reorderedPowerOf2(16)); + print_bool(Solution().reorderedPowerOf2(24)); + print_bool(Solution().reorderedPowerOf2(46)); + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0870-Advantage-Shuffle/cpp-0870/CMakeLists.txt b/0501-1000/0870-Advantage-Shuffle/cpp-0870/CMakeLists.txt new file mode 100644 index 00000000..85e27b1b --- /dev/null +++ b/0501-1000/0870-Advantage-Shuffle/cpp-0870/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(C) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(C ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0870-Advantage-Shuffle/cpp-0870/main.cpp b/0501-1000/0870-Advantage-Shuffle/cpp-0870/main.cpp new file mode 100644 index 00000000..81464333 --- /dev/null +++ b/0501-1000/0870-Advantage-Shuffle/cpp-0870/main.cpp @@ -0,0 +1,73 @@ +/// Source : https://leetcode.com/problems/advantage-shuffle/description/ +/// Author : liuyubobobo +/// Time : 2018-07-14 + +#include +#include +#include +#include + +using namespace std; + + +/// Greedy +/// Using HashMap and Set to store elements in A +/// +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + vector advantageCount(vector& A, vector& B) { + + unordered_map Afreq; + set Auniq; + for(int a: A){ + Afreq[a] ++; + Auniq.insert(a); + } + + vector res(A.size(), -1); + for(int i = 0 ; i < B.size() ; i ++){ + set::iterator iter = Auniq.upper_bound(B[i]); + if(iter != Auniq.end()){ + res[i] = *iter; + Afreq[*iter] --; + if(Afreq[*iter] == 0){ + Afreq.erase(*iter); + Auniq.erase(*iter); + } + } + } + + for(int i = 0 ; i < res.size() ; i ++) + if(res[i] == -1){ + int num = Afreq.begin()->first; + res[i] = num; + Afreq[num] --; + if(Afreq[num] == 0) + Afreq.erase(num); + } + + return res; + } +}; + + +void print_vec(const vector& vec){ + for(int e: vec) + cout << e << " "; + cout << endl; +} + +int main() { + + vector A1 = {2, 7, 11, 15}; + vector B1 = {1, 10, 4, 11}; + print_vec(Solution().advantageCount(A1, B1)); + + vector A2 = {12, 24, 8, 32}; + vector B2 = {13, 25, 32, 11}; + print_vec(Solution().advantageCount(A2, B2)); + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0871-Minimum-Number-of-Refueling-Stops/cpp-0871/CMakeLists.txt b/0501-1000/0871-Minimum-Number-of-Refueling-Stops/cpp-0871/CMakeLists.txt new file mode 100644 index 00000000..4eb65aca --- /dev/null +++ b/0501-1000/0871-Minimum-Number-of-Refueling-Stops/cpp-0871/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(D) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main4.cpp) +add_executable(D ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0871-Minimum-Number-of-Refueling-Stops/cpp-0871/main.cpp b/0501-1000/0871-Minimum-Number-of-Refueling-Stops/cpp-0871/main.cpp new file mode 100644 index 00000000..9feaf711 --- /dev/null +++ b/0501-1000/0871-Minimum-Number-of-Refueling-Stops/cpp-0871/main.cpp @@ -0,0 +1,71 @@ +/// Source : https://leetcode.com/problems/minimum-number-of-refueling-stops/description/ +/// Author : liuyubobobo +/// Time : 2018-08-05 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(n^3) +/// Space Complexity: O(n^2) +class Solution { + +public: + int minRefuelStops(int target, int startFuel, vector>& stations) { + + if(startFuel >= target) + return 0; + + int n = stations.size(); + vector> dp(n + 1, vector(n, 0)); + for(int i = n - 1; i >= 0; i --) + if(startFuel >= stations[i][0]){ + dp[1][i] = startFuel + stations[i][1]; + if(dp[1][i] >= target) + return 1; + } + + for(int k = 2; k <= n; k ++){ + for(int last = k - 2; last < n; last ++) + for(int cur = last + 1; cur < n ; cur ++) + if(dp[k-1][last] >= stations[cur][0]){ + dp[k][cur] = max(dp[k][cur], dp[k-1][last] + stations[cur][1]); + if(dp[k][cur] >= target) + return k; + } + else + break; + } + return -1; + } +}; + + +int main() { + + int target1 = 1, startFuel1 = 1; + vector> stations1; + cout << Solution().minRefuelStops(target1, startFuel1, stations1) << endl; + // 0 + + int target2 = 100, startFuel2 = 1; + vector> stations2 = {{10, 100}}; + cout << Solution().minRefuelStops(target2, startFuel2, stations2) << endl; + // -1 + + int target3 = 100, startFuel3 = 10; + vector> stations3 = {{10, 60}, {20, 30}, {30, 30}, {60, 40}}; + cout << Solution().minRefuelStops(target3, startFuel3, stations3) << endl; + // 2 + + int target4 = 1000, startFuel4 = 83; + vector> stations4 = {{25, 27}, {36, 187}, {140, 186}, {378, 6}, {492, 202}, + {517, 89}, {579, 234}, {673, 86}, {808, 53}, {954, 49}}; + cout << Solution().minRefuelStops(target4, startFuel4, stations4) << endl; + // -1 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0871-Minimum-Number-of-Refueling-Stops/cpp-0871/main2.cpp b/0501-1000/0871-Minimum-Number-of-Refueling-Stops/cpp-0871/main2.cpp new file mode 100644 index 00000000..cafdbb17 --- /dev/null +++ b/0501-1000/0871-Minimum-Number-of-Refueling-Stops/cpp-0871/main2.cpp @@ -0,0 +1,71 @@ +/// Source : https://leetcode.com/problems/minimum-number-of-refueling-stops/description/ +/// Author : liuyubobobo +/// Time : 2018-08-05 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(n^3) +/// Space Complexity: O(n) +class Solution { + +public: + int minRefuelStops(int target, int startFuel, vector>& stations) { + + if(startFuel >= target) + return 0; + + int n = stations.size(); + vector> dp(2, vector(n, 0)); + for(int i = n - 1; i >= 0; i --) + if(startFuel >= stations[i][0]){ + dp[1][i] = startFuel + stations[i][1]; + if(dp[1][i] >= target) + return 1; + } + + for(int k = 2; k <= n; k ++){ + for(int last = k - 2; last < n; last ++) + for(int cur = last + 1; cur < n ; cur ++) + if(dp[(k-1)&1][last] >= stations[cur][0]){ + dp[k&1][cur] = max(dp[k&1][cur], dp[(k-1)&1][last] + stations[cur][1]); + if(dp[k&1][cur] >= target) + return k; + } + else + break; + } + return -1; + } +}; + + +int main() { + + int target1 = 1, startFuel1 = 1; + vector> stations1; + cout << Solution().minRefuelStops(target1, startFuel1, stations1) << endl; + // 0 + + int target2 = 100, startFuel2 = 1; + vector> stations2 = {{10, 100}}; + cout << Solution().minRefuelStops(target2, startFuel2, stations2) << endl; + // -1 + + int target3 = 100, startFuel3 = 10; + vector> stations3 = {{10, 60}, {20, 30}, {30, 30}, {60, 40}}; + cout << Solution().minRefuelStops(target3, startFuel3, stations3) << endl; + // 2 + + int target4 = 1000, startFuel4 = 83; + vector> stations4 = {{25, 27}, {36, 187}, {140, 186}, {378, 6}, {492, 202}, + {517, 89}, {579, 234}, {673, 86}, {808, 53}, {954, 49}}; + cout << Solution().minRefuelStops(target4, startFuel4, stations4) << endl; + // -1 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0871-Minimum-Number-of-Refueling-Stops/cpp-0871/main3.cpp b/0501-1000/0871-Minimum-Number-of-Refueling-Stops/cpp-0871/main3.cpp new file mode 100644 index 00000000..6171a123 --- /dev/null +++ b/0501-1000/0871-Minimum-Number-of-Refueling-Stops/cpp-0871/main3.cpp @@ -0,0 +1,64 @@ +/// Source : https://leetcode.com/problems/minimum-number-of-refueling-stops/description/ +/// Author : liuyubobobo +/// Time : 2018-08-05 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { + +public: + int minRefuelStops(int target, int startFuel, vector>& stations) { + + if(startFuel >= target) + return 0; + + int n = stations.size(); + vector dp(n + 1, 0); + dp[0] = startFuel; + + for(int i = 0 ; i < n ; i ++) + for(int t = i ; t >= 0 ; t --) + if(dp[t] >= stations[i][0]){ + dp[t + 1] = max(dp[t + 1], dp[t] + stations[i][1]); + } + + for(int t = 0; t <= n; t ++) + if(dp[t] >= target) + return t; + return -1; + } +}; + + +int main() { + + int target1 = 1, startFuel1 = 1; + vector> stations1; + cout << Solution().minRefuelStops(target1, startFuel1, stations1) << endl; + // 0 + + int target2 = 100, startFuel2 = 1; + vector> stations2 = {{10, 100}}; + cout << Solution().minRefuelStops(target2, startFuel2, stations2) << endl; + // -1 + + int target3 = 100, startFuel3 = 10; + vector> stations3 = {{10, 60}, {20, 30}, {30, 30}, {60, 40}}; + cout << Solution().minRefuelStops(target3, startFuel3, stations3) << endl; + // 2 + + int target4 = 1000, startFuel4 = 83; + vector> stations4 = {{25, 27}, {36, 187}, {140, 186}, {378, 6}, {492, 202}, + {517, 89}, {579, 234}, {673, 86}, {808, 53}, {954, 49}}; + cout << Solution().minRefuelStops(target4, startFuel4, stations4) << endl; + // -1 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0871-Minimum-Number-of-Refueling-Stops/cpp-0871/main4.cpp b/0501-1000/0871-Minimum-Number-of-Refueling-Stops/cpp-0871/main4.cpp new file mode 100644 index 00000000..7c7d45fc --- /dev/null +++ b/0501-1000/0871-Minimum-Number-of-Refueling-Stops/cpp-0871/main4.cpp @@ -0,0 +1,62 @@ +/// Source : https://leetcode.com/problems/minimum-number-of-refueling-stops/description/ +/// Author : liuyubobobo +/// Time : 2020-05-10 + +#include +#include +#include + +using namespace std; + + +/// Greedy using PQ +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { + +public: + int minRefuelStops(int target, int startFuel, vector>& stations) { + + if(startFuel >= target) + return 0; + + int n = stations.size(); + priority_queue pq; + int i = 0, cur = startFuel, res = 0; + while(cur < target){ + for(; i < n && cur >= stations[i][0]; i ++) + pq.push(stations[i][1]); + + if(!pq.empty()) cur += pq.top(), pq.pop(), res ++; + else break; + } + return cur >= target ? res : -1; + } +}; + + +int main() { + + int target1 = 1, startFuel1 = 1; + vector> stations1; + cout << Solution().minRefuelStops(target1, startFuel1, stations1) << endl; + // 0 + + int target2 = 100, startFuel2 = 1; + vector> stations2 = {{10, 100}}; + cout << Solution().minRefuelStops(target2, startFuel2, stations2) << endl; + // -1 + + int target3 = 100, startFuel3 = 10; + vector> stations3 = {{10, 60}, {20, 30}, {30, 30}, {60, 40}}; + cout << Solution().minRefuelStops(target3, startFuel3, stations3) << endl; + // 2 + + int target4 = 1000, startFuel4 = 83; + vector> stations4 = {{25, 27}, {36, 187}, {140, 186}, {378, 6}, {492, 202}, + {517, 89}, {579, 234}, {673, 86}, {808, 53}, {954, 49}}; + cout << Solution().minRefuelStops(target4, startFuel4, stations4) << endl; + // -1 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0872-Leaf-Similar-Trees/cpp-0872/CMakeLists.txt b/0501-1000/0872-Leaf-Similar-Trees/cpp-0872/CMakeLists.txt new file mode 100644 index 00000000..b3fafe13 --- /dev/null +++ b/0501-1000/0872-Leaf-Similar-Trees/cpp-0872/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(A) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(A ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0872-Leaf-Similar-Trees/cpp-0872/main.cpp b/0501-1000/0872-Leaf-Similar-Trees/cpp-0872/main.cpp new file mode 100644 index 00000000..cedb35e0 --- /dev/null +++ b/0501-1000/0872-Leaf-Similar-Trees/cpp-0872/main.cpp @@ -0,0 +1,58 @@ +/// Source : https://leetcode.com/problems/leaf-similar-trees/description/ +/// Author : liuyubobobo +/// Time : 2018-07-21 + +#include +#include + +using namespace std; + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + + +/// DFS +/// Time Complexity: O(T1 + T2) +/// Space Complexity: O(T1 + T2) +class Solution { + +public: + bool leafSimilar(TreeNode* root1, TreeNode* root2) { + + vector leaf_seq1; + get_leaf_sequence(root1, leaf_seq1); + + vector leaf_seq2; + get_leaf_sequence(root2, leaf_seq2); + + return leaf_seq1 == leaf_seq2; + } + +private: + void get_leaf_sequence(TreeNode* node, vector& res){ + + if(node->left == NULL && node->right == NULL){ + res.push_back(node->val); + return; + } + + if(node->left) + get_leaf_sequence(node->left, res); + + if(node->right) + get_leaf_sequence(node->right, res); + + return; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0790-Domino-and-Tromino-Tiling/cpp-0790/CMakeLists.txt b/0501-1000/0873-Length-of-Longest-Fibonacci-Subsequence/cpp-0873/CMakeLists.txt similarity index 100% rename from 0790-Domino-and-Tromino-Tiling/cpp-0790/CMakeLists.txt rename to 0501-1000/0873-Length-of-Longest-Fibonacci-Subsequence/cpp-0873/CMakeLists.txt diff --git a/0501-1000/0873-Length-of-Longest-Fibonacci-Subsequence/cpp-0873/main.cpp b/0501-1000/0873-Length-of-Longest-Fibonacci-Subsequence/cpp-0873/main.cpp new file mode 100644 index 00000000..b6e94b6e --- /dev/null +++ b/0501-1000/0873-Length-of-Longest-Fibonacci-Subsequence/cpp-0873/main.cpp @@ -0,0 +1,61 @@ +/// Source : https://leetcode.com/problems/length-of-longest-fibonacci-subsequence/description/ +/// Author : liuyubobobo +/// Time : 2018-07-21 + +#include +#include +#include + +using namespace std; + + +/// Brute Force iterate the first 2 elements in the fibonacci sequence +/// Since the number will grow exponentially, there will be at most 43 items to check +/// Time Complexity: O(n^2*log(maxA)) +/// Space Complexity: O(A) +class Solution { + +public: + int lenLongestFibSubseq(vector& A) { + + unordered_set nums; + for(int a: A) + nums.insert(a); + + int res = 2; + for(int i = 0 ; i < A.size() ; i ++) + for(int j = i + 1; j < A.size() ; j ++){ + int len = 2; + int a = A[i], b = A[j]; + while(true){ + int next = a + b; + if(next > 1e9) + break; + if(nums.find(next) == nums.end()) + break; + + a = b, b = next, len ++; + } + res = max(res, len); + } + return res > 2 ? res : 0; + } +}; + + +int main() { + + vector nums1 = {1, 2, 3, 4, 5, 6, 7, 8}; + cout << Solution().lenLongestFibSubseq(nums1) << endl; + // 5 + + vector nums2 = {1, 3, 7, 11, 12, 14, 18}; + cout << Solution().lenLongestFibSubseq(nums2) << endl; + // 3 + + vector nums3 = {2, 4, 5, 6, 7, 8, 11, 13, 14, 15, 21, 22, 34}; + cout << Solution().lenLongestFibSubseq(nums3) << endl; + // 5 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0873-Length-of-Longest-Fibonacci-Subsequence/cpp-0873/main2.cpp b/0501-1000/0873-Length-of-Longest-Fibonacci-Subsequence/cpp-0873/main2.cpp new file mode 100644 index 00000000..466e552d --- /dev/null +++ b/0501-1000/0873-Length-of-Longest-Fibonacci-Subsequence/cpp-0873/main2.cpp @@ -0,0 +1,65 @@ +/// Source : https://leetcode.com/problems/length-of-longest-fibonacci-subsequence/description/ +/// Author : liuyubobobo +/// Time : 2018-07-21 + +#include +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(n^2) +/// Space Complexity: O(n^2) +class Solution { + +private: + int n; + unordered_map num_index; + +public: + int lenLongestFibSubseq(vector& A) { + + n = A.size(); + num_index.clear(); + for(int i = 0 ; i < A.size() ; i ++) + num_index[A[i]] = i; + + vector> dp(n, vector(n, -1)); + int res = 0; + for(int i = 1; i < n; i ++) + for(int j = i + 1; j < n ; j ++) + res = max(res, getRes(A, i, j, dp)); + return res == 2 ? 0 : res; + } + +private: + int getRes(const vector& A, int a, int b, vector>& dp){ + + if(dp[a][b] != -1) + return dp[a][b]; + + if(A[b] - A[a] < A[a] && num_index.find(A[b] - A[a]) != num_index.end()) + return dp[a][b] = 1 + getRes(A, num_index[A[b] - A[a]], a, dp); + return 2; + } +}; + + +int main() { + + vector nums1 = {1, 2, 3, 4, 5, 6, 7, 8}; + cout << Solution().lenLongestFibSubseq(nums1) << endl; + // 5 + + vector nums2 = {1, 3, 7, 11, 12, 14, 18}; + cout << Solution().lenLongestFibSubseq(nums2) << endl; + // 3 + + vector nums3 = {2, 4, 5, 6, 7, 8, 11, 13, 14, 15, 21, 22, 34}; + cout << Solution().lenLongestFibSubseq(nums3) << endl; + // 5 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0873-Length-of-Longest-Fibonacci-Subsequence/cpp-0873/main3.cpp b/0501-1000/0873-Length-of-Longest-Fibonacci-Subsequence/cpp-0873/main3.cpp new file mode 100644 index 00000000..ce9026ae --- /dev/null +++ b/0501-1000/0873-Length-of-Longest-Fibonacci-Subsequence/cpp-0873/main3.cpp @@ -0,0 +1,60 @@ +/// Source : https://leetcode.com/problems/length-of-longest-fibonacci-subsequence/description/ +/// Author : liuyubobobo +/// Time : 2018-07-21 +#include +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(n^2) +/// Space Complexity: O(n^2) +class Solution { + +public: + int lenLongestFibSubseq(vector& A) { + + int n = A.size(); + unordered_map num_index; + for(int i = 0 ; i < A.size() ; i ++) + num_index[A[i]] = i; + + vector> dp(n, vector(n, 2)); + int res = 0; + + for(int j = 2; j < n ; j ++) + if(A[0] + A[1] == A[j]){ + dp[1][j] = 3; + res = max(res, 3); + } + + for(int i = 2; i < n ; i ++) + for(int j = i + 1; j < n ; j ++){ + if(A[j] - A[i] < A[i] && num_index.find(A[j] - A[i]) != num_index.end()) { + dp[i][j] = dp[num_index[A[j] - A[i]]][i] + 1; + res = max(res, dp[i][j]); + } + } + return res; + } +}; + + +int main() { + + vector nums1 = {1, 2, 3, 4, 5, 6, 7, 8}; + cout << Solution().lenLongestFibSubseq(nums1) << endl; + // 5 + + vector nums2 = {1, 3, 7, 11, 12, 14, 18}; + cout << Solution().lenLongestFibSubseq(nums2) << endl; + // 3 + + vector nums3 = {2, 4, 5, 6, 7, 8, 11, 13, 14, 15, 21, 22, 34}; + cout << Solution().lenLongestFibSubseq(nums3) << endl; + // 5 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0874-Walking-Robot-Simulation/cpp-0874/CMakeLists.txt b/0501-1000/0874-Walking-Robot-Simulation/cpp-0874/CMakeLists.txt new file mode 100644 index 00000000..08335525 --- /dev/null +++ b/0501-1000/0874-Walking-Robot-Simulation/cpp-0874/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(B) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main2.cpp) +add_executable(B ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0874-Walking-Robot-Simulation/cpp-0874/main.cpp b/0501-1000/0874-Walking-Robot-Simulation/cpp-0874/main.cpp new file mode 100644 index 00000000..865a8722 --- /dev/null +++ b/0501-1000/0874-Walking-Robot-Simulation/cpp-0874/main.cpp @@ -0,0 +1,70 @@ +/// Source : https://leetcode.com/problems/walking-robot-simulation/description/ +/// Author : liuyubobobo +/// Time : 2018-07-21 + +#include +#include +#include +#include + +using namespace std; + + +/// Simulation with TreeMap +/// Since in C++, you can not use unordered_set directly with pair... +/// +/// Time Complexity: O(len(commands) * log(len(obstacles))) +/// Space Complexity: O(len(obstacles)) +class Solution { + +private: + int d[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + +public: + int robotSim(vector& commands, vector>& obstacles) { + + set> obstacle_set; + for(const vector vec: obstacles) + obstacle_set.insert(make_pair(vec[0], vec[1])); + + pair pos = make_pair(0, 0); + int direction = 0; + int res = 0; + for(int command: commands) + if(command == -1) + direction = (direction + 1) % 4; + else if(command == -2) + direction = (direction + 3) % 4; + else{ + assert(command > 0); + for(int i = 0 ; i < command ; i ++){ + pair nextpos = make_pair(pos.first + d[direction][0], pos.second + d[direction][1]); + if(obstacle_set.find(nextpos) == obstacle_set.end()){ + pos = nextpos; + res = max(res, pos.first * pos.first + pos.second * pos.second); +// cout << "go to " << pos.first << " , " << pos.second << endl; + } + else + break; + } + } + + return res; + } +}; + + +int main() { + + vector commands1 = {4, -1, 3}; + vector> obstacles1; + cout << Solution().robotSim(commands1, obstacles1) << endl; + // 25 + + vector commands2 = {4, -1, 4, -2, 4}; + vector> obstacles2 = {{2, 4}}; + cout << Solution().robotSim(commands2, obstacles2) << endl; + // 65 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0874-Walking-Robot-Simulation/cpp-0874/main2.cpp b/0501-1000/0874-Walking-Robot-Simulation/cpp-0874/main2.cpp new file mode 100644 index 00000000..a505a964 --- /dev/null +++ b/0501-1000/0874-Walking-Robot-Simulation/cpp-0874/main2.cpp @@ -0,0 +1,75 @@ +/// Source : https://leetcode.com/problems/walking-robot-simulation/description/ +/// Author : liuyubobobo +/// Time : 2018-07-21 + +#include +#include +#include +#include + +using namespace std; + + +/// Simulation with HashMap +/// if you want to use hashmap in C++, you need to do the hash function... +/// +/// Time Complexity: O(len(commands)) +/// Space Complexity: O(len(obstacles)) +class Solution { + +private: + int d[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + +public: + int robotSim(vector& commands, vector>& obstacles) { + + unordered_set obstacle_set; + for(const vector vec: obstacles) + obstacle_set.insert(hashcode(vec[0], vec[1])); + + pair pos = make_pair(0, 0); + int direction = 0; + int res = 0; + for(int command: commands) + if(command == -1) + direction = (direction + 1) % 4; + else if(command == -2) + direction = (direction + 3) % 4; + else{ + assert(command > 0); + for(int i = 0 ; i < command ; i ++){ + pair nextpos = make_pair(pos.first + d[direction][0], pos.second + d[direction][1]); + if(obstacle_set.find(hashcode(nextpos.first, nextpos.second)) == obstacle_set.end()){ + pos = nextpos; + res = max(res, pos.first * pos.first + pos.second * pos.second); +// cout << "go to " << pos.first << " , " << pos.second << endl; + } + else + break; + } + } + + return res; + } + +private: + long long hashcode(int a, int b){ + return ((long long)a + 30000ll) * 60001ll + (long long)b + 30000ll; + } +}; + + +int main() { + + vector commands1 = {4, -1, 3}; + vector> obstacles1; + cout << Solution().robotSim(commands1, obstacles1) << endl; + // 25 + + vector commands2 = {4, -1, 4, -2, 4}; + vector> obstacles2 = {{2, 4}}; + cout << Solution().robotSim(commands2, obstacles2) << endl; + // 65 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0875-Koko-Eating-Bananas/cpp-0875/CMakeLists.txt b/0501-1000/0875-Koko-Eating-Bananas/cpp-0875/CMakeLists.txt new file mode 100644 index 00000000..85e27b1b --- /dev/null +++ b/0501-1000/0875-Koko-Eating-Bananas/cpp-0875/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(C) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(C ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0875-Koko-Eating-Bananas/cpp-0875/main.cpp b/0501-1000/0875-Koko-Eating-Bananas/cpp-0875/main.cpp new file mode 100644 index 00000000..50bc6fdd --- /dev/null +++ b/0501-1000/0875-Koko-Eating-Bananas/cpp-0875/main.cpp @@ -0,0 +1,59 @@ +/// Source : https://leetcode.com/problems/koko-eating-bananas/description/ +/// Author : liuyubobobo +/// Time : 2018-07-21 + +#include +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(nlog(maxpile)) +/// Space Complexity: O(1) +class Solution { +public: + int minEatingSpeed(vector& piles, int H) { + + int l = 1, r = *max_element(piles.begin(), piles.end()); + while(l < r){ + int mid = (l + r) / 2; + if(ok(piles, mid, H)) + r = mid; + else + l = mid + 1; + } + return l; + } + +private: + bool ok(const vector& piles, int K, int H){ + + int T = 0; + for(int pile: piles) + T += pile / K + (pile % K == 0 ? 0 : 1); + return T <= H; + } +}; + + +int main() { + + vector piles1 = {3, 6, 7, 11}; + int H1 = 8; + cout << Solution().minEatingSpeed(piles1, H1) << endl; + // 4 + + vector piles2 = {30, 11, 23, 4, 20}; + int H2 = 5; + cout << Solution().minEatingSpeed(piles2, H2) << endl; + // 30 + + vector piles3 = {30, 11, 23, 4, 20}; + int H3 = 6; + cout << Solution().minEatingSpeed(piles3, H3) << endl; + // 23 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0876-Middle-of-the-Linked-List/cpp-0876/CMakeLists.txt b/0501-1000/0876-Middle-of-the-Linked-List/cpp-0876/CMakeLists.txt new file mode 100644 index 00000000..5cc31b93 --- /dev/null +++ b/0501-1000/0876-Middle-of-the-Linked-List/cpp-0876/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(A) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main3.cpp) +add_executable(A ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0876-Middle-of-the-Linked-List/cpp-0876/main.cpp b/0501-1000/0876-Middle-of-the-Linked-List/cpp-0876/main.cpp new file mode 100644 index 00000000..ac104ed7 --- /dev/null +++ b/0501-1000/0876-Middle-of-the-Linked-List/cpp-0876/main.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/middle-of-the-linked-list/description/ +/// Author : liuyubobobo +/// Time : 2018-08-02 + +#include +#include + +using namespace std; + + +/// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} +}; + + +/// Using Array +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + ListNode* middleNode(ListNode* head) { + + vector nums; + + ListNode* cur = head; + while(cur != NULL) + nums.push_back(cur), cur = cur->next; + + return nums[nums.size() / 2]; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0876-Middle-of-the-Linked-List/cpp-0876/main2.cpp b/0501-1000/0876-Middle-of-the-Linked-List/cpp-0876/main2.cpp new file mode 100644 index 00000000..7edc751a --- /dev/null +++ b/0501-1000/0876-Middle-of-the-Linked-List/cpp-0876/main2.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/middle-of-the-linked-list/description/ +/// Author : liuyubobobo +/// Time : 2018-07-28 + +#include + +using namespace std; + + +/// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} +}; + + +/// Two Linear Scans +/// Calculate length and get the answer +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + ListNode* middleNode(ListNode* head) { + + int len = 0; + ListNode* cur = head; + while(cur != NULL) + len ++, cur = cur->next; + + if(len == 1) + return head; + + int k = len / 2; + cur = head; + for(int i = 0 ; i < k ; i ++) + cur = cur->next; + return cur; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0876-Middle-of-the-Linked-List/cpp-0876/main3.cpp b/0501-1000/0876-Middle-of-the-Linked-List/cpp-0876/main3.cpp new file mode 100644 index 00000000..9d86c872 --- /dev/null +++ b/0501-1000/0876-Middle-of-the-Linked-List/cpp-0876/main3.cpp @@ -0,0 +1,42 @@ +/// Source : https://leetcode.com/problems/middle-of-the-linked-list/description/ +/// Author : liuyubobobo +/// Time : 2018-08-02 + +#include + +using namespace std; + + +/// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} +}; + + +/// Fast and Slow Pointers +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + ListNode* middleNode(ListNode* head) { + + if(head == NULL || head->next == NULL) + return head; + + ListNode* fast = head; + ListNode* slow = head; + while(fast && fast->next) { + slow = slow->next; + fast = fast->next->next; + } + return slow; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0877-Stone-Game/cpp-0877/CMakeLists.txt b/0501-1000/0877-Stone-Game/cpp-0877/CMakeLists.txt new file mode 100644 index 00000000..0d12d141 --- /dev/null +++ b/0501-1000/0877-Stone-Game/cpp-0877/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(B) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main3.cpp) +add_executable(B ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0877-Stone-Game/cpp-0877/main.cpp b/0501-1000/0877-Stone-Game/cpp-0877/main.cpp new file mode 100644 index 00000000..734b400f --- /dev/null +++ b/0501-1000/0877-Stone-Game/cpp-0877/main.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/stone-game/description/ +/// Author : liuyubobobo +/// Time : 2022-08-14 + +#include +#include + +using namespace std; + + +/// Memoization +/// Time Complexity: O(n^2) +/// Space Complexity: O(n^2) +class Solution { +public: + bool stoneGame(vector& piles) { + + int n = piles.size(); + vector> dp(n, vector(n, INT_MIN)); + + return play(piles, 0, n-1, dp) > 0; + } + +private: + int play(const vector& piles, int l, int r, + vector>& dp){ + + if(l == r) return piles[l]; + + if(dp[l][r] != INT_MIN) + return dp[l][r]; + + int res = max(piles[l] - play(piles, l + 1, r, dp), + piles[r] - play(piles, l, r - 1, dp)); + return dp[l][r] = res; + } +}; + + +void print_bool(bool res){ + cout << (res ? "True" : "False") << endl; +} + +int main() { + + vector piles1 = {5, 3, 4, 5}; + print_bool(Solution().stoneGame(piles1)); + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0877-Stone-Game/cpp-0877/main2.cpp b/0501-1000/0877-Stone-Game/cpp-0877/main2.cpp new file mode 100644 index 00000000..95a111ba --- /dev/null +++ b/0501-1000/0877-Stone-Game/cpp-0877/main2.cpp @@ -0,0 +1,62 @@ +/// Source : https://leetcode.com/problems/stone-game/description/ +/// Author : liuyubobobo +/// Time : 2018-07-28 +/// Updated: 2022-08-14 + +#include +#include + +using namespace std; + + +/// Memoization - using player as a state +/// The code and logic is more complex(, but might be educational) +/// Time Complexity: O(n^2) +/// Space Complexity: O(n^2) +class Solution { +public: + bool stoneGame(vector& piles) { + + int n = piles.size(); + vector>> dp(2, vector>(n, vector(n, INT_MIN))); + + return play(0, piles, 0, n-1, dp) > 0; + } + +private: + int play(int player, const vector& piles, int l, int r, + vector>>& dp){ + + if(l == r){ + if(player == 0) + return dp[player][l][r] = piles[l]; + else + return dp[player][l][r] = -piles[l]; + } + + if(dp[player][l][r] != INT_MIN) + return dp[player][l][r]; + + int res = 0; + if(player == 0) + res = max(piles[l] + play(1 - player, piles, l + 1, r, dp), + piles[r] + play(1 - player, piles, l, r - 1, dp)); + else + res = min(-piles[l] + play(1 - player, piles, l + 1, r, dp), + -piles[r] + play(1 - player, piles, l, r - 1, dp)); + return dp[player][l][r] = res; + } +}; + + +void print_bool(bool res){ + cout << (res ? "True" : "False") << endl; +} + +int main() { + + vector piles1 = {5, 3, 4, 5}; + print_bool(Solution().stoneGame(piles1)); + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0877-Stone-Game/cpp-0877/main3.cpp b/0501-1000/0877-Stone-Game/cpp-0877/main3.cpp new file mode 100644 index 00000000..879ce308 --- /dev/null +++ b/0501-1000/0877-Stone-Game/cpp-0877/main3.cpp @@ -0,0 +1,36 @@ +/// Source : https://leetcode.com/problems/stone-game/description/ +/// Author : liuyubobobo +/// Time : 2018-08-03 + +#include +#include + +using namespace std; + + +/// Mathematic, the answer will always be true! +/// Since the player can technically take all the stones from even-index piles, +/// or take all the stones from odd-index piles +/// One of the two strategy must win:) +/// +/// Time Complexity: O(1) +/// Space Complexity: O(1) +class Solution { +public: + bool stoneGame(vector& piles) { + return true; + } +}; + + +void print_bool(bool res){ + cout << (res ? "True" : "False") << endl; +} + +int main() { + + vector piles1 = {5, 3, 4, 5}; + print_bool(Solution().stoneGame(piles1)); + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0878-Nth-Magical-Number/cpp-0878/CMakeLists.txt b/0501-1000/0878-Nth-Magical-Number/cpp-0878/CMakeLists.txt new file mode 100644 index 00000000..2e1fe4bf --- /dev/null +++ b/0501-1000/0878-Nth-Magical-Number/cpp-0878/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(C) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main3.cpp) +add_executable(C ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0878-Nth-Magical-Number/cpp-0878/main.cpp b/0501-1000/0878-Nth-Magical-Number/cpp-0878/main.cpp new file mode 100644 index 00000000..008c75df --- /dev/null +++ b/0501-1000/0878-Nth-Magical-Number/cpp-0878/main.cpp @@ -0,0 +1,70 @@ +/// Source : https://leetcode.com/problems/nth-magical-number/description/ +/// Author : liuyubobobo +/// Time : 2018-07-28 + +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(log(min(A, B) * N)) +/// Space Complexity: O(1) +class Solution { + +private: + long long MOD = 1e9 + 7; + +public: + int nthMagicalNumber(int N, int A, int B) { + + int lcm = A * B / gcd(A, B); + long long l = 2ll, r = (long long)min(A, B) * (long long)N; + while(l <= r){ + long long mid = l + (r - l) / 2; + long long rank = getRank(mid, A, B, lcm); + + if(rank == (long long)N) { + if (mid % (long long) A == 0 || mid % (long long) B == 0) + return (int) (mid % MOD); + else + r = mid - 1ll; + } + else if(rank < (long long)N) + l = mid + 1ll; + else + r = mid - 1ll; + } + assert(false); + + return -1; + } + +private: + long long getRank(long long num, int A, int B, int lcm){ + long long arank = num / (long long)A; + long long brank = num / (long long)B; + long long abrank = num / (long long)lcm; + return arank + brank - abrank; + } + + int gcd(int A, int B){ + if(A > B) + swap(A, B); + if(B % A == 0) + return A; + return gcd(B % A, A); + } +}; + + +int main() { + + cout << Solution().nthMagicalNumber(1, 2, 3) << endl; // 2 + cout << Solution().nthMagicalNumber(4, 2, 3) << endl; // 6 + cout << Solution().nthMagicalNumber(5, 2, 4) << endl; // 10 + cout << Solution().nthMagicalNumber(3, 6, 4) << endl; // 8 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0878-Nth-Magical-Number/cpp-0878/main2.cpp b/0501-1000/0878-Nth-Magical-Number/cpp-0878/main2.cpp new file mode 100644 index 00000000..b1335381 --- /dev/null +++ b/0501-1000/0878-Nth-Magical-Number/cpp-0878/main2.cpp @@ -0,0 +1,61 @@ +/// Source : https://leetcode.com/problems/nth-magical-number/description/ +/// Author : liuyubobobo +/// Time : 2018-08-03 + +#include +#include + +using namespace std; + + +/// Binary Search Improved +/// Time Complexity: O(log(min(A, B) * N)) +/// Space Complexity: O(1) +class Solution { + +private: + long long MOD = 1e9 + 7; + +public: + int nthMagicalNumber(int N, int A, int B) { + + int lcm = A * B / gcd(A, B); + long long l = 2ll, r = (long long)min(A, B) * (long long)N; + while(l < r){ + long long mid = l + (r - l) / 2; + if(getRank(mid, A, B, lcm) >= (long long)N) + r = mid; + else + l = mid + 1ll; + } + + return (int)(l % MOD); + } + +private: + long long getRank(long long num, int A, int B, int lcm){ + long long arank = num / (long long)A; + long long brank = num / (long long)B; + long long abrank = num / (long long)lcm; + return arank + brank - abrank; + } + + int gcd(int A, int B){ + if(A > B) + swap(A, B); + if(B % A == 0) + return A; + return gcd(B % A, A); + } +}; + + +int main() { + + cout << Solution().nthMagicalNumber(1, 2, 3) << endl; // 2 + cout << Solution().nthMagicalNumber(4, 2, 3) << endl; // 6 + cout << Solution().nthMagicalNumber(5, 2, 4) << endl; // 10 + cout << Solution().nthMagicalNumber(3, 6, 4) << endl; // 8 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0878-Nth-Magical-Number/cpp-0878/main3.cpp b/0501-1000/0878-Nth-Magical-Number/cpp-0878/main3.cpp new file mode 100644 index 00000000..cd087a72 --- /dev/null +++ b/0501-1000/0878-Nth-Magical-Number/cpp-0878/main3.cpp @@ -0,0 +1,61 @@ +/// Source : https://leetcode.com/problems/nth-magical-number/description/ +/// Author : liuyubobobo +/// Time : 2018-08-03 + +#include +#include + +using namespace std; + + +/// Mathmatically Method +/// Time Complexity: O(log(min(A, B) * N)) +/// Space Complexity: O(1) +class Solution { + +private: + long long MOD = (long long)(1e9 + 7); + +public: + int nthMagicalNumber(int N, int A, int B) { + + int lcm = A * B / gcd(A, B); + int seg = lcm; + int segM = seg / A + seg / B - seg / lcm; + + int left = N % segM; + long long base = (long long)seg * (long long)(N / segM); + if(left == 0) + return (int)(base % MOD); + + pair d = make_pair((long long)A, (long long)B); + for(int i = 0 ; i < left - 1; i ++) + if(d.first <= d.second) + d.first += (long long)A; + else + d.second += (long long)B; + return (int)((base + min(d.first, d.second)) % MOD); + } + +private: + int gcd(int A, int B){ + if(A > B) + swap(A, B); + if(B % A == 0) + return A; + return gcd(B % A, A); + } +}; + + +int main() { + + cout << Solution().nthMagicalNumber(1, 2, 3) << endl; // 2 + cout << Solution().nthMagicalNumber(4, 2, 3) << endl; // 6 + cout << Solution().nthMagicalNumber(5, 2, 4) << endl; // 10 + cout << Solution().nthMagicalNumber(3, 6, 4) << endl; // 8 + cout << Solution().nthMagicalNumber(2, 7, 3) << endl; // 6 + cout << Solution().nthMagicalNumber(3, 8, 3) << endl; // 8 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0879-Profitable-Schemes/cpp-0879/CMakeLists.txt b/0501-1000/0879-Profitable-Schemes/cpp-0879/CMakeLists.txt new file mode 100644 index 00000000..6b562ad1 --- /dev/null +++ b/0501-1000/0879-Profitable-Schemes/cpp-0879/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0879) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0879 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0879-Profitable-Schemes/cpp-0879/main.cpp b/0501-1000/0879-Profitable-Schemes/cpp-0879/main.cpp new file mode 100644 index 00000000..c1690bac --- /dev/null +++ b/0501-1000/0879-Profitable-Schemes/cpp-0879/main.cpp @@ -0,0 +1,58 @@ +/// Source : https://leetcode.com/problems/profitable-schemes/description/ +/// Author : liuyubobobo +/// Time : 2018-08-04 +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(G * P * n) +/// Space Complexity: O(G * P) +class Solution { + +private: + int MOD = 1e9 + 7; + +public: + int profitableSchemes(int G, int P, vector& group, vector& profit) { + + //vector>> dp(2, vector>(G + 1, vector(P + 1, -1))); + vector> dp(P + 1, vector(G + 1, 0)); + dp[0][0] = 1; + for(int i = 0; i < group.size() ; i ++){ + + for(int j = P; j >= 0; j --) + for(int k = G - group[i]; k >= 0; k --){ + int p = min(P, j + profit[i]); + int g = k + group[i]; + dp[p][g] += dp[j][k]; + dp[p][g] %= MOD; + } + } + + long long res = 0ll; + for(int x: dp[P]){ + res += x; + res %= MOD; + } + return res; + } +}; + + +int main() { + + int G1 = 5, P1 = 3; + vector group1 = {2, 2}; + vector profit1 = {2, 3}; + cout << Solution().profitableSchemes(G1, P1, group1, profit1) << endl; // 2 + + int G2 = 10, P2 = 5; + vector group2 = {2, 3, 5}; + vector profit2 = {6, 7, 8}; + cout << Solution().profitableSchemes(G2, P2, group2, profit2) << endl; // 7 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0880-Decoded-String-at-Index/cpp-0880/CMakeLists.txt b/0501-1000/0880-Decoded-String-at-Index/cpp-0880/CMakeLists.txt new file mode 100644 index 00000000..10d4db6b --- /dev/null +++ b/0501-1000/0880-Decoded-String-at-Index/cpp-0880/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(C) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main2.cpp) +add_executable(C ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0880-Decoded-String-at-Index/cpp-0880/main.cpp b/0501-1000/0880-Decoded-String-at-Index/cpp-0880/main.cpp new file mode 100644 index 00000000..0e82f2fc --- /dev/null +++ b/0501-1000/0880-Decoded-String-at-Index/cpp-0880/main.cpp @@ -0,0 +1,51 @@ +/// Source : https://leetcode.com/problems/decoded-string-at-index/description/ +/// Author : liuyubobobo +/// Time : 2018-08-04 +#include +#include + +using namespace std; + + +/// Recursion +/// Time Complexity: O(len(S)*logK) +/// Space Complexity: O(logK) +class Solution { +public: + string decodeAtIndex(string S, int K) { + + int curl = 0; + int repeat = 1; + for(char c: S){ + if(isalpha(c)){ + if(curl * repeat + 1 == K) + return string(1, c); + curl = curl * repeat + 1; + repeat = 1; + } + else{ + repeat *= (c - '0'); + if((long long)K <= (long long)curl * (long long)repeat) + return decodeAtIndex(S, (K - 1) % curl + 1); + } + } + + assert(false); + return ""; + } +}; + + +int main() { + + string S1 = "leet2code3"; + cout << Solution().decodeAtIndex(S1, 10) << endl; // o + + string S2 = "ha22"; + cout << Solution().decodeAtIndex(S2, 5) << endl; // h + + string S3 = "a2345678999999999999999"; + cout << Solution().decodeAtIndex(S3, 1) << endl; // a + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0880-Decoded-String-at-Index/cpp-0880/main2.cpp b/0501-1000/0880-Decoded-String-at-Index/cpp-0880/main2.cpp new file mode 100644 index 00000000..8620d255 --- /dev/null +++ b/0501-1000/0880-Decoded-String-at-Index/cpp-0880/main2.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/decoded-string-at-index/description/ +/// Author : liuyubobobo +/// Time : 2018-08-05 +#include +#include + +using namespace std; + + +/// Backwards iteration +/// Time Complexity: O(len(S)) +/// Space Complexity: O(1) +class Solution { +public: + string decodeAtIndex(string S, int K) { + + long long curl = 0ll; + long long repeat = 1ll; + for(char c: S) + if(isalpha(c)){ + curl *= repeat, curl += 1ll; + repeat = 1ll; + } + else + repeat *= (long long)(c - '0'); + curl *= repeat; + + for(int i = S.size() - 1; i >= 0; i --) + if(isalpha(S[i])){ + if(K == curl) + return string(1, S[i]); + curl --; + } + else{ + curl /= (long long)(S[i] - '0'); + K = (int)((long long)(K - 1) % curl + 1ll); + } + + assert(false); + return ""; + } +}; + + +int main() { + + string S1 = "leet2code3"; + cout << Solution().decodeAtIndex(S1, 10) << endl; // o + + string S2 = "ha22"; + cout << Solution().decodeAtIndex(S2, 5) << endl; // h + + string S3 = "a2345678999999999999999"; + cout << Solution().decodeAtIndex(S3, 1) << endl; // a + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0881-Boats-to-Save-People/cpp-0881/CMakeLists.txt b/0501-1000/0881-Boats-to-Save-People/cpp-0881/CMakeLists.txt new file mode 100644 index 00000000..ae89e070 --- /dev/null +++ b/0501-1000/0881-Boats-to-Save-People/cpp-0881/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(B) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(B ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0881-Boats-to-Save-People/cpp-0881/main.cpp b/0501-1000/0881-Boats-to-Save-People/cpp-0881/main.cpp new file mode 100644 index 00000000..275e61e8 --- /dev/null +++ b/0501-1000/0881-Boats-to-Save-People/cpp-0881/main.cpp @@ -0,0 +1,51 @@ +/// Source : https://leetcode.com/problems/boats-to-save-people/description/ +/// Author : liuyubobobo +/// Time : 2018-08-04 +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + int numRescueBoats(vector& people, int limit) { + + sort(people.begin(), people.end()); + int i = 0, j = people.size() - 1; + int res = 0; + while(i <= j){ + if(i == j){ + res ++; + break; + } + + res ++; + if(people[i] + people[j] <= limit){ + i ++; + j --; + } + else + j --; + } + return res; + } +}; + + +int main() { + + vector people1 = {1, 2}; + cout << Solution().numRescueBoats(people1, 3) << endl; // 1 + + vector people2 = {3, 2, 2, 1}; + cout << Solution().numRescueBoats(people2, 3) << endl; // 3 + + vector people3 = {3, 5, 3, 4}; + cout << Solution().numRescueBoats(people3, 5) << endl; // 4 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0882-Reachable-Nodes-In-Subdivided-Graph/cpp-0882/CMakeLists.txt b/0501-1000/0882-Reachable-Nodes-In-Subdivided-Graph/cpp-0882/CMakeLists.txt new file mode 100644 index 00000000..1c3e7bb6 --- /dev/null +++ b/0501-1000/0882-Reachable-Nodes-In-Subdivided-Graph/cpp-0882/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(D) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(D ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0882-Reachable-Nodes-In-Subdivided-Graph/cpp-0882/main.cpp b/0501-1000/0882-Reachable-Nodes-In-Subdivided-Graph/cpp-0882/main.cpp new file mode 100644 index 00000000..610c47b0 --- /dev/null +++ b/0501-1000/0882-Reachable-Nodes-In-Subdivided-Graph/cpp-0882/main.cpp @@ -0,0 +1,83 @@ +/// Source : https://leetcode.com/problems/reachable-nodes-in-subdivided-graph/description/ +/// Author : liuyubobobo +/// Time : 2018-08-05 + +#include +#include +#include +#include +#include +#include + +using namespace std; + + +/// Dijkstra +/// Time Complexity: O(ElogN) +/// Space Complexity: O(E + N) +class Solution { +public: + int reachableNodes(vector>& edges, int M, int N) { + + vector> g(N, unordered_set()); + map, int> edges_map; + map, int> used_edges; + for(const vector& edge: edges){ + int u = edge[0], v = edge[1], w = edge[2]; + g[u].insert(v); + g[v].insert(u); + edges_map[make_pair(u, v)] = edges_map[make_pair(v, u)] = w; + used_edges[make_pair(u, v)] = used_edges[make_pair(v, u)] = 0; + } + + vector visited(N, false); + priority_queue, vector>, greater>> pq; + pq.push(make_pair(0, 0)); + while(!pq.empty()){ + int cur = pq.top().second; + int step = pq.top().first; + pq.pop(); + + if(!visited[cur]){ + visited[cur] = true; + for(int next: g[cur]){ + pair p = make_pair(cur, next); + if(step + edges_map[p] + 1 <= M){ + used_edges[p] = edges_map[p]; + pq.push(make_pair(step + edges_map[p] + 1, next)); + } + else + used_edges[p] = max(used_edges[p], M - step); + } + } + } + + int res = accumulate(visited.begin(), visited.end(), 0); + for(const vector& edge: edges){ + int u = edge[0], v = edge[1]; + res += min(used_edges[make_pair(u, v)] + used_edges[make_pair(v, u)], + edge[2]); + } + return res; + } +}; + + +int main() { + + vector> edges1 = {{0, 1, 10}, {0, 2, 1}, {1, 2, 2}}; + cout << Solution().reachableNodes(edges1, 6, 3) << endl; // 13 + + vector> edges2 = {{0, 1, 4}, {1, 2, 6}, {0, 2, 8}, {1, 3, 1}}; + cout << Solution().reachableNodes(edges2, 10, 4) << endl; // 23 + + vector> edges3 = + {{0, 3, 8}, {0, 1, 4}, {2, 4, 3}, {1, 2, 0}, {1, 3, 9}, + {0, 4, 7}, {3, 4, 9}, {1, 4, 4}, {0, 2, 7}, {2, 3, 1}}; + cout << Solution().reachableNodes(edges3, 8, 5) << endl; // 40 + + vector> edges4 = {{2, 4, 2}, {3, 4, 5}, {2, 3, 1}, {0, 2, 1}, {0, 3, 5}}; + cout << Solution().reachableNodes(edges4, 14, 5) << endl; // 18 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0883-Projection-Area-of-3D-Shapes/cpp-0883/CMakeLists.txt b/0501-1000/0883-Projection-Area-of-3D-Shapes/cpp-0883/CMakeLists.txt new file mode 100644 index 00000000..b3fafe13 --- /dev/null +++ b/0501-1000/0883-Projection-Area-of-3D-Shapes/cpp-0883/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(A) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(A ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0883-Projection-Area-of-3D-Shapes/cpp-0883/main.cpp b/0501-1000/0883-Projection-Area-of-3D-Shapes/cpp-0883/main.cpp new file mode 100644 index 00000000..0b33e5dc --- /dev/null +++ b/0501-1000/0883-Projection-Area-of-3D-Shapes/cpp-0883/main.cpp @@ -0,0 +1,65 @@ +/// Source : https://leetcode.com/problems/projection-area-of-3d-shapes/description/ +/// Author : liuyubobobo +/// Time : 2018-08-04 +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(m*n) +/// Space Complexity: O(1) +class Solution { + +public: + int projectionArea(vector>& grid) { + + int n = grid.size(); + int m = grid[0].size(); + + int res = n * m; + for(int i = 0; i < n ; i ++) + for(int j = 0 ; j < m ; j ++) + if(grid[i][j] == 0) + res --; + + for(const vector& line: grid) + res += *max_element(line.begin(), line.end()); + + for(int j = 0; j < m ; j ++){ + int v = grid[0][j]; + for(int i = 1 ; i < n ; i ++) + v = max(v, grid[i][j]); + res += v; + } + + return res; + } +}; + + +int main() { + + vector> grid1 = {{2}}; + cout << Solution().projectionArea(grid1) << endl; + // 5 + + vector> grid2 = {{1, 2}, {3, 4}}; + cout << Solution().projectionArea(grid2) << endl; + // 17 + + vector> grid3 = {{1, 0}, {0, 2}}; + cout << Solution().projectionArea(grid3) << endl; + // 8 + + vector> grid4 = {{1, 1, 1}, {1, 0, 1}, {1, 1, 1}}; + cout << Solution().projectionArea(grid4) << endl; + // 14 + + vector> grid5 = {{2, 2, 2}, {2, 1, 2}, {2, 2, 2}}; + cout << Solution().projectionArea(grid5) << endl; + // 21 + + return 0; +} \ No newline at end of file diff --git a/0733-Flood-Fill/cpp-0733/CMakeLists.txt b/0501-1000/0884-Uncommon-Words-from-Two-Sentences/cpp-0884/CMakeLists.txt similarity index 100% rename from 0733-Flood-Fill/cpp-0733/CMakeLists.txt rename to 0501-1000/0884-Uncommon-Words-from-Two-Sentences/cpp-0884/CMakeLists.txt diff --git a/0501-1000/0884-Uncommon-Words-from-Two-Sentences/cpp-0884/main.cpp b/0501-1000/0884-Uncommon-Words-from-Two-Sentences/cpp-0884/main.cpp new file mode 100644 index 00000000..b6732208 --- /dev/null +++ b/0501-1000/0884-Uncommon-Words-from-Two-Sentences/cpp-0884/main.cpp @@ -0,0 +1,55 @@ +/// Source : https://leetcode.com/problems/uncommon-words-from-two-sentences/description/ +/// Author : liuyubobobo +/// Time : 2018-08-11 + +#include +#include +#include + +using namespace std; + + +/// Simulation uncommon words concepts +/// Using Two HashMaps +/// +/// Time Complexity: O(len(A) + len(B)) +/// Space Complexity: O(len(A) + len(B)) +class Solution { +public: + vector uncommonFromSentences(string A, string B) { + + unordered_map freqA = getFreq(A); + unordered_map freqB = getFreq(B); + + vector res; + for(const pair& p: freqA) + if(p.second == 1 && freqB.find(p.first) == freqB.end()) + res.push_back(p.first); + for(const pair& p: freqB) + if(p.second == 1 && freqA.find(p.first) == freqA.end()) + res.push_back(p.first); + return res; + } + +private: + unordered_map getFreq(const string& s){ + + unordered_map freq; + int start = 0; + for(int i = start + 1; i <= s.size(); ) + if(i == s.size() || s[i] == ' '){ + freq[s.substr(start, i - start)] ++; + start = i + 1; + i = start + 1; + } + else + i ++; + return freq; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0884-Uncommon-Words-from-Two-Sentences/cpp-0884/main2.cpp b/0501-1000/0884-Uncommon-Words-from-Two-Sentences/cpp-0884/main2.cpp new file mode 100644 index 00000000..7200b86d --- /dev/null +++ b/0501-1000/0884-Uncommon-Words-from-Two-Sentences/cpp-0884/main2.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/uncommon-words-from-two-sentences/description/ +/// Author : liuyubobobo +/// Time : 2018-08-12 + +#include +#include +#include + +using namespace std; + + +/// Uncommon words only occur once +/// Using just one HashMap +/// +/// Time Complexity: O(len(A) + len(B)) +/// Space Complexity: O(len(A) + len(B)) +class Solution { +public: + vector uncommonFromSentences(string A, string B) { + + unordered_map freq; + getFreq(freq, A); + getFreq(freq, B); + + vector res; + for(const pair& p: freq) + if(p.second == 1) + res.push_back(p.first); + return res; + } + +private: + void getFreq(unordered_map& freq, const string& s){ + + int start = 0; + for(int i = start + 1; i <= s.size(); ) + if(i == s.size() || s[i] == ' '){ + freq[s.substr(start, i - start)] ++; + start = i + 1; + i = start + 1; + } + else + i ++; + return; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0885-Spiral-Matrix-III/cpp-0885/CMakeLists.txt b/0501-1000/0885-Spiral-Matrix-III/cpp-0885/CMakeLists.txt new file mode 100644 index 00000000..ae89e070 --- /dev/null +++ b/0501-1000/0885-Spiral-Matrix-III/cpp-0885/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(B) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(B ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0885-Spiral-Matrix-III/cpp-0885/main.cpp b/0501-1000/0885-Spiral-Matrix-III/cpp-0885/main.cpp new file mode 100644 index 00000000..e1d5f6ab --- /dev/null +++ b/0501-1000/0885-Spiral-Matrix-III/cpp-0885/main.cpp @@ -0,0 +1,55 @@ +/// Source : https://leetcode.com/problems/spiral-matrix-iii/description/ +/// Author : liuyubobobo +/// Time : 2018-08-11 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(max(R, C)^2) +/// Space Complexity: O(R * C) +class Solution { + +private: + int d[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + +public: + vector> spiralMatrixIII(int R, int C, int r0, int c0) { + + vector> ret = {{r0, c0}}; + + int res = 1, posx = r0, posy = c0; + int curD = 0, curSide = 1; + while(res < R * C){ + + for(int i = 0 ; i < 2; i ++){ + for(int j = 0; j < curSide; j ++){ + posx = posx + d[curD][0]; + posy = posy + d[curD][1]; + if(inArea(posx, posy, R, C)){ + ret.push_back({posx, posy}); + res ++; + } + } + curD = (curD + 1) % 4; + } + curSide ++; + } + + return ret; + } + +private: + bool inArea(int x, int y, int R, int C){ + return x >= 0 && x < R && y >= 0 && y < C; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0886-Possible-Bipartition/cpp-0886/CMakeLists.txt b/0501-1000/0886-Possible-Bipartition/cpp-0886/CMakeLists.txt new file mode 100644 index 00000000..85e27b1b --- /dev/null +++ b/0501-1000/0886-Possible-Bipartition/cpp-0886/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(C) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(C ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0886-Possible-Bipartition/cpp-0886/main.cpp b/0501-1000/0886-Possible-Bipartition/cpp-0886/main.cpp new file mode 100644 index 00000000..6dc8c3fd --- /dev/null +++ b/0501-1000/0886-Possible-Bipartition/cpp-0886/main.cpp @@ -0,0 +1,58 @@ +/// Source : https://leetcode.com/problems/possible-bipartition/description/ +/// Author : liuyubobobo +/// Time : 2017-08-12 + +#include +#include +#include + +using namespace std; + + +/// DFS with Node-coloring +/// Time Complexity: O(N + E) +/// Space Complexity: O(N + E) +class Solution { +public: + bool possibleBipartition(int N, vector>& dislikes) { + + vector> g(N); + for(const vector& p: dislikes){ + g[p[0] - 1].insert(p[1] - 1); + g[p[1] - 1].insert(p[0] - 1); + } + + vector color(N, -1); + for(int i = 0; i < N; i ++) + if(color[i] == -1 && !dfs(g, i, 0, color)) + return false; + return true; + } + +private: + bool dfs(const vector>& g, int u, int c, + vector& colors){ + + if(colors[u] != -1) + return colors[u] == c; + + colors[u] = c; + for(int next: g[u]) + if(!dfs(g, next, 1 - c, colors)) + return false; + return true; + } +}; + + +void print_bool(bool res){ + cout << (res ? "true" : "false") << endl; +} + +int main() { + + vector> dislikes1 = {{1, 2}, {1, 3}, {2, 4}}; + print_bool(Solution().possibleBipartition(4, dislikes1)); + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0888-Fair-Candy-Swap/cpp-0888/CMakeLists.txt b/0501-1000/0888-Fair-Candy-Swap/cpp-0888/CMakeLists.txt new file mode 100644 index 00000000..b3fafe13 --- /dev/null +++ b/0501-1000/0888-Fair-Candy-Swap/cpp-0888/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(A) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(A ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0888-Fair-Candy-Swap/cpp-0888/main.cpp b/0501-1000/0888-Fair-Candy-Swap/cpp-0888/main.cpp new file mode 100644 index 00000000..6d872839 --- /dev/null +++ b/0501-1000/0888-Fair-Candy-Swap/cpp-0888/main.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/fair-candy-swap/description/ +/// Author : liuyubobobo +/// Time : 2018-08-18 + +#include +#include +#include +#include + +using namespace std; + + +/// Hashing Set +/// Time Complexity: O(len(A) + len(B)) +/// Space Complexity: O(len(A) + len(B)) +class Solution { +public: + vector fairCandySwap(vector& A, vector& B) { + + unordered_set Aset, Bset; + int sumA = 0, sumB = 0; + for(int a: A){ + Aset.insert(a); + sumA += a; + } + + for(int b: B){ + Bset.insert(b); + sumB += b; + } + + int sz = (sumA + sumB) / 2; + + for(int a: A) + if(Bset.find(sz - (sumA - a)) != Bset.end()) + return {a, sz - (sumA - a)}; + + assert(false); + return {}; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0889-Construct-Binary-Tree-from-Preorder-and-Postorder-Traversal/cpp-0889/CMakeLists.txt b/0501-1000/0889-Construct-Binary-Tree-from-Preorder-and-Postorder-Traversal/cpp-0889/CMakeLists.txt new file mode 100644 index 00000000..85e27b1b --- /dev/null +++ b/0501-1000/0889-Construct-Binary-Tree-from-Preorder-and-Postorder-Traversal/cpp-0889/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(C) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(C ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0889-Construct-Binary-Tree-from-Preorder-and-Postorder-Traversal/cpp-0889/main.cpp b/0501-1000/0889-Construct-Binary-Tree-from-Preorder-and-Postorder-Traversal/cpp-0889/main.cpp new file mode 100644 index 00000000..c8a7b44f --- /dev/null +++ b/0501-1000/0889-Construct-Binary-Tree-from-Preorder-and-Postorder-Traversal/cpp-0889/main.cpp @@ -0,0 +1,82 @@ +/// Source : https://leetcode.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal/description/ +/// Author : liuyubobobo +/// Time : 2018-08-18 + +#include +#include +#include + +using namespace std; + + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + + +/// Recursion +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { +public: + TreeNode* constructFromPrePost(vector& pre, vector& post) { + + int n = pre.size(); + return construct(pre, 0, n - 1, post, 0, n - 1); + } + +private: + TreeNode* construct(const vector& pre, int preL, int preR, + const vector& post, int postL, int postR){ + + if(preL > preR) + return NULL; + + assert(preR - preL + 1 == postR - postL + 1); + + if(preL == preR){ + assert(postL == postR && pre[preL] == post[postL]); + return new TreeNode(pre[preL]); + } + + assert(pre[preL] == post[postR]); + TreeNode* root = new TreeNode(pre[preL]); + + int postPos = find(post.begin(), post.end(), pre[preL + 1]) - post.begin(); + assert(postPos >= postL && postPos <= postR - 1); + + int prePos = find(pre.begin(), pre.end(), post[postR - 1]) - pre.begin(); + assert(prePos >= preL + 1 && prePos <= preR); + + if(pre[prePos] == post[postPos]) + root->left = construct(pre, preL + 1, preR, post, postL, postR - 1); + else { + root->left = construct(pre, preL + 1, prePos - 1, post, postL, postPos); + root->right = construct(pre, prePos, preR, post, postPos + 1, postR - 1); + } + + return root; + } +}; + + +int main() { + + vector pre1 = {1, 2, 4, 5, 3, 6, 7}; + vector post1 = {4, 5, 2, 6, 7, 3, 1}; + Solution().constructFromPrePost(pre1, post1); + + vector pre2 = {2, 1}; + vector post2 = {1, 2}; + Solution().constructFromPrePost(pre2, post2); + + vector pre3 = {2, 1, 3}; + vector post3 = {3, 1, 2}; + Solution().constructFromPrePost(pre3, post3); + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0890-Find-and-Replace-Pattern/cpp-0890/CMakeLists.txt b/0501-1000/0890-Find-and-Replace-Pattern/cpp-0890/CMakeLists.txt new file mode 100644 index 00000000..ae89e070 --- /dev/null +++ b/0501-1000/0890-Find-and-Replace-Pattern/cpp-0890/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(B) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(B ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0890-Find-and-Replace-Pattern/cpp-0890/main.cpp b/0501-1000/0890-Find-and-Replace-Pattern/cpp-0890/main.cpp new file mode 100644 index 00000000..bb5d938f --- /dev/null +++ b/0501-1000/0890-Find-and-Replace-Pattern/cpp-0890/main.cpp @@ -0,0 +1,67 @@ +/// Source : https://leetcode.com/problems/find-and-replace-pattern/ +/// Author : liuyubobobo +/// Time : 2018-08-18 + +#include +#include +#include + +using namespace std; + + +/// Two Maps +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +public: + vector findAndReplacePattern(vector& words, string pattern) { + + vector res; + for(const string& word: words) + if(ok(word, pattern)) + res.push_back(word); + return res; + } + +private: + bool ok(const string& word, const string& pattern){ + + if(word.size() != pattern.size()) + return false; + + unordered_map match, rmatch; + for(int i = 0; i < word.size(); i ++) + if(match.find(word[i]) == match.end()){ + if(rmatch.find(pattern[i]) != rmatch.end()) + return false; + + match[word[i]] = pattern[i]; + rmatch[pattern[i]] = word[i]; + } + else{ + if(match[word[i]] != pattern[i]) + return false; + if(rmatch.find(pattern[i]) == rmatch.end() || + rmatch[pattern[i]] != word[i]) + return false; + } + + return true; + } +}; + + +void print_vec(const vector& vec){ + for(const string& e: vec) + cout << e << " "; + cout << endl; +} + +int main() { + + vector words1 = {"abc","deq","mee","aqq","dkd","ccc"}; + print_vec(Solution().findAndReplacePattern(words1, "abb")); + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0891-Sum-of-Subsequence-Widths/cpp-0891/CMakeLists.txt b/0501-1000/0891-Sum-of-Subsequence-Widths/cpp-0891/CMakeLists.txt new file mode 100644 index 00000000..1c3e7bb6 --- /dev/null +++ b/0501-1000/0891-Sum-of-Subsequence-Widths/cpp-0891/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(D) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(D ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0891-Sum-of-Subsequence-Widths/cpp-0891/main.cpp b/0501-1000/0891-Sum-of-Subsequence-Widths/cpp-0891/main.cpp new file mode 100644 index 00000000..56c2ccc0 --- /dev/null +++ b/0501-1000/0891-Sum-of-Subsequence-Widths/cpp-0891/main.cpp @@ -0,0 +1,56 @@ +/// Source : https://leetcode.com/problems/sum-of-subsequence-widths/description/ +/// Author : liuyubobobo +/// Time : 2018-08-19 + +#include +#include + +using namespace std; + + +/// Mathematics +/// Time Complexity: O(nlogn) +/// Space Complexity : O(1); +class Solution { + +private: + long long MOD = 1e9 + 7; + +public: + int sumSubseqWidths(vector& A) { + + sort(A.begin(), A.end()); + int n = A.size(); + + long long res = (power(2ll, n - 1) - 1ll) * (long long)A.back() % MOD; + res = (res - (power(2ll, n - 1) - 1ll) * (long long)A[0] % MOD) % MOD; + for(int i = 1; i < A.size() - 1 ; i ++){ + int left = i, right = n - (i + 1); + res = (res + (power(2ll, left) - 1ll) * (long long)A[i] % MOD) % MOD; + res = (res - (power(2ll, right) - 1ll) * (long long)A[i] % MOD) % MOD; + } + return res; + } + +private: + long long power(long long a, long long b){ + + if(b == 0ll) + return 1ll; + + long long t = power(a, b / 2ll); + long long ret = t * t % MOD; + if(b % 2ll == 1ll) + ret = ret * a % MOD; + return ret; + } +}; + + +int main() { + + vector nums = {2, 1, 3}; + cout << Solution().sumSubseqWidths(nums) << endl; + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0892-Surface-Area-of-3D-Shapes/cpp-0892/CMakeLists.txt b/0501-1000/0892-Surface-Area-of-3D-Shapes/cpp-0892/CMakeLists.txt new file mode 100644 index 00000000..b3fafe13 --- /dev/null +++ b/0501-1000/0892-Surface-Area-of-3D-Shapes/cpp-0892/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(A) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(A ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0892-Surface-Area-of-3D-Shapes/cpp-0892/main.cpp b/0501-1000/0892-Surface-Area-of-3D-Shapes/cpp-0892/main.cpp new file mode 100644 index 00000000..63af45a6 --- /dev/null +++ b/0501-1000/0892-Surface-Area-of-3D-Shapes/cpp-0892/main.cpp @@ -0,0 +1,76 @@ +/// Source : https://leetcode.com/problems/surface-area-of-3d-shapes/description/ +/// Author : liuyubobobo +/// Time : 2018-08-25 + +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(m*n) +/// Space Complexity: O(1) +class Solution { + +private: + int d[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + int m, n; + +public: + int surfaceArea(vector>& grid) { + + m = grid.size(); + if(m == 0) + return 0; + n = grid[0].size(); + + int res = 0; + for(int i = 0; i < m; i ++) + for(int j = 0; j < n; j ++){ + if(grid[i][j]){ + res += 2; + for(int k = 0; k < 4; k ++){ + int newX = i + d[k][0]; + int newY = j + d[k][1]; + if(!inArea(newX, newY)) + res += grid[i][j]; + else + res += max(grid[i][j] - grid[newX][newY], 0); + } + } + } + return res; + } + +private: + bool inArea(int x, int y){ + return x >= 0 && x < m && y >= 0 && y < n; + } +}; + + +int main() { + + vector> grid1 = {{2}}; + cout << Solution().surfaceArea(grid1) << endl; + // 10 + + vector> grid2 = {{1, 2}, {3, 4}}; + cout << Solution().surfaceArea(grid2) << endl; + // 34 + + vector> grid3 = {{1, 0}, {0, 2}}; + cout << Solution().surfaceArea(grid3) << endl; + // 16 + + vector> grid4 = {{1, 1, 1}, {1, 0, 1}, {1, 1, 1}}; + cout << Solution().surfaceArea(grid4) << endl; + // 32 + + vector> grid5 = {{2, 2, 2}, {2, 1, 2}, {2, 2, 2}}; + cout << Solution().surfaceArea(grid5) << endl; + // 46 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0893-Groups-of-Special-Equivalent-Strings/cpp-0893/CMakeLists.txt b/0501-1000/0893-Groups-of-Special-Equivalent-Strings/cpp-0893/CMakeLists.txt new file mode 100644 index 00000000..08335525 --- /dev/null +++ b/0501-1000/0893-Groups-of-Special-Equivalent-Strings/cpp-0893/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(B) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main2.cpp) +add_executable(B ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0893-Groups-of-Special-Equivalent-Strings/cpp-0893/main.cpp b/0501-1000/0893-Groups-of-Special-Equivalent-Strings/cpp-0893/main.cpp new file mode 100644 index 00000000..8e27e6a1 --- /dev/null +++ b/0501-1000/0893-Groups-of-Special-Equivalent-Strings/cpp-0893/main.cpp @@ -0,0 +1,72 @@ +/// Source : https://leetcode.com/problems/groups-of-special-equivalent-strings/solution/ +/// Author : liuyubobobo +/// Time : 2018-08-25 + +#include +#include +#include +#include + +using namespace std; + +/// Using Custom Hash Code +/// Time Complexity: O(n * len(s)), where len(s) is the average length of string in A +/// Space Complexity: O(n * len(s)) +class Solution { + +public: + int numSpecialEquivGroups(vector& A) { + + unordered_set groups; + for(const string& s: A) + groups.insert(getHashCode(s)); + return groups.size(); + } + +private: + string getHashCode(const string& s){ + vector freq1(26, 0); + for(int i = 0; i < s.size(); i += 2) + freq1[s[i] - 'a'] ++; + + string res = getFreqString(freq1); + res += "#"; + + vector freq2(26, 0); + for(int i = 1; i < s.size(); i += 2) + freq2[s[i] - 'a'] ++; + + res += getFreqString(freq2); + return res; + } + + string getFreqString(const vector& freq){ + + string res = ""; + for(int e: freq) + res += to_string(e) + " "; + return res; + } +}; + + +int main() { + + vector A1 = {"a","b","c","a","c","c"}; + cout << Solution().numSpecialEquivGroups(A1) << endl; + // 3 + + vector A2 = {"aa","bb","ab","ba"}; + cout << Solution().numSpecialEquivGroups(A2) << endl; + // 4 + + vector A3 = {"abc","acb","bac","bca","cab","cba"}; + cout << Solution().numSpecialEquivGroups(A3) << endl; + // 3 + + vector A4 = {"abcd","cdab","adcb","cbad"}; + cout << Solution().numSpecialEquivGroups(A4) << endl; + // 1 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0893-Groups-of-Special-Equivalent-Strings/cpp-0893/main2.cpp b/0501-1000/0893-Groups-of-Special-Equivalent-Strings/cpp-0893/main2.cpp new file mode 100644 index 00000000..7b1ff7d5 --- /dev/null +++ b/0501-1000/0893-Groups-of-Special-Equivalent-Strings/cpp-0893/main2.cpp @@ -0,0 +1,67 @@ +/// Source : https://leetcode.com/problems/groups-of-special-equivalent-strings/solution/ +/// Author : liuyubobobo +/// Time : 2018-08-26 + +#include +#include +#include +#include + +using namespace std; + + +/// Using HashCode +/// Only one vector is used in getHashCode function +/// +/// Time Complexity: O(n * len(s)), where len(s) is the average length of string in A +/// Space Complexity: O(n * len(s)) +class Solution { + +public: + int numSpecialEquivGroups(vector& A) { + + unordered_set groups; + for(const string& s: A) + groups.insert(getHashCode(s)); + return groups.size(); + } + +private: + string getHashCode(const string& s){ + vector freq(52, 0); + for(int i = 0; i < s.size(); i ++) + freq[(i % 2) * 26 + (s[i] - 'a')] ++; + + return getFreqString(freq); + } + + string getFreqString(const vector& freq){ + + string res = ""; + for(int e: freq) + res += to_string(e) + " "; + return res; + } +}; + + +int main() { + + vector A1 = {"a","b","c","a","c","c"}; + cout << Solution().numSpecialEquivGroups(A1) << endl; + // 3 + + vector A2 = {"aa","bb","ab","ba"}; + cout << Solution().numSpecialEquivGroups(A2) << endl; + // 4 + + vector A3 = {"abc","acb","bac","bca","cab","cba"}; + cout << Solution().numSpecialEquivGroups(A3) << endl; + // 3 + + vector A4 = {"abcd","cdab","adcb","cbad"}; + cout << Solution().numSpecialEquivGroups(A4) << endl; + // 1 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0894-All-Possible-Full-Binary-Trees/cpp-0894/CMakeLists.txt b/0501-1000/0894-All-Possible-Full-Binary-Trees/cpp-0894/CMakeLists.txt new file mode 100644 index 00000000..10d4db6b --- /dev/null +++ b/0501-1000/0894-All-Possible-Full-Binary-Trees/cpp-0894/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(C) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main2.cpp) +add_executable(C ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0894-All-Possible-Full-Binary-Trees/cpp-0894/main.cpp b/0501-1000/0894-All-Possible-Full-Binary-Trees/cpp-0894/main.cpp new file mode 100644 index 00000000..7fb6cb19 --- /dev/null +++ b/0501-1000/0894-All-Possible-Full-Binary-Trees/cpp-0894/main.cpp @@ -0,0 +1,59 @@ +/// Source : https://leetcode.com/problems/all-possible-full-binary-trees/description/ +/// Author : liuyubobobo +/// Time : 2018-08-26 + +#include +#include + +using namespace std; + + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + + +/// Recursion +/// Time Complexity: O(2^n) +/// Space Complexity: O(2^n) +class Solution { + +private: + TreeNode* root; + +public: + vector allPossibleFBT(int N) { + + if(N % 2 == 0) + return {}; + + if(N == 1) + return {new TreeNode(0)}; + + vector ret; + for(int i = 1; i < N; i += 2){ + vector left_vec = allPossibleFBT(i); + vector right_vec = allPossibleFBT(N - 1 - i); + for(TreeNode* left: left_vec) + for(TreeNode* right: right_vec){ + TreeNode* root = new TreeNode(0); + root->left = left; + root->right = right; + ret.push_back(root); + } + } + return ret; + } +}; + + +int main() { + + Solution().allPossibleFBT(7); + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0894-All-Possible-Full-Binary-Trees/cpp-0894/main2.cpp b/0501-1000/0894-All-Possible-Full-Binary-Trees/cpp-0894/main2.cpp new file mode 100644 index 00000000..22ee85b3 --- /dev/null +++ b/0501-1000/0894-All-Possible-Full-Binary-Trees/cpp-0894/main2.cpp @@ -0,0 +1,67 @@ +/// Source : https://leetcode.com/problems/all-possible-full-binary-trees/description/ +/// Author : liuyubobobo +/// Time : 2018-08-26 + +#include +#include +#include + +using namespace std; + + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + + +/// Memory Search +/// Time Complexity: O(n^4), Actually, maybe lower than that:) +/// Space Complexity: O(n^4) +class Solution { + +private: + TreeNode* root; + +public: + vector allPossibleFBT(int N){ + if(N % 2 == 0) + return {}; + + unordered_map> memo; + return allPossibleFBT(N, memo); + } + + vector allPossibleFBT(int N, unordered_map>& memo) { + + if(memo.find(N) != memo.end()) + return memo[N]; + + if(N == 1) + return memo[1] = {new TreeNode(0)}; + + for(int i = 1; i < N; i += 2){ + vector left_vec = allPossibleFBT(i); + vector right_vec = allPossibleFBT(N - 1 - i); + for(TreeNode* left: left_vec) + for(TreeNode* right: right_vec){ + TreeNode* root = new TreeNode(0); + root->left = left; + root->right = right; + memo[N].push_back(root); + } + } + return memo[N]; + } +}; + + +int main() { + + Solution().allPossibleFBT(7); + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0894-All-Possible-Full-Binary-Trees/cpp-0894/main3.cpp b/0501-1000/0894-All-Possible-Full-Binary-Trees/cpp-0894/main3.cpp new file mode 100644 index 00000000..8c405d10 --- /dev/null +++ b/0501-1000/0894-All-Possible-Full-Binary-Trees/cpp-0894/main3.cpp @@ -0,0 +1,61 @@ +/// Source : https://leetcode.com/problems/all-possible-full-binary-trees/description/ +/// Author : liuyubobobo +/// Time : 2018-08-25 + +#include +#include + +using namespace std; + + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + + +/// Dynamic Programming +/// Time Complexity: O(n^4), Actually, maybe lower than that:) +/// Space Complexity: O(n^4) +class Solution { + +private: + TreeNode* root; + +public: + vector allPossibleFBT(int N) { + + vector res; + if(N % 2 == 0) + return res; + + if(N == 1) + return {new TreeNode(0)}; + + vector> dp(N + 1); + dp[1] = {new TreeNode(0)}; + for(int i = 3; i <= N; i += 2){ + // total i nodes + for(int j = 1; j <= i - 1; j += 2){ + // left: j nodes, right: i - 1 - j nodes + for(TreeNode* left: dp[j]) + for(TreeNode* right: dp[i - 1 - j]) { + TreeNode* root = new TreeNode(0); + root->left = left; + root->right = right; + dp[i].push_back(root); + } + } + } + return dp[N]; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0805-Split-Array-With-Same-Average/cpp-0805/CMakeLists.txt b/0501-1000/0895-Maximum-Frequency-Stack/cpp-0895/CMakeLists.txt similarity index 100% rename from 0805-Split-Array-With-Same-Average/cpp-0805/CMakeLists.txt rename to 0501-1000/0895-Maximum-Frequency-Stack/cpp-0895/CMakeLists.txt diff --git a/0501-1000/0895-Maximum-Frequency-Stack/cpp-0895/main.cpp b/0501-1000/0895-Maximum-Frequency-Stack/cpp-0895/main.cpp new file mode 100644 index 00000000..a0d25c7d --- /dev/null +++ b/0501-1000/0895-Maximum-Frequency-Stack/cpp-0895/main.cpp @@ -0,0 +1,86 @@ +/// Source : https://leetcode.com/problems/maximum-frequency-stack/description/ +/// Author : liuyubobobo +/// Time : 2018-08-25 + +#include +#include +#include +#include + +using namespace std; + + +/// Using (freq, time) pair to record the order of all elements +/// Time Complexity: push: O(logn) +/// pop: O(logn) +/// Space Complexity: O(n) +class FreqStack { + +private: + unordered_map> order; + unordered_map> freq; + map, int> data; + + int times = 0; + +public: + FreqStack() { + order.clear(); + freq.clear(); + data.clear(); + times = 0; + } + + void push(int x) { + + if(freq.find(x) == freq.end()) + freq[x] = make_pair(1, times); + else{ + pair p = freq[x]; + p.first += 1; + p.second = times; + freq[x] = p; + } + + data[freq[x]] = x; + order[x].push(times); + + times ++; + } + + int pop() { + pair freqData = data.rbegin()->first; + int key = data.rbegin()->second; + + data.erase(freqData); + freqData.first -= 1; + order[key].pop(); + if(freqData.first == 0) + freq.erase(key); + else { + freqData.second = order[key].top(); + freq[key] = freqData; + data[freqData] = key; + } + + return key; + } +}; + + +int main() { + + FreqStack stack; + stack.push(5); + stack.push(7); + stack.push(5); + stack.push(7); + stack.push(4); + stack.push(5); + + cout << stack.pop() << endl; // 5 + cout << stack.pop() << endl; // 7 + cout << stack.pop() << endl; // 5 + cout << stack.pop() << endl; // 4 + return 0; +} \ No newline at end of file diff --git a/0501-1000/0895-Maximum-Frequency-Stack/cpp-0895/main2.cpp b/0501-1000/0895-Maximum-Frequency-Stack/cpp-0895/main2.cpp new file mode 100644 index 00000000..ba8bbbc0 --- /dev/null +++ b/0501-1000/0895-Maximum-Frequency-Stack/cpp-0895/main2.cpp @@ -0,0 +1,70 @@ +/// Source : https://leetcode.com/problems/maximum-frequency-stack/description/ +/// Author : liuyubobobo +/// Time : 2018-08-26 + +#include +#include +#include +#include + +using namespace std; + + +/// Using Two HashSets: (freq: stack) HashSet and (key: freq) HashSet +/// keeping max_freq in FreqStack to get pop element:) +/// +/// Time Complexity: push: O(1) +/// pop: O(1) +/// Space Complexity: O(n) +class FreqStack { + +private: + unordered_map> order; // freq -> order stack + unordered_map freq; // key -> freq + int max_freq; + +public: + FreqStack() { + order.clear(); + freq.clear(); + max_freq = 0; + } + + void push(int x) { + + freq[x] ++; + order[freq[x]].push(x); + + if(max_freq < freq[x]) + max_freq = freq[x]; + } + + int pop() { + + int ret = order[max_freq].top(); + order[max_freq].pop(); + if(order[max_freq].empty()) + max_freq --; + + freq[ret] --; + return ret; + } +}; + + +int main() { + + FreqStack stack; + stack.push(5); + stack.push(7); + stack.push(5); + stack.push(7); + stack.push(4); + stack.push(5); + + cout << stack.pop() << endl; // 5 + cout << stack.pop() << endl; // 7 + cout << stack.pop() << endl; // 5 + cout << stack.pop() << endl; // 4 + return 0; +} \ No newline at end of file diff --git a/0501-1000/0896-Monotonic-Array/cpp-0896/CMakeLists.txt b/0501-1000/0896-Monotonic-Array/cpp-0896/CMakeLists.txt new file mode 100644 index 00000000..557a8807 --- /dev/null +++ b/0501-1000/0896-Monotonic-Array/cpp-0896/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(A) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main2.cpp) +add_executable(A ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0896-Monotonic-Array/cpp-0896/main.cpp b/0501-1000/0896-Monotonic-Array/cpp-0896/main.cpp new file mode 100644 index 00000000..69514c00 --- /dev/null +++ b/0501-1000/0896-Monotonic-Array/cpp-0896/main.cpp @@ -0,0 +1,39 @@ +/// Source : https://leetcode.com/problems/monotonic-array/description/ +/// Author : liuyubobobo +/// Time : 2018-09-01 + +#include +#include + +using namespace std; + + +/// Two Pass +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + bool isMonotonic(vector& A) { + + int i; + for(i = 1; i < A.size() ; i ++) + if(A[i] < A[i - 1]) + break; + if(i == A.size()) + return true; + + for(i = 1; i < A.size() ; i ++) + if(A[i] > A[i - 1]) + break; + if(i == A.size()) + return true; + + return false; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0896-Monotonic-Array/cpp-0896/main2.cpp b/0501-1000/0896-Monotonic-Array/cpp-0896/main2.cpp new file mode 100644 index 00000000..d2517a3e --- /dev/null +++ b/0501-1000/0896-Monotonic-Array/cpp-0896/main2.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/monotonic-array/description/ +/// Author : liuyubobobo +/// Time : 2018-09-01 + +#include +#include + +using namespace std; + + +/// One Pass +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + bool isMonotonic(vector& A) { + + int trend = 0; + for(int i = 1; i < A.size() ; i ++) + if(trend == 0){ + if(A[i] > A[i - 1]) trend = 1; + else if(A[i] < A[i - 1]) trend = -1; + } + else{ + if(A[i] > A[i - 1] && trend == -1) return false; + else if(A[i] < A[i - 1] && trend == 1) return false; + } + + return true; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0896-Monotonic-Array/py-0896/Solution.py b/0501-1000/0896-Monotonic-Array/py-0896/Solution.py new file mode 100644 index 00000000..122df9fb --- /dev/null +++ b/0501-1000/0896-Monotonic-Array/py-0896/Solution.py @@ -0,0 +1,28 @@ +# Source : https://leetcode.com/problems/monotonic-array/ +# Author : penpenps +# Time : 2019-07-29 + +from typing import List + +# Two pass +# Time Complexity: O(n) +# Space Complexity: O(1) + +class Solution: + def isMonotonic(self, A: List[int]) -> bool: + n = len(A) + i = 1 + while i < n: + if A[i] > A[i-1]: + break + i += 1 + if i == n: + return True + i = 1 + while i < n: + if A[i] < A[i-1]: + break + i += 1 + if i == n: + return True + return False \ No newline at end of file diff --git a/0501-1000/0896-Monotonic-Array/py-0896/Solution2.py b/0501-1000/0896-Monotonic-Array/py-0896/Solution2.py new file mode 100644 index 00000000..86baa841 --- /dev/null +++ b/0501-1000/0896-Monotonic-Array/py-0896/Solution2.py @@ -0,0 +1,23 @@ +# Source : https://leetcode.com/problems/monotonic-array/ +# Author : penpenps +# Time : 2019-07-29 + +from typing import List + +# One pass +# Time Complexity: O(n) +# Space Complexity: O(1) + +class Solution: + def isMonotonic(self, A: List[int]) -> bool: + n = len(A) + trend = 0 + for i in range(1, n): + if trend == 0: + if A[i] > A[i-1]: + trend = 1 + elif A[i] < A[i-1]: + trend = -1 + elif trend * (A[i] - A[i-1]) < 0: + return False + return True \ No newline at end of file diff --git a/0501-1000/0896-Monotonic-Array/py-0896/Solution3.py b/0501-1000/0896-Monotonic-Array/py-0896/Solution3.py new file mode 100644 index 00000000..184241cb --- /dev/null +++ b/0501-1000/0896-Monotonic-Array/py-0896/Solution3.py @@ -0,0 +1,13 @@ +# Source : https://leetcode.com/problems/monotonic-array/ +# Author : penpenps +# Time : 2019-07-29 + +from typing import List + +# One-line solution +# Time Complexity: O(n) +# Space Complexity: O(1) + +class Solution: + def isMonotonic(self, A: List[int]) -> bool: + return not {(x>y) - (y>x) for x, y in zip(A, A[1:])} >= {1, -1} \ No newline at end of file diff --git a/0501-1000/0897-Increasing-Order-Search-Tree/cpp-0897/CMakeLists.txt b/0501-1000/0897-Increasing-Order-Search-Tree/cpp-0897/CMakeLists.txt new file mode 100644 index 00000000..45cd0786 --- /dev/null +++ b/0501-1000/0897-Increasing-Order-Search-Tree/cpp-0897/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(B) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main4.cpp) +add_executable(B ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0897-Increasing-Order-Search-Tree/cpp-0897/main.cpp b/0501-1000/0897-Increasing-Order-Search-Tree/cpp-0897/main.cpp new file mode 100644 index 00000000..f8aa2c9f --- /dev/null +++ b/0501-1000/0897-Increasing-Order-Search-Tree/cpp-0897/main.cpp @@ -0,0 +1,56 @@ +/// Source : https://leetcode.com/problems/increasing-order-search-tree/description/ +/// Author : liuyubobobo +/// Time : 2018-09-01 + +#include +#include + +using namespace std; + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + + +/// Inorder traversal and store all the nodes +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + TreeNode* increasingBST(TreeNode* root) { + + if(root == NULL) + return NULL; + + vector nodes; + inOrder(root, nodes); + + for(int i = 1; i < nodes.size(); i ++){ + nodes[i - 1]->left = NULL; + nodes[i - 1]->right = nodes[i]; + } + nodes.back()->left = nodes.back()->right = NULL; + return nodes[0]; + } + +private: + void inOrder(TreeNode* node, vector& nodes){ + + if(node == NULL) + return; + + inOrder(node->left, nodes); + nodes.push_back(node); + inOrder(node->right, nodes); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0897-Increasing-Order-Search-Tree/cpp-0897/main2.cpp b/0501-1000/0897-Increasing-Order-Search-Tree/cpp-0897/main2.cpp new file mode 100644 index 00000000..b146f493 --- /dev/null +++ b/0501-1000/0897-Increasing-Order-Search-Tree/cpp-0897/main2.cpp @@ -0,0 +1,69 @@ +/// Source : https://leetcode.com/problems/increasing-order-search-tree/description/ +/// Author : liuyubobobo +/// Time : 2018-09-01 + +#include +#include + +using namespace std; + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + + +/// Inorder traversal and link during the traversal +/// Time Complexity: O(n) +/// Space Complexity: O(h) where h is the height of the tree +class Solution { +public: + TreeNode* increasingBST(TreeNode* root) { + + if(root == NULL) + return NULL; + + TreeNode* tail; + return inOrder(root, tail); + } + +private: + TreeNode* inOrder(TreeNode* node, TreeNode* &tail){ + + if(node->left == NULL && node->right == NULL){ + tail = node; + return node; + } + + TreeNode* ret; + if(node->left){ + ret = inOrder(node->left, tail); + tail->left = NULL; + tail->right = node; + } + else + ret = node; + + node->left = NULL; + tail = node; + if(node->right) { + TreeNode *root = inOrder(node->right, tail); + node->right = root; + } + + return ret; + } +}; + + +int main() { + + TreeNode* root = new TreeNode(1); + root->left = new TreeNode(2); + Solution().increasingBST(root); + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0897-Increasing-Order-Search-Tree/cpp-0897/main3.cpp b/0501-1000/0897-Increasing-Order-Search-Tree/cpp-0897/main3.cpp new file mode 100644 index 00000000..5ed5369b --- /dev/null +++ b/0501-1000/0897-Increasing-Order-Search-Tree/cpp-0897/main3.cpp @@ -0,0 +1,68 @@ +/// Source : https://leetcode.com/problems/increasing-order-search-tree/description/ +/// Author : liuyubobobo +/// Time : 2018-09-01 + +#include +#include + +using namespace std; + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + + +/// Inorder traversal and link during the traversal +/// Using a class member TreeNode cur:) +/// +/// Time Complexity: O(n) +/// Space Complexity: O(h) where h is the height of the tree +class Solution { + +private: + TreeNode* cur; + +public: + TreeNode* increasingBST(TreeNode* root) { + + if(root == NULL) + return NULL; + + TreeNode* dummyRoot = new TreeNode(-1); + cur = dummyRoot; + inOrder(root); + + TreeNode* ret = dummyRoot->right; + delete dummyRoot; + return ret; + } + +private: + void inOrder(TreeNode* node){ + + if(node == NULL) + return; + + inOrder(node->left); + + cur->right = node; + cur = cur->right; + cur->left = NULL; + + inOrder(node->right); + } +}; + + +int main() { + + TreeNode* root = new TreeNode(1); + root->left = new TreeNode(2); + Solution().increasingBST(root); + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0897-Increasing-Order-Search-Tree/cpp-0897/main4.cpp b/0501-1000/0897-Increasing-Order-Search-Tree/cpp-0897/main4.cpp new file mode 100644 index 00000000..8d4d761c --- /dev/null +++ b/0501-1000/0897-Increasing-Order-Search-Tree/cpp-0897/main4.cpp @@ -0,0 +1,81 @@ +/// Source : https://leetcode.com/problems/increasing-order-search-tree/description/ +/// Author : liuyubobobo +/// Time : 2018-09-02 + +#include +#include + +using namespace std; + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + + +/// Using Morris Treversal +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { + +private: + TreeNode* cur; + +public: + TreeNode* increasingBST(TreeNode* root) { + + if(root == NULL) + return NULL; + + TreeNode* dummyRoot = new TreeNode(-1); + cur = dummyRoot; + + // Morris Traversal + TreeNode* node = root; + while(node){ + if(node->left == NULL){ + cur->right = node; + cur = cur->right; + cur->left = NULL; + + node = node->right; + } + else{ + TreeNode* prev = node->left; + while(prev->right && prev->right != node) + prev = prev->right; + + if(prev->right == NULL){ + prev->right = node; + node = node->left; + } + else{ + prev->right = NULL; + + cur->right = node; + cur = cur->right; + cur->left = NULL; + + node = node->right; + } + } + } + + TreeNode* ret = dummyRoot->right; + delete dummyRoot; + return ret; + } +}; + + +int main() { + + TreeNode* root = new TreeNode(1); + root->left = new TreeNode(2); + Solution().increasingBST(root); + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0898-Bitwise-ORs-of-Subarrays/cpp-0898/CMakeLists.txt b/0501-1000/0898-Bitwise-ORs-of-Subarrays/cpp-0898/CMakeLists.txt new file mode 100644 index 00000000..dc6dbe4c --- /dev/null +++ b/0501-1000/0898-Bitwise-ORs-of-Subarrays/cpp-0898/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0898) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0898 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0898-Bitwise-ORs-of-Subarrays/cpp-0898/main.cpp b/0501-1000/0898-Bitwise-ORs-of-Subarrays/cpp-0898/main.cpp new file mode 100644 index 00000000..67962406 --- /dev/null +++ b/0501-1000/0898-Bitwise-ORs-of-Subarrays/cpp-0898/main.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/bitwise-ors-of-subarrays/description/ +/// Author : liuyubobobo +/// Time : 2018-09-02 + +#include +#include +#include + +using namespace std; + + +/// Frontier Hash Set +/// Time Complexity: O(n*log(max_number)) +/// Space Complexity: O(n*log(max_number)) +class Solution { +public: + int subarrayBitwiseORs(vector& A) { + + unordered_set res; + unordered_set frontier; + unordered_set cur; + for(int a: A){ + cur.clear(); + cur.insert(a); + for(int x: frontier) + cur.insert(x | a); + + res.insert(cur.begin(), cur.end()); + frontier = cur; + } + + return res.size(); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0899-Orderly-Queue/cpp-0899/CMakeLists.txt b/0501-1000/0899-Orderly-Queue/cpp-0899/CMakeLists.txt new file mode 100644 index 00000000..e0015796 --- /dev/null +++ b/0501-1000/0899-Orderly-Queue/cpp-0899/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0899) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0899 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0899-Orderly-Queue/cpp-0899/main.cpp b/0501-1000/0899-Orderly-Queue/cpp-0899/main.cpp new file mode 100644 index 00000000..013b01c4 --- /dev/null +++ b/0501-1000/0899-Orderly-Queue/cpp-0899/main.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/orderly-queue/description/ +/// Author : liuyubobobo +/// Time : 2018-09-02 + +#include + +using namespace std; + + +/// Mathematic +/// When K = 1, solve it brutely +/// When K = 2, we can get any permutation of the S +/// When K > 2, we can also get any permutation of the S +/// +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { +public: + string orderlyQueue(string S, int K) { + + if(K == 1){ + string ret = S; + for(int len = 1; len < S.size(); len ++){ + string t_ret = S.substr(len) + S.substr(0, len); + if(t_ret < ret) + ret = t_ret; + } + return ret; + } + + sort(S.begin(), S.end()); + return S; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0900-RLE-Iterator/cpp-0900/CMakeLists.txt b/0501-1000/0900-RLE-Iterator/cpp-0900/CMakeLists.txt new file mode 100644 index 00000000..4361a6de --- /dev/null +++ b/0501-1000/0900-RLE-Iterator/cpp-0900/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0900) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0900 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0900-RLE-Iterator/cpp-0900/main.cpp b/0501-1000/0900-RLE-Iterator/cpp-0900/main.cpp new file mode 100644 index 00000000..6ad2d940 --- /dev/null +++ b/0501-1000/0900-RLE-Iterator/cpp-0900/main.cpp @@ -0,0 +1,55 @@ +/// Source : https://leetcode.com/problems/rle-iterator/description/ +/// Author : liuyubobobo +/// Time : 2018-09-10 + +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: init: O(n) +/// next: O(n) +/// Space Complexity: O(n) +class RLEIterator { + +private: + vector A; + int curnum_index = 1, index = 0; + +public: + RLEIterator(vector A) { + for(int a: A) + this->A.push_back(a); + } + + int next(int n) { + + if(curnum_index >= A.size()) + return -1; + + index += n; + while(curnum_index < A.size() && index > A[curnum_index - 1]){ + index -= A[curnum_index - 1]; + curnum_index += 2; + } + + if(curnum_index < A.size() && index <= A[curnum_index - 1]) + return A[curnum_index]; + return -1; + } +}; + + +int main() { + + vector A = {3, 8, 0, 9, 2, 5}; + RLEIterator rleIterator(A); + cout << rleIterator.next(2) << endl; // 8 + cout << rleIterator.next(1) << endl; // 8 + cout << rleIterator.next(1) << endl; // 5 + cout << rleIterator.next(2) << endl; // -1 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0901-Online-Stock-Span/cpp-0901/CMakeLists.txt b/0501-1000/0901-Online-Stock-Span/cpp-0901/CMakeLists.txt new file mode 100644 index 00000000..3844251f --- /dev/null +++ b/0501-1000/0901-Online-Stock-Span/cpp-0901/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0901) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0901 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0901-Online-Stock-Span/cpp-0901/main.cpp b/0501-1000/0901-Online-Stock-Span/cpp-0901/main.cpp new file mode 100644 index 00000000..28eeee16 --- /dev/null +++ b/0501-1000/0901-Online-Stock-Span/cpp-0901/main.cpp @@ -0,0 +1,55 @@ +/// Source : https://leetcode.com/problems/online-stock-span/description/ +/// Author : liuyubobobo +/// Time : 2018-09-10 + +#include +#include + +using namespace std; + + +/// Using Stack +/// Time Complexity: init: O(1) +/// next: O(1) - average +/// Space Complexity: O(n) +class StockSpanner { + +private: + vector> nums; + +public: + StockSpanner() { + nums.clear(); + } + + int next(int price) { + + if(nums.size() == 0 || price < nums.back().first){ + nums.push_back(make_pair(price, 1)); + return 1; + } + + int cnt = 1; + while(!nums.empty() && nums.back().first <= price){ + cnt += nums.back().second; + nums.pop_back(); + } + nums.push_back(make_pair(price, cnt)); + return cnt; + } +}; + + +int main() { + + StockSpanner stockSpanner; + cout << stockSpanner.next(100) << endl; // 1 + cout << stockSpanner.next(80) << endl; // 1 + cout << stockSpanner.next(60) << endl; // 1 + cout << stockSpanner.next(70) << endl; // 2 + cout << stockSpanner.next(60) << endl; // 1 + cout << stockSpanner.next(75) << endl; // 4 + cout << stockSpanner.next(85) << endl; // 6 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0902-Numbers-At-Most-N-Given-Digit-Set/cpp-0902/CMakeLists.txt b/0501-1000/0902-Numbers-At-Most-N-Given-Digit-Set/cpp-0902/CMakeLists.txt new file mode 100644 index 00000000..7dcc6f96 --- /dev/null +++ b/0501-1000/0902-Numbers-At-Most-N-Given-Digit-Set/cpp-0902/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0902) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main5.cpp) +add_executable(cpp_0902 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0902-Numbers-At-Most-N-Given-Digit-Set/cpp-0902/main.cpp b/0501-1000/0902-Numbers-At-Most-N-Given-Digit-Set/cpp-0902/main.cpp new file mode 100644 index 00000000..97b9085f --- /dev/null +++ b/0501-1000/0902-Numbers-At-Most-N-Given-Digit-Set/cpp-0902/main.cpp @@ -0,0 +1,83 @@ +/// Source : https://leetcode.com/problems/numbers-at-most-n-given-digit-set/description/ +/// Author : liuyubobobo +/// Time : 2018-09-10 + +#include +#include +#include + +using namespace std; + + +/// Recursion, lots of details need to be deal with in this version of code :-( +/// Time Complexity: (logN) +/// Space Complexity: O(logN) +class Solution { +public: + int atMostNGivenDigitSet(vector& D, int N) { + + string dset = ""; + for(string d: D) + dset += d; + + int res = 0; + int dnum = to_string(N).size(); + for(int i = 1; i < dnum; i ++) + res += (int)pow(dset.size(), i); + + return res + atMostNGivenDigitSet(dset, N, dnum); + } + +private: + int atMostNGivenDigitSet(const string& dset, int N, int d){ + + int dnum = to_string(N).size(); + if(dnum < d) + return 0; + if(dnum == 1){ + int res = 0; + for(char c: dset) + if(c - '0' <= N) + res ++; + return res; + } + + int res = 0; + char leftmost = to_string(N)[0]; + for(int i = 0; i < dset.size(); i ++) + if(dset[i] < leftmost) + res += (int)pow(dset.size(), dnum - 1); + else if(dset[i] == leftmost) + res += atMostNGivenDigitSet(dset, N - (leftmost - '0') * pow(10, dnum - 1), dnum - 1); + else + break; + + return res; + } +}; + + +int main() { + + vector D1 = {"1","3","5","7"}; + cout << Solution().atMostNGivenDigitSet(D1, 100) << endl; + // 20 + + vector D2 = {"1", "4", "9"}; + cout << Solution().atMostNGivenDigitSet(D2, 1000000000) << endl; + // 29523 + + vector D3 = {"3", "4", "8"}; + cout << Solution().atMostNGivenDigitSet(D3, 4) << endl; + // 2 + + vector D4 = {"1", "2", "3", "6", "7", "8"}; + cout << Solution().atMostNGivenDigitSet(D4, 211) << endl; + // 79 + + vector D5 = {"1", "5", "7", "8"}; + cout << Solution().atMostNGivenDigitSet(D5, 10212) << endl; + // 340 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0902-Numbers-At-Most-N-Given-Digit-Set/cpp-0902/main2.cpp b/0501-1000/0902-Numbers-At-Most-N-Given-Digit-Set/cpp-0902/main2.cpp new file mode 100644 index 00000000..25544c8f --- /dev/null +++ b/0501-1000/0902-Numbers-At-Most-N-Given-Digit-Set/cpp-0902/main2.cpp @@ -0,0 +1,77 @@ +/// Source : https://leetcode.com/problems/numbers-at-most-n-given-digit-set/description/ +/// Author : liuyubobobo +/// Time : 2018-09-11 + +#include +#include +#include + +using namespace std; + + +/// Recursion +/// Second version of codes, more clear :-) +/// +/// Time Complexity: (logN) +/// Space Complexity: O(logN) +class Solution { +public: + int atMostNGivenDigitSet(vector& D, int N) { + + string dset = ""; + for(string d: D) + dset += d; + + int res = 0; + int dnum = to_string(N).size(); + for(int i = 1; i < dnum; i ++) + res += (int)pow(dset.size(), i); + + return res + atMostNGivenDigitSet(dset, to_string(N)); + } + +private: + int atMostNGivenDigitSet(const string& dset, const string& snum){ + + int dnum = snum.size(); + if(snum.size() == 0) + return 1; + + int res = 0; + for(int i = 0; i < dset.size(); i ++) + if(dset[i] < snum[0]) + res += (int)pow(dset.size(), snum.size() - 1); + else if(dset[i] == snum[0]) + res += atMostNGivenDigitSet(dset, snum.substr(1)); + else + break; + + return res; + } +}; + + +int main() { + + vector D1 = {"1","3","5","7"}; + cout << Solution().atMostNGivenDigitSet(D1, 100) << endl; + // 20 + + vector D2 = {"1", "4", "9"}; + cout << Solution().atMostNGivenDigitSet(D2, 1000000000) << endl; + // 29523 + + vector D3 = {"3", "4", "8"}; + cout << Solution().atMostNGivenDigitSet(D3, 4) << endl; + // 2 + + vector D4 = {"1", "2", "3", "6", "7", "8"}; + cout << Solution().atMostNGivenDigitSet(D4, 211) << endl; + // 79 + + vector D5 = {"1", "5", "7", "8"}; + cout << Solution().atMostNGivenDigitSet(D5, 10212) << endl; + // 340 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0902-Numbers-At-Most-N-Given-Digit-Set/cpp-0902/main3.cpp b/0501-1000/0902-Numbers-At-Most-N-Given-Digit-Set/cpp-0902/main3.cpp new file mode 100644 index 00000000..d7de66fc --- /dev/null +++ b/0501-1000/0902-Numbers-At-Most-N-Given-Digit-Set/cpp-0902/main3.cpp @@ -0,0 +1,81 @@ +/// Source : https://leetcode.com/problems/numbers-at-most-n-given-digit-set/description/ +/// Author : liuyubobobo +/// Time : 2018-09-11 + +#include +#include +#include + +using namespace std; + + +/// Memorization +/// Time Complexity: (logN) +/// Space Complexity: O(logN) +class Solution { + +public: + int atMostNGivenDigitSet(vector& D, int N) { + + string dset = ""; + for(string d: D) + dset += d; + + int res = 0; + int dnum = to_string(N).size(); + for(int i = 1; i < dnum; i ++) + res += (int)pow(dset.size(), i); + + // dp[i]: the number of num <= last i digits of N + vector dp(dnum + 1, -1); + return res + atMostNGivenDigitSet(dset, to_string(N), dp); + } + +private: + int atMostNGivenDigitSet(const string& dset, const string& snum, + vector& dp){ + + if(snum.size() == 0) + return 1; + + if(dp[snum.size()] != -1) + return dp[snum.size()]; + + int res = 0; + for(int i = 0; i < dset.size(); i ++) + if(dset[i] < snum[0]) + res += (int)pow(dset.size(), snum.size() - 1); + else if(dset[i] == snum[0]) + res += atMostNGivenDigitSet(dset, snum.substr(1), dp); + else + break; + + return dp[snum.size()] = res; + } +}; + + +int main() { + + vector D1 = {"1","3","5","7"}; + cout << Solution().atMostNGivenDigitSet(D1, 100) << endl; + // 20 + + vector D2 = {"1", "4", "9"}; + cout << Solution().atMostNGivenDigitSet(D2, 1000000000) << endl; + // 29523 + + vector D3 = {"3", "4", "8"}; + cout << Solution().atMostNGivenDigitSet(D3, 4) << endl; + // 2 + + vector D4 = {"1", "2", "3", "6", "7", "8"}; + cout << Solution().atMostNGivenDigitSet(D4, 211) << endl; + // 79 + + vector D5 = {"1", "5", "7", "8"}; + cout << Solution().atMostNGivenDigitSet(D5, 10212) << endl; + // 340 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0902-Numbers-At-Most-N-Given-Digit-Set/cpp-0902/main4.cpp b/0501-1000/0902-Numbers-At-Most-N-Given-Digit-Set/cpp-0902/main4.cpp new file mode 100644 index 00000000..36316c4a --- /dev/null +++ b/0501-1000/0902-Numbers-At-Most-N-Given-Digit-Set/cpp-0902/main4.cpp @@ -0,0 +1,71 @@ +/// Source : https://leetcode.com/problems/numbers-at-most-n-given-digit-set/description/ +/// Author : liuyubobobo +/// Time : 2018-09-11 + +#include +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: (logN) +/// Space Complexity: O(logN) +class Solution { + +public: + int atMostNGivenDigitSet(vector& D, int N) { + + string dset = ""; + for(string d: D) + dset += d; + + string snum = to_string(N); + int dnum = snum.size(); + + // dp[i]: the number of num <= last i digits of N + vector dp(dnum + 1, 0); + dp[0] = 1; + for(int i = 1; i <= dnum; i ++){ + for(int j = 0; j < dset.size(); j ++) + if(dset[j] < snum[dnum - i]) + dp[i] += (int)pow(dset.size(), i - 1); + else if(dset[j] == snum[dnum - i]) + dp[i] += dp[i - 1]; + else + break; + } + + int res = 0; + for(int i = 1; i < dnum; i ++) + res += (int)pow(dset.size(), i); + return res + dp[dnum]; + } +}; + + +int main() { + + vector D1 = {"1","3","5","7"}; + cout << Solution().atMostNGivenDigitSet(D1, 100) << endl; + // 20 + + vector D2 = {"1", "4", "9"}; + cout << Solution().atMostNGivenDigitSet(D2, 1000000000) << endl; + // 29523 + + vector D3 = {"3", "4", "8"}; + cout << Solution().atMostNGivenDigitSet(D3, 4) << endl; + // 2 + + vector D4 = {"1", "2", "3", "6", "7", "8"}; + cout << Solution().atMostNGivenDigitSet(D4, 211) << endl; + // 79 + + vector D5 = {"1", "5", "7", "8"}; + cout << Solution().atMostNGivenDigitSet(D5, 10212) << endl; + // 340 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0902-Numbers-At-Most-N-Given-Digit-Set/cpp-0902/main5.cpp b/0501-1000/0902-Numbers-At-Most-N-Given-Digit-Set/cpp-0902/main5.cpp new file mode 100644 index 00000000..3b5a36a1 --- /dev/null +++ b/0501-1000/0902-Numbers-At-Most-N-Given-Digit-Set/cpp-0902/main5.cpp @@ -0,0 +1,96 @@ +/// Source : https://leetcode.com/problems/numbers-at-most-n-given-digit-set/description/ +/// Author : liuyubobobo +/// Time : 2018-09-11 + +#include +#include +#include + +using namespace std; + + +/// Mathematics +/// map digits of D into {0, 1, 2, ...} +/// if there're d digits in D, then it's a d-based number problem +/// +/// Time Complexity: (logN) +/// Space Complexity: O(logN) +class Solution { + +public: + int atMostNGivenDigitSet(vector& D, int N) { + + string dset = ""; + for(string d: D) + dset += d; + + unordered_map dmap; + for(int i = 0; i < dset.size(); i ++) + dmap[dset[i]] = i + 1; + + string snum = to_string(N); + for(int i = 0; i < snum.size(); i ++){ + int j; + for(j = 0; j <= dset.size(); j ++) + if(j == dset.size() || dset[j] > snum[i]){ + int k; + snum[i] = dset[j - 1]; + for(k = i; k >= 0 && snum[k] == '0'; k--); + if(k >= 0) snum[k] = dmap[snum[k]] - 1 >= 0 ? dset[dmap[snum[k]] - 1] : '0'; + for(k = k + 1; k < snum.size(); k ++) + snum[k] = dset.back(); + break; + } + else if(dset[j] == snum[i]) + break; + } + +// cout << "sum:" << snum << endl; + int res = 0; + for(char c: snum) + res = res * dset.size() + dmap[c]; + return res; + } +}; + + +int main() { + + vector D1 = {"1","3","5","7"}; + cout << Solution().atMostNGivenDigitSet(D1, 100) << endl; + // 20 + + vector D2 = {"1", "4", "9"}; + cout << Solution().atMostNGivenDigitSet(D2, 1000000000) << endl; + // 29523 + + vector D3 = {"3", "4", "8"}; + cout << Solution().atMostNGivenDigitSet(D3, 4) << endl; + // 2 + + vector D4 = {"1", "2", "3", "6", "7", "8"}; + cout << Solution().atMostNGivenDigitSet(D4, 211) << endl; + // 79 + + vector D5 = {"1", "5", "7", "8"}; + cout << Solution().atMostNGivenDigitSet(D5, 10212) << endl; + // 340 + + vector D6 = {"7"}; + cout << Solution().atMostNGivenDigitSet(D6, 8) << endl; + // 1 + + vector D7 = {"1", "7"}; + cout << Solution().atMostNGivenDigitSet(D7, 231) << endl; + // 10 + + vector D8 = {"1", "6", "7", "8", "9"}; + cout << Solution().atMostNGivenDigitSet(D8, 433) << endl; + // 55 + + vector D9 = {"5"}; + cout << Solution().atMostNGivenDigitSet(D9, 6122) << endl; + // 4 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0903-Valid-Permutations-for-DI-Sequence/cpp-0903/CMakeLists.txt b/0501-1000/0903-Valid-Permutations-for-DI-Sequence/cpp-0903/CMakeLists.txt new file mode 100644 index 00000000..2a9f1847 --- /dev/null +++ b/0501-1000/0903-Valid-Permutations-for-DI-Sequence/cpp-0903/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0903) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main2.cpp) +add_executable(cpp_0903 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0903-Valid-Permutations-for-DI-Sequence/cpp-0903/main.cpp b/0501-1000/0903-Valid-Permutations-for-DI-Sequence/cpp-0903/main.cpp new file mode 100644 index 00000000..77f722e9 --- /dev/null +++ b/0501-1000/0903-Valid-Permutations-for-DI-Sequence/cpp-0903/main.cpp @@ -0,0 +1,78 @@ +/// Source : https://leetcode.com/problems/valid-permutations-for-di-sequence/description/ +/// Author : liuyubobobo +/// Time : 2018-09-13 + +#include +#include +#include + +using namespace std; + + +/// Memory Search +/// Put minimum number in interval [l...r] +/// +/// Time Complexity: O(n^3) +/// Space Complexity: O(n^2) +class Solution { + +private: + vector> C; + const int MOD = 1e9 + 7; + +public: + int numPermsDISequence(string S) { + + calcC(); + vector> dp(201, vector(201, -1)); + return go(S, 0, S.size(), dp); + } + +private: + int go(const string& s, int l, int r, vector>& dp){ + + assert(l <= r); + if(l == r) + return 1; + + if(dp[l][r] != -1) + return dp[l][r]; + + int res = 0; + if(s[l] == 'I') + res = (res + go(s, l + 1, r, dp)) % MOD; + if(s[r - 1] == 'D') + res = (res + go(s, l, r - 1, dp)) % MOD; + for(int i = l + 1; i < r; i ++) + if(s.substr(i - 1, 2) == "DI"){ + int leftnum = i - l; + res = (res + ((long long)C[r - l][leftnum] * ((long long)go(s, l, i - 1, dp)) % (long long)MOD + * (long long)go(s, i + 1, r, dp)) % (long long)MOD) % MOD; + } + return dp[l][r] = res; + } + + void calcC(){ + C.clear(); + for(int i = 0; i <= 200; i ++) + C.push_back(vector(201, 0)); + + for(int i = 0; i <= 200; i ++){ + C[i][0] = 1; + for(int j = 1; j <= i; j ++) + C[i][j] = (C[i - 1][j] + C[i - 1][j - 1]) % MOD; + } + } +}; + + +int main() { + + cout << Solution().numPermsDISequence("DID") << endl; + // 5 + + cout << Solution().numPermsDISequence("ID") << endl; + // 2 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0903-Valid-Permutations-for-DI-Sequence/cpp-0903/main2.cpp b/0501-1000/0903-Valid-Permutations-for-DI-Sequence/cpp-0903/main2.cpp new file mode 100644 index 00000000..bff6380d --- /dev/null +++ b/0501-1000/0903-Valid-Permutations-for-DI-Sequence/cpp-0903/main2.cpp @@ -0,0 +1,70 @@ +/// Source : https://leetcode.com/problems/valid-permutations-for-di-sequence/description/ +/// Author : liuyubobobo +/// Time : 2018-09-13 + +#include +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Put minimum number in interval [l...r] +/// +/// Time Complexity: O(n^3) +/// Space Complexity: O(n^2) +class Solution { + +private: + vector> C; + const int MOD = 1e9 + 7; + +public: + int numPermsDISequence(string S) { + + calcC(); + + vector> dp(201, vector(201, 1)); + for(int len = 3; len <= S.size() + 1; len ++) + for(int l = 0; l + len - 1 <= S.size(); l ++){ + dp[l][len] = 0; + if(S[l] == 'I') + dp[l][len] = (dp[l][len] + dp[l + 1][len - 1]) % MOD; + if(S[l + len - 2] == 'D') + dp[l][len] = (dp[l][len] + dp[l][len - 1]) % MOD; + for(int k = l + 1; k < l + len - 1; k ++) + if(S.substr(k - 1, 2) == "DI") { + int leftnum = k - l; + dp[l][len] = (dp[l][len] + (((long long)C[len - 1][leftnum] * (long long)dp[l][leftnum]) % (long long)MOD + * (long long)dp[k + 1][len - leftnum - 1]) % (long long) MOD) % MOD; + } + } + return dp[0][S.size() + 1]; + } + +private: + void calcC(){ + C.clear(); + for(int i = 0; i <= 200; i ++) + C.push_back(vector(201, 0)); + + for(int i = 0; i <= 200; i ++){ + C[i][0] = 1; + for(int j = 1; j <= i; j ++) + C[i][j] = (C[i - 1][j] + C[i - 1][j - 1]) % MOD; + } + } +}; + + +int main() { + + cout << Solution().numPermsDISequence("DID") << endl; + // 5 + + cout << Solution().numPermsDISequence("ID") << endl; + // 2 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0904-Fruit-Into-Baskets/cpp-0904/CMakeLists.txt b/0501-1000/0904-Fruit-Into-Baskets/cpp-0904/CMakeLists.txt new file mode 100644 index 00000000..08335525 --- /dev/null +++ b/0501-1000/0904-Fruit-Into-Baskets/cpp-0904/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(B) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main2.cpp) +add_executable(B ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0904-Fruit-Into-Baskets/cpp-0904/main.cpp b/0501-1000/0904-Fruit-Into-Baskets/cpp-0904/main.cpp new file mode 100644 index 00000000..b5ccf75f --- /dev/null +++ b/0501-1000/0904-Fruit-Into-Baskets/cpp-0904/main.cpp @@ -0,0 +1,65 @@ +/// Source : https://leetcode.com/problems/fruit-into-baskets/description/ +/// Author : liuyubobobo +/// Time : 2018-09-15 + +#include +#include +#include + +using namespace std; + + +/// Segment the array into blocks +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int totalFruit(vector& tree) { + + vector> blocks; + int start = 0; + for(int i = start + 1; i <= tree.size(); i ++) + if(i == tree.size() || tree[i] != tree[start]){ + blocks.push_back(make_pair(tree[start], i - start)); + start = i; + i = start; + } +// for(const pair& p: blocks) +// cout << "(" << p.first << "," << p.second << ") "; +// cout << endl; + + int res = 0; + unordered_set fruits; + int sum = 0; + for(int i = 0; i <= blocks.size();) + if(i == blocks.size() || (fruits.size() == 2 && fruits.count(blocks[i].first) == 0)){ + res = max(res, sum); + + if(i < blocks.size()){ + sum = 0; + i --; + fruits.clear(); + } + else + break; + } + else{ + fruits.insert(blocks[i].first); + sum += blocks[i].second; + i ++; + } + return res; + } +}; + + +int main() { + + vector nums1 = {1, 2, 1}; + cout << Solution().totalFruit(nums1) << endl; + + vector nums2 = {0, 1, 2, 2}; + cout << Solution().totalFruit(nums2) << endl; + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0904-Fruit-Into-Baskets/cpp-0904/main2.cpp b/0501-1000/0904-Fruit-Into-Baskets/cpp-0904/main2.cpp new file mode 100644 index 00000000..fa9f1483 --- /dev/null +++ b/0501-1000/0904-Fruit-Into-Baskets/cpp-0904/main2.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/fruit-into-baskets/description/ +/// Author : liuyubobobo +/// Time : 2018-09-15 + +#include +#include +#include + +using namespace std; + + +/// Sliding Window +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int totalFruit(vector& tree) { + + unordered_map freq; + int l = 0, r = -1, res = 0; + while(l < tree.size()){ + if(freq.size() <= 2 && r + 1 < tree.size()){ + r ++; + freq[tree[r]] ++; + } + else{ + freq[tree[l]] --; + if(freq[tree[l]] == 0) + freq.erase(tree[l]); + l ++; + } + + if(freq.size() <= 2) + res = max(res, getFruits(freq)); + } + return res; + } + +private: + int getFruits(const unordered_map& freq){ + int res = 0; + for(const pair& p: freq) + res += p.second; + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0905-Sort-Array-By-Parity/cpp-0905/CMakeLists.txt b/0501-1000/0905-Sort-Array-By-Parity/cpp-0905/CMakeLists.txt new file mode 100644 index 00000000..5cc31b93 --- /dev/null +++ b/0501-1000/0905-Sort-Array-By-Parity/cpp-0905/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(A) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main3.cpp) +add_executable(A ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0905-Sort-Array-By-Parity/cpp-0905/main.cpp b/0501-1000/0905-Sort-Array-By-Parity/cpp-0905/main.cpp new file mode 100644 index 00000000..467acca3 --- /dev/null +++ b/0501-1000/0905-Sort-Array-By-Parity/cpp-0905/main.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/sort-array-by-parity/solution/ +/// Author : liuyubobobo +/// Time : 2018-09-15 + +#include +#include + +using namespace std; + + +/// Two Pass +/// Time Complexity : O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector sortArrayByParity(vector& A) { + + vector ret; + for(int a: A) + if(a % 2 == 0) + ret.push_back(a); + for(int a: A) + if(a % 2) + ret.push_back(a); + return ret; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0905-Sort-Array-By-Parity/cpp-0905/main2.cpp b/0501-1000/0905-Sort-Array-By-Parity/cpp-0905/main2.cpp new file mode 100644 index 00000000..fae8f8fd --- /dev/null +++ b/0501-1000/0905-Sort-Array-By-Parity/cpp-0905/main2.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/sort-array-by-parity/solution/ +/// Author : liuyubobobo +/// Time : 2018-09-15 + +#include +#include + +using namespace std; + + +/// Sorting by custom comparator +/// Time Complexity : O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + vector sortArrayByParity(vector& A) { + + sort(A.begin(), A.end(), cmp); + return A; + } + +private: + static bool cmp(int a, int b){ + if(a % 2 != b % 2) + return a % 2 == 0; + else + return a < b; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0905-Sort-Array-By-Parity/cpp-0905/main3.cpp b/0501-1000/0905-Sort-Array-By-Parity/cpp-0905/main3.cpp new file mode 100644 index 00000000..be475978 --- /dev/null +++ b/0501-1000/0905-Sort-Array-By-Parity/cpp-0905/main3.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/sort-array-by-parity/solution/ +/// Author : liuyubobobo +/// Time : 2018-09-15 + +#include +#include + +using namespace std; + + +/// Rearrange in place +/// Time Complexity : O(n) +/// Space Complexity: O(1) +class Solution { +public: + vector sortArrayByParity(vector& A) { + + for(int i = 0; i < A.size(); i ++) + if(A[i] % 2){ + int j = nextEven(A, i + 1); + if(j < A.size()) + swap(A[i], A[j]); + } + return A; + } + +private: + int nextEven(const vector& A, int start){ + + for(int i = start; i < A.size(); i ++) + if(A[i] % 2 == 0) + return i; + return A.size(); + } +}; + + +void print_vec(const vector& vec){ + for(int e: vec) + cout << e << " "; + cout << endl; +} + +int main() { + + vector nums {3, 1, 2, 4}; + print_vec(Solution().sortArrayByParity(nums)); + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0906-Super-Palindromes/cpp-0906/CMakeLists.txt b/0501-1000/0906-Super-Palindromes/cpp-0906/CMakeLists.txt new file mode 100644 index 00000000..2a61a012 --- /dev/null +++ b/0501-1000/0906-Super-Palindromes/cpp-0906/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0906) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0906 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0906-Super-Palindromes/cpp-0906/main.cpp b/0501-1000/0906-Super-Palindromes/cpp-0906/main.cpp new file mode 100644 index 00000000..31512dbb --- /dev/null +++ b/0501-1000/0906-Super-Palindromes/cpp-0906/main.cpp @@ -0,0 +1,64 @@ +/// Source : https://leetcode.com/problems/super-palindromes/description/ +/// Author : liuyubobobo +/// Time : 2018-09-16 + +#include +#include + +using namespace std; + + +/// Enumerate all base number which can construct a palindrome number +/// and check if the square is also a palindrome number +/// +/// Time Complexity: O(sqrt(sqrt(R))*log(R)) +/// Space Complexity: O(log(R)) +class Solution { +public: + int superpalindromesInRange(string L, string R) { + + long long lnum = atol(L.c_str()); + long long rnum = atol(R.c_str()); + long long limit = (long long)sqrt(rnum); + + int res = 0; + for(int k = 0; k <= 1; k ++) + for(int i = 1; ; i ++){ + long long x = getPalindrome(i, k); + if(x > limit) break; + long long square = x * x; + if(isPalindrome(square) && square >= lnum && square <= rnum) + res ++; + } + + return res; + } + +private: + long long getPalindrome(int num, bool useLast){ + string num_str = to_string(num); + + string rnum_str = num_str; + reverse(rnum_str.begin(), rnum_str.end()); + + if(useLast) return atol((num_str + rnum_str.substr(1)).c_str()); + return atol((num_str + rnum_str).c_str()); + } + + bool isPalindrome(long long num){ + string s = to_string(num); + for(int i = 0, j = s.size() - 1; i < j; i ++, j --) + if(s[i] != s[j]) + return false; + return true; + } +}; + + +int main() { + + cout << Solution().superpalindromesInRange("4", "1000") << endl; + cout << Solution().superpalindromesInRange("1", "5") << endl; + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0907-Sum-of-Subarray-Minimums/cpp-0907/CMakeLists.txt b/0501-1000/0907-Sum-of-Subarray-Minimums/cpp-0907/CMakeLists.txt new file mode 100644 index 00000000..85e27b1b --- /dev/null +++ b/0501-1000/0907-Sum-of-Subarray-Minimums/cpp-0907/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(C) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(C ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0907-Sum-of-Subarray-Minimums/cpp-0907/main.cpp b/0501-1000/0907-Sum-of-Subarray-Minimums/cpp-0907/main.cpp new file mode 100644 index 00000000..c26ca6a0 --- /dev/null +++ b/0501-1000/0907-Sum-of-Subarray-Minimums/cpp-0907/main.cpp @@ -0,0 +1,83 @@ +/// Source : https://leetcode.com/problems/sum-of-subarray-minimums/description/ +/// Author : liuyubobobo +/// Time : 2018-09-16 + +#include +#include + +using namespace std; + + +/// Two Stacks +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +private: + long long mod = 1e9 + 7; + +public: + int sumSubarrayMins(vector& A) { + + int n = A.size(); + + vector stack; + + vector rSmaller(n, n); + for(int i = 0; i < n ; i ++){ + while(!stack.empty() && A[stack.back()] >= A[i]){ + rSmaller[stack.back()] = i; + stack.pop_back(); + } + stack.push_back(i); + } +// Solution::print_vec(rSmaller); + + stack.clear(); + vector lSmaller(n, -1); + for(int i = n - 1; i >= 0; i --){ + while(!stack.empty() && A[stack.back()] > A[i]){ + lSmaller[stack.back()] = i; + stack.pop_back(); + } + stack.push_back(i); + } +// Solution::print_vec(lSmaller); + + long long res = 0; + for(int i = 0; i < n; i ++){ + res += (long long)(rSmaller[i] - i) * (long long)(i - lSmaller[i]) % mod * (long long)A[i] % mod; + res %= mod; + } + + return res; + } + + static void print_vec(const vector& vec){ + for(int e: vec) + cout << e << " "; + cout << endl; + } +}; + + +int main() { + + vector nums1 = {3,1,2,4}; + cout << Solution().sumSubarrayMins(nums1) << endl; + // 17 + + vector nums2 = {48, 87, 27}; + cout << Solution().sumSubarrayMins(nums2) << endl; + // 264 + + vector nums3 = {71, 55, 82, 55}; + cout << Solution().sumSubarrayMins(nums3) << endl; + // 593 + + vector nums4 = {19, 19, 62, 66}; + cout << Solution().sumSubarrayMins(nums4) << endl; + // 323 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0908-Smallest-Range-I/cpp-0908/CMakeLists.txt b/0501-1000/0908-Smallest-Range-I/cpp-0908/CMakeLists.txt new file mode 100644 index 00000000..b3fafe13 --- /dev/null +++ b/0501-1000/0908-Smallest-Range-I/cpp-0908/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(A) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(A ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0908-Smallest-Range-I/cpp-0908/main.cpp b/0501-1000/0908-Smallest-Range-I/cpp-0908/main.cpp new file mode 100644 index 00000000..47eccc9e --- /dev/null +++ b/0501-1000/0908-Smallest-Range-I/cpp-0908/main.cpp @@ -0,0 +1,29 @@ +/// Source : https://leetcode.com/problems/smallest-range-i/description/ +/// Author : liuyubobobo +/// Time : 2018-09-2 + +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int smallestRangeI(vector& A, int K) { + + int mina = *min_element(A.begin(), A.end()); + int maxa = *max_element(A.begin(), A.end()); + int diff = maxa - mina; + return diff >= 2 * K ? diff - 2 * K : 0; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0909-Snakes-and-Ladders/cpp-0909/CMakeLists.txt b/0501-1000/0909-Snakes-and-Ladders/cpp-0909/CMakeLists.txt new file mode 100644 index 00000000..08335525 --- /dev/null +++ b/0501-1000/0909-Snakes-and-Ladders/cpp-0909/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(B) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main2.cpp) +add_executable(B ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0909-Snakes-and-Ladders/cpp-0909/main.cpp b/0501-1000/0909-Snakes-and-Ladders/cpp-0909/main.cpp new file mode 100644 index 00000000..c4321446 --- /dev/null +++ b/0501-1000/0909-Snakes-and-Ladders/cpp-0909/main.cpp @@ -0,0 +1,82 @@ +/// Source : https://leetcode.com/problems/snakes-and-ladders/description/ +/// Author : liuyubobobo +/// Time : 2018-09-22 + +#include +#include +#include +#include + +using namespace std; + + +/// BFS +/// Time Complexity: O(n^2) +/// Space Complexity: O(n^2) +class Solution { +public: + int snakesAndLadders(vector>& board) { + + int n = board.size(); + vector b; + + int order = 0; + for(int i = n - 1; i >= 0; i --){ + if(order) + reverse(board[i].begin(), board[i].end()); + for(int j = 0; j < n; j ++){ + if(board[i][j] != -1) + board[i][j] --; + b.push_back(board[i][j]); + } + order = 1 - order; + } + assert(b.size() == n * n); + + return bfs(b, 0, n * n - 1); + } + +private: + int bfs(const vector& b, int s, int t){ + + vector visited(b.size(), false); + queue> q; + q.push(make_pair(s, 0)); + visited[s] = true; + while(!q.empty()){ + int pos = q.front().first; + int step = q.front().second; + q.pop(); + + if(pos == t) + return step; + + for(int i = 1; i <= 6 && pos + i < b.size(); i ++){ + int next = pos + i; + if(b[next] != -1) + next = b[next]; + if(!visited[next]){ + visited[next] = true; + q.push(make_pair(next, step + 1)); + } + } + } + + return -1; + } +}; + + +int main() { + + vector> board1 = { + {-1,1,2,-1}, + {2,13,15,-1}, + {-1,10,-1,-1}, + {-1,6,2,8} + }; + cout << Solution().snakesAndLadders(board1) << endl; + // 2 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0909-Snakes-and-Ladders/cpp-0909/main2.cpp b/0501-1000/0909-Snakes-and-Ladders/cpp-0909/main2.cpp new file mode 100644 index 00000000..673c42b7 --- /dev/null +++ b/0501-1000/0909-Snakes-and-Ladders/cpp-0909/main2.cpp @@ -0,0 +1,88 @@ +/// Source : https://leetcode.com/problems/snakes-and-ladders/description/ +/// Author : liuyubobobo +/// Time : 2018-09-25 + +#include +#include +#include +#include + +using namespace std; + + +/// BFS +/// Calculate the board position during the bfs +/// +/// Time Complexity: O(n^2) +/// Space Complexity: O(n^2) +class Solution { +public: + int snakesAndLadders(vector>& board) { + + int n = board.size(); + int n2 = n * n; + + vector visited(n2 + 1, false); + queue> q; + q.push(make_pair(1, 0)); + visited[1] = true; + while(!q.empty()){ + int pos = q.front().first; + int step = q.front().second; + q.pop(); + + if(pos == n2) + return step; + + for(int i = 1; i <= 6 && pos + i <= n2; i ++){ + int next = pos + i; + int x, y; + getPos(next, x, y, n); + if(board[x][y] != -1) + next = board[x][y]; + if(!visited[next]){ + visited[next] = true; + q.push(make_pair(next, step + 1)); + } + } + } + + return -1; + } + +private: + void getPos(int pos, int& x, int& y, int n){ + + x = (pos - 1) / n; + y = (pos - 1) % n; + x = n - 1 - x; + if(x % 2 == n % 2) + y = n - 1 - y; + } +}; + + +int main() { + + vector> board1 = { + {-1,1,2,-1}, + {2,13,15,-1}, + {-1,10,-1,-1}, + {-1,6,2,8} + }; + cout << Solution().snakesAndLadders(board1) << endl; + // 2 + + vector> board2 = { + {-1, -1, -1, -1, -1, -1}, + {-1, -1, -1, -1, -1, -1}, + {-1, -1, -1, -1, -1, -1}, + {-1, 35, -1, -1, 13, -1}, + {-1, -1, -1, -1, -1, -1}, + {-1, 15, -1, -1, -1, -1} + }; + cout << Solution().snakesAndLadders(board2) << endl; + // 4 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0910-Smallest-Range-II/cpp-0910/CMakeLists.txt b/0501-1000/0910-Smallest-Range-II/cpp-0910/CMakeLists.txt new file mode 100644 index 00000000..85e27b1b --- /dev/null +++ b/0501-1000/0910-Smallest-Range-II/cpp-0910/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(C) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(C ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0910-Smallest-Range-II/cpp-0910/main.cpp b/0501-1000/0910-Smallest-Range-II/cpp-0910/main.cpp new file mode 100644 index 00000000..693571c9 --- /dev/null +++ b/0501-1000/0910-Smallest-Range-II/cpp-0910/main.cpp @@ -0,0 +1,31 @@ +/// Source : https://leetcode.com/problems/smallest-range-ii/description/ +/// Author : liuyubobobo +/// Time : 2018-09-22 + +#include +#include + +using namespace std; + + +/// Sorting and Greedy +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + int smallestRangeII(vector& A, int K) { + + sort(A.begin(), A.end()); + int res = A.back() - A[0]; + for(int i = 0; i < A.size() - 1; i ++) + res = min(res, + max(A[i] + K, A.back() - K) - min(A[0] + K, A[i + 1] - K)); + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0911-Online-Election/cpp-0911/CMakeLists.txt b/0501-1000/0911-Online-Election/cpp-0911/CMakeLists.txt new file mode 100644 index 00000000..ade1f6b8 --- /dev/null +++ b/0501-1000/0911-Online-Election/cpp-0911/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(D) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main2.cpp) +add_executable(D ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0911-Online-Election/cpp-0911/main.cpp b/0501-1000/0911-Online-Election/cpp-0911/main.cpp new file mode 100644 index 00000000..daef3f95 --- /dev/null +++ b/0501-1000/0911-Online-Election/cpp-0911/main.cpp @@ -0,0 +1,82 @@ +/// Source : https://leetcode.com/problems/online-election/description/ +/// Author : liuyubobobo +/// Time : 2018-09-22 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// Using Priority Queue to precalculate the winner in every time +/// Using Binary Search to query +/// +/// Time Complexity: init: O(nlogn) +/// query: O(logn) +class TopVotedCandidate { + +private: + vector> winner; + +public: + TopVotedCandidate(vector persons, vector times) { + + priority_queue, int>> pq; // (votes, time), id + vector nearest(persons.size() + 1, 0); + vector votes(persons.size(), 0); + + winner.clear(); + for(int i = 0; i < times.size(); i ++){ + nearest[persons[i]] = times[i]; + votes[persons[i]] ++; + pq.push(make_pair(make_pair(votes[persons[i]], times[i]), persons[i])); + while(true){ + int vote = pq.top().first.first; + int time = pq.top().first.second; + int person = pq.top().second; + + if(nearest[person] == time){ + winner.push_back(make_pair(times[i], person)); + break; + } + else + pq.pop(); + } + } + } + + int q(int t) { + + vector>::iterator iter = + lower_bound(winner.begin(), winner.end(), make_pair(t, -1)); + if(iter->first != t){ + assert(iter != winner.begin()); + iter --; + } + return iter->second; + } +}; + + +int main() { + + vector persons1 = {0,1,1,0,0,1,0}; + vector times1 = {0,5,10,15,20,25,30}; + TopVotedCandidate topVotedCandidate1(persons1, times1); + + cout << topVotedCandidate1.q(3) << endl; + // 0 + + + vector persons2 = {0,0,0,0,1}; + vector times2 = {0,6,39,52,75}; + TopVotedCandidate topVotedCandidate2(persons2, times2); + + cout << topVotedCandidate2.q(99) << endl; + // 0 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0911-Online-Election/cpp-0911/main2.cpp b/0501-1000/0911-Online-Election/cpp-0911/main2.cpp new file mode 100644 index 00000000..5950ef26 --- /dev/null +++ b/0501-1000/0911-Online-Election/cpp-0911/main2.cpp @@ -0,0 +1,74 @@ +/// Source : https://leetcode.com/problems/online-election/description/ +/// Author : liuyubobobo +/// Time : 2018-09-22 + +#include +#include +#include +#include +#include + + +using namespace std; + + +/// Using HashSet to precalculate the winner in every time +/// Using Binary Search to query +/// +/// Time Complexity: init: O(n) +/// query: O(logn) +class TopVotedCandidate { + +private: + vector> winner; + +public: + TopVotedCandidate(vector persons, vector times) { + + unordered_map cnt; // person -> votes + int maxVote = 0; + int winID = -1; + + winner.clear(); + for(int i = 0; i < persons.size(); i ++){ + cnt[persons[i]] ++; + if(cnt[persons[i]] >= maxVote){ + maxVote = cnt[persons[i]]; + winID = persons[i]; + } + winner.push_back(make_pair(times[i], winID)); + } + } + + int q(int t) { + + vector>::iterator iter = + lower_bound(winner.begin(), winner.end(), make_pair(t, -1)); + if(iter->first != t){ + assert(iter != winner.begin()); + iter --; + } + return iter->second; + } +}; + + +int main() { + + vector persons1 = {0,1,1,0,0,1,0}; + vector times1 = {0,5,10,15,20,25,30}; + TopVotedCandidate topVotedCandidate1(persons1, times1); + + cout << topVotedCandidate1.q(3) << endl; + // 0 + + + vector persons2 = {0,0,0,0,1}; + vector times2 = {0,6,39,52,75}; + TopVotedCandidate topVotedCandidate2(persons2, times2); + + cout << topVotedCandidate2.q(99) << endl; + // 0 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0911-Online-Election/cpp-0911/main3.cpp b/0501-1000/0911-Online-Election/cpp-0911/main3.cpp new file mode 100644 index 00000000..29eb2473 --- /dev/null +++ b/0501-1000/0911-Online-Election/cpp-0911/main3.cpp @@ -0,0 +1,84 @@ +/// Source : https://leetcode.com/problems/online-election/description/ +/// Author : liuyubobobo +/// Time : 2018-09-22 + +#include +#include +#include +#include + + +using namespace std; + + +/// Using 2D vectors votes +/// Votes[i][j] is the jth vote make some person's vote count == i +/// Then use Binary Search twice to query +/// The performance is not the best for the problem +/// But I think the idea is good to think about +/// +/// Time Complexity: init: O(n) +/// query: O(2logn) +class TopVotedCandidate { + +private: + vector>> votes; // time, person + +public: + TopVotedCandidate(vector persons, vector times) { + + unordered_map cnt; // person -> votes + votes.clear(); + votes.push_back(vector>()); + for(int i = 0; i < persons.size(); i ++){ + cnt[persons[i]] ++; + if(votes.size() <= cnt[persons[i]]) { + assert(votes.size() == cnt[persons[i]]); + votes.push_back(vector>()); + } + assert(cnt[persons[i]] < votes.size()); + votes[cnt[persons[i]]].push_back(make_pair(times[i], persons[i])); + } + } + + int q(int t) { + + int l = 0, r = votes.size() - 1; + while(l < r){ + + int mid = (l + r + 1) / 2; + assert(votes[mid].size() > 0); + if(votes[mid][0].first > t) + r = mid - 1; + else // votes[mid][0].first <= t + l = mid; + } + + vector>:: iterator iter = + lower_bound(votes[l].begin(), votes[l].end(), make_pair(t, -1)); + if(iter->first != t) + iter --; + return iter->second; + } +}; + + +int main() { + + vector persons1 = {0,1,1,0,0,1,0}; + vector times1 = {0,5,10,15,20,25,30}; + TopVotedCandidate topVotedCandidate1(persons1, times1); + + cout << topVotedCandidate1.q(3) << endl; + // 0 + + + vector persons2 = {0,0,0,0,1}; + vector times2 = {0,6,39,52,75}; + TopVotedCandidate topVotedCandidate2(persons2, times2); + + cout << topVotedCandidate2.q(99) << endl; + // 0 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0912-Sort-an-Array/cpp-0912/CMakeLists.txt b/0501-1000/0912-Sort-an-Array/cpp-0912/CMakeLists.txt new file mode 100644 index 00000000..5e2a19da --- /dev/null +++ b/0501-1000/0912-Sort-an-Array/cpp-0912/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_0912) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0912 main.cpp) \ No newline at end of file diff --git a/0501-1000/0912-Sort-an-Array/cpp-0912/main.cpp b/0501-1000/0912-Sort-an-Array/cpp-0912/main.cpp new file mode 100644 index 00000000..a95bb6e2 --- /dev/null +++ b/0501-1000/0912-Sort-an-Array/cpp-0912/main.cpp @@ -0,0 +1,26 @@ +/// Source : https://leetcode.com/problems/sort-an-array/ +/// Author : liuyubobobo +/// Time : 2021-07-09 + +#include +#include + +using namespace std; + + +/// Sorting API +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + vector sortArray(vector& nums) { + sort(nums.begin(), nums.end()); + return nums; + } +}; + + +int main() { + + return 0; +} diff --git a/0501-1000/0913-Cat-and-Mouse-Game/cpp-0913/CMakeLists.txt b/0501-1000/0913-Cat-and-Mouse-Game/cpp-0913/CMakeLists.txt new file mode 100644 index 00000000..ade1f6b8 --- /dev/null +++ b/0501-1000/0913-Cat-and-Mouse-Game/cpp-0913/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(D) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main2.cpp) +add_executable(D ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0913-Cat-and-Mouse-Game/cpp-0913/main.cpp b/0501-1000/0913-Cat-and-Mouse-Game/cpp-0913/main.cpp new file mode 100644 index 00000000..41558909 --- /dev/null +++ b/0501-1000/0913-Cat-and-Mouse-Game/cpp-0913/main.cpp @@ -0,0 +1,221 @@ +/// Source : https://leetcode.com/problems/cat-and-mouse/ +/// Author : liuyubobobo +/// Time : 2018-11-04 + +#include +#include +#include +#include +#include +#include +#include + +using namespace std; + + +/// Topological Sorting +/// Create the underlying graph and reverse graph explictly +/// +/// Time Complexity: O(node * node * 2 * maxdegree) +/// Space Complexity: O(node * node * 2) +class Solution { + +private: + const int DRAW = 0, HOLE = 0, MOUSE = 1, CAT = 2; + +public: + int catMouseGame(vector>& graph) { + + int n = graph.size(); + + unordered_map dp; + unordered_map> g = constructG(graph, dp); + + unordered_map> rg = reverseG(g); + + unordered_map degree; + queue q; + for(const pair>& p: g){ + degree[p.first] = p.second.size(); + if(degree[p.first] == 0) + q.push(p.first); + } + + while(!q.empty()){ + int curkey = q.front(); + q.pop(); + + int curmouse, curcat, curwho; + get(curkey, curmouse, curcat, curwho); + assert(dp.count(curkey)); + if(curmouse == MOUSE && curcat == CAT && curwho == MOUSE) + return dp[curkey]; + + for(int prekey: rg[curkey]) + if(!dp.count(prekey)){ + int premouse, precat, prewho; + get(prekey, premouse, precat, prewho); + + if(prewho == dp[curkey]){ + degree[prekey] = 0; + dp[prekey] = dp[curkey]; + q.push(prekey); + } + else{ + degree[prekey] --; + if(degree[prekey] == 0){ + int res = 3 - prewho; + for(int x: g[prekey]){ + assert(dp.count(x) && dp[x] != prewho); + if(dp[x] == DRAW){ + res = DRAW; + break; + } + } + dp[prekey] = res; + q.push(prekey); + } + } + } + + } + return 0; + } + +private: + unordered_map> reverseG( + const unordered_map>& g){ + + unordered_map> res; + for(const pair>& p: g){ + int u = p.first; + for(int v: p.second) + res[v].insert(u); + } + return res; + } + + unordered_map> constructG( + const vector>& graph, + unordered_map& dp){ + + unordered_map> res; + + unordered_set visited; + stack stack; + stack.push(key(MOUSE, CAT, MOUSE)); + visited.insert(key(MOUSE, CAT, MOUSE)); + while(!stack.empty()){ + int curkey = stack.top(); + stack.pop(); + + int curmouse, curcat, curwho; + get(curkey, curmouse, curcat, curwho); + + if(curmouse == HOLE){ + dp[curkey] = MOUSE; + res[curkey] = unordered_set(); + continue; + } + + if(curmouse == curcat){ + dp[curkey] = CAT; + res[curkey] = unordered_set(); + continue; + } + + if(curwho == MOUSE){ + for(int x: graph[curmouse]){ + int nextkey = key(x, curcat, CAT); + res[curkey].insert(nextkey); + if(!visited.count(nextkey)){ + visited.insert(nextkey); + stack.push(nextkey); + } + } + } + else{ // curwho == CAT + for(int x: graph[curcat]) if(x){ + int nextkey = key(curmouse, x, MOUSE); + res[curkey].insert(nextkey); + if(!visited.count(nextkey)){ + visited.insert(nextkey); + stack.push(nextkey); + } + } + } + } + + return res; + } + + int key(int mousepos, int catpos, int who){ + return (mousepos * 100 + catpos) * 100 + who; + } + + void get(int key, int& mousepos, int& catpos, int& who){ + + who = key % 100; + key /= 100; + catpos = key % 100; + mousepos = key / 100; + } + +// void printG(const unordered_map>& g){ +// for(const pair>& p: g){ +// cout << p.first << " : "; +// for(int e: p.second) +// cout << e << " "; +// cout << endl; +// } +// cout << "----------" << endl; +// } +}; + + +int main() { + + vector> g0 = { + {2},{2},{0,1} + }; + cout << Solution().catMouseGame(g0) << endl; + // 2 + + // 2-4-3-1 + // |\ / + // 0-5 + vector> g1 = { + {2,5},{3},{0,4,5},{1,4,5},{2,3},{0,2,3} + }; + cout << Solution().catMouseGame(g1) << endl; + // 0 + + // 0-2 + // | | + // 4-3 1 + vector> g2 = {{2,3},{2},{0,1},{0,4},{3}}; + cout << Solution().catMouseGame(g2) << endl; + // 2 + + // 0-2 + // /|/ + // 1-4 3 + vector> g3 = {{2,3,4},{4},{0,3},{0,2},{0,1}}; + cout << Solution().catMouseGame(g3) << endl; + // 1 + + // 0-2-1 + // |\|/ + // 3-4 + vector> g4 = {{2,3,4},{2,4},{0,1,4},{0,4},{0,1,2,3}}; + cout << Solution().catMouseGame(g4) << endl; + // 2 + + vector> g5 = { + {6},{4},{9},{5},{1,5}, + {3,4,6},{0,5,10},{8,9,10},{7},{2,7},{6,7}}; + cout << Solution().catMouseGame(g5) << endl; + // 1 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0913-Cat-and-Mouse-Game/cpp-0913/main2.cpp b/0501-1000/0913-Cat-and-Mouse-Game/cpp-0913/main2.cpp new file mode 100644 index 00000000..c50d4020 --- /dev/null +++ b/0501-1000/0913-Cat-and-Mouse-Game/cpp-0913/main2.cpp @@ -0,0 +1,188 @@ +/// Source : https://leetcode.com/problems/cat-and-mouse/ +/// Author : liuyubobobo +/// Time : 2018-11-05 + +#include +#include +#include +#include +#include +#include + +using namespace std; + + +/// Topological Sorting +/// Without Creating the underlying graph and reverse graph explictly +/// Much much faster +/// +/// BTW: There's a similar challenge in CodeSignal +/// This idea can pass it but the previous idea will lead to TLE +/// See https://app.codesignal.com/challenge/Q4sEyWz7Kw3QpyYC8 for more details :-) +/// +/// Time Complexity: O(node * node * 2 * maxdegree) +/// Space Complexity: O(node * node * 2) +class Solution { + +private: + const int DRAW = 0, HOLE = 0, MOUSE = 1, CAT = 2; + +public: + int catMouseGame(vector>& graph) { + + int n = graph.size(); + + unordered_map dp; + queue q; + + for(int i = 1; i < n; i ++) + for(int who = 1; who <= 2; who ++){ + + int k = key(0, i, who); + dp[k] = MOUSE; + q.push(k); + + k = key(i, i, who); + dp[k] = CAT; + q.push(k); + } + + unordered_map degree; + for(int i = 0; i < n; i ++) + for(int j = 1; j < n; j ++){ + degree[key(i, j, MOUSE)] = graph[i].size(); + degree[key(i, j, CAT)] = graph[j].size(); + for(int x: graph[j]) + if(!x) degree[key(i, j, CAT)] --; + } + + while(!q.empty()){ + int curkey = q.front(); + q.pop(); + + int curmouse, curcat, curwho; + get(curkey, curmouse, curcat, curwho); + assert(dp.count(curkey)); + if(curmouse == MOUSE && curcat == CAT && curwho == MOUSE) + return dp[curkey]; + + if(curwho == MOUSE){ + for(int precat: graph[curcat]) + if(precat){ + int prekey = key(curmouse, precat, CAT); + if(!dp.count(prekey)) + process(curkey, prekey, dp, degree, q, graph); + } + } + else{ // curwho == CAT + for(int premouse: graph[curmouse]) + if(premouse != curcat){ + int prekey = key(premouse, curcat, MOUSE); + if(!dp.count(prekey)) + process(curkey, prekey, dp, degree, q, graph); + } + } + } + return 0; + } + +private: + void process(int curkey, int prekey, unordered_map& dp, + unordered_map& degree, queue& q, + const vector>& graph){ + + int curmouse, curcat, curwho; + get(curkey, curmouse, curcat, curwho); + + int premouse, precat, prewho; + get(prekey, premouse, precat, prewho); + + if(prewho == dp[curkey]){ + degree[prekey] = 0; + dp[prekey] = dp[curkey]; + q.push(prekey); + } + else{ + degree[prekey] --; + if(degree[prekey] == 0){ + int res = 3 - prewho; + if(prewho == MOUSE){ + for(int x: graph[premouse]) + if(x != curcat){ + if(dp[key(x, precat, curwho)] == DRAW){ + res = DRAW; + break; + } + } + } + else{ // prewho == CAT + for(int x: graph[precat]) + if(x){ + if(dp[key(premouse, x, curwho)] == DRAW){ + res = DRAW; + break; + } + } + } + + dp[prekey] = res; + q.push(prekey); + } + } + } + + int key(int mousepos, int catpos, int who){ + return (mousepos * 100 + catpos) * 100 + who; + } + + void get(int key, int& mousepos, int& catpos, int& who){ + + who = key % 100; + key /= 100; + catpos = key % 100; + mousepos = key / 100; + } + +}; + + +int main() { + + // 2-4-3-1 + // |\ / + // 0-5 + vector> g1 = { + {2,5},{3},{0,4,5},{1,4,5},{2,3},{0,2,3} + }; + cout << Solution().catMouseGame(g1) << endl; + // 0 + + // 0-2 + // | | + // 4-3 1 + vector> g2 = {{2,3},{2},{0,1},{0,4},{3}}; + cout << Solution().catMouseGame(g2) << endl; + // 2 + + // 0-2 + // /|/ + // 1-4 3 + vector> g3 = {{2,3,4},{4},{0,3},{0,2},{0,1}}; + cout << Solution().catMouseGame(g3) << endl; + // 1 + + // 0-2-1 + // |\|/ + // 3-4 + vector> g4 = {{2,3,4},{2,4},{0,1,4},{0,4},{0,1,2,3}}; + cout << Solution().catMouseGame(g4) << endl; + // 2 + + vector> g5 = { + {6},{4},{9},{5},{1,5}, + {3,4,6},{0,5,10},{8,9,10},{7},{2,7},{6,7}}; + cout << Solution().catMouseGame(g5) << endl; + // 1 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0914-X-of-a-Kind-in-a-Deck-of-Cards/cpp-0914/CMakeLists.txt b/0501-1000/0914-X-of-a-Kind-in-a-Deck-of-Cards/cpp-0914/CMakeLists.txt new file mode 100644 index 00000000..5cc31b93 --- /dev/null +++ b/0501-1000/0914-X-of-a-Kind-in-a-Deck-of-Cards/cpp-0914/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(A) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main3.cpp) +add_executable(A ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0914-X-of-a-Kind-in-a-Deck-of-Cards/cpp-0914/main.cpp b/0501-1000/0914-X-of-a-Kind-in-a-Deck-of-Cards/cpp-0914/main.cpp new file mode 100644 index 00000000..cdcac8e3 --- /dev/null +++ b/0501-1000/0914-X-of-a-Kind-in-a-Deck-of-Cards/cpp-0914/main.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/x-of-a-kind-in-a-deck-of-cards/description/ +/// Author : liuyubobobo +/// Time : 2018-09-30 + +#include +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { +public: + bool hasGroupsSizeX(vector& deck) { + + unordered_map freq; + for(int x: deck) + freq[x] ++; + + for(int i = 2; i <= deck.size(); i ++){ + bool ok = true; + for(const pair& p: freq) + if(p.second % i){ + ok = false; + break; + } + if(ok) + return true; + } + + return false; + } +}; + + +int main() { + + vector vec = {1,1,1,1,2,2,2,2,2,2}; + cout << Solution().hasGroupsSizeX(vec) << endl; + // true + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0914-X-of-a-Kind-in-a-Deck-of-Cards/cpp-0914/main2.cpp b/0501-1000/0914-X-of-a-Kind-in-a-Deck-of-Cards/cpp-0914/main2.cpp new file mode 100644 index 00000000..0ab2473f --- /dev/null +++ b/0501-1000/0914-X-of-a-Kind-in-a-Deck-of-Cards/cpp-0914/main2.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/x-of-a-kind-in-a-deck-of-cards/description/ +/// Author : liuyubobobo +/// Time : 2018-09-29 + +#include +#include +#include + +using namespace std; + +/// Brute Force +/// but only iterate from 2 to the minFreq +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { +public: + bool hasGroupsSizeX(vector& deck) { + unordered_map freq; + for(int x: deck) + freq[x] ++; + + int minFreq = INT_MAX; + for(const pair& p: freq) + minFreq = min(minFreq, p.second); + + for(int i = 2; i <= minFreq; i ++) + if(minFreq % i == 0){ + bool ok = true; + for(const pair& p: freq) + if(p.second % i){ + ok = false; + break; + } + if(ok) + return true; + } + + return false; + } +}; + + +int main() { + + vector vec = {1,1,1,1,2,2,2,2,2,2}; + cout << Solution().hasGroupsSizeX(vec) << endl; + // true + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0914-X-of-a-Kind-in-a-Deck-of-Cards/cpp-0914/main3.cpp b/0501-1000/0914-X-of-a-Kind-in-a-Deck-of-Cards/cpp-0914/main3.cpp new file mode 100644 index 00000000..5d06a40e --- /dev/null +++ b/0501-1000/0914-X-of-a-Kind-in-a-Deck-of-Cards/cpp-0914/main3.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/x-of-a-kind-in-a-deck-of-cards/description/ +/// Author : liuyubobobo +/// Time : 2018-09-30 + +#include +#include +#include +#include + +using namespace std; + +/// Calculate the gcd of all frequency +/// Time Complexity: O(n*logn) +/// Space Complexity: O(n) +class Solution { +public: + bool hasGroupsSizeX(vector& deck) { + unordered_map freq; + for(int x: deck) + freq[x] ++; + + int g = -1; + for(const pair& p: freq) + if(g == -1) + g = p.second; + else + g = gcd(g, p.second); + + return g > 1; + } + +private: + int gcd(int a, int b){ + if(a < b) + swap(a, b); + + if(a % b == 0) + return b; + + return gcd(b, a%b); + } +}; + + +int main() { + + vector vec = {1,1,1,1,2,2,2,2,2,2}; + cout << Solution().hasGroupsSizeX(vec) << endl; + // true + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0915-Partition-Array-into-Disjoint-Intervals/cpp-0915/CMakeLists.txt b/0501-1000/0915-Partition-Array-into-Disjoint-Intervals/cpp-0915/CMakeLists.txt new file mode 100644 index 00000000..ae89e070 --- /dev/null +++ b/0501-1000/0915-Partition-Array-into-Disjoint-Intervals/cpp-0915/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(B) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(B ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0915-Partition-Array-into-Disjoint-Intervals/cpp-0915/main.cpp b/0501-1000/0915-Partition-Array-into-Disjoint-Intervals/cpp-0915/main.cpp new file mode 100644 index 00000000..9da2f9f9 --- /dev/null +++ b/0501-1000/0915-Partition-Array-into-Disjoint-Intervals/cpp-0915/main.cpp @@ -0,0 +1,58 @@ +/// Source : https://leetcode.com/problems/partition-array-into-disjoint-intervals/description/ +/// Author : liuyubobobo +/// Time : 2018-09-29 + +#include +#include +#include + +using namespace std; + + +/// pre-calculation +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int partitionDisjoint(vector& A) { + + int n = A.size(); + + vector lmax(n, A[0]); + for(int i = 1; i < n; i ++) + lmax[i] = max(lmax[i - 1], A[i]); + + vector rmin(n, A[n - 1]); + for(int i = n - 2; i >= 0; i --) + rmin[i] = min(rmin[i + 1], A[i]); + + for(int i = 1; i < n; i ++) + if(lmax[i - 1] <= rmin[i]) + return i; + + assert(false); + return 0; + } +}; + + +int main() { + + vector A1 = {5,0,3,8,6}; + cout << Solution().partitionDisjoint(A1) << endl; + // 3 + + vector A2 = {1,1,1,0,6,12}; + cout << Solution().partitionDisjoint(A2) << endl; + // 4 + + vector A3 = {32,57,24,19,0,24,49,67,87,87}; + cout << Solution().partitionDisjoint(A3) << endl; + // 7 + + vector A4 = {1, 1}; + cout << Solution().partitionDisjoint(A4) << endl; + // 1 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0916-Word-Subsets/cpp-0916/CMakeLists.txt b/0501-1000/0916-Word-Subsets/cpp-0916/CMakeLists.txt new file mode 100644 index 00000000..85e27b1b --- /dev/null +++ b/0501-1000/0916-Word-Subsets/cpp-0916/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(C) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(C ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0916-Word-Subsets/cpp-0916/main.cpp b/0501-1000/0916-Word-Subsets/cpp-0916/main.cpp new file mode 100644 index 00000000..741c74d9 --- /dev/null +++ b/0501-1000/0916-Word-Subsets/cpp-0916/main.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/word-subsets/description/ +/// Author : liuyubobobo +/// Time : 2018-09-30 + +#include +#include + +using namespace std; + + +/// Reduce set B into a single word b +/// Time Complexity: O(A.size() + B.size()) +/// Space Complexity: O(26) +class Solution { +public: + vector wordSubsets(vector& A, vector& B) { + + vector b = getFreq(B[0]); + for(int i = 1; i < B.size(); i ++){ + vector tb = getFreq(B[i]); + for(int j = 0; j < 26; j ++) + b[j] = max(b[j], tb[j]); + } + + vector res; + for(const string& word: A){ + vector a = getFreq(word); + if(contains(a, b)) + res.push_back(word); + } + return res; + } + +private: + vector getFreq(const string& word){ + vector freq(26, 0); + for(char c: word) + freq[c - 'a'] ++; + return freq; + } + + bool contains(const vector& a, const vector& b){ + for(int i = 0; i < 26; i ++) + if(a[i] < b[i]) + return false; + return true; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0917-Reverse-Only-Letters/cpp-0917/CMakeLists.txt b/0501-1000/0917-Reverse-Only-Letters/cpp-0917/CMakeLists.txt new file mode 100644 index 00000000..557a8807 --- /dev/null +++ b/0501-1000/0917-Reverse-Only-Letters/cpp-0917/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(A) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main2.cpp) +add_executable(A ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0917-Reverse-Only-Letters/cpp-0917/main.cpp b/0501-1000/0917-Reverse-Only-Letters/cpp-0917/main.cpp new file mode 100644 index 00000000..35abf418 --- /dev/null +++ b/0501-1000/0917-Reverse-Only-Letters/cpp-0917/main.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/reverse-only-letters/description/ +/// Author : liuyubobobo +/// Time : 2018-10-06 + +#include + +using namespace std; + + +/// Two Pointers +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + string reverseOnlyLetters(string S) { + + int i = nextLetter(S, 0), j = prevLetter(S, S.size() - 1); + while(i < j){ + swap(S[i], S[j]); + i = nextLetter(S, i + 1); + j = prevLetter(S, j - 1); + } + return S; + } + +private: + int nextLetter(const string& s, int start){ + for(int i = start; i < s.size(); i ++) + if(isalpha(s[i])) + return i; + return s.size(); + } + + int prevLetter(const string& s, int start){ + for(int i = start; i >= 0; i --) + if(isalpha(s[i])) + return i; + return -1; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0917-Reverse-Only-Letters/cpp-0917/main2.cpp b/0501-1000/0917-Reverse-Only-Letters/cpp-0917/main2.cpp new file mode 100644 index 00000000..0d6cd107 --- /dev/null +++ b/0501-1000/0917-Reverse-Only-Letters/cpp-0917/main2.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/reverse-only-letters/description/ +/// Author : liuyubobobo +/// Time : 2018-10-06 + +#include +#include + +using namespace std; + + +/// Using Stack +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + string reverseOnlyLetters(string S) { + + stack stack; + for(char c: S) + if(isalpha(c)) + stack.push(c); + + for(char& c: S) + if(isalpha(c)) + c = stack.top(), stack.pop(); + return S; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0918-Maximum-Sum-Circular-Subarray/cpp-0918/CMakeLists.txt b/0501-1000/0918-Maximum-Sum-Circular-Subarray/cpp-0918/CMakeLists.txt new file mode 100644 index 00000000..75978cbc --- /dev/null +++ b/0501-1000/0918-Maximum-Sum-Circular-Subarray/cpp-0918/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(B) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main5.cpp) +add_executable(B ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0918-Maximum-Sum-Circular-Subarray/cpp-0918/main.cpp b/0501-1000/0918-Maximum-Sum-Circular-Subarray/cpp-0918/main.cpp new file mode 100644 index 00000000..93f3828e --- /dev/null +++ b/0501-1000/0918-Maximum-Sum-Circular-Subarray/cpp-0918/main.cpp @@ -0,0 +1,96 @@ +/// Source : https://leetcode.com/problems/maximum-sum-circular-subarray/description/ +/// Author : liuyubobobo +/// Time : 2018-10-06 + +#include +#include +#include +#include + +using namespace std; + + +/// Iterate every possible start place +/// For every start point, using Kadane's Algorithm +/// +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { +public: + int maxSubarraySumCircular(vector& A) { + + int n = A.size(); + int res = *max_element(A.begin(), A.end()); + if(res <= 0) + return res; + + bool hasNegative = false; + for(int a: A) + if(a < 0){ + hasNegative = true; + break; + } + if(!hasNegative) + return accumulate(A.begin(), A.end(), 0); + + unordered_set visited; + for(int k = 0; k < A.size(); k ++) + if(A[k] < 0 && A[(k + 1)%n] >= 0 && !visited.count((k + 1)%n)){ + int start = (k + 1) % n; + int sum = A[start]; + visited.insert(start); + for(int i = (start + 1) % n; i != start; i = (i + 1) % n){ + if(sum > 0) + sum += A[i]; + else{ + start = i; + if(visited.count(start)) + break; + visited.insert(start); + sum = A[i]; + } + + res = max(res, sum); + } + } + return res; + } +}; + + +int main() { + + vector A1 = {1,-2,3,-2}; + cout << Solution().maxSubarraySumCircular(A1) << endl; + // 3 + + vector A2 = {5,-3,5}; + cout << Solution().maxSubarraySumCircular(A2) << endl; + // 10 + + vector A3 = {3,-1,2,-1}; + cout << Solution().maxSubarraySumCircular(A3) << endl; + // 4 + + vector A4 = {3,-2,2,-3}; + cout << Solution().maxSubarraySumCircular(A4) << endl; + // 3 + + vector A5 = {-2,-3,-1}; + cout << Solution().maxSubarraySumCircular(A5) << endl; + // -1 + + vector A6 = {-2,4,-5,4,-5,9,4}; + cout << Solution().maxSubarraySumCircular(A6) << endl; + // 15 + + vector A7 = {-5,4,-6}; + cout << Solution().maxSubarraySumCircular(A7) << endl; + // 4 + + vector A8 = {-5,-2,5,6,-2,-7,0,2,8}; + cout << Solution().maxSubarraySumCircular(A7) << endl; + // 4 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0918-Maximum-Sum-Circular-Subarray/cpp-0918/main2.cpp b/0501-1000/0918-Maximum-Sum-Circular-Subarray/cpp-0918/main2.cpp new file mode 100644 index 00000000..97e7908a --- /dev/null +++ b/0501-1000/0918-Maximum-Sum-Circular-Subarray/cpp-0918/main2.cpp @@ -0,0 +1,102 @@ +/// Source : https://leetcode.com/problems/maximum-sum-circular-subarray/description/ +/// Author : liuyubobobo +/// Time : 2018-10-06 + +#include +#include +#include +#include + +using namespace std; + + +/// The result should be 1-interval or 2-intervals +/// Using lmin and rmin to get 1-interval result +/// Using lmax and rmax to get 2-interval result +/// +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int maxSubarraySumCircular(vector& A) { + + int n = A.size(); + + vector lmin(n + 1, 0); + int sum = 0; + for(int i = 0; i < n; i ++){ + sum += A[i]; + lmin[i + 1] = min(lmin[i], sum); + } + + vector rmin(n + 1, 0); + sum = 0; + for(int i = n - 1; i >= 0; i --){ + sum += A[i]; + rmin[i] = min(rmin[i + 1], sum); + } + + vector lmax(n + 1, 0); + sum = 0; + for(int i = 0; i < n; i ++){ + sum += A[i]; + lmax[i + 1] = max(lmax[i], sum); + } + + vector rmax(n + 1, 0); + sum = 0; + for(int i = n - 1; i >= 0; i --){ + sum += A[i]; + rmax[i] = max(rmax[i + 1], sum); + } + + sum = accumulate(A.begin(), A.end(), 0); + int res = INT_MIN; + for(int i = 0; i <= n; i ++) + res = max(res, sum - lmin[i] - rmin[i]); + for(int i = 0; i <= n; i ++) + res = max(res, lmax[i] + rmax[i]); + + if(res == 0) + res = *max_element(A.begin(), A.end()); + return res; + } +}; + + +int main() { + + vector A1 = {1,-2,3,-2}; + cout << Solution().maxSubarraySumCircular(A1) << endl; + // 3 + + vector A2 = {5,-3,5}; + cout << Solution().maxSubarraySumCircular(A2) << endl; + // 10 + + vector A3 = {3,-1,2,-1}; + cout << Solution().maxSubarraySumCircular(A3) << endl; + // 4 + + vector A4 = {3,-2,2,-3}; + cout << Solution().maxSubarraySumCircular(A4) << endl; + // 3 + + vector A5 = {-2,-3,-1}; + cout << Solution().maxSubarraySumCircular(A5) << endl; + // -1 + + vector A6 = {-2,4,-5,4,-5,9,4}; + cout << Solution().maxSubarraySumCircular(A6) << endl; + // 15 + + vector A7 = {-5,4,-6}; + cout << Solution().maxSubarraySumCircular(A7) << endl; + // 4 + + vector A8 = {-5,-2,5,6,-2,-7,0,2,8}; + cout << Solution().maxSubarraySumCircular(A7) << endl; + // 4 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0918-Maximum-Sum-Circular-Subarray/cpp-0918/main3.cpp b/0501-1000/0918-Maximum-Sum-Circular-Subarray/cpp-0918/main3.cpp new file mode 100644 index 00000000..45d207a8 --- /dev/null +++ b/0501-1000/0918-Maximum-Sum-Circular-Subarray/cpp-0918/main3.cpp @@ -0,0 +1,100 @@ +/// Source : https://leetcode.com/problems/maximum-sum-circular-subarray/description/ +/// Author : liuyubobobo +/// Time : 2018-10-06 + +#include +#include +#include +#include + +using namespace std; + + +/// The result should be 1-interval or 2-intervals +/// Using Kadane's Algorithm to get 1-interval result +/// Using lmax and rmax to get 2-interval result +/// +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int maxSubarraySumCircular(vector& A) { + + int n = A.size(); + + int res = INT_MIN; + int sum = 0; + + // Kadane's Algorithm +// for(int i = 0; i < n; i ++){ +// sum += A[i]; +// res = max(res, sum); +// if(sum < 0) +// sum = 0; +// } + + // Kadane's Algorithm + for(int i = 0; i < n; i ++){ + sum = A[i] + max(sum, 0); + res = max(res, sum); + } + + vector lmax(n, A[0]); + sum = A[0]; + for(int i = 1; i < n; i ++){ + sum += A[i]; + lmax[i] = max(lmax[i - 1], sum); + } + + vector rmax(n, A[n - 1]); + sum = A[n - 1]; + for(int i = n - 2; i >= 0; i --){ + sum += A[i]; + rmax[i] = max(rmax[i + 1], sum); + } + + sum = accumulate(A.begin(), A.end(), 0); + for(int i = 1; i < n; i ++) + res = max(res, lmax[i - 1] + rmax[i]); + + return res; + } +}; + + +int main() { + + vector A1 = {1,-2,3,-2}; + cout << Solution().maxSubarraySumCircular(A1) << endl; + // 3 + + vector A2 = {5,-3,5}; + cout << Solution().maxSubarraySumCircular(A2) << endl; + // 10 + + vector A3 = {3,-1,2,-1}; + cout << Solution().maxSubarraySumCircular(A3) << endl; + // 4 + + vector A4 = {3,-2,2,-3}; + cout << Solution().maxSubarraySumCircular(A4) << endl; + // 3 + + vector A5 = {-2,-3,-1}; + cout << Solution().maxSubarraySumCircular(A5) << endl; + // -1 + + vector A6 = {-2,4,-5,4,-5,9,4}; + cout << Solution().maxSubarraySumCircular(A6) << endl; + // 15 + + vector A7 = {-5,4,-6}; + cout << Solution().maxSubarraySumCircular(A7) << endl; + // 4 + + vector A8 = {-5,-2,5,6,-2,-7,0,2,8}; + cout << Solution().maxSubarraySumCircular(A7) << endl; + // 4 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0918-Maximum-Sum-Circular-Subarray/cpp-0918/main4.cpp b/0501-1000/0918-Maximum-Sum-Circular-Subarray/cpp-0918/main4.cpp new file mode 100644 index 00000000..bfb369c5 --- /dev/null +++ b/0501-1000/0918-Maximum-Sum-Circular-Subarray/cpp-0918/main4.cpp @@ -0,0 +1,84 @@ +/// Source : https://leetcode.com/problems/maximum-sum-circular-subarray/description/ +/// Author : liuyubobobo +/// Time : 2018-10-08 + +#include +#include +#include +#include + +using namespace std; + + +/// The result should be 1-interval or 2-intervals +/// Using Kadane's Algorithm to get 1-interval result +/// For 2-interval results, we can also use Kadane's Algorithm's max subarray algorithm +/// Just make every elements in the array into minus :-) +/// +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int maxSubarraySumCircular(vector& A) { + + int n = A.size(); + + int res = INT_MIN; + int sum = 0; + + // Kadane's Algorithm + for(int i = 0; i < n; i ++){ + sum = A[i] + max(sum, 0); + res = max(res, sum); + } + + sum = accumulate(A.begin(), A.end(), 0); + int sum2 = 0; + for(int i = 0; i < n; i ++){ + sum2 = -A[i] + max(sum2, 0); + res = max(res, sum + sum2); + } + + if(res == 0) + res = *max_element(A.begin(), A.end()); + return res; + } +}; + + +int main() { + + vector A1 = {1,-2,3,-2}; + cout << Solution().maxSubarraySumCircular(A1) << endl; + // 3 + + vector A2 = {5,-3,5}; + cout << Solution().maxSubarraySumCircular(A2) << endl; + // 10 + + vector A3 = {3,-1,2,-1}; + cout << Solution().maxSubarraySumCircular(A3) << endl; + // 4 + + vector A4 = {3,-2,2,-3}; + cout << Solution().maxSubarraySumCircular(A4) << endl; + // 3 + + vector A5 = {-2,-3,-1}; + cout << Solution().maxSubarraySumCircular(A5) << endl; + // -1 + + vector A6 = {-2,4,-5,4,-5,9,4}; + cout << Solution().maxSubarraySumCircular(A6) << endl; + // 15 + + vector A7 = {-5,4,-6}; + cout << Solution().maxSubarraySumCircular(A7) << endl; + // 4 + + vector A8 = {-5,-2,5,6,-2,-7,0,2,8}; + cout << Solution().maxSubarraySumCircular(A7) << endl; + // 4 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0918-Maximum-Sum-Circular-Subarray/cpp-0918/main5.cpp b/0501-1000/0918-Maximum-Sum-Circular-Subarray/cpp-0918/main5.cpp new file mode 100644 index 00000000..adefcf2f --- /dev/null +++ b/0501-1000/0918-Maximum-Sum-Circular-Subarray/cpp-0918/main5.cpp @@ -0,0 +1,84 @@ +/// Source : https://leetcode.com/problems/maximum-sum-circular-subarray/description/ +/// Author : liuyubobobo +/// Time : 2018-10-08 + +#include +#include +#include +#include + +using namespace std; + + +/// The result should be 1-interval or 2-intervals +/// Using Kadane's Algorithm to get 1-interval result +/// We can also use Kadane's Algorithm's min subarray algorithm to get the 2-interval result +/// It's just the same :-) +/// +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int maxSubarraySumCircular(vector& A) { + + int n = A.size(); + + int res = INT_MIN; + int sum = 0; + + // Kadane's Algorithm + for(int i = 0; i < n; i ++){ + sum = A[i] + max(sum, 0); + res = max(res, sum); + } + + sum = accumulate(A.begin(), A.end(), 0); + int sum2 = 0; + for(int i = 0; i < n; i ++){ + sum2 = A[i] + min(sum2, 0); + res = max(res, sum - sum2); + } + + if(res == 0) + res = *max_element(A.begin(), A.end()); + return res; + } +}; + + +int main() { + + vector A1 = {1,-2,3,-2}; + cout << Solution().maxSubarraySumCircular(A1) << endl; + // 3 + + vector A2 = {5,-3,5}; + cout << Solution().maxSubarraySumCircular(A2) << endl; + // 10 + + vector A3 = {3,-1,2,-1}; + cout << Solution().maxSubarraySumCircular(A3) << endl; + // 4 + + vector A4 = {3,-2,2,-3}; + cout << Solution().maxSubarraySumCircular(A4) << endl; + // 3 + + vector A5 = {-2,-3,-1}; + cout << Solution().maxSubarraySumCircular(A5) << endl; + // -1 + + vector A6 = {-2,4,-5,4,-5,9,4}; + cout << Solution().maxSubarraySumCircular(A6) << endl; + // 15 + + vector A7 = {-5,4,-6}; + cout << Solution().maxSubarraySumCircular(A7) << endl; + // 4 + + vector A8 = {-5,-2,5,6,-2,-7,0,2,8}; + cout << Solution().maxSubarraySumCircular(A7) << endl; + // 4 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0918-Maximum-Sum-Circular-Subarray/cpp-0918/main6.cpp b/0501-1000/0918-Maximum-Sum-Circular-Subarray/cpp-0918/main6.cpp new file mode 100644 index 00000000..fdeeb635 --- /dev/null +++ b/0501-1000/0918-Maximum-Sum-Circular-Subarray/cpp-0918/main6.cpp @@ -0,0 +1,98 @@ +/// Source : https://leetcode.com/problems/maximum-sum-circular-subarray/description/ +/// Author : liuyubobobo +/// Time : 2018-10-08 + +#include +#include +#include +#include + +using namespace std; + + +/// Make an array of A + A +/// The purpose of this problem is to find the largest subarray in A + A, +/// but length less or equal to len(A) +/// Using stack strategy to keep a mono-space +/// Since we need to make the length less or equal to len(A) +/// deque is actually used (to remove element) +/// +/// It'snot a quite efficient algorithm compare to main4 or main5 +/// But the thinking and implementation is interesting and good to know +/// (Also hard to think) +/// Please complare this implementation to Leetcode 901 and Leetcode 910 :-) +/// +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int maxSubarraySumCircular(vector& A) { + + int n = A.size(); + + vector p(2 * n + 1, 0); + for(int i = 0; i < n; i ++) + p[i + 1] = p[n + i + 1] = A[i]; + for(int i = 1; i <= 2 * n; i ++) + p[i] += p[i - 1]; + +// for(int e: p) +// cout << e << " "; +// cout << endl; + + int res = INT_MIN; + + deque q; + q.push_back(0); + for(int i = 1; i <= 2 * n; i ++){ + if(!q.empty() && i - q.front() > n) + q.pop_front(); + + res = max(res, p[i] - p[q.front()]); + + while(!q.empty() && p[i] <= p[q.back()]) + q.pop_back(); + + q.push_back(i); + } + return res; + } +}; + + +int main() { + + vector A1 = {1,-2,3,-2}; + cout << Solution().maxSubarraySumCircular(A1) << endl; + // 3 + + vector A2 = {5,-3,5}; + cout << Solution().maxSubarraySumCircular(A2) << endl; + // 10 + + vector A3 = {3,-1,2,-1}; + cout << Solution().maxSubarraySumCircular(A3) << endl; + // 4 + + vector A4 = {3,-2,2,-3}; + cout << Solution().maxSubarraySumCircular(A4) << endl; + // 3 + + vector A5 = {-2,-3,-1}; + cout << Solution().maxSubarraySumCircular(A5) << endl; + // -1 + + vector A6 = {-2,4,-5,4,-5,9,4}; + cout << Solution().maxSubarraySumCircular(A6) << endl; + // 15 + + vector A7 = {-5,4,-6}; + cout << Solution().maxSubarraySumCircular(A7) << endl; + // 4 + + vector A8 = {-5,-2,5,6,-2,-7,0,2,8}; + cout << Solution().maxSubarraySumCircular(A7) << endl; + // 4 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0919-Complete-Binary-Tree-Inserter/cpp-0919/CMakeLists.txt b/0501-1000/0919-Complete-Binary-Tree-Inserter/cpp-0919/CMakeLists.txt new file mode 100644 index 00000000..10d4db6b --- /dev/null +++ b/0501-1000/0919-Complete-Binary-Tree-Inserter/cpp-0919/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(C) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main2.cpp) +add_executable(C ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0919-Complete-Binary-Tree-Inserter/cpp-0919/main.cpp b/0501-1000/0919-Complete-Binary-Tree-Inserter/cpp-0919/main.cpp new file mode 100644 index 00000000..cefc1a35 --- /dev/null +++ b/0501-1000/0919-Complete-Binary-Tree-Inserter/cpp-0919/main.cpp @@ -0,0 +1,86 @@ +/// Source : https://leetcode.com/problems/complete-binary-tree-inserter/description/ +/// Author : liuyubobobo +/// Time : 2018-10-06 + +#include + +using namespace std; + + +/// Inspiring by Heap, using an integer to present every node, starting from 1 +/// Then, we know in a complete tree, if the node's id is x +/// It's left child's id would be 2*x, it's right child's id would be 2*x + 1 +/// +/// Time Complexity: init: O(n) +/// insert: O((logn)^2) +/// get_root: O(1) +/// Space Complexity: O(1) + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +class CBTInserter { + +private: + int nextID; + TreeNode* root; + +public: + CBTInserter(TreeNode* root) { + this->root = root; + nextID = getNodeNumber(root) + 1; + } + + int insert(int v) { + + TreeNode* p = root; + int pID = 1; + while(true){ + if(nextID == 2 * pID){ + p->left = new TreeNode(v); + break; + } + else if(nextID == 2 * pID + 1){ + p->right = new TreeNode(v); + break; + } + + int id = nextID; + while(id / 2 != pID) + id /= 2; + + if(id == 2 * pID) + p = p->left; + else + p = p->right; + pID = id; + } + + nextID ++; + return p->val; + } + + TreeNode* get_root() { + return root; + } + +private: + int getNodeNumber(TreeNode* node){ + + if(!node) + return 0; + + return 1 + getNodeNumber(node->left) + getNodeNumber(node->right); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0919-Complete-Binary-Tree-Inserter/cpp-0919/main2.cpp b/0501-1000/0919-Complete-Binary-Tree-Inserter/cpp-0919/main2.cpp new file mode 100644 index 00000000..d2ce191d --- /dev/null +++ b/0501-1000/0919-Complete-Binary-Tree-Inserter/cpp-0919/main2.cpp @@ -0,0 +1,72 @@ +/// Source : https://leetcode.com/problems/complete-binary-tree-inserter/description/ +/// Author : liuyubobobo +/// Time : 2018-10-07 + +#include +#include +#include + +using namespace std; + + +/// Using queue +/// Time Complexity: init: O(n) +/// insert: O(1) +/// get_root: O(1) +/// Space Complexity: O(n) + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +class CBTInserter { + +private: + queue q; + TreeNode* root; + +public: + CBTInserter(TreeNode* root) { + this->root = root; + q.push(this->root); + while(true){ + TreeNode* cur = q.front(); + if(cur->left) q.push(cur->left); + if(cur->right) q.push(cur->right); + if(cur->left && cur->right) + q.pop(); + else + break; + } + } + + int insert(int v) { + + TreeNode* cur = q.front(); + if(!cur->left){ + cur->left = new TreeNode(v); + q.push(cur->left); + } + else{ + assert(!cur->right); + cur->right = new TreeNode(v); + q.push(cur->right); + q.pop(); + } + return cur->val; + } + + TreeNode* get_root() { + return root; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0920-Number-of-Music-Playlists/cpp-0920/CMakeLists.txt b/0501-1000/0920-Number-of-Music-Playlists/cpp-0920/CMakeLists.txt new file mode 100644 index 00000000..d58a861e --- /dev/null +++ b/0501-1000/0920-Number-of-Music-Playlists/cpp-0920/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(D) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main3.cpp) +add_executable(D ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0920-Number-of-Music-Playlists/cpp-0920/main.cpp b/0501-1000/0920-Number-of-Music-Playlists/cpp-0920/main.cpp new file mode 100644 index 00000000..87f19034 --- /dev/null +++ b/0501-1000/0920-Number-of-Music-Playlists/cpp-0920/main.cpp @@ -0,0 +1,84 @@ +/// Source : https://leetcode.com/problems/number-of-music-playlists/description/ +/// Author : liuyubobobo +/// Time : 2018-10-06 + +#include +#include + +using namespace std; + + +/// Combination Mathematic +/// Using inclusive-exclusive theory +/// +/// Time Complexity: O((N - K) * L + N * N) +/// Space Complexity: O(N * N) +class Solution { + +private: + long long MOD = 1e9 + 7; + +public: + int numMusicPlaylists(int N, int L, int K) { + + vector> dp(101, vector(101, -1ll)); + + long long res = num(N, L, K); + + for(int sub = 1; N - sub >= K + 1; sub ++){ + + int n = N - sub; + long long tres = num(n, L, K); + tres = (tres * C(N, n, dp)) % MOD; + + if(sub % 2){ + res -= tres; + if(res < 0ll) res += MOD; + } + else + res = (res + tres) % MOD; + } + return res; + } + +private: + long long C(int a, int b, vector>& dp){ + + if(b == 0 || a == b) + return 1ll; + + if(dp[a][b] != -1ll) + return dp[a][b]; + + return dp[a][b] = (C(a - 1, b, dp) + C(a - 1, b - 1, dp)) % MOD; + } + + // How many music list can we get to use at most n songs + int num(int N, int L, int K) { + + long long res = 1ll; + for(int i = 0; i <= K; i ++) + res = res * (N - i) % MOD; + for(int i = K + 1; i < L; i ++) + res = res * (N - K) % MOD; + return res; + } +}; + + +int main() { + + cout << Solution().numMusicPlaylists(3, 3, 1) << endl; + // 6 + + cout << Solution().numMusicPlaylists(2, 3, 0) << endl; + // 6 + + cout << Solution().numMusicPlaylists(2, 3, 1) << endl; + // 2 + + cout << Solution().numMusicPlaylists(3, 3, 0) << endl; + // 6 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0920-Number-of-Music-Playlists/cpp-0920/main2.cpp b/0501-1000/0920-Number-of-Music-Playlists/cpp-0920/main2.cpp new file mode 100644 index 00000000..c22e6948 --- /dev/null +++ b/0501-1000/0920-Number-of-Music-Playlists/cpp-0920/main2.cpp @@ -0,0 +1,59 @@ +/// Source : https://leetcode.com/problems/number-of-music-playlists/description/ +/// Author : liuyubobobo +/// Time : 2018-10-07 + +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(L * N) +/// Space Complexity: O(L * N) +class Solution { + +private: + long long MOD = 1e9 + 7; + +public: + int numMusicPlaylists(int N, int L, int K) { + + vector> dp(L + 1, vector(N + 1, -1ll)); + return dfs(L, N, K, N, dp); + } + +private: + long long dfs(int l, int n, int K, int N, + vector>& dp) { + + if(n == 0 && l == 0) + return 1; + + if(n == 0 || l == 0) + return 0; + + if(dp[l][n] != -1) return dp[l][n]; + + return dp[l][n] = ((dfs(l - 1, n - 1, K, N, dp) * (N - n + 1)) % MOD + + (dfs(l - 1, n, K, N, dp) * max(n - K, 0)) % MOD) % MOD; + } +}; + + +int main() { + + cout << Solution().numMusicPlaylists(3, 3, 1) << endl; + // 6 + + cout << Solution().numMusicPlaylists(2, 3, 0) << endl; + // 6 + + cout << Solution().numMusicPlaylists(2, 3, 1) << endl; + // 2 + + cout << Solution().numMusicPlaylists(3, 3, 0) << endl; + // 6 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0920-Number-of-Music-Playlists/cpp-0920/main3.cpp b/0501-1000/0920-Number-of-Music-Playlists/cpp-0920/main3.cpp new file mode 100644 index 00000000..2243fb8e --- /dev/null +++ b/0501-1000/0920-Number-of-Music-Playlists/cpp-0920/main3.cpp @@ -0,0 +1,49 @@ +/// Source : https://leetcode.com/problems/number-of-music-playlists/description/ +/// Author : liuyubobobo +/// Time : 2018-10-07 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(L * N) +/// Space Complexity: O(L * N) +class Solution { + +private: + long long MOD = 1e9 + 7; + +public: + int numMusicPlaylists(int N, int L, int K) { + + vector> dp(L + 1, vector(N + 1, 0ll)); + dp[0][0] = 1ll; + for(int i = 1; i <= L; i ++) + for(int j = 1; j <= N; j ++){ + dp[i][j] = (dp[i][j] + dp[i - 1][j - 1] * (N - j + 1) % MOD) % MOD; + dp[i][j] = (dp[i][j] + dp[i - 1][j] * max(j - K, 0) % MOD) % MOD; + } + return dp[L][N]; + } +}; + + +int main() { + + cout << Solution().numMusicPlaylists(3, 3, 1) << endl; + // 6 + + cout << Solution().numMusicPlaylists(2, 3, 0) << endl; + // 6 + + cout << Solution().numMusicPlaylists(2, 3, 1) << endl; + // 2 + + cout << Solution().numMusicPlaylists(3, 3, 0) << endl; + // 6 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0921-Minimum-Add-to-Make-Parentheses-Valid/cpp-0921/CMakeLists.txt b/0501-1000/0921-Minimum-Add-to-Make-Parentheses-Valid/cpp-0921/CMakeLists.txt new file mode 100644 index 00000000..08335525 --- /dev/null +++ b/0501-1000/0921-Minimum-Add-to-Make-Parentheses-Valid/cpp-0921/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(B) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main2.cpp) +add_executable(B ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0921-Minimum-Add-to-Make-Parentheses-Valid/cpp-0921/main.cpp b/0501-1000/0921-Minimum-Add-to-Make-Parentheses-Valid/cpp-0921/main.cpp new file mode 100644 index 00000000..a211be46 --- /dev/null +++ b/0501-1000/0921-Minimum-Add-to-Make-Parentheses-Valid/cpp-0921/main.cpp @@ -0,0 +1,39 @@ +/// Source : https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/description/ +/// Author : liuyubobobo +/// Time : 2018-10-13 + +#include +#include + +using namespace std; + + +/// Using Stack +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int minAddToMakeValid(string S) { + + stack s; + for(char c: S) + if(c == '(') + s.push(c); + else{ + if(!s.empty() && s.top() == '(') + s.pop(); + else + s.push(c); + } + return s.size(); + } +}; + + +int main() { + + cout << Solution().minAddToMakeValid("()))((") << endl; + // 4 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0921-Minimum-Add-to-Make-Parentheses-Valid/cpp-0921/main2.cpp b/0501-1000/0921-Minimum-Add-to-Make-Parentheses-Valid/cpp-0921/main2.cpp new file mode 100644 index 00000000..b64ff0e5 --- /dev/null +++ b/0501-1000/0921-Minimum-Add-to-Make-Parentheses-Valid/cpp-0921/main2.cpp @@ -0,0 +1,39 @@ +/// Source : https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/description/ +/// Author : liuyubobobo +/// Time : 2018-10-14 + +#include +#include + +using namespace std; + + +/// Using balance to record the stack top '(' size +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int minAddToMakeValid(string S) { + + int res = 0, bal = 0; + for(char c: S) + if(c == '(') + res ++, bal ++; + else{ + if(bal) + res --, bal --; + else + res ++, bal = 0; + } + return res; + } +}; + + +int main() { + + cout << Solution().minAddToMakeValid("()))((") << endl; + // 4 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0922-Sort-Array-By-Parity-II/cpp-0922/CMakeLists.txt b/0501-1000/0922-Sort-Array-By-Parity-II/cpp-0922/CMakeLists.txt new file mode 100644 index 00000000..651ecc24 --- /dev/null +++ b/0501-1000/0922-Sort-Array-By-Parity-II/cpp-0922/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(A) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main4.cpp) +add_executable(A ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0922-Sort-Array-By-Parity-II/cpp-0922/main.cpp b/0501-1000/0922-Sort-Array-By-Parity-II/cpp-0922/main.cpp new file mode 100644 index 00000000..b50e450d --- /dev/null +++ b/0501-1000/0922-Sort-Array-By-Parity-II/cpp-0922/main.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/sort-array-by-parity-ii/description/ +/// Author : liuyubobobo +/// Time : 2018-10-13 + +#include +#include + +using namespace std; + + +/// Seperate odd and even elements into different vectors +/// Time Complexity: O(n) +/// Space Complexity: O(2*n) +class Solution { +public: + vector sortArrayByParityII(vector& A) { + + vector even, odd; + for(int i = 0; i < A.size(); i ++) + if(A[i] % 2) + odd.push_back(A[i]); + else + even.push_back(A[i]); + + vector ret; + int p_odd = 0, p_even = 0; + for(int i = 0; i < A.size(); i ++) + if(i % 2) + ret.push_back(odd[p_odd ++]); + else + ret.push_back(even[p_even ++]); + return ret; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0922-Sort-Array-By-Parity-II/cpp-0922/main2.cpp b/0501-1000/0922-Sort-Array-By-Parity-II/cpp-0922/main2.cpp new file mode 100644 index 00000000..23296027 --- /dev/null +++ b/0501-1000/0922-Sort-Array-By-Parity-II/cpp-0922/main2.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/sort-array-by-parity-ii/description/ +/// Author : liuyubobobo +/// Time : 2018-10-13 + +#include +#include + +using namespace std; + + +/// Two pass to deal with odd and even elements seperately +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector sortArrayByParityII(vector& A) { + + vector ret(A.size()); + int p_even = 0; + for(int a: A) + if(a % 2 == 0){ + ret[p_even] = a; + p_even += 2; + } + + int p_odd = 1; + for(int a: A) + if(a % 2){ + ret[p_odd] = a; + p_odd += 2; + } + return ret; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0922-Sort-Array-By-Parity-II/cpp-0922/main3.cpp b/0501-1000/0922-Sort-Array-By-Parity-II/cpp-0922/main3.cpp new file mode 100644 index 00000000..46194888 --- /dev/null +++ b/0501-1000/0922-Sort-Array-By-Parity-II/cpp-0922/main3.cpp @@ -0,0 +1,41 @@ +/// Source : https://leetcode.com/problems/sort-array-by-parity-ii/description/ +/// Author : liuyubobobo +/// Time : 2018-10-14 + +#include +#include + +using namespace std; + + +/// Make the change in place +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + vector sortArrayByParityII(vector& A) { + + for(int i = 0; i < A.size(); i ++) + if(i % 2 == 0 && A[i] % 2){ + int j = i + 1; + for(; j < A.size(); j += 2) + if(A[j] % 2 == 0) + break; + swap(A[i], A[j]); + } + else if(i % 2 && A[i] % 2 == 0){ + int j = i + 1; + for(; j < A.size(); j += 2) + if(A[j] % 2) + break; + swap(A[i], A[j]); + } + return A; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0922-Sort-Array-By-Parity-II/cpp-0922/main4.cpp b/0501-1000/0922-Sort-Array-By-Parity-II/cpp-0922/main4.cpp new file mode 100644 index 00000000..2c8f0021 --- /dev/null +++ b/0501-1000/0922-Sort-Array-By-Parity-II/cpp-0922/main4.cpp @@ -0,0 +1,36 @@ +/// Source : https://leetcode.com/problems/sort-array-by-parity-ii/description/ +/// Author : liuyubobobo +/// Time : 2018-10-14 + +#include +#include + +using namespace std; + + +/// Make the change in place +/// and the code clearer :-) +/// +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + vector sortArrayByParityII(vector& A) { + + int j = 1; + for(int i = 0; i < A.size(); i += 2) + if(A[i] % 2){ + for(; j < A.size(); j += 2) + if(A[j] % 2 == 0) + break; + swap(A[i], A[j]); + } + return A; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0923-3Sum-With-Multiplicity/cpp-0923/CMakeLists.txt b/0501-1000/0923-3Sum-With-Multiplicity/cpp-0923/CMakeLists.txt new file mode 100644 index 00000000..62f938f1 --- /dev/null +++ b/0501-1000/0923-3Sum-With-Multiplicity/cpp-0923/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(C) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main4.cpp) +add_executable(C ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0923-3Sum-With-Multiplicity/cpp-0923/main.cpp b/0501-1000/0923-3Sum-With-Multiplicity/cpp-0923/main.cpp new file mode 100644 index 00000000..14d5bbdf --- /dev/null +++ b/0501-1000/0923-3Sum-With-Multiplicity/cpp-0923/main.cpp @@ -0,0 +1,89 @@ +/// Source : https://leetcode.com/problems/3sum-with-multiplicity/description/ +/// Author : liuyubobobo +/// Time : 2018-10-13 + +#include +#include +#include + +using namespace std; + + +/// Using HashMap and Combinations +/// Using Memory Search to calculate the combinations +/// +/// Try to use Dynamic Programming to get the combinations table but MLE :-( +/// +/// Time Complexity: O(n^2) +/// Space Complexity: O(n^2) +class Solution { + +private: + int MOD = 1e9 + 7; + +public: + int threeSumMulti(vector& A, int target) { + + map freq; + for(int a: A) + freq[a] ++; + + vector keys; + for(const pair& p: freq) + keys.push_back(p.first); + + int res = 0; + vector> comb(3001, vector(3001, -1)); + for(int i = 0; i < keys.size(); i ++) + for(int j = i; j < keys.size(); j ++){ + int a = keys[i], b = keys[j], c = target - keys[i] - keys[j]; + if(c >= b){ + if(a == b && b == c) + res = (res + C(freq[a], 3, comb)) % MOD; + else if(a == b) + res = (res + (long long)C(freq[a], 2, comb) * freq[c]) % MOD; + else if(b == c) + res = (res + freq[a] * (long long)C(freq[b], 2, comb)) % MOD; + else + res = (res + freq[a] * freq[b] * freq[c]) % MOD; + } + else + break; + } + return res; + } + +private: + int C(int m, int n, vector>& comb){ + + if(n > m) + return 0; + + if(n == 0 || m == n) + return 1; + + if(comb[m][n] != -1) + return comb[m][n]; + + return comb[m][n] = (C(m - 1, n, comb) + C(m - 1, n - 1, comb)) % MOD; + } +}; + + +int main() { + + vector A1 = {1,1,2,2,3,3,4,4,5,5}; + cout << Solution().threeSumMulti(A1, 8) << endl; + // 20 + + vector A2 = {1,1,2,2,2,2}; + cout << Solution().threeSumMulti(A2, 5) << endl; + // 12 + + vector A3(3000, 0); + cout << Solution().threeSumMulti(A3, 0) << endl; + // 495500972 + + cout << sizeof("") << endl; + return 0; +} \ No newline at end of file diff --git a/0501-1000/0923-3Sum-With-Multiplicity/cpp-0923/main2.cpp b/0501-1000/0923-3Sum-With-Multiplicity/cpp-0923/main2.cpp new file mode 100644 index 00000000..781b7b4c --- /dev/null +++ b/0501-1000/0923-3Sum-With-Multiplicity/cpp-0923/main2.cpp @@ -0,0 +1,87 @@ +/// Source : https://leetcode.com/problems/3sum-with-multiplicity/description/ +/// Author : liuyubobobo +/// Time : 2018-10-15 + +#include +#include +#include + +using namespace std; + + +/// Using HashMap and Combinations +/// Since we ony use combination numbers like C(n, 2) or C(n, 3), +/// There's no need to calculate the n * n combination tables, +/// We calculate a n * 3 combination table instead :-) +/// +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { + +private: + int MOD = 1e9 + 7; + +public: + int threeSumMulti(vector& A, int target) { + + vector> C = calcC(A.size()); + + map freq; + for(int a: A) + freq[a] ++; + + vector keys; + for(const pair& p: freq) + keys.push_back(p.first); + + int res = 0; + for(int i = 0; i < keys.size(); i ++) + for(int j = i; j < keys.size(); j ++){ + int a = keys[i], b = keys[j], c = target - keys[i] - keys[j]; + if(c >= b){ + if(a == b && b == c) + res = (res + C[freq[a]][3]) % MOD; + else if(a == b) + res = (res + (long long)C[freq[a]][2] * freq[c]) % MOD; + else if(b == c) + res = (res + freq[a] * (long long)C[freq[b]][2]) % MOD; + else + res = (res + freq[a] * freq[b] * freq[c]) % MOD; + } + else + break; + } + return res; + } + +private: + vector> calcC(int n){ + + vector> C(n + 1, vector(4, 0)); + C[0][0] = 1; + for(int i = 1; i <= n; i ++){ + C[i][0] = 1; + for(int j = 1; j <= 4; j ++) + C[i][j] = (C[i - 1][j] + C[i - 1][j - 1]) % MOD; + } + return C; + } +}; + + +int main() { + + vector A1 = {1,1,2,2,3,3,4,4,5,5}; + cout << Solution().threeSumMulti(A1, 8) << endl; + // 20 + + vector A2 = {1,1,2,2,2,2}; + cout << Solution().threeSumMulti(A2, 5) << endl; + // 12 + + vector A3(3000, 0); + cout << Solution().threeSumMulti(A3, 0) << endl; + // 495500972 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0923-3Sum-With-Multiplicity/cpp-0923/main3.cpp b/0501-1000/0923-3Sum-With-Multiplicity/cpp-0923/main3.cpp new file mode 100644 index 00000000..de297297 --- /dev/null +++ b/0501-1000/0923-3Sum-With-Multiplicity/cpp-0923/main3.cpp @@ -0,0 +1,87 @@ +/// Source : https://leetcode.com/problems/3sum-with-multiplicity/description/ +/// Author : liuyubobobo +/// Time : 2018-10-15 + +#include +#include +#include + +using namespace std; + + +/// Using HashMap and Combinations +/// Since we ony use combination numbers like C(n, 2) or C(n, 3), +/// There's no need to calculate any combination tables, actually :-) +/// +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { + +private: + int MOD = 1e9 + 7; + +public: + int threeSumMulti(vector& A, int target) { + + map freq; + for(int a: A) + freq[a] ++; + + vector keys; + for(const pair& p: freq) + keys.push_back(p.first); + + int res = 0; + for(int i = 0; i < keys.size(); i ++) + for(int j = i; j < keys.size(); j ++){ + int a = keys[i], b = keys[j], c = target - keys[i] - keys[j]; + if(c >= b){ + if(a == b && b == c && freq[a] >= 3){ + long long C = ((long long)freq[a] * (freq[a] - 1) * (freq[a] - 2) / 6) % (long long)MOD; + res = (res + C) % MOD; + } + else if(a == b && b != c && freq[a] >= 2){ + long long C = freq[a] * (freq[a] - 1) / 2; + res = (res + C * freq[c]) % MOD; + continue; + } + else if(b == c && a != b && freq[b] >= 2){ + long long C = freq[b] * (freq[b] - 1) / 2; + res = (res + freq[a] * C) % MOD; + continue; + } + else if(a != b && b != c) + res = (res + freq[a] * freq[b] * freq[c]) % MOD; + } + else + break; + } + return res; + } +}; + + +int main() { + + vector A1 = {1,1,2,2,3,3,4,4,5,5}; + cout << Solution().threeSumMulti(A1, 8) << endl; + // 20 + + vector A2 = {1,1,2,2,2,2}; + cout << Solution().threeSumMulti(A2, 5) << endl; + // 12 + + vector A3(3000, 0); + cout << Solution().threeSumMulti(A3, 0) << endl; + // 495500972 + + vector A4 = {2, 1, 3}; + cout << Solution().threeSumMulti(A4, 6) << endl; + // 1 + + vector A5 = {3, 3, 0, 0, 3, 2, 2, 3}; + cout << Solution().threeSumMulti(A5, 6) << endl; + // 12 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0923-3Sum-With-Multiplicity/cpp-0923/main4.cpp b/0501-1000/0923-3Sum-With-Multiplicity/cpp-0923/main4.cpp new file mode 100644 index 00000000..98bb7de2 --- /dev/null +++ b/0501-1000/0923-3Sum-With-Multiplicity/cpp-0923/main4.cpp @@ -0,0 +1,84 @@ +/// Source : https://leetcode.com/problems/3sum-with-multiplicity/description/ +/// Author : liuyubobobo +/// Time : 2018-10-16 + +#include +#include +#include + +using namespace std; + + +/// Three Pointers +/// Based on Two Pointers Algorithm in 2-Sum Problem +/// +/// Time Complexity: O(n^2) +/// Space Complexity: O(1) +class Solution { + +private: + int MOD = 1e9 + 7; + +public: + int threeSumMulti(vector& A, int target) { + + sort(A.begin(), A.end()); + + int res = 0; + for(int i = 0; i < A.size(); i ++){ + + int t = target - A[i]; + int j = i + 1, k = A.size() - 1; + while(j < k){ + if(A[j] + A[k] < t) + j ++; + else if(A[j] + A[k] > t) + k --; + else{ + if(A[j] != A[k]){ + int jj = j + 1; + for(; jj < A.size() && A[jj] == A[j]; jj ++); + + int kk = k - 1; + for(; kk >= 0 && A[kk] == A[k]; kk --); + + res = (res + (jj - j) * (k - kk)) % MOD; + j = jj; + k = kk; + } + else{ + res = (res + (k - j + 1) * (k - j) / 2) % MOD; + break; + } + } + } + } + return res; + } +}; + + +int main() { + + vector A1 = {1,1,2,2,3,3,4,4,5,5}; + cout << Solution().threeSumMulti(A1, 8) << endl; + // 20 + + vector A2 = {1,1,2,2,2,2}; + cout << Solution().threeSumMulti(A2, 5) << endl; + // 12 + + vector A3(3000, 0); + cout << Solution().threeSumMulti(A3, 0) << endl; + // 495500972 + + vector A4 = {2, 1, 3}; + cout << Solution().threeSumMulti(A4, 6) << endl; + // 1 + + vector A5 = {3, 3, 0, 0, 3, 2, 2, 3}; + cout << Solution().threeSumMulti(A5, 6) << endl; + // 12 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0924-Minimize-Malware-Spread/cpp-0924/CMakeLists.txt b/0501-1000/0924-Minimize-Malware-Spread/cpp-0924/CMakeLists.txt new file mode 100644 index 00000000..ade1f6b8 --- /dev/null +++ b/0501-1000/0924-Minimize-Malware-Spread/cpp-0924/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(D) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main2.cpp) +add_executable(D ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0924-Minimize-Malware-Spread/cpp-0924/main.cpp b/0501-1000/0924-Minimize-Malware-Spread/cpp-0924/main.cpp new file mode 100644 index 00000000..4f05f2b9 --- /dev/null +++ b/0501-1000/0924-Minimize-Malware-Spread/cpp-0924/main.cpp @@ -0,0 +1,66 @@ +/// Source : https://leetcode.com/problems/minimize-malware-spread/description/ +/// Author : liuyubobobo +/// Time : 2018-10-13 +/// Updated: 2019-09-23 + +#include +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { + +private: + int n; + set init_set; + vector visited; + vector cc_sz; + vector cc_mal_num; + +public: + int minMalwareSpread(vector>& graph, vector& initial) { + + for(int e: initial) + init_set.insert(e); + + n = graph.size(); + visited.resize(n, false); + + int best = 0, res = -1, ccid = 0; + for(int v: init_set) + if(!visited[v]){ + cc_sz.push_back(0), cc_mal_num.push_back(0); + cc_sz[ccid] = dfs(graph, v, ccid); + if(cc_mal_num[ccid] == 1 && cc_sz[ccid] > best){ + best = cc_sz[ccid]; + res = v; + } + ccid ++; + } + return res == -1 ? *init_set.begin() : res; + } + +private: + int dfs(const vector>& g, int v, int ccid){ + + visited[v] = true; + if(init_set.count(v)) cc_mal_num[ccid] ++; + + int res = 1; + for(int next = 0; next < n; next ++) + if(g[v][next] && !visited[next]) + res += dfs(g, next, ccid); + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0924-Minimize-Malware-Spread/cpp-0924/main2.cpp b/0501-1000/0924-Minimize-Malware-Spread/cpp-0924/main2.cpp new file mode 100644 index 00000000..f6760ca1 --- /dev/null +++ b/0501-1000/0924-Minimize-Malware-Spread/cpp-0924/main2.cpp @@ -0,0 +1,91 @@ +/// Source : https://leetcode.com/problems/minimize-malware-spread/description/ +/// Author : liuyubobobo +/// Time : 2018-10-16 +/// Updated: 2019-09-23 + +#include +#include +#include +#include + +using namespace std; + + +/// Using Union-Find +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class UF{ + +private: + vector parent, sz; + +public: + UF(int n){ + parent.clear(); + for(int i = 0 ; i < n ; i ++){ + parent.push_back(i); + sz.push_back(1); + } + } + + int find(int p){ + if( p != parent[p] ) + parent[p] = find( parent[p] ); + return parent[p]; + } + + bool isConnected(int p , int q){ + return find(p) == find(q); + } + + void unionElements(int p, int q){ + + int pRoot = find(p); + int qRoot = find(q); + + if( pRoot == qRoot ) + return; + + parent[pRoot] = qRoot; + sz[qRoot] += sz[pRoot]; + } + + int size(int p){ + return sz[find(p)]; + } +}; + +class Solution { + +public: + int minMalwareSpread(vector>& graph, vector& initial) { + + int n = graph.size(); + UF uf(n); + for(int i = 0; i < n; i ++) + for(int j = i + 1; j < n; j ++) + if(graph[i][j]) + uf.unionElements(i, j); + + set init_set(initial.begin(), initial.end()); + + unordered_map cc_sz, cc_mal_num; + for(int e: init_set) + cc_sz[uf.find(e)] = uf.size(e), + cc_mal_num[uf.find(e)] ++; + + int best = 0, res = -1; + for(int e: init_set) + if(cc_mal_num[uf.find(e)] == 1 && cc_sz[uf.find(e)] > best){ + best = cc_sz[uf.find(e)]; + res = e; + } + return res == -1 ? *init_set.begin() : res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0925-Long-Pressed-Name/cpp-0925/CMakeLists.txt b/0501-1000/0925-Long-Pressed-Name/cpp-0925/CMakeLists.txt new file mode 100644 index 00000000..5cc31b93 --- /dev/null +++ b/0501-1000/0925-Long-Pressed-Name/cpp-0925/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(A) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main3.cpp) +add_executable(A ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0925-Long-Pressed-Name/cpp-0925/main.cpp b/0501-1000/0925-Long-Pressed-Name/cpp-0925/main.cpp new file mode 100644 index 00000000..1449ccfc --- /dev/null +++ b/0501-1000/0925-Long-Pressed-Name/cpp-0925/main.cpp @@ -0,0 +1,60 @@ +/// Source : https://leetcode.com/problems/long-pressed-name/ +/// Author : liuyubobobo +/// Time : 2018-10-21 + +#include +#include + +using namespace std; + + +/// Split the name and typed by characters +/// Time Complexity: O(len(typed) + len(name)) +/// Space Complexity: O(max(len(typed), len(name))) +class Solution { + +public: + bool isLongPressedName(string name, string typed) { + + vector> chars1 = split(name); + vector> chars2 = split(typed); + if(chars1.size() != chars2.size()) + return false; + + for(int i = 0; i < chars1.size(); i ++) + if(chars1[i] > chars2[i]) + return false; + return true; + } + +private: + vector> split(const string& s){ + + vector> res; + int start = 0; + for(int i = start + 1; i <= s.size(); i ++) + if(i == s.size() || s[i] != s[start]){ + res.push_back(make_pair(s[start], i - start)); + start = i; + } + return res; + } +}; + + +int main() { + + cout << Solution().isLongPressedName("alex", "aaleex") << endl; + // true + + cout << Solution().isLongPressedName("saeed", "ssaaedd") << endl; + // false + + cout << Solution().isLongPressedName("leelee", "lleeelee") << endl; + // true + + cout << Solution().isLongPressedName("laiden", "laiden") << endl; + // true + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0925-Long-Pressed-Name/cpp-0925/main2.cpp b/0501-1000/0925-Long-Pressed-Name/cpp-0925/main2.cpp new file mode 100644 index 00000000..301c41f3 --- /dev/null +++ b/0501-1000/0925-Long-Pressed-Name/cpp-0925/main2.cpp @@ -0,0 +1,61 @@ +/// Source : https://leetcode.com/problems/long-pressed-name/ +/// Author : liuyubobobo +/// Time : 2018-10-21 + +#include +#include + +using namespace std; + + +/// Split the name and typed by characters +/// Do not use vector to store the split result :-) +/// +/// Time Complexity: O(len(typed) + len(name)) +/// Space Complexity: O(1) +class Solution { + +public: + bool isLongPressedName(string name, string typed) { + + int start1 = 0, start2 = 0; + for(int i1 = start1 + 1; i1 <= name.size(); i1 ++) + if(i1 == name.size() || name[i1] != name[start1]){ + + if(start2 >= typed.size()) + return false; + + for(int i2 = start2 + 1; i2 <= typed.size(); i2 ++) + if(i2 == typed.size() || typed[i2] != typed[start2]){ + + if(typed[start2] != name[start1] || i2 - start2 < i1 - start1) + return false; + + start2 = i2; + break; + } + + start1 = i1; + } + + return start1 == name.size(); + } +}; + + +int main() { + + cout << Solution().isLongPressedName("alex", "aaleex") << endl; + // true + + cout << Solution().isLongPressedName("saeed", "ssaaedd") << endl; + // false + + cout << Solution().isLongPressedName("leelee", "lleeelee") << endl; + // true + + cout << Solution().isLongPressedName("laiden", "laiden") << endl; + // true + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0925-Long-Pressed-Name/cpp-0925/main3.cpp b/0501-1000/0925-Long-Pressed-Name/cpp-0925/main3.cpp new file mode 100644 index 00000000..01a329b7 --- /dev/null +++ b/0501-1000/0925-Long-Pressed-Name/cpp-0925/main3.cpp @@ -0,0 +1,48 @@ +/// Source : https://leetcode.com/problems/long-pressed-name/ +/// Author : liuyubobobo +/// Time : 2018-10-20 + +#include + +using namespace std; + + +/// Two Pointers +/// Time Complexity: O(len(typed)) +/// Space Complexity: O(1) +class Solution { +public: + bool isLongPressedName(string name, string typed) { + + if (name[0] != typed[0]) + return false; + + int j = 1; + for (int i = 1; i < name.size();) + if (typed[j] == name[i]) + j++, i++; + else if (typed[j] == name[i - 1]) + j++; + else + return false; + return true; + } +}; + + +int main() { + + cout << Solution().isLongPressedName("alex", "aaleex") << endl; + // true + + cout << Solution().isLongPressedName("saeed", "ssaaedd") << endl; + // false + + cout << Solution().isLongPressedName("leelee", "lleeelee") << endl; + // true + + cout << Solution().isLongPressedName("laiden", "laiden") << endl; + // true + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0926-Flip-String-to-Monotone-Increasing/cpp-0926/CMakeLists.txt b/0501-1000/0926-Flip-String-to-Monotone-Increasing/cpp-0926/CMakeLists.txt new file mode 100644 index 00000000..ae89e070 --- /dev/null +++ b/0501-1000/0926-Flip-String-to-Monotone-Increasing/cpp-0926/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(B) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(B ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0926-Flip-String-to-Monotone-Increasing/cpp-0926/main.cpp b/0501-1000/0926-Flip-String-to-Monotone-Increasing/cpp-0926/main.cpp new file mode 100644 index 00000000..5291e61c --- /dev/null +++ b/0501-1000/0926-Flip-String-to-Monotone-Increasing/cpp-0926/main.cpp @@ -0,0 +1,41 @@ +/// Source : https://leetcode.com/problems/flip-string-to-monotone-increasing/ +/// Author : liuyubobobo +/// Time : 2018-10-20 + +#include +#include + +using namespace std; + + +/// Precalculation +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int minFlipsMonoIncr(string S) { + + if(S.size() == 0 || S.size() == 1) + return 0; + + int n = S.size(); + vector zeros(n + 1, 0), ones(n + 1, 0); + + for(int i = 1; i <= S.size(); i ++) + ones[i] = ones[i - 1] + (S[i - 1] == '1'); + + for(int i = n - 1; i >= 0; i --) + zeros[i] = zeros[i + 1] + (S[i] == '0'); + + int res = INT_MAX; + for(int i = 0; i <= n; i ++) + res = min(res, ones[i] + zeros[i]); + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0927-Three-Equal-Parts/cpp-0927/CMakeLists.txt b/0501-1000/0927-Three-Equal-Parts/cpp-0927/CMakeLists.txt new file mode 100644 index 00000000..85e27b1b --- /dev/null +++ b/0501-1000/0927-Three-Equal-Parts/cpp-0927/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(C) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(C ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0927-Three-Equal-Parts/cpp-0927/main.cpp b/0501-1000/0927-Three-Equal-Parts/cpp-0927/main.cpp new file mode 100644 index 00000000..0105b97d --- /dev/null +++ b/0501-1000/0927-Three-Equal-Parts/cpp-0927/main.cpp @@ -0,0 +1,75 @@ +/// Source : https://leetcode.com/problems/three-equal-parts/ +/// Author : liuyubobobo +/// Time : 2018-10-20 + +#include +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// The three parts must contain equal number of ones :-) +/// +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + vector threeEqualParts(vector& A) { + + int n = A.size(); + + int sum = accumulate(A.begin(), A.end(), 0); + if(sum == 0) + return {0, n - 1}; + + if(sum % 3) + return {-1, -1}; + + int k = sum / 3; + int j = n - 1, t = 0; + for(; j >= 0; j --){ + t += (A[j] == 1); + if(t == k) + break; + } + + int i = 0; + for(;i < n; i ++) + if(A[i]) break; + + for(int jj = j; jj < n; i ++, jj ++) + if(A[i] != A[jj]) + return {-1, -1}; + + for(k = i; k < n; k ++) + if(A[k]) break; + + for(int jj = j; jj < n; k ++, jj ++) + if(A[k] != A[jj]) + return {-1, -1}; + + return {i - 1, k}; + } +}; + + +void print_vec(const vector& vec){ + for(int e: vec) + cout << e << " "; + cout << endl; +} + +int main() { + + vector A1 = {1,0,1,0,1}; + print_vec(Solution().threeEqualParts(A1)); + // 0 3 + + vector A2 = {1,1,0,1,1}; + print_vec(Solution().threeEqualParts(A2)); + // -1 -1 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0928-Minimize-Malware-Spread-II/cpp-0928/CMakeLists.txt b/0501-1000/0928-Minimize-Malware-Spread-II/cpp-0928/CMakeLists.txt new file mode 100644 index 00000000..d58a861e --- /dev/null +++ b/0501-1000/0928-Minimize-Malware-Spread-II/cpp-0928/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(D) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main3.cpp) +add_executable(D ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0928-Minimize-Malware-Spread-II/cpp-0928/main.cpp b/0501-1000/0928-Minimize-Malware-Spread-II/cpp-0928/main.cpp new file mode 100644 index 00000000..4249e64f --- /dev/null +++ b/0501-1000/0928-Minimize-Malware-Spread-II/cpp-0928/main.cpp @@ -0,0 +1,83 @@ +/// Source : https://leetcode.com/problems/minimize-malware-spread-ii/ +/// Author : liuyubobobo +/// Time : 2018-10-20 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(len(initial) * v^2) +/// Space Complexity: O(v) +class Solution { + +private: + int n; + +public: + int minMalwareSpread(vector>& graph, vector& initial) { + + n = graph.size(); + sort(initial.begin(), initial.end()); + + int res = -1, best = INT_MAX; + for(int v: initial) { + int num = try_remove(graph, v, initial); + if(num < best){ + best = num; + res = v; + } + } + return res; + } + +private: + int try_remove(const vector>& g, int v, const vector& initial){ + + vector visited(n, false); + int res = 0; + for(int u: initial) + if(u != v && !visited[u]) + res += dfs(g, u, v, visited); + return res; + } + + int dfs(const vector>& g, int u, int v, vector& visited){ + + visited[u] = true; + + int res = 1; + for(int i = 0; i < n; i ++) + if(g[u][i] && i != v && !visited[i]) + res += dfs(g, i, v, visited); + return res; + } + +}; + + +int main() { + + vector> g1 = {{1,1,0,0},{1,1,1,0},{0,1,1,1},{0,0,1,1}}; + vector initial1 = {3,0}; + cout << Solution().minMalwareSpread(g1, initial1) << endl; + // 0 + + vector> g2 = { + {1,0,0,0,0,0,0,0,0}, + {0,1,0,0,0,0,0,0,0}, + {0,0,1,0,1,0,1,0,0}, + {0,0,0,1,0,0,0,0,0}, + {0,0,1,0,1,0,0,0,0}, + {0,0,0,0,0,1,0,0,0}, + {0,0,1,0,0,0,1,0,0}, + {0,0,0,0,0,0,0,1,0}, + {0,0,0,0,0,0,0,0,1}}; + vector initial2 = {6,0,4}; + cout << Solution().minMalwareSpread(g2, initial2) << endl; + // 0 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0928-Minimize-Malware-Spread-II/cpp-0928/main2.cpp b/0501-1000/0928-Minimize-Malware-Spread-II/cpp-0928/main2.cpp new file mode 100644 index 00000000..b005cdc5 --- /dev/null +++ b/0501-1000/0928-Minimize-Malware-Spread-II/cpp-0928/main2.cpp @@ -0,0 +1,94 @@ +/// Source : https://leetcode.com/problems/minimize-malware-spread-ii/ +/// Author : liuyubobobo +/// Time : 2018-10-21 + +#include +#include +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(len(initial) * v^2) +/// Space Complexity: O(v) +class Solution { + +private: + int n; + +public: + int minMalwareSpread(vector>& graph, vector& initial) { + + n = graph.size(); + vector removed(n, false); + for(int v: initial) + removed[v] = true; + + vector> infection(n); + for(int v: initial){ + vector visited(n, false); + dfs(graph, v, removed, visited); + for(int u = 0; u < n; u ++) + if(visited[u]) + infection[u].insert(v); + } + + unordered_map effective; + for(int i = 0; i < n; i ++) + if(infection[i].size() == 1) + effective[*infection[i].begin()] ++; + + int res = -1, best = 0; + for(const pair& p: effective) + if(p.second > best){ + best = p.second; + res = p.first; + } + else if(p.second == best) + res = min(res, p.first); + return res; + } + +private: + void dfs(const vector>& g, int v, + const vector& removed, vector& visited){ + + visited[v] = true; + + for(int i = 0; i < n; i ++) + if(g[v][i] && !removed[i] && !visited[i]) + dfs(g, i, removed, visited); + } +}; + + +int main() { + + vector> g1 = {{1,1,0,0},{1,1,1,0},{0,1,1,1},{0,0,1,1}}; + vector initial1 = {3,0}; + cout << Solution().minMalwareSpread(g1, initial1) << endl; + // 0 + + vector> g2 = { + {1,0,0,0,0,0,0,0,0}, + {0,1,0,0,0,0,0,0,0}, + {0,0,1,0,1,0,1,0,0}, + {0,0,0,1,0,0,0,0,0}, + {0,0,1,0,1,0,0,0,0}, + {0,0,0,0,0,1,0,0,0}, + {0,0,1,0,0,0,1,0,0}, + {0,0,0,0,0,0,0,1,0}, + {0,0,0,0,0,0,0,0,1}}; + vector initial2 = {6,0,4}; + cout << Solution().minMalwareSpread(g2, initial2) << endl; + // 0 + + vector> g3 = {{1,1,0},{1,1,1},{0,1,1}}; + vector initial3 = {0,1}; + cout << Solution().minMalwareSpread(g3, initial3) << endl; + // 1 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0928-Minimize-Malware-Spread-II/cpp-0928/main3.cpp b/0501-1000/0928-Minimize-Malware-Spread-II/cpp-0928/main3.cpp new file mode 100644 index 00000000..b62b6af9 --- /dev/null +++ b/0501-1000/0928-Minimize-Malware-Spread-II/cpp-0928/main3.cpp @@ -0,0 +1,135 @@ +/// Source : https://leetcode.com/problems/minimize-malware-spread-ii/ +/// Author : liuyubobobo +/// Time : 2018-10-21 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// Using Union-Find +/// Time Complexity: O(v^2 * a(v)) +/// Space Complexity: O(v) +class UF{ + +private: + vector parent, sz; + +public: + UF(int n){ + parent.clear(); + for(int i = 0 ; i < n ; i ++){ + parent.push_back(i); + sz.push_back(1); + } + } + + int find(int p){ + if( p != parent[p] ) + parent[p] = find( parent[p] ); + return parent[p]; + } + + bool isConnected(int p , int q){ + return find(p) == find(q); + } + + void unionElements(int p, int q){ + + int pRoot = find(p); + int qRoot = find(q); + + if( pRoot == qRoot ) + return; + + parent[pRoot] = qRoot; + sz[qRoot] += sz[pRoot]; + } + + int size(int p){ + return sz[find(p)]; + } +}; + + +class Solution { + +private: + int n; + +public: + int minMalwareSpread(vector>& graph, vector& initial) { + + n = graph.size(); + vector removed(n, false); + for(int v: initial) + removed[v] = true; + + UF uf(n); + for(int i = 0; i < n; i ++) + if(!removed[i]) + for(int j = 0; j < n; j ++) + if(!removed[j] && graph[i][j]) + uf.unionElements(i, j); + + unordered_map> infection; + for(int v: initial) + for(int i = 0; i < n; i ++) + if(!removed[i] && graph[v][i]) + infection[uf.find(i)].insert(v); + + unordered_map effective; + for(const pair>& p: infection) + if(p.second.size() == 1) + effective[*p.second.begin()] += uf.size(p.first); + + int res = *min_element(initial.begin(), initial.end()), best = 0; + for(const pair& p: effective) + if(p.second > best){ + best = p.second; + res = p.first; + } + else if(p.second == best) + res = min(res, p.first); + return res; + } +}; + + +int main() { + + vector> g1 = {{1,1,0,0},{1,1,1,0},{0,1,1,1},{0,0,1,1}}; + vector initial1 = {3,0}; + cout << Solution().minMalwareSpread(g1, initial1) << endl; + // 0 + + vector> g2 = { + {1,0,0,0,0,0,0,0,0}, + {0,1,0,0,0,0,0,0,0}, + {0,0,1,0,1,0,1,0,0}, + {0,0,0,1,0,0,0,0,0}, + {0,0,1,0,1,0,0,0,0}, + {0,0,0,0,0,1,0,0,0}, + {0,0,1,0,0,0,1,0,0}, + {0,0,0,0,0,0,0,1,0}, + {0,0,0,0,0,0,0,0,1}}; + vector initial2 = {6,0,4}; + cout << Solution().minMalwareSpread(g2, initial2) << endl; + // 0 + + vector> g3 = {{1,1,0},{1,1,1},{0,1,1}}; + vector initial3 = {0,1}; + cout << Solution().minMalwareSpread(g3, initial3) << endl; + // 1 + + vector> g4 = {{1,1,0},{1,1,0},{0,0,1}}; + vector initial4 = {0,1}; + cout << Solution().minMalwareSpread(g4, initial4) << endl; + // 0 + + return 0; +} diff --git a/0501-1000/0929-Unique-Email-Addresses/cpp-0929/CMakeLists.txt b/0501-1000/0929-Unique-Email-Addresses/cpp-0929/CMakeLists.txt new file mode 100644 index 00000000..b3fafe13 --- /dev/null +++ b/0501-1000/0929-Unique-Email-Addresses/cpp-0929/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(A) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(A ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0929-Unique-Email-Addresses/cpp-0929/main.cpp b/0501-1000/0929-Unique-Email-Addresses/cpp-0929/main.cpp new file mode 100644 index 00000000..d4e58eb0 --- /dev/null +++ b/0501-1000/0929-Unique-Email-Addresses/cpp-0929/main.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/unique-email-addresses/ +/// Author : liuyubobobo +/// Time : 2018-10-27 + +#include +#include +#include + +using namespace std; + + +/// Using HashSet +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int numUniqueEmails(vector& emails) { + + unordered_set set; + for(const string& email: emails) + set.insert(process(email)); + return set.size(); + } + +private: + string process(const string& email){ + + int at = email.find('@'); + string s = email.substr(0, at); + + int plus = s.find('+'); + if(plus != string::npos) + s = s.substr(0, plus); + + string res = ""; + for(char c: s) + if(c != '.') + res += c; + return res + email.substr(at); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0930-Binary-Subarrays-With-Sum/cpp-0930/CMakeLists.txt b/0501-1000/0930-Binary-Subarrays-With-Sum/cpp-0930/CMakeLists.txt new file mode 100644 index 00000000..45cd0786 --- /dev/null +++ b/0501-1000/0930-Binary-Subarrays-With-Sum/cpp-0930/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(B) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main4.cpp) +add_executable(B ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0930-Binary-Subarrays-With-Sum/cpp-0930/main.cpp b/0501-1000/0930-Binary-Subarrays-With-Sum/cpp-0930/main.cpp new file mode 100644 index 00000000..fa1c9090 --- /dev/null +++ b/0501-1000/0930-Binary-Subarrays-With-Sum/cpp-0930/main.cpp @@ -0,0 +1,61 @@ +/// Source : https://leetcode.com/problems/binary-subarrays-with-sum/ +/// Author : liuyubobobo +/// Time : 2018-10-29 + +#include +#include + +using namespace std; + + +/// Using all 1's index +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int numSubarraysWithSum(vector& A, int S) { + + if(A.size() == 0) + return S == 0; + + vector ones = {-1}; + for(int i = 0; i < A.size(); i ++) + if(A[i] == 1) + ones.push_back(i); + ones.push_back(A.size()); + + int res = 0; + if(S == 0){ + for(int i = 1; i < ones.size(); i ++){ + int n = ones[i] - ones[i - 1] - 1; + res += n + n * (n - 1) / 2; + } + return res; + } + + for(int i = 1; i + S < ones.size(); i ++){ + int l = ones[i] - ones[i - 1]; + int r = ones[i + S] - ones[i + S - 1]; + res += l * r; + } + return res; + } +}; + + +int main() { + + vector A1 = {1,0,1,0,1}; + cout << Solution().numSubarraysWithSum(A1, 2) << endl; + // 4 + + vector A2 = {0,0,0,0,0}; + cout << Solution().numSubarraysWithSum(A2, 0) << endl; + // 15 + + vector A3 = {0,0,0,0,1,0,0,0,0,0,1,1,0,0,0,0,0,1,0,0}; + cout << Solution().numSubarraysWithSum(A3, 3) << endl; + // 48 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0930-Binary-Subarrays-With-Sum/cpp-0930/main2.cpp b/0501-1000/0930-Binary-Subarrays-With-Sum/cpp-0930/main2.cpp new file mode 100644 index 00000000..2b38f844 --- /dev/null +++ b/0501-1000/0930-Binary-Subarrays-With-Sum/cpp-0930/main2.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/binary-subarrays-with-sum/ +/// Author : liuyubobobo +/// Time : 2018-10-29 + +#include +#include +#include + +using namespace std; + + +/// Using PreSum and HashMap +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int numSubarraysWithSum(vector& A, int S) { + + if(A.size() == 0) + return S == 0; + + vector sum(A.size() + 1, 0); + for(int i = 0; i < A.size(); i ++) + sum[i + 1] = A[i] + sum[i]; + + unordered_map freq; // sum, freq + freq[0] ++; + + int res = 0; + for(int i = 0; i < A.size(); i ++){ + res += freq[sum[i + 1] - S]; + freq[sum[i + 1]] ++; + } + return res; + } +}; + + +int main() { + + vector A1 = {1,0,1,0,1}; + cout << Solution().numSubarraysWithSum(A1, 2) << endl; + // 4 + + vector A2 = {0,0,0,0,0}; + cout << Solution().numSubarraysWithSum(A2, 0) << endl; + // 15 + + vector A3 = {0,0,0,0,1,0,0,0,0,0,1,1,0,0,0,0,0,1,0,0}; + cout << Solution().numSubarraysWithSum(A3, 3) << endl; + // 48 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0930-Binary-Subarrays-With-Sum/cpp-0930/main3.cpp b/0501-1000/0930-Binary-Subarrays-With-Sum/cpp-0930/main3.cpp new file mode 100644 index 00000000..e526c6e7 --- /dev/null +++ b/0501-1000/0930-Binary-Subarrays-With-Sum/cpp-0930/main3.cpp @@ -0,0 +1,88 @@ +/// Source : https://leetcode.com/problems/binary-subarrays-with-sum/ +/// Author : liuyubobobo +/// Time : 2018-10-27 + +#include +#include +#include + +using namespace std; + + +/// Two Pointers +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int numSubarraysWithSum(vector& A, int S) { + + if(A.size() == 0) + return S == 0; + + if(S == 0) + return dealZero(A); + + unordered_map nextZero; + int lastOne = -1; + for(int i = 0; i < A.size(); i ++) + if(A[i] == 0 && lastOne >= 0) + nextZero[lastOne] ++; + else if(A[i] == 1) + lastOne = i; + + unordered_map prevZero; + lastOne = -1; + for(int i = A.size() - 1; i >= 0; i --) + if(A[i] == 0 && lastOne >= 0) + prevZero[lastOne] ++; + else if(A[i] == 1) + lastOne = i; + + int l = 0, r = -1, sum = 0, res = 0; + while(l < A.size()){ + if(r + 1 < A.size() && sum < S){ + sum += A[++r]; + } + else + sum -= A[l++]; + + if(sum == S && A[l] && A[r]) + res += (nextZero[r] + 1) * (prevZero[l] + 1); + } + return res; + } + +private: + int dealZero(const vector& A){ + int res = 0, start = 0; + for(int i = start + 1; i <= A.size(); i ++) + if(i == A.size() || A[i] != A[start]){ + if(A[start] == 0){ + int n = i - start; + // cout << "n : " << n << endl; + res += n + n * (n - 1) / 2; + } + start = i; + i = start; + } + return res; + } +}; + + +int main() { + + vector A1 = {1,0,1,0,1}; + cout << Solution().numSubarraysWithSum(A1, 2) << endl; + // 4 + + vector A2 = {0,0,0,0,0}; + cout << Solution().numSubarraysWithSum(A2, 0) << endl; + // 15 + + vector A3 = {0,0,0,0,1,0,0,0,0,0,1,1,0,0,0,0,0,1,0,0}; + cout << Solution().numSubarraysWithSum(A3, 3) << endl; + // 48 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0930-Binary-Subarrays-With-Sum/cpp-0930/main4.cpp b/0501-1000/0930-Binary-Subarrays-With-Sum/cpp-0930/main4.cpp new file mode 100644 index 00000000..f5cafd3b --- /dev/null +++ b/0501-1000/0930-Binary-Subarrays-With-Sum/cpp-0930/main4.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/binary-subarrays-with-sum/ +/// Author : liuyubobobo +/// Time : 2018-10-29 + +#include +#include +#include + +using namespace std; + + +/// Three Pointers +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int numSubarraysWithSum(vector& A, int S) { + + int i_low = 0, i_high = 0; + int sum_low = 0, sum_high = 0; + int res = 0; + for(int j = 0; j < A.size(); j ++){ + sum_low += A[j]; + while(sum_low > S) + sum_low -= A[i_low ++]; + + sum_high += A[j]; + while((sum_high > S || (sum_high == S && A[i_high] == 0)) && i_high < j) + sum_high -= A[i_high ++]; + + if(sum_low == S) + res += (i_high - i_low + 1); + } + return res; + } +}; + + +int main() { + + vector A1 = {1,0,1,0,1}; + cout << Solution().numSubarraysWithSum(A1, 2) << endl; + // 4 + + vector A2 = {0,0,0,0,0}; + cout << Solution().numSubarraysWithSum(A2, 0) << endl; + // 15 + + vector A3 = {0,0,0,0,1,0,0,0,0,0,1,1,0,0,0,0,0,1,0,0}; + cout << Solution().numSubarraysWithSum(A3, 3) << endl; + // 48 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0931-Minimum-Path-Falling-Sum/cpp-0931/CMakeLists.txt b/0501-1000/0931-Minimum-Path-Falling-Sum/cpp-0931/CMakeLists.txt new file mode 100644 index 00000000..85e27b1b --- /dev/null +++ b/0501-1000/0931-Minimum-Path-Falling-Sum/cpp-0931/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(C) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(C ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0931-Minimum-Path-Falling-Sum/cpp-0931/main.cpp b/0501-1000/0931-Minimum-Path-Falling-Sum/cpp-0931/main.cpp new file mode 100644 index 00000000..bb95305e --- /dev/null +++ b/0501-1000/0931-Minimum-Path-Falling-Sum/cpp-0931/main.cpp @@ -0,0 +1,42 @@ +/// Source : https://leetcode.com/problems/minimum-falling-path-sum/ +/// Author : liuyubobobo +/// Time : 2018-10-27 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(m * n) +/// Space Complexity: O(1) +class Solution { +public: + int minFallingPathSum(vector>& A) { + + int m = A.size(); + if(m == 0) return 0; + + int n = A[0].size(); + vector> dp(m, vector(n, INT_MAX)); + + dp[0] = A[0]; + for(int i = 1; i < m; i ++) + for(int j = 0; j < n; j ++) + for(int k = max(j - 1, 0); k <= min(n - 1, j + 1); k ++) + dp[i][j] = min(dp[i][j], dp[i - 1][k] + A[i][j]); + + return *min_element(dp[m - 1].begin(), dp[m - 1].end()); + } +}; + + +int main() { + + vector> A = {{1,2,3},{4,5,6},{7,8,9}}; + cout << Solution().minFallingPathSum(A) << endl; + // 12 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0932-Beautiful-Array/cpp-0932/CMakeLists.txt b/0501-1000/0932-Beautiful-Array/cpp-0932/CMakeLists.txt new file mode 100644 index 00000000..1c3e7bb6 --- /dev/null +++ b/0501-1000/0932-Beautiful-Array/cpp-0932/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(D) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(D ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0932-Beautiful-Array/cpp-0932/main.cpp b/0501-1000/0932-Beautiful-Array/cpp-0932/main.cpp new file mode 100644 index 00000000..9f7f5609 --- /dev/null +++ b/0501-1000/0932-Beautiful-Array/cpp-0932/main.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/beautiful-array/ +/// Author : liuyubobobo +/// Time : 2018-10-30 + +#include +#include +#include + +using namespace std; + + +/// Divide and Conquer +/// The key observation is that {odd number, x, even number} satisfies the property forever! +/// +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + vector beautifulArray(int N) { + + if(N == 0) return {}; + if(N == 1) return {1}; + if(N == 2) return {1, 2}; + + vector res; + int odd = (N + 1) / 2, even = N - odd; + + vector left = beautifulArray(odd); + for(int e: left) + res.push_back(2 * e - 1); + + vector right = beautifulArray(even); + for(int e: right) + res.push_back(2 * e); + + + return res; + } +}; + + +void print_vec(const vector& vec){ + for(int e: vec) + cout << e << " "; + cout << endl; +} + +int main() { + + print_vec(Solution().beautifulArray(5)); + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0933-Number-of-Recent-Calls/cpp-0933/CMakeLists.txt b/0501-1000/0933-Number-of-Recent-Calls/cpp-0933/CMakeLists.txt new file mode 100644 index 00000000..b3fafe13 --- /dev/null +++ b/0501-1000/0933-Number-of-Recent-Calls/cpp-0933/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(A) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(A ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0933-Number-of-Recent-Calls/cpp-0933/main.cpp b/0501-1000/0933-Number-of-Recent-Calls/cpp-0933/main.cpp new file mode 100644 index 00000000..18da7c3b --- /dev/null +++ b/0501-1000/0933-Number-of-Recent-Calls/cpp-0933/main.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/number-of-recent-calls/ +/// Author : liuyubobobo +/// Time : 2018-11-03 + +#include +#include + +using namespace std; + + +/// Using a Queue +/// Time Complexity: O(query) +/// Space Complexity: O(3000) +class RecentCounter { + +private: + queue q; +public: + RecentCounter() { } + + int ping(int t) { + q.push(t); + while(t - 3000 > q.front()) + q.pop(); + return q.size(); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0934-Shortest-Bridge/cpp-0934/CMakeLists.txt b/0501-1000/0934-Shortest-Bridge/cpp-0934/CMakeLists.txt new file mode 100644 index 00000000..10d4db6b --- /dev/null +++ b/0501-1000/0934-Shortest-Bridge/cpp-0934/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(C) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main2.cpp) +add_executable(C ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0934-Shortest-Bridge/cpp-0934/main.cpp b/0501-1000/0934-Shortest-Bridge/cpp-0934/main.cpp new file mode 100644 index 00000000..d4e121c2 --- /dev/null +++ b/0501-1000/0934-Shortest-Bridge/cpp-0934/main.cpp @@ -0,0 +1,108 @@ +/// Source : https://leetcode.com/problems/shortest-bridge/ +/// Author : liuyubobobo +/// Time : 2018-11-03 + +#include +#include +#include + +using namespace std; + + +/// From all the nodes of outer-ring in one component, +/// get the shortest one to the other component, +/// Using BFS +/// +/// Time Complexity: O((m * n)^2) +/// Space Complexity: O(m * n) +class Solution { + +private: + int m, n; + const int d[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; + +public: + int shortestBridge(vector>& A) { + + m = A.size(); + n = A[0].size(); + for(int i = 0; i < m; i ++) + for(int j = 0; j < n; j ++) + if(A[i][j]){ + floodfill(A, i, j); + goto shortest; + } + + shortest: + int res = INT_MAX; + for(int i = 0; i < m; i ++) + for(int j = 0; j < n; j ++) + if(A[i][j] == 3) + res = min(res, bfs(A, i, j)); + return res; + } + +private: + int bfs(const vector>& A, int startx, int starty){ + + queue q; + vector visited(m * n, false); + vector prev(m * n, -1); + + q.push(startx * n + starty); + visited[startx * n + starty] = true; + + int cur; + while(!q.empty()){ + + cur = q.front(); + int curx = cur / n, cury = cur % n; + q.pop(); + + if(A[curx][cury] == 1) + break; + + for(int i = 0; i < 4; i ++){ + int nextx = curx + d[i][0], nexty = cury + d[i][1]; + int next = nextx * n + nexty; + if(inArea(nextx, nexty) && !visited[next]){ + visited[next] = true; + prev[next] = cur; + q.push(next); + } + } + } + + int res = 0; + while(cur != -1){ + if(!A[cur / n][cur % n]) + res ++; + cur = prev[cur]; + } + return res; + } + + void floodfill(vector>& A, int x, int y){ + + A[x][y] = 2; + for(int i = 0; i < 4; i ++){ + int nextx = x + d[i][0], nexty = y + d[i][1]; + if(inArea(nextx, nexty)){ + if(A[nextx][nexty] == 1) + floodfill(A, nextx, nexty); + else if(A[nextx][nexty] == 0) + A[x][y] = 3; // outer-ring point + } + } + } + + bool inArea(int x, int y){ + return x >= 0 && x < m && y >= 0 && y < n; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0934-Shortest-Bridge/cpp-0934/main2.cpp b/0501-1000/0934-Shortest-Bridge/cpp-0934/main2.cpp new file mode 100644 index 00000000..019566ac --- /dev/null +++ b/0501-1000/0934-Shortest-Bridge/cpp-0934/main2.cpp @@ -0,0 +1,107 @@ +/// Source : https://leetcode.com/problems/shortest-bridge/ +/// Author : liuyubobobo +/// Time : 2018-11-03 + +#include +#include +#include +#include + +using namespace std; + + +/// From all the nodes of one component, +/// get the shortest one to the other component, +/// Using BFS +/// We can put all the nodes in one component into the queue :-) +/// +/// Time Complexity: O(m * n) +/// Space Complexity: O(m * n) +class Solution { + +private: + int m, n; + const int d[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; + +public: + int shortestBridge(vector>& A) { + + m = A.size(); + n = A[0].size(); + for(int i = 0; i < m; i ++) + for(int j = 0; j < n; j ++) + if(A[i][j]){ + floodfill(A, i, j); + return bfs(A); + } + + assert(false); + return -1; + } + +private: + int bfs(const vector>& A){ + + queue q; + vector visited(m * n, false); + vector prev(m * n, -1); + + for(int i = 0; i < m; i ++) + for(int j = 0; j < n; j ++) + if(A[i][j] == 2){ + q.push(i * n + j); + visited[i * n + j] = true; + } + + int cur; + while(!q.empty()){ + + cur = q.front(); + int curx = cur / n, cury = cur % n; + q.pop(); + + if(A[curx][cury] == 1) + break; + + for(int i = 0; i < 4; i ++){ + int nextx = curx + d[i][0], nexty = cury + d[i][1]; + int next = nextx * n + nexty; + if(inArea(nextx, nexty) && !visited[next]){ + visited[next] = true; + prev[next] = cur; + q.push(next); + } + } + } + + int res = 0; + while(cur != -1){ + if(!A[cur / n][cur % n]) + res ++; + cur = prev[cur]; + } + return res; + } + + void floodfill(vector>& A, int x, int y){ + + A[x][y] = 2; + for(int i = 0; i < 4; i ++){ + int nextx = x + d[i][0], nexty = y + d[i][1]; + if(inArea(nextx, nexty)){ + if(A[nextx][nexty] == 1) + floodfill(A, nextx, nexty); + } + } + } + + bool inArea(int x, int y){ + return x >= 0 && x < m && y >= 0 && y < n; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0935-Knight-Dialer/cpp-0935/CMakeLists.txt b/0501-1000/0935-Knight-Dialer/cpp-0935/CMakeLists.txt new file mode 100644 index 00000000..0d12d141 --- /dev/null +++ b/0501-1000/0935-Knight-Dialer/cpp-0935/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(B) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main3.cpp) +add_executable(B ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0935-Knight-Dialer/cpp-0935/main.cpp b/0501-1000/0935-Knight-Dialer/cpp-0935/main.cpp new file mode 100644 index 00000000..f11c09ff --- /dev/null +++ b/0501-1000/0935-Knight-Dialer/cpp-0935/main.cpp @@ -0,0 +1,84 @@ +/// Source : https://leetcode.com/problems/knight-dialer/ +/// Author : liuyubobobo +/// Time : 2018-11-03 + +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(10 * N) +/// Space Complexity: O(10 * N) +class Solution { + +private: + int MOD = 1e9 + 7; + const vector> trans = { + {4, 6}, // 0 + {6, 8}, // 1 + {7, 9}, // 2 + {4, 8}, // 3 + {3, 9, 0}, // 4 + {}, // 5 + {1, 7, 0}, // 6 + {2, 6}, // 7 + {1, 3}, // 8 + {2, 4} // 9 + }; + +public: + int knightDialer(int N) { + + if(N == 1) + return 10; + + vector> dp(N, vector(10, -1)); + int res = 0; + for(int i = 0; i < 10; i ++) + if(i != 5){ + res += dfs(i, N - 1, dp); + res %= MOD; + } + return res; + } + +private: + int dfs(int start, int step, vector>& dp){ + + if(step == 0) + return 1; + + if(dp[step][start] != -1) + return dp[step][start]; + + int res = 0; + for(int i = 0; i < trans[start].size(); i ++){ + res += dfs(trans[start][i], step - 1, dp); + res %= MOD; + } + return dp[step][start] = res; + } +}; + + +int main() { + + cout << Solution().knightDialer(1) << endl; + // 10 + + cout << Solution().knightDialer(2) << endl; + // 20 + + cout << Solution().knightDialer(3) << endl; + // 46 + + cout << Solution().knightDialer(4) << endl; + // 104 + + cout << Solution().knightDialer(18) << endl; + // 11208704 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0935-Knight-Dialer/cpp-0935/main2.cpp b/0501-1000/0935-Knight-Dialer/cpp-0935/main2.cpp new file mode 100644 index 00000000..6d157ded --- /dev/null +++ b/0501-1000/0935-Knight-Dialer/cpp-0935/main2.cpp @@ -0,0 +1,70 @@ +/// Source : https://leetcode.com/problems/knight-dialer/ +/// Author : liuyubobobo +/// Time : 2018-11-03 + +#include +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(10 * N) +/// Space Complexity: O(10 * N) +class Solution { + +private: + int MOD = 1e9 + 7; + const vector> trans = { + {4, 6}, // 0 + {6, 8}, // 1 + {7, 9}, // 2 + {4, 8}, // 3 + {3, 9, 0}, // 4 + {}, // 5 + {1, 7, 0}, // 6 + {2, 6}, // 7 + {1, 3}, // 8 + {2, 4} // 9 + }; + +public: + int knightDialer(int N) { + + vector> dp(N, vector(10, 0)); + for(int j = 0; j < 10; j ++) + dp[0][j] = 1; + + for(int i = 1; i < N; i ++) + for(int j = 0; j < 10; j ++) + for(int next: trans[j]) + dp[i][next] = (dp[i][next] + dp[i - 1][j]) % MOD; + + int res = 0; + for(int j = 0; j < 10; j ++) + res = (res + dp[N - 1][j]) % MOD; + return res; + } +}; + + +int main() { + + cout << Solution().knightDialer(1) << endl; + // 10 + + cout << Solution().knightDialer(2) << endl; + // 20 + + cout << Solution().knightDialer(3) << endl; + // 46 + + cout << Solution().knightDialer(4) << endl; + // 104 + + cout << Solution().knightDialer(18) << endl; + // 11208704 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0935-Knight-Dialer/cpp-0935/main3.cpp b/0501-1000/0935-Knight-Dialer/cpp-0935/main3.cpp new file mode 100644 index 00000000..f5862358 --- /dev/null +++ b/0501-1000/0935-Knight-Dialer/cpp-0935/main3.cpp @@ -0,0 +1,77 @@ +/// Source : https://leetcode.com/problems/knight-dialer/ +/// Author : liuyubobobo +/// Time : 2018-11-03 + +#include +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Space Optimized +/// +/// Time Complexity: O(10 * N) +/// Space Complexity: O(2 * 10) +class Solution { + +private: + int MOD = 1e9 + 7; + const vector> trans = { + {4, 6}, // 0 + {6, 8}, // 1 + {7, 9}, // 2 + {4, 8}, // 3 + {3, 9, 0}, // 4 + {}, // 5 + {1, 7, 0}, // 6 + {2, 6}, // 7 + {1, 3}, // 8 + {2, 4} // 9 + }; + +public: + int knightDialer(int N) { + + if(N == 1) + return 10; + + vector> dp(2, vector(10, 0)); + for(int j = 0; j < 10; j ++) + dp[0][j] = 1; + + for(int i = 1; i < N; i ++){ + fill(dp[i & 1].begin(), dp[i & 1].end(), 0); + for(int j = 0; j < 10; j ++) + for(int next: trans[j]) + dp[i & 1][next] = (dp[i & 1][next] + dp[(i - 1) & 1][j]) % MOD; + } + + int res = 0; + for(int j = 0; j < 10; j ++) + res = (res + dp[(N - 1) & 1][j]) % MOD; + return res; + } +}; + + +int main() { + + cout << Solution().knightDialer(1) << endl; + // 10 + + cout << Solution().knightDialer(2) << endl; + // 20 + + cout << Solution().knightDialer(3) << endl; + // 46 + + cout << Solution().knightDialer(4) << endl; + // 104 + + cout << Solution().knightDialer(18) << endl; + // 11208704 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0936-Stamping-The-Sequence/cpp-0936/CMakeLists.txt b/0501-1000/0936-Stamping-The-Sequence/cpp-0936/CMakeLists.txt new file mode 100644 index 00000000..1c3e7bb6 --- /dev/null +++ b/0501-1000/0936-Stamping-The-Sequence/cpp-0936/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(D) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(D ${SOURCE_FILES}) \ No newline at end of file diff --git a/0501-1000/0936-Stamping-The-Sequence/cpp-0936/main.cpp b/0501-1000/0936-Stamping-The-Sequence/cpp-0936/main.cpp new file mode 100644 index 00000000..8b1e2936 --- /dev/null +++ b/0501-1000/0936-Stamping-The-Sequence/cpp-0936/main.cpp @@ -0,0 +1,85 @@ +/// Source : https://leetcode.com/problems/stamping-the-sequence/ +/// Author : liuyubobobo +/// Time : 2018-11-03 + +#include +#include + +using namespace std; + + +/// Reverse Simulation +/// Time Complexity: O(len(target) * len(stamp)) +/// Space Complexity: O(1) +class Solution { +public: + vector movesToStamp(string stamp, string target) { + + if(target.size() < stamp.size()) + return {}; + + if(target.size() == stamp.size()){ + if(stamp == target) + return {0}; + return {}; + } + + vector res; + while(!allQ(target, 0, target.size())){ + + int pos = possibleStamp(target, stamp); + if(pos == -1) + return {}; + + res.push_back(pos); + for(int i = 0; i < stamp.size(); i ++) + target[pos + i] = '?'; + } + reverse(res.begin(), res.end()); + return res; + } + +private: + bool allQ(const string& s, int start, int end){ + for(int i = start; i < end; i ++) + if(s[i] != '?') + return false; + return true; + } + + int possibleStamp(const string& s, const string& stamp){ + + for(int i = 0; i <= s.size() - stamp.size(); i ++) + if(!allQ(s, i, i + stamp.size()) && ok(s, i, stamp)) + return i; + return -1; + } + + bool ok(const string& s, int start, const string& stamp){ + + for(int i = 0; i < stamp.size(); i ++) + if(s[start + i] != '?' && s[start + i] != stamp[i]) + return false; + return true; + } +}; + + +void print_vec(const vector& vec){ + for(int e: vec) + cout << e << " "; + cout << endl; +} + +int main() { + + string stamp1 = "abc", target1 = "ababc"; + print_vec(Solution().movesToStamp(stamp1, target1)); + // [0, 2] + + string stamp2 = "abca", target2 = "aabcaca"; + print_vec(Solution().movesToStamp(stamp2, target2)); + // [3, 0, 1] + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0937-Reorder-Log-File/cpp-0937/CMakeLists.txt b/0501-1000/0937-Reorder-Log-File/cpp-0937/CMakeLists.txt new file mode 100644 index 00000000..52a38668 --- /dev/null +++ b/0501-1000/0937-Reorder-Log-File/cpp-0937/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.12) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main2.cpp) \ No newline at end of file diff --git a/0501-1000/0937-Reorder-Log-File/cpp-0937/main.cpp b/0501-1000/0937-Reorder-Log-File/cpp-0937/main.cpp new file mode 100644 index 00000000..05ee05c2 --- /dev/null +++ b/0501-1000/0937-Reorder-Log-File/cpp-0937/main.cpp @@ -0,0 +1,70 @@ +/// Source : https://leetcode.com/problems/reorder-log-files/ +/// Author : liuyubobobo +/// Time : 2018-11-11 + +#include +#include + +using namespace std; + + +/// Using Custom Class and overloading < operator to sort +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { + +private: + class Log{ + + private: + string s; + int index; + string id; + string after; + bool is_letter; + + public: + Log(const string& log, int index): s(log), index(index){ + + int space = s.find(' '); + id = s.substr(0, space); + after = s.substr(space + 1); + is_letter = isalpha(after[0]); + } + + bool operator<(const Log& another){ + + if(is_letter != another.is_letter) + return is_letter; + + if(is_letter) + return after == another.after ? id < another.id : after < another.after; + return index < another.index; + } + + string get_s() const{ + return s; + } + }; + +public: + vector reorderLogFiles(vector& logs) { + + vector arr; + for(int i = 0; i < logs.size(); i ++) + arr.push_back(Log(logs[i], i)); + + sort(arr.begin(), arr.end()); + + vector res; + for(const Log& e: arr) + res.push_back(e.get_s()); + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0937-Reorder-Log-File/cpp-0937/main2.cpp b/0501-1000/0937-Reorder-Log-File/cpp-0937/main2.cpp new file mode 100644 index 00000000..905b6545 --- /dev/null +++ b/0501-1000/0937-Reorder-Log-File/cpp-0937/main2.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/reorder-log-files/ +/// Author : liuyubobobo +/// Time : 2018-11-10 + +#include +#include + +using namespace std; + + +/// Using Sort and custom compare lambda function +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { + +public: + vector reorderLogFiles(vector& logs) { + + stable_sort(logs.begin(), logs.end(), [](const string& log1, const string& log2) -> bool{ + int space1 = log1.find(' '); + string id1 = log1.substr(0, space1), after1 = log1.substr(space1 + 1); + + int space2 = log2.find(' '); + string id2 = log2.substr(0, space2), after2 = log2.substr(space2 + 1); + + if(isalpha(after1[0]) != isalpha(after2[0])) + return isalpha(after1[0]); + + return isalpha(after1[0]) && + (after1 == after2 ? id1 < id2 : after1 < after2); + }); + return logs; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0938-Range-Sum-of-BST/cpp-0938/CMakeLists.txt b/0501-1000/0938-Range-Sum-of-BST/cpp-0938/CMakeLists.txt new file mode 100644 index 00000000..d2fbf07c --- /dev/null +++ b/0501-1000/0938-Range-Sum-of-BST/cpp-0938/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.12) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp main2.cpp) \ No newline at end of file diff --git a/0501-1000/0938-Range-Sum-of-BST/cpp-0938/main.cpp b/0501-1000/0938-Range-Sum-of-BST/cpp-0938/main.cpp new file mode 100644 index 00000000..be6de922 --- /dev/null +++ b/0501-1000/0938-Range-Sum-of-BST/cpp-0938/main.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/range-sum-of-bst/ +/// Author : liuyubobobo +/// Time : 2018-11-10 + +#include + +using namespace std; + + +/// Recursion +/// Time Complexity: O(n) +/// Space Complexity: O(h) + +/// 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: + int rangeSumBST(TreeNode* root, int L, int R) { + + return sum(root, L, R); + } + +private: + int sum(TreeNode* node, int L, int R){ + + if(!node) + return 0; + + if(node->val < L) + return sum(node->right, L, R); + + if(node->val > R) + return sum(node->left, L, R); + + int res = node->val; + res += sum(node->left, L, node->val - 1); + res += sum(node->right, node->val + 1, R); + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0938-Range-Sum-of-BST/cpp-0938/main2.cpp b/0501-1000/0938-Range-Sum-of-BST/cpp-0938/main2.cpp new file mode 100644 index 00000000..a2b7bbb9 --- /dev/null +++ b/0501-1000/0938-Range-Sum-of-BST/cpp-0938/main2.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/range-sum-of-bst/ +/// Author : liuyubobobo +/// Time : 2018-11-11 + +#include +#include + +using namespace std; + + +/// Non-Recursion, using stack +/// Time Complexity: O(n) +/// Space Complexity: O(h) + +/// 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: + int rangeSumBST(TreeNode* root, int L, int R) { + + int res = 0; + stack stack; + stack.push(root); + while(!stack.empty()){ + TreeNode* cur = stack.top(); + stack.pop(); + + if(!cur) continue; + + if(L <= cur->val && cur->val <= R){ + res += cur->val; + stack.push(cur->right); + stack.push(cur->left); + } + else if(cur->val < L) + stack.push(cur->right); + else + stack.push(cur->left); + } + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0939-Minimum-Area-Rectangle/cpp-0939/CMakeLists.txt b/0501-1000/0939-Minimum-Area-Rectangle/cpp-0939/CMakeLists.txt new file mode 100644 index 00000000..a4186a72 --- /dev/null +++ b/0501-1000/0939-Minimum-Area-Rectangle/cpp-0939/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.12) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main3.cpp) \ No newline at end of file diff --git a/0501-1000/0939-Minimum-Area-Rectangle/cpp-0939/main.cpp b/0501-1000/0939-Minimum-Area-Rectangle/cpp-0939/main.cpp new file mode 100644 index 00000000..0d6c3c75 --- /dev/null +++ b/0501-1000/0939-Minimum-Area-Rectangle/cpp-0939/main.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/minimum-area-rectangle/ +/// Author : liuyubobobo +/// Time : 2018-11-10 + +#include +#include +#include + +using namespace std; + + +/// Using Set to store every point +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { +public: + int minAreaRect(vector>& points) { + + set> set; + for(const vector& point: points) + set.insert(make_pair(point[0], point[1])); + + int min_area = INT_MAX; + for(int i = 0; i < points.size(); i ++) + for(int j = i + 1; j < points.size(); j ++){ + pair p1 = make_pair(points[i][0], points[j][1]); + pair p2 = make_pair(points[j][0], points[i][1]); + if(set.count(p1) && set.count(p2) && + points[i][0] != points[j][0] && points[i][1] != points[j][1]) + min_area = min(min_area, + abs(points[i][0] - points[j][0]) * abs(points[i][1] - points[j][1])); + } + return min_area == INT_MAX ? 0 : min_area; + } +}; + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0939-Minimum-Area-Rectangle/cpp-0939/main2.cpp b/0501-1000/0939-Minimum-Area-Rectangle/cpp-0939/main2.cpp new file mode 100644 index 00000000..90557b4b --- /dev/null +++ b/0501-1000/0939-Minimum-Area-Rectangle/cpp-0939/main2.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/minimum-area-rectangle/ +/// Author : liuyubobobo +/// Time : 2018-11-11 + +#include +#include +#include + +using namespace std; + + +/// Using HashSet to store every point +/// Using Integer to represent evey point +/// +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { + +private: + const int N = 40001; + +public: + int minAreaRect(vector>& points) { + + unordered_set set; + for(const vector& point: points) + set.insert(point[0] * N + point[1]); + + int min_area = INT_MAX; + for(int i = 0; i < points.size(); i ++) + for(int j = i + 1; j < points.size(); j ++){ + int p1 = points[i][0] * N + points[j][1]; + int p2 = points[j][0] * N + points[i][1]; + if(set.count(p1) && set.count(p2) && + points[i][0] != points[j][0] && points[i][1] != points[j][1]) + min_area = min(min_area, + abs(points[i][0] - points[j][0]) * abs(points[i][1] - points[j][1])); + } + return min_area == INT_MAX ? 0 : min_area; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0939-Minimum-Area-Rectangle/cpp-0939/main3.cpp b/0501-1000/0939-Minimum-Area-Rectangle/cpp-0939/main3.cpp new file mode 100644 index 00000000..86941de8 --- /dev/null +++ b/0501-1000/0939-Minimum-Area-Rectangle/cpp-0939/main3.cpp @@ -0,0 +1,55 @@ +/// Source : https://leetcode.com/problems/minimum-area-rectangle/ +/// Author : liuyubobobo +/// Time : 2018-11-12 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// Using TreeMap to store every point in column +/// Using a "code" to record every height of each column +/// Tricky in my opinion :-) +/// +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { + +private: + const int N = 40001; + +public: + int minAreaRect(vector>& points) { + + map> pts; + for(const vector& point: points) + pts[point[0]].push_back(point[1]); + + for(const pair>& col: pts) + sort(pts[col.first].begin(), pts[col.first].end()); + + unordered_map last; // code -> x + int min_area = INT_MAX; + for(const pair>& col: pts){ + + for(int i = 0; i < col.second.size(); i ++) + for(int j = i + 1; j < col.second.size(); j ++){ + int code = col.second[i] * N + col.second[j]; + if(last.count(code)) + min_area = min(min_area, (col.first - last[code]) * abs(col.second[i] - col.second[j])); + last[code] = col.first; + } + } + return min_area == INT_MAX ? 0 : min_area; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0940-Distinct-Subsequences-II/cpp-0940/CMakeLists.txt b/0501-1000/0940-Distinct-Subsequences-II/cpp-0940/CMakeLists.txt new file mode 100644 index 00000000..085ebafc --- /dev/null +++ b/0501-1000/0940-Distinct-Subsequences-II/cpp-0940/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.12) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) \ No newline at end of file diff --git a/0501-1000/0940-Distinct-Subsequences-II/cpp-0940/main.cpp b/0501-1000/0940-Distinct-Subsequences-II/cpp-0940/main.cpp new file mode 100644 index 00000000..e4da463e --- /dev/null +++ b/0501-1000/0940-Distinct-Subsequences-II/cpp-0940/main.cpp @@ -0,0 +1,67 @@ +/// Source : https://leetcode.com/problems/distinct-subsequences-ii/ +/// Author : liuyubobobo +/// Time : 2018-11-12 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +private: + int MOD = 1e9 + 7; + +public: + int distinctSubseqII(string S) { + + int n = S.size(); + vector dp(n + 1, 1), last(26, -1); + + dp[0] = 1; + for(int i = 0; i < n; i ++){ + dp[i + 1] = 2 * dp[i] % MOD; + if(last[S[i] - 'a'] != -1){ + dp[i + 1] -= dp[last[S[i] - 'a']]; + if(dp[i + 1] < 0) + dp[i + 1] += MOD; + } + last[S[i] - 'a'] = i; + } + return dp[n] - 1 < 0 ? MOD - 1 : dp[n] - 1; + } +}; + + +int main() { + + string s1 = "abc"; + cout << Solution().distinctSubseqII(s1) << endl; + // 7 + + string s2 = "aba"; + cout << Solution().distinctSubseqII(s2) << endl; + // 6 + + string s3 = "aaa"; + cout << Solution().distinctSubseqII(s3) << endl; + // 3 + + string s4 = "cdce"; + cout << Solution().distinctSubseqII(s4) << endl; + // 13 + + string s5 = "lee"; + cout << Solution().distinctSubseqII(s5) << endl; + // 5 + + string s6 = "bcbbca"; + cout << Solution().distinctSubseqII(s6) << endl; + // 35 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0941-Valid-Mountain-Array/cpp-0941/CMakeLists.txt b/0501-1000/0941-Valid-Mountain-Array/cpp-0941/CMakeLists.txt new file mode 100644 index 00000000..f0cda401 --- /dev/null +++ b/0501-1000/0941-Valid-Mountain-Array/cpp-0941/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.12) +project(A) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/0501-1000/0941-Valid-Mountain-Array/cpp-0941/main.cpp b/0501-1000/0941-Valid-Mountain-Array/cpp-0941/main.cpp new file mode 100644 index 00000000..aed21d28 --- /dev/null +++ b/0501-1000/0941-Valid-Mountain-Array/cpp-0941/main.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/valid-mountain-array/ +/// Author : liuyubobobo +/// Time : 2018-11-17 + +#include +#include + +using namespace std; + + +/// One Pass +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + bool validMountainArray(vector& A) { + + if(A.size() < 3) + return false; + + int i; + for(i = 1; i < A.size(); i ++) + if(A[i] < A[i - 1]) + break; + else if(A[i] == A[i - 1]) + return false; + + if(i == 1 || i == A.size()) + return false; + + for(int j = i; j < A.size(); j ++) + if(A[j - 1] <= A[j]) + return false; + + return true; + } +}; + + +int main() { + + vector A1 = {0, 3, 2, 1}; + cout << Solution().validMountainArray(A1) << endl; + // true + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0942-DI-String-Match/cpp-0942/CMakeLists.txt b/0501-1000/0942-DI-String-Match/cpp-0942/CMakeLists.txt new file mode 100644 index 00000000..d721d568 --- /dev/null +++ b/0501-1000/0942-DI-String-Match/cpp-0942/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.12) +project(C) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(C main2.cpp) \ No newline at end of file diff --git a/0501-1000/0942-DI-String-Match/cpp-0942/main.cpp b/0501-1000/0942-DI-String-Match/cpp-0942/main.cpp new file mode 100644 index 00000000..9d75ae71 --- /dev/null +++ b/0501-1000/0942-DI-String-Match/cpp-0942/main.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/di-string-match/ +/// Author : liuyubobobo +/// Time : 2018-11-17 + +#include +#include + +using namespace std; + + +/// Generating the result from 0 +/// Adding the offset at last +/// +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + vector diStringMatch(string S) { + + int n = S.size(); + vector res(n + 1, 0); + + int minv = 0, maxv = 0; + for(int i = 0; i < S.size(); i ++){ + int x; + if(S[i] == 'I') + x = ++maxv; + else + x = --minv; + + res[i + 1] = x; + } + + for(int& e: res) + e += -minv; + return res; + } +}; + + +void print_vec(const vector& vec){ + for(int e: vec) + cout << e << " "; + cout << endl; +} + +int main() { + + string S1 = "IDID"; + print_vec(Solution().diStringMatch(S1)); + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0942-DI-String-Match/cpp-0942/main2.cpp b/0501-1000/0942-DI-String-Match/cpp-0942/main2.cpp new file mode 100644 index 00000000..56b82f49 --- /dev/null +++ b/0501-1000/0942-DI-String-Match/cpp-0942/main2.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/di-string-match/ +/// Author : liuyubobobo +/// Time : 2018-11-17 + +#include +#include +#include + +using namespace std; + + +/// Generating the result from min value 0 and max value n - 1 +/// +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + vector diStringMatch(string S) { + + int n = S.size(); + vector res(n + 1, 0); + + int l = 0, h = n; + for(int i = 0; i < S.size(); i ++){ + if(S[i] == 'I') + res[i] = l ++; + else + res[i] = h --; + } + + assert(l == h); + res.back() = l; + return res; + } +}; + + +void print_vec(const vector& vec){ + for(int e: vec) + cout << e << " "; + cout << endl; +} + +int main() { + + string S1 = "IDID"; + print_vec(Solution().diStringMatch(S1)); + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0943-Find-the-Shortest-Superstring/cpp-0943/CMakeLists.txt b/0501-1000/0943-Find-the-Shortest-Superstring/cpp-0943/CMakeLists.txt new file mode 100644 index 00000000..13a2112e --- /dev/null +++ b/0501-1000/0943-Find-the-Shortest-Superstring/cpp-0943/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.12) +project(D) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(D main2.cpp) \ No newline at end of file diff --git a/0501-1000/0943-Find-the-Shortest-Superstring/cpp-0943/main.cpp b/0501-1000/0943-Find-the-Shortest-Superstring/cpp-0943/main.cpp new file mode 100644 index 00000000..c90a843e --- /dev/null +++ b/0501-1000/0943-Find-the-Shortest-Superstring/cpp-0943/main.cpp @@ -0,0 +1,95 @@ +/// Source : https://leetcode.com/problems/find-the-shortest-superstring/ +/// Author : liuyubobobo +/// Time : 2018-11-17 +/// Updated: 2020-04-29 + +#include +#include +#include +#include + +using namespace std; + + +/// Memory Search +/// Pre-calculate overlapped to improve the performance +/// Time Complexity: O(2^n * n * n) +/// Space Complexity: O(2^n * n) +class Solution { + +private: + int n; + +public: + string shortestSuperstring(vector& A) { + + n = A.size(); + vector> dp(n, vector(1 << n, -1)); + + vector> overlaped(n, vector(n, 0)); + for(int i = 0; i < n; i ++) + for(int j = 0; j < n; j ++) + for(int len = min(A[i].size(), A[j].size()); len > 0; len --) + if(A[i].substr(A[i].size() - len, len) == A[j].substr(0, len)){ + overlaped[i][j] = len; + break; + } + + int best = INT_MAX, start; + for(int i = 0; i < n; i ++){ + int tres = dfs(A, 1 << i, i, overlaped, dp); + if(tres < best) best = tres, start = i; + } + + int state = (1 << start), cur = start; + string res = A[start]; + while(state != ((1 << n) - 1)){ + for(int i = 0; i < n; i ++) + if(i != cur && ((1 << i) & state) == 0 && + dp[cur][state] == A[cur].size() + dp[i][state + (1 << i)] - overlaped[cur][i]){ + res += A[i].substr(overlaped[cur][i]); + state += (1 << i); + cur = i; + break; + } + } + return res; + } + +private: + int dfs(const vector& A, int state, int index, + const vector>& overlapped, vector>& dp){ + + if(dp[index][state] != -1) return dp[index][state]; + if(state == (1 << n) - 1) return dp[index][state] = A[index].size(); + + int res = INT_MAX; + for(int i = 0; i < n; i ++) + if((state & (1 << i)) == 0){ + int tres = A[index].size() + dfs(A, state | (1 << i), i, overlapped, dp) - overlapped[index][i]; + res = min(res, tres); + } + return dp[index][state] = res; + } +}; + + +int main() { + + vector A1 = {"alex","loves","leetcode"}; + string res1 = Solution().shortestSuperstring(A1); + cout << res1 << endl; + // "alexlovesleetcode"; + + vector A2 = {"wmiy","yarn","rnnwc","arnnw","wcj"}; + string res2 = Solution().shortestSuperstring(A2); + cout << res2 << endl; + // "wmiyarnnwcj"; + + vector A3 = {"chakgmeinq","lhdbntkf","mhkelhye","hdbntkfch","kfchakgme","wymhkelh","kgmeinqw"}; + string res3 = Solution().shortestSuperstring(A3); + cout << res3 << endl; + // "lhdbntkfchakgmeinqwymhkelhye"; + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0943-Find-the-Shortest-Superstring/cpp-0943/main2.cpp b/0501-1000/0943-Find-the-Shortest-Superstring/cpp-0943/main2.cpp new file mode 100644 index 00000000..1b22b94b --- /dev/null +++ b/0501-1000/0943-Find-the-Shortest-Superstring/cpp-0943/main2.cpp @@ -0,0 +1,95 @@ +/// Source : https://leetcode.com/problems/find-the-shortest-superstring/ +/// Author : liuyubobobo +/// Time : 2020-04-28 + +#include +#include +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(2^n * n * n) +/// Space Complexity: O(2^n * n) +class Solution { + +public: + string shortestSuperstring(vector& A) { + + int n = A.size(); + if(n == 1) return A[0]; + + vector> overlaped(n, vector(n, 0)); + for(int i = 0; i < n; i ++) + for(int j = 0; j < n; j ++) + for(int len = min(A[i].size(), A[j].size()); len > 0; len --) + if(A[i].substr(A[i].size() - len, len) == A[j].substr(0, len)){ + overlaped[i][j] = len; + break; + } + + vector> dp(n, vector(1 << n, -1)); + string res = ""; + for(int start = 0; start < n; start ++){ + dp[start][1 << start] = A[start].size(); + for(int state = 1; state < (1 << n); state ++) + for(int i = 0; i < n; i ++){ + if(dp[i][state] != -1){ + for(int j = 0; j < n; j ++) + if(((1 << j) & state) == 0){ + int t = dp[i][state] + A[j].size() - overlaped[i][j]; + if(dp[j][(1 << j) | state] == -1) + dp[j][(1 << j) | state] = t; + else if(t < dp[j][(1 << j) | state]) + dp[j][(1 << j) | state] = t; + } + } + } + + int tlen = INT_MAX, tend; + for(int end = 0; end < n; end ++) + if(end != start && dp[end][(1 << n) - 1] < tlen) + tlen = dp[end][(1 << n) - 1], tend = end; + + int state = (1 << n) - 1, cur = tend; + string tres = A[tend]; + while(true){ + if(state - (1 << cur) == 0) break; + for(int i = 0; i < n; i ++) + if(i != cur && ((1 << i) & state) && + dp[cur][state] == dp[i][state - (1 << cur)] + A[cur].size() - overlaped[i][cur]){ + tres = A[i] + tres.substr(overlaped[i][cur]); + state -= (1 << cur); + cur = i; + break; + } + } + + if(res == "" || tres.size() < res.size()) res = tres; + } + return res; + } +}; + + +int main() { + + vector A1 = {"alex","loves","leetcode"}; + string res1 = Solution().shortestSuperstring(A1); + cout << res1 << endl; + // "alexlovesleetcode"; + + vector A2 = {"wmiy","yarn","rnnwc","arnnw","wcj"}; + string res2 = Solution().shortestSuperstring(A2); + cout << res2 << endl; + // "wmiyarnnwcj"; + + vector A3 = {"chakgmeinq","lhdbntkf","mhkelhye","hdbntkfch","kfchakgme","wymhkelh","kgmeinqw"}; + string res3 = Solution().shortestSuperstring(A3); + cout << res3 << endl; + // "lhdbntkfchakgmeinqwymhkelhye"; + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0944-Delete-Columns-to-Make-Sorted/cpp-0944/CMakeLists.txt b/0501-1000/0944-Delete-Columns-to-Make-Sorted/cpp-0944/CMakeLists.txt new file mode 100644 index 00000000..9a9ee22f --- /dev/null +++ b/0501-1000/0944-Delete-Columns-to-Make-Sorted/cpp-0944/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.12) +project(B) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/0501-1000/0944-Delete-Columns-to-Make-Sorted/cpp-0944/main.cpp b/0501-1000/0944-Delete-Columns-to-Make-Sorted/cpp-0944/main.cpp new file mode 100644 index 00000000..e4fc41e6 --- /dev/null +++ b/0501-1000/0944-Delete-Columns-to-Make-Sorted/cpp-0944/main.cpp @@ -0,0 +1,41 @@ +/// Source : https://leetcode.com/problems/delete-columns-to-make-sorted/ +/// Author : liuyubobobo +/// Time : 2018-11-17 + +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(m * n) +/// Space Complexity: O(1) +class Solution { +public: + int minDeletionSize(vector& A) { + + int m = A.size(); + if(m == 0 || m == 1) return 0; + + int n = A[0].size(); + if(n == 0) return 0; + + int res = 0; + for(int j = 0; j < n; j ++){ + + for(int i = 1; i < m; i ++) + if(A[i][j] < A[i - 1][j]){ + res ++; + break; + } + } + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0945-Minimum-Increment-to-Make-Array-Unique/cpp-0945/CMakeLists.txt b/0501-1000/0945-Minimum-Increment-to-Make-Array-Unique/cpp-0945/CMakeLists.txt new file mode 100644 index 00000000..44a5c369 --- /dev/null +++ b/0501-1000/0945-Minimum-Increment-to-Make-Array-Unique/cpp-0945/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.12) +project(A) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(A main3.cpp) \ No newline at end of file diff --git a/0501-1000/0945-Minimum-Increment-to-Make-Array-Unique/cpp-0945/main.cpp b/0501-1000/0945-Minimum-Increment-to-Make-Array-Unique/cpp-0945/main.cpp new file mode 100644 index 00000000..75e22431 --- /dev/null +++ b/0501-1000/0945-Minimum-Increment-to-Make-Array-Unique/cpp-0945/main.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/minimum-increment-to-make-array-unique/ +/// Author : liuyubobobo +/// Time : 2018-11-24 + +#include +#include + +using namespace std; + + +/// Using sort and change the A array +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + int minIncrementForUnique(vector& A) { + + sort(A.begin(), A.end()); + int res = 0; + for(int i = 1; i < A.size(); i ++) + if(A[i] == A[i - 1]){ + res += (A[i - 1] + 1 - A[i]); + A[i] = A[i - 1] + 1; + } + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0945-Minimum-Increment-to-Make-Array-Unique/cpp-0945/main2.cpp b/0501-1000/0945-Minimum-Increment-to-Make-Array-Unique/cpp-0945/main2.cpp new file mode 100644 index 00000000..4eff6e7b --- /dev/null +++ b/0501-1000/0945-Minimum-Increment-to-Make-Array-Unique/cpp-0945/main2.cpp @@ -0,0 +1,44 @@ +/// Source : https://leetcode.com/problems/minimum-increment-to-make-array-unique/ +/// Author : liuyubobobo +/// Time : 2018-11-25 + +#include +#include + +using namespace std; + + +/// Using sort and don't change the A array +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + int minIncrementForUnique(vector& A) { + + if(A.size() == 0) + return 0; + + sort(A.begin(), A.end()); + int res = 0, left = 0; + for(int i = 1; i < A.size(); i ++) + if(A[i] == A[i - 1]){ + left ++; + res -= A[i]; + } + else{ + int seg = min(left, A[i] - A[i - 1] - 1); + res += (A[i - 1] + 1 + A[i - 1] + seg) * seg / 2; + left -= seg; + } + + if(left) + res += (A.back() + 1 + A.back() + left) * left / 2; + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0945-Minimum-Increment-to-Make-Array-Unique/cpp-0945/main3.cpp b/0501-1000/0945-Minimum-Increment-to-Make-Array-Unique/cpp-0945/main3.cpp new file mode 100644 index 00000000..69f04a1c --- /dev/null +++ b/0501-1000/0945-Minimum-Increment-to-Make-Array-Unique/cpp-0945/main3.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/minimum-increment-to-make-array-unique/ +/// Author : liuyubobobo +/// Time : 2018-11-25 + +#include +#include + +using namespace std; + + +/// Using an array hashtable to record duplicate elements +/// Time Complexity: O(max number) +/// Space Complexity: O(max number) +class Solution { + +private: + const int MAX_NUM = 40000; + +public: + int minIncrementForUnique(vector& A) { + + vector freq(MAX_NUM + 1, 0); + for(int a: A) + freq[a] ++; + + int res = 0, left = 0; + for(int i = 0; i <= MAX_NUM; i ++) + if(freq[i] >= 2){ + res -= (freq[i] - 1) * i; + left += freq[i] - 1; + } + else if(freq[i] == 0 && left){ + res += i; + left --; + } + + for(int i = 1; i <= left; i ++) + res += (MAX_NUM + i); + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0946-Validate-Stack-Sequences/cpp-0946/CMakeLists.txt b/0501-1000/0946-Validate-Stack-Sequences/cpp-0946/CMakeLists.txt new file mode 100644 index 00000000..c10f124d --- /dev/null +++ b/0501-1000/0946-Validate-Stack-Sequences/cpp-0946/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.12) +project(B) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(B main2.cpp) \ No newline at end of file diff --git a/0501-1000/0946-Validate-Stack-Sequences/cpp-0946/main.cpp b/0501-1000/0946-Validate-Stack-Sequences/cpp-0946/main.cpp new file mode 100644 index 00000000..d571c444 --- /dev/null +++ b/0501-1000/0946-Validate-Stack-Sequences/cpp-0946/main.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/validate-stack-sequences/ +/// Author : liuyubobobo +/// Time : 2018-11-24 + +#include +#include +#include +#include + +using namespace std; + + +/// Using a stack to simulation +/// and using a HashSet to record every elements +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + bool validateStackSequences(vector& pushed, vector& popped) { + + unordered_set set; + stack stack; + int i = 0; + for(int e: pushed){ + stack.push(e); + set.insert(e); + + while(i < popped.size() && !stack.empty() && popped[i] == stack.top()){ + stack.pop(); + set.erase(e); + i ++; + } + + if(i < popped.size() && !stack.empty() + && popped[i] != stack.top() && set.count(popped[i])) + return false; + } + return stack.empty(); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0946-Validate-Stack-Sequences/cpp-0946/main2.cpp b/0501-1000/0946-Validate-Stack-Sequences/cpp-0946/main2.cpp new file mode 100644 index 00000000..df8b609b --- /dev/null +++ b/0501-1000/0946-Validate-Stack-Sequences/cpp-0946/main2.cpp @@ -0,0 +1,38 @@ +/// Source : https://leetcode.com/problems/validate-stack-sequences/ +/// Author : liuyubobobo +/// Time : 2018-11-25 + +#include +#include +#include +#include + +using namespace std; + + +/// Using a stack to simulation +/// Greedy Thinking is used when deal with popped elements +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + bool validateStackSequences(vector& pushed, vector& popped) { + + stack stack; + int i = 0; + for(int e: pushed){ + stack.push(e); + while(i < popped.size() && !stack.empty() && popped[i] == stack.top()){ + stack.pop(); + i ++; + } + } + return i == popped.size(); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0947-Most-Stones-Removed-with-Same-Row-or-Column/cpp-0947/CMakeLists.txt b/0501-1000/0947-Most-Stones-Removed-with-Same-Row-or-Column/cpp-0947/CMakeLists.txt new file mode 100644 index 00000000..d721d568 --- /dev/null +++ b/0501-1000/0947-Most-Stones-Removed-with-Same-Row-or-Column/cpp-0947/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.12) +project(C) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(C main2.cpp) \ No newline at end of file diff --git a/0501-1000/0947-Most-Stones-Removed-with-Same-Row-or-Column/cpp-0947/main.cpp b/0501-1000/0947-Most-Stones-Removed-with-Same-Row-or-Column/cpp-0947/main.cpp new file mode 100644 index 00000000..ca80bb7a --- /dev/null +++ b/0501-1000/0947-Most-Stones-Removed-with-Same-Row-or-Column/cpp-0947/main.cpp @@ -0,0 +1,65 @@ +/// Source : https://leetcode.com/problems/most-stones-removed-with-same-row-or-column/ +/// Author : liuyubobobo +/// Time : 2018-11-25 + +#include +#include +#include + +using namespace std; + + +/// Using DFS to calculate connected components +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int removeStones(vector>& stones) { + + int n = stones.size(); + vector> g(n); + for(int i = 0; i < n; i ++) + for(int j = i + 1; j < n; j ++) + if(stones[i][0] == stones[j][0] || stones[i][1] == stones[j][1]){ + g[i].insert(j); + g[j].insert(i); + } + + int res = 0; + vector visited(n, false); + for(int i = 0; i < n; i ++) + if(!visited[i]) + res += dfs(g, i, visited) - 1; + + return res; + } + +private: + int dfs(const vector> &g, int v, vector &visited){ + + visited[v] = true; + int res = 1; + for(int next: g[v]) + if(!visited[next]) + res += dfs(g, next, visited); + return res; + } +}; + + +int main() { + + vector> stones1 = {{0,0},{0,1},{1,0},{1,2},{2,1},{2,2}}; + cout << Solution().removeStones(stones1) << endl; + // 5 + + vector> stones2 = {{0,0},{0,2},{1,1},{2,0},{2,2}}; + cout << Solution().removeStones(stones2) << endl; + // 3 + + vector> stones3 = {{0,0}}; + cout << Solution().removeStones(stones3) << endl; + // 0 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0947-Most-Stones-Removed-with-Same-Row-or-Column/cpp-0947/main2.cpp b/0501-1000/0947-Most-Stones-Removed-with-Same-Row-or-Column/cpp-0947/main2.cpp new file mode 100644 index 00000000..53836356 --- /dev/null +++ b/0501-1000/0947-Most-Stones-Removed-with-Same-Row-or-Column/cpp-0947/main2.cpp @@ -0,0 +1,94 @@ +/// Source : https://leetcode.com/problems/most-stones-removed-with-same-row-or-column/ +/// Author : liuyubobobo +/// Time : 2018-11-25 + +#include +#include +#include + +using namespace std; + + +/// Using Union-Find to calculate connected components +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class UF{ + +private: + vector parent, sz; + +public: + UF(int n): sz(n, 1){ + for(int i = 0 ; i < n ; i ++) + parent.push_back(i); + } + + int find(int p){ + if(p != parent[p]) + parent[p] = find(parent[p]); + return parent[p]; + } + + bool isConnected(int p , int q){ + return find(p) == find(q); + } + + void unionElements(int p, int q){ + + int pRoot = find(p); + int qRoot = find(q); + + if( pRoot == qRoot ) + return; + + parent[pRoot] = qRoot; + sz[qRoot] += sz[pRoot]; + } + + int size(int p){ + return sz[find(p)]; + } +}; + +class Solution { +public: + int removeStones(vector>& stones) { + + int n = stones.size(); + UF uf(n); + for(int i = 0; i < n; i ++) + for(int j = i + 1; j < n; j ++) + if(stones[i][0] == stones[j][0] || stones[i][1] == stones[j][1]) + uf.unionElements(i, j); + + int res = 0; + unordered_set groups; + for(int i = 0; i < n; i ++){ + int group = uf.find(i); + if(!groups.count(group)){ + res += uf.size(i) - 1; + groups.insert(group); + } + } + + return res; + } +}; + + +int main() { + + vector> stones1 = {{0,0},{0,1},{1,0},{1,2},{2,1},{2,2}}; + cout << Solution().removeStones(stones1) << endl; + // 5 + + vector> stones2 = {{0,0},{0,2},{1,1},{2,0},{2,2}}; + cout << Solution().removeStones(stones2) << endl; + // 3 + + vector> stones3 = {{0,0}}; + cout << Solution().removeStones(stones3) << endl; + // 0 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0948-Bag-of-Tokens/cpp-0948/CMakeLists.txt b/0501-1000/0948-Bag-of-Tokens/cpp-0948/CMakeLists.txt new file mode 100644 index 00000000..b1bd6b17 --- /dev/null +++ b/0501-1000/0948-Bag-of-Tokens/cpp-0948/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.12) +project(D) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(D main.cpp) \ No newline at end of file diff --git a/0501-1000/0948-Bag-of-Tokens/cpp-0948/main.cpp b/0501-1000/0948-Bag-of-Tokens/cpp-0948/main.cpp new file mode 100644 index 00000000..d035b92c --- /dev/null +++ b/0501-1000/0948-Bag-of-Tokens/cpp-0948/main.cpp @@ -0,0 +1,65 @@ +/// Source : https://leetcode.com/problems/bag-of-tokens/ +/// Author : liuyubobobo +/// Time : 2018-11-25 + +#include +#include + +using namespace std; + + +/// Greedy Simulation +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { + +public: + int bagOfTokensScore(vector& tokens, int P) { + + if(tokens.size() == 0) + return 0; + + sort(tokens.begin(), tokens.end()); + int res = 0, l = 0, r = tokens.size() - 1; + while(true){ + if(P >= tokens[l]){ + P -= tokens[l++]; + res ++; + } + else { + if (l < r && res) { + P += tokens[r--]; + res--; + } + else if (l == r || !res) + break; + } + + if(l > r) + break; + } + return res; + } +}; + + +int main() { + + vector tokens1 = {100}; + cout << Solution().bagOfTokensScore(tokens1, 50) << endl; + // 0 + + vector tokens2 = {100, 200}; + cout << Solution().bagOfTokensScore(tokens2, 150) << endl; + // 1 + + vector tokens3 = {100, 200, 300, 400}; + cout << Solution().bagOfTokensScore(tokens3, 200) << endl; + // 2 + + vector tokens4 = {71, 55, 82}; + cout << Solution().bagOfTokensScore(tokens4, 54) << endl; + // 0 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0949-Largest-Time-for-Given-Digits/cpp-0949/CMakeLists.txt b/0501-1000/0949-Largest-Time-for-Given-Digits/cpp-0949/CMakeLists.txt new file mode 100644 index 00000000..f0cda401 --- /dev/null +++ b/0501-1000/0949-Largest-Time-for-Given-Digits/cpp-0949/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.12) +project(A) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/0501-1000/0949-Largest-Time-for-Given-Digits/cpp-0949/main.cpp b/0501-1000/0949-Largest-Time-for-Given-Digits/cpp-0949/main.cpp new file mode 100644 index 00000000..39ad1ef6 --- /dev/null +++ b/0501-1000/0949-Largest-Time-for-Given-Digits/cpp-0949/main.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/largest-time-for-given-digits/ +/// Author : liuyubobobo +/// Time : 2018-12-01 + +#include +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(4!) +/// Space Complexity: O(1) +class Solution { +public: + string largestTimeFromDigits(vector& A) { + + sort(A.begin(), A.end()); + string res = ""; + do{ + if(ok(A)) + res = to_string(A[0]) + to_string(A[1]) + ":" + to_string(A[2]) + to_string(A[3]); + }while(next_permutation(A.begin(), A.end())); + return res; + } + +private: + bool ok(const vector& A){ + int h = A[0] * 10 + A[1]; + int m = A[2] * 10 + A[2]; + return h <= 23 && m <= 59; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0950-Reveal-Cards-In-Increasing-Order/cpp-0950/CMakeLists.txt b/0501-1000/0950-Reveal-Cards-In-Increasing-Order/cpp-0950/CMakeLists.txt new file mode 100644 index 00000000..4edcf090 --- /dev/null +++ b/0501-1000/0950-Reveal-Cards-In-Increasing-Order/cpp-0950/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.12) +project(C) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/0501-1000/0950-Reveal-Cards-In-Increasing-Order/cpp-0950/main.cpp b/0501-1000/0950-Reveal-Cards-In-Increasing-Order/cpp-0950/main.cpp new file mode 100644 index 00000000..67ccbb75 --- /dev/null +++ b/0501-1000/0950-Reveal-Cards-In-Increasing-Order/cpp-0950/main.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/reveal-cards-in-increasing-order/ +/// Author : liuyubobobo +/// Time : 2018-12-01 + +#include +#include +#include + +using namespace std; + + +/// Simulation with deque +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + vector deckRevealedIncreasing(vector& deck) { + + sort(deck.begin(), deck.end(), greater()); + + deque deque; + deque.push_back(deck[0]); + for(int i = 1; i < deck.size(); i ++){ + int back = deque.back(); + deque.pop_back(); + deque.push_front(back); + deque.push_front(deck[i]); + } + + return vector(deque.begin(), deque.end()); + } +}; + + +void print_vec(const vector& vec){ + for(int e: vec) + cout << e << " "; + cout << endl; +} + +int main() { + + vector deck1 = {17, 13, 11, 2, 3, 5, 7}; + print_vec(Solution().deckRevealedIncreasing(deck1)); + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0951-Flip-Equivalent-Binary-Trees/cpp-0951/CMakeLists.txt b/0501-1000/0951-Flip-Equivalent-Binary-Trees/cpp-0951/CMakeLists.txt new file mode 100644 index 00000000..c10f124d --- /dev/null +++ b/0501-1000/0951-Flip-Equivalent-Binary-Trees/cpp-0951/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.12) +project(B) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(B main2.cpp) \ No newline at end of file diff --git a/0501-1000/0951-Flip-Equivalent-Binary-Trees/cpp-0951/main.cpp b/0501-1000/0951-Flip-Equivalent-Binary-Trees/cpp-0951/main.cpp new file mode 100644 index 00000000..66d6eb79 --- /dev/null +++ b/0501-1000/0951-Flip-Equivalent-Binary-Trees/cpp-0951/main.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/flip-equivalent-binary-trees/ +/// Author : liuyubobobo +/// Time : 2018-12-01 + +#include + +using namespace std; + + +/// Recursion +/// Time Complexity: O(min(N1, N2)) +/// Space Complexity: O(min(h1, h2)) + +/// 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: + bool flipEquiv(TreeNode* root1, TreeNode* root2) { + + return check(root1, root2); + } + +private: + bool check(TreeNode* node1, TreeNode* node2){ + + if(!node1 && !node2) + return true; + + if(!node1 || !node2) + return false; + + if(node1->val != node2->val) + return false; + + return (check(node1->left, node2->left) && check(node1->right, node2->right)) || + (check(node1->right, node2->left) && check(node1->left, node2->right)); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0951-Flip-Equivalent-Binary-Trees/cpp-0951/main2.cpp b/0501-1000/0951-Flip-Equivalent-Binary-Trees/cpp-0951/main2.cpp new file mode 100644 index 00000000..62822eb6 --- /dev/null +++ b/0501-1000/0951-Flip-Equivalent-Binary-Trees/cpp-0951/main2.cpp @@ -0,0 +1,65 @@ +/// Source : https://leetcode.com/problems/flip-equivalent-binary-trees/ +/// Author : liuyubobobo +/// Time : 2018-12-01 + +#include +#include + +using namespace std; + + +/// Canonical Traversal +/// Time Complexity: O(N1 + N2) +/// Space Complexity: O(N1 + N2) + +/// 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: + bool flipEquiv(TreeNode* root1, TreeNode* root2) { + + vector vec1, vec2; + + dfs(root1, vec1); +// for(TreeNode* node: vec1) +// cout << (node ? node->val : -1) << " "; +// cout << endl; + + dfs(root2, vec2); +// for(TreeNode* node: vec2) +// cout << (node ? node->val : -1) << " "; +// cout << endl; + + return vec1 == vec2; + } + +private: + void dfs(TreeNode* node, vector& vec){ + + vec.push_back(node ? node->val : -1); + if(!node) + return; + + int L = node->left ? node->left->val : -1; + int R = node->right ? node->right->val : -1; + if(L <= R) + dfs(node->left, vec), dfs(node->right, vec); + else + dfs(node->right, vec), dfs(node->left, vec); + } +}; + + +int main() { + + cout << Solution().flipEquiv(NULL, new TreeNode(1)) << endl; + // False + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0952-Largest-Component-Size-by-Common-Factor/cpp-0952/CMakeLists.txt b/0501-1000/0952-Largest-Component-Size-by-Common-Factor/cpp-0952/CMakeLists.txt new file mode 100644 index 00000000..b1bd6b17 --- /dev/null +++ b/0501-1000/0952-Largest-Component-Size-by-Common-Factor/cpp-0952/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.12) +project(D) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(D main.cpp) \ No newline at end of file diff --git a/0501-1000/0952-Largest-Component-Size-by-Common-Factor/cpp-0952/main.cpp b/0501-1000/0952-Largest-Component-Size-by-Common-Factor/cpp-0952/main.cpp new file mode 100644 index 00000000..01199b5a --- /dev/null +++ b/0501-1000/0952-Largest-Component-Size-by-Common-Factor/cpp-0952/main.cpp @@ -0,0 +1,99 @@ +/// Source : https://leetcode.com/problems/largest-component-size-by-common-factor/ +/// Author : liuyubobobo +/// Time : 2018-12-01 + +#include +#include +#include +#include + +using namespace std; + + +/// Using Union Find +/// Time Complexity: O(n * sqrt(max_number)) +/// Space Complexity: O(n * sqrt(max_number)) + +class UF{ + +private: + vector parent, sz; + +public: + UF(int n){ + for(int i = 0 ; i < n ; i ++){ + parent.push_back(i); + sz.push_back(1); + } + } + + int find(int p){ + if( p != parent[p] ) + parent[p] = find( parent[p] ); + return parent[p]; + } + + bool isConnected(int p , int q){ + return find(p) == find(q); + } + + void unionElements(int p, int q){ + + int pRoot = find(p); + int qRoot = find(q); + + if( pRoot == qRoot ) + return; + + parent[pRoot] = qRoot; + sz[qRoot] += sz[pRoot]; + } + + int size(int p){ + return sz[find(p)]; + } +}; + +class Solution { + +public: + int largestComponentSize(vector& A) { + + unordered_map map; // a -> index + for(int i = 0; i < A.size(); i ++) + map[A[i]] = i; + + unordered_map> factors; + UF uf(A.size()); + for(int a: A) + for(int i = 1; i * i <= a; i ++) + if(a % i == 0){ + if(i != 1) { + if (!factors[i].empty()) + uf.unionElements(map[a], map[factors[i][0]]); + factors[i].push_back(a); + } + if(i * i < a){ + int j = a / i; + if(!factors[j].empty()) + uf.unionElements(map[a], map[factors[j][0]]); + factors[j].push_back(a); + } + } + + int res = 0; + for(int a: A) + res = max(res, uf.size(map[a])); + return res; + } +}; + + +int main() { + + vector A = {2,3,6,7,4,12,21,39}; + cout << Solution().largestComponentSize(A) << endl; + // 8 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0953-Verifying-an-Alien-Dictionary/cpp-0953/CMakeLists.txt b/0501-1000/0953-Verifying-an-Alien-Dictionary/cpp-0953/CMakeLists.txt new file mode 100644 index 00000000..88857baf --- /dev/null +++ b/0501-1000/0953-Verifying-an-Alien-Dictionary/cpp-0953/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(A) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/0501-1000/0953-Verifying-an-Alien-Dictionary/cpp-0953/main.cpp b/0501-1000/0953-Verifying-an-Alien-Dictionary/cpp-0953/main.cpp new file mode 100644 index 00000000..92442fb8 --- /dev/null +++ b/0501-1000/0953-Verifying-an-Alien-Dictionary/cpp-0953/main.cpp @@ -0,0 +1,38 @@ +/// Source : https://leetcode.com/problems/verifying-an-alien-dictionary/ +/// Author : liuyubobobo +/// Time : 2018-12-08 + +#include +#include +#include + +using namespace std; + + +/// Transform and Compare +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + bool isAlienSorted(vector& words, string order) { + + unordered_map map; + for(int i = 0; i < order.size(); i ++) + map[order[i]] = 'a' + i; + + for(string&word: words) + for(char& c: word) + c = map[c]; + + for(int i = 1; i < words.size(); i ++) + if(words[i - 1] > words[i]) + return false; + return true; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0954-canReorderDoubled/cpp-0954/CMakeLists.txt b/0501-1000/0954-canReorderDoubled/cpp-0954/CMakeLists.txt new file mode 100644 index 00000000..8a0a1cc7 --- /dev/null +++ b/0501-1000/0954-canReorderDoubled/cpp-0954/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(B) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/0501-1000/0954-canReorderDoubled/cpp-0954/main.cpp b/0501-1000/0954-canReorderDoubled/cpp-0954/main.cpp new file mode 100644 index 00000000..93acfc12 --- /dev/null +++ b/0501-1000/0954-canReorderDoubled/cpp-0954/main.cpp @@ -0,0 +1,49 @@ +/// Source : https://leetcode.com/problems/array-of-doubled-pairs/ +/// Author : liuyubobobo +/// Time : 2018-12-12 + +#include +#include +#include + +using namespace std; + + +/// Greedy, from large absolute value to small absolute value +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + bool canReorderDoubled(vector& A) { + + unordered_map freq; + for(int a: A) + freq[a] ++; + + sort(A.begin(), A.end(), [](int a, int b){return abs(a) < abs(b);}); +// for(int a: A) +// cout << a << " "; +// cout << endl; + + for(int a: A){ + if(freq[a]){ + if(!freq[2 * a]) + return false; + freq[a] --; + if(!freq[2 * a]) + return false; + freq[2 * a] --; + } + } + return true; + } +}; + + +int main() { + + vector A1 = {4, -2, 2, -4}; + cout << Solution().canReorderDoubled(A1) << endl; + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0955-Delete-Columns-to-Make-Sorted-II/cpp-0955/CMakeLists.txt b/0501-1000/0955-Delete-Columns-to-Make-Sorted-II/cpp-0955/CMakeLists.txt new file mode 100644 index 00000000..c8cc528c --- /dev/null +++ b/0501-1000/0955-Delete-Columns-to-Make-Sorted-II/cpp-0955/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(C) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(C main2.cpp) \ No newline at end of file diff --git a/0501-1000/0955-Delete-Columns-to-Make-Sorted-II/cpp-0955/main.cpp b/0501-1000/0955-Delete-Columns-to-Make-Sorted-II/cpp-0955/main.cpp new file mode 100644 index 00000000..e29554cf --- /dev/null +++ b/0501-1000/0955-Delete-Columns-to-Make-Sorted-II/cpp-0955/main.cpp @@ -0,0 +1,69 @@ +/// Source : https://leetcode.com/problems/delete-columns-to-make-sorted-ii/ +/// Author : liuyubobobo +/// Time : 2018-12-12 + +#include +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(m * m * n) +/// Space Complexity: O(m * n) +class Solution { + +public: + int minDeletionSize(vector& A) { + + int m = A.size(), n = A[0].size(), res = 0; + vector cur(m); + for(int j = 0; j < n; j ++){ + + vector cur2 = cur; + for(int i = 0; i < m; i ++) + cur2[i] += A[i][j]; + + if(!is_sort(cur2)) + res ++; + else + cur = cur2; + } + return res; + } + +private: + bool is_sort(const vector& s){ + for(int i = 1; i < s.size(); i ++) + if(s[i - 1] > s[i]) + return false; + return true; + } +}; + + +int main() { + + vector A1 = {"ca","bb","ac"}; + cout << Solution().minDeletionSize(A1) << endl; + // 1 + + vector A2 = {"xc","yb","za"}; + cout << Solution().minDeletionSize(A2) << endl; + // 0 + + vector A3 = {"zyx","wvu","tsr"}; + cout << Solution().minDeletionSize(A3) << endl; + // 3 + + vector A4 = {"xga","xfb","yfa"}; + cout << Solution().minDeletionSize(A4) << endl; + //1 + + vector A5 = {"bwwdyeyfhc","bchpphbtkh","hmpudwfkpw","lqeoyqkqwe","riobghmpaa","stbheblgao","snlaewujlc","tqlzolljas","twdkexzvfx","wacnnhjdis"}; + cout << Solution().minDeletionSize(A5) << endl; + //4 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0955-Delete-Columns-to-Make-Sorted-II/cpp-0955/main2.cpp b/0501-1000/0955-Delete-Columns-to-Make-Sorted-II/cpp-0955/main2.cpp new file mode 100644 index 00000000..e846a189 --- /dev/null +++ b/0501-1000/0955-Delete-Columns-to-Make-Sorted-II/cpp-0955/main2.cpp @@ -0,0 +1,67 @@ +/// Source : https://leetcode.com/problems/delete-columns-to-make-sorted-ii/ +/// Author : liuyubobobo +/// Time : 2018-12-16 + +#include +#include +#include + +using namespace std; + + +/// Greedy and check in place +/// Time Complexity: O(m * n) +/// Space Complexity: O(m) +class Solution { + +public: + int minDeletionSize(vector& A) { + + int m = A.size(), n = A[0].size(), res = 0; + vector check(m - 1, false); + for(int j = 0; j < n; j ++){ + + bool ok = true; + for(int i = 1; i < m; i ++) + if(!check[i - 1] && A[i][j] < A[i - 1][j]){ + ok = false; + break; + } + + if(ok){ + for(int i = 1; i < m; i ++) + if(!check[i - 1] && A[i][j] > A[i - 1][j]) + check[i - 1] = true; + } + else + res ++; + } + return res; + } +}; + + +int main() { + + vector A1 = {"ca","bb","ac"}; + cout << Solution().minDeletionSize(A1) << endl; + // 1 + + vector A2 = {"xc","yb","za"}; + cout << Solution().minDeletionSize(A2) << endl; + // 0 + + vector A3 = {"zyx","wvu","tsr"}; + cout << Solution().minDeletionSize(A3) << endl; + // 3 + + vector A4 = {"xga","xfb","yfa"}; + cout << Solution().minDeletionSize(A4) << endl; + //1 + + vector A5 = {"bwwdyeyfhc","bchpphbtkh","hmpudwfkpw","lqeoyqkqwe","riobghmpaa","stbheblgao","snlaewujlc","tqlzolljas","twdkexzvfx","wacnnhjdis"}; + cout << Solution().minDeletionSize(A5) << endl; + //4 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0956-Tallest-Billboard/cpp-0956/CMakeLists.txt b/0501-1000/0956-Tallest-Billboard/cpp-0956/CMakeLists.txt new file mode 100644 index 00000000..28e28e0f --- /dev/null +++ b/0501-1000/0956-Tallest-Billboard/cpp-0956/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(cpp_0956) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0956 main2.cpp) \ No newline at end of file diff --git a/0501-1000/0956-Tallest-Billboard/cpp-0956/main.cpp b/0501-1000/0956-Tallest-Billboard/cpp-0956/main.cpp new file mode 100644 index 00000000..1069cb9d --- /dev/null +++ b/0501-1000/0956-Tallest-Billboard/cpp-0956/main.cpp @@ -0,0 +1,60 @@ +/// Source : https://leetcode.com/problems/tallest-billboard/ +/// Author : liuyubobobo +/// Time : 2020-05-12 + +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(n * max_sum) +/// Space Complexity: O(n * max_sum) +class Solution { + +private: + const int OFFSET = 5000; + +public: + int tallestBillboard(vector& rods) { + + vector> dp(20, vector(10001, -1)); + int res = dfs(rods, 0, 0, dp); + return res == INT_MIN ? 0 : res; + } + +private: + // diff is left - right + int dfs(const vector& rods, int index, int diff, vector>& dp){ + + if(index == rods.size()) return diff == 0 ? 0 : INT_MIN; + + int state = diff + OFFSET; + if(dp[index][state] != -1) return dp[index][state]; + + int res = dfs(rods, index + 1, diff, dp); + + int tres = dfs(rods, index + 1, diff - rods[index], dp); + res = max(res, tres); + + tres = dfs(rods, index + 1, diff + rods[index], dp); + res = max(res, tres + rods[index]); + + return dp[index][state] = res; + } +}; + + +int main() { + + vector rods1 = {243,269,278,237,208,279,229,231,262,256,248,261,232,275,254,224,264}; + cout << Solution().tallestBillboard(rods1) << endl; + // 2125 + + vector rods2 = {1, 2}; + cout << Solution().tallestBillboard(rods2) << endl; + // 0 + + return 0; +} diff --git a/0501-1000/0956-Tallest-Billboard/cpp-0956/main2.cpp b/0501-1000/0956-Tallest-Billboard/cpp-0956/main2.cpp new file mode 100644 index 00000000..bcb5208c --- /dev/null +++ b/0501-1000/0956-Tallest-Billboard/cpp-0956/main2.cpp @@ -0,0 +1,73 @@ +/// Source : https://leetcode.com/problems/tallest-billboard/ +/// Author : liuyubobobo +/// Time : 2020-10-17 + +#include +#include +#include + +using namespace std; + + +/// Meet in the middle +/// Time Complexity: O(3 ^ (n/2)) +/// Space Complexity: O(3 ^ (n / 2)) +class Solution { + +private: + vector pow3; + +public: + int tallestBillboard(vector& rods) { + + pow3 = {1}; + for(int i = 1; i <= 10; i ++) pow3.push_back(pow3.back() * 3); + + int n = rods.size(); + int left = n / 2, right = n - n / 2; + + unordered_map ltable, rtable; + for(int lstate = 0; lstate < pow3[left]; lstate ++){ + int l = lstate, lsum = 0, sum = 0, index = 0; + while(l){ + int x = l % 3; + if(x == 1) lsum += rods[index], sum += rods[index]; + else if(x == 2) lsum -= rods[index], sum += rods[index]; + l /= 3; + index ++; + } + ltable[lsum] = sum; + } + for(int rstate = 0; rstate < pow3[right]; rstate ++){ + + int r = rstate, rsum = 0, sum = 0, index = 0; + while(r){ + int x = r % 3; + if(x == 1) rsum += rods[left + index], sum += rods[left + index]; + else if(x == 2) rsum -= rods[left + index], sum += rods[left + index]; + r /= 3; + index ++; + } + rtable[rsum] = sum; + } + + int res = 0; + for(const pair& p: ltable) + if(rtable.count(-p.first)) res = max(res, (p.second + rtable[-p.first]) / 2); + return res; + } +}; + + +int main() { + + vector rods1 = {243,269,278,237,208,279,229,231,262,256,248,261,232,275,254,224,264}; + cout << Solution().tallestBillboard(rods1) << endl; + // 2125 + + vector rods2 = {1, 2}; + cout << Solution().tallestBillboard(rods2) << endl; + // 0 + + return 0; +} diff --git a/0501-1000/0957-Prison-Cells-After-N-Days/cpp-0957/CMakeLists.txt b/0501-1000/0957-Prison-Cells-After-N-Days/cpp-0957/CMakeLists.txt new file mode 100644 index 00000000..8a0a1cc7 --- /dev/null +++ b/0501-1000/0957-Prison-Cells-After-N-Days/cpp-0957/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(B) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/0501-1000/0957-Prison-Cells-After-N-Days/cpp-0957/main.cpp b/0501-1000/0957-Prison-Cells-After-N-Days/cpp-0957/main.cpp new file mode 100644 index 00000000..83a5d878 --- /dev/null +++ b/0501-1000/0957-Prison-Cells-After-N-Days/cpp-0957/main.cpp @@ -0,0 +1,90 @@ +/// Source : https://leetcode.com/problems/prison-cells-after-n-days/ +/// Author : liuyubobobo +/// Time : 2018-12-15 + +#include +#include +#include + +using namespace std; + + +/// Using Hash Map and State Compression +/// Time Complexity: O(2^8) +/// Space Complexity: O(2^8 * 8) +class Solution { +public: + vector prisonAfterNDays(vector& cells, int N) { + + unordered_map visited; + + vector> arr; + vector cur = cells; + int i = 0; + while(true){ + + vector next(8, 0); + for(int i = 1; i < 7; i ++) + if(cur[i - 1] == cur[i + 1]) + next[i] = 1; + + int state = get_state(next); + if(visited.count(state)){ + int start = visited[state]; + int len = i - start; + return arr[start + (N - 1 - start) % len]; + } + + arr.push_back(next); + visited[state] = i; + + if(i == N - 1) + return next; + + i ++; + cur = next; + } + assert(false); + return {}; + } + +private: + int get_state(const vector& cells){ + int state = 0; + for(int i = 0; i < 8; i ++) + if(cells[i]) + state += (1 << i); + return state; + } +}; + + +void print_cells(const vector& cells){ + for(int cell: cells) + cout << cell << " "; + cout << endl; +} + +int main() { + + vector cells1 = {0,1,0,1,1,0,0,1}; + print_cells(Solution().prisonAfterNDays(cells1, 7)); + // 0 0 1 1 0 0 0 0 + + vector cells2 = {1,0,0,1,0,0,1,0}; + print_cells(Solution().prisonAfterNDays(cells2, 1000000000)); + // 0 0 1 1 1 1 1 0 + + vector cells3 = {0,1,0,1,0,1,0,0}; + print_cells(Solution().prisonAfterNDays(cells3, 27)); + + vector cells4 = {1,1,0,0,0,0,1,1}; + print_cells(Solution().prisonAfterNDays(cells4, 7)); + + vector cells5 = {0,1,0,1,1,0,0,1}; + print_cells(Solution().prisonAfterNDays(cells5, 7)); + // 0 0 1 1 0 0 0 0 + + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0958-Check-Completeness-of-a-Binary-Tree/cpp-0958/CMakeLists.txt b/0501-1000/0958-Check-Completeness-of-a-Binary-Tree/cpp-0958/CMakeLists.txt new file mode 100644 index 00000000..c2b7a0b7 --- /dev/null +++ b/0501-1000/0958-Check-Completeness-of-a-Binary-Tree/cpp-0958/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(A) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(A main2.cpp) \ No newline at end of file diff --git a/0501-1000/0958-Check-Completeness-of-a-Binary-Tree/cpp-0958/main.cpp b/0501-1000/0958-Check-Completeness-of-a-Binary-Tree/cpp-0958/main.cpp new file mode 100644 index 00000000..33ad4be8 --- /dev/null +++ b/0501-1000/0958-Check-Completeness-of-a-Binary-Tree/cpp-0958/main.cpp @@ -0,0 +1,60 @@ +/// Source : https://leetcode.com/problems/check-completeness-of-a-binary-tree/ +/// Author : liuyubobobo +/// Time : 2018-12-15 + +#include +#include + +using namespace std; + + +/// Recursion +/// Time Complexity: O(n+) +/// Space Complexity: O(h) + +/// 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: + bool isCompleteTree(TreeNode* root) { + + if(!root) return true; + + TreeNode* cur = root; + int left = 0; + while(cur) + left ++, cur = cur->left; + + cur = root; + int right = 0; + while(cur) + right ++, cur = cur->right; + + if(left < right) return false; + if(left == right) + return isFullTree(root->left, left - 1) && isFullTree(root->right, right - 1); + if(left - right > 1) return false; + return (isFullTree(root->left, left - 1) && isCompleteTree(root->right)) || + (isCompleteTree(root->left) && isFullTree(root->right, right - 1)); + } + +private: + bool isFullTree(TreeNode* root, int depth){ + if(!root) + return depth == 0; + return isFullTree(root->left, depth - 1) && isFullTree(root->right, depth - 1); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0958-Check-Completeness-of-a-Binary-Tree/cpp-0958/main2.cpp b/0501-1000/0958-Check-Completeness-of-a-Binary-Tree/cpp-0958/main2.cpp new file mode 100644 index 00000000..2e960cb0 --- /dev/null +++ b/0501-1000/0958-Check-Completeness-of-a-Binary-Tree/cpp-0958/main2.cpp @@ -0,0 +1,55 @@ +/// Source : https://leetcode.com/problems/check-completeness-of-a-binary-tree/ +/// Author : liuyubobobo +/// Time : 2018-12-15 + +#include +#include +#include + +using namespace std; + + +/// BFS +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// 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: + bool isCompleteTree(TreeNode* root) { + + if(!root) return true; + + queue> queue; + queue.push(make_pair(root, 1)); + int max_index = -1, sz = 0; + while(!queue.empty()){ + TreeNode* node = queue.front().first; + int index = queue.front().second; + queue.pop(); + + sz ++; + max_index = max(max_index, index); + + if(node->left) + queue.push(make_pair(node->left, 2 * index)); + if(node->right) + queue.push(make_pair(node->right, 2 * index + 1)); + } + return sz == max_index; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0959-Regions-Cut-By-Slashes/cpp-0959/CMakeLists.txt b/0501-1000/0959-Regions-Cut-By-Slashes/cpp-0959/CMakeLists.txt new file mode 100644 index 00000000..c8cc528c --- /dev/null +++ b/0501-1000/0959-Regions-Cut-By-Slashes/cpp-0959/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(C) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(C main2.cpp) \ No newline at end of file diff --git a/0501-1000/0959-Regions-Cut-By-Slashes/cpp-0959/main.cpp b/0501-1000/0959-Regions-Cut-By-Slashes/cpp-0959/main.cpp new file mode 100644 index 00000000..e4bfe7ca --- /dev/null +++ b/0501-1000/0959-Regions-Cut-By-Slashes/cpp-0959/main.cpp @@ -0,0 +1,78 @@ +/// Source : https://leetcode.com/problems/regions-cut-by-slashes/ +/// Author : liuyubobobo +/// Time : 2018-12-15 + +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(4 * m * n) +/// Space Complexity: O(4 * m * n) +class Solution { + +private: + const int d[4][2] = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}}; + int m, n; + +public: + int regionsBySlashes(vector& grid) { + + m = grid.size(), n = grid[0].size(); + vector>> visited(m, + vector>(n, vector(4, false))); + + int res = 0; + for(int i = 0; i < m; i ++) + for(int j = 0; j < n; j ++) + for(int k = 0; k < 4; k ++) + if(!visited[i][j][k]) + res ++, dfs(grid, i, j, k, visited); + return res; + } + +private: + void dfs(const vector& grid, int r, int c, int k, + vector>>& visited){ + + visited[r][c][k] = true; + if(grid[r][c] == '/'){ + if(k < 2){ + if(!visited[r][c][1 - k]) dfs(grid, r, c, 1 - k, visited); + } + else{ + if(!visited[r][c][5 - k]) dfs(grid, r, c, 5 - k, visited); + } + } + else if(grid[r][c] == '\\'){ + if(!visited[r][c][3 - k]) dfs(grid, r, c, 3 - k, visited); + } + else{ + for(int kk = 0; kk < 4; kk ++) + if(!visited[r][c][kk]) + dfs(grid, r, c, kk, visited); + } + + int nextr = r + d[k][0], nextc = c + d[k][1]; + if(in_area(nextr, nextc)){ + if(k % 2){ + if(!visited[nextr][nextc][4 - k]) dfs(grid, nextr, nextc, 4 - k, visited); + } + else{ + if(!visited[nextr][nextc][2 - k]) dfs(grid, nextr, nextc, 2 - k, visited); + } + } + } + + bool in_area(int x, int y){ + return x >= 0 && x < m && y >= 0 && y < n; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0959-Regions-Cut-By-Slashes/cpp-0959/main2.cpp b/0501-1000/0959-Regions-Cut-By-Slashes/cpp-0959/main2.cpp new file mode 100644 index 00000000..ff199122 --- /dev/null +++ b/0501-1000/0959-Regions-Cut-By-Slashes/cpp-0959/main2.cpp @@ -0,0 +1,98 @@ +/// Source : https://leetcode.com/problems/regions-cut-by-slashes/ +/// Author : liuyubobobo +/// Time : 2018-12-16 + +#include +#include + +using namespace std; + + +/// Union-Find +/// Time Complexity: O(4 * m * n) +/// Space Complexity: O(4 * m * n) +class UF{ + +private: + vector parent; + int sz; + +public: + UF(int n){ + for(int i = 0 ; i < n ; i ++) + parent.push_back(i); + sz = n; + } + + int find(int p){ + if( p != parent[p] ) + parent[p] = find( parent[p] ); + return parent[p]; + } + + bool isConnected(int p , int q){ + return find(p) == find(q); + } + + void unionElements(int p, int q){ + + int pRoot = find(p); + int qRoot = find(q); + + if( pRoot == qRoot ) + return; + + parent[pRoot] = qRoot; + sz --; + } + + int size(){ + return sz; + } +}; + +class Solution { + +private: + const int d[4][2] = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}}; + int m, n; + +public: + int regionsBySlashes(vector& grid) { + + m = grid.size(), n = grid[0].size(); + + UF uf(m * n * 4); + for(int r = 0; r < m; r ++) + for(int c = 0; c < n; c ++) + for(int k = 0; k < 4; k ++){ + if(grid[r][c] == '/') + uf.unionElements(id(r, c, k), id(r, c, k < 2 ? 1 - k : 5 - k)); + else if(grid[r][c] == '\\') + uf.unionElements(id(r, c, k), id(r, c, 3 - k)); + else + for(int kk = 0; kk < 4; kk ++) + uf.unionElements(id(r, c, k), id(r, c, kk)); + + int nextr = r + d[k][0], nextc = c + d[k][1]; + if(in_area(nextr, nextc)) + uf.unionElements(id(r, c, k), id(nextr, nextc, k % 2 ? 4 - k : 2 - k)); + } + return uf.size(); + } + +private: + int id(int r, int c, int k){ + return r * n * 4 + c * 4 + k; + } + + bool in_area(int x, int y){ + return x >= 0 && x < m && y >= 0 && y < n; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0960-Delete-Columns-to-Make-Sorted-III/cpp-0960/CMakeLists.txt b/0501-1000/0960-Delete-Columns-to-Make-Sorted-III/cpp-0960/CMakeLists.txt new file mode 100644 index 00000000..f0e51103 --- /dev/null +++ b/0501-1000/0960-Delete-Columns-to-Make-Sorted-III/cpp-0960/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(D) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(D main3.cpp) \ No newline at end of file diff --git a/0501-1000/0960-Delete-Columns-to-Make-Sorted-III/cpp-0960/main.cpp b/0501-1000/0960-Delete-Columns-to-Make-Sorted-III/cpp-0960/main.cpp new file mode 100644 index 00000000..173490f3 --- /dev/null +++ b/0501-1000/0960-Delete-Columns-to-Make-Sorted-III/cpp-0960/main.cpp @@ -0,0 +1,62 @@ +/// Source : https://leetcode.com/problems/delete-columns-to-make-sorted-iii/ +/// Author : liuyubobobo +/// Time : 2018-12-15 + +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(m * n * n) +/// Space Complexity: O(m * n) +class Solution { + +private: + int m, n; + +public: + int minDeletionSize(vector& A) { + + for(string& s: A) + s = "a" + s; + m = A.size(); + n = A[0].size(); + vector> dp(n, vector(n, -1)); + return dfs(A, 0, 0, dp); + } + +private: + int dfs(const vector& A, int index, int prev, + vector>& dp){ + + if(index == n) + return 0; + + if(dp[index][prev] != -1) + return dp[index][prev]; + + int res = 1 + dfs(A, index + 1, prev, dp); + + bool ok = true; + for(int i = 0; i < m; i ++) + if(A[i][index] < A[i][prev]){ + ok = false; + break; + } + if(ok) + res = min(res, dfs(A, index + 1, index, dp)); + + return dp[index][prev] = res; + } +}; + + +int main() { + + vector A1 = {"babca","bbazb"}; + cout << Solution().minDeletionSize(A1) << endl; + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0960-Delete-Columns-to-Make-Sorted-III/cpp-0960/main2.cpp b/0501-1000/0960-Delete-Columns-to-Make-Sorted-III/cpp-0960/main2.cpp new file mode 100644 index 00000000..81dec3f0 --- /dev/null +++ b/0501-1000/0960-Delete-Columns-to-Make-Sorted-III/cpp-0960/main2.cpp @@ -0,0 +1,68 @@ +/// Source : https://leetcode.com/problems/delete-columns-to-make-sorted-iii/ +/// Author : liuyubobobo +/// Time : 2018-12-16 + +#include +#include + +using namespace std; + + +/// Memory Search +/// Using keep which columns as the state :-) +/// Time Complexity: O(m * n * n) +/// Space Complexity: O(n) +class Solution { + +private: + int m, n; + +public: + int minDeletionSize(vector& A) { + + m = A.size(); + n = A[0].size(); + vector dp(n, -1); + for(int i = 0; i < n; i ++) + dfs(A, i, dp); + + return n - *max_element(dp.begin(), dp.end()); + } + +private: + int dfs(const vector& A, int index, vector& dp){ + + if(index == 0) + return dp[index] = 1; + + if(dp[index] != -1) + return dp[index]; + + int res = 1; + for(int j = index - 1; j >= 0; j --) { + bool ok = true; + for(int i = 0; i < m; i ++) + if (A[i][index] < A[i][j]) { + ok = false; + break; + } + if (ok) + res = max(res, 1 + dfs(A, j, dp)); + } + return dp[index] = res; + } +}; + + +int main() { + + vector A1 = {"babca","bbazb"}; + cout << Solution().minDeletionSize(A1) << endl; + // 3 + + vector A2 = {"abbba"}; + cout << Solution().minDeletionSize(A2) << endl; + // 1 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0960-Delete-Columns-to-Make-Sorted-III/cpp-0960/main3.cpp b/0501-1000/0960-Delete-Columns-to-Make-Sorted-III/cpp-0960/main3.cpp new file mode 100644 index 00000000..17e02b8c --- /dev/null +++ b/0501-1000/0960-Delete-Columns-to-Make-Sorted-III/cpp-0960/main3.cpp @@ -0,0 +1,48 @@ +/// Source : https://leetcode.com/problems/delete-columns-to-make-sorted-iii/ +/// Author : liuyubobobo +/// Time : 2018-12-16 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(m * n * n) +/// Space Complexity: O(n) +class Solution { + +public: + int minDeletionSize(vector& A) { + + int m = A.size(), n = A[0].size(); + vector dp(n, 1); + + for(int index = 1; index < n; index ++){ + + for(int prev = index - 1; prev >= 0; prev --){ + + bool ok = true; + for(int i = 0; i < m; i ++) + if(A[i][index] < A[i][prev]){ + ok = false; + break; + } + if(ok) + dp[index] = max(dp[index], 1 + dp[prev]); + } + } + + return n - *max_element(dp.begin(), dp.end()); + } +}; + + +int main() { + + vector A1 = {"babca","bbazb"}; + cout << Solution().minDeletionSize(A1) << endl; + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0961-N-Repeated-Element-in-Size-2N-Array/cpp-0961/CMakeLists.txt b/0501-1000/0961-N-Repeated-Element-in-Size-2N-Array/cpp-0961/CMakeLists.txt new file mode 100644 index 00000000..a1a00c61 --- /dev/null +++ b/0501-1000/0961-N-Repeated-Element-in-Size-2N-Array/cpp-0961/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(cpp_0961) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0961 main4.cpp) \ No newline at end of file diff --git a/0501-1000/0961-N-Repeated-Element-in-Size-2N-Array/cpp-0961/main.cpp b/0501-1000/0961-N-Repeated-Element-in-Size-2N-Array/cpp-0961/main.cpp new file mode 100644 index 00000000..6f934379 --- /dev/null +++ b/0501-1000/0961-N-Repeated-Element-in-Size-2N-Array/cpp-0961/main.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/n-repeated-element-in-size-2n-array/ +/// Author : liuyubobobo +/// Time : 2019-08-11 + +#include +#include +#include +#include + +using namespace std; + + +/// Using HashMap to get the frequency +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int repeatedNTimes(vector& A) { + + unordered_map freq; + for(int e: A){ + freq[e] ++; + if(freq[e] == A.size() / 2) return e; + } + assert(false); + return -1; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0961-N-Repeated-Element-in-Size-2N-Array/cpp-0961/main2.cpp b/0501-1000/0961-N-Repeated-Element-in-Size-2N-Array/cpp-0961/main2.cpp new file mode 100644 index 00000000..6d208abd --- /dev/null +++ b/0501-1000/0961-N-Repeated-Element-in-Size-2N-Array/cpp-0961/main2.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/n-repeated-element-in-size-2n-array/ +/// Author : liuyubobobo +/// Time : 2019-08-11 + +#include +#include +#include +#include + +using namespace std; + + +/// Using HashSet to check repeating +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int repeatedNTimes(vector& A) { + + unordered_set set; + for(int e: A) + if(set.count(e)) return e; + else set.insert(e); + assert(false); + return -1; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0961-N-Repeated-Element-in-Size-2N-Array/cpp-0961/main3.cpp b/0501-1000/0961-N-Repeated-Element-in-Size-2N-Array/cpp-0961/main3.cpp new file mode 100644 index 00000000..0392c5af --- /dev/null +++ b/0501-1000/0961-N-Repeated-Element-in-Size-2N-Array/cpp-0961/main3.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/n-repeated-element-in-size-2n-array/ +/// Author : liuyubobobo +/// Time : 2019-08-11 + +#include +#include +#include +#include + +using namespace std; + + +/// Sorting +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + int repeatedNTimes(vector& A) { + + sort(A.begin(), A.end()); + for(int i = 1; i < A.size(); i ++) + if(A[i] == A[i - 1]) + return A[i]; + assert(false); + return -1; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0961-N-Repeated-Element-in-Size-2N-Array/cpp-0961/main4.cpp b/0501-1000/0961-N-Repeated-Element-in-Size-2N-Array/cpp-0961/main4.cpp new file mode 100644 index 00000000..e30522e2 --- /dev/null +++ b/0501-1000/0961-N-Repeated-Element-in-Size-2N-Array/cpp-0961/main4.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/n-repeated-element-in-size-2n-array/ +/// Author : liuyubobobo +/// Time : 2019-08-11 + +#include +#include +#include +#include + +using namespace std; + + +/// Random Algorithm +/// Time Complexity: O(1) +/// Space Complexity: O(1) +class Solution { +public: + int repeatedNTimes(vector& A) { + + int n = A.size(); + while(true){ + int i = rand() % n, j = rand() % n; + if(i != j && A[i] == A[j]) return A[i]; + } + assert(false); + return -1; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0965-Univalued-Binary-Tree/cpp-0965/CMakeLists.txt b/0501-1000/0965-Univalued-Binary-Tree/cpp-0965/CMakeLists.txt new file mode 100644 index 00000000..0a7433d2 --- /dev/null +++ b/0501-1000/0965-Univalued-Binary-Tree/cpp-0965/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(cpp_0965) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0965 main.cpp) \ No newline at end of file diff --git a/0501-1000/0965-Univalued-Binary-Tree/cpp-0965/main.cpp b/0501-1000/0965-Univalued-Binary-Tree/cpp-0965/main.cpp new file mode 100644 index 00000000..035e4b53 --- /dev/null +++ b/0501-1000/0965-Univalued-Binary-Tree/cpp-0965/main.cpp @@ -0,0 +1,44 @@ +/// Source : https://leetcode.com/contest/weekly-contest-117/problems/univalued-binary-tree/ +/// Author : liuyubobobo +/// Time : 2019-03-17 + +#include + +using namespace std; + + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + + +/// Recursion +/// Time Complexity: O(n) +/// Space Complexity: O(h) +class Solution { +public: + bool isUnivalTree(TreeNode* root) { + + if(!root) return true; + + int v = root->val; + return dfs(root, v); + } + +private: + bool dfs(TreeNode* root, int v){ + + if(!root) return true; + return root->val == v && dfs(root->left, v) && dfs(root->right, v); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0966-Vowel-Spellchecker/cpp-0966/CMakeLists.txt b/0501-1000/0966-Vowel-Spellchecker/cpp-0966/CMakeLists.txt new file mode 100644 index 00000000..b59bcccf --- /dev/null +++ b/0501-1000/0966-Vowel-Spellchecker/cpp-0966/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(cpp_0966) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0966 main.cpp) \ No newline at end of file diff --git a/0501-1000/0966-Vowel-Spellchecker/cpp-0966/main.cpp b/0501-1000/0966-Vowel-Spellchecker/cpp-0966/main.cpp new file mode 100644 index 00000000..41160608 --- /dev/null +++ b/0501-1000/0966-Vowel-Spellchecker/cpp-0966/main.cpp @@ -0,0 +1,84 @@ +/// Source : https://leetcode.com/problems/vowel-spellchecker/ +/// Author : liuyubobobo +/// Time : 2019-03-17 + +#include +#include +#include +#include + +using namespace std; + + +/// Using HashSet and HashMap +/// Time Complexity: O(n + q) +/// Space Complexity: O(n) +class Solution { + +private: + const unordered_set vowels = {'a', 'e', 'i', 'o', 'u'}; + +public: + vector spellchecker(vector& wordlist, vector& queries) { + + unordered_set set; + unordered_map> map1; // all_lower -> origin + unordered_map> map2; // replace vowel -> origin + for(const string& word: wordlist){ + set.insert(word); + + string lower_word = to_lower(word); + map1[lower_word].push_back(word); + + string novowel_word = replace_vowel(word); + map2[novowel_word].push_back(word); + } + + vector res; + for(const string& query: queries){ + + bool ok = false; + if(set.count(query)){ + res.push_back(query); + ok = true; + } + else{ + string lower_query = to_lower(query); + if(map1.count(lower_query)){ + res.push_back(map1[lower_query][0]); + ok = true; + } + else{ + string novowel_query = replace_vowel(query); + if(map2.count(novowel_query)){ + res.push_back(map2[novowel_query][0]); + ok = true; + } + } + } + if(!ok) res.push_back(""); + } + return res; + } + +private: + string to_lower(const string& word){ + string res = ""; + for(char c: word) res += tolower(c); + return res; + } + + string replace_vowel(const string& word){ + string res = ""; + for(char c: word) + if(vowels.count(tolower(c))) res += "#"; + else res += tolower(c); + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0967-Numbers-With-Same-Consecutive-Differences/cpp-0967/CMakeLists.txt b/0501-1000/0967-Numbers-With-Same-Consecutive-Differences/cpp-0967/CMakeLists.txt new file mode 100644 index 00000000..45483cf3 --- /dev/null +++ b/0501-1000/0967-Numbers-With-Same-Consecutive-Differences/cpp-0967/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(cpp_0967) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0967 main.cpp) \ No newline at end of file diff --git a/0501-1000/0967-Numbers-With-Same-Consecutive-Differences/cpp-0967/main.cpp b/0501-1000/0967-Numbers-With-Same-Consecutive-Differences/cpp-0967/main.cpp new file mode 100644 index 00000000..e713a40e --- /dev/null +++ b/0501-1000/0967-Numbers-With-Same-Consecutive-Differences/cpp-0967/main.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/numbers-with-same-consecutive-differences/ +/// Author : liuyubobobo +/// Time : 2019-03-17 + +#include +#include + +using namespace std; + + +/// Backtrack +/// Time Complexity: O(2^N) +/// Space Complexity: O(N) +class Solution { +public: + vector numsSameConsecDiff(int N, int K) { + + vector num(N, -1); + vector res; + + for(int i = 0 + (N != 1); i <= 9; i ++) + dfs(num, 0, i, K, res); + return res; + } + +private: + void dfs(vector& num, int pos, int digit, int K, vector& res){ + + num[pos] = digit; + if(pos == num.size() - 1){ + res.push_back(get_num(num)); + return; + } + + if(digit - K >= 0) dfs(num, pos + 1, digit - K, K, res); + if(digit + K <= 9 && K) dfs(num, pos + 1, digit + K, K, res); + } + + int get_num(const vector& num){ + int ret = 0; + for(int e: num) ret = ret * 10 + e; + return ret; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0968-Binary-Tree-Cameras/cpp-0968/CMakeLists.txt b/0501-1000/0968-Binary-Tree-Cameras/cpp-0968/CMakeLists.txt new file mode 100644 index 00000000..3730ea4d --- /dev/null +++ b/0501-1000/0968-Binary-Tree-Cameras/cpp-0968/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(cpp_0968) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_0968 main4.cpp) \ No newline at end of file diff --git a/0501-1000/0968-Binary-Tree-Cameras/cpp-0968/main.cpp b/0501-1000/0968-Binary-Tree-Cameras/cpp-0968/main.cpp new file mode 100644 index 00000000..f02e0d19 --- /dev/null +++ b/0501-1000/0968-Binary-Tree-Cameras/cpp-0968/main.cpp @@ -0,0 +1,92 @@ +/// Source : https://leetcode.com/problems/binary-tree-cameras/ +/// Author : liuyubobobo +/// Time : 2019-03-17 + +#include +#include +#include + +using namespace std; + + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +/// Memory Search +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +private: + unordered_map indexes; + +public: + int minCameraCover(TreeNode* root) { + + if(!root) return 0; + + indexes.clear(); + tagIndexes(root, indexes); + + vector dp(indexes.size() * 4, -1); + return dfs(root, false, true, dp); + } + +private: + int dfs(TreeNode* root, bool isCamera, bool needToCover, vector& dp){ + + if(!root) return 0; + + int index = indexes[root]; + int hashcode = index * 4 + isCamera * 2 + needToCover; + + if(dp[hashcode] != -1) return dp[hashcode]; + + int res; + if(isCamera){ + res = dfs(root->left, false, false, dp) + dfs(root->right, false, false, dp); + } + else{ + res = 1 + dfs(root->left, false, false, dp) + dfs(root->right, false, false, dp); + if(!needToCover) + res = min(res, dfs(root->left, false, true, dp) + dfs(root->right, false, true,dp)); + else{ + if(root->left) + res = min(res, 1 + dfs(root->left, true, false, dp) + dfs(root->right, false, true, dp)); + if(root->right) + res = min(res, 1 + dfs(root->right, true, false, dp) + dfs(root->left, false, true, dp)); + if(root->left && root->right) + res = min(res, 2 + dfs(root->left, true, false, dp) + dfs(root->right, true, false, dp)); + } + } + + return dp[hashcode] = res; + } + + void tagIndexes(TreeNode* root, unordered_map& indexes){ + + if(!root) return; + + int index = indexes.size(); + indexes[root] = index; + + tagIndexes(root->left, indexes); + tagIndexes(root->right, indexes); + } +}; + +int main() { + + TreeNode* root1 = new TreeNode(0); + root1->left = new TreeNode(0); + root1->left->left = new TreeNode(0); + root1->left->right = new TreeNode(0); + cout << Solution().minCameraCover(root1) << endl; + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0968-Binary-Tree-Cameras/cpp-0968/main2.cpp b/0501-1000/0968-Binary-Tree-Cameras/cpp-0968/main2.cpp new file mode 100644 index 00000000..f57f1baf --- /dev/null +++ b/0501-1000/0968-Binary-Tree-Cameras/cpp-0968/main2.cpp @@ -0,0 +1,75 @@ +/// Source : https://leetcode.com/problems/binary-tree-cameras/ +/// Author : liuyubobobo +/// Time : 2019-03-17 + +#include +#include +#include + +using namespace std; + + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + + +/// Memory Search - Tree DP +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +public: + int minCameraCover(TreeNode* root) { + + if(!root) return 0; + // isCamera, needToeCover - 00, 01, 10, 11 + vector res = dfs(root); + return res[0 * 2 + 1]; + } + +private: + vector dfs(TreeNode* root){ + + if(!root) return {0, 0, 0, 0}; + + vector lres = dfs(root->left); + vector rres = dfs(root->right); + + vector res(4); + // 10 and 11 + res[1 * 2 + 0] = res[1 * 2 + 1] = lres[0 * 2 + 0] + rres[0 * 2 + 0]; + + // 00 and 01 + res[0 * 2 + 0] = res[0 * 2 + 1] = 1 + lres[0 * 2 + 0] + rres[0 * 2 + 0]; + + // 00 + res[0 * 2 + 0] = min(res[0 * 2 + 0], lres[0 * 2 + 1] + rres[0 * 2 + 1]); + + // 01 + if(root->left) + res[0 * 2 + 1] = min(res[0 * 2 + 1], 1 + lres[1 * 2 + 0] + rres[0 * 2 + 1]); + if(root->right) + res[0 * 2 + 1] = min(res[0 * 2 + 1], 1 + lres[0 * 2 + 1] + rres[1 * 2 + 0]); + if(root->left && root->right) + res[0 * 2 + 1] = min(res[0 * 2 + 1], 2 + lres[1 * 2 + 0] + rres[1 * 2 + 0]); + + return res; + } +}; + + +int main() { + + TreeNode* root1 = new TreeNode(0); + root1->left = new TreeNode(0); + root1->left->left = new TreeNode(0); + root1->left->right = new TreeNode(0); + cout << Solution().minCameraCover(root1) << endl; + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0968-Binary-Tree-Cameras/cpp-0968/main3.cpp b/0501-1000/0968-Binary-Tree-Cameras/cpp-0968/main3.cpp new file mode 100644 index 00000000..b37f96a5 --- /dev/null +++ b/0501-1000/0968-Binary-Tree-Cameras/cpp-0968/main3.cpp @@ -0,0 +1,75 @@ +/// Source : https://leetcode.com/problems/binary-tree-cameras/ +/// Author : liuyubobobo +/// Time : 2019-03-18 + +#include +#include +#include + +using namespace std; + + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + + +/// Memory Search - Tree DP +/// Using 3 states instead of 4 states (3 states is enough) +/// +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +public: + int minCameraCover(TreeNode* root) { + + if(!root) return 0; + vector res = dfs(root); + return res[2]; + } + +private: + /// State 0: install a camera + /// State 1: not install a camera but do not need to be covered + /// State 2: not install a camera but do need to be covered + vector dfs(TreeNode* root){ + + if(!root) return {0, 0, 0}; + + vector lres = dfs(root->left); + vector rres = dfs(root->right); + + vector res(3); + + res[0] = lres[1] + rres[1]; + + res[1] = res[2] = 1 + lres[1] + rres[1]; + res[1] = min(res[1], lres[2] + rres[2]); + + if(root->left) + res[2] = min(res[2], 1 + lres[0] + rres[2]); + if(root->right) + res[2] = min(res[2], 1 + lres[2] + rres[0]); + if(root->left && root->right) + res[2] = min(res[2], 2 + lres[0] + rres[0]); + + return res; + } +}; + + +int main() { + + TreeNode* root1 = new TreeNode(0); + root1->left = new TreeNode(0); + root1->left->left = new TreeNode(0); + root1->left->right = new TreeNode(0); + cout << Solution().minCameraCover(root1) << endl; + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0968-Binary-Tree-Cameras/cpp-0968/main4.cpp b/0501-1000/0968-Binary-Tree-Cameras/cpp-0968/main4.cpp new file mode 100644 index 00000000..e6323afc --- /dev/null +++ b/0501-1000/0968-Binary-Tree-Cameras/cpp-0968/main4.cpp @@ -0,0 +1,90 @@ +/// Source : https://leetcode.com/problems/binary-tree-cameras/ +/// Author : liuyubobobo +/// Time : 2019-03-18 + +#include +#include +#include + +using namespace std; + + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + + +/// Greedy +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +private: + int res; + unordered_set set; + +public: + int minCameraCover(TreeNode* root) { + + res = 0; + set.clear(); + dfs(root, NULL); + return res ? res : 1; + } + +private: + void dfs(TreeNode* root, TreeNode* parent){ + + if(!root) return; + + dfs(root->left, root); + dfs(root->right, root); + + if((!root->left || set.count(root->left)) && (!root->right || set.count(root->right))){ + if(!set.count(root) && !parent) res ++; + return; + } + + if((root->left && !set.count(root->left)) || + (root->right && !set.count(root->right))) { + res++; + if (root->left) set.insert(root->left); + if (root->right) set.insert(root->right); + set.insert(root); + if (parent) set.insert(parent); + } + return; + } +}; + + +int main() { + + TreeNode* root1 = new TreeNode(0); + root1->left = new TreeNode(0); + root1->left->left = new TreeNode(0); + root1->left->right = new TreeNode(0); + cout << Solution().minCameraCover(root1) << endl; + // 1 + + + TreeNode* root2 = new TreeNode(0); + root2->right = new TreeNode(0); + root2->right->right = new TreeNode(0); + root2->right->right->right = new TreeNode(0); + cout << Solution().minCameraCover(root2) << endl; + // 2 + + TreeNode* root3 = new TreeNode(0); + root3->left = new TreeNode(0); + root3->right = new TreeNode(0); + root3->right->right = new TreeNode(0); + cout << Solution().minCameraCover(root3) << endl; + // 2 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0969-Pancake-Sorting/cpp-0969/CMakeLists.txt b/0501-1000/0969-Pancake-Sorting/cpp-0969/CMakeLists.txt new file mode 100644 index 00000000..8a0a1cc7 --- /dev/null +++ b/0501-1000/0969-Pancake-Sorting/cpp-0969/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(B) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/0501-1000/0969-Pancake-Sorting/cpp-0969/main.cpp b/0501-1000/0969-Pancake-Sorting/cpp-0969/main.cpp new file mode 100644 index 00000000..d86afe93 --- /dev/null +++ b/0501-1000/0969-Pancake-Sorting/cpp-0969/main.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/pancake-sorting/ +/// Author : liuyubobobo +/// Time : 2018-01-05 + +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { +public: + vector pancakeSort(vector& A) { + + int n = A.size(); + + vector res; + for(int i = n - 1; i >= 0; i --){ + + int max_index = find(A.begin(), A.end(), i + 1) - A.begin(); + res.push_back(max_index + 1); + reverse(A.begin(), A.begin() + max_index + 1); + res.push_back(i + 1); + reverse(A.begin(), A.begin() + i + 1); + } + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0970-Powerful-Integers/cpp-0970/CMakeLists.txt b/0501-1000/0970-Powerful-Integers/cpp-0970/CMakeLists.txt new file mode 100644 index 00000000..c2b7a0b7 --- /dev/null +++ b/0501-1000/0970-Powerful-Integers/cpp-0970/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(A) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(A main2.cpp) \ No newline at end of file diff --git a/0501-1000/0970-Powerful-Integers/cpp-0970/main.cpp b/0501-1000/0970-Powerful-Integers/cpp-0970/main.cpp new file mode 100644 index 00000000..a91483a5 --- /dev/null +++ b/0501-1000/0970-Powerful-Integers/cpp-0970/main.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/powerful-integers/ +/// Author : liuyubobobo +/// Time : 2019-01-05 + +#include +#include +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(log(bound)^2) +/// Space Complexity: O(n) +class Solution { +public: + vector powerfulIntegers(int x, int y, int bound) { + + unordered_set res; + for(int i = 0;;i ++){ + int powx = pow(x, i); + if(powx > bound) break; + for(int j = 0;;j ++) { + int t = powx + pow(y, j); + if(t > bound) break; + res.insert(t); + if(y == 1) break; + } + if(x == 1) break; + } + return vector(res.begin(), res.end()); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0970-Powerful-Integers/cpp-0970/main2.cpp b/0501-1000/0970-Powerful-Integers/cpp-0970/main2.cpp new file mode 100644 index 00000000..f34cc579 --- /dev/null +++ b/0501-1000/0970-Powerful-Integers/cpp-0970/main2.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/powerful-integers/ +/// Author : liuyubobobo +/// Time : 2019-01-06 + +#include +#include +#include +#include + +using namespace std; + + +/// Brute Force +/// Calculate the x and y limits based on the constriction of bound :-) +/// +/// Time Complexity: O(log(bound)^2) +/// Space Complexity: O(n) +class Solution { +public: + vector powerfulIntegers(int x, int y, int bound) { + + unordered_set res; + for(int i = 0; i < 20; i ++){ + int powx = pow(x, i); + if(powx > bound) break; + for(int j = 0; j < 20; j ++) { + int t = powx + pow(y, j); + if(t > bound) break; + res.insert(t); + } + } + return vector(res.begin(), res.end()); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0971-Flip-Binary-Tree-To-Match-Preorder-Traversal/cpp-0971/CMakeLists.txt b/0501-1000/0971-Flip-Binary-Tree-To-Match-Preorder-Traversal/cpp-0971/CMakeLists.txt new file mode 100644 index 00000000..6324cdf7 --- /dev/null +++ b/0501-1000/0971-Flip-Binary-Tree-To-Match-Preorder-Traversal/cpp-0971/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(C) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/0501-1000/0971-Flip-Binary-Tree-To-Match-Preorder-Traversal/cpp-0971/main.cpp b/0501-1000/0971-Flip-Binary-Tree-To-Match-Preorder-Traversal/cpp-0971/main.cpp new file mode 100644 index 00000000..9998522a --- /dev/null +++ b/0501-1000/0971-Flip-Binary-Tree-To-Match-Preorder-Traversal/cpp-0971/main.cpp @@ -0,0 +1,88 @@ +/// Source : https://leetcode.com/problems/flip-binary-tree-to-match-preorder-traversal/ +/// Author : liuyubobobo +/// Time : 2018-01-05 + +#include +#include + +using namespace std; + + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector flipMatchVoyage(TreeNode* root, vector& voyage) { + + vector res; + int index = 0; + if(!go(root, index, voyage, res)) + return {-1}; + return res; + } + +private: + bool go(TreeNode* root, int& index, const vector& voyage, vector& res){ + + if(!root){ + if(index < voyage.size()) + return false; + return true; + } + + if(index >= voyage.size() || root->val != voyage[index]) + return false; + index ++; + + if(root->left && !root->right) + return go(root->left, index, voyage, res); + + if(root->right && !root->left) + return go(root->right, index, voyage, res); + + if(!root->left && !root->right) + return true; + + if(root->left->val != voyage[index]){ + res.push_back(root->val); + swap(root->left, root->right); + } + + if(!go(root->left, index, voyage, res)) + return false; + + return go(root->right, index, voyage, res); + } +}; + + +void print_vec(const vector& vec){ + + if(vec.size() == 0) + cout << "empty"; + else + for(int e: vec) + cout << e << " "; + cout << endl; +} + +int main() { + + // [1,null,2], [1,2] + TreeNode* root1 = new TreeNode(1); + root1->right = new TreeNode(2); + vector voyage1 = {1, 2}; + print_vec(Solution().flipMatchVoyage(root1, voyage1)); + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0972-Equal-Rational-Numbers/cpp-0972/CMakeLists.txt b/0501-1000/0972-Equal-Rational-Numbers/cpp-0972/CMakeLists.txt new file mode 100644 index 00000000..415dd8de --- /dev/null +++ b/0501-1000/0972-Equal-Rational-Numbers/cpp-0972/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(D) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(D main2.cpp) \ No newline at end of file diff --git a/0501-1000/0972-Equal-Rational-Numbers/cpp-0972/main.cpp b/0501-1000/0972-Equal-Rational-Numbers/cpp-0972/main.cpp new file mode 100644 index 00000000..9ac6ce5b --- /dev/null +++ b/0501-1000/0972-Equal-Rational-Numbers/cpp-0972/main.cpp @@ -0,0 +1,128 @@ +/// Source : https://leetcode.com/problems/equal-rational-numbers/ +/// Author : liuyubobobo +/// Time : 2018-01-05 + +#include +#include +#include +#include + +using namespace std; + + +/// Implement a Fraction class +/// For rational equal, try to compare the two fraction string +/// or adding 0.000...0001 to the smaller fraction and compare again +/// +/// Time Complexity: O(1) +/// Space Complexity: O(1) +class Fraction{ + +private: + const int n = 100; + string integer_part, decimal_part; + +public: + Fraction(const string& s){ + int dot = s.find('.'); + if(dot == string::npos){ + integer_part = s; + decimal_part = string(n, '0'); + } + else{ + integer_part = s.substr(0, dot); + string t = s.substr(dot + 1); + int l = t.find('('); + if(l == string::npos) + decimal_part = t + string(n - t.size(), '0'); + else{ + assert(t.back() == ')'); + decimal_part = t.substr(0, l); + string repeat_part = t.substr(l + 1, t.size() - decimal_part.size() - 2); + while(decimal_part.size() <= n) + decimal_part += repeat_part; + decimal_part = decimal_part.substr(0, n); + } + } + } + + bool rational_equal(Fraction& another){ + + if(*this == another) + return true; + + if(*this < another){ + Fraction x = this->add_a_bit(); + return x == another; + } + + Fraction x = another.add_a_bit(); + return *this == x; + } + + Fraction add_a_bit(){ + + int carry = 0; + string new_decimal_part = add_one(decimal_part, carry); + string new_integer_part = integer_part; + if(carry){ + carry = 0; + new_integer_part = add_one(integer_part, carry); + if(carry) new_integer_part = "1" + new_integer_part; + } + return Fraction(new_integer_part + "." + new_decimal_part); + } + + bool operator==(const Fraction& another){ + return this->integer_part == another.integer_part && + this->decimal_part == another.decimal_part; + } + + bool operator<(const Fraction& another){ + return this->integer_part < another.integer_part || + (this->integer_part == another.integer_part && + this->decimal_part < another.decimal_part); + } + +private: + string add_one(const string& s, int& ret_carry){ + + string res = s; + assert(res.size() > 0); + + res[res.size() - 1] += 1; + int carry = 0; + for(int i = (int)res.size() - 1; i >= 0; i --){ + int num = res[i] - '0' + carry; + res[i] = '0' + num % 10; + carry = num / 10; + } + ret_carry = carry; + return res; + } +}; + +class Solution { + +public: + bool isRationalEqual(string S, string T) { + + Fraction s = Fraction(S), t = Fraction(T); + return s.rational_equal(t); + } +}; + + +int main() { + + string S1 = "0.(52)", T1 = "0.5(25)"; + cout << Solution().isRationalEqual(S1, T1) << endl; + + string S2 = "0.1666(6)", T2 = "0.166(66)"; + cout << Solution().isRationalEqual(S2, T2) << endl; + + string S3 = "0.9(9)", T3 = "1."; + cout << Solution().isRationalEqual(S3, T3) << endl; + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0972-Equal-Rational-Numbers/cpp-0972/main2.cpp b/0501-1000/0972-Equal-Rational-Numbers/cpp-0972/main2.cpp new file mode 100644 index 00000000..5a68236f --- /dev/null +++ b/0501-1000/0972-Equal-Rational-Numbers/cpp-0972/main2.cpp @@ -0,0 +1,80 @@ +/// Source : https://leetcode.com/problems/equal-rational-numbers/ +/// Author : liuyubobobo +/// Time : 2018-01-06 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// Implement a Fraction class +/// Using geometric sum to deal with the repeat part :-) +/// +/// Time Complexity: O(1) +/// Space Complexity: O(1) +class Fraction{ + +private: + const double e = 1e-8; + double x = 0.0; + +public: + Fraction(const string& s){ + int dot = s.find('.'); + if(dot == string::npos) + x = atoi(s.c_str()); + else{ + x = atoi(s.substr(0, dot).c_str()); + + string t = s.substr(dot + 1); + int l = t.find('('); + if(l == string::npos) + x += (double)atoi(t.c_str()) * pow(0.1, t.size()); + else{ + assert(t.back() == ')'); + string decimal_part = t.substr(0, l); + x += (double)atoi(decimal_part.c_str()) * pow(0.1, decimal_part.size()); + + string repeat_part = t.substr(l + 1, t.size() - decimal_part.size() - 2); + double r = pow(0.1, repeat_part.size()); + x += (double)atoi(repeat_part.c_str()) * pow(0.1, decimal_part.size()) * r / (1 - r); + } + } + } + + bool rational_equal(Fraction& another){ + return abs(x - another.x) < e; + } +}; + +class Solution { + +public: + bool isRationalEqual(string S, string T) { + + Fraction s = Fraction(S), t = Fraction(T); + return s.rational_equal(t); + } +}; + + +int main() { + + string S1 = "0.(52)", T1 = "0.5(25)"; + cout << Solution().isRationalEqual(S1, T1) << endl; + // true + + string S2 = "0.1666(6)", T2 = "0.166(66)"; + cout << Solution().isRationalEqual(S2, T2) << endl; + // true + + string S3 = "0.9(9)", T3 = "1."; + cout << Solution().isRationalEqual(S3, T3) << endl; + // true + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0973-K-Closest-Points-to-Origin/cpp-0973/CMakeLists.txt b/0501-1000/0973-K-Closest-Points-to-Origin/cpp-0973/CMakeLists.txt new file mode 100644 index 00000000..67fd0212 --- /dev/null +++ b/0501-1000/0973-K-Closest-Points-to-Origin/cpp-0973/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(A) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(A main3.cpp) \ No newline at end of file diff --git a/0501-1000/0973-K-Closest-Points-to-Origin/cpp-0973/main.cpp b/0501-1000/0973-K-Closest-Points-to-Origin/cpp-0973/main.cpp new file mode 100644 index 00000000..62e63a4c --- /dev/null +++ b/0501-1000/0973-K-Closest-Points-to-Origin/cpp-0973/main.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/k-closest-points-to-origin/ +/// Author : liuyubobobo +/// Time : 2019-01-20 + +#include +#include +#include + +using namespace std; + + +/// Sorting +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + vector> kClosest(vector>& points, int K) { + + vector>> v; + for(const vector& point: points) + v.push_back(make_pair(point[0] * point[0] + point[1] * point[1], make_pair(point[0], point[1]))); + sort(v.begin(), v.end()); + + vector> res; + for(const pair>& p: v){ + res.push_back({p.second.first, p.second.second}); + if(res.size() == K) break; + } + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0973-K-Closest-Points-to-Origin/cpp-0973/main2.cpp b/0501-1000/0973-K-Closest-Points-to-Origin/cpp-0973/main2.cpp new file mode 100644 index 00000000..0f1e1c5f --- /dev/null +++ b/0501-1000/0973-K-Closest-Points-to-Origin/cpp-0973/main2.cpp @@ -0,0 +1,29 @@ +/// Source : https://leetcode.com/problems/k-closest-points-to-origin/ +/// Author : liuyubobobo +/// Time : 2019-01-12 + +#include +#include +#include + +using namespace std; + + +/// Sorting in the original array directly +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + vector> kClosest(vector>& points, int K) { + sort(points.begin(), points.end(), [](const vector& pa, const vector& pb){ + return pa[0] * pa[0] + pa[1] * pa[1] <= pb[0] * pb[0] + pb[1] * pb[1]; + }); + return vector>(points.begin(), points.begin() + K); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0973-K-Closest-Points-to-Origin/cpp-0973/main3.cpp b/0501-1000/0973-K-Closest-Points-to-Origin/cpp-0973/main3.cpp new file mode 100644 index 00000000..d68c1bf1 --- /dev/null +++ b/0501-1000/0973-K-Closest-Points-to-Origin/cpp-0973/main3.cpp @@ -0,0 +1,59 @@ +/// Source : https://leetcode.com/problems/k-closest-points-to-origin/ +/// Author : liuyubobobo +/// Time : 2019-01-21 + +#include +#include +#include + +using namespace std; + + +/// Quick Sort based k-selection algorithm +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + vector> kClosest(vector>& points, int K) { + + int n = points.size(); + selectionK(points, 0, n - 1, K - 1); + return vector>(points.begin(), points.begin() + K); + } + +private: + void selectionK(vector>& points, int start, int end, int K){ + + if(start >= end) return; + + int d = points[start][0] * points[start][0] + points[start][1] * points[start][1]; + int p = start; // arr[start + 1...p] < v + for(int i = start + 1; i <= end; i ++) + if(points[i][0] * points[i][0] + points[i][1] * points[i][1] <= d) + swap(points[i], points[++p]); + swap(points[start], points[p]); + + if(p == K) return; + if(p > K) selectionK(points, start, p - 1, K); + selectionK(points, p + 1, end, K); + } +}; + + +void print_vec(const vector>& vec){ + for(const vector& e: vec) + cout << "[" << e[0] << "," << e[1] << "] "; + cout << endl; +} + +int main() { + + vector> points1 = { + {68,97},{34,-84},{60,100},{2,31},{-27,-38},{-73,-74},{-55,-39},{62,91},{62,92},{-57,-67} + }; + int K1 = 5; + print_vec(Solution().kClosest(points1, K1)); + // [[2,31],[-27,-38],[-55,-39],[-57,-67],[34,-84]] + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0974-Subarray-Sums-Divisible-by-K/cpp-0974/CMakeLists.txt b/0501-1000/0974-Subarray-Sums-Divisible-by-K/cpp-0974/CMakeLists.txt new file mode 100644 index 00000000..c8cc528c --- /dev/null +++ b/0501-1000/0974-Subarray-Sums-Divisible-by-K/cpp-0974/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(C) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(C main2.cpp) \ No newline at end of file diff --git a/0501-1000/0974-Subarray-Sums-Divisible-by-K/cpp-0974/main.cpp b/0501-1000/0974-Subarray-Sums-Divisible-by-K/cpp-0974/main.cpp new file mode 100644 index 00000000..9f75702d --- /dev/null +++ b/0501-1000/0974-Subarray-Sums-Divisible-by-K/cpp-0974/main.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/subarray-sums-divisible-by-k/ +/// Author : liuyubobobo +/// Time : 2019-01-12 + +#include +#include + +using namespace std; + + +/// Pre Sums and Counts +/// to deal with negative number, calculate an offset to make all numbers positive +/// +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int subarraysDivByK(vector& A, int K) { + + int v = *min_element(A.begin(), A.end()); + if(v < 0){ + int x = 0; + while(v < 0) v += K, x += K; + + for(int &e: A) e += x; + } + + int n = A.size(); + vector pre(n + 1, 0); + for(int i = 0; i < n; i ++) + pre[i + 1] = pre[i] + A[i]; + + vector mod(K, 0); + for(int e: pre) + mod[e % K] ++; + + int res = 0; + for(int a: mod) + if(a >= 2) res += a * (a - 1) / 2; + + return res; + } +}; + + +int main() { + + vector A1 = {4,5,0,-2,-3,1}; + cout << Solution().subarraysDivByK(A1, 5) << endl; + // 7 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0974-Subarray-Sums-Divisible-by-K/cpp-0974/main2.cpp b/0501-1000/0974-Subarray-Sums-Divisible-by-K/cpp-0974/main2.cpp new file mode 100644 index 00000000..e9db71cc --- /dev/null +++ b/0501-1000/0974-Subarray-Sums-Divisible-by-K/cpp-0974/main2.cpp @@ -0,0 +1,49 @@ +/// Source : https://leetcode.com/problems/subarray-sums-divisible-by-k/ +/// Author : liuyubobobo +/// Time : 2019-01-21 + +#include +#include + +using namespace std; + + +/// Pre Sums and Counts +/// Using mod operations to deal with negative numbers +/// See comments below :-) +/// +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int subarraysDivByK(vector& A, int K) { + + int n = A.size(); + vector pre(n + 1, 0); + for(int i = 0; i < n; i ++) + pre[i + 1] = pre[i] + A[i]; + + vector mod(K, 0); + for(int e: pre) + mod[((e % K) + K) % K] ++; // deal with negative + // Attention: a negative number's mod is still negative + // to make it positive, + K + // since for positive numbers, +K will make the result >= K, + // so, we need to % K again + + int res = 0; + for(int a: mod) + if(a >= 2) res += a * (a - 1) / 2; + + return res; + } +}; + + +int main() { + + cout << (-4) % 3 << endl; + // -1: -4 = -1 * 3 - 1 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0975-Odd-Even-Jump/cpp-0975/CMakeLists.txt b/0501-1000/0975-Odd-Even-Jump/cpp-0975/CMakeLists.txt new file mode 100644 index 00000000..f0e51103 --- /dev/null +++ b/0501-1000/0975-Odd-Even-Jump/cpp-0975/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(D) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(D main3.cpp) \ No newline at end of file diff --git a/0501-1000/0975-Odd-Even-Jump/cpp-0975/main.cpp b/0501-1000/0975-Odd-Even-Jump/cpp-0975/main.cpp new file mode 100644 index 00000000..e5454a95 --- /dev/null +++ b/0501-1000/0975-Odd-Even-Jump/cpp-0975/main.cpp @@ -0,0 +1,158 @@ +/// Source : https://leetcode.com/problems/odd-even-jump/ +/// Author : liuyubobobo +/// Time : 2019-01-12 + +#include +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Using a self-implement BST to store the next step information :-) +/// Of course, using AVL or RBTree will be better, but for this problem, just BST is enough, +/// int main2, I will use RBTree in Standard Library :-) +/// +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class BST{ + +private: + class Node{ + public: + int v, smallest_index, largest_index; + Node* left, *right; + + Node(int v, int index): v(v), smallest_index(index), largest_index(index), + left(NULL), right(NULL){} + }; + + Node* root; + +public: + BST(): root(NULL){} + + void add(int v, int index){ + root = add(root, v, index); + } + + int larger_than(int x){ + Node* ret = larger_than(root, x); + if(!ret) return -1; + return ret->smallest_index; + } + + int smaller_than(int x){ + Node* ret = smaller_than(root, x); + if(!ret) return -1; + return ret->smallest_index; + } + +private: + Node* smaller_than(Node* node, int x){ + + if(!node) return NULL; + if(node->v == x) + return node; + if(node->v < x){ + Node* ret = smaller_than(node->right, x); + if(!ret) return node; + return ret; + } + return smaller_than(node->left, x); + } + + Node* larger_than(Node* node, int x){ + + if(!node) return NULL; + if(node->v == x) + return node; + if(node->v > x){ + Node* ret = larger_than(node->left, x); + if(!ret) return node; + return ret; + } + return larger_than(node->right, x); + } + + Node* add(Node* node, int x, int index){ + + if(!node) return new Node(x, index); + + if(x == node->v) + node->smallest_index = min(node->smallest_index, index), + node->largest_index = max(node->largest_index, index); + else if(x < node->v) + node->left = add(node->left, x, index); + else + node->right = add(node->right, x, index); + return node; + } +}; + +class Solution { +public: + int oddEvenJumps(const vector& A) { + + int n = A.size(); + + vector larger(n, -1); + larger[n - 1] = n - 1; + BST bst1; + bst1.add(A[n - 1], n - 1); + for(int i = n - 2; i >= 0; i --){ + larger[i] = bst1.larger_than(A[i]); + bst1.add(A[i], i); + } +// cout << "larger : "; +// for(int e: larger) +// cout << e << " "; +// cout << endl; + + vector smaller(n, -1); + smaller[n - 1] = n - 1; + BST bst2; + bst2.add(A[n - 1], n - 1); + for(int i = n - 2; i >= 0; i --){ + smaller[i] = bst2.smaller_than(A[i]); + bst2.add(A[i], i); + } +// cout << "smaller : "; +// for(int e: smaller) +// cout << e << " "; +// cout << endl; + + vector> dp(n, vector(2, false)); + dp[n - 1][0] = dp[n - 1][1] = true; + for(int i = n - 2; i >= 0; i --){ + if(larger[i] != -1) + dp[i][0] = dp[larger[i]][1]; + if(smaller[i] != -1) + dp[i][1] = dp[smaller[i]][0]; + } + + int res = 0; + for(int i = 0; i < n; i ++) + res += dp[i][0]; + return res; + } +}; + + +int main() { + + vector A1 = {10,13,12,14,15}; + cout << Solution().oddEvenJumps(A1) << endl; + // 2 + + vector A2 = {2,3,1,1,4}; + cout << Solution().oddEvenJumps(A2) << endl; + // 3 + + vector A3 = {5,1,3,4,2}; + cout << Solution().oddEvenJumps(A3) << endl; + // 3 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0975-Odd-Even-Jump/cpp-0975/main2.cpp b/0501-1000/0975-Odd-Even-Jump/cpp-0975/main2.cpp new file mode 100644 index 00000000..1c6bf090 --- /dev/null +++ b/0501-1000/0975-Odd-Even-Jump/cpp-0975/main2.cpp @@ -0,0 +1,83 @@ +/// Source : https://leetcode.com/problems/odd-even-jump/ +/// Author : liuyubobobo +/// Time : 2019-01-21 + +#include +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Using C++ STL map(a RBT underlying) to store the next step information :-) +/// +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + int oddEvenJumps(const vector& A) { + + int n = A.size(); + + vector larger(n, -1); + larger[n - 1] = n - 1; + set> bst1; + bst1.insert(make_pair(A[n - 1], n - 1)); + for(int i = n - 2; i >= 0; i --){ + set>::iterator iter = bst1.upper_bound(make_pair(A[i], i)); + if(iter != bst1.end()) larger[i] = iter->second; + bst1.insert(make_pair(A[i], i)); + } +// cout << "larger : "; +// for(int e: larger) +// cout << e << " "; +// cout << endl; + + vector smaller(n, -1); + smaller[n - 1] = n - 1; + set> bst2; + bst2.insert(make_pair(-A[n - 1], n - 1)); + for(int i = n - 2; i >= 0; i --){ + set>::iterator iter = bst2.upper_bound(make_pair(-A[i], i)); + if(iter != bst2.end()) smaller[i] = iter->second; + bst2.insert(make_pair(-A[i], i)); + } +// cout << "smaller : "; +// for(int e: smaller) +// cout << e << " "; +// cout << endl; + + vector> dp(n, vector(2, false)); + dp[n - 1][0] = dp[n - 1][1] = true; + for(int i = n - 2; i >= 0; i --){ + if(larger[i] != -1) + dp[i][0] = dp[larger[i]][1]; + if(smaller[i] != -1) + dp[i][1] = dp[smaller[i]][0]; + } + + int res = 0; + for(int i = 0; i < n; i ++) + res += dp[i][0]; + return res; + } +}; + + +int main() { + + vector A1 = {10,13,12,14,15}; + cout << Solution().oddEvenJumps(A1) << endl; + // 2 + + vector A2 = {2,3,1,1,4}; + cout << Solution().oddEvenJumps(A2) << endl; + // 3 + + vector A3 = {5,1,3,4,2}; + cout << Solution().oddEvenJumps(A3) << endl; + // 3 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0975-Odd-Even-Jump/cpp-0975/main3.cpp b/0501-1000/0975-Odd-Even-Jump/cpp-0975/main3.cpp new file mode 100644 index 00000000..074abec3 --- /dev/null +++ b/0501-1000/0975-Odd-Even-Jump/cpp-0975/main3.cpp @@ -0,0 +1,79 @@ +/// Source : https://leetcode.com/problems/odd-even-jump/ +/// Author : liuyubobobo +/// Time : 2019-03-16 + +#include +#include +#include +#include + +using namespace std; + + +/// Monotonic Stack +/// +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + int oddEvenJumps(const vector& A) { + + int n = A.size(); + + vector> data(n); + for(int i = 0; i < n; i ++) data[i] = make_pair(A[i], i); + + vector larger(n, -1); + sort(data.begin(), data.end()); + stack s1; + s1.push(data[0].second); + for(int i = 1; i < n; i ++){ + while(!s1.empty() && s1.top() < data[i].second) + larger[s1.top()] = data[i].second, s1.pop(); + s1.push(data[i].second); + } + + vector smaller(n, -1); + for(int i = 0; i < n; i ++) data[i] = make_pair(-A[i], i); + sort(data.begin(), data.end()); + stack s2; + s2.push(data[0].second); + for(int i = 1; i < n; i ++){ + while(!s2.empty() && s2.top() < data[i].second) + smaller[s2.top()] = data[i].second, s2.pop(); + s2.push(data[i].second); + } + + vector> dp(n, vector(2, false)); + dp[n - 1][0] = dp[n - 1][1] = true; + for(int i = n - 2; i >= 0; i --){ + if(larger[i] != -1) + dp[i][0] = dp[larger[i]][1]; + if(smaller[i] != -1) + dp[i][1] = dp[smaller[i]][0]; + } + + int res = 0; + for(int i = 0; i < n; i ++) + res += dp[i][0]; + return res; + } +}; + + +int main() { + + vector A1 = {10,13,12,14,15}; + cout << Solution().oddEvenJumps(A1) << endl; + // 2 + + vector A2 = {2,3,1,1,4}; + cout << Solution().oddEvenJumps(A2) << endl; + // 3 + + vector A3 = {5,1,3,4,2}; + cout << Solution().oddEvenJumps(A3) << endl; + // 3 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0976-Largest-Perimeter-Triangle/cpp-0976/CMakeLists.txt b/0501-1000/0976-Largest-Perimeter-Triangle/cpp-0976/CMakeLists.txt new file mode 100644 index 00000000..8a0a1cc7 --- /dev/null +++ b/0501-1000/0976-Largest-Perimeter-Triangle/cpp-0976/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(B) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/0501-1000/0976-Largest-Perimeter-Triangle/cpp-0976/main.cpp b/0501-1000/0976-Largest-Perimeter-Triangle/cpp-0976/main.cpp new file mode 100644 index 00000000..3ed5de2b --- /dev/null +++ b/0501-1000/0976-Largest-Perimeter-Triangle/cpp-0976/main.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/largest-perimeter-triangle/ +/// Author : liuyubobobo +/// Time : 2019-01-12 + +#include +#include +#include + +using namespace std; + + +/// Sort and Brute Force +/// Time Complexity: O(n^2) +/// Space Complexity: O(1) +class Solution { +public: + int largestPerimeter(vector& A) { + + sort(A.begin(), A.end()); + + int n = A.size(); + int best = 0; + for(int i = n - 1; i >= 0; i --) + for(int j = i - 1; j >= 0; j --){ + if(j - 1 >= 0 && A[j - 1] > A[i] - A[j]) + best = max(best, A[i] + A[j] + A[j - 1]); + else + break; + } + return best; + } +}; + + +int main() { + + vector A1 = {2, 3, 3, 4}; + cout << Solution().largestPerimeter(A1) << endl; + // 10 + + vector A2 = {2, 3, 3, 6}; + cout << Solution().largestPerimeter(A2) << endl; + // 8 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0976-Largest-Perimeter-Triangle/cpp-0976/main2.cpp b/0501-1000/0976-Largest-Perimeter-Triangle/cpp-0976/main2.cpp new file mode 100644 index 00000000..3cb3c95b --- /dev/null +++ b/0501-1000/0976-Largest-Perimeter-Triangle/cpp-0976/main2.cpp @@ -0,0 +1,39 @@ +/// Source : https://leetcode.com/problems/largest-perimeter-triangle/ +/// Author : liuyubobobo +/// Time : 2019-01-21 + +#include +#include +#include + +using namespace std; + + +/// Sort and Greedy +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + int largestPerimeter(vector& A) { + + sort(A.begin(), A.end()); + for(int i = A.size() - 3; i >= 0; i --) + if(A[i] + A[i + 1] > A[i + 2]) + return A[i] + A[i + 1] + A[i + 2]; + return 0; + } +}; + + +int main() { + + vector A1 = {2, 3, 3, 4}; + cout << Solution().largestPerimeter(A1) << endl; + // 10 + + vector A2 = {2, 3, 3, 6}; + cout << Solution().largestPerimeter(A2) << endl; + // 8 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0977-Squares-of-a-Sorted-Arrays/cpp-0977/CMakeLists.txt b/0501-1000/0977-Squares-of-a-Sorted-Arrays/cpp-0977/CMakeLists.txt new file mode 100644 index 00000000..88857baf --- /dev/null +++ b/0501-1000/0977-Squares-of-a-Sorted-Arrays/cpp-0977/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(A) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/0501-1000/0977-Squares-of-a-Sorted-Arrays/cpp-0977/main.cpp b/0501-1000/0977-Squares-of-a-Sorted-Arrays/cpp-0977/main.cpp new file mode 100644 index 00000000..1a711d0b --- /dev/null +++ b/0501-1000/0977-Squares-of-a-Sorted-Arrays/cpp-0977/main.cpp @@ -0,0 +1,29 @@ +/// Source : https://leetcode.com/problems/squares-of-a-sorted-array/ +/// Author : liuyubobobo +/// Time : 2019-01-19 + +#include +#include + +using namespace std; + + +/// Sorting +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + vector sortedSquares(vector& A) { + + for(int& e: A) + e = e * e; + sort(A.begin(), A.end()); + return A; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0977-Squares-of-a-Sorted-Arrays/cpp-0977/main2.cpp b/0501-1000/0977-Squares-of-a-Sorted-Arrays/cpp-0977/main2.cpp new file mode 100644 index 00000000..1ece13d8 --- /dev/null +++ b/0501-1000/0977-Squares-of-a-Sorted-Arrays/cpp-0977/main2.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/squares-of-a-sorted-array/ +/// Author : liuyubobobo +/// Time : 2019-01-20 + +#include +#include + +using namespace std; + + +/// Two Pointers +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector sortedSquares(vector& A) { + + int n = A.size(), i = 0, j = n -1; + vector ret; + while(i <= j) + if(abs(A[i]) > abs(A[j])) + ret.push_back(A[i] * A[i]), i ++; + else + ret.push_back(A[j] * A[j]), j --; + reverse(ret.begin(), ret.end()); + return ret; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0978-Longest-Turbulent-Subarray/cpp-0978/CMakeLists.txt b/0501-1000/0978-Longest-Turbulent-Subarray/cpp-0978/CMakeLists.txt new file mode 100644 index 00000000..8a0a1cc7 --- /dev/null +++ b/0501-1000/0978-Longest-Turbulent-Subarray/cpp-0978/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(B) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/0501-1000/0978-Longest-Turbulent-Subarray/cpp-0978/main.cpp b/0501-1000/0978-Longest-Turbulent-Subarray/cpp-0978/main.cpp new file mode 100644 index 00000000..6d9dbd58 --- /dev/null +++ b/0501-1000/0978-Longest-Turbulent-Subarray/cpp-0978/main.cpp @@ -0,0 +1,65 @@ +/// Source : https://leetcode.com/problems/longest-turbulent-subarray/ +/// Author : liuyubobobo +/// Time : 2018-01-19 +/// Updated: 2021-02-08 + +#include +#include + +using namespace std; + + +/// Precalculate the diff array +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int maxTurbulenceSize(vector& A) { + + vector diff; + int res = 0; + for(int i = 1; i < A.size(); i ++){ + diff.push_back(get_sign(A[i] - A[i - 1])); + if(diff.back() != 0) res = 1; + } + + for(int start = 0, i = start + 1; i < diff.size(); ) + if((diff[i - 1] == 1 && diff[i] == -1) || (diff[i - 1] == -1 && diff[i] == 1)){ + res = max(res, i + 1 - start); + i ++; + } + else start = i, i = start + 1; + return res + 1; + } + +private: + int get_sign(int x){ + return x > 0 ? 1 : (x == 0 ? 0 : -1); + } +}; + + +int main() { + + vector A1 = {9,4,2,10,7,8,8,1,9}; + cout << Solution().maxTurbulenceSize(A1) << endl; + // 5 + + vector A2 = {4,8,12,16}; + cout << Solution().maxTurbulenceSize(A2) << endl; + // 2 + + vector A3 = {100}; + cout << Solution().maxTurbulenceSize(A3) << endl; + // 1 + + vector A4 = {9, 9}; + cout << Solution().maxTurbulenceSize(A4) << endl; + // 1 + + vector A5 = {9, 9, 9}; + cout << Solution().maxTurbulenceSize(A5) << endl; + // 1 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0979-Distribute-Coins-in-Binary-Tree/cpp-0979/CMakeLists.txt b/0501-1000/0979-Distribute-Coins-in-Binary-Tree/cpp-0979/CMakeLists.txt new file mode 100644 index 00000000..6324cdf7 --- /dev/null +++ b/0501-1000/0979-Distribute-Coins-in-Binary-Tree/cpp-0979/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(C) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/0501-1000/0979-Distribute-Coins-in-Binary-Tree/cpp-0979/main.cpp b/0501-1000/0979-Distribute-Coins-in-Binary-Tree/cpp-0979/main.cpp new file mode 100644 index 00000000..63830944 --- /dev/null +++ b/0501-1000/0979-Distribute-Coins-in-Binary-Tree/cpp-0979/main.cpp @@ -0,0 +1,63 @@ +/// Source : https://leetcode.com/problems/distribute-coins-in-binary-tree/ +/// Author : liuyubobobo +/// Time : 2019-01-20 + +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(1) + +/// 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: + int distributeCoins(TreeNode* root) { + + int res = 0; + dfs(root, res); + return res; + } + +private: + int dfs(TreeNode* node, int& res){ + + if(!node) return 0; + + int l = dfs(node->left, res); + int r = dfs(node->right, res); + res += abs(l) + abs(r); + return node->val + l + r - 1; + } +}; + + +int main() { + + TreeNode* root = new TreeNode(3); + root->left = new TreeNode(0); + root->right = new TreeNode(0); + cout << Solution().distributeCoins(root) << endl; + // 2 + + // [5,0,0,null,null,0,0,3,null,null,0,null,null,null,0] + // 13 + + // [3,null,0,0,null,0,null,2] + // 4 + + // [0,2,3,0,0,null,null,1] + // 5 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0980-Unique-Paths-III/cpp-980/CMakeLists.txt b/0501-1000/0980-Unique-Paths-III/cpp-980/CMakeLists.txt new file mode 100644 index 00000000..b79820ad --- /dev/null +++ b/0501-1000/0980-Unique-Paths-III/cpp-980/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(cpp_980) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_980 main3.cpp) \ No newline at end of file diff --git a/0501-1000/0980-Unique-Paths-III/cpp-980/main.cpp b/0501-1000/0980-Unique-Paths-III/cpp-980/main.cpp new file mode 100644 index 00000000..0516b7e2 --- /dev/null +++ b/0501-1000/0980-Unique-Paths-III/cpp-980/main.cpp @@ -0,0 +1,86 @@ +/// Source : https://leetcode.com/problems/unique-paths-iii/ +/// Author : liuyubobobo +/// Time : 2019-01-21 + +#include +#include + +using namespace std; + + +/// Backtrack +/// Time Complexity: O(4 ^ (m * n)) +/// Space Complexity: O(m * n) +class Solution { + +private: + int m, n, end; + const int d[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; + +public: + int uniquePathsIII(vector>& grid) { + + m = grid.size(); + n = grid[0].size(); + int start, todo = 0; + for(int i = 0; i < m; i ++) + for(int j = 0; j < n; j ++){ + int pos = i * n + j; + if(grid[i][j] == 1) + start = pos; + else if(grid[i][j] == 2) + end = pos, grid[i][j] = 0, todo ++; + else if(grid[i][j] == 0) + todo ++; + } + return dfs(grid, start, todo); + } + +private: + int dfs(vector>& grid, int pos, int todo){ + + if(pos == end) + return !todo; + + int x = pos / n, y = pos % n, res = 0; + for(int i = 0; i < 4; i ++){ + int nextx = x + d[i][0], nexty = y + d[i][1]; + if(nextx >= 0 && nextx < m && nexty >= 0 && nexty < n && grid[nextx][nexty] == 0){ + grid[nextx][nexty] = 1; + res += dfs(grid, nextx * n + nexty, todo - 1); + grid[nextx][nexty] = 0; + } + } + return res; + } +}; + + +int main() { + + vector> g0 = { + {1,0}, + {0,0}, + {0,2} + }; + cout << Solution().uniquePathsIII(g0) << endl; + // 1 + + vector> g1 = { + {1,0,0,0}, + {0,0,0,0}, + {0,0,2,-1} + }; + cout << Solution().uniquePathsIII(g1) << endl; + // 2 + + vector> g2 = { + {1,0,0,0}, + {0,0,0,0}, + {0,0,0,2} + }; + cout << Solution().uniquePathsIII(g2) << endl; + // 4 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0980-Unique-Paths-III/cpp-980/main2.cpp b/0501-1000/0980-Unique-Paths-III/cpp-980/main2.cpp new file mode 100644 index 00000000..69d4ed59 --- /dev/null +++ b/0501-1000/0980-Unique-Paths-III/cpp-980/main2.cpp @@ -0,0 +1,99 @@ +/// Source : https://leetcode.com/problems/unique-paths-iii/ +/// Author : liuyubobobo +/// Time : 2020-04-28 + +#include +#include + +using namespace std; + + +/// State Compression + Memory Search +/// Time Complexity: O(m * n * 2 ^ (m * n)) +/// Space Complexity: O(m * n * 2 ^ (m * n)) +class Solution { + +private: + int m, n, end; + const int d[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; + +public: + int uniquePathsIII(vector>& grid) { + + m = grid.size(), n = grid[0].size(); + int start, state = 0; + for(int i = 0; i < m; i ++) + for(int j = 0; j < n; j ++){ + int pos = i * n + j; + if(grid[i][j] == 1) + start = pos; + else if(grid[i][j] == 2) + end = pos, grid[i][j] = 0; + else if(grid[i][j] == -1) + state |= (1 << pos); + } + vector> dp((m * n), vector(1 << (m * n), -1)); + return dfs(grid, state | (1 << start), start, dp); + } + +private: + int dfs(vector>& grid, int state, int pos, vector>& dp){ + + if(pos == end) + return state == (1 << (m * n)) - 1 ? 1 : 0; + if(dp[pos][state] != -1) return dp[pos][state]; + + int x = pos / n, y = pos % n, res = 0; + for(int i = 0; i < 4; i ++){ + int nextx = x + d[i][0], nexty = y + d[i][1]; + int next = nextx * n + nexty; + if(in_area(nextx, nexty) && (state & (1 << next)) == 0){ + res += dfs(grid, state | (1 << next), next, dp); + } + } + return dp[pos][state] = res; + } + + bool in_area(int x, int y){ + return x >= 0 && x < m && y >= 0 && y < n; + } +}; + + +int main() { + + vector> g0 = { + {1,0}, + {0,0}, + {0,2} + }; + cout << Solution().uniquePathsIII(g0) << endl; + // 1 + + vector> g1 = { + {1,0,0,0}, + {0,0,0,0}, + {0,0,2,-1} + }; + cout << Solution().uniquePathsIII(g1) << endl; + // 2 + + vector> g2 = { + {1,0,0,0}, + {0,0,0,0}, + {0,0,0,2} + }; + cout << Solution().uniquePathsIII(g2) << endl; + // 4 + + vector> g3 = { + {0,0,0,0,0}, + {0,2,1,0,0}, + {0,0,0,0,0}, + {0,0,0,0,0} + }; + cout << Solution().uniquePathsIII(g3) << endl; + // 8 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0980-Unique-Paths-III/cpp-980/main3.cpp b/0501-1000/0980-Unique-Paths-III/cpp-980/main3.cpp new file mode 100644 index 00000000..ef28d923 --- /dev/null +++ b/0501-1000/0980-Unique-Paths-III/cpp-980/main3.cpp @@ -0,0 +1,99 @@ +/// Source : https://leetcode.com/problems/unique-paths-iii/ +/// Author : liuyubobobo +/// Time : 2020-04-28 + +#include +#include +#include + +using namespace std; + + +/// State Compression + Dynamic Programming +/// Time Complexity: O(m * n * 2 ^ (m * n)) +/// Space Complexity: O(m * n * 2 ^ (m * n)) +class Solution { + +private: + int m, n; + const int dirs[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; + +public: + int uniquePathsIII(vector>& grid) { + + m = grid.size(), n = grid[0].size(); + int start, end, k = 0; + map posToIndex, indexToPos; + for(int i = 0; i < m; i ++) + for(int j = 0; j < n; j ++){ + int pos = i * n + j; + if(grid[i][j] == 1) + start = pos, grid[i][j] = 0; + else if(grid[i][j] == 2) + end = pos, grid[i][j] = 0; + + if(grid[i][j] == -1) continue; + + posToIndex[pos] = k; + indexToPos[k] = pos; + k ++; + } + vector> dp(k, vector(1 << k, 0)); + dp[posToIndex[start]][1 << posToIndex[start]] = 1; + for(int state = 1; state < (1 << k); state ++) + for(int i = 0; i < k; i ++) + if((state & (1 << i)) && dp[i][state]){ + int pos = indexToPos[i], x = pos / n, y = pos %n; + for(int d = 0; d < 4; d ++) { + int nextx = x + dirs[d][0], nexty = y + dirs[d][1], next = nextx * n + nexty; + if(in_area(nextx, nexty) && grid[nextx][nexty] != -1 && (state & (1 << next)) == 0) + dp[posToIndex[next]][state | (1 << posToIndex[next])] += dp[i][state]; + } + } + return dp[posToIndex[end]][(1 << k) - 1]; + } + +private: + bool in_area(int x, int y){ + return x >= 0 && x < m && y >= 0 && y < n; + } +}; + + +int main() { + + vector> g0 = { + {1,0}, + {0,0}, + {0,2} + }; + cout << Solution().uniquePathsIII(g0) << endl; + // 1 + + vector> g1 = { + {1,0,0,0}, + {0,0,0,0}, + {0,0,2,-1} + }; + cout << Solution().uniquePathsIII(g1) << endl; + // 2 + + vector> g2 = { + {1,0,0,0}, + {0,0,0,0}, + {0,0,0,2} + }; + cout << Solution().uniquePathsIII(g2) << endl; + // 4 + + vector> g3 = { + {0,0,0,0,0}, + {0,2,1,0,0}, + {0,0,0,0,0}, + {0,0,0,0,0} + }; + cout << Solution().uniquePathsIII(g3) << endl; + // 8 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0980-Unique-Paths-III/java-0980/src/Solution.java b/0501-1000/0980-Unique-Paths-III/java-0980/src/Solution.java new file mode 100644 index 00000000..6f687c84 --- /dev/null +++ b/0501-1000/0980-Unique-Paths-III/java-0980/src/Solution.java @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/unique-paths-iii/ +/// Author : liuyubobobo +/// Time : 2019-01-21 + +/// Backtrack +/// Time Complexity: O(4 ^ (m * n)) +/// Space Complexity: O(m * n) +class Solution { + + private int m, n, end; + private int d[][] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; + + public int uniquePathsIII(int[][] grid) { + + m = grid.length; + n = grid[0].length; + int start = 0, todo = 0; + for(int i = 0; i < m; i ++) + for(int j = 0; j < n; j ++){ + int pos = i * n + j; + if(grid[i][j] == 1) + start = pos; + else if(grid[i][j] == 2){ + end = pos; + grid[i][j] = 0; + todo ++; + } + else if(grid[i][j] == 0) + todo ++; + } + return dfs(grid, start, todo); + } + + private int dfs(int[][] grid, int pos, int todo){ + + if(pos == end) + return todo == 0 ? 1 : 0; + + int x = pos / n, y = pos % n, res = 0; + for(int i = 0; i < 4; i ++){ + int nextx = x + d[i][0], nexty = y + d[i][1]; + if(nextx >= 0 && nextx < m && nexty >= 0 && nexty < n && grid[nextx][nexty] == 0) { + grid[nextx][nexty] = 1; + res += dfs(grid, nextx * n + nexty, todo - 1); + grid[nextx][nexty] = 0; + } + } + return res; + } +} \ No newline at end of file diff --git a/0501-1000/0980-Unique-Paths-III/java-0980/src/Solution2.java b/0501-1000/0980-Unique-Paths-III/java-0980/src/Solution2.java new file mode 100644 index 00000000..8baa3bbe --- /dev/null +++ b/0501-1000/0980-Unique-Paths-III/java-0980/src/Solution2.java @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/unique-paths-iii/ +/// Author : liuyubobobo +/// Time : 2019-01-21 + +/// Memory Search +/// Time Complexity: O(m * n * 2 ^ (m * n)) +/// Space Complexity: O(m * n) +class Solution2 { + + private int m, n, end; + private int d[][] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; + + public int uniquePathsIII(int[][] grid) { + + m = grid.length; + n = grid[0].length; + int start = 0, state = 0; + for(int i = 0; i < m; i ++) + for(int j = 0; j < n; j ++){ + int pos = i * n + j; + if(grid[i][j] == 1){ + start = pos; + state += (1 << pos); + } + else if(grid[i][j] == 2){ + end = pos; + grid[i][j] = 0; + } + else if(grid[i][j] == -1) + state += (1 << pos); + } + + int[][] dp = new int[1 << (m * n)][m * n]; + for(int i = 0; i < (1 << (m * n)); i ++) + for(int j = 0; j < m * n; j ++) + dp[i][j] = -1; + return dfs(grid, state, start, dp); + } + + private int dfs(int[][] grid, int state, int pos, int[][] dp){ + + if(pos == end) + return state == (1 << m * n) - 1 ? 1 : 0; + + if(dp[state][pos] != -1) + return dp[state][pos]; + + int x = pos / n, y = pos % n, res = 0; + for(int i = 0; i < 4; i ++){ + int nextx = x + d[i][0], nexty = y + d[i][1]; + int next = nextx * n + nexty; + if(nextx >= 0 && nextx < m && nexty >= 0 && nexty < n && (state & (1 << next)) == 0) + res += dfs(grid, state | (1 << next), next, dp); + } + return dp[state][pos] = res; + } +} \ No newline at end of file diff --git a/0501-1000/0981-Time-Based-Key-Value-Store/cpp-0981/CMakeLists.txt b/0501-1000/0981-Time-Based-Key-Value-Store/cpp-0981/CMakeLists.txt new file mode 100644 index 00000000..35590b8b --- /dev/null +++ b/0501-1000/0981-Time-Based-Key-Value-Store/cpp-0981/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(B) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(B main3.cpp) \ No newline at end of file diff --git a/0501-1000/0981-Time-Based-Key-Value-Store/cpp-0981/main.cpp b/0501-1000/0981-Time-Based-Key-Value-Store/cpp-0981/main.cpp new file mode 100644 index 00000000..92eb75f6 --- /dev/null +++ b/0501-1000/0981-Time-Based-Key-Value-Store/cpp-0981/main.cpp @@ -0,0 +1,62 @@ +/// Source : https://leetcode.com/problems/time-based-key-value-store/ +/// Author : liuyubobobo +/// Time : 2019-01-26 + +#include +#include +#include + + +/// Using TreeSet to store (time, value) pair information for each key +/// Time Complexity: init: O(1) +/// set: O(logn) +/// get: O(logn) +/// Space Complexity: O(n) +class TimeMap { + +private: + std::unordered_map>> map; // key -> (time, value) + +public: + /** Initialize your data structure here. */ + TimeMap() {} + + void set(std::string key, std::string value, int timestamp) { + map[key].insert(make_pair(timestamp, value)); + } + + std::string get(std::string key, int timestamp) { + + std::set>::iterator iter = + map[key].lower_bound(std::make_pair(timestamp, "")); + if(iter == map[key].end() || iter->first > timestamp){ + if(iter == map[key].begin()) return ""; + iter --; + } + return iter->second; + } +}; + + +int main() { + + TimeMap timeMap; + timeMap.set("foo", "bar", 1); + std::cout << timeMap.get("foo", 1) << std::endl; + // bar + + std::cout << timeMap.get("foo", 3) << std::endl; + // bar + + timeMap.set("foo", "bar2", 4); + std::cout << timeMap.get("foo", 4) << std::endl; + // bar2 + + std::cout << timeMap.get("foo", 5) << std::endl; + // bar2 + + std::cout << timeMap.get("foo", 1) << std::endl; + // bar + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0981-Time-Based-Key-Value-Store/cpp-0981/main2.cpp b/0501-1000/0981-Time-Based-Key-Value-Store/cpp-0981/main2.cpp new file mode 100644 index 00000000..1895b67c --- /dev/null +++ b/0501-1000/0981-Time-Based-Key-Value-Store/cpp-0981/main2.cpp @@ -0,0 +1,64 @@ +/// Source : https://leetcode.com/problems/time-based-key-value-store/ +/// Author : liuyubobobo +/// Time : 2019-01-28 + +#include +#include +#include + +using namespace std; + + +/// Using TreeMap to store (time, value) pair information for each key +/// Time Complexity: init: O(1) +/// set: O(logn) +/// get: O(logn) +/// Space Complexity: O(n) +class TimeMap { + +private: + unordered_map> timeMap; // key -> (time, value) + +public: + /** Initialize your data structure here. */ + TimeMap() {} + + void set(string key, string value, int timestamp) { + timeMap[key][timestamp] = value; + } + + string get(string key, int timestamp) { + + map::iterator iter = + timeMap[key].lower_bound(timestamp); + if(iter == timeMap[key].end() || iter->first > timestamp){ + if(iter == timeMap[key].begin()) return ""; + iter --; + } + return iter->second; + } +}; + + +int main() { + + TimeMap timeMap; + timeMap.set("foo", "bar", 1); + cout << timeMap.get("foo", 1) << endl; + // bar + + cout << timeMap.get("foo", 3) << endl; + // bar + + timeMap.set("foo", "bar2", 4); + cout << timeMap.get("foo", 4) << endl; + // bar2 + + cout << timeMap.get("foo", 5) << endl; + // bar2 + + cout << timeMap.get("foo", 1) << endl; + // bar + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0981-Time-Based-Key-Value-Store/cpp-0981/main3.cpp b/0501-1000/0981-Time-Based-Key-Value-Store/cpp-0981/main3.cpp new file mode 100644 index 00000000..dc85371f --- /dev/null +++ b/0501-1000/0981-Time-Based-Key-Value-Store/cpp-0981/main3.cpp @@ -0,0 +1,69 @@ +/// Source : https://leetcode.com/problems/time-based-key-value-store/ +/// Author : liuyubobobo +/// Time : 2019-01-28 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// Since the timestamp is strictly increasing, +/// We can just use array to store all data +/// and use binary search directly for the array corresponding to each key +/// +/// Time Complexity: init: O(1) +/// set: O(1) +/// get: O(logn) +/// Space Complexity: O(n) +class TimeMap { + +private: + unordered_map>> timeMap; // key -> (time, value) + +public: + /** Initialize your data structure here. */ + TimeMap() {} + + void set(string key, string value, int timestamp) { + timeMap[key].push_back(make_pair(timestamp, value)); + } + + string get(string key, int timestamp) { + + vector>::iterator iter = + lower_bound(timeMap[key].begin(), timeMap[key].end(), make_pair(timestamp, string(""))); + if(iter == timeMap[key].end() || iter->first > timestamp){ + if(iter == timeMap[key].begin()) return ""; + iter --; + } + return iter->second; + } +}; + + +int main() { + + TimeMap timeMap; + timeMap.set("foo", "bar", 1); + cout << timeMap.get("foo", 1) << endl; + // bar + + cout << timeMap.get("foo", 3) << endl; + // bar + + timeMap.set("foo", "bar2", 4); + cout << timeMap.get("foo", 4) << endl; + // bar2 + + cout << timeMap.get("foo", 5) << endl; + // bar2 + + cout << timeMap.get("foo", 1) << endl; + // bar + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0982-Triples-with-Bitwise-AND-Equal-To-Zero/cpp-0982/CMakeLists.txt b/0501-1000/0982-Triples-with-Bitwise-AND-Equal-To-Zero/cpp-0982/CMakeLists.txt new file mode 100644 index 00000000..7d2a9b26 --- /dev/null +++ b/0501-1000/0982-Triples-with-Bitwise-AND-Equal-To-Zero/cpp-0982/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(D) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(D main.cpp) \ No newline at end of file diff --git a/0501-1000/0982-Triples-with-Bitwise-AND-Equal-To-Zero/cpp-0982/main.cpp b/0501-1000/0982-Triples-with-Bitwise-AND-Equal-To-Zero/cpp-0982/main.cpp new file mode 100644 index 00000000..257438da --- /dev/null +++ b/0501-1000/0982-Triples-with-Bitwise-AND-Equal-To-Zero/cpp-0982/main.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/triples-with-bitwise-and-equal-to-zero/ +/// Author : liuyubobobo +/// Time : 2019-01-26 + +#include +#include + +using namespace std; + + +/// Using HashSet +/// Time Complexity: O(max(2^16 * n, n^2)) +/// Space Complexity: O(2^16 * n) +class Solution { +public: + int countTriplets(vector& A) { + + int n = A.size(); + vector table(65536, 0); + for(int a: A) + for(int i = 0; i < 65536; i ++) + if(!(a & i)) + table[i] ++; + + int res = 0; + for(int i = 0; i < n; i ++) + for(int j = 0; j < n; j ++) + res += table[A[i] & A[j]]; + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0983-Minimum-Cost-For-Tickets/cpp-0983/CMakeLists.txt b/0501-1000/0983-Minimum-Cost-For-Tickets/cpp-0983/CMakeLists.txt new file mode 100644 index 00000000..97a4f1eb --- /dev/null +++ b/0501-1000/0983-Minimum-Cost-For-Tickets/cpp-0983/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(C) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(C main6.cpp) \ No newline at end of file diff --git a/0501-1000/0983-Minimum-Cost-For-Tickets/cpp-0983/main.cpp b/0501-1000/0983-Minimum-Cost-For-Tickets/cpp-0983/main.cpp new file mode 100644 index 00000000..870e031f --- /dev/null +++ b/0501-1000/0983-Minimum-Cost-For-Tickets/cpp-0983/main.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/minimum-cost-for-tickets/ +/// Author : liuyubobobo +/// Time : 2019-01-28 + +#include +#include +#include +#include + +using namespace std; + + +/// Memory Search - Day Variant +/// Time Complexity: O(365) +/// Space Complexity: O(len(days)) +class Solution { +public: + int mincostTickets(vector& days, vector& costs) { + + unordered_set day_set; + for(int day: days) + day_set.insert(day); + + vector dp(366, -1); + return dfs(0, day_set, costs, dp); + } + +private: + int dfs(int day, const unordered_set day_set, const vector& costs, + vector& dp){ + + if(day > 365) return 0; + if(dp[day] != -1) return dp[day]; + + if(!day_set.count(day)) + return dp[day] = dfs(day + 1, day_set, costs, dp); + + int res = costs[0] + dfs(day + 1, day_set, costs, dp); + res = min(res, costs[1] + dfs(day + 7, day_set, costs, dp)); + res = min(res, costs[2] + dfs(day + 30, day_set, costs, dp)); + + return dp[day] = res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0983-Minimum-Cost-For-Tickets/cpp-0983/main2.cpp b/0501-1000/0983-Minimum-Cost-For-Tickets/cpp-0983/main2.cpp new file mode 100644 index 00000000..1bde6d78 --- /dev/null +++ b/0501-1000/0983-Minimum-Cost-For-Tickets/cpp-0983/main2.cpp @@ -0,0 +1,42 @@ +/// Source : https://leetcode.com/problems/minimum-cost-for-tickets/ +/// Author : liuyubobobo +/// Time : 2019-01-28 + +#include +#include +#include +#include + +using namespace std; + + +/// Dynamic Programming - Day Variant +/// Time Complexity: O(365) +/// Space Complexity: O(len(days)) +class Solution { +public: + int mincostTickets(vector& days, vector& costs) { + + unordered_set day_set; + for(int day: days) + day_set.insert(day); + + vector dp(400, 0); + dp[365] = day_set.count(365) ? costs[0] : 0; + for(int day = 364; day >= 1; day --) { + if (!day_set.count(day)) dp[day] = dp[day + 1]; + else{ + dp[day] = costs[0] + dp[day + 1]; + dp[day] = min(dp[day], costs[1] + dp[day + 7]); + dp[day] = min(dp[day], costs[2] + dp[day + 30]); + } + } + return dp[1]; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0983-Minimum-Cost-For-Tickets/cpp-0983/main3.cpp b/0501-1000/0983-Minimum-Cost-For-Tickets/cpp-0983/main3.cpp new file mode 100644 index 00000000..6fa822ca --- /dev/null +++ b/0501-1000/0983-Minimum-Cost-For-Tickets/cpp-0983/main3.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/minimum-cost-for-tickets/ +/// Author : liuyubobobo +/// Time : 2019-01-28 + +#include +#include +#include + +using namespace std; + + +/// Memory Search +/// No need have 365 states, n states would be enough :-) +/// +/// Time Complexity: O(n) +/// Space Complexity: O(len(days)) +class Solution { +public: + int mincostTickets(vector& days, vector& costs) { + + int n = days.size(); + vector dp(n, -1); + + return dfs(days, 0, n, costs, dp); + } + +private: + int dfs(const vector& days, int index, int n, const vector& costs, vector& dp){ + + if(index >= n) return 0; + if(dp[index] != -1) return dp[index]; + + int res = costs[0] + dfs(days, index + 1, n, costs, dp); + + int i1 = 0; + for(; i1 < n; i1 ++) + if(days[i1] >= days[index] + 7) break; + res = min(res, costs[1] + dfs(days, i1, n, costs, dp)); + + int i2 = 0; + for(; i2 < n; i2 ++) + if(days[i2] >= days[index] + 30) break; + res = min(res, costs[2] + dfs(days, i2, n, costs, dp)); + + return dp[index] = res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0983-Minimum-Cost-For-Tickets/cpp-0983/main4.cpp b/0501-1000/0983-Minimum-Cost-For-Tickets/cpp-0983/main4.cpp new file mode 100644 index 00000000..872c6bd4 --- /dev/null +++ b/0501-1000/0983-Minimum-Cost-For-Tickets/cpp-0983/main4.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/minimum-cost-for-tickets/ +/// Author : liuyubobobo +/// Time : 2019-01-28 + +#include +#include +#include + +using namespace std; + + +/// Memory Search +/// No need have 365 states, n states would be enough :-) +/// +/// Time Complexity: O(n) +/// Space Complexity: O(len(days)) +class Solution { +public: + int mincostTickets(vector& days, vector& costs) { + + int n = days.size(); + vector dp(n + 1, 0); + dp[n - 1] = costs[0]; + for(int i = n - 2; i >= 0; i --){ + dp[i] = costs[0] + dp[i + 1]; + + int i1 = 0; + for(; i1 < n; i1 ++) + if(days[i1] >= days[i] + 7) break; + dp[i] = min(dp[i], costs[1] + dp[i1]); + + int i2 = 0; + for(; i2 < n; i2 ++) + if(days[i2] >= days[i] + 30) break; + dp[i] = min(dp[i], costs[2] + dp[i2]); + } + + return dp[0]; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0983-Minimum-Cost-For-Tickets/cpp-0983/main5.cpp b/0501-1000/0983-Minimum-Cost-For-Tickets/cpp-0983/main5.cpp new file mode 100644 index 00000000..9d7262a1 --- /dev/null +++ b/0501-1000/0983-Minimum-Cost-For-Tickets/cpp-0983/main5.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/minimum-cost-for-tickets/ +/// Author : liuyubobobo +/// Time : 2019-01-26 + +#include +#include +#include + +using namespace std; + + +/// Memory Search +/// No need have 365 states, n states would be enough :-) +/// Since days is in increasing order, we can use binary search to get next state more quickly :-) +/// +/// Time Complexity: O(n) +/// Space Complexity: O(len(days)) +class Solution { +public: + int mincostTickets(vector& days, vector& costs) { + + int n = days.size(); + vector dp(n, -1); + + return dfs(days, 0, n, costs, dp); + } + +private: + int dfs(const vector& days, int index, int n, const vector& costs, vector& dp){ + + if(index >= n) return 0; + if(dp[index] != -1) return dp[index]; + + int res = costs[0] + dfs(days, index + 1, n, costs, dp); + + int i1 = upper_bound(days.begin(), days.end(), days[index] + 6) - days.begin(); + res = min(res, costs[1] + dfs(days, i1, n, costs, dp)); + + int i2 = upper_bound(days.begin(), days.end(), days[index] + 29) - days.begin(); + res = min(res, costs[2] + dfs(days, i2, n, costs, dp)); + + return dp[index] = res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0983-Minimum-Cost-For-Tickets/cpp-0983/main6.cpp b/0501-1000/0983-Minimum-Cost-For-Tickets/cpp-0983/main6.cpp new file mode 100644 index 00000000..70ab9d8a --- /dev/null +++ b/0501-1000/0983-Minimum-Cost-For-Tickets/cpp-0983/main6.cpp @@ -0,0 +1,43 @@ +/// Source : https://leetcode.com/problems/minimum-cost-for-tickets/ +/// Author : liuyubobobo +/// Time : 2019-01-28 + +#include +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// No need have 365 states, n states would be enough :-) +/// Since days is in increasing order, we can use binary search to get next state more quickly :-) +/// +/// Time Complexity: O(n) +/// Space Complexity: O(len(days)) +class Solution { +public: + int mincostTickets(vector& days, vector& costs) { + + int n = days.size(); + vector dp(n + 1, 0); + dp[n - 1] = costs[0]; + for(int i = n - 2; i >= 0; i --){ + dp[i] = costs[0] + dp[i + 1]; + + int i1 = upper_bound(days.begin(), days.end(), days[i] + 6) - days.begin(); + dp[i] = min(dp[i], costs[1] + dp[i1]); + + int i2 = upper_bound(days.begin(), days.end(), days[i] + 29) - days.begin(); + dp[i] = min(dp[i], costs[2] + dp[i2]); + } + + return dp[0]; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0984-String-Without-AAA-or-BBB/cpp-0984/CMakeLists.txt b/0501-1000/0984-String-Without-AAA-or-BBB/cpp-0984/CMakeLists.txt new file mode 100644 index 00000000..88857baf --- /dev/null +++ b/0501-1000/0984-String-Without-AAA-or-BBB/cpp-0984/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(A) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/0501-1000/0984-String-Without-AAA-or-BBB/cpp-0984/main.cpp b/0501-1000/0984-String-Without-AAA-or-BBB/cpp-0984/main.cpp new file mode 100644 index 00000000..bd89b652 --- /dev/null +++ b/0501-1000/0984-String-Without-AAA-or-BBB/cpp-0984/main.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/string-without-aaa-or-bbb/ +/// Author : liuyubobobo +/// Time : 2019-01-26 + +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(A + B) +/// Space Complexity: O(1) +class Solution { +public: + string strWithout3a3b(int A, int B) { + + if(A > B) + return get_str(A - B, "a", B, "ab"); + return get_str(B - A, "b", A, "ba"); + } + +private: + string get_str(int k1, const string& s1, int k2, const string& s2){ + string res = ""; + while(k1 -- && k2 --) res += s1 + s2; + while(k2 --) res += s2; + while(k1 --) res += s1; + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0985-Sum-of-Even-Numbers-After-Queries/cpp-0985/CMakeLists.txt b/0501-1000/0985-Sum-of-Even-Numbers-After-Queries/cpp-0985/CMakeLists.txt new file mode 100644 index 00000000..88857baf --- /dev/null +++ b/0501-1000/0985-Sum-of-Even-Numbers-After-Queries/cpp-0985/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(A) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/0501-1000/0985-Sum-of-Even-Numbers-After-Queries/cpp-0985/main.cpp b/0501-1000/0985-Sum-of-Even-Numbers-After-Queries/cpp-0985/main.cpp new file mode 100644 index 00000000..9c36ec07 --- /dev/null +++ b/0501-1000/0985-Sum-of-Even-Numbers-After-Queries/cpp-0985/main.cpp @@ -0,0 +1,51 @@ +/// Source : https://leetcode.com/problems/sum-of-even-numbers-after-queries/ +/// Author : liuyubobobo +/// Time : 2019-02-02 + +#include +#include + +using namespace std; + + +/// Maintain sum +/// Time Complexity: O(n + q) +/// Space Complexity: O(1) +class Solution { +public: + vector sumEvenAfterQueries(vector& A, vector>& queries) { + + int sum = 0; + for(int a: A) + if(abs(a) % 2 == 0) + sum += a; + + vector res; + for(const vector& q: queries){ + + int x = A[q[1]]; + if(abs(x) % 2 == 0) sum -= x; + A[q[1]] += q[0]; + if(abs(A[q[1]]) % 2 == 0) + sum += A[q[1]]; + res.push_back(sum); + } + return res; + } +}; + + +void print_res(const vector& vec){ + for(int e: vec) + cout << e << " "; + cout << endl; +} + +int main() { + + vector A = {1,2,3,4}; + vector> queries = {{1,0},{-3,1},{-4,0},{2,3}}; + print_res(Solution().sumEvenAfterQueries(A, queries)); + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0986-Interval-List-Intersections/cpp-0986/CMakeLists.txt b/0501-1000/0986-Interval-List-Intersections/cpp-0986/CMakeLists.txt new file mode 100644 index 00000000..6324cdf7 --- /dev/null +++ b/0501-1000/0986-Interval-List-Intersections/cpp-0986/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(C) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/0501-1000/0986-Interval-List-Intersections/cpp-0986/main.cpp b/0501-1000/0986-Interval-List-Intersections/cpp-0986/main.cpp new file mode 100644 index 00000000..44edabc8 --- /dev/null +++ b/0501-1000/0986-Interval-List-Intersections/cpp-0986/main.cpp @@ -0,0 +1,65 @@ +/// Source : https://leetcode.com/problems/interval-list-intersections/ +/// Author : liuyubobobo +/// Time : 2019-02-04 +/// Updated: 2021-07-17 + +#include +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(m + n) +/// Space Complexity: O(1) +class Solution { +public: + vector> intervalIntersection(vector>& A, vector>& B) { + + vector> res; + + int i = 0, j = 0; + while(i < A.size() && j < B.size()){ + + int l = max(A[i][0], B[j][0]); + int h = min(A[i][1], B[j][1]); + if(l <= h) + res.push_back({l, h}); + + if(A[i][1] <= B[j][1]) + i ++; + else + j ++; + } + return res; + } +}; + + +void print_vec(const vector>& vec){ + + for(const vector& v: vec) + cout << "(" << v[0] << "," << v[1] << ") "; + cout << endl; +} + +int main() { + + vector> A1 = {{0,2}, {5,10}, {13,23}, {24,25}}; + vector> B1 = {{1,5}, {8,12}, {15,24}, {25,26}}; + print_vec(Solution().intervalIntersection(A1, B1)); + // [[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]] + + vector> A2 = {{5,10}}; + vector> B2 = {{5,10}}; + print_vec(Solution().intervalIntersection(A2, B2)); + // [[5, 10]] + + vector> A3 = {{3,5}, {9, 20}}; + vector> B3 = {{4,5}, {7, 10}, {11, 12}, {14, 15}, {16, 20}}; + print_vec(Solution().intervalIntersection(A3, B3)); + // [[4,5],[9,10],[11,12],[14,15],[16,20]] + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0987-Vertical-Order-Traversal-of-a-Binary-Tree/cpp-0987/CMakeLists.txt b/0501-1000/0987-Vertical-Order-Traversal-of-a-Binary-Tree/cpp-0987/CMakeLists.txt new file mode 100644 index 00000000..7d2a9b26 --- /dev/null +++ b/0501-1000/0987-Vertical-Order-Traversal-of-a-Binary-Tree/cpp-0987/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(D) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(D main.cpp) \ No newline at end of file diff --git a/0501-1000/0987-Vertical-Order-Traversal-of-a-Binary-Tree/cpp-0987/main.cpp b/0501-1000/0987-Vertical-Order-Traversal-of-a-Binary-Tree/cpp-0987/main.cpp new file mode 100644 index 00000000..7b12d455 --- /dev/null +++ b/0501-1000/0987-Vertical-Order-Traversal-of-a-Binary-Tree/cpp-0987/main.cpp @@ -0,0 +1,61 @@ +/// Source : https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/ +/// Author : liuyubobobo +/// Time : 2019-02-02 + +#include +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) + +/// 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: + vector> verticalTraversal(TreeNode* root) { + + map>> pos; + dfs(root, 0, 0, pos); + + vector> res; + for(pair>> p: pos){ + sort(p.second.begin(), p.second.end()); + vector r; + for(const pair& e: p.second) + r.push_back(e.second); + res.push_back(r); + } + return res; + } + +private: + void dfs(TreeNode* node, int x, int y, map>>& pos){ + + if(!node) + return; + + pos[x].push_back(make_pair(y, node->val)); + dfs(node->left, x - 1, y + 1, pos); + dfs(node->right, x + 1, y + 1, pos); + } +}; + + +int main() { + + // [0,5,1,9,null,2,null,null,null,null,3,4,8,6,null,null,null,7] + // [[9,7],[5,6],[0,2,4],[1,3],[8]] + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0988-Smallest-String-Starting-From-Leaf/cpp-0988/CMakeLists.txt b/0501-1000/0988-Smallest-String-Starting-From-Leaf/cpp-0988/CMakeLists.txt new file mode 100644 index 00000000..8a0a1cc7 --- /dev/null +++ b/0501-1000/0988-Smallest-String-Starting-From-Leaf/cpp-0988/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(B) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/0501-1000/0988-Smallest-String-Starting-From-Leaf/cpp-0988/main.cpp b/0501-1000/0988-Smallest-String-Starting-From-Leaf/cpp-0988/main.cpp new file mode 100644 index 00000000..76844cc9 --- /dev/null +++ b/0501-1000/0988-Smallest-String-Starting-From-Leaf/cpp-0988/main.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/smallest-string-starting-from-leaf/ +/// Author : liuyubobobo +/// Time : 2019-02-02 + +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n), where n is the nodes' number of the tree +/// Space Complexity: O(h), where h is the height of the tree + +/// 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: + string smallestFromLeaf(TreeNode* root) { + + string cur = "", best = ""; + dfs(root, cur, best); + return best; + } + +private: + void dfs(TreeNode* node, string& cur, string& best){ + + cur += ('a' + node->val); + + if(!node->left && !node->right){ + string s = cur; + reverse(s.begin(), s.end()); + if(best == "" | s < best) best = s; + } + + if(node->left) dfs(node->left, cur, best); + if(node->right) dfs(node->right, cur, best); + cur.pop_back(); + } +}; + + +int main() { + + // [0,null,1] + // "ba" + return 0; +} \ No newline at end of file diff --git a/0501-1000/0989-Add-to-Array-Form-of-Integer/cpp-0989/CMakeLists.txt b/0501-1000/0989-Add-to-Array-Form-of-Integer/cpp-0989/CMakeLists.txt new file mode 100644 index 00000000..c2b7a0b7 --- /dev/null +++ b/0501-1000/0989-Add-to-Array-Form-of-Integer/cpp-0989/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(A) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(A main2.cpp) \ No newline at end of file diff --git a/0501-1000/0989-Add-to-Array-Form-of-Integer/cpp-0989/main.cpp b/0501-1000/0989-Add-to-Array-Form-of-Integer/cpp-0989/main.cpp new file mode 100644 index 00000000..df33f012 --- /dev/null +++ b/0501-1000/0989-Add-to-Array-Form-of-Integer/cpp-0989/main.cpp @@ -0,0 +1,65 @@ +/// Source : https://leetcode.com/problems/add-to-array-form-of-integer/ +/// Author : liuyubobobo +/// Time : 2019-02-09 + +#include +#include + +using namespace std; + + +/// Two array's addition +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector addToArrayForm(vector& A, int K) { + + reverse(A.begin(), A.end()); +// Solution::print_vec(A); + + vector B; + while(K) + B.push_back(K % 10), K /= 10; + if(B.empty()) B.push_back(0); +// Solution::print_vec(B); + + + while(A.size() < B.size()) A.push_back(0); + while(B.size() < A.size()) B.push_back(0); +// Solution::print_vec(A); +// Solution::print_vec(B); + + int carry = 0; + for(int i = 0; i < A.size(); i ++){ + int t = A[i] + B[i] + carry; + A[i] = t % 10; + carry = t / 10; + } + if(carry) A.push_back(1); +// Solution::print_vec(A); + + while(!A.empty() && A.back() == 0) A.pop_back(); + if(A.empty()) A.push_back(0); + + reverse(A.begin(), A.end()); +// Solution::print_vec(A); + return A; + } + + static void print_vec(const vector& vec){ + + for(int e: vec) cout << e; + cout << endl; + } +}; + + +int main() { + + vector A1 = {0}; + int K1 = 0; + Solution::print_vec(Solution().addToArrayForm(A1, K1)); + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0989-Add-to-Array-Form-of-Integer/cpp-0989/main2.cpp b/0501-1000/0989-Add-to-Array-Form-of-Integer/cpp-0989/main2.cpp new file mode 100644 index 00000000..251e2ef4 --- /dev/null +++ b/0501-1000/0989-Add-to-Array-Form-of-Integer/cpp-0989/main2.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/add-to-array-form-of-integer/ +/// Author : liuyubobobo +/// Time : 2019-02-13 + +#include +#include + +using namespace std; + + +/// Array and number addition +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + vector addToArrayForm(vector& A, int K) { + + vector res; + + int carry = 0, i = A.size() - 1; + while(i >= 0 || K){ + int t = K % 10 + carry; + K /= 10; + + if(i >= 0) t += A[i]; + + res.push_back(t % 10); + carry = t / 10; + + i --; + } + if(carry) res.push_back(1); + + reverse(res.begin(), res.end()); + return res; + } +}; + + +void print_vec(const vector& vec){ + + for(int e: vec) cout << e; + cout << endl; +} + +int main() { + + vector A1 = {0}; + int K1 = 0; + print_vec(Solution().addToArrayForm(A1, K1)); + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0990-Satisfiability-of-Equality-Equations/cpp-0990/CMakeLists.txt b/0501-1000/0990-Satisfiability-of-Equality-Equations/cpp-0990/CMakeLists.txt new file mode 100644 index 00000000..8a0a1cc7 --- /dev/null +++ b/0501-1000/0990-Satisfiability-of-Equality-Equations/cpp-0990/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(B) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/0501-1000/0990-Satisfiability-of-Equality-Equations/cpp-0990/main.cpp b/0501-1000/0990-Satisfiability-of-Equality-Equations/cpp-0990/main.cpp new file mode 100644 index 00000000..f17ed7ad --- /dev/null +++ b/0501-1000/0990-Satisfiability-of-Equality-Equations/cpp-0990/main.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/satisfiability-of-equality-equations/ +/// Author : liuyubobobo +/// Time : 2019-02-13 + +#include +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(26^2 * n) +/// Space Complexity: O(26^2) +class Solution { +public: + bool equationsPossible(vector& equations) { + + vector> g(26); + for(const string& e: equations) + if(e[1] == '=') + g[e[0] - 'a'].insert(e[3] - 'a'), + g[e[3] - 'a'].insert(e[0] - 'a'); + + for(const string& e: equations) + if(e[1] == '!' && isConnected(g, e[0] - 'a', e[3] - 'a')) + return false; + return true; + } + +private: + bool isConnected(const vector>& g, int x, int y){ + + vector visited(26, false); + return dfs(g, x, y, visited); + } + + bool dfs(const vector>& g, int s, int t, vector& visited){ + + visited[s] = true; + if(s == t) return true; + for(int next: g[s]) + if(!visited[next] && dfs(g, next, t, visited)) + return true; + return false; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0990-Satisfiability-of-Equality-Equations/cpp-0990/main2.cpp b/0501-1000/0990-Satisfiability-of-Equality-Equations/cpp-0990/main2.cpp new file mode 100644 index 00000000..886aa438 --- /dev/null +++ b/0501-1000/0990-Satisfiability-of-Equality-Equations/cpp-0990/main2.cpp @@ -0,0 +1,67 @@ +/// Source : https://leetcode.com/problems/satisfiability-of-equality-equations/ +/// Author : liuyubobobo +/// Time : 2019-02-09 + +#include +#include + +using namespace std; + + +/// Using Union-Found +/// Time Complexity: O(n) +/// Space Complexity: O(26) +class UF{ + +private: + vector parent; + +public: + UF(int n){ + for(int i = 0 ; i < n ; i ++) + parent.push_back(i); + } + + int find(int p){ + if( p != parent[p] ) + parent[p] = find( parent[p] ); + return parent[p]; + } + + bool isConnected(int p , int q){ + return find(p) == find(q); + } + + void unionElements(int p, int q){ + + int pRoot = find(p); + int qRoot = find(q); + + if( pRoot == qRoot ) + return; + + parent[pRoot] = qRoot; + } +}; + +class Solution { +public: + bool equationsPossible(vector& equations) { + + UF uf(26); + for(const string& e: equations) + if(e[1] == '=') + uf.unionElements(e[0] - 'a', e[3] - 'a'); + + for(const string& e: equations) + if(e[1] == '!' && uf.isConnected(e[0] - 'a', e[3] - 'a')) + return false; + return true; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0991-Broken-Calculator/cpp-0991/CMakeLists.txt b/0501-1000/0991-Broken-Calculator/cpp-0991/CMakeLists.txt new file mode 100644 index 00000000..6324cdf7 --- /dev/null +++ b/0501-1000/0991-Broken-Calculator/cpp-0991/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(C) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/0501-1000/0991-Broken-Calculator/cpp-0991/main.cpp b/0501-1000/0991-Broken-Calculator/cpp-0991/main.cpp new file mode 100644 index 00000000..82dc5f76 --- /dev/null +++ b/0501-1000/0991-Broken-Calculator/cpp-0991/main.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/broken-calculator/ +/// Author : liuyubobobo +/// Time : 2019-02-09 + +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(logY) +/// Space Complexity: O(1) +class Solution { +public: + int brokenCalc(int X, int Y) { + + if(X >= Y) return X - Y; + + int res = 0; + while(X != Y){ + if(Y % 2) res ++, Y ++; + else res ++, Y /= 2; + + if(X > Y) + return res + X - Y; + } + + return res; + } +}; + + +int main() { + + cout << Solution().brokenCalc(2, 3) << endl; + // 2 + + cout << Solution().brokenCalc(5, 8) << endl; + // 2 + + cout << Solution().brokenCalc(3, 10) << endl; + // 3 + + cout << Solution().brokenCalc(1024, 1) << endl; + // 1023 + + cout << Solution().brokenCalc(1, 1000000000) << endl; + // 39 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0992-Subarrays-with-K-Different-Integers/cpp-0992/CMakeLists.txt b/0501-1000/0992-Subarrays-with-K-Different-Integers/cpp-0992/CMakeLists.txt new file mode 100644 index 00000000..7d2a9b26 --- /dev/null +++ b/0501-1000/0992-Subarrays-with-K-Different-Integers/cpp-0992/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(D) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(D main.cpp) \ No newline at end of file diff --git a/0501-1000/0992-Subarrays-with-K-Different-Integers/cpp-0992/main.cpp b/0501-1000/0992-Subarrays-with-K-Different-Integers/cpp-0992/main.cpp new file mode 100644 index 00000000..b0b857a1 --- /dev/null +++ b/0501-1000/0992-Subarrays-with-K-Different-Integers/cpp-0992/main.cpp @@ -0,0 +1,60 @@ +/// Source : https://leetcode.com/problems/subarrays-with-k-different-integers/ +/// Author : liuyubobobo +/// Time : 2019-02-13 + +#include +#include +#include +#include + +using namespace std; + + +/// Sliding Window +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int subarraysWithKDistinct(vector& A, int K) { + + unordered_map set_left, set_right; + int left = 0, right = 0, res = 0; + for(int e: A){ + set_left[e] ++; + set_right[e] ++; + + while(set_left.size() > K){ + set_left[A[left]] --; + if(set_left[A[left]] == 0) + set_left.erase(A[left]); + left ++; + } + + while(set_right.size() >= K){ + set_right[A[right]] --; + if(set_right[A[right]] == 0) + set_right.erase(A[right]); + right ++; + } + + res += right - left; + } + return res; + } +}; + + +int main() { + + vector A1 = {1,2,1,2,3}; + int K1 = 2; + cout << Solution().subarraysWithKDistinct(A1, K1) << endl; + // 7 + + vector A2 = {1,2,1,3,4}; + int K2 = 3; + cout << Solution().subarraysWithKDistinct(A2, K2) << endl; + // 3 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0993-Cousins-in-Binary-Tree/cpp-0993/CMakeLists.txt b/0501-1000/0993-Cousins-in-Binary-Tree/cpp-0993/CMakeLists.txt new file mode 100644 index 00000000..c2b7a0b7 --- /dev/null +++ b/0501-1000/0993-Cousins-in-Binary-Tree/cpp-0993/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(A) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(A main2.cpp) \ No newline at end of file diff --git a/0501-1000/0993-Cousins-in-Binary-Tree/cpp-0993/main.cpp b/0501-1000/0993-Cousins-in-Binary-Tree/cpp-0993/main.cpp new file mode 100644 index 00000000..a1d1cfd4 --- /dev/null +++ b/0501-1000/0993-Cousins-in-Binary-Tree/cpp-0993/main.cpp @@ -0,0 +1,67 @@ +/// Source : https://leetcode.com/problems/cousins-in-binary-tree/ +/// Author : liuyubobobo +/// Time : 2019-02-16 + +#include +#include + +using namespace std; + + +/// Two-Pass DFS +/// Time Complexity: O(n) +/// Space Complexity: O(h) + +/// 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: + bool isCousins(TreeNode* root, int x, int y) { + + if(!root || root->val == x || root->val == y) + return false; + + pair p1; // depth, parent + if(!dfs(root, x, 0, p1)) return false; + + pair p2; + if(!dfs(root, y, 0, p2)) return false; + + return p1.first == p2.first && p1.second != p2.second; + } + +private: + bool dfs(TreeNode* node, int x, int d, pair& p){ + + if(node->left && node->left->val == x){ + p = make_pair(d + 1, node->val); + return true; + } + + if(node->right && node->right->val == x){ + p = make_pair(d + 1, node->val); + return true; + } + + if(node->left && dfs(node->left, x, d + 1, p)) + return true; + + if(node->right && dfs(node->right, x, d + 1, p)) + return true; + + return false; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0993-Cousins-in-Binary-Tree/cpp-0993/main2.cpp b/0501-1000/0993-Cousins-in-Binary-Tree/cpp-0993/main2.cpp new file mode 100644 index 00000000..79ec5b62 --- /dev/null +++ b/0501-1000/0993-Cousins-in-Binary-Tree/cpp-0993/main2.cpp @@ -0,0 +1,59 @@ +/// Source : https://leetcode.com/problems/cousins-in-binary-tree/ +/// Author : liuyubobobo +/// Time : 2019-02-18 + +#include +#include +#include + +using namespace std; + + +/// One-Pass DFS +/// Using HashMap to record the result :-) +/// +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// 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: + bool isCousins(TreeNode* root, int x, int y) { + + if(!root || root->val == x || root->val == y) + return false; + + unordered_map> record; // depth, parent + dfs(root, 0, record); + + return record[x].first == record[y].first && record[x].second != record[y].second; + } + +private: + void dfs(TreeNode* node, int d, unordered_map>& record){ + + if(node->left) { + record[node->left->val] = make_pair(d + 1, node->val); + dfs(node->left, d + 1, record); + } + + if(node->right){ + record[node->right->val] = make_pair(d + 1, node->val); + dfs(node->right, d + 1, record); + } + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0994-Rotting-Oranges/cpp-0994/CMakeLists.txt b/0501-1000/0994-Rotting-Oranges/cpp-0994/CMakeLists.txt new file mode 100644 index 00000000..b74fb382 --- /dev/null +++ b/0501-1000/0994-Rotting-Oranges/cpp-0994/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(B) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(B main2.cpp) \ No newline at end of file diff --git a/0501-1000/0994-Rotting-Oranges/cpp-0994/main.cpp b/0501-1000/0994-Rotting-Oranges/cpp-0994/main.cpp new file mode 100644 index 00000000..cefc4add --- /dev/null +++ b/0501-1000/0994-Rotting-Oranges/cpp-0994/main.cpp @@ -0,0 +1,106 @@ +/// Source : https://leetcode.com/problems/rotting-oranges/ +/// Author : liuyubobobo +/// Time : 2019-02-16 + +#include +#include +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +private: + const int d[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + int m, n; + +public: + int orangesRotting(vector>& grid) { + + assert(grid.size() && grid[0].size()); + m = grid.size(), n = grid[0].size(); + + vector rotten; + int fresh = 0; + for(int i = 0; i < m; i ++) + for(int j = 0; j < n; j ++) + if(grid[i][j] == 1) + fresh ++; + else if(grid[i][j] == 2) + rotten.push_back(i * n + j); + + if(!rotten.size()) + return fresh ? -1 : 0; + + unordered_set used; + for(int e: rotten) used.insert(e); + + int res = 0; + while(rotten.size()){ + +// cout << "rotten : "; +// for(int e: rotten) cout << e << " "; +// cout << endl; + + vector newrotten; + for(int e: rotten){ + int x = e / n, y = e % n; + for(int i = 0; i < 4; i ++){ + int nextx = x + d[i][0], nexty = y + d[i][1]; + if(nextx >= 0 && nextx < m && nexty >= 0 && nexty < n && grid[nextx][nexty] == 1){ + grid[nextx][nexty] = 2; + newrotten.push_back(nextx * n + nexty); + used.insert(nextx * n + nexty); + } + } + } + + if(newrotten.size()) res ++; + rotten = newrotten; + } + + if(!allRotten(grid)) return -1; + return res; + } + +private: + bool allRotten(const vector>& grid){ + for(int i = 0; i < m; i ++) + for(int j = 0; j < n; j ++) + if(grid[i][j] == 1) + return false; + return true; + } +}; + + +int main() { + + vector> grid1 = { + {2,1,1}, + {1,1,0}, + {0,1,1} + }; + cout << Solution().orangesRotting(grid1) << endl; + // 4 + + vector> grid2 = { + {0, 0}, + {0, 0} + }; + cout << Solution().orangesRotting(grid2) << endl; + // 0 + + vector> grid3 = { + {1} + }; + cout << Solution().orangesRotting(grid3) << endl; + // -1 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0994-Rotting-Oranges/cpp-0994/main2.cpp b/0501-1000/0994-Rotting-Oranges/cpp-0994/main2.cpp new file mode 100644 index 00000000..4b92e3b1 --- /dev/null +++ b/0501-1000/0994-Rotting-Oranges/cpp-0994/main2.cpp @@ -0,0 +1,99 @@ +/// Source : https://leetcode.com/problems/rotting-oranges/ +/// Author : liuyubobobo +/// Time : 2019-02-16 + +#include +#include +#include +#include + +using namespace std; + + +/// BFS +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +private: + const int d[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + int m, n; + +public: + int orangesRotting(vector>& grid) { + + assert(grid.size() && grid[0].size()); + m = grid.size(), n = grid[0].size(); + + queue> q; + unordered_set used; + int fresh = 0; + for(int i = 0; i < m; i ++) + for(int j = 0; j < n; j ++) + if(grid[i][j] == 2){ + int pos = i * n + j; + q.push(make_pair(pos, 0)); + used.insert(pos); + } + + int res = 0; + while(!q.empty()){ + + int cur = q.front().first; + int step = q.front().second; + q.pop(); + + res = max(res, step); + + int x = cur / n, y = cur % n; + for(int i = 0; i < 4; i ++){ + int nextx = x + d[i][0], nexty = y + d[i][1]; + if(nextx >= 0 && nextx < m && nexty >= 0 && nexty < n && grid[nextx][nexty] == 1){ + int nextpos = nextx * n + nexty; + grid[nextx][nexty] = 2; + q.push(make_pair(nextpos, step + 1)); + used.insert(nextpos); + } + } + } + + if(!allRotten(grid)) return -1; + return res; + } + +private: + bool allRotten(const vector>& grid){ + for(int i = 0; i < m; i ++) + for(int j = 0; j < n; j ++) + if(grid[i][j] == 1) + return false; + return true; + } +}; + + +int main() { + + vector> grid1 = { + {2,1,1}, + {1,1,0}, + {0,1,1} + }; + cout << Solution().orangesRotting(grid1) << endl; + // 4 + + vector> grid2 = { + {0, 0}, + {0, 0} + }; + cout << Solution().orangesRotting(grid2) << endl; + // 0 + + vector> grid3 = { + {1} + }; + cout << Solution().orangesRotting(grid3) << endl; + // -1 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0995-Minimum-Number-of-K-Consecutive-Bit-Flips/cpp-0995/CMakeLists.txt b/0501-1000/0995-Minimum-Number-of-K-Consecutive-Bit-Flips/cpp-0995/CMakeLists.txt new file mode 100644 index 00000000..c8cc528c --- /dev/null +++ b/0501-1000/0995-Minimum-Number-of-K-Consecutive-Bit-Flips/cpp-0995/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(C) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(C main2.cpp) \ No newline at end of file diff --git a/0501-1000/0995-Minimum-Number-of-K-Consecutive-Bit-Flips/cpp-0995/main.cpp b/0501-1000/0995-Minimum-Number-of-K-Consecutive-Bit-Flips/cpp-0995/main.cpp new file mode 100644 index 00000000..4ce693c4 --- /dev/null +++ b/0501-1000/0995-Minimum-Number-of-K-Consecutive-Bit-Flips/cpp-0995/main.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/minimum-number-of-k-consecutive-bit-flips/ +/// Author : liuyubobobo +/// Time : 2019-02-16 + +#include +#include + +using namespace std; + + +/// Greedy + Simulation +/// Time Complexity: O((N - K) * K) +/// Space Complexity: O(1) +class Solution { +public: + int minKBitFlips(vector& A, int K) { + + int res = 0; + for(int i = 0; i < A.size(); i ++) + if(A[i] == 0){ + if(i + K > A.size()) return -1; + + res ++; + for(int j = 0; j < K; j ++) + A[i + j] = 1 - A[i + j]; + } + return res; + } +}; + + +int main() { + + vector A1 = {0,1,0}; + cout << Solution().minKBitFlips(A1, 1) << endl; + // 2 + + vector A2 = {1,1,0}; + cout << Solution().minKBitFlips(A2, 2) << endl; + // -1 + + vector A3 = {0,0,0,1,0,1,1,0}; + cout << Solution().minKBitFlips(A3, 3) << endl; + // 3 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0995-Minimum-Number-of-K-Consecutive-Bit-Flips/cpp-0995/main2.cpp b/0501-1000/0995-Minimum-Number-of-K-Consecutive-Bit-Flips/cpp-0995/main2.cpp new file mode 100644 index 00000000..b16e80d1 --- /dev/null +++ b/0501-1000/0995-Minimum-Number-of-K-Consecutive-Bit-Flips/cpp-0995/main2.cpp @@ -0,0 +1,56 @@ +/// Source : https://leetcode.com/problems/minimum-number-of-k-consecutive-bit-flips/ +/// Author : liuyubobobo +/// Time : 2019-02-18 + +#include +#include + +using namespace std; + + +/// Greedy + Events +/// Record every closed event +/// Time Complexity: O(N) +/// Space Complexity: O(N) +class Solution { +public: + int minKBitFlips(vector& A, int K) { + + int res = 0; + vector event(A.size(), false); + int flip = 0; + + for(int i = 0; i < A.size(); i ++){ + if((A[i] && flip % 2) || (!A[i] && flip % 2 == 0)){ + + if(i + K - 1 >= A.size()) return -1; + + res ++; + + flip ++; + event[i + K - 1] = true; + } + + if(event[i]) flip --; + } + return res; + } +}; + + +int main() { + + vector A1 = {0,1,0}; + cout << Solution().minKBitFlips(A1, 1) << endl; + // 2 + + vector A2 = {1,1,0}; + cout << Solution().minKBitFlips(A2, 2) << endl; + // -1 + + vector A3 = {0,0,0,1,0,1,1,0}; + cout << Solution().minKBitFlips(A3, 3) << endl; + // 3 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0996-Number-of-Squareful-Arrays/cpp-0996/CMakeLists.txt b/0501-1000/0996-Number-of-Squareful-Arrays/cpp-0996/CMakeLists.txt new file mode 100644 index 00000000..f0e51103 --- /dev/null +++ b/0501-1000/0996-Number-of-Squareful-Arrays/cpp-0996/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(D) + +set(CMAKE_CXX_STANDARD 11) + +add_executable(D main3.cpp) \ No newline at end of file diff --git a/0501-1000/0996-Number-of-Squareful-Arrays/cpp-0996/main.cpp b/0501-1000/0996-Number-of-Squareful-Arrays/cpp-0996/main.cpp new file mode 100644 index 00000000..72a5342d --- /dev/null +++ b/0501-1000/0996-Number-of-Squareful-Arrays/cpp-0996/main.cpp @@ -0,0 +1,96 @@ +/// Source : https://leetcode.com/problems/number-of-squareful-arrays/ +/// Author : liuyubobobo +/// Time : 2019-02-16 + +#include +#include +#include +#include + +using namespace std; + + +/// Backtrack +/// Using string hash to record the same value +/// Time Complexity: O(n^n) +/// Space Complexity: O(n) +class Solution { + +private: + int n; + +public: + int numSquarefulPerms(vector& A) { + + n = A.size(); + vector> ok(n); + for(int i = 0; i < n; i ++) + for(int j = 0; j < n; j ++) + if(j != i && perfectSquare(A[i] + A[j])) + ok[i].push_back(j); + + int res = 0; + unordered_set hashset; + for(int i = 0; i < n; i ++){ + vector visited(n, false); + visited[i] = true; + + vector seqindex = {i}; + + string hash = to_string(A[i]); + hashset.insert(hash); + + res += dfs(A, ok, 1, seqindex, hash, visited, hashset); + } + return res; + } + +private: + int dfs(const vector& A, const vector>& ok, + int index, vector& seqindex, const string& hash, vector& visited, + unordered_set& hashset){ + + if(index == n) + return 1; + + int res = 0; + for(int next: ok[seqindex[index - 1]]) + if(!visited[next]){ + + string newhash = hash + "#" + to_string(A[next]); + if(!hashset.count(newhash)){ + hashset.insert(newhash); + + seqindex.push_back(next); + visited[next] = true; + res += dfs(A, ok, index + 1, seqindex, newhash, visited, hashset); + visited[next] = false; + seqindex.pop_back(); + } + } + return res; + } + + bool perfectSquare(int x){ + int t = sqrt(x); + return t * t == x; + } +}; + + +int main() { + + vector A1 = {1, 17, 8}; + cout << Solution().numSquarefulPerms(A1) << endl; + // 2 + + vector A2 = {2, 2, 2}; + cout << Solution().numSquarefulPerms(A2) << endl; + // 1 + + vector A3(12, 0); + cout << Solution().numSquarefulPerms(A3) << endl; + // 1 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0996-Number-of-Squareful-Arrays/cpp-0996/main2.cpp b/0501-1000/0996-Number-of-Squareful-Arrays/cpp-0996/main2.cpp new file mode 100644 index 00000000..d9210afb --- /dev/null +++ b/0501-1000/0996-Number-of-Squareful-Arrays/cpp-0996/main2.cpp @@ -0,0 +1,90 @@ +/// Source : https://leetcode.com/problems/number-of-squareful-arrays/ +/// Author : liuyubobobo +/// Time : 2019-02-19 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// Backtrack +/// Using HashMap to record the same value +/// Time Complexity: O(n^n) +/// Space Complexity: O(n) +class Solution { + +private: + int n; + +public: + int numSquarefulPerms(vector& A) { + + n = A.size(); + unordered_map freq; + unordered_set elements; + for(int e: A){ + freq[e] ++; + elements.insert(e); + } + + unordered_map> g; + for(int i = 0; i < n; i ++) + for(int j = i + 1; j < n; j ++) + if(perfectSquare(A[i] + A[j])){ + g[A[i]].insert(A[j]); + g[A[j]].insert(A[i]); + } + + int res = 0; + for(int e: elements){ + freq[e] --; + res += dfs(g, e, 1, freq); + freq[e] ++; + } + return res; + } + +private: + int dfs(unordered_map>& g, + int e, int index, unordered_map& freq){ + + if(index == n) + return 1; + + int res = 0; + for(int next: g[e]) + if(freq[next]){ + freq[next] --; + res += dfs(g, next, index + 1, freq); + freq[next] ++; + } + return res; + } + + bool perfectSquare(int x){ + int t = sqrt(x); + return t * t == x; + } +}; + + +int main() { + + vector A1 = {1, 17, 8}; + cout << Solution().numSquarefulPerms(A1) << endl; + // 2 + + vector A2 = {2, 2, 2}; + cout << Solution().numSquarefulPerms(A2) << endl; + // 1 + + vector A3(12, 0); + cout << Solution().numSquarefulPerms(A3) << endl; + // 1 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0996-Number-of-Squareful-Arrays/cpp-0996/main3.cpp b/0501-1000/0996-Number-of-Squareful-Arrays/cpp-0996/main3.cpp new file mode 100644 index 00000000..73e29657 --- /dev/null +++ b/0501-1000/0996-Number-of-Squareful-Arrays/cpp-0996/main3.cpp @@ -0,0 +1,92 @@ +/// Source : https://leetcode.com/problems/number-of-squareful-arrays/ +/// Author : liuyubobobo +/// Time : 2019-02-19 + +#include +#include +#include +#include + +using namespace std; + + +/// Memory Search +/// Divide corresponding factorial number to avoid repeating counting :-) +/// Time Complexity: O(n*2^n) +/// Space Complexity: O(n*2^n) +class Solution { + +private: + int n; + +public: + int numSquarefulPerms(vector& A) { + + n = A.size(); + + vector> g(n); + for(int i = 0; i < n; i ++) + for(int j = i + 1; j < n; j ++) + if(perfectSquare(A[i] + A[j])){ + g[i].push_back(j); + g[j].push_back(i); + } + + int res = 0; + vector> dp(n, vector(1 << n, -1)); + for(int i = 0; i < n; i ++) + res += dfs(g, i, 1 << i, dp); + + unordered_map freq; + for(int e: A) freq[e] ++; + for(const pair& p: freq) res /= fac(p.second); + return res; + } + +private: + int dfs(const vector>& g, + int index, int visited, vector>& dp){ + + if(visited == (1 << n) - 1) + return 1; + + if(dp[index][visited] != -1) return dp[index][visited]; + + int res = 0; + for(int next: g[index]) + if(!(visited & (1 << next))){ + visited += (1 << next); + res += dfs(g, next, visited, dp); + visited -= (1 << next); + } + return dp[index][visited] = res; + } + + int fac(int x){ + if(x == 0 || x == 1) return 1; + return x * fac(x - 1); + } + + bool perfectSquare(int x){ + int t = sqrt(x); + return t * t == x; + } +}; + + +int main() { + + vector A1 = {1, 17, 8}; + cout << Solution().numSquarefulPerms(A1) << endl; + // 2 + + vector A2 = {2, 2, 2}; + cout << Solution().numSquarefulPerms(A2) << endl; + // 1 + + vector A3(12, 0); + cout << Solution().numSquarefulPerms(A3) << endl; + // 1 + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0997-Find-the-Town-Judge/cpp-0997/CMakeLists.txt b/0501-1000/0997-Find-the-Town-Judge/cpp-0997/CMakeLists.txt new file mode 100644 index 00000000..2d73f980 --- /dev/null +++ b/0501-1000/0997-Find-the-Town-Judge/cpp-0997/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/0501-1000/0997-Find-the-Town-Judge/cpp-0997/main.cpp b/0501-1000/0997-Find-the-Town-Judge/cpp-0997/main.cpp new file mode 100644 index 00000000..48d3f214 --- /dev/null +++ b/0501-1000/0997-Find-the-Town-Judge/cpp-0997/main.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/find-the-town-judge/ +/// Author : liuyubobobo +/// Time : 2019-02-23 + +#include +#include + +using namespace std; + + +/// in-degrees and out-degrees +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int findJudge(int N, vector>& trust) { + + vector indegrees(N, 0), outdegrees(N, 0); + for(const vector& e: trust) + outdegrees[e[0] - 1] ++, + indegrees[e[1] - 1] ++; + + for(int i = 0; i < N; i ++) + if(indegrees[i] == N - 1 && outdegrees[i] == 0) + return i + 1; + return -1; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0998-Maximum-Binary-Tree-II/cpp-0998/CMakeLists.txt b/0501-1000/0998-Maximum-Binary-Tree-II/cpp-0998/CMakeLists.txt new file mode 100644 index 00000000..2235a661 --- /dev/null +++ b/0501-1000/0998-Maximum-Binary-Tree-II/cpp-0998/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/0501-1000/0998-Maximum-Binary-Tree-II/cpp-0998/main.cpp b/0501-1000/0998-Maximum-Binary-Tree-II/cpp-0998/main.cpp new file mode 100644 index 00000000..ab23a576 --- /dev/null +++ b/0501-1000/0998-Maximum-Binary-Tree-II/cpp-0998/main.cpp @@ -0,0 +1,61 @@ +/// Source : https://leetcode.com/problems/maximum-binary-tree-ii/ +/// Author : liuyubobobo +/// Time : 2019-02-23 + +#include +#include + +using namespace std; + + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + + +/// Simulation +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { +public: + TreeNode* insertIntoMaxTree(TreeNode* root, int val) { + + vector A; + dfs(root, A); + A.push_back(val); + return construct(A, 0, A.size() - 1); + } + +private: + TreeNode* construct(const vector& A, int l, int r){ + + if(l > r) return NULL; + + int best_val = A[l], best_index = l; + for(int i = l + 1; i <= r; i ++) + if(A[i] > best_val) + best_val = A[i], best_index = i; + + TreeNode* retNode = new TreeNode(A[best_index]); + retNode->left = construct(A, l, best_index - 1); + retNode->right = construct(A, best_index + 1, r); + return retNode; + } + + void dfs(TreeNode* root, vector& A){ + + if(!root) return; + dfs(root->left, A); + A.push_back(root->val); + dfs(root->right, A); + } +}; + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/0999-Available-Captures-for-Rook/cpp-0999/CMakeLists.txt b/0501-1000/0999-Available-Captures-for-Rook/cpp-0999/CMakeLists.txt new file mode 100644 index 00000000..b4b16ecd --- /dev/null +++ b/0501-1000/0999-Available-Captures-for-Rook/cpp-0999/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/0501-1000/0999-Available-Captures-for-Rook/cpp-0999/main.cpp b/0501-1000/0999-Available-Captures-for-Rook/cpp-0999/main.cpp new file mode 100644 index 00000000..7df502ef --- /dev/null +++ b/0501-1000/0999-Available-Captures-for-Rook/cpp-0999/main.cpp @@ -0,0 +1,51 @@ +/// Source : https://leetcode.com/problems/available-captures-for-rook/ +/// Author : liuyubobobo +/// Time : 2019-02-23 + +#include +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n^2) +/// Space Complexity: O(1) +class Solution { + +private: + const int d[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; + +public: + int numRookCaptures(vector>& board) { + + int rPos = -1; + for(int i = 0; i < 64; i ++) + if(board[i / 8][i % 8] == 'R'){ + rPos = i; + break; + } + assert(rPos != -1); + + int res = 0; + for(int i = 0; i < 4; i ++){ + + for(int k = 1;;k++){ + int x = rPos / 8 + k * d[i][0], y = rPos % 8 + k * d[i][1]; + if(x >= 0 && x < 8 && y >= 0 && y < 8){ + if(board[x][y] == 'p'){res ++; break;} + else if(board[x][y] == 'B') break; + } + else break; + } + } + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/0501-1000/1000-Minimum-Cost-to-Merge-Stones/cpp-1000/CMakeLists.txt b/0501-1000/1000-Minimum-Cost-to-Merge-Stones/cpp-1000/CMakeLists.txt new file mode 100644 index 00000000..d20b982d --- /dev/null +++ b/0501-1000/1000-Minimum-Cost-to-Merge-Stones/cpp-1000/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) \ No newline at end of file diff --git a/0501-1000/1000-Minimum-Cost-to-Merge-Stones/cpp-1000/main.cpp b/0501-1000/1000-Minimum-Cost-to-Merge-Stones/cpp-1000/main.cpp new file mode 100644 index 00000000..6a856ead --- /dev/null +++ b/0501-1000/1000-Minimum-Cost-to-Merge-Stones/cpp-1000/main.cpp @@ -0,0 +1,80 @@ +/// Source : https://leetcode.com/problems/minimum-cost-to-merge-stones/ +/// Author : liuyubobobo +/// Time : 2019-03-04 + +#include +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(n^3 * K) +/// Space Complexity: O(n^3) +class Solution { + +public: + int mergeStones(vector& stones, int K) { + + int n = stones.size(); + if((n - 1) % (K - 1)) return -1; + + vector>> dp(n + 1, vector>(n + 1, vector(K + 1, -1))); + return dfs(stones, 0, n - 1, 1, K, dp); + } + + int dfs(const vector& stones, int l, int r, int pile, int K, + vector>>& dp){ + + if(dp[l][r][pile] != -1) return dp[l][r][pile]; + + if(l == r) + return dp[l][r][pile] = (pile == 1 ? 0 : INT_MAX); + + if(pile == 1) { + int tres = dfs(stones, l, r, K, K, dp); + return dp[l][r][pile] = tres == INT_MAX ? tres : + tres + accumulate(stones.begin() + l, stones.begin() + (r + 1), 0); + } + + int res = INT_MAX; + for(int i = l; i < r; i ++){ + int tres1 = dfs(stones, l, i, 1, K, dp), + tres2 = dfs(stones, i + 1, r, pile - 1, K, dp); + if(tres1 != INT_MAX && tres2 != INT_MAX) + res = min(res, tres1 + tres2); + } + return dp[l][r][pile] = res; + } +}; + + +int main() { + + vector stones1 = {3,2,4,1}; + cout << Solution().mergeStones(stones1, 2) << endl; + // 20 + + vector stones2 = {3,2,4,1}; + cout << Solution().mergeStones(stones2, 3) << endl; + // -1 + + vector stones3 = {3,5,1,2,6}; + cout << Solution().mergeStones(stones3, 3) << endl; + // 25 + + vector stones4 = {1}; + cout << Solution().mergeStones(stones4, 2) << endl; + // 0 + + vector stones5 = {69,39,79,78,16,6,36,97,79,27,14,31,4}; + cout << Solution().mergeStones(stones5, 2) << endl; + // 1957 + + vector stones6 = {95,54,31,48,44,96,99,20,51,54,18,85,25,84,91,48,40,72,22}; + cout << Solution().mergeStones(stones6, 2) << endl; + // 4517 + + return 0; +} \ No newline at end of file diff --git a/0677-Map-Sum-Pairs/cpp-0677/CMakeLists.txt b/0677-Map-Sum-Pairs/cpp-0677/CMakeLists.txt deleted file mode 100644 index 9538df7b..00000000 --- a/0677-Map-Sum-Pairs/cpp-0677/CMakeLists.txt +++ /dev/null @@ -1,7 +0,0 @@ -cmake_minimum_required(VERSION 3.5) -project(cpp_0677) - -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") - -set(SOURCE_FILES main4.cpp) -add_executable(cpp_0677 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0677-Map-Sum-Pairs/cpp-0677/main.cpp b/0677-Map-Sum-Pairs/cpp-0677/main.cpp deleted file mode 100644 index fd33231d..00000000 --- a/0677-Map-Sum-Pairs/cpp-0677/main.cpp +++ /dev/null @@ -1,47 +0,0 @@ -/// Source : https://leetcode.com/problems/map-sum-pairs/description/ -/// Author : liuyubobobo -/// Time : 2017-11-05 - -#include -#include - -using namespace std; - -/// HashMap + Brute Force -/// Time Complexity: insert: O(1) -/// sum: O(n * len(prefix)) -/// Space Complexity: O(sum(len(wi))) where wi is the length of the ith word. -class MapSum { - -private: - unordered_map mapsum; - -public: - /** Initialize your data structure here. */ - MapSum() { - mapsum.clear(); - } - - void insert(string key, int val) { - mapsum[key] = val; - } - - int sum(string prefix) { - int ret = 0; - for(pair e: mapsum) - if(e.first.substr(0, prefix.size()) == prefix) - ret += e.second; - return ret; - } -}; - -int main() { - - MapSum obj; - obj.insert("apple", 3); - cout << obj.sum("ap") << endl; // 3 - obj.insert("app", 2); - cout << obj.sum("ap") << endl; // 5 - - return 0; -} \ No newline at end of file diff --git a/0677-Map-Sum-Pairs/cpp-0677/main2.cpp b/0677-Map-Sum-Pairs/cpp-0677/main2.cpp deleted file mode 100644 index bc5420a3..00000000 --- a/0677-Map-Sum-Pairs/cpp-0677/main2.cpp +++ /dev/null @@ -1,54 +0,0 @@ -/// Source : https://leetcode.com/problems/map-sum-pairs/description/ -/// Author : liuyubobobo -/// Time : 2017-11-05 - -#include -#include - -using namespace std; - -/// Prefix HashMap + Brute Force -/// Time Complexity: insert: O(len(prefix)^2) -/// sum: O(len(prefix)) -/// Space Complexity: O(sum(len(wi)^2)) where wi is the length of the ith word. -class MapSum { - -private: - unordered_map prefixScore; - unordered_map summap; -public: - /** Initialize your data structure here. */ - MapSum() { - summap.clear(); - prefixScore.clear(); - } - - void insert(string key, int val) { - - if(summap.find(key) == summap.end()){ - for(int i = 1 ; i <= key.size() ; i ++) - prefixScore[key.substr(0, i)] += val; - } - else{ - for(int i = 1 ; i <= key.size() ; i ++) - prefixScore[key.substr(0, i)] = val; - } - - summap[key] = val; - } - - int sum(string prefix) { - return prefixScore[prefix]; - } -}; - -int main() { - - MapSum obj; - obj.insert("apple", 3); - cout << obj.sum("ap") << endl; // 3 - obj.insert("app", 2); - cout << obj.sum("ap") << endl; // 5 - - return 0; -} \ No newline at end of file diff --git a/0677-Map-Sum-Pairs/cpp-0677/main3.cpp b/0677-Map-Sum-Pairs/cpp-0677/main3.cpp deleted file mode 100644 index b36f3fdf..00000000 --- a/0677-Map-Sum-Pairs/cpp-0677/main3.cpp +++ /dev/null @@ -1,103 +0,0 @@ -/// Source : https://leetcode.com/problems/map-sum-pairs/description/ -/// Author : liuyubobobo -/// Time : 2017-11-05 - -#include -#include -#include - -using namespace std; - -/// Trie -/// Time Complexity: insert: O(len(prefix)) -/// sum: O(sum(len(wi))) -/// Space Complexity: O(sum(len(wi))) where wi is the length of the ith word. - -class Trie{ - -private: - struct Node{ - map next; - int val = 0; - }; - vector trie; - -public: - Trie(){ - trie.clear(); - trie.push_back(Node()); - } - - void insert(const string& word, int val){ - insert(0, word, 0, val); - } - - int sum(const string& prefix){ - int treeID = findTreeID(0, prefix, 0); - if(treeID == -1) - return 0; - return dfs(treeID); - } - -private: - void insert(int treeID, const string& word, int index, int val){ - - if(index == word.size()) { - trie[treeID].val = val; - return; - } - - if(trie[treeID].next.find(word[index]) == trie[treeID].next.end()){ - trie[treeID].next[word[index]] = trie.size(); - trie.push_back(Node()); - } - - insert(trie[treeID].next[word[index]], word, index + 1, val); - } - - int findTreeID(int treeID, const string& word, int index){ - - if(index == word.size()) - return treeID; - - if(trie[treeID].next.find(word[index]) == trie[treeID].next.end()) - return -1; - - return findTreeID(trie[treeID].next[word[index]], word, index + 1); - } - - int dfs(int treeID){ - - int res = trie[treeID].val; - for(pair next: trie[treeID].next) - res += dfs(next.second); - return res; - } -}; - -class MapSum { - -private: - Trie trie; - -public: - - void insert(string key, int val) { - trie.insert(key, val); - } - - int sum(string prefix) { - return trie.sum(prefix); - } -}; - -int main() { - - MapSum obj; - obj.insert("apple", 3); - cout << obj.sum("ap") << endl; // 3 - obj.insert("app", 2); - cout << obj.sum("ap") << endl; // 5 - - return 0; -} \ No newline at end of file diff --git a/0677-Map-Sum-Pairs/cpp-0677/main4.cpp b/0677-Map-Sum-Pairs/cpp-0677/main4.cpp deleted file mode 100644 index b4babe53..00000000 --- a/0677-Map-Sum-Pairs/cpp-0677/main4.cpp +++ /dev/null @@ -1,117 +0,0 @@ -/// Source : https://leetcode.com/problems/map-sum-pairs/description/ -/// Author : liuyubobobo -/// Time : 2017-11-05 - -#include -#include -#include - -using namespace std; - -/// Trie -/// Update key value when key already in the trie -/// Time Complexity: insert: O(len(prefix)) -/// sum: O(len(prefix)) -/// Space Complexity: O(sum(len(wi))) where wi is the length of the ith word. - -class Trie{ - -private: - struct Node{ - map next; - int val = 0; - bool end = false; - }; - vector trie; - -public: - Trie(){ - trie.clear(); - trie.push_back(Node()); - } - - void insert(const string& word, int val){ - insert(0, word, 0, val); -// cout << "After insert " << word << ", trie is:" << endl; -// print(); - } - - int sum(const string& prefix){ - int treeID = findTreeID(0, prefix, 0); - if(treeID == -1) - return 0; - return trie[treeID].val; - } - -private: - int insert(int treeID, const string& word, int index, int val){ - - if(index == word.size()) { - - if(trie[treeID].end){ - int change = val - trie[treeID].val; - trie[treeID].val = val; - return change; - } - else{ - trie[treeID].end = true; - trie[treeID].val += val; - return val; - } - } - - if(trie[treeID].next.find(word[index]) == trie[treeID].next.end()){ - trie[treeID].next[word[index]] = trie.size(); - trie.push_back(Node()); - } - - int change = insert(trie[treeID].next[word[index]], word, index + 1, val); - trie[treeID].val += change; - - return change; - } - - int findTreeID(int treeID, const string& word, int index){ - - if(index == word.size()) - return treeID; - - if(trie[treeID].next.find(word[index]) == trie[treeID].next.end()) - return -1; - - return findTreeID(trie[treeID].next[word[index]], word, index + 1); - } - - void print(){ - for(Node node: trie) - cout << node.val << " "; - cout << endl; - } -}; - -class MapSum { - -private: - Trie trie; - -public: - - void insert(string key, int val) { - trie.insert(key, val); - } - - int sum(string prefix) { - return trie.sum(prefix); - } -}; - -int main() { - - MapSum obj; - obj.insert("apple", 3); - cout << obj.sum("ap") << endl; // 3 - obj.insert("app", 2); - cout << obj.sum("ap") << endl; // 5 - - return 0; -} \ No newline at end of file diff --git a/0699-Falling-Squares/cpp-0699/main.cpp b/0699-Falling-Squares/cpp-0699/main.cpp deleted file mode 100644 index b2ec486e..00000000 --- a/0699-Falling-Squares/cpp-0699/main.cpp +++ /dev/null @@ -1,74 +0,0 @@ -/// Source : https://leetcode.com/contest/leetcode-weekly-contest-54/problems/falling-squares/ -/// Author : liuyubobobo -/// Time : 2017-10-21 - -#include -#include -using namespace std; - -/// Using heights to record all the falling squares -/// Time Complexity: O(len(position)^2) -/// Space Complexity: O(len(position)) -class Solution { - -public: - vector fallingSquares(vector>& positions) { - - int n = positions.size(); - vector heights(n, 0); - for(int i = 0 ; i < positions.size() ; i ++){ - - heights[i] = positions[i].second; - for(int j = 0 ; j < i ; j ++) - if(intersection(positions[j], positions[i])) - heights[i] = max(heights[i], heights[j] + positions[i].second); - } - - vector res(n, 0); - res[0] = heights[0]; - for(int i = 1 ; i < n ; i ++) - res[i] = max(heights[i], res[i-1]); - - return res; - } - -private: - bool intersection(const pair& a, const pair& b){ - int l1 = a.first; - int r1 = a.first + a.second - 1; - int l2 = b.first; - int r2 = b.first + b.second - 1; - - if(l1 > r2 || l2 > r1) - return false; - - return true; - } -}; - - -void printVec(const vector& vec){ - - for(int i = 0 ; i < vec.size() ; i ++) - cout << vec[i] << ((i == vec.size() - 1) ? '\n' : ' '); -} - - -int main() { - - vector> va; - va.push_back(make_pair(1, 2)); - va.push_back(make_pair(2, 3)); - va.push_back(make_pair(6, 1)); - vector res1 = Solution().fallingSquares(va); - printVec(res1); - - - vector> vb; - vb.push_back(make_pair(100, 100)); - vb.push_back(make_pair(200, 100)); - vector res2 = Solution().fallingSquares(vb); - printVec(res2); - - return 0; -} \ No newline at end of file diff --git a/0699-Falling-Squares/cpp-0699/main2.cpp b/0699-Falling-Squares/cpp-0699/main2.cpp deleted file mode 100644 index 184f9edd..00000000 --- a/0699-Falling-Squares/cpp-0699/main2.cpp +++ /dev/null @@ -1,87 +0,0 @@ -/// Source : https://leetcode.com/contest/leetcode-weekly-contest-54/problems/falling-squares/ -/// Author : liuyubobobo -/// Time : 2017-10-28 - -#include -#include -#include -#include -#include - -using namespace std; - -/// Coordinates compression and simulation -/// Time Complexity: O(len(position)^2) -/// Space Complexity: O(len(position)) -class Solution { - -public: - vector fallingSquares(vector>& positions) { - - int n = positions.size(); - set unique_pos; - for(pair position: positions){ - unique_pos.insert(position.first); - unique_pos.insert(position.first + position.second - 1); - } - - map indexes; // pos -> index - vector pos; // index -> pos - for(int p: unique_pos){ - indexes[p] = pos.size(); - pos.push_back(p); - } - - assert(indexes.size() == pos.size()); - vector heights(indexes.size(), 0); - vector res; - for(pair position: positions){ - - int startIndex = indexes[position.first]; - int rightBound = position.first + position.second - 1; - - int best = 0; - for(int i = startIndex ; i < pos.size() && pos[i] <= rightBound ; i ++) - best = max(best, heights[i]); - - for(int i = startIndex ; i < pos.size() && pos[i] <= rightBound ; i ++) - heights[i] = best + position.second; - - best = 0; - for(int i = 0 ; i < heights.size() ; i ++) - best = max(best, heights[i]); - - res.push_back(best); - } - - return res; - } - -}; - - -void printVec(const vector& vec){ - - for(int i = 0 ; i < vec.size() ; i ++) - cout << vec[i] << ((i == vec.size() - 1) ? '\n' : ' '); -} - - -int main() { - - vector> va; - va.push_back(make_pair(1, 2)); - va.push_back(make_pair(2, 3)); - va.push_back(make_pair(6, 1)); - vector res1 = Solution().fallingSquares(va); - printVec(res1); - - - vector> vb; - vb.push_back(make_pair(100, 100)); - vb.push_back(make_pair(200, 100)); - vector res2 = Solution().fallingSquares(vb); - printVec(res2); - - return 0; -} \ No newline at end of file diff --git a/0716-Max-Stack/cpp-0716/CMakeLists.txt b/0716-Max-Stack/cpp-0716/CMakeLists.txt deleted file mode 100644 index 60bc5041..00000000 --- a/0716-Max-Stack/cpp-0716/CMakeLists.txt +++ /dev/null @@ -1,7 +0,0 @@ -cmake_minimum_required(VERSION 3.5) -project(cpp_0716) - -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") - -set(SOURCE_FILES main3.cpp) -add_executable(cpp_0716 ${SOURCE_FILES}) \ No newline at end of file diff --git a/0716-Max-Stack/cpp-0716/main.cpp b/0716-Max-Stack/cpp-0716/main.cpp deleted file mode 100644 index 4f9d95bd..00000000 --- a/0716-Max-Stack/cpp-0716/main.cpp +++ /dev/null @@ -1,91 +0,0 @@ -/// Source : https://leetcode.com/problems/max-stack/description/ -/// Author : liuyubobobo -/// Time : 2017-11-16 - -#include -#include -#include - -using namespace std; - -/// Using two sets -/// Time Complexity: push: O(logn) -/// pop: O(logn) -/// top: O(logn) -/// peekMax: O(logn) -/// popMax: O(logn) -/// Space Complexity: O(n) -class MaxStack { - -private: - int index = 0; - set> vi; // value - index - set> iv; // index - value - -public: - /** initialize your data structure here. */ - MaxStack() { - vi.clear(); - iv.clear(); - index = 0; - } - - void push(int x) { - vi.insert(make_pair(x, index)); - iv.insert(make_pair(index, x)); - index ++; - } - - int pop() { - - assert(iv.size() > 0); - - pair e_iv = *iv.rbegin(); - iv.erase(e_iv); - - pair e_vi = make_pair(e_iv.second, e_iv.first); - vi.erase(e_vi); - - return e_iv.second; - } - - int top() { - assert(iv.size() > 0); - return iv.rbegin()->second; - } - - int peekMax() { - assert(vi.size() > 0); - return vi.rbegin()->first; - } - - int popMax() { - - assert(vi.size() > 0); - - pair e_vi = *vi.rbegin(); - vi.erase(e_vi); - - pair e_iv = make_pair(e_vi.second, e_vi.first); - iv.erase(e_iv); - - return e_vi.first; - } -}; - - -int main() { - - MaxStack stack; - stack.push(5); - stack.push(1); - stack.push(5); - cout << stack.top() << endl; // -> 5 - cout << stack.popMax() << endl; // -> 5 - cout << stack.top() << endl; // -> 1 - cout << stack.peekMax() << endl; // -> 5 - cout << stack.pop() << endl; // -> 1 - cout << stack.top() << endl; // -> 5 - - return 0; -} \ No newline at end of file diff --git a/0716-Max-Stack/cpp-0716/main2.cpp b/0716-Max-Stack/cpp-0716/main2.cpp deleted file mode 100644 index cb931f9e..00000000 --- a/0716-Max-Stack/cpp-0716/main2.cpp +++ /dev/null @@ -1,107 +0,0 @@ -/// Source : https://leetcode.com/problems/max-stack/description/ -/// Author : liuyubobobo -/// Time : 2017-11-27 - -#include -#include -#include - -using namespace std; - -/// Using two stacks -/// We have one regular stack for push, pop and top operations -/// We have another stack for peekMax and popMax operations, which named maxStack -/// maxStack will store the current max value in the stack -/// for popMax, we will find the max value in the stack in O(n) time -/// -/// Time Complexity: push: O(1) -/// pop: O(1) -/// top: O(1) -/// peekMax: O(1) -/// popMax: O(n) -/// Space Complexity: O(n) -class MaxStack { - -private: - stack normalStack; - stack maxStack; - -public: - /** initialize your data structure here. */ - MaxStack() { - while(!normalStack.empty()) - normalStack.pop(); - - while(!maxStack.empty()) - maxStack.pop(); - } - - void push(int x) { - normalStack.push(x); - if(maxStack.empty()) - maxStack.push(x); - else - maxStack.push(max(maxStack.top(), x)); - } - - int pop() { - - assert(normalStack.size() > 0); - - int v = normalStack.top(); - normalStack.pop(); - maxStack.pop(); - - return v; - } - - int top() { - assert(normalStack.size() > 0); - return normalStack.top(); - } - - int peekMax() { - assert(normalStack.size() > 0); - return maxStack.top(); - } - - int popMax() { - - assert(normalStack.size() > 0); - - int maxValue = peekMax(); - stack tstack; - - while(true){ - int value = pop(); - - if(value == maxValue) - break; - - tstack.push(value); - } - - while(!tstack.empty()){ - push(tstack.top()); - tstack.pop(); - } - - return maxValue; - } -}; - -int main() { - - MaxStack stack; - stack.push(5); - stack.push(1); - stack.push(5); - cout << stack.top() << endl; // -> 5 - cout << stack.popMax() << endl; // -> 5 - cout << stack.top() << endl; // -> 1 - cout << stack.peekMax() << endl; // -> 5 - cout << stack.pop() << endl; // -> 1 - cout << stack.top() << endl; // -> 5 - - return 0; -} \ No newline at end of file diff --git a/0716-Max-Stack/cpp-0716/main3.cpp b/0716-Max-Stack/cpp-0716/main3.cpp deleted file mode 100644 index 8b62d5d8..00000000 --- a/0716-Max-Stack/cpp-0716/main3.cpp +++ /dev/null @@ -1,137 +0,0 @@ -/// Source : https://leetcode.com/problems/max-stack/description/ -/// Author : liuyubobobo -/// Time : 2017-11-27 - -#include -#include -#include -#include -#include - -using namespace std; - -/// Using a list to simulate th stack -/// Using a TreeMap to record every node in the list -/// So we can get the max value in the list quickly and erase it easily -/// -/// Time Complexity: push: O(1) -/// pop: O(1) -/// top: O(1) -/// peekMax: O(1) -/// popMax: O(logn) -/// Space Complexity: O(n) -class MaxStack { - -private: - list stack; - map::iterator>> record; - -public: - /** initialize your data structure here. */ - MaxStack() { - stack.clear(); - record.clear(); - } - - void push(int x) { - stack.push_back(x); - - list::iterator iter = stack.begin(); - advance(iter, stack.size() - 1); - - record[x].push_back(iter); - } - - int pop() { - - int ret = stack.back(); - stack.pop_back(); - - record[ret].pop_back(); - if(record[ret].size() == 0) - record.erase(ret); - - return ret; - } - - int top() { - assert(stack.size() > 0); - return stack.back(); - } - - int peekMax() { - assert(stack.size() > 0); - return record.rbegin()->first; - } - - int popMax() { - assert(stack.size() > 0); - int ret = record.rbegin()->first; - - stack.erase((record.rbegin()->second).back()); - (record.rbegin()->second).pop_back(); - if((record.rbegin()->second).size() == 0) - record.erase(ret); - return ret; - } -}; - - -int main() { - - MaxStack stack1; - stack1.push(5); - stack1.push(1); - stack1.push(5); - cout << stack1.top() << endl; // -> 5 - cout << stack1.popMax() << endl; // -> 5 - cout << stack1.top() << endl; // -> 1 - cout << stack1.peekMax() << endl; // -> 5 - cout << stack1.pop() << endl; // -> 1 - cout << stack1.top() << endl; // -> 5 - cout << endl; - - // --- - - MaxStack stack2; - stack2.push(-83); - stack2.push(-1); - stack2.push(98); - stack2.push(38); - stack2.push(-99); - cout << stack2.top() << endl; // -> -99 - cout << stack2.popMax() << endl; // -> 98 - cout << stack2.popMax() << endl; // -> 38 - stack2.push(-92); - stack2.push(-17); - stack2.push(-1); - stack2.push(-74); - cout << stack2.popMax() << endl; // -> -1 - cout << stack2.pop() << endl; // -> -74 - cout << stack2.popMax() << endl; // -> -1 - stack2.push(-80); - stack2.push(-13); - cout << stack2.top() << endl; // -13 - stack2.push(-25); - cout << endl; - - // --- - - MaxStack stack3; - stack3.push(74); - cout << stack3.popMax() << endl; // -> 74 - stack3.push(89); - stack3.push(67); - cout << stack3.popMax() << endl; // -> 89 - cout << stack3.pop() << endl; // -> 67 - stack3.push(61); - stack3.push(-77); - cout << stack3.peekMax() << endl; // 61 - cout << stack3.popMax() << endl; // 61 - stack3.push(81); - cout << stack3.pop() << endl; // 81 - stack3.push(-71); - stack3.push(32); - - return 0; -} \ No newline at end of file diff --git a/0719-Find-K-th-Smallest-Pair-Distance/cpp-0719/main.cpp b/0719-Find-K-th-Smallest-Pair-Distance/cpp-0719/main.cpp deleted file mode 100644 index b35b51fe..00000000 --- a/0719-Find-K-th-Smallest-Pair-Distance/cpp-0719/main.cpp +++ /dev/null @@ -1,57 +0,0 @@ -/// Source : https://leetcode.com/problems/find-k-th-smallest-pair-distance/description/ -/// Author : liuyubobobo -/// Time : 2017-10-28 - -#include -#include -#include -#include - -using namespace std; - -/// Time Complexity: O(nlogn + n^2 + W) -/// Space Complexity: O(W), where W = max(nums) - min(nums) -class Solution { -public: - int smallestDistancePair(vector& nums, int k) { - - int dis[1000000]; - for(int i = 0 ; i < 1000000 ; i ++) - dis[i] = 0; - - sort(nums.begin(), nums.end()); - for(int i = 0 ; i < nums.size() ; i ++) - for(int j = i + 1 ; j < nums.size() ; j ++){ - //cout << nums[j] - nums[i] << endl; - dis[nums[j]-nums[i]] ++; - } - - int index = 0; - for(int i = 0 ; i < 1000000 ; i ++){ - index += dis[i]; - if(k <= index) - return i; - } - - return -1; - } -}; - -int main() { - - int nums1[] = {1, 3, 1}; - int k1 = 1; - vector vec1(nums1, nums1 + sizeof(nums1)/sizeof(int)); - cout << Solution().smallestDistancePair(vec1, k1) << endl; - // 0 - - // --- - - int nums2[] = {1, 6, 1}; - int k2 = 3; - vector vec2(nums2, nums2 + sizeof(nums2)/sizeof(int)); - cout << Solution().smallestDistancePair(vec2, k2) << endl; - // 5 - - return 0; -} \ No newline at end of file diff --git a/0727-Minimum-Window-Subsequence/cpp-0727/main.cpp b/0727-Minimum-Window-Subsequence/cpp-0727/main.cpp deleted file mode 100644 index 1ac865ab..00000000 --- a/0727-Minimum-Window-Subsequence/cpp-0727/main.cpp +++ /dev/null @@ -1,78 +0,0 @@ -/// Source : https://leetcode.com/contest/weekly-contest-58/problems/minimum-window-subsequence/ -/// Author : liuyubobobo -/// Time : 2017-11-11 - -#include -#include -#include -#include - -using namespace std; - -/// Memory Search -/// -/// !!! Memory Limit Exceed !!! -/// -/// Time Complexity: O(len(S)*len(T)) -/// Space Complexity: O(len(S)*len(T)) - -class Solution { - -private: - int MY_MAX_INT = 20001; - -public: - string minWindow(string S, string T) { - - vector> mem(20001, vector(101, -1)); - - int min_length = MY_MAX_INT; - int start = -1; - for(int i = 0 ; i < S.size() ; i ++){ - search(mem, S, i, T, 0); - assert(mem[i][0] != -1); - //cout << mem[i][0] << endl; - if(mem[i][0] < min_length){ - min_length = mem[i][0]; - start = i; - } - } - - for(int i = 0 ; i < S.size() ; i ++){ - for(int j = 0 ; j < T.size() ; j ++) - cout << mem[i][j] << "\t"; - cout << endl; - } - //cout << start << " " << min_length << endl; - return start == -1 ? "" : S.substr(start, min_length); - return ""; - } - -private: - int search(vector>& mem, - const string& S, int i1, const string& T, int i2){ - - if(i2 == T.size()) - return 0; - - if(i1 == S.size()) - return MY_MAX_INT; - - if(mem[i1][i2] != -1) - return mem[i1][i2]; - - int res = 1 + search(mem, S, i1+1, T, i2); - if(S[i1] == T[i2]) - res = min(res, 1 + search(mem, S, i1+1, T, i2+1)); - return mem[i1][i2] = res; - } -}; - -int main() { - - string S1 = "abcdebdde"; - string T1 = "bde"; - cout << Solution().minWindow(S1, T1) << endl; - - return 0; -} \ No newline at end of file diff --git a/0727-Minimum-Window-Subsequence/cpp-0727/main2.cpp b/0727-Minimum-Window-Subsequence/cpp-0727/main2.cpp deleted file mode 100644 index 2ce133ff..00000000 --- a/0727-Minimum-Window-Subsequence/cpp-0727/main2.cpp +++ /dev/null @@ -1,84 +0,0 @@ -/// Source : https://leetcode.com/contest/weekly-contest-58/problems/minimum-window-subsequence/ -/// Author : liuyubobobo -/// Time : 2017-11-12 - -#include -#include -#include -#include - -/// Dynamic Programming with Rolling 1-D Array -/// dp[i][j] - the minimum length W for subsequence in S[i...end) to satify T[j...end) -/// the result is the minimum value for all dp[i][0] where len(S[i...end)) > len(T) -/// -/// Time Complexity: O(len(S)*len(T)) -/// Space Complexity: O(len(T)) -using namespace std; - -class Solution { - -private: - int MY_MAX_INT = 20001; - -public: - string minWindow(string S, string T) { - - vector> dp(2, vector(T.size(), MY_MAX_INT)); - - int min_length = MY_MAX_INT; - int start = -1; - - dp[(S.size()-1)%2][T.size()-1] = (S.back() == T.back() ? 1 : MY_MAX_INT); - if(dp[(S.size()-1)%2][0] == 1 && T.size() == 1){ - min_length = 1; - start = S.size()-1; - } - else - for(int j = T.size()-2 ; j >= 0 ; j --) - dp[(S.size()-1)%2][j] = MY_MAX_INT; - - for(int i = S.size()-2 ; i >= 0 ; i --){ - dp[i%2][T.size()-1] = dp[(i+1)%2][T.size()-1] + 1; - if(S[i] == T.back()) - dp[i%2][T.size()-1] = 1; - - for(int j = T.size() - 2 ; j >= 0 ; j --){ - dp[i%2][j] = min(MY_MAX_INT, 1 + dp[(i+1)%2][j]); - if(S[i] == T[j]) - dp[i%2][j] = min(dp[i%2][j], 1 + dp[(i+1)%2][j+1]); - } - - if(i + T.size() <= S.size() && dp[i%2][0] <= min_length){ - min_length = dp[i%2][0]; - start = i; - } - } - - return (start != -1 && min_length < MY_MAX_INT) ? - S.substr(start, min_length) : ""; - } -}; - -int main() { - - string S1 = "abcdebdde"; - string T1 = "bde"; - cout << Solution().minWindow(S1, T1) << endl; - // bcde - - // --- - - string S2 = "ab"; - string T2 = "b"; - cout << Solution().minWindow(S2, T2) << endl; - // b - - // --- - - string S3 = "cnhczmccqouqadqtmjjzl"; - string T3 = "mm"; - cout << Solution().minWindow(S3, T3) << endl; - // mccqouqadqtm - - return 0; -} \ No newline at end of file diff --git a/0727-Minimum-Window-Subsequence/cpp-0727/main3.cpp b/0727-Minimum-Window-Subsequence/cpp-0727/main3.cpp deleted file mode 100644 index 3b51228d..00000000 --- a/0727-Minimum-Window-Subsequence/cpp-0727/main3.cpp +++ /dev/null @@ -1,89 +0,0 @@ -/// Source : https://leetcode.com/contest/weekly-contest-58/problems/minimum-window-subsequence/ -/// Author : liuyubobobo -/// Time : 2017-11-12 - -#include -#include -#include -#include - -/// Dynamic Programming with Rolling 1-D Array -/// dp[i][j] - the largest start index s for S[s...i] to satify T[0...j] -/// -/// Time Complexity: O(len(S)*len(T)) -/// Space Complexity: O(len(S)) -using namespace std; - -class Solution { - -private: - int MY_MAX_INT = 20001; - -public: - string minWindow(string S, string T) { - - if(T.size() == 1 && S.find(T[0]) != string::npos) - return T; - - vector> dp(2, vector(S.size(), -1)); - - dp[0][0] = (S[0] == T[0]) ? 0 : -1; - for(int j = 1 ; j < S.size() ; j ++) - dp[0][j] = (S[j] == T[0]) ? j : dp[0][j-1]; - - for(int i = 1 ; i < T.size() ; i ++){ - for(int j = 0 ; j < i ; j ++) - dp[i%2][j] = -1; - for(int j = i ; j < S.size() ; j ++){ - dp[i%2][j] = dp[i%2][j-1]; - if(T[i] == S[j]) - dp[i%2][j] = max(dp[(i-1)%2][j-1], dp[i%2][j]); - } - } - - int min_length = MY_MAX_INT; - int start = -1; - for(int j = T.size() - 1 ; j < S.size() ; j ++) - if(dp[(T.size()-1)%2][j] != -1){ - int length = j - dp[(T.size()-1)%2][j] + 1; - assert(length > 0); - if(length < min_length){ - min_length = length; - start = dp[(T.size()-1)%2][j]; - } - } - return (start != -1 && min_length < MY_MAX_INT) ? - S.substr(start, min_length) : ""; - } -}; - -int main() { - - string S1 = "abcdebdde"; - string T1 = "bde"; - cout << Solution().minWindow(S1, T1) << endl; - // bcde - - // --- - - string S2 = "ab"; - string T2 = "b"; - cout << Solution().minWindow(S2, T2) << endl; - // b - - // --- - - string S3 = "cnhczmccqouqadqtmjjzl"; - string T3 = "mm"; - cout << Solution().minWindow(S3, T3) << endl; - // mccqouqadqtm - - // --- - - string S4 = "clgkckxqhqojiroohcudeyhlylicvafvpbubcjictifyoshucybzswblioaflxaoxdjbjejvzgqiuedmzgmqbhpkjlwxvobrcgqhzzelxppwdkwqlplflnldxpkwobqyqhqbfcxolrmrllmzpgjemzhscagqxhyuqquopquyyxwcuetxnxebbrgsbiwtkqdpqmvsprrnyficfxagfsssvppwqdsqesz"; - string T4 = "cihfrleqav"; - cout << Solution().minWindow(S4, T4) << endl; - // cybzswblioaflxaoxdjbjejvzgqiuedmzgmqbhpkjlwxvobrcgqhzzelxppwdkwqlplflnldxpkwobqyqhqbfcxolrmrllmzpgjemzhscagqxhyuqquopquyyxwcuetxnxebbrgsbiwtkqdpqmvsprrnyficfxagfsssv - - return 0; -} \ No newline at end of file diff --git a/0728-Self-Dividing-Numbers/cpp-0728/main.cpp b/0728-Self-Dividing-Numbers/cpp-0728/main.cpp deleted file mode 100644 index ed8c62a4..00000000 --- a/0728-Self-Dividing-Numbers/cpp-0728/main.cpp +++ /dev/null @@ -1,50 +0,0 @@ -/// Source : https://leetcode.com/problems/longest-increasing-subsequence/description/ -/// Author : liuyubobobo -/// Time : 2017-11-18 - -#include -#include - -using namespace std; - -/// Ad-Hoc -/// Time Complexity: O((right-left+1)*log10(right)) -/// Space Complexity: O(1) -class Solution { - -public: - vector selfDividingNumbers(int left, int right) { - - vector res; - for(int i = left ; i <= right ; i ++) - if(selfDividing(i)) - res.push_back(i); - return res; - } - -private: - bool selfDividing(int num){ - int t = num; - while(t){ - int x = t % 10; - t /= 10; - if(x == 0 || num % x != 0) - return false; - } - return true; - } -}; - - -void printVec(const vector& vec){ - for(int e: vec) - cout << e << " "; - cout << endl; -} - -int main() { - - printVec(Solution().selfDividingNumbers(1, 22)); - - return 0; -} \ No newline at end of file diff --git a/0734-Sentence-Similarity/cpp-0734/main.cpp b/0734-Sentence-Similarity/cpp-0734/main.cpp deleted file mode 100644 index ef064205..00000000 --- a/0734-Sentence-Similarity/cpp-0734/main.cpp +++ /dev/null @@ -1,57 +0,0 @@ -/// Source : https://leetcode.com/problems/sentence-similarity/solution/ -/// Author : liuyubobobo -/// Time : 2017-11-25 - -#include -#include -#include - -using namespace std; - -/// Using Set -/// Saving Pairs -/// Time Complexity: O(len(pairs) + len(s)) -/// Space Complexity: O(len(pairs)) -class Solution { -public: - bool areSentencesSimilar(vector& words1, vector& words2, vector> pairs) { - - if(words1.size() != words2.size()) - return false; - - if(words1.size() == 0) - return true; - - set> similarity; - for(pair p: pairs) { - similarity.insert(make_pair(p.first, p.second)); - similarity.insert(make_pair(p.second, p.first)); - } - - for(int i = 0 ; i < words1.size() ; i ++) - if(words1[i] != words2[i] && similarity.find(make_pair(words1[i], words2[i])) == similarity.end()) - return false; - - return true; - } -}; - - -void printBool(bool res){ - cout << (res ? "True" : "False") << endl; -} - -int main() { - - vector words1 = {"great", "acting", "skills"}; - vector words2 = {"fine", "drama", "talent"}; - - vector> pairs; - pairs.push_back(make_pair("great", "fine")); - pairs.push_back(make_pair("acting", "drama")); - pairs.push_back(make_pair("skills", "talent")); - - printBool(Solution().areSentencesSimilar(words1, words2, pairs)); - - return 0; -} \ No newline at end of file diff --git a/0734-Sentence-Similarity/cpp-0734/main2.cpp b/0734-Sentence-Similarity/cpp-0734/main2.cpp deleted file mode 100644 index 65fc2797..00000000 --- a/0734-Sentence-Similarity/cpp-0734/main2.cpp +++ /dev/null @@ -1,59 +0,0 @@ -/// Source : https://leetcode.com/problems/sentence-similarity/solution/ -/// Author : liuyubobobo -/// Time : 2017-11-25 - -#include -#include -#include - -using namespace std; - -/// Using Set -/// Saving Pairs String -/// Time Complexity: O(len(pairs) + len(s)) -/// Space Complexity: O(len(pairs)) -class Solution { -public: - bool areSentencesSimilar(vector& words1, vector& words2, vector> pairs) { - - if(words1.size() != words2.size()) - return false; - - if(words1.size() == 0) - return true; - - set similarity; - for(pair p: pairs) { - string hashcode1 = p.first + "#" + p.second; - string hashcode2 = p.second + "#" + p.first; - similarity.insert(hashcode1); - similarity.insert(hashcode2); - } - - for(int i = 0 ; i < words1.size() ; i ++) - if(words1[i] != words2[i] && similarity.find(words1[i] + "#" + words2[i]) == similarity.end()) - return false; - - return true; - } -}; - - -void printBool(bool res){ - cout << (res ? "True" : "False") << endl; -} - -int main() { - - vector words1 = {"great", "acting", "skills"}; - vector words2 = {"fine", "drama", "talent"}; - - vector> pairs; - pairs.push_back(make_pair("great", "fine")); - pairs.push_back(make_pair("acting", "drama")); - pairs.push_back(make_pair("skills", "talent")); - - printBool(Solution().areSentencesSimilar(words1, words2, pairs)); - - return 0; -} \ No newline at end of file diff --git a/0793-Preimage-Size-of-Factorial-Zeroes-Function/cpp-0793/main.cpp b/0793-Preimage-Size-of-Factorial-Zeroes-Function/cpp-0793/main.cpp deleted file mode 100644 index 4eab670c..00000000 --- a/0793-Preimage-Size-of-Factorial-Zeroes-Function/cpp-0793/main.cpp +++ /dev/null @@ -1,52 +0,0 @@ -/// Source : https://leetcode.com/problems/preimage-size-of-factorial-zeroes-function/description/ -/// Author : liuyubobobo -/// Time : 2018-03-03 - -#include - -using namespace std; - -/// Binary Search -/// Time Complexity: O(logK * logK) -/// Space Complexity: O(1) -class Solution { -public: - int preimageSizeFZF(int K) { - - if(K == 0) - return 5; - - int l = 0, r = 1000000000; - while(l <= r){ - int mid = (l + r) / 2; - int f_res = f(mid); - if(f_res == K) - return 5; - else if(f_res > K) - r = mid - 1; - else - l = mid + 1; - } - - return 0; - } - -private: - int f(int x){ - int res = 0; - int factor = 5; - while(factor <= x){ - res += x / factor; - factor *= 5; - } - return res; - } -}; - -int main() { - - cout << Solution().preimageSizeFZF(0) << endl; - cout << Solution().preimageSizeFZF(5) << endl; - - return 0; -} \ No newline at end of file diff --git a/0805-Split-Array-With-Same-Average/cpp-0805/main.cpp b/0805-Split-Array-With-Same-Average/cpp-0805/main.cpp deleted file mode 100644 index 34763118..00000000 --- a/0805-Split-Array-With-Same-Average/cpp-0805/main.cpp +++ /dev/null @@ -1,84 +0,0 @@ -/// Source : https://leetcode.com/problems/split-array-with-same-average/description/ -/// Author : liuyubobobo -/// Time : 2018-03-24 - -#include -#include -#include -#include - -using namespace std; - -/// Dynamic Programming -/// -/// Suppose the same average is ave, then ave = sum(A) / len(A) -/// Try how many items B contains from 1 to len(A)/2 -/// Suppose B contains i items, then sum(B) = i * ave -/// This sub-problem can be solved by dynamic programming -/// -/// Time Complexity: O(len(A) * len(A) * sum(A)) -/// Space Complexity: O(len(A) * sum(A)) -class Solution { - -public: - bool splitArraySameAverage(vector& A) { - - int m = A.size(); - int sum = accumulate(A.begin(), A.end(), 0); - - for(int i = 1 ; i <= m/2 ; i ++) - if((sum * i) % m == 0 && ok(A, (sum * i) / m, i)) - return true; - - return false; - } - -private: - bool ok(const vector& A, int c, int num){ - - vector> dp(c + 1, unordered_set()); - dp[0].insert(0); - - for(int a: A) - for(int i = c ; i >= a ; i --) - if(dp[i - a].size() != 0) - if(a == 0) { // dp[i-a] is dp[i] - vector tmp(dp[i].begin(), dp[i].end()); - for(int i = 0 ; i < tmp.size() ; i ++) - tmp[i] ++; - for(int e: tmp) - dp[i].insert(e); - } - else{ - for(int x: dp[i - a]) - dp[i].insert(x + 1); - } - return dp[c].find(num) != dp[c].end(); - } -}; - -void print_bool(bool res){ - cout << (res ? "True" : "False") << endl; -} - - -int main() { - - vector A1 = {1,2,3,4,5,6,7,8}; - print_bool(Solution().splitArraySameAverage(A1)); - // true - - vector A2 = {3, 1}; - print_bool(Solution().splitArraySameAverage(A2)); - // false - - vector A3 = {18, 10, 5, 3}; - print_bool(Solution().splitArraySameAverage(A3)); - // false - - vector A4 = {2,0,5,6,16,12,15,12,4}; - print_bool(Solution().splitArraySameAverage(A4)); - // true - - return 0; -} \ No newline at end of file diff --git a/0805-Split-Array-With-Same-Average/cpp-0805/main2.cpp b/0805-Split-Array-With-Same-Average/cpp-0805/main2.cpp deleted file mode 100644 index 0f7a95bf..00000000 --- a/0805-Split-Array-With-Same-Average/cpp-0805/main2.cpp +++ /dev/null @@ -1,166 +0,0 @@ -/// Source : https://leetcode.com/problems/split-array-with-same-average/description/ -/// Author : liuyubobobo -/// Time : 2018-03-24 - -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace std; - -/// Meet in the Middle -/// -/// Using a Custom Fraction class -/// The Algorithm is based on the official solution: -/// https://leetcode.com/problems/split-array-with-same-average/solution/ -/// -/// Time Complexity: O(2^(N/2)) -/// Space Complexity: O(2^(N/2)) - -class Fraction{ - -private: - int num, denom; - -public: - Fraction(int a = 0, int b = 1): num(a), denom(b){ - - if(num == 0) - denom = 1; - else{ - if(denom < 0){ - num = -num; - denom = -denom; - } - int g = gcd(abs(num), denom); - num /= g; - denom /= g; - } - } - - Fraction operator-(const Fraction& another){ - return Fraction(num * another.denom - another.num * denom, - denom * another.denom); - } - - Fraction operator-(){ - return Fraction(-num, denom); - } - - Fraction operator+(const Fraction& another){ - return Fraction(num * another.denom + another.num * denom, - denom * another.denom); - } - - string hash_string() const{ - return to_string(num) + "/" + to_string(denom); - } - -private: - int gcd(int a, int b){ - - if(a < b) - swap(a, b); - // a > b - if(a % b == 0) - return b; - return gcd(b, a % b); - } -}; - -bool operator==(const Fraction& f1, const Fraction& f2) { - return f1.hash_string() == f2.hash_string(); -} - -bool operator!=(const Fraction& f1, const Fraction& f2) { - return !(f1 == f2); -} - -// Custom Hash Function for Fraction -namespace std { - template<> - struct hash { - size_t operator()(Fraction const &f) const noexcept { - return std::hash{}(f.hash_string()); - } - }; -} - -class Solution { -public: - bool splitArraySameAverage(vector& A) { - - int sum = accumulate(A.begin(), A.end(), 0); - Fraction average(sum , A.size()); - - vector v; - for(int a: A) - v.push_back(Fraction(a, 1) - average); - - unordered_set left_bag = get_sum(v, 0, A.size()/2); - if(left_bag.find(Fraction(0, 1)) != left_bag.end()) - return true; - - unordered_set right_bag = get_sum(v, A.size()/2, A.size()); - if(right_bag.find(Fraction(0, 1)) != right_bag.end()) - return true; - - Fraction leftsum = accumulate(v.begin(), v.begin() + v.size() / 2, Fraction(0, 1)); - Fraction rightsum = accumulate(v.begin() + v.size() / 2, v.end(), Fraction(0, 1)); - for(Fraction num: left_bag) - if(num != leftsum && right_bag.find(-num) != right_bag.end()) - return true; - - return false; - } - -private: - unordered_set get_sum(const vector& v, int l, int r){ - - unordered_set bag; - for(int i = l ; i < r ; i ++){ - unordered_set new_bag; - for(Fraction e: bag) - new_bag.insert(e + v[i]); - bag.insert(new_bag.begin(), new_bag.end()); - bag.insert(v[i]); - } - - return bag; - } -}; - -void print_bool(bool res){ - cout << (res ? "True" : "False") << endl; -} - - -int main() { - - vector A1 = {1,2,3,4,5,6,7,8}; - print_bool(Solution().splitArraySameAverage(A1)); - // true - - vector A2 = {3, 1}; - print_bool(Solution().splitArraySameAverage(A2)); - // false - - vector A3 = {18, 10, 5, 3}; - print_bool(Solution().splitArraySameAverage(A3)); - // false - - vector A4 = {2,0,5,6,16,12,15,12,4}; - print_bool(Solution().splitArraySameAverage(A4)); - // true - - vector A5 = {10,29,13,53,33,48,76,70,5,5}; - print_bool(Solution().splitArraySameAverage(A5)); - // true - - return 0; -} \ No newline at end of file diff --git a/1001-1500/1001-Grid-Illumination/cpp-1001/CMakeLists.txt b/1001-1500/1001-Grid-Illumination/cpp-1001/CMakeLists.txt new file mode 100644 index 00000000..d20b982d --- /dev/null +++ b/1001-1500/1001-Grid-Illumination/cpp-1001/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) \ No newline at end of file diff --git a/1001-1500/1001-Grid-Illumination/cpp-1001/main.cpp b/1001-1500/1001-Grid-Illumination/cpp-1001/main.cpp new file mode 100644 index 00000000..4dcaa5f9 --- /dev/null +++ b/1001-1500/1001-Grid-Illumination/cpp-1001/main.cpp @@ -0,0 +1,77 @@ +/// Source : https://leetcode.com/problems/grid-illumination/ +/// Author : liuyubobobo +/// Time : 2019-02-23 + +#include +#include +#include +#include + +using namespace std; + + +/// Using HashSet +/// Time Complexity: O(n + q) +/// Space Complexity : O(n) +class Solution { +public: + vector gridIllumination(int N, vector>& lamps, vector>& queries) { + + set> lamp_set; + for(const vector& lamp: lamps){ + int x = lamp[0], y = lamp[1]; + lamp_set.insert(make_pair(x, y)); + } + + unordered_map row, col, dia1, dia2; + for(const pair& lamp: lamp_set){ + int x = lamp.first, y = lamp.second; + row[x] ++; + col[y] ++; + dia1[x - y] ++; + dia2[x + y] ++; + } + + vector res; + for(const vector& q: queries){ + int x = q[0], y = q[1]; + if(row[x] || col[y] || dia1[x - y] || dia2[x + y]) + res.push_back(1); + else res.push_back(0); + + for(int i = -1; i <= 1; i ++) + for(int j = -1; j <= 1; j ++){ + int xx = x + i, yy = y + j; + pair pp = make_pair(xx, yy); + if(lamp_set.count(pp)){ + lamp_set.erase(pp); + row[xx] --; + col[yy] --; + dia1[xx - yy] --; + dia2[xx + yy] --; + } + } + } + return res; + } +}; + + +void print_vec(const vector& vec){ + for(int e: vec) cout << e << " "; + cout << endl; +} + +int main() { + + vector> lamps1 = {{0, 0}, {4, 4}}; + vector> queries1 = {{1, 1}, {1, 0}}; + print_vec(Solution().gridIllumination(5, lamps1, queries1)); + + vector> lamps2 = {{2,5},{4,2},{0,3},{0,5},{1,4},{4,2},{3,3},{1,0}}; + vector> queries2 = {{4,3},{3,1},{5,3},{0,5},{4,4},{3,3}}; + print_vec(Solution().gridIllumination(6, lamps2, queries2)); + // 1 0 1 1 0 1 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1002-Find-Common-Characters/cpp-1002/CMakeLists.txt b/1001-1500/1002-Find-Common-Characters/cpp-1002/CMakeLists.txt new file mode 100644 index 00000000..f2ed7a9b --- /dev/null +++ b/1001-1500/1002-Find-Common-Characters/cpp-1002/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main2.cpp) \ No newline at end of file diff --git a/1001-1500/1002-Find-Common-Characters/cpp-1002/main.cpp b/1001-1500/1002-Find-Common-Characters/cpp-1002/main.cpp new file mode 100644 index 00000000..e517698a --- /dev/null +++ b/1001-1500/1002-Find-Common-Characters/cpp-1002/main.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/find-common-characters/ +/// Author : liuyubobobo +/// Time : 2019-03-02 + +#include +#include +#include + +using namespace std; + + +/// Sorting every string +/// Using two pointers technique to get the intersection of every two strings +/// Time Complexity: O(n * ave_len_of_strings) +/// Space Complexity: O(ave_len_of_strings) +class Solution { +public: + vector commonChars(vector& A) { + + for(string& s: A) sort(s.begin(), s.end()); + + string res = A[0]; + for(int i = 1; i < A.size(); i ++) + res = intersection(res, A[i]); + + vector ret; + for(char c: res) + ret.push_back(string(1, c)); + return ret; + } + +private: + string intersection(const string& s1, const string& s2){ + + int i1 = 0, i2 = 0; + string res = ""; + while(i1 < s1.size() && i2 < s2.size()) + if(s1[i1] == s2[i2]) + res += s1[i1], i1 ++, i2 ++; + else if(s1[i1] < s2[i2]) + i1 ++; + else + i2 ++; + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1002-Find-Common-Characters/cpp-1002/main2.cpp b/1001-1500/1002-Find-Common-Characters/cpp-1002/main2.cpp new file mode 100644 index 00000000..53b9ae5b --- /dev/null +++ b/1001-1500/1002-Find-Common-Characters/cpp-1002/main2.cpp @@ -0,0 +1,48 @@ +/// Source : https://leetcode.com/problems/find-common-characters/ +/// Author : liuyubobobo +/// Time : 2019-03-03 + +#include +#include +#include + +using namespace std; + + +/// Sorting and using C++ STL set_intersection :-) +/// Time Complexity: O(n * ave_len_of_strings) +/// Space Complexity: O(ave_len_of_strings) +class Solution { +public: + vector commonChars(vector& A) { + + for(string& s: A) sort(s.begin(), s.end()); + + string res = A[0]; + for(int i = 1; i < A.size(); i ++){ + string cur(max(res.size(), A[i].size()), ' '); + string::iterator iter = set_intersection(res.begin(), res.end(), A[i].begin(), A[i].end(), cur.begin()); + while(cur.size() && cur.back() == ' ') cur.pop_back(); + res = cur; + } + + vector ret; + for(char c: res) + ret.push_back(string(1, c)); + return ret; + } +}; + + +void print_vec(const vector& vec){ + for(const string& s: vec) cout << s << " "; + cout << endl; +} + +int main() { + + vector A1 = {"bella","label","roller"}; + print_vec(Solution().commonChars(A1)); + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1002-Find-Common-Characters/cpp-1002/main3.cpp b/1001-1500/1002-Find-Common-Characters/cpp-1002/main3.cpp new file mode 100644 index 00000000..386ba6ba --- /dev/null +++ b/1001-1500/1002-Find-Common-Characters/cpp-1002/main3.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/find-common-characters/ +/// Author : liuyubobobo +/// Time : 2019-03-03 + +#include +#include +#include +#include + +using namespace std; + + +/// Using HashMap to get the intersection of every two strings +/// Time Complexity: O(n * ave_len_of_strings) +/// Space Complexity: O(26) +class Solution { +public: + vector commonChars(vector& A) { + + vector> freqs(A.size()); + for(int i = 0; i < A.size(); i ++) + for(char c: A[i]) + freqs[i][c] ++; + + unordered_map res = freqs[0]; + for(int i = 1; i < freqs.size(); i ++) + res = intersection(res, freqs[i]); + + vector ret; + for(const pair& p: res) + for(int i = 0; i < p.second; i ++) + ret.push_back(string(1, p.first)); + return ret; + } + +private: + unordered_map intersection(unordered_map& freq1, + unordered_map& freq2){ + + unordered_map res; + for(const pair& p: freq1) + if(freq2.count(p.first)) + res[p.first] = min(p.second, freq2[p.first]); + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1002-Find-Common-Characters/cpp-1002/main4.cpp b/1001-1500/1002-Find-Common-Characters/cpp-1002/main4.cpp new file mode 100644 index 00000000..79892763 --- /dev/null +++ b/1001-1500/1002-Find-Common-Characters/cpp-1002/main4.cpp @@ -0,0 +1,60 @@ +/// Source : https://leetcode.com/problems/find-common-characters/ +/// Author : liuyubobobo +/// Time : 2019-03-03 + +#include +#include +#include +#include + +using namespace std; + + +/// Using MultiSet to get the intersection of every two strings +/// Time Complexity: O(n * ave_len_of_strings * log(ave_len_of_strings)) +/// Space Complexity: O(n * ave_len_of_strings) +class Solution { +public: + vector commonChars(vector& A) { + + vector> sets(A.size()); + for(int i = 0; i < A.size(); i ++) + for(char c: A[i]) + sets[i].insert(c); + + multiset res = sets[0]; + for(int i = 1; i < sets.size(); i ++) + res = intersection(res, sets[i]); + + vector ret; + for(char c: res) + ret.push_back(string(1, c)); + return ret; + } + +private: + multiset intersection(multiset& set1, multiset& set2){ + + multiset res; + for(char c: set1){ + multiset::iterator iter = set2.find(c); + if(iter != set2.end()) + res.insert(c), set2.erase(iter); + } + return res; + } +}; + + +void print_vec(const vector& vec){ + for(const string& s: vec) cout << s << " "; + cout << endl; +} + +int main() { + + vector A1 = {"bella","label","roller"}; + print_vec(Solution().commonChars(A1)); + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1003-Check-If-Word-Is-Valid-After-Substitutions/cpp-1003/CMakeLists.txt b/1001-1500/1003-Check-If-Word-Is-Valid-After-Substitutions/cpp-1003/CMakeLists.txt new file mode 100644 index 00000000..b4b16ecd --- /dev/null +++ b/1001-1500/1003-Check-If-Word-Is-Valid-After-Substitutions/cpp-1003/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1001-1500/1003-Check-If-Word-Is-Valid-After-Substitutions/cpp-1003/main.cpp b/1001-1500/1003-Check-If-Word-Is-Valid-After-Substitutions/cpp-1003/main.cpp new file mode 100644 index 00000000..f1f6f8d4 --- /dev/null +++ b/1001-1500/1003-Check-If-Word-Is-Valid-After-Substitutions/cpp-1003/main.cpp @@ -0,0 +1,32 @@ +/// Source : https://leetcode.com/problems/check-if-word-is-valid-after-substitutions/ +/// Author : liuyubobobo +/// Time : 2019-03-02 + +#include + +using namespace std; + + +/// Ad-Hoc +/// Recursive +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { +public: + bool isValid(const string& s) { + + if(s.size() % 3) return false; + if(s.size() == 0) return true; + + for(int i = 2; i < s.size(); i ++) + if(s[i - 2] == 'a' && s[i - 1] == 'b' && s[i] == 'c') + return isValid(s.substr(0, i - 2) + s.substr(i + 1)); + return false; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1003-Check-If-Word-Is-Valid-After-Substitutions/cpp-1003/main2.cpp b/1001-1500/1003-Check-If-Word-Is-Valid-After-Substitutions/cpp-1003/main2.cpp new file mode 100644 index 00000000..858fd376 --- /dev/null +++ b/1001-1500/1003-Check-If-Word-Is-Valid-After-Substitutions/cpp-1003/main2.cpp @@ -0,0 +1,28 @@ +/// Source : https://leetcode.com/problems/check-if-word-is-valid-after-substitutions/ +/// Author : liuyubobobo +/// Time : 2019-03-03 + +#include + +using namespace std; + + +/// Ad-Hoc +/// Iterative +/// Time Complexity: O(n^2) +/// Space Complexity: O(1) +class Solution { +public: + bool isValid(string s) { + + for(int i = s.find("abc"); i != string::npos; i = s.find("abc")) + s.erase(i, 3); + return s == ""; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1004-Max-Consecutive-Ones-III/cpp-1004/CMakeLists.txt b/1001-1500/1004-Max-Consecutive-Ones-III/cpp-1004/CMakeLists.txt new file mode 100644 index 00000000..2235a661 --- /dev/null +++ b/1001-1500/1004-Max-Consecutive-Ones-III/cpp-1004/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1001-1500/1004-Max-Consecutive-Ones-III/cpp-1004/main.cpp b/1001-1500/1004-Max-Consecutive-Ones-III/cpp-1004/main.cpp new file mode 100644 index 00000000..3ee4679a --- /dev/null +++ b/1001-1500/1004-Max-Consecutive-Ones-III/cpp-1004/main.cpp @@ -0,0 +1,56 @@ +/// Source : https://leetcode.com/problems/max-consecutive-ones-iii/ +/// Author : liuyubobobo +/// Time : 2019-03-02 + +#include +#include + +using namespace std; + + +/// Sliding Window +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int longestOnes(vector& A, int K) { + + int i = 0, j = -1, curK = 0, curLen = 0, best = 0; + while(j + 1 < A.size()){ + if(A[j + 1] == 1) + curLen += 1, + j ++; + else{ + // data[j + 1].first == 0 + if(curK < K) + curLen += 1, + curK += 1, + j ++; + else + curLen -= 1, + curK -= (A[i] == 0 ? 1 : 0), + i ++; + } + best = max(best, curLen); + } + return best; + } +}; + + +int main() { + + vector A1 = {1,1,1,0,0,0,1,1,1,1,0}; + cout << Solution().longestOnes(A1, 2) << endl; + // 6 + + vector A2 = {0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1}; + cout << Solution().longestOnes(A2, 3) << endl; + // 10 + + vector A3 = {1,0,0,0,1,1,0,0,1,1,0,0,0,0,0,0,1,1,1,1,0,1,0,1,1,1,1,1,1,0,1,0,1,0,0,1,1,0,1,1}; + cout << Solution().longestOnes(A3, 8) << endl; + // 25 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1005-Maximize-Sum-Of-Array-After-K-Negations/cpp-1005/CMakeLists.txt b/1001-1500/1005-Maximize-Sum-Of-Array-After-K-Negations/cpp-1005/CMakeLists.txt new file mode 100644 index 00000000..2d73f980 --- /dev/null +++ b/1001-1500/1005-Maximize-Sum-Of-Array-After-K-Negations/cpp-1005/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1001-1500/1005-Maximize-Sum-Of-Array-After-K-Negations/cpp-1005/main.cpp b/1001-1500/1005-Maximize-Sum-Of-Array-After-K-Negations/cpp-1005/main.cpp new file mode 100644 index 00000000..67eb8813 --- /dev/null +++ b/1001-1500/1005-Maximize-Sum-Of-Array-After-K-Negations/cpp-1005/main.cpp @@ -0,0 +1,48 @@ +/// Source : https://leetcode.com/problems/maximize-sum-of-array-after-k-negations/ +/// Author : liuyubobobo +/// Time : 2019-03-09 + +#include +#include +#include + +using namespace std; + + +/// Sorting and Greedy +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + int largestSumAfterKNegations(vector& A, int K) { + + sort(A.begin(), A.end()); + + int neg = 0; + bool hasZero = false; + for(int i = 0; i < A.size(); i ++) + if(A[i] < 0) neg ++; + else if(A[i] == 0) hasZero = true; + + int t = min(neg, K); + for(int i = 0; i < t; i ++) + A[i] = -A[i]; + K -= t; + + if(K && !hasZero && K % 2){ + sort(A.begin(), A.end()); + A[0] = -A[0]; + } + + return accumulate(A.begin(), A.end(), 0); + } +}; + + +int main() { + + vector A1 = {4, 2, 3}; + cout << Solution().largestSumAfterKNegations(A1, 1) << endl; + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1006-Clumsy-Factorial/cpp-1006/CMakeLists.txt b/1001-1500/1006-Clumsy-Factorial/cpp-1006/CMakeLists.txt new file mode 100644 index 00000000..b4b16ecd --- /dev/null +++ b/1001-1500/1006-Clumsy-Factorial/cpp-1006/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1001-1500/1006-Clumsy-Factorial/cpp-1006/main.cpp b/1001-1500/1006-Clumsy-Factorial/cpp-1006/main.cpp new file mode 100644 index 00000000..7a0f0550 --- /dev/null +++ b/1001-1500/1006-Clumsy-Factorial/cpp-1006/main.cpp @@ -0,0 +1,38 @@ +/// Source : https://leetcode.com/problems/clumsy-factorial/ +/// Author : liuyubobobo +/// Time : 2019-03-09 + +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int clumsy(int N) { + + if(N == 1) return 1; + if(N == 2) return 2; + if(N == 3) return 6; + + int res = N * (N - 1) / (N - 2); + N -= 3; + while(N >= 4){ + res += N - (N - 1) * (N - 2) / (N - 3); + N -= 4; + } + return res + !!N; + } +}; + + +int main() { + + cout << Solution().clumsy(4) << endl; + cout << Solution().clumsy(10) << endl; + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1007-Minimum-Domino-Rotations-For-Equal-Row/cpp-1007/CMakeLists.txt b/1001-1500/1007-Minimum-Domino-Rotations-For-Equal-Row/cpp-1007/CMakeLists.txt new file mode 100644 index 00000000..2235a661 --- /dev/null +++ b/1001-1500/1007-Minimum-Domino-Rotations-For-Equal-Row/cpp-1007/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1001-1500/1007-Minimum-Domino-Rotations-For-Equal-Row/cpp-1007/main.cpp b/1001-1500/1007-Minimum-Domino-Rotations-For-Equal-Row/cpp-1007/main.cpp new file mode 100644 index 00000000..261c3c0d --- /dev/null +++ b/1001-1500/1007-Minimum-Domino-Rotations-For-Equal-Row/cpp-1007/main.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/minimum-domino-rotations-for-equal-row/ +/// Author : liuyubobobo +/// Time : 2019-03-09 + +#include +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int minDominoRotations(vector& A, vector& B) { + + int n = A.size(); + unordered_set set = {A[0], B[0]}; + for(int i = 1; i < n; i ++) + set = intersection(set, A[i], B[i]); + + if(set.size() == 0) return -1; + + int target = *set.begin(); + return min(go(A, target), go(B, target)); + } + +private: + int go(const vector& v, int target){ + + int res = 0; + for(int e: v) + if(e != target) res ++; + return res; + } + + unordered_set intersection(const unordered_set& set, int a, int b){ + + unordered_set res; + if(set.count(a)) res.insert(a); + if(set.count(b)) res.insert(b); + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1008-Construct-Binary-Search-Tree-from-Preorder-Traversal/cpp-1008/CMakeLists.txt b/1001-1500/1008-Construct-Binary-Search-Tree-from-Preorder-Traversal/cpp-1008/CMakeLists.txt new file mode 100644 index 00000000..d20b982d --- /dev/null +++ b/1001-1500/1008-Construct-Binary-Search-Tree-from-Preorder-Traversal/cpp-1008/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) \ No newline at end of file diff --git a/1001-1500/1008-Construct-Binary-Search-Tree-from-Preorder-Traversal/cpp-1008/main.cpp b/1001-1500/1008-Construct-Binary-Search-Tree-from-Preorder-Traversal/cpp-1008/main.cpp new file mode 100644 index 00000000..fb42e06e --- /dev/null +++ b/1001-1500/1008-Construct-Binary-Search-Tree-from-Preorder-Traversal/cpp-1008/main.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/ +/// Author : liuyubobobo +/// Time : 2019-03-09 + +#include +#include + +using namespace std; + + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + + +/// Recursive +/// Time Complexity: O(n^2) +/// Space Complexity: O(1) +class Solution { +public: + TreeNode* bstFromPreorder(vector& preorder) { + + int n = preorder.size(); + return dfs(preorder, 0, n - 1); + } + +private: + TreeNode* dfs(const vector& v, int l, int r){ + + if(l > r || l >= v.size() || r >= v.size()) return NULL; + + TreeNode* root = new TreeNode(v[l]); + + int i; + for(i = l + 1; i <= r; i ++) + if(v[i] > v[l]) break; + + root->left = dfs(v, l + 1, i - 1); + root->right = dfs(v, i, r); + return root; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1009-Complement-of-Base-10-Integer/cpp-1009/CMakeLists.txt b/1001-1500/1009-Complement-of-Base-10-Integer/cpp-1009/CMakeLists.txt new file mode 100644 index 00000000..2d73f980 --- /dev/null +++ b/1001-1500/1009-Complement-of-Base-10-Integer/cpp-1009/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1001-1500/1009-Complement-of-Base-10-Integer/cpp-1009/main.cpp b/1001-1500/1009-Complement-of-Base-10-Integer/cpp-1009/main.cpp new file mode 100644 index 00000000..77056385 --- /dev/null +++ b/1001-1500/1009-Complement-of-Base-10-Integer/cpp-1009/main.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/complement-of-base-10-integer/ +/// Author : liuyubobobo +/// Time : 2019-03-16 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(logN) +/// Space Complexity: O(logN) +class Solution { +public: + int bitwiseComplement(int N) { + + if(!N) return 1; + + vector binary; + while(N) binary.push_back(1 - N % 2), N /= 2; + reverse(binary.begin(), binary.end()); + + int res = 0; + for(int b: binary) res = res * 2 + b; + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1010-Pairs-of-Songs-With-Total-Durations-Divisible-by-60/cpp-1010/CMakeLists.txt b/1001-1500/1010-Pairs-of-Songs-With-Total-Durations-Divisible-by-60/cpp-1010/CMakeLists.txt new file mode 100644 index 00000000..b4b16ecd --- /dev/null +++ b/1001-1500/1010-Pairs-of-Songs-With-Total-Durations-Divisible-by-60/cpp-1010/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1001-1500/1010-Pairs-of-Songs-With-Total-Durations-Divisible-by-60/cpp-1010/main.cpp b/1001-1500/1010-Pairs-of-Songs-With-Total-Durations-Divisible-by-60/cpp-1010/main.cpp new file mode 100644 index 00000000..64ada6ea --- /dev/null +++ b/1001-1500/1010-Pairs-of-Songs-With-Total-Durations-Divisible-by-60/cpp-1010/main.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/pairs-of-songs-with-total-durations-divisible-by-60/ +/// Author : liuyubobobo +/// Time : 2019-03-16 + +#include +#include + +using namespace std; + + +/// Using HashMap +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int numPairsDivisibleBy60(vector& time) { + + vector rem(60, 0); + for(int t: time) rem[t % 60] ++; + + long long res = 0; + if(rem[0]) res += (long long)rem[0] * (rem[0] - 1) / 2; + if(rem[30]) res += (long long)rem[30] * (rem[30] - 1) / 2; + for(int i = 1; i < 30; i ++) + res += (long long)rem[i] * rem[60 - i]; + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1011-Capacity-To-Ship-Packages-Within-D-Days/cpp-1011/CMakeLists.txt b/1001-1500/1011-Capacity-To-Ship-Packages-Within-D-Days/cpp-1011/CMakeLists.txt new file mode 100644 index 00000000..2235a661 --- /dev/null +++ b/1001-1500/1011-Capacity-To-Ship-Packages-Within-D-Days/cpp-1011/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1001-1500/1011-Capacity-To-Ship-Packages-Within-D-Days/cpp-1011/main.cpp b/1001-1500/1011-Capacity-To-Ship-Packages-Within-D-Days/cpp-1011/main.cpp new file mode 100644 index 00000000..af45bf5c --- /dev/null +++ b/1001-1500/1011-Capacity-To-Ship-Packages-Within-D-Days/cpp-1011/main.cpp @@ -0,0 +1,56 @@ +/// Source : https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/ +/// Author : liuyubobobo +/// Time : 2019-03-16 + +#include +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(nlog(sum(weights))) +/// Space Complexity: O(1) +class Solution { +public: + int shipWithinDays(vector& weights, int D) { + + int l = *max_element(weights.begin(), weights.end()), + r = accumulate(weights.begin(), weights.end(), 0); + while(l < r){ +// cout << "check " << l << " " << r << endl; + int mid = (l + r) / 2; + if(ok(weights, mid, D)) + r = mid; + else + l = mid + 1; + } + return l; + } + +private: + bool ok(const vector& weights, int C, int D){ + + int d = 0, cur = 0; + for(int w: weights) + if(cur + w <= C) cur += w; + else d ++, cur = w; + if(cur) d ++; + return d <= D; + } +}; + + +int main() { + + vector weight1 = {1,2,3,4,5,6,7,8,9,10}; + cout << Solution().shipWithinDays(weight1, 5) << endl; + // 15 + + vector weight2 = {1,2,3,1,1}; + cout << Solution().shipWithinDays(weight2, 4) << endl; + // 3 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1012-Numbers-With-1-Repeated-Digit/cpp-1012/CMakeLists.txt b/1001-1500/1012-Numbers-With-1-Repeated-Digit/cpp-1012/CMakeLists.txt new file mode 100644 index 00000000..f3578850 --- /dev/null +++ b/1001-1500/1012-Numbers-With-1-Repeated-Digit/cpp-1012/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main2.cpp) \ No newline at end of file diff --git a/1001-1500/1012-Numbers-With-1-Repeated-Digit/cpp-1012/main.cpp b/1001-1500/1012-Numbers-With-1-Repeated-Digit/cpp-1012/main.cpp new file mode 100644 index 00000000..15c8d7a2 --- /dev/null +++ b/1001-1500/1012-Numbers-With-1-Repeated-Digit/cpp-1012/main.cpp @@ -0,0 +1,106 @@ +/// Source : https://leetcode.com/problems/numbers-with-1-repeated-digit/ +/// Author : liuyubobobo +/// Time : 2019-03-16 + +#include +#include +#include + +using namespace std; + + +/// Combination Mathematics +/// Time Complexity: O(log(N)^2) +/// Space Complexity: O(logN) +class Solution { +public: + int numDupDigitsAtMostN(int N) { + + vector diff(10, 0); + for(int i = 1; i <= 9; i ++) + diff[i] = get_diff(i); + for(int i = 1; i < 10; i ++) diff[i] += diff[i - 1]; +// for(int e: diff) cout << e << " "; cout << endl; + + vector power10(10, 1); + for(int i = 1; i < 10; i ++) power10[i] = power10[i - 1] * 10; +// for(int e: power10) cout << e << " "; cout << endl; + + vector num; + while(N) num.push_back(N % 10), N /= 10; + reverse(num.begin(), num.end()); +// for(int e: num) cout << e << " "; cout << endl; + + int res = power10[num.size() - 1] - 1 - diff[num.size() - 1]; +// cout << res << endl; + + unordered_set digits; + for(int i = 0; i < num.size(); i ++){ + + if(i == num.size() - 1){ + for(int d = 0; d <= num[i]; d ++) + if(digits.count(d)) res ++; + break; + } + else if(num[i]){ + int tres = (num[i] - (i == 0)) * power10[num.size() - 1 - i]; + if(tres){ + tres -= howmanydiff(num.size() - i, digits, num[i], i != 0); + res += tres; + } + } + + if(!digits.count(num[i])) + digits.insert(num[i]); + else{ + res += 1 + get_num(num, i + 1); + break; + } + } + return res; + } + +private: + int howmanydiff(int n, const unordered_set& digits, int first, bool canZero){ + + int res = 0; + for(int i = canZero ? 0 : 1; i < first; i ++) + if(!digits.count(i)) res ++; + n --; + + int cur = 10 - (digits.size() + 1); + while(n --) + res *= cur--; + return res; + } + + int get_num(const vector& num, int s){ + int res = 0; + for(int i = s; i < num.size(); i ++) + res = res * 10 + num[i]; + return res; + } + + int get_diff(int n){ + + int res = 9; + n --; + + int cur = 9; + while(n --) res *= cur --; + return res; + } +}; + + +int main() { + + cout << Solution().numDupDigitsAtMostN(20) << endl; // 1 + cout << Solution().numDupDigitsAtMostN(100) << endl; // 10 + cout << Solution().numDupDigitsAtMostN(1000) << endl; // 262 + cout << Solution().numDupDigitsAtMostN(11) << endl; // 1 + cout << Solution().numDupDigitsAtMostN(101) << endl; // 11 + cout << Solution().numDupDigitsAtMostN(110) << endl; // 12 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1012-Numbers-With-1-Repeated-Digit/cpp-1012/main2.cpp b/1001-1500/1012-Numbers-With-1-Repeated-Digit/cpp-1012/main2.cpp new file mode 100644 index 00000000..5707199b --- /dev/null +++ b/1001-1500/1012-Numbers-With-1-Repeated-Digit/cpp-1012/main2.cpp @@ -0,0 +1,82 @@ +/// Source : https://leetcode.com/problems/numbers-with-1-repeated-digit/ +/// Author : liuyubobobo +/// Time : 2020-04-08 + +#include +#include +#include + +using namespace std; + + +/// Digital DP +/// Time Complexity: O(log(N) * 2^10 * 4) +/// Space Complexity: O(logN) +class Solution { + +public: + int numDupDigitsAtMostN(int N) { + + if(N <= 10) return 0; + + vector digits = get_digits(N); + vector>> dp(digits.size(), vector>(1 << 10, vector(4, -1))); + return dfs(0, 0, 0b11, digits, dp); + } + +private: + int dfs(int index, int digits, int state, + const vector& N, vector>>& dp){ + + if(index == N.size()) return 0; + if(dp[index][digits][state] != -1) return dp[index][digits][state]; + + int limit = state & 1, leadzero = state >> 1; + + int bound = limit ? N[index] : 9; + int res = 0; + for(int i = 0; i <= bound; i ++){ + int next_limit = limit ? (i == bound ? 1 : 0) : 0; + if(digits & (1 << i)){ + res += next_limit ? get_num(N, index + 1) + 1 : pow(10, N.size() - index - 1); + } + else{ + int next_digits = leadzero && (i == 0) ? digits : (digits | (1 << i)); + int next_leadzero = leadzero ? (i == 0 ? 1 : 0) : 0; + int next_state = next_leadzero * 2 + next_limit; + res += dfs(index + 1, next_digits, next_state, N, dp); + } + } + return dp[index][digits][state] = res; + } + + int get_num(const vector& num, int start){ + + int res = 0; + for(int i = start; i < num.size(); i ++) + res = res * 10 + num[i]; + return res; + } + + vector get_digits(int x){ + + vector res; + while(x) res.push_back(x % 10), x /= 10; + reverse(res.begin(), res.end()); + return res; + } +}; + + +int main() { + + cout << Solution().numDupDigitsAtMostN(20) << endl; // 1 + cout << Solution().numDupDigitsAtMostN(100) << endl; // 10 + cout << Solution().numDupDigitsAtMostN(1000) << endl; // 262 + cout << Solution().numDupDigitsAtMostN(11) << endl; // 1 + cout << Solution().numDupDigitsAtMostN(101) << endl; // 11 + cout << Solution().numDupDigitsAtMostN(110) << endl; // 12 + cout << Solution().numDupDigitsAtMostN(111) << endl; // 13 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1013-Partition-Array-Into-Three-Parts-With-Equal-Sum/cpp-1013/CMakeLists.txt b/1001-1500/1013-Partition-Array-Into-Three-Parts-With-Equal-Sum/cpp-1013/CMakeLists.txt new file mode 100644 index 00000000..2d73f980 --- /dev/null +++ b/1001-1500/1013-Partition-Array-Into-Three-Parts-With-Equal-Sum/cpp-1013/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1001-1500/1013-Partition-Array-Into-Three-Parts-With-Equal-Sum/cpp-1013/main.cpp b/1001-1500/1013-Partition-Array-Into-Three-Parts-With-Equal-Sum/cpp-1013/main.cpp new file mode 100644 index 00000000..84592903 --- /dev/null +++ b/1001-1500/1013-Partition-Array-Into-Three-Parts-With-Equal-Sum/cpp-1013/main.cpp @@ -0,0 +1,44 @@ +/// Source : https://leetcode.com/problems/partition-array-into-three-parts-with-equal-sum/ +/// Author : liuyubobobo +/// Time : 2019-03-23 + +#include +#include +#include +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + bool canThreePartsEqualSum(vector& A) { + + int sum = accumulate(A.begin(), A.end(), 0); + if(sum % 3) return false; + + int cur = 0, i = 0, j = A.size() - 1; + do{ + cur += A[i ++]; + }while(i < A.size() && cur != sum / 3); + + if(i == A.size()) return false; + + cur = 0; + do{ + cur += A[j --]; + }while(j >= 0 && cur != sum / 3); + if(j < 0) return false; + + return i <= j; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1014-Best-Sightseeing-Pair/cpp-1014/CMakeLists.txt b/1001-1500/1014-Best-Sightseeing-Pair/cpp-1014/CMakeLists.txt new file mode 100644 index 00000000..e47439c9 --- /dev/null +++ b/1001-1500/1014-Best-Sightseeing-Pair/cpp-1014/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main2.cpp) \ No newline at end of file diff --git a/1001-1500/1014-Best-Sightseeing-Pair/cpp-1014/main.cpp b/1001-1500/1014-Best-Sightseeing-Pair/cpp-1014/main.cpp new file mode 100644 index 00000000..28448dc9 --- /dev/null +++ b/1001-1500/1014-Best-Sightseeing-Pair/cpp-1014/main.cpp @@ -0,0 +1,48 @@ +/// Source : https://leetcode.com/problems/best-sightseeing-pair/ +/// Author : liuyubobobo +/// Time : 2019-03-23 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int maxScoreSightseeingPair(vector& A) { + + int n = A.size(); + + vector B = A; + for(int i = 0; i < n; i ++) B[i] -= i; + for(int i = n - 2; i >= 0; i --) + B[i] = max(B[i], B[i + 1]); + + int res = A[0] + B[1]; + for(int i = 1; i + 1 < n; i ++) + res = max(res, A[i] + i + B[i + 1]); + return res; + } +}; + + +int main() { + + vector A1 = {8,1,5,2,6}; + cout << Solution().maxScoreSightseeingPair(A1) << endl; + // 11 + + vector A2 = {3,7,2,3}; + cout << Solution().maxScoreSightseeingPair(A2) << endl; + // 9 + + vector A3 = {1, 3, 5}; + cout << Solution().maxScoreSightseeingPair(A3) << endl; + // 7 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1014-Best-Sightseeing-Pair/cpp-1014/main2.cpp b/1001-1500/1014-Best-Sightseeing-Pair/cpp-1014/main2.cpp new file mode 100644 index 00000000..7686fddc --- /dev/null +++ b/1001-1500/1014-Best-Sightseeing-Pair/cpp-1014/main2.cpp @@ -0,0 +1,45 @@ +/// Source : https://leetcode.com/problems/best-sightseeing-pair/ +/// Author : liuyubobobo +/// Time : 2019-03-23 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int maxScoreSightseeingPair(vector& A) { + + int n = A.size(); + + int res = A[0] + A[n - 1] - (n - 1), maxv = A[n - 1] - (n - 1); + for(int i = n - 2; i >= 0; i --){ + res = max(res, A[i] + i + maxv); + maxv = max(maxv, A[i] - i); + } + return res; + } +}; + + +int main() { + + vector A1 = {8,1,5,2,6}; + cout << Solution().maxScoreSightseeingPair(A1) << endl; + // 11 + + vector A2 = {3,7,2,3}; + cout << Solution().maxScoreSightseeingPair(A2) << endl; + // 9 + + vector A3 = {1, 3, 5}; + cout << Solution().maxScoreSightseeingPair(A3) << endl; + // 7 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1015-Smallest-Integer-Divisible-by-K/cpp-1015/CMakeLists.txt b/1001-1500/1015-Smallest-Integer-Divisible-by-K/cpp-1015/CMakeLists.txt new file mode 100644 index 00000000..5a882133 --- /dev/null +++ b/1001-1500/1015-Smallest-Integer-Divisible-by-K/cpp-1015/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main2.cpp) \ No newline at end of file diff --git a/1001-1500/1015-Smallest-Integer-Divisible-by-K/cpp-1015/main.cpp b/1001-1500/1015-Smallest-Integer-Divisible-by-K/cpp-1015/main.cpp new file mode 100644 index 00000000..490003f0 --- /dev/null +++ b/1001-1500/1015-Smallest-Integer-Divisible-by-K/cpp-1015/main.cpp @@ -0,0 +1,49 @@ +/// Source : https://leetcode.com/problems/two-sum/description/ +/// Author : liuyubobobo +/// Time : 2019-03-23 + +#include +#include +#include + +using namespace std; + + +/// Multiplication Simulation +/// Time Complexity: O(K) +/// Space Complexity: O(K) +class Solution { +public: + int smallestRepunitDivByK(int K) { + + if(K % 2 == 0 || K % 5 == 0) return -1; + + unordered_set visited; + + int left = 0, len = 0; + while(true){ + + int i = 0; + for(i = 0; i <= 9; i ++) + if((K * i + left) % 10 == 1){ + left = (K * i + left) / 10; + len ++; + break; + } + + if(i == 10) return -1; + if(left == 0) return len; + + if(visited.count(left)) break; + visited.insert(left); + } + return -1; + } +}; + +int main() { + + cout << Solution().smallestRepunitDivByK(3) << endl; + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1015-Smallest-Integer-Divisible-by-K/cpp-1015/main2.cpp b/1001-1500/1015-Smallest-Integer-Divisible-by-K/cpp-1015/main2.cpp new file mode 100644 index 00000000..bf59e397 --- /dev/null +++ b/1001-1500/1015-Smallest-Integer-Divisible-by-K/cpp-1015/main2.cpp @@ -0,0 +1,36 @@ +/// Source : https://leetcode.com/problems/two-sum/description/ +/// Author : liuyubobobo +/// Time : 2019-03-23 + +#include +#include +#include + +using namespace std; + + +/// Multiplication Simulation +/// Time Complexity: O(K) +/// Space Complexity: O(1) +class Solution { +public: + int smallestRepunitDivByK(int K) { + + if(K % 2 == 0 || K % 5 == 0) return -1; + + int r = 0; + for(int len = 1; len <= K; len ++){ + r = (r * 10 + 1) % K; + if(r == 0) return len; + } + return -1; + } +}; + + +int main() { + + cout << Solution().smallestRepunitDivByK(3) << endl; + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1016-Binary-String-With-Substrings-Representing-1-To-N/cpp-1016/CMakeLists.txt b/1001-1500/1016-Binary-String-With-Substrings-Representing-1-To-N/cpp-1016/CMakeLists.txt new file mode 100644 index 00000000..d20b982d --- /dev/null +++ b/1001-1500/1016-Binary-String-With-Substrings-Representing-1-To-N/cpp-1016/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) \ No newline at end of file diff --git a/1001-1500/1016-Binary-String-With-Substrings-Representing-1-To-N/cpp-1016/main.cpp b/1001-1500/1016-Binary-String-With-Substrings-Representing-1-To-N/cpp-1016/main.cpp new file mode 100644 index 00000000..a24acf50 --- /dev/null +++ b/1001-1500/1016-Binary-String-With-Substrings-Representing-1-To-N/cpp-1016/main.cpp @@ -0,0 +1,44 @@ +/// Source : https://leetcode.com/problems/binary-string-with-substrings-representing-1-to-n/ +/// Author : liuyubobobo +/// Time : 2019-03-23 + +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(|S|^2) +/// Space Complexity: O(logN) +class Solution { +public: + bool queryString(string S, int N) { + + int n = S.size(); + for(int i = N; i >= 1; i --){ + + string s = get_binary_string(i); + if(S.find(s) == string::npos) + return false; + } + return true; + } + +private: + string get_binary_string(int x){ + + string ret = ""; + while(x){ + ret += ('0' + x % 2); + x /= 2; + } + reverse(ret.begin(), ret.end()); + return ret; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1017-Convert-to-Base--2/cpp-1017/CMakeLists.txt b/1001-1500/1017-Convert-to-Base--2/cpp-1017/CMakeLists.txt new file mode 100644 index 00000000..b4b16ecd --- /dev/null +++ b/1001-1500/1017-Convert-to-Base--2/cpp-1017/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1001-1500/1017-Convert-to-Base--2/cpp-1017/main.cpp b/1001-1500/1017-Convert-to-Base--2/cpp-1017/main.cpp new file mode 100644 index 00000000..7144fe80 --- /dev/null +++ b/1001-1500/1017-Convert-to-Base--2/cpp-1017/main.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/convert-to-base-2/ +/// Author : liuyubobobo +/// Time : 2019-03-30 + +#include + +using namespace std; + + +/// Mathematics +/// Time Complexity: O(logn) +/// Space Complexity: O(1) +class Solution { +public: + string baseNeg2(int N) { + + string res = ""; + while(N){ + if(abs(N) % 2) res += "1"; + else res += "0"; + + if(abs(N) % 2) N --; + N /= -2; + } + + reverse(res.begin(), res.end()); + return res.size() ? res : "0"; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1018-Binary-Prefix-Divisible-By-5/cpp-1018/CMakeLists.txt b/1001-1500/1018-Binary-Prefix-Divisible-By-5/cpp-1018/CMakeLists.txt new file mode 100644 index 00000000..2d73f980 --- /dev/null +++ b/1001-1500/1018-Binary-Prefix-Divisible-By-5/cpp-1018/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1001-1500/1018-Binary-Prefix-Divisible-By-5/cpp-1018/main.cpp b/1001-1500/1018-Binary-Prefix-Divisible-By-5/cpp-1018/main.cpp new file mode 100644 index 00000000..0a9a9313 --- /dev/null +++ b/1001-1500/1018-Binary-Prefix-Divisible-By-5/cpp-1018/main.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/binary-prefix-divisible-by-5/ +/// Author : liuyubobobo +/// Time : 2019-03-30 + +#include +#include + +using namespace std; + + +/// Mathematics +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + vector prefixesDivBy5(vector& A) { + + int n = A.size(); + vector res; + + int a = 0; + for(int e: A){ + a = a * 2 + e; + res.push_back(a % 5 == 0); + a %= 10; + } + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1019-Next-Greater-Node-In-Linked-List/cpp-1019/CMakeLists.txt b/1001-1500/1019-Next-Greater-Node-In-Linked-List/cpp-1019/CMakeLists.txt new file mode 100644 index 00000000..2235a661 --- /dev/null +++ b/1001-1500/1019-Next-Greater-Node-In-Linked-List/cpp-1019/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1001-1500/1019-Next-Greater-Node-In-Linked-List/cpp-1019/main.cpp b/1001-1500/1019-Next-Greater-Node-In-Linked-List/cpp-1019/main.cpp new file mode 100644 index 00000000..56a80c7b --- /dev/null +++ b/1001-1500/1019-Next-Greater-Node-In-Linked-List/cpp-1019/main.cpp @@ -0,0 +1,78 @@ +/// Source : https://leetcode.com/problems/next-greater-node-in-linked-list/ +/// Author : liuyubobobo +/// Time : 2019-03-30 + +#include +#include +#include + +using namespace std; + + +/// Using Stack +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} +}; + +class Solution { +public: + vector nextLargerNodes(ListNode* head) { + + vector nums = get_nums(head); + return nextLargerNodes(nums); + } + + vector nextLargerNodes(const vector& nums){ + + stack stack; + vector res(nums.size(), 0); + for(int i = 0; i < nums.size(); i ++){ + + while(!stack.empty() && nums[stack.top()] < nums[i]) + res[stack.top()] = nums[i], stack.pop(); + + stack.push(i); + } + return res; + } + +private: + vector get_nums(ListNode* head){ + + vector res; + + ListNode* cur = head; + while(cur){ + res.push_back(cur->val); + cur = cur->next; + } + return res; + } +}; + + +void print_vec(const vector& vec){ + for(int e: vec) cout << e << " "; + cout << endl; +} + +int main() { + + vector nums1 = {2, 1, 5}; + print_vec(Solution().nextLargerNodes(nums1)); + + vector nums2 = {2, 7, 4, 3, 5}; + print_vec(Solution().nextLargerNodes(nums2)); + + vector nums3 = {1,7,5,1,9,2,5,1}; + print_vec(Solution().nextLargerNodes(nums3)); + + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1020-Number-of-Enclaves/cpp-1020/CMakeLists.txt b/1001-1500/1020-Number-of-Enclaves/cpp-1020/CMakeLists.txt new file mode 100644 index 00000000..d20b982d --- /dev/null +++ b/1001-1500/1020-Number-of-Enclaves/cpp-1020/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) \ No newline at end of file diff --git a/1001-1500/1020-Number-of-Enclaves/cpp-1020/main.cpp b/1001-1500/1020-Number-of-Enclaves/cpp-1020/main.cpp new file mode 100644 index 00000000..a2af9bf1 --- /dev/null +++ b/1001-1500/1020-Number-of-Enclaves/cpp-1020/main.cpp @@ -0,0 +1,71 @@ +/// Source : https://leetcode.com/problems/number-of-enclaves/ +/// Author : liuyubobobo +/// Time : 2019-03-30 + +#include +#include + +using namespace std; + + +/// Floodfill +/// Time Complexity: O(n * m) +/// Space Complexity: O(n * m) +class Solution { + +private: + int n, m; + const int d[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; + +public: + int numEnclaves(vector>& A) { + + if(A.size() == 0 || A[0].size() == 0) return 0; + + n = A.size(), m = A[0].size(); + for(int i = 0; i < n; i ++){ + if(A[i][0]) dfs(A, i, 0); + if(A[i][m - 1]) dfs(A, i, m - 1); + } + + for(int j = 0; j < m; j ++){ + if(A[0][j]) dfs(A, 0, j); + if(A[n - 1][j]) dfs(A, n - 1, j); + } + + int res = 0; + for(int i = 0; i < n; i ++) + for(int j = 0; j < m; j ++) + res += A[i][j]; + return res; + } + +private: + void dfs(vector>& A, int x, int y){ + + A[x][y] = 0; + for(int i = 0; i < 4; i ++){ + int nextx = x + d[i][0], nexty = y + d[i][1]; + if(in_area(nextx, nexty) && A[nextx][nexty]) + dfs(A, nextx, nexty); + } + } + + bool in_area(int x, int y){ + return x >= 0 && x < n && y >= 0 && y < m; + } +}; + + +int main() { + + vector> A1 = {{0,0,0,0},{1,0,1,0},{0,1,1,0},{0,0,0,0}}; + cout << Solution().numEnclaves(A1) << endl; + // 3 + + vector> A2 = {{0,1,1,0},{0,0,1,0},{0,0,1,0},{0,0,0,0}}; + cout << Solution().numEnclaves(A2) << endl; + // 0 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1021-Remove-Outermost-Parentheses/cpp-1021/CMakeLists.txt b/1001-1500/1021-Remove-Outermost-Parentheses/cpp-1021/CMakeLists.txt new file mode 100644 index 00000000..2d73f980 --- /dev/null +++ b/1001-1500/1021-Remove-Outermost-Parentheses/cpp-1021/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1001-1500/1021-Remove-Outermost-Parentheses/cpp-1021/main.cpp b/1001-1500/1021-Remove-Outermost-Parentheses/cpp-1021/main.cpp new file mode 100644 index 00000000..03439251 --- /dev/null +++ b/1001-1500/1021-Remove-Outermost-Parentheses/cpp-1021/main.cpp @@ -0,0 +1,41 @@ +/// Source : https://leetcode.com/problems/remove-outermost-parentheses/ +/// Author : liuyubobobo +/// Time : 2019-04-06 + +#include +#include + +using namespace std; + + +/// Using Stack +/// Time Complexity: O(|s|) +/// Space Complexity: O(1) +class Solution { +public: + string removeOuterParentheses(string S) { + + string res = ""; + int stack = 1, start = 0; + + for(int i = 1; i < S.size(); i ++){ + + if(S[i] == '(') stack ++; + else stack --; + + if(stack == 0){ + res += S.substr(start + 1, i - start + 1 - 2); + start = i + 1; + } + } + return res; + } +}; + + +int main() { + + cout << Solution().removeOuterParentheses("(()())(())") << endl; + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1022-Sum-of-Root-To-Leaf-Binary-Numbers/cpp-1022/CMakeLists.txt b/1001-1500/1022-Sum-of-Root-To-Leaf-Binary-Numbers/cpp-1022/CMakeLists.txt new file mode 100644 index 00000000..b4b16ecd --- /dev/null +++ b/1001-1500/1022-Sum-of-Root-To-Leaf-Binary-Numbers/cpp-1022/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1001-1500/1022-Sum-of-Root-To-Leaf-Binary-Numbers/cpp-1022/main.cpp b/1001-1500/1022-Sum-of-Root-To-Leaf-Binary-Numbers/cpp-1022/main.cpp new file mode 100644 index 00000000..affeda6c --- /dev/null +++ b/1001-1500/1022-Sum-of-Root-To-Leaf-Binary-Numbers/cpp-1022/main.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/ +/// Author : liuyubobobo +/// Time : 2019-04-06 + +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(h) + +/// 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 { + +private: + int res = 0; + const int MOD = 1e9 + 7; + +public: + int sumRootToLeaf(TreeNode* root) { + + dfs(root, 0); + return res; + } + +private: + void dfs(TreeNode* node, int num){ + + num = (2 * num + node->val) % MOD; + + if(!node->left && !node->right){ + res = (res + num) % MOD; + return; + } + + if(node->left) dfs(node->left, num); + if(node->right) dfs(node->right, num); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1023-Camelcase-Matching/cpp-1023/CMakeLists.txt b/1001-1500/1023-Camelcase-Matching/cpp-1023/CMakeLists.txt new file mode 100644 index 00000000..2235a661 --- /dev/null +++ b/1001-1500/1023-Camelcase-Matching/cpp-1023/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1001-1500/1023-Camelcase-Matching/cpp-1023/main.cpp b/1001-1500/1023-Camelcase-Matching/cpp-1023/main.cpp new file mode 100644 index 00000000..a3a5789e --- /dev/null +++ b/1001-1500/1023-Camelcase-Matching/cpp-1023/main.cpp @@ -0,0 +1,39 @@ +/// Source : https://leetcode.com/problems/camelcase-matching/ +/// Author : liuyubobobo +/// Time : 2019-04-06 + +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(n * len(|q|)) +/// Space Complexity: O(1) +class Solution { +public: + vector camelMatch(vector& queries, string pattern) { + + vector res; + for(const string& s : queries) + res.push_back(ok(s, pattern)); + return res; + } + +private: + bool ok(const string& s, const string& p){ + + int i = 0; + for(char c: s) + if(c == p[i]) i ++; + else if(isupper(c)) return false; + return i == p.size(); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1024-Video-Stitching/cpp-1024/CMakeLists.txt b/1001-1500/1024-Video-Stitching/cpp-1024/CMakeLists.txt new file mode 100644 index 00000000..d20b982d --- /dev/null +++ b/1001-1500/1024-Video-Stitching/cpp-1024/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) \ No newline at end of file diff --git a/1001-1500/1024-Video-Stitching/cpp-1024/main.cpp b/1001-1500/1024-Video-Stitching/cpp-1024/main.cpp new file mode 100644 index 00000000..b0d259cb --- /dev/null +++ b/1001-1500/1024-Video-Stitching/cpp-1024/main.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/video-stitching/ +/// Author : liuyubobobo +/// Time : 2019-04-06 + +#include +#include + +using namespace std; + + +/// Sorting and Greedy +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + int videoStitching(vector>& clips, int T) { + + if(T == 0) return 0; + + sort(clips.begin(), clips.end(),[](const vector& a, const vector& b){ + if(a[0] != b[0]) return a[0] < b[0]; + return a[1] > b[1]; + }); + + if(clips[0][0]) return -1; + + int res = 1, end = clips[0][1], tmax = end; + if(end >= T) return 1; + + for(int i = 1; i < clips.size(); i ++) + if(clips[i][0] <= end) tmax = max(tmax, clips[i][1]); + else{ + res ++; + end = tmax; + if(end >= T) return res; + if(clips[i][0] > end) return -1; + } + + if(tmax >= T) return res + 1; + return -1; + } +}; + + +int main() { + + vector> clips1 = {{0,2},{4,6},{8,10},{1,9},{1,5},{5,9}}; + cout << Solution().videoStitching(clips1, 10) << endl; + // 3 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1025-Divisor-Game/cpp-1025/CMakeLists.txt b/1001-1500/1025-Divisor-Game/cpp-1025/CMakeLists.txt new file mode 100644 index 00000000..2d73f980 --- /dev/null +++ b/1001-1500/1025-Divisor-Game/cpp-1025/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1001-1500/1025-Divisor-Game/cpp-1025/main.cpp b/1001-1500/1025-Divisor-Game/cpp-1025/main.cpp new file mode 100644 index 00000000..38c6c061 --- /dev/null +++ b/1001-1500/1025-Divisor-Game/cpp-1025/main.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/divisor-game/ +/// Author : liuyubobobo +/// Time : 2019-04-13 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { + +public: + bool divisorGame(int N) { + + vector dp(N + 1, -1); + return dfs(N, dp, true); + } + +private: + bool dfs(int x, vector& dp, bool isAlice){ + + if(x == 1) return isAlice ? false : true; + + if(dp[x] != -1) return dp[x]; + + if(isAlice){ + for(int i = 1; i * i <= x; i ++) + if(x % i == 0 && dfs(x - i, dp, false)) + return dp[x] = true; + return dp[x] = false; + } + else{ + for(int i = 1; i * i <= x; i ++) + if(x % i == 0 && !dfs(x - i, dp, true)) + return dp[x] = false; + return dp[x] = true; + } + } +}; + + +int main() { + + cout << Solution().divisorGame(2) << endl; // true + cout << Solution().divisorGame(3) << endl; // false + cout << Solution().divisorGame(9) << endl; // false + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1025-Divisor-Game/cpp-1025/main2.cpp b/1001-1500/1025-Divisor-Game/cpp-1025/main2.cpp new file mode 100644 index 00000000..38ec3d86 --- /dev/null +++ b/1001-1500/1025-Divisor-Game/cpp-1025/main2.cpp @@ -0,0 +1,32 @@ +/// Source : https://leetcode.com/problems/divisor-game/ +/// Author : liuyubobobo +/// Time : 2019-04-13 + +#include +#include + +using namespace std; + + +/// Mathematics +/// Prove can be see here: https://leetcode.com/problems/divisor-game/discuss/274606/JavaC%2B%2BPython-return-N-2-0 +/// +/// Time Complexity: O(1) +/// Space Complexity: O(1) +class Solution { + +public: + bool divisorGame(int N) { + return N % 2 == 0; + } +}; + + +int main() { + + cout << Solution().divisorGame(2) << endl; // true + cout << Solution().divisorGame(3) << endl; // false + cout << Solution().divisorGame(9) << endl; // false + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1026-Maximum-Difference-Between-Node-and-Ancestor/cpp-1026/CMakeLists.txt b/1001-1500/1026-Maximum-Difference-Between-Node-and-Ancestor/cpp-1026/CMakeLists.txt new file mode 100644 index 00000000..b4b16ecd --- /dev/null +++ b/1001-1500/1026-Maximum-Difference-Between-Node-and-Ancestor/cpp-1026/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1001-1500/1026-Maximum-Difference-Between-Node-and-Ancestor/cpp-1026/main.cpp b/1001-1500/1026-Maximum-Difference-Between-Node-and-Ancestor/cpp-1026/main.cpp new file mode 100644 index 00000000..21ba37a7 --- /dev/null +++ b/1001-1500/1026-Maximum-Difference-Between-Node-and-Ancestor/cpp-1026/main.cpp @@ -0,0 +1,72 @@ +/// Source : https://leetcode.com/problems/maximum-difference-between-node-and-ancestor/ +/// Author : liuyubobobo +/// Time : 2019-04-13 + +#include + +using namespace std; + + +/// Recusion +/// Time Complexity: O(n) +/// Space Complexity: O(h) + +/// 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: + int maxAncestorDiff(TreeNode* root) { + + int maxv, minv; + return dfs(root, maxv, minv); + } + + int dfs(TreeNode* node, int& maxv, int& minv){ + + maxv = node->val; + minv = node->val; +// cout << "in " << node->val << endl; + + int res = 0; + if(node->left){ + int lmaxv, lminv; + int lres = dfs(node->left, lmaxv, lminv); + + res = max(res, lres); + res = max(res, abs(node->val - lmaxv)); + res = max(res, abs(node->val - lminv)); +// cout << "after search left : " << res << endl; + + maxv = max(maxv, lmaxv); + minv = min(minv, lminv); + } + + if(node->right){ + int rmaxv, rminv; + int rres = dfs(node->right, rmaxv, rminv); + + res = max(res, rres); + res = max(res, abs(node->val - rmaxv)); + res = max(res, abs(node->val - rminv)); +// cout << "after search right : " << res << endl; + + maxv = max(maxv, rmaxv); + minv = min(minv, rminv); + } + + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1027-Longest-Arithmetic-Sequence/cpp-1027/CMakeLists.txt b/1001-1500/1027-Longest-Arithmetic-Sequence/cpp-1027/CMakeLists.txt new file mode 100644 index 00000000..2235a661 --- /dev/null +++ b/1001-1500/1027-Longest-Arithmetic-Sequence/cpp-1027/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1001-1500/1027-Longest-Arithmetic-Sequence/cpp-1027/main.cpp b/1001-1500/1027-Longest-Arithmetic-Sequence/cpp-1027/main.cpp new file mode 100644 index 00000000..a896c371 --- /dev/null +++ b/1001-1500/1027-Longest-Arithmetic-Sequence/cpp-1027/main.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/longest-arithmetic-sequence/ +/// Author : liuyubobobo +/// Time : 2019-04-13 +/// Updated: 2023-04-13 + +#include +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(n^2) +/// Space Complexity: O(n^2) +class Solution { + +private: + const int offset = 500; + +public: + int longestArithSeqLength(vector& A) { + + int n = A.size(); + vector> dp(n, vector(1001, 1)); + + int res = 1; + for(int i = 1; i < n; i ++) + for(int j = i - 1; j >= 0; j --){ + int d = A[i] - A[j] + offset; + dp[i][d] = max(dp[i][d], dp[j][d] + 1); + res = max(res, dp[i][d]); + } + + return res; + } +}; + + +int main() { + + vector A1 = {3, 6, 9, 12}; + cout << Solution().longestArithSeqLength(A1) << endl; // 4 + + vector A2 = {9, 4, 7, 2, 10}; + cout << Solution().longestArithSeqLength(A2) << endl; // 3 + + vector A3 = {20,1,15,3,10,5,8}; + cout << Solution().longestArithSeqLength(A3) << endl; // 4 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1028-Recover-a-Tree-From-Preorder-Traversal/cpp-1028/CMakeLists.txt b/1001-1500/1028-Recover-a-Tree-From-Preorder-Traversal/cpp-1028/CMakeLists.txt new file mode 100644 index 00000000..d20b982d --- /dev/null +++ b/1001-1500/1028-Recover-a-Tree-From-Preorder-Traversal/cpp-1028/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) \ No newline at end of file diff --git a/1001-1500/1028-Recover-a-Tree-From-Preorder-Traversal/cpp-1028/main.cpp b/1001-1500/1028-Recover-a-Tree-From-Preorder-Traversal/cpp-1028/main.cpp new file mode 100644 index 00000000..d0b38a05 --- /dev/null +++ b/1001-1500/1028-Recover-a-Tree-From-Preorder-Traversal/cpp-1028/main.cpp @@ -0,0 +1,90 @@ +/// Source : https://leetcode.com/problems/recover-a-tree-from-preorder-traversal/ +/// Author : liuyubobobo +/// Time : 2019-04-13 + +#include +#include + +using namespace std; + + +/// Recursion +/// Time Complexity: O(|s|^2) +/// Space Complexity: O(|s|) + +/// 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* recoverFromPreorder(string S) { + return build(S, 0); + } + +private: + TreeNode* build(string s, int d){ + + if(d >= s.size()) return NULL; + + assert(s[d] != '-'); + + int num = first_number(s); + TreeNode* root = new TreeNode(num); + + if(s.size()){ + int another = -1; + for(int i = d + 1; i < s.size(); i ++) + if(s[i] != '-' && ok(s, i + 1, d + 1)){ + another = i + 1; + break; + } + + if(another == -1) root->left = build(s, d + 1); + else{ + root->left = build(s.substr(0, another), d + 1); + root->right = build(s.substr(another), d + 1); + } + + } + return root; + } + + int first_number(string& s){ + + int digit = 0; + for(; digit < s.size() && s[digit] == '-'; digit ++); + + int digit_end = digit + 1; + for(;digit_end < s.size() && s[digit_end] != '-'; digit_end ++); + + string num_str = s.substr(digit, digit_end - digit); + s = s.substr(digit_end); + return atoi(num_str.c_str()); + } + + bool ok(const string& s, int start, int d){ + + return ok(s.substr(start, d + 1), d); + } + + bool ok(const string& s, int d){ + if(s.size() != d + 1) return false; + for(int i = 0; i < s.size() - 1; i ++) + if(s[i] != '-') return false; + return s.back() != '-'; + } +}; + + +int main() { + + Solution().recoverFromPreorder("1-401--349---90--88"); + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1029-Two-City-Scheduling/cpp-1029/CMakeLists.txt b/1001-1500/1029-Two-City-Scheduling/cpp-1029/CMakeLists.txt new file mode 100644 index 00000000..afa8217d --- /dev/null +++ b/1001-1500/1029-Two-City-Scheduling/cpp-1029/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1001-1500/1029-Two-City-Scheduling/cpp-1029/main.cpp b/1001-1500/1029-Two-City-Scheduling/cpp-1029/main.cpp new file mode 100644 index 00000000..09598134 --- /dev/null +++ b/1001-1500/1029-Two-City-Scheduling/cpp-1029/main.cpp @@ -0,0 +1,38 @@ +/// Source : https://leetcode.com/problems/two-city-scheduling/ +/// Author : liuyubobobo +/// Time : 2019-04-20 + +#include +#include +#include + +using namespace std; + + +/// Sorting +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + vector> allCellsDistOrder(int R, int C, int r0, int c0) { + + vector> res; + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++) + res.push_back({i, j}); + + sort(res.begin(), res.end(), [r0, c0](const vector& v1, const vector& v2){ + + int dis1 = abs(v1[0] - r0) + abs(v1[1] - c0); + int dis2 = abs(v2[0] - r0) + abs(v2[1] - c0); + return dis1 < dis2; + }); + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1030-Matrix-Cells-in-Distance-Order/cpp-1030/CMakeLists.txt b/1001-1500/1030-Matrix-Cells-in-Distance-Order/cpp-1030/CMakeLists.txt new file mode 100644 index 00000000..3c6ea462 --- /dev/null +++ b/1001-1500/1030-Matrix-Cells-in-Distance-Order/cpp-1030/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1001-1500/1030-Matrix-Cells-in-Distance-Order/cpp-1030/main.cpp b/1001-1500/1030-Matrix-Cells-in-Distance-Order/cpp-1030/main.cpp new file mode 100644 index 00000000..93f8ee10 --- /dev/null +++ b/1001-1500/1030-Matrix-Cells-in-Distance-Order/cpp-1030/main.cpp @@ -0,0 +1,45 @@ +/// Source : https://leetcode.com/problems/matrix-cells-in-distance-order/ +/// Author : liuyubobobo +/// Time : 2019-04-20 + +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + int twoCitySchedCost(vector>& costs) { + + vector> A, B; + + int res = 0; + for(const vector& cost: costs) + if(cost[0] < cost[1]) + res += cost[0], A.push_back(cost); + else + res += cost[1], B.push_back(cost); + + vector>& t = A.size() < B.size() ? B : A; + + sort(t.begin(), t.end(), [](const vector& v1, const vector& v2){ + return abs(v1[0] - v1[1]) > abs(v2[0] - v2[1]); + }); + + while(t.size() > costs.size() / 2){ + res += abs(t.back()[0] - t.back()[1]); + t.pop_back(); + } + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1031-Maximum-Sum-of-Two-Non-Overlapping-Subarrays/cpp-1031/CMakeLists.txt b/1001-1500/1031-Maximum-Sum-of-Two-Non-Overlapping-Subarrays/cpp-1031/CMakeLists.txt new file mode 100644 index 00000000..a9faeff1 --- /dev/null +++ b/1001-1500/1031-Maximum-Sum-of-Two-Non-Overlapping-Subarrays/cpp-1031/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1001-1500/1031-Maximum-Sum-of-Two-Non-Overlapping-Subarrays/cpp-1031/main.cpp b/1001-1500/1031-Maximum-Sum-of-Two-Non-Overlapping-Subarrays/cpp-1031/main.cpp new file mode 100644 index 00000000..dd03ca92 --- /dev/null +++ b/1001-1500/1031-Maximum-Sum-of-Two-Non-Overlapping-Subarrays/cpp-1031/main.cpp @@ -0,0 +1,51 @@ +/// Source : https://leetcode.com/problems/maximum-sum-of-two-non-overlapping-subarrays/ +/// Author : liuyubobobo +/// Time : 2019-04-20 + +#include +#include +#include + +using namespace std; + + +/// Pre Sum +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { +public: + int maxSumTwoNoOverlap(vector& A, int L, int M) { + + vector sumL, sumM; + + sumL.push_back(accumulate(A.begin(), A.begin() + L, 0)); + for(int i = L; i < A.size(); i ++) + sumL.push_back(sumL.back() - A[i - L] + A[i]); +// for(int e: sumL) cout << e << " "; cout << endl; + + sumM.push_back(accumulate(A.begin(), A.begin() + M, 0)); + for(int i = M; i < A.size(); i ++) + sumM.push_back(sumM.back() - A[i - M] + A[i]); +// for(int e: sumM) cout << e << " "; cout << endl; + + int res = 0; + for(int i = 0; i < sumL.size(); i ++){ + + for(int j = 0; j + M - 1 < i; j ++) + res = max(res, sumL[i] + sumM[j]); + + for(int j = i + L; j < sumM.size(); j ++) + res = max(res, sumL[i] + sumM[j]); + } + return res; + } +}; + + +int main() { + + vector A1 = {0,6,5,2,2,5,1,9,4}; + cout << Solution().maxSumTwoNoOverlap(A1, 1, 2) << endl; + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1032-Stream-of-Characters/cpp-1032/CMakeLists.txt b/1001-1500/1032-Stream-of-Characters/cpp-1032/CMakeLists.txt new file mode 100644 index 00000000..89658265 --- /dev/null +++ b/1001-1500/1032-Stream-of-Characters/cpp-1032/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) \ No newline at end of file diff --git a/1001-1500/1032-Stream-of-Characters/cpp-1032/main.cpp b/1001-1500/1032-Stream-of-Characters/cpp-1032/main.cpp new file mode 100644 index 00000000..a32ee570 --- /dev/null +++ b/1001-1500/1032-Stream-of-Characters/cpp-1032/main.cpp @@ -0,0 +1,89 @@ +/// Source : https://leetcode.com/problems/stream-of-characters/ +/// Author : liuyubobobo +/// Time : 2019-04-20 + +#include +#include +#include + +using namespace std; + + +/// Trie +/// Time Complexity: init: O(n * |word|) +/// query: O(max length of words) +/// Space Complexity: O(n * |word| + |q|) +class Trie { + +private: + struct Node{ + unordered_map next; + bool end = false; + }; + vector trie; + +public: + Trie(){ + trie.clear(); + trie.push_back(Node()); + } + + void insert(const string& word){ + + int treeID = 0; + for(char c: word){ + if(trie[treeID].next.find(c) == trie[treeID].next.end()){ + trie[treeID].next[c] = trie.size(); + trie.push_back(Node()); + } + + treeID = trie[treeID].next[c]; + } + + trie[treeID].end = true; + } + + bool search(const string& q){ + + int treeID = 0; + for(int i = q.size() - 1; i >= 0; i --){ + + if(trie[treeID].end) return true; + + char c = q[i]; + if(!trie[treeID].next.count(c)) + return false; + + treeID = trie[treeID].next[c]; + } + return trie[treeID].end; + } +}; + +class StreamChecker { + +private: + Trie trie; + string q = ""; + +public: + StreamChecker(vector& words){ + + for(string& word: words){ + reverse(word.begin(), word.end()); + trie.insert(word); + } + } + + bool query(char letter) { + + q += letter; + return trie.search(q); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1033-Moving-Stones-Until-Consecutive/cpp-1033/CMakeLists.txt b/1001-1500/1033-Moving-Stones-Until-Consecutive/cpp-1033/CMakeLists.txt new file mode 100644 index 00000000..afa8217d --- /dev/null +++ b/1001-1500/1033-Moving-Stones-Until-Consecutive/cpp-1033/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1001-1500/1033-Moving-Stones-Until-Consecutive/cpp-1033/main.cpp b/1001-1500/1033-Moving-Stones-Until-Consecutive/cpp-1033/main.cpp new file mode 100644 index 00000000..74e6ab25 --- /dev/null +++ b/1001-1500/1033-Moving-Stones-Until-Consecutive/cpp-1033/main.cpp @@ -0,0 +1,44 @@ +/// Source : https://leetcode.com/problems/moving-stones-until-consecutive/ +/// Author : liuyubobobo +/// Time : 2019-04-27 + +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(1) +/// Space Complexity: O(1) +class Solution { +public: + vector numMovesStones(int a, int b, int c) { + + vector A = {a, b, c}; + sort(A.begin(), A.end()); + + int min_res = 2; + if(A[1] - A[0] == 1 && A[2] - A[1] == 1) + min_res = 0; + else if(A[1] - A[0] <= 2 || A[2] - A[1] <= 2) + min_res = 1; + + int max_res = (A[1] - A[0] - 1) + (A[2] - A[1] - 1); + return {min_res, max_res}; + } +}; + + +int main() { + + vector res1 = Solution().numMovesStones(3, 5, 1); + cout << res1[0] << " " << res1[1] << endl; + // 1 2 + + vector res2 = Solution().numMovesStones(1, 2, 5); + cout << res2[0] << " " << res2[1] << endl; + // 1 2 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1034-Coloring-A-Border/cpp-1034/CMakeLists.txt b/1001-1500/1034-Coloring-A-Border/cpp-1034/CMakeLists.txt new file mode 100644 index 00000000..7f3bfb51 --- /dev/null +++ b/1001-1500/1034-Coloring-A-Border/cpp-1034/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main2.cpp) \ No newline at end of file diff --git a/1001-1500/1034-Coloring-A-Border/cpp-1034/main.cpp b/1001-1500/1034-Coloring-A-Border/cpp-1034/main.cpp new file mode 100644 index 00000000..e2c1ac99 --- /dev/null +++ b/1001-1500/1034-Coloring-A-Border/cpp-1034/main.cpp @@ -0,0 +1,92 @@ +/// Source : https://leetcode.com/problems/coloring-a-border/ +/// Author : liuyubobobo +/// Time : 2019-04-27 + +#include +#include +#include + +using namespace std; + + +/// DFS Connected Components +/// Time Complexity: O(m * n) +/// Space Complexity: O(m * n) +class Solution { + +private: + const int d[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; + int m, n; + +public: + vector> colorBorder(vector>& grid, int r0, int c0, int color) { + + m = grid.size(); + n = grid[0].size(); + + int target = grid[r0][c0]; + if(target == color) return grid; + + set> cc; + dfs(grid, r0, c0, target, cc); + + vector> border; + for(const pair& p: cc) + if(isborder(grid, p.first, p.second, target)) + border.push_back(p); + + for(const pair& p: border) + grid[p.first][p.second] = color; + return grid; + } + +private: + void dfs(vector>& grid, int x, int y, int target, set>& cc){ + + cc.insert(make_pair(x, y)); + for(int i = 0; i < 4; i ++){ + int nextx = x + d[i][0], nexty = y + d[i][1]; + if(nextx >= 0 && nextx < m && nexty >= 0 && nexty < n && grid[nextx][nexty] == target && + !cc.count(make_pair(nextx, nexty))) + dfs(grid, nextx, nexty, target, cc); + } + } + + bool isborder(vector>& grid, int x, int y, int target){ + + for(int i = 0; i < 4; i ++){ + int nextx = x + d[i][0], nexty = y + d[i][1]; + if(nextx < 0 || nextx >= m || nexty < 0 || nexty >= n) + return true; + if(grid[nextx][nexty] != target) + return true; + } + return false; + } +}; + + +void print_2dvec(const vector>& vec){ + for(const vector& row: vec){ + for(int e: row) cout << e << " "; cout << endl; + } +} + +int main() { + + vector> grid1 = {{1,2,1},{1,2,2},{2,2,1}}; + vector> res1 = Solution().colorBorder(grid1, 1, 1, 2); + print_2dvec(res1); + // 1 2 1 + // 1 2 2 + // 2 2 1 + + vector> grid2 = {{1,2,1,2,1,2},{2,2,2,2,1,2},{1,2,2,2,1,2}}; + vector> res2 = Solution().colorBorder(grid2, 1, 3, 1); + print_2dvec(res2); + // 1 1 1 1 1 2 + // 1 2 1 1 1 2 + // 1 1 1 1 1 2 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1034-Coloring-A-Border/cpp-1034/main2.cpp b/1001-1500/1034-Coloring-A-Border/cpp-1034/main2.cpp new file mode 100644 index 00000000..1ea18d67 --- /dev/null +++ b/1001-1500/1034-Coloring-A-Border/cpp-1034/main2.cpp @@ -0,0 +1,84 @@ +/// Source : https://leetcode.com/problems/coloring-a-border/ +/// Author : liuyubobobo +/// Time : 2019-04-30 + +#include +#include +#include + +using namespace std; + + +/// DFS - Check border directly during DFS +/// Time Complexity: O(m * n) +/// Space Complexity: O(m * n) +class Solution { + +private: + const int d[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; + int m, n; + +public: + vector> colorBorder(vector>& grid, int r0, int c0, int color) { + + m = grid.size(); + n = grid[0].size(); + + int target = grid[r0][c0]; + if(target == color) return grid; + + vector> border; + set> visited; + dfs(grid, r0, c0, target, border, visited); + + for(const pair& p: border) + grid[p.first][p.second] = color; + return grid; + } + +private: + void dfs(vector>& grid, int x, int y, int target, + vector>& border, set>& visited){ + + visited.insert(make_pair(x, y)); + + int around = 0; + for(int i = 0; i < 4; i ++){ + + int nextx = x + d[i][0], nexty = y + d[i][1]; + if(nextx >= 0 && nextx < m && nexty >= 0 && nexty < n && grid[nextx][nexty] == target){ + around ++; + if(!visited.count(make_pair(nextx, nexty))) + dfs(grid, nextx, nexty, target, border, visited); + } + } + + if(around != 4) border.push_back(make_pair(x, y)); + } +}; + + +void print_2dvec(const vector>& vec){ + for(const vector& row: vec){ + for(int e: row) cout << e << " "; cout << endl; + } +} + +int main() { + + vector> grid1 = {{1,2,1},{1,2,2},{2,2,1}}; + vector> res1 = Solution().colorBorder(grid1, 1, 1, 2); + print_2dvec(res1); + // 1 2 1 + // 1 2 2 + // 2 2 1 + + vector> grid2 = {{1,2,1,2,1,2},{2,2,2,2,1,2},{1,2,2,2,1,2}}; + vector> res2 = Solution().colorBorder(grid2, 1, 3, 1); + print_2dvec(res2); + // 1 1 1 1 1 2 + // 1 2 1 1 1 2 + // 1 1 1 1 1 2 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1035-Uncrossed-Lines/cpp-1035/CMakeLists.txt b/1001-1500/1035-Uncrossed-Lines/cpp-1035/CMakeLists.txt new file mode 100644 index 00000000..b170a313 --- /dev/null +++ b/1001-1500/1035-Uncrossed-Lines/cpp-1035/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main4.cpp) \ No newline at end of file diff --git a/1001-1500/1035-Uncrossed-Lines/cpp-1035/main.cpp b/1001-1500/1035-Uncrossed-Lines/cpp-1035/main.cpp new file mode 100644 index 00000000..10936cd1 --- /dev/null +++ b/1001-1500/1035-Uncrossed-Lines/cpp-1035/main.cpp @@ -0,0 +1,58 @@ +/// Source : https://leetcode.com/problems/uncrossed-lines/ +/// Author : liuyubobobo +/// Time : 2019-04-27 + +#include +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(|A| * |B|) +/// Space Complexity: O(|A| * |B|) +class Solution { +public: + int maxUncrossedLines(vector& A, vector& B) { + + unordered_map> Apos, Bpos; + for(int i = 0; i < A.size(); i ++) + Apos[A[i]].push_back(i); + for(int i = 0; i < B.size(); i ++) + Bpos[B[i]].push_back(i); + + vector> dp(A.size(), vector(B.size(), -1)); + return dfs(A, B, 0, 0, Apos, Bpos, dp); + } + +private: + int dfs(const vector& A, const vector& B, int ai, int bj, + unordered_map>& Apos, + unordered_map>& Bpos, + vector>& dp){ + + if(ai >= A.size() || bj >= B.size()) + return 0; + + if(dp[ai][bj] != -1) return dp[ai][bj]; + + int res = dfs(A, B, ai + 1, bj, Apos, Bpos, dp); + for(int j: Bpos[A[ai]]) + if(j >= bj) + res = max(res, 1 + dfs(A, B, ai + 1, j + 1, Apos, Bpos, dp)); + + return dp[ai][bj] = res; + } +}; + + +int main() { + + vector A1 = {3}; + vector B1 = {3, 3, 2}; + cout << Solution().maxUncrossedLines(A1, B1) << endl; + // 1 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1035-Uncrossed-Lines/cpp-1035/main2.cpp b/1001-1500/1035-Uncrossed-Lines/cpp-1035/main2.cpp new file mode 100644 index 00000000..71456674 --- /dev/null +++ b/1001-1500/1035-Uncrossed-Lines/cpp-1035/main2.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/uncrossed-lines/ +/// Author : liuyubobobo +/// Time : 2019-04-30 + +#include +#include +#include + +using namespace std; + + +/// Memory Search +/// It's actualy The Longest Common Subsequence Problem +/// +/// Time Complexity: O(|A| * |B|) +/// Space Complexity: O(|A| * |B|) +class Solution { +public: + int maxUncrossedLines(vector& A, vector& B) { + + vector> dp(A.size(), vector(B.size(), -1)); + return dfs(A, B, 0, 0, dp); + } + +private: + int dfs(const vector& A, const vector& B, int ai, int bj, + vector>& dp){ + + if(ai >= A.size() || bj >= B.size()) + return 0; + + if(dp[ai][bj] != -1) return dp[ai][bj]; + + int res = dfs(A, B, ai + 1, bj, dp); + for(int j = bj; j < B.size(); j ++) + if(A[ai] == B[j]) + res = max(res, 1 + dfs(A, B, ai + 1, j + 1, dp)); + + return dp[ai][bj] = res; + } +}; + + +int main() { + + vector A1 = {3}; + vector B1 = {3, 3, 2}; + cout << Solution().maxUncrossedLines(A1, B1) << endl; + // 1 + + vector A2 = {2, 5, 1, 2, 5}; + vector B2 = {10, 5, 2, 1, 5, 2}; + cout << Solution().maxUncrossedLines(A2, B2) << endl; + // 3 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1035-Uncrossed-Lines/cpp-1035/main3.cpp b/1001-1500/1035-Uncrossed-Lines/cpp-1035/main3.cpp new file mode 100644 index 00000000..60c62d84 --- /dev/null +++ b/1001-1500/1035-Uncrossed-Lines/cpp-1035/main3.cpp @@ -0,0 +1,56 @@ +/// Source : https://leetcode.com/problems/uncrossed-lines/ +/// Author : liuyubobobo +/// Time : 2019-04-30 + +#include +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// It's actualy The Longest Common Subsequence Problem +/// 2-D Dynamic Programming +/// +/// Time Complexity: O(|A| * |B|) +/// Space Complexity: O(|A| * |B|) +class Solution { +public: + int maxUncrossedLines(vector& A, vector& B) { + + vector> dp(A.size() + 1, vector(B.size() + 1, 0)); + for(int i = 1; i <= A.size(); i ++) + for(int j = 1; j <= B.size(); j ++) + dp[i][j] = max(max(dp[i - 1][j], dp[i][j - 1]), (A[i - 1] == B[j - 1]) + dp[i - 1][j - 1]); + +// for(int i = 0; i <= A.size(); i ++){ +// for(int j = 0; j <= B.size(); j ++) +// cout << dp[i][j] << " "; +// cout << endl; +// } + + return dp[A.size()][B.size()]; + } +}; + + +int main() { + + vector A1 = {3}; + vector B1 = {3, 3, 2}; + cout << Solution().maxUncrossedLines(A1, B1) << endl; + // 1 + + vector A2 = {2, 5, 1, 2, 5}; + vector B2 = {10, 5, 2, 1, 5, 2}; + cout << Solution().maxUncrossedLines(A2, B2) << endl; + // 3 + + vector A3 = {1, 4, 2}; + vector B3 = {1, 2, 4}; + cout << Solution().maxUncrossedLines(A3, B3) << endl; + // 2 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1035-Uncrossed-Lines/cpp-1035/main4.cpp b/1001-1500/1035-Uncrossed-Lines/cpp-1035/main4.cpp new file mode 100644 index 00000000..da1b5acb --- /dev/null +++ b/1001-1500/1035-Uncrossed-Lines/cpp-1035/main4.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/uncrossed-lines/ +/// Author : liuyubobobo +/// Time : 2019-04-30 + +#include +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// It's actualy The Longest Common Subsequence Problem +/// 1-D Dynamic Programming +/// +/// Time Complexity: O(|A| * |B|) +/// Space Complexity: O(|B|) +class Solution { +public: + int maxUncrossedLines(vector& A, vector& B) { + + vector dp(B.size() + 1, 0); + for(int i = 1; i <= A.size(); i ++){ + for(int j = B.size(); j >= 1; j --) + if(A[i - 1] == B[j - 1]) + dp[j] = 1 + dp[j - 1]; + for(int j = 1; j <= B.size(); j ++) + dp[j] = max(dp[j], dp[j - 1]); + } + + return dp[B.size()]; + } +}; + + +int main() { + + vector A1 = {3}; + vector B1 = {3, 3, 2}; + cout << Solution().maxUncrossedLines(A1, B1) << endl; + // 1 + + vector A2 = {2, 5, 1, 2, 5}; + vector B2 = {10, 5, 2, 1, 5, 2}; + cout << Solution().maxUncrossedLines(A2, B2) << endl; + // 3 + + vector A3 = {1, 4, 2}; + vector B3 = {1, 2, 4}; + cout << Solution().maxUncrossedLines(A3, B3) << endl; + // 2 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1036-Escape-a-Large-Maze/cpp-1036/CMakeLists.txt b/1001-1500/1036-Escape-a-Large-Maze/cpp-1036/CMakeLists.txt new file mode 100644 index 00000000..89658265 --- /dev/null +++ b/1001-1500/1036-Escape-a-Large-Maze/cpp-1036/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) \ No newline at end of file diff --git a/1001-1500/1036-Escape-a-Large-Maze/cpp-1036/main.cpp b/1001-1500/1036-Escape-a-Large-Maze/cpp-1036/main.cpp new file mode 100644 index 00000000..66944e7f --- /dev/null +++ b/1001-1500/1036-Escape-a-Large-Maze/cpp-1036/main.cpp @@ -0,0 +1,83 @@ +/// Source : https://leetcode.com/problems/escape-a-large-maze/ +/// Author : liuyubobobo +/// Time : 2022-01-10 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// BFS +/// Time Complexity: O(|blocks|^2) +/// Space Complexity: O(|blocks|^2) +class Solution { + +private: + const int dirs[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; + int N = 1000000; + +public: + bool isEscapePossible(vector>& blocked, vector& source, vector& target) { + + set> blockset; + for(const vector& e: blocked) + blockset.insert({e[0], e[1]}); + + return bfs(source[0], source[1], target[0], target[1], blockset) && + bfs(target[0], target[1], source[0], source[1], blockset); + } + +private: + bool bfs(int sx, int sy, int tx, int ty, + set>& blockset){ + + int L = blockset.size(); + + queue> q; + map, int> dis; + q.push({sx, sy}); + dis[{sx, sy}] = 0; + + int maxv = 0; + while(!q.empty()){ + int cx = q.front().first, cy = q.front().second, v = dis[{cx, cy}]; + q.pop(); + + if(cx == tx && cy == ty) return true; + + maxv = max(maxv, v); + if(v == L) continue; + + for(int d = 0; d < 4; d ++){ + int nx = cx + dirs[d][0], ny = cy + dirs[d][1]; + if(in_area(nx, ny) && !blockset.count({nx, ny}) && !dis.count({nx, ny})){ + q.push({nx, ny}); + dis[{nx, ny}] = v + 1; + } + } + } + return maxv >= L; + } + + bool in_area(int x, int y){ + return x >= 0 && x < N && y >= 0 && y < N; + } +}; + + +int main() { + + vector> block1 = { + {691938,300406},{710196,624190},{858790,609485},{268029,225806}, + {200010,188664},{132599,612099},{329444,633495},{196657,757958},{628509,883388} + }; + vector source1 = {655988,180910}, target1 = {267728,840949}; + cout << Solution().isEscapePossible(block1, source1, target1) << endl; + // 1 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1037-Valid-Boomerang/cpp-1037/CMakeLists.txt b/1001-1500/1037-Valid-Boomerang/cpp-1037/CMakeLists.txt new file mode 100644 index 00000000..b1976006 --- /dev/null +++ b/1001-1500/1037-Valid-Boomerang/cpp-1037/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main2.cpp) \ No newline at end of file diff --git a/1001-1500/1037-Valid-Boomerang/cpp-1037/main.cpp b/1001-1500/1037-Valid-Boomerang/cpp-1037/main.cpp new file mode 100644 index 00000000..c58462c7 --- /dev/null +++ b/1001-1500/1037-Valid-Boomerang/cpp-1037/main.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/valid-boomerang/ +/// Author : liuyubobobo +/// Time : 2019-05-04 + +#include +#include + +using namespace std; + + +/// Calculate Slope +/// Time Compelxity: O(1) +/// Space Complexity: O(1) +class Solution { +public: + bool isBoomerang(vector>& points) { + + if(points[0] == points[1] || points[1] == points[2]) + return false; + + int a = points[1][0] - points[0][0], c = points[2][0] - points[1][0], + b = points[1][1] - points[0][1], d = points[2][1] - points[1][1]; + return a * d != b * c; + } +}; + + +int main() { + + vector> points1 = {{1, 1}, {2, 3}, {3, 2}}; + cout << Solution().isBoomerang(points1) << endl; + // true + + vector> points2 = {{1, 1}, {2, 2}, {3, 3}}; + cout << Solution().isBoomerang(points2) << endl; + // false + + vector> points3 = {{0, 0}, {1, 1}, {1, 1}}; + cout << Solution().isBoomerang(points3) << endl; + // false + + vector> points4 = {{80, 32}, {46, 32}, {59, 32}}; + cout << Solution().isBoomerang(points3) << endl; + // false + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1037-Valid-Boomerang/cpp-1037/main2.cpp b/1001-1500/1037-Valid-Boomerang/cpp-1037/main2.cpp new file mode 100644 index 00000000..cea7611a --- /dev/null +++ b/1001-1500/1037-Valid-Boomerang/cpp-1037/main2.cpp @@ -0,0 +1,43 @@ +/// Source : https://leetcode.com/problems/valid-boomerang/ +/// Author : liuyubobobo +/// Time : 2019-05-18 + +#include +#include + +using namespace std; + + +/// Calculate Cross Multiplication +/// Time Compelxity: O(1) +/// Space Complexity: O(1) +class Solution { +public: + bool isBoomerang(vector>& p) { + int a = p[1][0] - p[0][0], b = p[1][1] - p[0][1], + c = p[2][0] - p[1][0], d = p[2][1] - p[1][1]; + return a * d - b * c != 0; + } +}; + + +int main() { + + vector> points1 = {{1, 1}, {2, 3}, {3, 2}}; + cout << Solution().isBoomerang(points1) << endl; + // true + + vector> points2 = {{1, 1}, {2, 2}, {3, 3}}; + cout << Solution().isBoomerang(points2) << endl; + // false + + vector> points3 = {{0, 0}, {1, 1}, {1, 1}}; + cout << Solution().isBoomerang(points3) << endl; + // false + + vector> points4 = {{80, 32}, {46, 32}, {59, 32}}; + cout << Solution().isBoomerang(points3) << endl; + // false + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1038-Binary-Search-Tree-to-Greater-Sum-Tree/cpp-1038/CMakeLists.txt b/1001-1500/1038-Binary-Search-Tree-to-Greater-Sum-Tree/cpp-1038/CMakeLists.txt new file mode 100644 index 00000000..7f3bfb51 --- /dev/null +++ b/1001-1500/1038-Binary-Search-Tree-to-Greater-Sum-Tree/cpp-1038/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main2.cpp) \ No newline at end of file diff --git a/1001-1500/1038-Binary-Search-Tree-to-Greater-Sum-Tree/cpp-1038/main.cpp b/1001-1500/1038-Binary-Search-Tree-to-Greater-Sum-Tree/cpp-1038/main.cpp new file mode 100644 index 00000000..04ba8562 --- /dev/null +++ b/1001-1500/1038-Binary-Search-Tree-to-Greater-Sum-Tree/cpp-1038/main.cpp @@ -0,0 +1,65 @@ +/// Source : https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/ +/// Author : liuyubobobo +/// Time : 2019-05-04 + +#include +#include + +using namespace std; + + +/// Inorder Traversal and Store all values +/// Time Complexity: O(2n) +/// Space Complexity: O(n) + +/// 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 { + +private: + int index = 0; + +public: + TreeNode* bstToGst(TreeNode* root) { + + if(!root) return root; + if(!root->left && !root->right) return root; + + vector order; + inorder(root, order); + + for(int i = order.size() - 2; i >= 0; i --) + order[i] += order[i + 1]; + + index = 0; + go(root, order); + return root; + } + +private: + void inorder(TreeNode* root, vector& order){ + + if(root->left) inorder(root->left, order); + order.push_back(root->val); + if(root->right) inorder(root->right, order); + } + + void go(TreeNode* root, const vector& order){ + + if(root->left) go(root->left, order); + root->val = order[index ++]; + if(root->right) go(root->right, order); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1038-Binary-Search-Tree-to-Greater-Sum-Tree/cpp-1038/main2.cpp b/1001-1500/1038-Binary-Search-Tree-to-Greater-Sum-Tree/cpp-1038/main2.cpp new file mode 100644 index 00000000..328025ea --- /dev/null +++ b/1001-1500/1038-Binary-Search-Tree-to-Greater-Sum-Tree/cpp-1038/main2.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/ +/// Author : liuyubobobo +/// Time : 2019-05-19 + +#include +#include + +using namespace std; + + +/// Inorder Traversal and Change the values during traversal +/// Using a class member pre +/// +/// Time Complexity: O(n) +/// Space Complexity: O(h) + +/// 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 { + +private: + int pre = 0; + +public: + TreeNode* bstToGst(TreeNode* root) { + + if(!root) return root; + + if(root->right) + bstToGst(root->right); + + pre += root->val; + root->val = pre; + + if(root->left) + bstToGst(root->left); + + return root; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1039-Minimum-Score-Triangulation-of-Polygon/cpp-1039/CMakeLists.txt b/1001-1500/1039-Minimum-Score-Triangulation-of-Polygon/cpp-1039/CMakeLists.txt new file mode 100644 index 00000000..70268b97 --- /dev/null +++ b/1001-1500/1039-Minimum-Score-Triangulation-of-Polygon/cpp-1039/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main2.cpp) \ No newline at end of file diff --git a/1001-1500/1039-Minimum-Score-Triangulation-of-Polygon/cpp-1039/main.cpp b/1001-1500/1039-Minimum-Score-Triangulation-of-Polygon/cpp-1039/main.cpp new file mode 100644 index 00000000..f14f2c2b --- /dev/null +++ b/1001-1500/1039-Minimum-Score-Triangulation-of-Polygon/cpp-1039/main.cpp @@ -0,0 +1,56 @@ +/// Source : https://leetcode.com/problems/minimum-score-triangulation-of-polygon/ +/// Author : liuyubobobo +/// Time : 2019-05-04 + +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(|A|^3) +/// Space Complexity: O(|A|^2) +class Solution { + +public: + int minScoreTriangulation(vector& A) { + + int n = A.size(); + vector> dp(n, vector(n, -1)); + return dfs(A, 0, n - 1, dp); + } + +private: + int dfs(const vector& A, int i, int j, + vector>& dp){ + + if(i + 2 > j) return 0; + if(i + 2 == j) return A[i] * A[i + 1] * A[i + 2]; + + if(dp[i][j] != -1) return dp[i][j]; + + int res = INT_MAX; + for(int k = i + 1; k < j; k ++) + res = min(res, dfs(A, i, k, dp) + dfs(A, k, j, dp) + A[i] * A[j] * A[k]); + return dp[i][j] = res; + } +}; + + +int main() { + + vector A1 = {1, 2, 3}; + cout << Solution().minScoreTriangulation(A1) << endl; + // 6 + + vector A2 = {3, 7, 4, 5}; + cout << Solution().minScoreTriangulation(A2) << endl; + // 144 + + vector A3 = {1, 3, 1, 4, 1, 5}; + cout << Solution().minScoreTriangulation(A3) << endl; + // 13 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1039-Minimum-Score-Triangulation-of-Polygon/cpp-1039/main2.cpp b/1001-1500/1039-Minimum-Score-Triangulation-of-Polygon/cpp-1039/main2.cpp new file mode 100644 index 00000000..daa5faab --- /dev/null +++ b/1001-1500/1039-Minimum-Score-Triangulation-of-Polygon/cpp-1039/main2.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/minimum-score-triangulation-of-polygon/ +/// Author : liuyubobobo +/// Time : 2019-05-19 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(|A|^3) +/// Space Complexity: O(|A|^2) +class Solution { + +public: + int minScoreTriangulation(vector& A) { + + int n = A.size(); + vector> dp(n, vector(n, 0)); + + for(int i = 0; i + 2 < n; i ++) + dp[i][i + 2] = A[i] * A[i + 1] * A[i + 2]; + + for(int len = 4; len <= n; len ++) + for(int i = 0; i + len - 1 < n; i ++){ + + int j = i + len - 1; + dp[i][j] = INT_MAX; + for(int k = i + 1; k < j; k ++) + dp[i][j] = min(dp[i][j], dp[i][k] + dp[k][j] + A[i] * A[j] * A[k]); + } + return dp[0][n - 1]; + } +}; + + +int main() { + + vector A1 = {1, 2, 3}; + cout << Solution().minScoreTriangulation(A1) << endl; + // 6 + + vector A2 = {3, 7, 4, 5}; + cout << Solution().minScoreTriangulation(A2) << endl; + // 144 + + vector A3 = {1, 3, 1, 4, 1, 5}; + cout << Solution().minScoreTriangulation(A3) << endl; + // 13 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1040-Moving-Stones-Until-Consecutive-II/cpp-1040/CMakeLists.txt b/1001-1500/1040-Moving-Stones-Until-Consecutive-II/cpp-1040/CMakeLists.txt new file mode 100644 index 00000000..89658265 --- /dev/null +++ b/1001-1500/1040-Moving-Stones-Until-Consecutive-II/cpp-1040/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) \ No newline at end of file diff --git a/1001-1500/1040-Moving-Stones-Until-Consecutive-II/cpp-1040/main.cpp b/1001-1500/1040-Moving-Stones-Until-Consecutive-II/cpp-1040/main.cpp new file mode 100644 index 00000000..df481771 --- /dev/null +++ b/1001-1500/1040-Moving-Stones-Until-Consecutive-II/cpp-1040/main.cpp @@ -0,0 +1,56 @@ +/// Source : https://leetcode.com/problems/moving-stones-until-consecutive-ii/ +/// Author : liuyubobobo +/// Time : 2019-05-19 + +#include +#include + +using namespace std; + + +/// Sorting +/// For Upperbound: Mathematics +/// For Lowerbound: Sliding Window +/// +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { + +private: + int n; + +public: + vector numMovesStonesII(vector& stones) { + + n = stones.size(); + sort(stones.begin(), stones.end()); + return {get_min(stones), get_max(stones)}; + } + +private: + int get_min(const vector& stones){ + + int res = INT_MAX; + int l = 0; + for(int r = 0; r < n; r ++){ + while(stones[r] - stones[l] + 1 > n) l ++; + if(r - l + 1 == n - 1 && stones[r] - stones[l] + 1 == n - 1) + res = min(res, 2); + else + res = min(res, n - (r - l + 1)); + } + return res; + } + + int get_max(const vector& stones){ + + return max((stones[n - 1] - stones[1] + 1) - n + 1, + (stones[n - 2] - stones[0] + 1) - n + 1); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1041-Robot-Bounded-In-Circle/cpp-1041/CMakeLists.txt b/1001-1500/1041-Robot-Bounded-In-Circle/cpp-1041/CMakeLists.txt new file mode 100644 index 00000000..b1976006 --- /dev/null +++ b/1001-1500/1041-Robot-Bounded-In-Circle/cpp-1041/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main2.cpp) \ No newline at end of file diff --git a/1001-1500/1041-Robot-Bounded-In-Circle/cpp-1041/main.cpp b/1001-1500/1041-Robot-Bounded-In-Circle/cpp-1041/main.cpp new file mode 100644 index 00000000..1ae1ef25 --- /dev/null +++ b/1001-1500/1041-Robot-Bounded-In-Circle/cpp-1041/main.cpp @@ -0,0 +1,62 @@ +/// Source : https://leetcode.com/problems/robot-bounded-in-circle/ +/// Author : liuyubobobo +/// Time : 2019-05-11 + +#include +#include + +using namespace std; + + +/// Simulation 4 * instructions +/// Time Complexity: O(4 * n) +/// Space Complexity: O(1) +class Solution { + +private: + const int d[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + +public: + bool isRobotBounded(string instructions) { + + string s = ""; + for(int i = 0; i < 4; i ++) s += instructions; + int curd = 0; + + pair cur = make_pair(0, 0); + + for(char c: s){ + if(c == 'G'){ + cur.first += d[curd][0]; + cur.second += d[curd][1]; + } + else if(c == 'L') + curd = (curd + 3) % 4; + else + curd = (curd + 1) % 4; + } + return !cur.first && !cur.second; + } +}; + + +int main() { + + string ins1 = "RRGRRGLLLRLGGLGLLGRLRLGLRLRRGLGGLLRRRLRLRLLGRGLGRRRGRLG"; + cout << Solution().isRobotBounded(ins1) << endl; + // 0 + + string ins2 = "GGLLGG"; + cout << Solution().isRobotBounded(ins2) << endl; + // 1 + + string ins3 = "GG"; + cout << Solution().isRobotBounded(ins3) << endl; + // 0 + + string ins4 = "GL"; + cout << Solution().isRobotBounded(ins4) << endl; + // 1 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1041-Robot-Bounded-In-Circle/cpp-1041/main2.cpp b/1001-1500/1041-Robot-Bounded-In-Circle/cpp-1041/main2.cpp new file mode 100644 index 00000000..e4ee8ef5 --- /dev/null +++ b/1001-1500/1041-Robot-Bounded-In-Circle/cpp-1041/main2.cpp @@ -0,0 +1,61 @@ +/// Source : https://leetcode.com/problems/robot-bounded-in-circle/ +/// Author : liuyubobobo +/// Time : 2019-05-19 + +#include +#include + +using namespace std; + + +/// Just Simulation one instructions sequence +/// If the robot's direction is not still north +/// It can definitely go back! +/// +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { + +private: + const int d[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + +public: + bool isRobotBounded(string instructions) { + + int curd = 0; + pair cur = make_pair(0, 0); + for(char c: instructions){ + if(c == 'G'){ + cur.first += d[curd][0]; + cur.second += d[curd][1]; + } + else if(c == 'L') + curd = (curd + 3) % 4; + else + curd = (curd + 1) % 4; + } + return (!cur.first && !cur.second) || curd; + } +}; + + +int main() { + + string ins1 = "RRGRRGLLLRLGGLGLLGRLRLGLRLRRGLGGLLRRRLRLRLLGRGLGRRRGRLG"; + cout << Solution().isRobotBounded(ins1) << endl; + // 0 + + string ins2 = "GGLLGG"; + cout << Solution().isRobotBounded(ins2) << endl; + // 1 + + string ins3 = "GG"; + cout << Solution().isRobotBounded(ins3) << endl; + // 0 + + string ins4 = "GL"; + cout << Solution().isRobotBounded(ins4) << endl; + // 1 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1042-Flower-Planting-With-No-Adjacent/cpp-1042/CMakeLists.txt b/1001-1500/1042-Flower-Planting-With-No-Adjacent/cpp-1042/CMakeLists.txt new file mode 100644 index 00000000..195bfb41 --- /dev/null +++ b/1001-1500/1042-Flower-Planting-With-No-Adjacent/cpp-1042/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main3.cpp) \ No newline at end of file diff --git a/1001-1500/1042-Flower-Planting-With-No-Adjacent/cpp-1042/main.cpp b/1001-1500/1042-Flower-Planting-With-No-Adjacent/cpp-1042/main.cpp new file mode 100644 index 00000000..b003f0dc --- /dev/null +++ b/1001-1500/1042-Flower-Planting-With-No-Adjacent/cpp-1042/main.cpp @@ -0,0 +1,83 @@ +/// Source : https://leetcode.com/problems/flower-planting-with-no-adjacent/ +/// Author : liuyubobobo +/// Time : 2019-05-11 + +#include +#include +#include +#include + +using namespace std; + + +/// BFS +/// Time Complexity: O(n^2) +/// Space Complexity: O(n^2) +class Solution { +public: + vector gardenNoAdj(int N, vector>& paths) { + + vector> g(N); + for(const vector& edge: paths){ + g[edge[0] - 1].insert(edge[1] - 1); + g[edge[1] - 1].insert(edge[0] - 1); + } + + vector colors(N, -1); + for(int i = 0; i < N; i ++) + if(colors[i] < 0) + bfs(g, i, colors); + return colors; + } + +private: + void bfs(const vector>& g, int v, vector& colors){ + + queue q; + q.push(v); + colors[v] = 1; + + while(!q.empty()){ + int cur = q.front(); + q.pop(); + + for(int next: g[cur]) + if(colors[next] == -1){ + unordered_set options = get_options(g, next, colors); + colors[next] = *options.begin(); + q.push(next); + } + } + } + + unordered_set get_options(const vector>& g, int v, + const vector& colors){ + + unordered_set options = {1, 2, 3, 4}; + for(int u: g[v]) + if(colors[u] != -1) + options.erase(colors[u]); + return options; + } +}; + + +void print_vec(const vector& vec){ + + for(int e: vec) + cout << e << " "; + cout << endl; +} + +int main() { + + vector> paths1 = {{1, 2}, {2, 3}, {3, 1}}; + print_vec(Solution().gardenNoAdj(3, paths1)); + // 1 2 3 + + vector> paths2 = {{3, 4}, {4, 5}, {3, 2}, {5, 1}, {1, 3}, {4, 2}}; + print_vec(Solution().gardenNoAdj(5, paths2)); + // 1 2 4 3 1 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1042-Flower-Planting-With-No-Adjacent/cpp-1042/main2.cpp b/1001-1500/1042-Flower-Planting-With-No-Adjacent/cpp-1042/main2.cpp new file mode 100644 index 00000000..a5e66f95 --- /dev/null +++ b/1001-1500/1042-Flower-Planting-With-No-Adjacent/cpp-1042/main2.cpp @@ -0,0 +1,74 @@ +/// Source : https://leetcode.com/problems/flower-planting-with-no-adjacent/ +/// Author : liuyubobobo +/// Time : 2019-05-19 + +#include +#include +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n^2) +/// Space Complexity: O(n^2) +class Solution { +public: + vector gardenNoAdj(int N, vector>& paths) { + + vector> g(N); + for(const vector& edge: paths){ + g[edge[0] - 1].insert(edge[1] - 1); + g[edge[1] - 1].insert(edge[0] - 1); + } + + vector colors(N, -1); + for(int i = 0; i < N; i ++) + if(colors[i] < 0) + dfs(g, i, colors); + return colors; + } + +private: + void dfs(const vector>& g, int v, vector& colors){ + + unordered_set options = get_options(g, v, colors); + colors[v] = *options.begin(); + + for(int next: g[v]) + if(colors[next] == -1) + dfs(g, next, colors); + } + + unordered_set get_options(const vector>& g, int v, + const vector& colors){ + + unordered_set options = {1, 2, 3, 4}; + for(int u: g[v]) + if(colors[u] != -1) + options.erase(colors[u]); + return options; + } +}; + + +void print_vec(const vector& vec){ + + for(int e: vec) + cout << e << " "; + cout << endl; +} + +int main() { + + vector> paths1 = {{1, 2}, {2, 3}, {3, 1}}; + print_vec(Solution().gardenNoAdj(3, paths1)); + // 1 2 3 + + vector> paths2 = {{3, 4}, {4, 5}, {3, 2}, {5, 1}, {1, 3}, {4, 2}}; + print_vec(Solution().gardenNoAdj(5, paths2)); + // 1 2 4 3 1 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1042-Flower-Planting-With-No-Adjacent/cpp-1042/main3.cpp b/1001-1500/1042-Flower-Planting-With-No-Adjacent/cpp-1042/main3.cpp new file mode 100644 index 00000000..9f6e7933 --- /dev/null +++ b/1001-1500/1042-Flower-Planting-With-No-Adjacent/cpp-1042/main3.cpp @@ -0,0 +1,67 @@ +/// Source : https://leetcode.com/problems/flower-planting-with-no-adjacent/ +/// Author : liuyubobobo +/// Time : 2019-05-19 + +#include +#include +#include +#include + +using namespace std; + + +/// Greedy +/// Actually no need to BFS or DFS +/// +/// Time Complexity: O(n^2) +/// Space Complexity: O(n^2) +class Solution { +public: + vector gardenNoAdj(int N, vector>& paths) { + + vector> g(N); + for(const vector& edge: paths){ + g[edge[0] - 1].insert(edge[1] - 1); + g[edge[1] - 1].insert(edge[0] - 1); + } + + vector colors(N, -1); + for(int i = 0; i < N; i ++){ + unordered_set options = get_options(g, i, colors); + colors[i] = *options.begin(); + } + return colors; + } + +private: + unordered_set get_options(const vector>& g, int v, + const vector& colors){ + + unordered_set options = {1, 2, 3, 4}; + for(int u: g[v]) + if(colors[u] != -1) + options.erase(colors[u]); + return options; + } +}; + + +void print_vec(const vector& vec){ + + for(int e: vec) + cout << e << " "; + cout << endl; +} + +int main() { + + vector> paths1 = {{1, 2}, {2, 3}, {3, 1}}; + print_vec(Solution().gardenNoAdj(3, paths1)); + // 1 2 3 + + vector> paths2 = {{3, 4}, {4, 5}, {3, 2}, {5, 1}, {1, 3}, {4, 2}}; + print_vec(Solution().gardenNoAdj(5, paths2)); + // 1 2 4 3 1 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1043-Partition-Array-for-Maximum-Sum/cpp-1043/CMakeLists.txt b/1001-1500/1043-Partition-Array-for-Maximum-Sum/cpp-1043/CMakeLists.txt new file mode 100644 index 00000000..70268b97 --- /dev/null +++ b/1001-1500/1043-Partition-Array-for-Maximum-Sum/cpp-1043/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main2.cpp) \ No newline at end of file diff --git a/1001-1500/1043-Partition-Array-for-Maximum-Sum/cpp-1043/main.cpp b/1001-1500/1043-Partition-Array-for-Maximum-Sum/cpp-1043/main.cpp new file mode 100644 index 00000000..ccb822fc --- /dev/null +++ b/1001-1500/1043-Partition-Array-for-Maximum-Sum/cpp-1043/main.cpp @@ -0,0 +1,42 @@ +/// Source : https://leetcode.com/problems/partition-array-for-maximum-sum/ +/// Author : liuyubobobo +/// Time : 2019-05-11 + +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(|A|^2) +/// Space Complexity :O(|A|) +class Solution { +public: + int maxSumAfterPartitioning(vector& A, int K) { + + vector dp(A.size(), -1); + return dfs(A, 0, K, dp); + } + +private: + int dfs(const vector& A, int start, int K, vector& dp){ + + if(start == A.size()) return 0; + if(dp[start] != -1) return dp[start]; + + int maxv = A[start]; + int res = 0; + for(int end = start; end <= min(start + K - 1, (int)A.size() - 1); end ++){ + maxv = max(maxv, A[end]); + res = max(res, maxv * (end - start + 1) + dfs(A, end + 1, K, dp)); + } + return dp[start] = res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1043-Partition-Array-for-Maximum-Sum/cpp-1043/main2.cpp b/1001-1500/1043-Partition-Array-for-Maximum-Sum/cpp-1043/main2.cpp new file mode 100644 index 00000000..5ff8e931 --- /dev/null +++ b/1001-1500/1043-Partition-Array-for-Maximum-Sum/cpp-1043/main2.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/partition-array-for-maximum-sum/ +/// Author : liuyubobobo +/// Time : 2019-05-19 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(|A|^2) +/// Space Complexity :O(|A|) +class Solution { +public: + int maxSumAfterPartitioning(vector& A, int K) { + + vector dp(A.size()); + for(int i = 0; i < A.size(); i ++){ + + int curMax = 0; + for(int k = 1; k <= K && i - k + 1 >= 0; k ++){ + curMax = max(curMax, A[i - k + 1]); + dp[i] = max(dp[i], (i >= k ? dp[i - k] : 0) + curMax * k); + } + } + return dp[A.size() - 1]; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1044-Longest-Duplicate-Substring/cpp-1044/CMakeLists.txt b/1001-1500/1044-Longest-Duplicate-Substring/cpp-1044/CMakeLists.txt new file mode 100644 index 00000000..643141f3 --- /dev/null +++ b/1001-1500/1044-Longest-Duplicate-Substring/cpp-1044/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(cpp_1044) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1044 main.cpp) \ No newline at end of file diff --git a/1001-1500/1044-Longest-Duplicate-Substring/cpp-1044/main.cpp b/1001-1500/1044-Longest-Duplicate-Substring/cpp-1044/main.cpp new file mode 100644 index 00000000..852a594f --- /dev/null +++ b/1001-1500/1044-Longest-Duplicate-Substring/cpp-1044/main.cpp @@ -0,0 +1,72 @@ +/// Source : https://leetcode.com/problems/longest-duplicate-substring/ +/// Author : liuyubobobo +/// Time : 2019-05-19 + +#include +#include +#include + +using namespace std; + + +/// Binary Search + Rolling Hash +/// Time Complexity: O(|S| * log(|S|)) +/// Space Complexity: O(|S|) +class Solution { + +private: + long long MOD = 9223372036854775807ll / 26ll; + vector power; + +public: + string longestDupSubstring(string S) { + + power.push_back(1ll); + for(int i = 1; i < S.size(); i ++) + power.push_back(power.back() * 26 % MOD); + + int l = 0, h = S.size() - 1; + string res = ""; + while(l < h){ + + int mid = (l + h + 1) / 2; + string tres = ok(S, mid); + if(tres != "") + l = mid, res = tres; + else + h = mid - 1; + } + return res; + } + +private: + string ok(const string& s, int len){ + + long long base = power[len - 1]; + long long hash = 0; + for(int i = 0; i < len; i ++) + hash = (hash * 26ll + (s[i] - 'a')) % MOD; + + unordered_set seen; + seen.insert(hash); + for(int i = len; i < s.size(); i ++){ + hash = (hash - (s[i - len] - 'a') * base % MOD + MOD) % MOD; + hash = (hash * 26ll + (s[i] - 'a')) % MOD; + if(seen.count(hash)) return s.substr(i - len + 1, len); + seen.insert(hash); + } + return ""; + } +}; + + +int main() { + + cout << Solution().longestDupSubstring("banana") << endl; + // ana + + cout << Solution().longestDupSubstring("abcd") << endl; + // "" + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1046-Last-Stone-Weight/cpp-1046/CMakeLists.txt b/1001-1500/1046-Last-Stone-Weight/cpp-1046/CMakeLists.txt new file mode 100644 index 00000000..b1976006 --- /dev/null +++ b/1001-1500/1046-Last-Stone-Weight/cpp-1046/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main2.cpp) \ No newline at end of file diff --git a/1001-1500/1046-Last-Stone-Weight/cpp-1046/main.cpp b/1001-1500/1046-Last-Stone-Weight/cpp-1046/main.cpp new file mode 100644 index 00000000..6493393c --- /dev/null +++ b/1001-1500/1046-Last-Stone-Weight/cpp-1046/main.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/last-stone-weight/ +/// Author : liuyubobobo +/// Time : 2019-05-18 + +#include +#include + +using namespace std; + + +/// Simulation and keep sorting +/// Time Complexity: O(n * nlogn) +/// Space Complexity: O(1) +class Solution { +public: + int lastStoneWeight(vector& stones) { + + sort(stones.begin(), stones.end()); + while(stones.size() > 1){ + int a = stones.back(); + stones.pop_back(); + int b = stones.back(); + stones.pop_back(); + + if(a != b){ + stones.push_back(a - b); + sort(stones.begin(), stones.end()); + } + } + + if(stones.size()) return stones[0]; + return 0; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1046-Last-Stone-Weight/cpp-1046/main2.cpp b/1001-1500/1046-Last-Stone-Weight/cpp-1046/main2.cpp new file mode 100644 index 00000000..b62e5080 --- /dev/null +++ b/1001-1500/1046-Last-Stone-Weight/cpp-1046/main2.cpp @@ -0,0 +1,38 @@ +/// Source : https://leetcode.com/problems/last-stone-weight/ +/// Author : liuyubobobo +/// Time : 2019-05-19 + +#include +#include +#include + +using namespace std; + + +/// Using Priority Queue +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + int lastStoneWeight(vector& stones) { + + priority_queue pq; + for(int e: stones) pq.push(e); + + while(pq.size() > 1){ + int a = pq.top(); pq.pop(); + int b = pq.top(); pq.pop(); + pq.push(a - b); + } + return pq.size() == 1 ? pq.top() : 0; + } +}; + + +int main() { + + vector stones = {2,7,4,1,8,1}; + cout << Solution().lastStoneWeight(stones) << endl; + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1047-Remove-All-Adjacent-Duplicates-In-String/cpp-1047/CMakeLists.txt b/1001-1500/1047-Remove-All-Adjacent-Duplicates-In-String/cpp-1047/CMakeLists.txt new file mode 100644 index 00000000..3c6ea462 --- /dev/null +++ b/1001-1500/1047-Remove-All-Adjacent-Duplicates-In-String/cpp-1047/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1001-1500/1047-Remove-All-Adjacent-Duplicates-In-String/cpp-1047/main.cpp b/1001-1500/1047-Remove-All-Adjacent-Duplicates-In-String/cpp-1047/main.cpp new file mode 100644 index 00000000..1d8237ff --- /dev/null +++ b/1001-1500/1047-Remove-All-Adjacent-Duplicates-In-String/cpp-1047/main.cpp @@ -0,0 +1,31 @@ +/// Source : https://leetcode.com/problems/two-sum/description/ +/// Author : liuyubobobo +/// Time : 2019-05-18 + +#include + +using namespace std; + + +/// Using Stack +/// Time Complexity: O(|S|) +/// Space Complexity: O(1) +class Solution { +public: + string removeDuplicates(string S) { + + string res = ""; + for(char c: S) + if(!res.size() || res.back() != c) + res += c; + else + res.pop_back(); + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1049-Last-Stone-Weight-II/cpp-1049/CMakeLists.txt b/1001-1500/1049-Last-Stone-Weight-II/cpp-1049/CMakeLists.txt new file mode 100644 index 00000000..fb6b8f50 --- /dev/null +++ b/1001-1500/1049-Last-Stone-Weight-II/cpp-1049/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_1049) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1049 main.cpp) \ No newline at end of file diff --git a/1001-1500/1049-Last-Stone-Weight-II/cpp-1049/main.cpp b/1001-1500/1049-Last-Stone-Weight-II/cpp-1049/main.cpp new file mode 100644 index 00000000..0d210a58 --- /dev/null +++ b/1001-1500/1049-Last-Stone-Weight-II/cpp-1049/main.cpp @@ -0,0 +1,49 @@ +/// Source : https://leetcode.com/problems/last-stone-weight-ii/ +/// Author : liuyubobobo +/// Time : 2021-06-07 + +#include +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(n * sum) +/// Space Complexity: O(sum) +class Solution { +public: + int lastStoneWeightII(vector& stones) { + + int n = stones.size(); + int sum = accumulate(stones.begin(), stones.end(), 0); + + vector dp(sum / 2 + 1, false); + dp[0] = true; + if(stones[0] <= sum / 2) dp[stones[0]] = true; + for(int i = 1; i < n; i ++){ + for(int j = sum / 2; j >= stones[i]; j --) + dp[j] = dp[j - stones[i]] || dp[j]; + } + + int res = 0; + for(int i = sum / 2; i >= 0; i --) + if(dp[i]){ + res = i; break; + } +// cout << "res = " << res << endl; + + return sum - 2 * res; + } +}; + + +int main() { + + vector stones1 = {31,26,33,21,40}; + cout << Solution().lastStoneWeightII(stones1) << endl; + // 5 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1051-Height-Checker/cpp-1051/CMakeLists.txt b/1001-1500/1051-Height-Checker/cpp-1051/CMakeLists.txt new file mode 100644 index 00000000..0cc7ac25 --- /dev/null +++ b/1001-1500/1051-Height-Checker/cpp-1051/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_1051) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1051 main.cpp) diff --git a/1001-1500/1051-Height-Checker/cpp-1051/main.cpp b/1001-1500/1051-Height-Checker/cpp-1051/main.cpp new file mode 100644 index 00000000..ea6d0669 --- /dev/null +++ b/1001-1500/1051-Height-Checker/cpp-1051/main.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/height-checker/s +/// Author : liuyubobobo +/// Time : 2022-06-12 + +#include +#include +#include + +using namespace std; + + +/// Sorting +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + int heightChecker(vector& heights) { + + vector final(heights.begin(), heights.end()); + sort(final.begin(), final.end()); + + int res = 0; + for(int i = 0; i < heights.size(); i ++) + res += heights[i] != final[i]; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1052-Grumpy-Bookstore-Owner/cpp-1052/CMakeLists.txt b/1001-1500/1052-Grumpy-Bookstore-Owner/cpp-1052/CMakeLists.txt new file mode 100644 index 00000000..0c7baf5a --- /dev/null +++ b/1001-1500/1052-Grumpy-Bookstore-Owner/cpp-1052/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1052) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1052 main.cpp) \ No newline at end of file diff --git a/1001-1500/1052-Grumpy-Bookstore-Owner/cpp-1052/main.cpp b/1001-1500/1052-Grumpy-Bookstore-Owner/cpp-1052/main.cpp new file mode 100644 index 00000000..54da67d8 --- /dev/null +++ b/1001-1500/1052-Grumpy-Bookstore-Owner/cpp-1052/main.cpp @@ -0,0 +1,44 @@ +/// Source : https://leetcode.com/problems/grumpy-bookstore-owner/ +/// Author : liuyubobobo +/// Time : 2021-02-22 + +#include +#include + +using namespace std; + + +/// Sliding Window +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int maxSatisfied(vector& customers, vector& grumpy, int X) { + + int cur = 0, maxv = 0, sum = 0; + for(int i = 0; i + 1 < X; i ++){ + cur += grumpy[i] * customers[i]; + sum += (1 - grumpy[i]) * customers[i]; + } + + for(int i = X - 1; i < customers.size(); i ++){ + cur += customers[i] * grumpy[i]; + sum += (1 - grumpy[i]) * customers[i]; + maxv = max(maxv, cur); + cur -= customers[i - (X - 1)] * grumpy[i - (X - 1)]; + } + + return sum + maxv; + } +}; + + +int main() { + + vector customers = {1, 0, 1, 2, 1, 1, 7, 5}; + vector grumpy = {0, 1, 0, 1, 0, 1, 0, 1}; + cout << Solution().maxSatisfied(customers, grumpy, 3) << endl; + // 16 + + return 0; +} diff --git a/1001-1500/1053-Previous-Permutation-With-One-Swap/cpp-1053/CMakeLists.txt b/1001-1500/1053-Previous-Permutation-With-One-Swap/cpp-1053/CMakeLists.txt new file mode 100644 index 00000000..41d3cd9c --- /dev/null +++ b/1001-1500/1053-Previous-Permutation-With-One-Swap/cpp-1053/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_1053) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_1053 main.cpp) diff --git a/1001-1500/1053-Previous-Permutation-With-One-Swap/cpp-1053/main.cpp b/1001-1500/1053-Previous-Permutation-With-One-Swap/cpp-1053/main.cpp new file mode 100644 index 00000000..867973c2 --- /dev/null +++ b/1001-1500/1053-Previous-Permutation-With-One-Swap/cpp-1053/main.cpp @@ -0,0 +1,42 @@ +/// Source : https://leetcode.com/problems/previous-permutation-with-one-swap/description/ +/// Author : liuyubobobo +/// Time : 2023-04-02 + +#include +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + vector prevPermOpt1(vector& arr) { + + if(is_sorted(arr.begin(), arr.end())) return arr; + + int n = arr.size(); + for(int i = n - 1; i > 0; i --) + if(arr[i - 1] > arr[i]){ + auto iter = lower_bound(arr.begin() + i, arr.end(), arr[i - 1]); + iter --; + + int index = iter - arr.begin(); + int t = *iter; + while(arr[index - 1] == t) index --; + + swap(arr[i - 1], arr[index]); + break; + } + return arr; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1054-Distant-Barcodes/cpp-1054/CMakeLists.txt b/1001-1500/1054-Distant-Barcodes/cpp-1054/CMakeLists.txt new file mode 100644 index 00000000..3bb48eff --- /dev/null +++ b/1001-1500/1054-Distant-Barcodes/cpp-1054/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_1054) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_1054 main.cpp) diff --git a/1001-1500/1054-Distant-Barcodes/cpp-1054/main.cpp b/1001-1500/1054-Distant-Barcodes/cpp-1054/main.cpp new file mode 100644 index 00000000..39a11892 --- /dev/null +++ b/1001-1500/1054-Distant-Barcodes/cpp-1054/main.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/distant-barcodes/description/ +/// Author : liuyubobobo +/// Time : 2023-05-13 + +#include +#include +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + vector rearrangeBarcodes(vector& barcodes) { + + int n = barcodes.size(); + map f; + for(int barcode : barcodes) f[barcode]++; + + vector> v; + for(const pair& p: f) v.push_back(p); + + sort(v.begin(), v.end(), [](const pair& a, const pair& b) { + return a.second < b.second; + }); + + vector res(n); + for(int i = 0; i < n; i += 2){ + res[i] = v.back().first; + v.back().second --; + if(v.back().second == 0) v.pop_back(); + } + for(int i = 1; i < n; i += 2){ + res[i] = v.back().first; + v.back().second --; + if(v.back().second == 0) v.pop_back(); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1055-Shortest-Way-to-Form-String/cpp-1055/CMakeLists.txt b/1001-1500/1055-Shortest-Way-to-Form-String/cpp-1055/CMakeLists.txt new file mode 100644 index 00000000..d16026a9 --- /dev/null +++ b/1001-1500/1055-Shortest-Way-to-Form-String/cpp-1055/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_1055) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_1055 main.cpp) diff --git a/1001-1500/1055-Shortest-Way-to-Form-String/cpp-1055/main.cpp b/1001-1500/1055-Shortest-Way-to-Form-String/cpp-1055/main.cpp new file mode 100644 index 00000000..10767f82 --- /dev/null +++ b/1001-1500/1055-Shortest-Way-to-Form-String/cpp-1055/main.cpp @@ -0,0 +1,43 @@ +/// Source : https://leetcode.com/problems/shortest-way-to-form-string/description/ +/// Author : liuyubobobo +/// Time : 2023-03-09 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(|s| * |t|) +/// Space Complexity: O(1) +class Solution { +public: + int shortestWay(string source, string target) { + + int res = 0, start = 0; + while(start < target.size()) { + if(ok(source, target, start)) res++; + else return -1; + } + return res; + } + +private: + bool ok(const string& source, const string& target, int& start) { + + int j = start; + for(int i = 0; i < source.size() && j < target.size(); i ++) + if(source[i] == target[j]) j ++; + + if(j == start) return false; + start = j; + return true; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1056-Confusing-Number/cpp-1056/CMakeLists.txt b/1001-1500/1056-Confusing-Number/cpp-1056/CMakeLists.txt new file mode 100644 index 00000000..500ba285 --- /dev/null +++ b/1001-1500/1056-Confusing-Number/cpp-1056/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_1056) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_1056 main.cpp) diff --git a/1001-1500/1056-Confusing-Number/cpp-1056/main.cpp b/1001-1500/1056-Confusing-Number/cpp-1056/main.cpp new file mode 100644 index 00000000..8dffe08a --- /dev/null +++ b/1001-1500/1056-Confusing-Number/cpp-1056/main.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/confusing-number/description/ +/// Author : liuyubobobo +/// Time : 2023-01-04 + +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(logn) +/// Space Compelxity: O(logn) +class Solution { +public: + bool confusingNumber(int n) { + + string s1 = to_string(n); + string s2 = s1; + reverse(s2.begin(), s2.end()); + + for(char& c: s2){ + if(c != '0' && c != '1' && c != '6' && c != '8' && c != '9') return false; + if(c == '6') c = '9'; else if(c == '9') c = '6'; + } + return s1 != s2; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1059-All-Paths-from-Source-Lead-to-Destination/cpp-1059/CMakeLists.txt b/1001-1500/1059-All-Paths-from-Source-Lead-to-Destination/cpp-1059/CMakeLists.txt new file mode 100644 index 00000000..ab30ca52 --- /dev/null +++ b/1001-1500/1059-All-Paths-from-Source-Lead-to-Destination/cpp-1059/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_1059) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1059 main.cpp) \ No newline at end of file diff --git a/1001-1500/1059-All-Paths-from-Source-Lead-to-Destination/cpp-1059/main.cpp b/1001-1500/1059-All-Paths-from-Source-Lead-to-Destination/cpp-1059/main.cpp new file mode 100644 index 00000000..95cd9305 --- /dev/null +++ b/1001-1500/1059-All-Paths-from-Source-Lead-to-Destination/cpp-1059/main.cpp @@ -0,0 +1,66 @@ +/// Source : https://leetcode.com/problems/all-paths-from-source-lead-to-destination/ +/// Author : liuyubobobo +/// Time : 2021-06-22 +#include +#include +#include + +using namespace std; + + +/// Directed Graph find loop + DFS +/// Time Complexity: O(V + E) +/// Space Complexity: O(V + E) +class Solution { +public: + bool leadsToDestination(int n, vector>& edges, int source, int destination) { + + vector> g(n); + vector indeg(n, 0); + for(const vector& e: edges){ + g[e[0]].push_back(e[1]); + indeg[e[1]] ++; + } + + vector inloop(n, false); + queue q; + for(int i = 0; i < n; i ++) + if(indeg[i] == 0) q.push(i); + while(!q.empty()){ + int u = q.front(); + q.pop(); + + for(int v: g[u]){ + indeg[v] --; + if(indeg[v] == 0) + q.push(v); + } + } + + for(int i = 0; i < n; i ++) + if(indeg[i]) inloop[i] = true; + + vector visited(n, false); + return dfs(g, source, destination, inloop, visited); + } + +private: + bool dfs(const vector>& g, int u, int t, + const vector& inloop, vector& visited){ + + visited[u] = true; + + if(inloop[u]) return false; + if(g[u].size() == 0) return u == t; + + for(int v: g[u]) + if(!visited[v] && !dfs(g, v, t, inloop, visited)) return false; + return true; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1061-Lexicographically-Smallest-Equivalent-String/cpp-1061/CMakeLists.txt b/1001-1500/1061-Lexicographically-Smallest-Equivalent-String/cpp-1061/CMakeLists.txt new file mode 100644 index 00000000..000615a7 --- /dev/null +++ b/1001-1500/1061-Lexicographically-Smallest-Equivalent-String/cpp-1061/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_1061) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_1061 main.cpp) diff --git a/1001-1500/1061-Lexicographically-Smallest-Equivalent-String/cpp-1061/main.cpp b/1001-1500/1061-Lexicographically-Smallest-Equivalent-String/cpp-1061/main.cpp new file mode 100644 index 00000000..df32fc80 --- /dev/null +++ b/1001-1500/1061-Lexicographically-Smallest-Equivalent-String/cpp-1061/main.cpp @@ -0,0 +1,70 @@ +/// Source : https://leetcode.com/problems/lexicographically-smallest-equivalent-string/description/ +/// Author : liuyubobobo +/// Time : 2023-01-14 + +#include +#include + +using namespace std; + + +/// UF +/// Time Complexity: O(n) +/// Space Compelxity: O(1) +class UF{ + +private: + vector parent; + +public: + UF(int n) : parent(n){ + for(int i = 0 ; i < n ; i ++) + parent[i] = i; + } + + int find(int p){ + if(p != parent[p]) + parent[p] = find(parent[p]); + return parent[p]; + } + + bool is_connected(int p, int q){ + return find(p) == find(q); + } + + void union_elements(int p, int q){ + + int p_root = find(p), q_root = find(q); + + if(p_root == q_root) return; + + parent[p_root] = q_root; + } +}; + +class Solution { +public: + string smallestEquivalentString(string s1, string s2, string baseStr) { + + UF uf(26); + for(int i = 0; i < s1.size(); i ++) + uf.union_elements(s1[i] - 'a', s2[i] - 'a'); + + vector min_char(26, 'z'); + for(int i = 0; i < 26; i ++){ + int p = uf.find(i); + min_char[p] = min(min_char[p], (char)('a' + i)); + } + + string res(baseStr.size(), ' '); + for(int i = 0; i < baseStr.size(); i ++) + res[i] = min_char[uf.find(baseStr[i] - 'a')]; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1062-Longest-Repeating-Substring/cpp-1062/CMakeLists.txt b/1001-1500/1062-Longest-Repeating-Substring/cpp-1062/CMakeLists.txt new file mode 100644 index 00000000..e3e13ee1 --- /dev/null +++ b/1001-1500/1062-Longest-Repeating-Substring/cpp-1062/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(cpp_1062) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1062 main3.cpp) \ No newline at end of file diff --git a/1001-1500/1062-Longest-Repeating-Substring/cpp-1062/main.cpp b/1001-1500/1062-Longest-Repeating-Substring/cpp-1062/main.cpp new file mode 100644 index 00000000..8f0de6d5 --- /dev/null +++ b/1001-1500/1062-Longest-Repeating-Substring/cpp-1062/main.cpp @@ -0,0 +1,43 @@ +/// Source : https://leetcode.com/problems/longest-repeating-substring/ +/// Author : liuyubobobo +/// Time : 2020-06-19 + +#include +#include + +using namespace std; + + +/// Binary Search + Hash Table +/// Time Complexity: O(|s|^2 * log|s|) +/// Space Complexity: O(|s|^2) +class Solution { +public: + int longestRepeatingSubstring(string s) { + + int l = 0, r = s.size() - 1; + while(l < r){ + int mid = (l + r + 1) / 2; + if(ok(s, mid)) l = mid; + else r = mid - 1; + } + return l; + } + +private: + bool ok(const string& s, int len){ + + unordered_set hashtable; + for(int i = 0; i + len <= s.size(); i ++){ + string t = s.substr(i, len); + if(hashtable.count(t)) return true; + hashtable.insert(t); + } + return false; + } +}; + +int main() { + + return 0; +} diff --git a/1001-1500/1062-Longest-Repeating-Substring/cpp-1062/main2.cpp b/1001-1500/1062-Longest-Repeating-Substring/cpp-1062/main2.cpp new file mode 100644 index 00000000..9dd977a4 --- /dev/null +++ b/1001-1500/1062-Longest-Repeating-Substring/cpp-1062/main2.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/longest-repeating-substring/ +/// Author : liuyubobobo +/// Time : 2020-06-19 + +#include +#include + +using namespace std; + + +/// Binary Search + Rolling Hash +/// Time Complexity: O(|s| * log|s|) +/// Space Complexity: O(|s|) +class Solution { +public: + int longestRepeatingSubstring(string s) { + + int l = 0, r = s.size() - 1; + while(l < r){ + int mid = (l + r + 1) / 2; + if(ok(s, mid)) l = mid; + else r = mid - 1; + } + return l; + } + +private: + bool ok(const string& s, int len){ + + unordered_set hashtable; + int b = 26, MOD = 82595483, al = 1; + for(int i = 1; i < len; i ++) al = (al * b) % MOD; + + int hash = 0; + for(int i = 0; i + 1 < len; i ++) hash = (hash * b + (s[i] - 'a')) % MOD; + + for(int i = len - 1; i < s.size(); i ++){ + hash = (hash * b + (s[i] - 'a')) % MOD; + + if(hashtable.count(hash)) return true; + hashtable.insert(hash); + + hash -= (s[i - (len - 1)] - 'a') * al; + while(hash < 0) hash += MOD; + } + return false; + } +}; + + +int main() { + + cout << Solution().longestRepeatingSubstring("abbaba") << endl; + // 2 + + return 0; +} diff --git a/1001-1500/1062-Longest-Repeating-Substring/cpp-1062/main3.cpp b/1001-1500/1062-Longest-Repeating-Substring/cpp-1062/main3.cpp new file mode 100644 index 00000000..3eeefcaa --- /dev/null +++ b/1001-1500/1062-Longest-Repeating-Substring/cpp-1062/main3.cpp @@ -0,0 +1,58 @@ +#include +#include +#include + +using namespace std; + + +/// Binary Search + Rolling Hash + Dealing with collision +/// Time Complexity: O(|s| * log|s|) +/// Space Complexity: O(|s|^2) +class Solution { +public: + int longestRepeatingSubstring(string s) { + + int l = 0, r = s.size() - 1; + while(l < r){ + int mid = (l + r + 1) / 2; + if(ok(s, mid)) l = mid; + else r = mid - 1; + } + return l; + } + +private: + bool ok(const string& s, int len){ + + unordered_map> hashtable; + int b = 26, MOD = 82595483, al = 1; + for(int i = 1; i < len; i ++) al = (al * b) % MOD; + + int hash = 0; + for(int i = 0; i + 1 < len; i ++) hash = (hash * b + (s[i] - 'a')) % MOD; + + for(int i = len - 1; i < s.size(); i ++){ + string t = s.substr(i - (len - 1), len); + hash = (hash * b + (s[i] - 'a')) % MOD; + + if(hashtable.count(hash)){ + for(const string& e : hashtable[hash]) + if(e == t) return true; + } + hashtable[hash].push_back(t); + + hash -= (s[i - (len - 1)] - 'a') * al; + while(hash < 0) hash += MOD; + } + return false; + } +}; + + +int main() { + + cout << Solution().longestRepeatingSubstring("abbaba") << endl; + // 2 + + return 0; +} diff --git a/1001-1500/1065-Index-Pairs-of-a-String/cpp-1065/CMakeLists.txt b/1001-1500/1065-Index-Pairs-of-a-String/cpp-1065/CMakeLists.txt new file mode 100644 index 00000000..34246b31 --- /dev/null +++ b/1001-1500/1065-Index-Pairs-of-a-String/cpp-1065/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_1065) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_1065 main.cpp) diff --git a/1001-1500/1065-Index-Pairs-of-a-String/cpp-1065/main.cpp b/1001-1500/1065-Index-Pairs-of-a-String/cpp-1065/main.cpp new file mode 100644 index 00000000..b45b56e4 --- /dev/null +++ b/1001-1500/1065-Index-Pairs-of-a-String/cpp-1065/main.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/index-pairs-of-a-string/description/ +/// Author : liuyubobobo +/// Time : 2023-04-30 + +#include +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(|words|^2 * |text|) +/// Space Complexity: O(1) +class Solution { +public: + vector> indexPairs(string text, vector& words) { + + vector> res; + for(const string& word: words) { + int pos = 0; + while(true){ + pos = text.find(word, pos); + if(pos != string::npos) { + res.push_back({pos, pos + (int) word.size() - 1}); + pos = pos + 1; + } + else break; + } + } + sort(res.begin(), res.end()); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1066-Campus-Bikes-II/cpp-1066/CMakeLists.txt b/1001-1500/1066-Campus-Bikes-II/cpp-1066/CMakeLists.txt new file mode 100644 index 00000000..5266da59 --- /dev/null +++ b/1001-1500/1066-Campus-Bikes-II/cpp-1066/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_1066) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_1066 main.cpp) diff --git a/1001-1500/1066-Campus-Bikes-II/cpp-1066/main.cpp b/1001-1500/1066-Campus-Bikes-II/cpp-1066/main.cpp new file mode 100644 index 00000000..e2c4da89 --- /dev/null +++ b/1001-1500/1066-Campus-Bikes-II/cpp-1066/main.cpp @@ -0,0 +1,55 @@ +/// Source : https://leetcode.com/problems/campus-bikes-ii/ +/// Author : liuyubobobo +/// Time : 2022-12-17 + +#include +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(n * m * 2^m) +/// Space Complexity: O(n * 2^m) +class Solution { +public: + int assignBikes(vector>& workers, vector>& bikes) { + + int n = workers.size(), m = bikes.size(); + vector> dis(n, vector(m)); + for(int i = 0; i < n; i ++) + for(int j = 0; j < m; j ++) + dis[i][j] = get_dis(workers[i], bikes[j]); + + vector> dp(n, vector(1 << m, -1)); + return dfs(n, m, dis, 0, 0, dp); + } + +private: + int dfs(int n, int m, const vector>& dis, int index, int state, + vector>& dp){ + + if(index == n) return 0; + if(dp[index][state] != -1) return dp[index][state]; + + int res = INT_MAX; + for(int j = 0; j < m; j ++){ + if(state & (1 << j)) continue; + res = min(res, dis[index][j] + dfs(n, m, dis, index + 1, state | (1 << j), dp)); + } + return dp[index][state] = res; + } + + int get_dis(const vector& v1, const vector& v2){ + int x1 = v1[0], y1 = v1[1]; + int x2 = v2[0], y2 = v2[1]; + return abs(x1 - x2) + abs(y1 - y2); + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1072-Flip-Columns-For-Maximum-Number-of-Equal-Rows/cpp-1072/CMakeLists.txt b/1001-1500/1072-Flip-Columns-For-Maximum-Number-of-Equal-Rows/cpp-1072/CMakeLists.txt new file mode 100644 index 00000000..3c6ea462 --- /dev/null +++ b/1001-1500/1072-Flip-Columns-For-Maximum-Number-of-Equal-Rows/cpp-1072/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1001-1500/1072-Flip-Columns-For-Maximum-Number-of-Equal-Rows/cpp-1072/main.cpp b/1001-1500/1072-Flip-Columns-For-Maximum-Number-of-Equal-Rows/cpp-1072/main.cpp new file mode 100644 index 00000000..aa154d29 --- /dev/null +++ b/1001-1500/1072-Flip-Columns-For-Maximum-Number-of-Equal-Rows/cpp-1072/main.cpp @@ -0,0 +1,41 @@ +/// Source : https://leetcode.com/problems/flip-columns-for-maximum-number-of-equal-rows/ +/// Author : liuyubobobo +/// Time : 2019-06-01 + +#include +#include +#include + +using namespace std; + + +/// Using Map to record all the flip possibilities +/// Time Complexity: O(n^2) +/// Space Complexity: O(2*n^2) +class Solution { +public: + int maxEqualRowsAfterFlips(vector>& matrix) { + + map, int> flip; + for(vector& row: matrix){ + flip[row] ++; + for(int& c: row) + c = 1 - c; + flip[row] ++; + } + + int res = 0; + for(const pair, int>& p: flip) + res = max(res, p.second); + return res; + } +}; + + +int main() { + + vector> matrix1 = {{0, 1}, {1, 1}}; + cout << Solution().maxEqualRowsAfterFlips(matrix1) << endl; + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1072-Flip-Columns-For-Maximum-Number-of-Equal-Rows/cpp-1072/main2.cpp b/1001-1500/1072-Flip-Columns-For-Maximum-Number-of-Equal-Rows/cpp-1072/main2.cpp new file mode 100644 index 00000000..c7681b92 --- /dev/null +++ b/1001-1500/1072-Flip-Columns-For-Maximum-Number-of-Equal-Rows/cpp-1072/main2.cpp @@ -0,0 +1,45 @@ +/// Source : https://leetcode.com/problems/flip-columns-for-maximum-number-of-equal-rows/ +/// Author : liuyubobobo +/// Time : 2019-06-02 + +#include +#include +#include + +using namespace std; + + +/// Using Map to record all the patterns +/// Time Complexity: O(n^2) +/// Space Complexity: O(n^2) +class Solution { +public: + int maxEqualRowsAfterFlips(vector>& matrix) { + + map, int> flip; + for(vector& row: matrix){ + + if(!row[0]) + flip[row] ++; + else{ + for(int& c: row) + c = 1 - c; + flip[row] ++; + } + } + + int res = 0; + for(const pair, int>& p: flip) + res = max(res, p.second); + return res; + } +}; + + +int main() { + + vector> matrix1 = {{0, 1}, {1, 1}}; + cout << Solution().maxEqualRowsAfterFlips(matrix1) << endl; + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1074-Number-of-Submatrices-That-Sum-to-Target/cpp-1074/CMakeLists.txt b/1001-1500/1074-Number-of-Submatrices-That-Sum-to-Target/cpp-1074/CMakeLists.txt new file mode 100644 index 00000000..f542c09c --- /dev/null +++ b/1001-1500/1074-Number-of-Submatrices-That-Sum-to-Target/cpp-1074/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_1074) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1074 main.cpp) \ No newline at end of file diff --git a/1001-1500/1074-Number-of-Submatrices-That-Sum-to-Target/cpp-1074/main.cpp b/1001-1500/1074-Number-of-Submatrices-That-Sum-to-Target/cpp-1074/main.cpp new file mode 100644 index 00000000..44048cfb --- /dev/null +++ b/1001-1500/1074-Number-of-Submatrices-That-Sum-to-Target/cpp-1074/main.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/number-of-submatrices-that-sum-to-target/ +/// Author : liuyubobobo +/// Time : 2021-04-17 + +#include +#include +#include + +using namespace std; + + +/// Presum + HashMap +/// Time Complexity: O(n^3) +/// Space Complexity: O(n^2) +class Solution { +public: + int numSubmatrixSumTarget(vector>& matrix, int target) { + + int R = matrix.size(), C = matrix[0].size(); + vector> presum(R + 1, vector(C, 0)); + for(int j = 0; j < C; j ++) + for(int i = 0; i < R; i ++) + presum[i + 1][j] = presum[i][j] + matrix[i][j]; + + int res = 0; + for(int r1 = 0; r1 < R; r1 ++) + for(int r2 = r1; r2 < R; r2 ++){ + + unordered_map table; + table[0] ++; + int sum = 0; + for(int c = 0; c < C; c ++){ + sum += presum[r2 + 1][c] - presum[r1][c]; + res += table[sum - target]; + table[sum] ++; + } + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1078-Occurrences-After-Bigram/cpp-1078/CMakeLists.txt b/1001-1500/1078-Occurrences-After-Bigram/cpp-1078/CMakeLists.txt new file mode 100644 index 00000000..afa8217d --- /dev/null +++ b/1001-1500/1078-Occurrences-After-Bigram/cpp-1078/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1001-1500/1078-Occurrences-After-Bigram/cpp-1078/main.cpp b/1001-1500/1078-Occurrences-After-Bigram/cpp-1078/main.cpp new file mode 100644 index 00000000..d24b588f --- /dev/null +++ b/1001-1500/1078-Occurrences-After-Bigram/cpp-1078/main.cpp @@ -0,0 +1,38 @@ +/// Source : https://leetcode.com/problems/occurrences-after-bigram/ +/// Author : liuyubobobo +/// Time : 2019-06-08 + +#include +#include + +using namespace std; + + +/// Linear Scan and split +/// Time Complexity: O(|text|) +/// Space Complexity: O(|text|) +class Solution { +public: + vector findOcurrences(string text, string first, string second) { + + vector res; + vector v; + for(int start = 0, i = start + 1; i <= text.size(); i ++) + if(i == text.size() || text[i] == ' '){ + string word = text.substr(start, i - start); + if(v.size() >= 2 && v[v.size() - 2] == first && v[v.size() - 1] == second) + res.push_back(word); + v.push_back(word); + + start = i; + i = start; + } + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1079-Letter-Tile-Possibilities/cpp-1079/CMakeLists.txt b/1001-1500/1079-Letter-Tile-Possibilities/cpp-1079/CMakeLists.txt new file mode 100644 index 00000000..7f3bfb51 --- /dev/null +++ b/1001-1500/1079-Letter-Tile-Possibilities/cpp-1079/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main2.cpp) \ No newline at end of file diff --git a/1001-1500/1079-Letter-Tile-Possibilities/cpp-1079/main.cpp b/1001-1500/1079-Letter-Tile-Possibilities/cpp-1079/main.cpp new file mode 100644 index 00000000..26f39bff --- /dev/null +++ b/1001-1500/1079-Letter-Tile-Possibilities/cpp-1079/main.cpp @@ -0,0 +1,48 @@ +/// Source : https://leetcode.com/problems/letter-tile-possibilities/ +/// Author : liuyubobobo +/// Time : 2019-06-08 + +#include +#include +#include + +using namespace std; + + +/// Backtracking and Permutation, Storing by Hash Set +/// Time Complexity: O(n! * n!) +/// Space Complexity: O(n) +class Solution { +public: + int numTilePossibilities(string tiles) { + + sort(tiles.begin(), tiles.end()); + unordered_set set; + dfs(tiles, 0, "", set); + return set.size(); + } + +private: + void dfs(const string& tiles, int index, const string& cur_res, unordered_set& set){ + + if(index == tiles.size()){ + if(cur_res != ""){ + string t = cur_res; + sort(t.begin(), t.end()); + do{ + set.insert(t); + }while(next_permutation(t.begin(), t.end())); + } + return; + } + + dfs(tiles, index + 1, cur_res + tiles[index], set); + dfs(tiles, index + 1, cur_res, set); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1079-Letter-Tile-Possibilities/cpp-1079/main2.cpp b/1001-1500/1079-Letter-Tile-Possibilities/cpp-1079/main2.cpp new file mode 100644 index 00000000..8d68903f --- /dev/null +++ b/1001-1500/1079-Letter-Tile-Possibilities/cpp-1079/main2.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/letter-tile-possibilities/ +/// Author : liuyubobobo +/// Time : 2019-06-15 + +#include +#include +#include +#include + +using namespace std; + + +/// Counting on the fly, based on frequency of characters +/// Time Complexity: O(n!) +/// Space Complexity: O(n) +class Solution { + +public: + int numTilePossibilities(string tiles) { + + unordered_map freq; + for(char c: tiles) + freq[c] ++; + + return dfs(freq); + } + +private: + int dfs(unordered_map& freq){ + + int res = 0; + for(char e = 'A'; e <= 'Z'; e ++) + if(freq[e]){ + res ++; + freq[e] --; + res += dfs(freq); + freq[e] ++; + } + return res; + } +}; + + +int main() { + + cout << Solution().numTilePossibilities("AAB") << endl; + // 8 + + cout << Solution().numTilePossibilities("AAABBC") << endl; + // 188 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1080-Insufficient-Nodes-in-Root-to-Leaf-Paths/cpp-1080/CMakeLists.txt b/1001-1500/1080-Insufficient-Nodes-in-Root-to-Leaf-Paths/cpp-1080/CMakeLists.txt new file mode 100644 index 00000000..a9faeff1 --- /dev/null +++ b/1001-1500/1080-Insufficient-Nodes-in-Root-to-Leaf-Paths/cpp-1080/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1001-1500/1080-Insufficient-Nodes-in-Root-to-Leaf-Paths/cpp-1080/main.cpp b/1001-1500/1080-Insufficient-Nodes-in-Root-to-Leaf-Paths/cpp-1080/main.cpp new file mode 100644 index 00000000..9e536db5 --- /dev/null +++ b/1001-1500/1080-Insufficient-Nodes-in-Root-to-Leaf-Paths/cpp-1080/main.cpp @@ -0,0 +1,75 @@ +/// Source : https://leetcode.com/problems/insufficient-nodes-in-root-to-leaf-paths/ +/// Author : liuyubobobo +/// Time : 2019-06-08 + +#include +#include +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(h) + +/// 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* sufficientSubset(TreeNode* root, int limit) { + + unordered_map> map; + vector path; + return dfs(root, 0, path, map, limit); + } + +private: + TreeNode* dfs(TreeNode* node, int cur_sum, vector& path, + unordered_map>& map, int limit){ + + path.push_back(node); + cur_sum += node->val; + + if(!node->left && !node->right){ + for(TreeNode* t: path) + map[t].push_back(cur_sum); + } + else{ + if(node->left) + node->left = dfs(node->left, cur_sum, path, map, limit); + if(node->right) + node->right = dfs(node->right, cur_sum, path, map, limit); + } + + path.pop_back(); + + if(insufficient(map[node], limit)){ + if(node->left && node->right) assert(false); + else if(node->left) return node->left; + else if(node->right) return node->right; + return NULL; + } + return node; + } + + bool insufficient(const vector& vec, int limit){ + + for(int e: vec) + if(e >= limit) return false; + return true; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1081-Smallest-Subsequence-of-Distinct-Characters/cpp-1081/CMakeLists.txt b/1001-1500/1081-Smallest-Subsequence-of-Distinct-Characters/cpp-1081/CMakeLists.txt new file mode 100644 index 00000000..90e11ac0 --- /dev/null +++ b/1001-1500/1081-Smallest-Subsequence-of-Distinct-Characters/cpp-1081/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1081) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1081 main.cpp) \ No newline at end of file diff --git a/1001-1500/1081-Smallest-Subsequence-of-Distinct-Characters/cpp-1081/main.cpp b/1001-1500/1081-Smallest-Subsequence-of-Distinct-Characters/cpp-1081/main.cpp new file mode 100644 index 00000000..a444ac15 --- /dev/null +++ b/1001-1500/1081-Smallest-Subsequence-of-Distinct-Characters/cpp-1081/main.cpp @@ -0,0 +1,41 @@ +/// Source : https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/ +/// Author : liuyubobobo +/// Time : 2020-12-01 + +#include +#include + +using namespace std; + + +/// Mono Stack +/// Same as 316 +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + string smallestSubsequence(string s) { + + vector left(26, 0), used(26, 0); + for(char c: s) left[c - 'a'] ++; + + string res = ""; + for(char c: s){ + if(!used[c - 'a']){ + while(res != "" && left[res.back() - 'a'] && c <= res.back()){ + used[res.back() - 'a'] = false ; + res.pop_back(); + } + res += c, used[c - 'a'] = true; + } + left[c - 'a'] --; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1087-Brace-Expansion/cpp-1087/CMakeLists.txt b/1001-1500/1087-Brace-Expansion/cpp-1087/CMakeLists.txt new file mode 100644 index 00000000..3ea1ed9c --- /dev/null +++ b/1001-1500/1087-Brace-Expansion/cpp-1087/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(cpp_1087) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1087 main2.cpp) \ No newline at end of file diff --git a/1001-1500/1087-Brace-Expansion/cpp-1087/main.cpp b/1001-1500/1087-Brace-Expansion/cpp-1087/main.cpp new file mode 100644 index 00000000..ba046f50 --- /dev/null +++ b/1001-1500/1087-Brace-Expansion/cpp-1087/main.cpp @@ -0,0 +1,92 @@ +/// Source : https://leetcode.com/problems/brace-expansion/ +/// Author : liuyubobobo +/// Time : 2020-05-07 + +#include +#include +#include + +using namespace std; + + +/// DFS +/// Using TreeSet to keep order +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector expand(string s) { + + set res = expand(s, 0, s.size() - 1); + return vector(res.begin(), res.end()); + } + +private: + set expand(const string& s, int l, int r){ + + if(l > r) return {}; + + set a, b; + int i; + if(s[l] == '{'){ + for(i = l + 1; i <= r; i ++) + if(s[i] == '}'){ + a = split(s, l + 1, i - 1); + break; + } + b = expand(s, i + 1, r); + return mul(a, b); + } + + for(i = l; i <= r; i ++) + if(s[i] == '{') break; + + a = split(s, l, i - 1); + b = expand(s, i, r); + return mul(a, b); + } + + set mul(const set& a, const set& b){ + + if(a.empty()) return b; + if(b.empty()) return a; + + set res; + for(const string& s1: a) + for(const string& s2: b) + res.insert(s1 + s2); + return res; + } + + set split(const string& s, int l, int r){ + set res; + for(int start = l, i = start + 1; i <= r + 1; i ++) + if(i == r + 1 || s[i] == ','){ + res.insert(s.substr(start, i - start)); + start = i + 1; + i = start; + } + return res; + } +}; + + +void print_vec(const vector& vec){ + + for(const string& e: vec) + cout << e << " "; + cout << endl; +} + +int main() { + + print_vec(Solution().expand("{a,b}c{d,e}f")); + // "acdf","acef","bcdf","bcef" + + print_vec(Solution().expand("abcd")); + // abcd + + print_vec(Solution().expand("k{a,b,c,d,e,f,g}")); + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1087-Brace-Expansion/cpp-1087/main2.cpp b/1001-1500/1087-Brace-Expansion/cpp-1087/main2.cpp new file mode 100644 index 00000000..313bdd0e --- /dev/null +++ b/1001-1500/1087-Brace-Expansion/cpp-1087/main2.cpp @@ -0,0 +1,93 @@ +/// Source : https://leetcode.com/problems/brace-expansion/ +/// Author : liuyubobobo +/// Time : 2020-05-07 + +#include +#include +#include + +using namespace std; + + +/// DFS +/// Using vector to store result and sorting at last +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + vector expand(string s) { + + vector res = expand(s, 0, s.size() - 1); + sort(res.begin(), res.end()); + return res; + } + +private: + vector expand(const string& s, int l, int r){ + + if(l > r) return {}; + + vector a, b; + int i; + if(s[l] == '{'){ + for(i = l + 1; i <= r; i ++) + if(s[i] == '}'){ + a = split(s, l + 1, i - 1); + break; + } + b = expand(s, i + 1, r); + return mul(a, b); + } + + for(i = l; i <= r; i ++) + if(s[i] == '{') break; + + a = split(s, l, i - 1); + b = expand(s, i, r); + return mul(a, b); + } + + vector mul(const vector& a, const vector& b){ + + if(a.empty()) return b; + if(b.empty()) return a; + + vector res; + for(const string& s1: a) + for(const string& s2: b) + res.push_back(s1 + s2); + return res; + } + + vector split(const string& s, int l, int r){ + vector res; + for(int start = l, i = start + 1; i <= r + 1; i ++) + if(i == r + 1 || s[i] == ','){ + res.push_back(s.substr(start, i - start)); + start = i + 1; + i = start; + } + return res; + } +}; + + +void print_vec(const vector& vec){ + + for(const string& e: vec) + cout << e << " "; + cout << endl; +} + +int main() { + + print_vec(Solution().expand("{a,b}c{d,e}f")); + // "acdf","acef","bcdf","bcef" + + print_vec(Solution().expand("abcd")); + // abcd + + print_vec(Solution().expand("k{a,b,c,d,e,f,g}")); + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1088-Confusing-Number-II/cpp-1088/CMakeLists.txt b/1001-1500/1088-Confusing-Number-II/cpp-1088/CMakeLists.txt new file mode 100644 index 00000000..7d08cc44 --- /dev/null +++ b/1001-1500/1088-Confusing-Number-II/cpp-1088/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_1088) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_1088 main.cpp) diff --git a/1001-1500/1088-Confusing-Number-II/cpp-1088/main.cpp b/1001-1500/1088-Confusing-Number-II/cpp-1088/main.cpp new file mode 100644 index 00000000..d9992184 --- /dev/null +++ b/1001-1500/1088-Confusing-Number-II/cpp-1088/main.cpp @@ -0,0 +1,68 @@ +/// Source : https://leetcode.com/problems/confusing-number-ii/description/ +/// Author : liuyubobobo +/// Time : 2023-01-21 + +#include +#include +#include + +using namespace std; + + +/// Backtrack +/// Time Complexity: O(5^9) +/// Space Complexity: O(1) +class Solution { + +private: + const vector valid_digits = {0, 1, 6, 8, 9}; + const vector r_digits = {0, 1, -1, -1, -1, -1, 9, -1, 8, 6}; + +public: + int confusingNumberII(int n) { + + int len = to_string(n).size(); + vector nums(len); + return dfs(len, nums, 0, 0, n); + } + +private: + int dfs(int len, vector& nums, int index, long long cur, long long n){ + + if(cur > n) return 0; + + if(index == len){ + + int i = 0; + for(i = 0; i < len && nums[i] == 0; i ++); + + long long r = 0; + for(int j = len - 1; j >= i; j --) + r = r * 10ll + r_digits[nums[j]]; +// if(cur != r) cout << cur << '\n'; + return cur != r; + } + + int res = 0; + for(int d: valid_digits){ + nums[index] = d; + res += dfs(len, nums, index + 1, cur * 10ll + d, n); + } + return res; + } +}; + + +int main() { + + cout << Solution().confusingNumberII(20) << '\n'; + // 6 + + cout << Solution().confusingNumberII(100) << '\n'; + // 19 + + cout << Solution().confusingNumberII(1000000000) << '\n'; + // 1950627 + + return 0; +} diff --git a/1001-1500/1089-Duplicate-Zeros/cpp-1089/CMakeLists.txt b/1001-1500/1089-Duplicate-Zeros/cpp-1089/CMakeLists.txt new file mode 100644 index 00000000..b1976006 --- /dev/null +++ b/1001-1500/1089-Duplicate-Zeros/cpp-1089/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main2.cpp) \ No newline at end of file diff --git a/1001-1500/1089-Duplicate-Zeros/cpp-1089/main.cpp b/1001-1500/1089-Duplicate-Zeros/cpp-1089/main.cpp new file mode 100644 index 00000000..051d94b8 --- /dev/null +++ b/1001-1500/1089-Duplicate-Zeros/cpp-1089/main.cpp @@ -0,0 +1,32 @@ +/// Source : https://leetcode.com/problems/duplicate-zeros/ +/// Author : liuyubobobo +/// Time : 2019-06-15 + +#include +#include + +using namespace std; + + +/// Using another array to construct the result +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + void duplicateZeros(vector& arr) { + + vector res; + for(int e: arr) + if(e) res.push_back(e); + else res.push_back(0), res.push_back(0); + + for(int i = 0; i < arr.size(); i ++) + arr[i] = res[i]; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1089-Duplicate-Zeros/cpp-1089/main2.cpp b/1001-1500/1089-Duplicate-Zeros/cpp-1089/main2.cpp new file mode 100644 index 00000000..6f5abdbd --- /dev/null +++ b/1001-1500/1089-Duplicate-Zeros/cpp-1089/main2.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/duplicate-zeros/ +/// Author : liuyubobobo +/// Time : 2019-06-15 + +#include +#include + +using namespace std; + + +/// Scan from end to start to make sure every position +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + void duplicateZeros(vector& arr) { + + int n = arr.size(); + int j = n + count(arr.begin(), arr.end(), 0); + for(int i = n - 1; i >= 0; i --){ + if(--j < n) + arr[j] = arr[i]; + if(!arr[i] && --j < n) + arr[j] = 0; + } + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1090-Largest-Values-From-Labels/cpp-1090/CMakeLists.txt b/1001-1500/1090-Largest-Values-From-Labels/cpp-1090/CMakeLists.txt new file mode 100644 index 00000000..3c6ea462 --- /dev/null +++ b/1001-1500/1090-Largest-Values-From-Labels/cpp-1090/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1001-1500/1090-Largest-Values-From-Labels/cpp-1090/main.cpp b/1001-1500/1090-Largest-Values-From-Labels/cpp-1090/main.cpp new file mode 100644 index 00000000..68507c3f --- /dev/null +++ b/1001-1500/1090-Largest-Values-From-Labels/cpp-1090/main.cpp @@ -0,0 +1,48 @@ +/// Source : https://leetcode.com/problems/largest-values-from-labels/ +/// Author : liuyubobobo +/// Time : 2019-06-15 + +#include +#include +#include + +using namespace std; + + +/// Sorting and Greedy +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + int largestValsFromLabels(vector& values, vector& labels, int num_wanted, int use_limit) { + + vector> vec; + for(int i = 0; i < values.size(); i ++) + vec.push_back(make_pair(values[i], labels[i])); + sort(vec.begin(), vec.end(), greater>()); + + unordered_map freq; + int sum = 0, num = 0; + for(const pair& p: vec) + if(freq[p.second] < use_limit){ + + sum += p.first; + num ++; + freq[p.second] ++; + if(num == num_wanted) + break; + } + return sum; + } +}; + + +int main() { + + vector values = {5,4,3,2,1}; + vector labels = {1,1,2,2,3}; + int num_wanted = 3, use_limit = 1; + cout << Solution().largestValsFromLabels(values, labels, num_wanted, use_limit) << endl; + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1091-Shortest-Path-in-Binary-Matrix/cpp-1091/CMakeLists.txt b/1001-1500/1091-Shortest-Path-in-Binary-Matrix/cpp-1091/CMakeLists.txt new file mode 100644 index 00000000..a9faeff1 --- /dev/null +++ b/1001-1500/1091-Shortest-Path-in-Binary-Matrix/cpp-1091/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1001-1500/1091-Shortest-Path-in-Binary-Matrix/cpp-1091/main.cpp b/1001-1500/1091-Shortest-Path-in-Binary-Matrix/cpp-1091/main.cpp new file mode 100644 index 00000000..8fd1bc34 --- /dev/null +++ b/1001-1500/1091-Shortest-Path-in-Binary-Matrix/cpp-1091/main.cpp @@ -0,0 +1,64 @@ +/// Source : https://leetcode.com/problems/shortest-path-in-binary-matrix/ +/// Author : liuyubobobo +/// Time : 2019-06-15 + +#include +#include +#include + +using namespace std; + + +/// BFS +/// Time Complexity: O(n * m) +/// Space Complexity: O(n * m) +class Solution { + +private: + const int d[8][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}, + {1, 1}, {1, -1}, {-1, 1}, {-1, -1}}; + int n, m; + +public: + int shortestPathBinaryMatrix(vector>& grid) { + + if(grid[0][0]) return -1; + + n = grid.size(), m = grid[0].size(); + vector> res(n, vector(m, -2)); + + queue q; + res[0][0] = 0; + q.push(0); + while(!q.empty()){ + int x = q.front() / m; + int y = q.front() % m; + q.pop(); + + for(int i = 0; i < 8; i ++){ + int newX = x + d[i][0], newY = y + d[i][1]; + if(newX >= 0 && newX < n && newY >= 0 && newY < m && + grid[newX][newY] == 0 && res[newX][newY] == -2){ + res[newX][newY] = res[x][y] + 1; + q.push(newX * m + newY); + } + } + } + +// for(int i = 0; i < n; i ++){ +// for(int j = 0; j < m; j ++) +// cout << res[i][j] << " "; +// cout << endl; +// } + return res[n - 1][m - 1] + 1; + } +}; + + +int main() { + + vector> grid = {{0,0,0},{1,1,0},{1,1,0}}; + cout << Solution().shortestPathBinaryMatrix(grid) << endl; + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1092-Shortest-Common-Supersequence/cpp-1092/CMakeLists.txt b/1001-1500/1092-Shortest-Common-Supersequence/cpp-1092/CMakeLists.txt new file mode 100644 index 00000000..bee29d53 --- /dev/null +++ b/1001-1500/1092-Shortest-Common-Supersequence/cpp-1092/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main2.cpp) \ No newline at end of file diff --git a/1001-1500/1092-Shortest-Common-Supersequence/cpp-1092/main.cpp b/1001-1500/1092-Shortest-Common-Supersequence/cpp-1092/main.cpp new file mode 100644 index 00000000..95f63797 --- /dev/null +++ b/1001-1500/1092-Shortest-Common-Supersequence/cpp-1092/main.cpp @@ -0,0 +1,63 @@ +/// Source : https://leetcode.com/problems/shortest-common-supersequence/ +/// Author : liuyubobobo +/// Time : 2019-06-15 + +#include +#include + +using namespace std; + + +/// LCS + Using DP table to reconstruct result +/// Time Complexity: O(|str1| * |str2|) +/// Space Complexity: O(|str1| * |str2|) +class Solution { +public: + string shortestCommonSupersequence(string str1, string str2) { + + int n = str1.size(), m = str2.size(); + vector> dp(n + 1, vector(m + 1, 0)); + + for(int i = 0; i < n; i ++) + for(int j = 0; j < m; j ++) + if(str1[i] == str2[j]) + dp[i + 1][j + 1] = 1 + dp[i][j]; + else + dp[i + 1][j + 1] = max(dp[i + 1][j], dp[i][j + 1]); + +// for(int i = 0; i <= n; i ++){ +// for(int j = 0; j <= m; j ++) +// cout << dp[i][j] << " "; +// cout << endl; +// } +// cout << dp[n][m] << endl; + + string res = ""; + int cur1 = n, cur2 = m; + while(cur1 && cur2){ + if(str1[cur1 - 1] != str2[cur2 - 1]){ + if(dp[cur1][cur2] == dp[cur1 - 1][cur2]) + res += str1[cur1 - 1], cur1 --; + else + res += str2[cur2 - 1], cur2 --; + } + else + res += str1[cur1 - 1], cur1 --, cur2 --; + } + while(cur1) + res += str1[cur1 - 1], cur1 --; + while(cur2) + res += str2[cur2 - 1], cur2 --; + reverse(res.begin(), res.end()); + return res; + } +}; + + +int main() { + + string str1 = "abac", str2 = "cab"; + cout << Solution().shortestCommonSupersequence(str1, str2) << endl; + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1092-Shortest-Common-Supersequence/cpp-1092/main2.cpp b/1001-1500/1092-Shortest-Common-Supersequence/cpp-1092/main2.cpp new file mode 100644 index 00000000..43ef5523 --- /dev/null +++ b/1001-1500/1092-Shortest-Common-Supersequence/cpp-1092/main2.cpp @@ -0,0 +1,51 @@ +/// Source : https://leetcode.com/problems/shortest-common-supersequence/ +/// Author : liuyubobobo +/// Time : 2019-06-16 + +#include +#include + +using namespace std; + + +/// LCS + Using LCS string to reconstruct +/// Time Complexity: O(|str1| * |str2|) +/// Space Complexity: O(|str1| * |str2|) +class Solution { +public: + string shortestCommonSupersequence(string str1, string str2) { + + int n = str1.size(), m = str2.size(); + vector> dp(n + 1, vector(m + 1, "")); + + for(int i = 0; i < n; i ++) + for(int j = 0; j < m; j ++) + if(str1[i] == str2[j]) + dp[i + 1][j + 1] = dp[i][j] + str1[i]; + else + dp[i + 1][j + 1] = dp[i + 1][j].size() > dp[i][j + 1].size() ? + dp[i + 1][j] : dp[i][j + 1]; + string lcs = dp[n][m]; +// cout << lcs << endl; + + string res = ""; + int cur1 = 0, cur2 = 0; + for(char c: lcs){ + while(cur1 < n && str1[cur1] != c) + res += str1[cur1 ++]; + while(cur2 < m && str2[cur2] != c) + res += str2[cur2 ++]; + res += c, cur1 ++, cur2 ++; + } + return res + str1.substr(cur1) + str2.substr(cur2); + } +}; + + +int main() { + + string str1 = "abac", str2 = "cab"; + cout << Solution().shortestCommonSupersequence(str1, str2) << endl; + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1093-Statistics-from-a-Large-Sample/cpp-1093/CMakeLists.txt b/1001-1500/1093-Statistics-from-a-Large-Sample/cpp-1093/CMakeLists.txt new file mode 100644 index 00000000..b1976006 --- /dev/null +++ b/1001-1500/1093-Statistics-from-a-Large-Sample/cpp-1093/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main2.cpp) \ No newline at end of file diff --git a/1001-1500/1093-Statistics-from-a-Large-Sample/cpp-1093/main.cpp b/1001-1500/1093-Statistics-from-a-Large-Sample/cpp-1093/main.cpp new file mode 100644 index 00000000..b3454e69 --- /dev/null +++ b/1001-1500/1093-Statistics-from-a-Large-Sample/cpp-1093/main.cpp @@ -0,0 +1,82 @@ +/// Source : https://leetcode.com/problems/statistics-from-a-large-sample/ +/// Author : liuyubobobo +/// Time : 2019-06-22 + +#include +#include +#include + +using namespace std; + + +/// Mathematics +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + vector sampleStats(vector& count) { + + vector res; + res.push_back(min_value(count)); + res.push_back(max_value(count)); + res.push_back(mean(count)); + res.push_back(median(count)); + res.push_back(mode(count)); + return res; + } + +private: + int min_value(const vector& count) { + for(int i = 0; i <= 255; i ++) + if(count[i]) + return i; + return -1; + } + + int max_value(const vector& count) { + for(int i = 255; i >= 0; i --) + if(count[i]) + return i; + return -1; + } + + double mean(const vector& count){ + + long long sum = 0ll; + int n = accumulate(count.begin(), count.end(), 0); + + for(long long i = 0; i <= 255; i ++) + sum += i * count[i]; + return sum / (double)n; + } + + double median(const vector& count){ + + int n = accumulate(count.begin(), count.end(), 0); + if(n % 2) return get_num(count, n / 2); + return (get_num(count, n / 2 - 1) + get_num(count, n / 2)) / 2.0; + } + + int get_num(const vector& count, int index){ + + for(int i = 0; i <= 255; i ++) + if(count[i] && index < count[i]) return i; + else index -= count[i]; + return -1; + } + + int mode(const vector& count){ + + int best = 0, res = -1; + for(int i = 0; i <= 255; i ++) + if(count[i] > best) + best = count[i], res = i; + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1093-Statistics-from-a-Large-Sample/cpp-1093/main2.cpp b/1001-1500/1093-Statistics-from-a-Large-Sample/cpp-1093/main2.cpp new file mode 100644 index 00000000..847f9997 --- /dev/null +++ b/1001-1500/1093-Statistics-from-a-Large-Sample/cpp-1093/main2.cpp @@ -0,0 +1,82 @@ +/// Source : https://leetcode.com/problems/statistics-from-a-large-sample/ +/// Author : liuyubobobo +/// Time : 2019-06-22 + +#include +#include +#include + +using namespace std; + + +/// Mathematics +/// A smarter way to calculate median :-) +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + vector sampleStats(vector& count) { + + vector res; + res.push_back(min_value(count)); + res.push_back(max_value(count)); + res.push_back(mean(count)); + res.push_back(median(count)); + res.push_back(mode(count)); + return res; + } + +private: + int min_value(const vector& count) { + for(int i = 0; i <= 255; i ++) + if(count[i]) + return i; + return -1; + } + + int max_value(const vector& count) { + for(int i = 255; i >= 0; i --) + if(count[i]) + return i; + return -1; + } + + double mean(const vector& count){ + + long long sum = 0ll; + int n = accumulate(count.begin(), count.end(), 0); + + for(long long i = 0; i <= 255; i ++) + sum += i * count[i]; + return sum / (double)n; + } + + double median(const vector& count){ + + int n = accumulate(count.begin(), count.end(), 0); + return (get_num(count, n / 2 - 1) + get_num(count, n / 2)) / 2.0; + } + + int get_num(const vector& count, int index){ + + for(int i = 0; i <= 255; i ++) + if(count[i] && index < count[i]) return i; + else index -= count[i]; + return -1; + } + + int mode(const vector& count){ + + int best = 0, res = -1; + for(int i = 0; i <= 255; i ++) + if(count[i] > best) + best = count[i], res = i; + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1094-Car-Pooling/cpp-1094/CMakeLists.txt b/1001-1500/1094-Car-Pooling/cpp-1094/CMakeLists.txt new file mode 100644 index 00000000..3c6ea462 --- /dev/null +++ b/1001-1500/1094-Car-Pooling/cpp-1094/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1001-1500/1094-Car-Pooling/cpp-1094/main.cpp b/1001-1500/1094-Car-Pooling/cpp-1094/main.cpp new file mode 100644 index 00000000..606fb617 --- /dev/null +++ b/1001-1500/1094-Car-Pooling/cpp-1094/main.cpp @@ -0,0 +1,36 @@ +/// Source : https://leetcode.com/problems/car-pooling/ +/// Author : liuyubobobo +/// Time : 2019-06-22 + +#include +#include +#include + +using namespace std; + + +/// Using TreeMap to record all the time events +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + bool carPooling(vector>& trips, int capacity) { + + map map; + for(const vector& trip: trips) + map[trip[1]] += trip[0], map[trip[2]] -= trip[0]; + + int cur = 0; + for(const pair& p: map){ + cur += p.second; + if(cur > capacity) return false; + } + return true; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1095-Find-in-Mountain-Array/cpp-1095/CMakeLists.txt b/1001-1500/1095-Find-in-Mountain-Array/cpp-1095/CMakeLists.txt new file mode 100644 index 00000000..70268b97 --- /dev/null +++ b/1001-1500/1095-Find-in-Mountain-Array/cpp-1095/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main2.cpp) \ No newline at end of file diff --git a/1001-1500/1095-Find-in-Mountain-Array/cpp-1095/main.cpp b/1001-1500/1095-Find-in-Mountain-Array/cpp-1095/main.cpp new file mode 100644 index 00000000..1e75b977 --- /dev/null +++ b/1001-1500/1095-Find-in-Mountain-Array/cpp-1095/main.cpp @@ -0,0 +1,74 @@ +/// Source : https://leetcode.com/problems/find-in-mountain-array/ +/// Author : liuyubobobo +/// Time : 2019-06-22 + +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(logn) +/// Space Complexity: O(logn) +class MountainArray { +public: + int get(int index){return -1;} + int length(){return -1;} +}; + + +class Solution { + +private: + int n; + +public: + int findInMountainArray(int target, MountainArray &mountainArr) { + + n = mountainArr.length(); + return findInMountainArray(target, mountainArr, 0, n - 1); + } + +private: + int findInMountainArray(int target, MountainArray &mountainArr, int l, int r){ + + if(l > r) return -1; + + int mid = (l + r) / 2; + int e = mountainArr.get(mid); + + bool isInc = isIncrease(mountainArr, mid, e); + + if(e == target){ + if(isInc) return mid; + else{ + int res = findInMountainArray(target, mountainArr, l, mid - 1); + return res == -1 ? mid : res; + } + } + else if(e < target){ + if(isInc) return findInMountainArray(target, mountainArr, mid + 1, r); + else return findInMountainArray(target, mountainArr, l, mid - 1); + } + else{ // e > target + int res = findInMountainArray(target, mountainArr, l, mid - 1); + return res == -1 ? findInMountainArray(target, mountainArr, mid + 1, r) : res; + } + + return -1; + } + + bool isIncrease(MountainArray &mountainArr, int index, int e){ + + if(index == 0) return true; + + int e2 = mountainArr.get(index - 1); + return e2 < e; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1095-Find-in-Mountain-Array/cpp-1095/main2.cpp b/1001-1500/1095-Find-in-Mountain-Array/cpp-1095/main2.cpp new file mode 100644 index 00000000..0ca5d31d --- /dev/null +++ b/1001-1500/1095-Find-in-Mountain-Array/cpp-1095/main2.cpp @@ -0,0 +1,76 @@ +/// Source : https://leetcode.com/problems/find-in-mountain-array/ +/// Author : liuyubobobo +/// Time : 2019-06-22 + +#include + +using namespace std; + + +/// Find peak and then Using Binary Search +/// Time Complexity: O(logn) +/// Space Complexity: O(logn) +class MountainArray { +public: + int get(int index){return -1;} + int length(){return -1;} +}; + + +class Solution { + +private: + int n; + +public: + int findInMountainArray(int target, MountainArray &mountainArr) { + + n = mountainArr.length(); + + // find peak + int peak = find_peak(mountainArr); + + // binary search + int res = binary_search(mountainArr, 0, peak, target, true); + return res == -1 ? binary_search(mountainArr, peak, n - 1, target, false) : res; + } + +private: + int find_peak(MountainArray &mountainArr){ + + int l = 0, r = n - 1; + while(l < r){ + int mid = (l + r) / 2; + if(mountainArr.get(mid) < mountainArr.get(mid + 1)) + l = mid + 1; + else + r = mid; + } + return l; + } + + int binary_search(MountainArray &mountainArr, int l, int r, int target, bool is_inc){ + + while(l <= r){ + int mid = (l + r) / 2; + int e = mountainArr.get(mid); + if(e == target) return mid; + + if(is_inc){ + if(e < target) l = mid + 1; + else r = mid - 1; + } + else{ + if(e < target) r = mid - 1; + else l = mid + 1; + } + } + return -1; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1096-Brace-Expansion-II/cpp-1096/CMakeLists.txt b/1001-1500/1096-Brace-Expansion-II/cpp-1096/CMakeLists.txt new file mode 100644 index 00000000..89658265 --- /dev/null +++ b/1001-1500/1096-Brace-Expansion-II/cpp-1096/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) \ No newline at end of file diff --git a/1001-1500/1096-Brace-Expansion-II/cpp-1096/main.cpp b/1001-1500/1096-Brace-Expansion-II/cpp-1096/main.cpp new file mode 100644 index 00000000..657696e3 --- /dev/null +++ b/1001-1500/1096-Brace-Expansion-II/cpp-1096/main.cpp @@ -0,0 +1,138 @@ +/// Source : https://leetcode.com/problems/brace-expansion-ii/ +/// Author : liuyubobobo +/// Time : 2019-06-22 + +#include +#include +#include +#include + +using namespace std; + + +/// Recursion +/// Time Complexity: O(n^n) +/// Space Complexity: O(n) +class Solution { +public: + vector braceExpansionII(string exp) { + + set res = braceExpansion(exp, 0, exp.size() - 1); + return vector(res.begin(), res.end()); + } + +private: + set braceExpansion(const string& exp, int l, int r) { + + if(l > r) return {}; + + if(hasComma(exp, l, r)){ + + set res; + int stack = 0; + for(int start = l, i = l; i <= r + 1; i ++) + if(i == r + 1 || (exp[i] == ',' && !stack)){ + res = add(res, braceExpansion(exp, start, i - 1)); + start = i + 1; + i = start - 1; + } + else if(exp[i] == '{') stack ++; + else if(exp[i] == '}') stack --; + return res; + } + + if(exp[l] == '{'){ + int next = get_next(exp, l); + set a = braceExpansion(exp, l + 1, next - 1); + if(next == r) return a; + else if(exp[next + 1] == ',') + return add(a, braceExpansion(exp, next + 2, r)); + else + return mul(a, braceExpansion(exp, next + 1, r)); + } + + string e = ""; + while(l <= r && isalpha(exp[l])) + e += exp[l ++]; + + set a = {e}; + l --; + + if(l == r) return a; + + if(exp[l + 1] == '{'){ + + int next = get_next(exp, l + 1); + set res = mul(a, braceExpansion(exp, l + 1, next)); + + if(next == r) return res; + else if(exp[next + 1] == ',') + return add(res, braceExpansion(exp, next + 2, r)); + else + return mul(res, braceExpansion(exp, next + 1, r)); + } + else{ + assert(exp[l + 1] == ','); + return add(a, braceExpansion(exp, l + 2, r)); + } + + assert(false); + return {}; + } + + bool hasComma(const string& exp, int l, int r){ + + int stack = 0; + for(int i = l; i <= r; i ++) + if(exp[i] == '{') stack ++; + else if(exp[i] == '}') stack --; + else if(exp[i] == ',' && !stack) return true; + return false; + } + + set mul(const set& a, const set& b){ + set res; + for(const string& e1: a) + for(const string& e2: b) + res.insert(e1 + e2); + return res; + } + + set add(const set& a, const set& b){ + set res = a; + for(const string& e: b) + res.insert(e); + return res; + } + + int get_next(const string& exp, int start){ + + assert(exp[start] == '{'); + int stack = 1; + for(int i = start + 1; i < exp.size(); i ++) + if(exp[i] == '{') stack ++; + else if(exp[i] == '}'){ + stack --; + if(!stack) return i; + } + return exp.size(); + } +}; + + +void print_vec(const vector& vec){ + for(const string& e: vec) + cout << e << " "; + cout << endl; +} + +int main() { + + print_vec(Solution().braceExpansionII("{a,b}{c{d,e}}")); + print_vec(Solution().braceExpansionII("{{a,z},a{b,c},{ab,z}}")); + print_vec(Solution().braceExpansionII("{a,b}c{d,e}f")); + print_vec(Solution().braceExpansionII("{a{x,ia,o}w,{n,{g{u,o}},{a,{x,ia,o},w}},er}")); + // ["a","aiaw","aow","axw","er","go","gu","ia","n","o","w","x"] + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1099-Two-Sum-Less-Than-K/cpp-1099/CMakeLists.txt b/1001-1500/1099-Two-Sum-Less-Than-K/cpp-1099/CMakeLists.txt new file mode 100644 index 00000000..afa8217d --- /dev/null +++ b/1001-1500/1099-Two-Sum-Less-Than-K/cpp-1099/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1001-1500/1099-Two-Sum-Less-Than-K/cpp-1099/main.cpp b/1001-1500/1099-Two-Sum-Less-Than-K/cpp-1099/main.cpp new file mode 100644 index 00000000..7c901c95 --- /dev/null +++ b/1001-1500/1099-Two-Sum-Less-Than-K/cpp-1099/main.cpp @@ -0,0 +1,31 @@ +/// Source : https://leetcode.com/problems/two-sum-less-than-k/ +/// Author : liuyubobobo +/// Time : 2019-06-29 + +#include +#include + +using namespace std; + + +/// Two Pointers +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int twoSumLessThanK(vector& A, int K) { + + int best = -1; + for(int i = 0; i < A.size(); i ++) + for(int j = i + 1; j < A.size(); j ++) + if(A[i] + A[j] < K) + best = max(best, A[i] + A[j]); + return best; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1100-Find-K-Length-Substrings-With-No-Repeated-Characters/cpp-1100/CMakeLists.txt b/1001-1500/1100-Find-K-Length-Substrings-With-No-Repeated-Characters/cpp-1100/CMakeLists.txt new file mode 100644 index 00000000..7f3bfb51 --- /dev/null +++ b/1001-1500/1100-Find-K-Length-Substrings-With-No-Repeated-Characters/cpp-1100/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main2.cpp) \ No newline at end of file diff --git a/1001-1500/1100-Find-K-Length-Substrings-With-No-Repeated-Characters/cpp-1100/main.cpp b/1001-1500/1100-Find-K-Length-Substrings-With-No-Repeated-Characters/cpp-1100/main.cpp new file mode 100644 index 00000000..0e3e91fd --- /dev/null +++ b/1001-1500/1100-Find-K-Length-Substrings-With-No-Repeated-Characters/cpp-1100/main.cpp @@ -0,0 +1,45 @@ +/// Source : https://leetcode.com/problems/find-k-length-substrings-with-no-repeated-characters/ +/// Author : liuyubobobo +/// Time : 2019-06-29 + +#include +#include + +using namespace std; + + +/// Two Pointers +/// Time Complexity: O(26n) +/// Space Complexity: O(1) +class Solution { +public: + int numKLenSubstrNoRepeats(string S, int K) { + + if(S.size() < K) return 0; + + vector freq(26, 0); + for(int i = 0; i < K - 1; i ++) + freq[S[i] - 'a'] ++; + + int res = 0; + for(int i = K - 1; i < S.size(); i ++){ + freq[S[i] - 'a'] ++; + if(ok(freq)) res ++; + freq[S[i - (K - 1)] - 'a'] --; + } + return res; + } + +private: + bool ok(const vector& freq){ + for(int e: freq) + if(e > 1) return false; + return true; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1100-Find-K-Length-Substrings-With-No-Repeated-Characters/cpp-1100/main2.cpp b/1001-1500/1100-Find-K-Length-Substrings-With-No-Repeated-Characters/cpp-1100/main2.cpp new file mode 100644 index 00000000..f192e018 --- /dev/null +++ b/1001-1500/1100-Find-K-Length-Substrings-With-No-Repeated-Characters/cpp-1100/main2.cpp @@ -0,0 +1,51 @@ +/// Source : https://leetcode.com/problems/find-k-length-substrings-with-no-repeated-characters/ +/// Author : liuyubobobo +/// Time : 2019-07-07 + +#include +#include +#include + +using namespace std; + + +/// Two Pointers and use a unordered_set to record all repeats characters +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int numKLenSubstrNoRepeats(string S, int K) { + + if(S.size() < K) return 0; + + vector freq(26, 0); + unordered_set repeats; + for(int i = 0; i < K - 1; i ++){ + freq[S[i] - 'a'] ++; + if(freq[S[i] - 'a'] > 1) + repeats.insert(S[i]); + } + + int res = 0; + for(int i = K - 1; i < S.size(); i ++){ + freq[S[i] - 'a'] ++; + if(freq[S[i] - 'a'] > 1) repeats.insert(S[i]); + + if(!repeats.size()) res ++; + + freq[S[i - (K - 1)] - 'a'] --; + if(freq[S[i - (K - 1)] - 'a'] <= 1) + repeats.erase(S[i - (K - 1)]); + } + return res; + } +}; + + +int main() { + + cout << Solution().numKLenSubstrNoRepeats("havefunonleetcode", 5) << endl; + // 6 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1101-The-Earliest-Moment-When-Everyone-Become-Friends/cpp-1101/CMakeLists.txt b/1001-1500/1101-The-Earliest-Moment-When-Everyone-Become-Friends/cpp-1101/CMakeLists.txt new file mode 100644 index 00000000..a9faeff1 --- /dev/null +++ b/1001-1500/1101-The-Earliest-Moment-When-Everyone-Become-Friends/cpp-1101/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1001-1500/1101-The-Earliest-Moment-When-Everyone-Become-Friends/cpp-1101/main.cpp b/1001-1500/1101-The-Earliest-Moment-When-Everyone-Become-Friends/cpp-1101/main.cpp new file mode 100644 index 00000000..e4da6125 --- /dev/null +++ b/1001-1500/1101-The-Earliest-Moment-When-Everyone-Become-Friends/cpp-1101/main.cpp @@ -0,0 +1,76 @@ +/// Source : https://leetcode.com/problems/the-earliest-moment-when-everyone-become-friends/ +/// Author : liuyubobobo +/// Time : 2019-06-30 + +#include +#include + +using namespace std; + + +/// Sorting + Union Find +/// Time Complexity: O(nlogn + n * a(n)) +/// Space Complexity: O(n) +class UF{ + +private: + vector parent; + int size; + +public: + UF(int n){ + for(int i = 0 ; i < n ; i ++) + parent.push_back(i); + size = n; + } + + int find(int p){ + if( p != parent[p] ) + parent[p] = find( parent[p] ); + return parent[p]; + } + + bool isConnected(int p , int q){ + return find(p) == find(q); + } + + void unionElements(int p, int q){ + + int pRoot = find(p); + int qRoot = find(q); + + if( pRoot == qRoot ) + return; + + parent[pRoot] = qRoot; + size --; + } + + int sz(){ + return size; + } +}; + +class Solution { +public: + int earliestAcq(vector>& logs, int N) { + + sort(logs.begin(), logs.end(), + [](const vector& log1, const vector& log2){ + return log1[0] < log2[0]; + }); + + UF uf(N); + for(const vector& log: logs){ + uf.unionElements(log[1], log[2]); + if(uf.sz() == 1) return log[0]; + } + return -1; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1102-Path-With-Maximum-Minimum-Value/cpp-1102/CMakeLists.txt b/1001-1500/1102-Path-With-Maximum-Minimum-Value/cpp-1102/CMakeLists.txt new file mode 100644 index 00000000..89658265 --- /dev/null +++ b/1001-1500/1102-Path-With-Maximum-Minimum-Value/cpp-1102/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) \ No newline at end of file diff --git a/1001-1500/1102-Path-With-Maximum-Minimum-Value/cpp-1102/main.cpp b/1001-1500/1102-Path-With-Maximum-Minimum-Value/cpp-1102/main.cpp new file mode 100644 index 00000000..95c4b18a --- /dev/null +++ b/1001-1500/1102-Path-With-Maximum-Minimum-Value/cpp-1102/main.cpp @@ -0,0 +1,73 @@ +/// Source : https://leetcode.com/problems/path-with-maximum-minimum-value/ +/// Author : liuyubobobo +/// Time : 2019-06-30 + +#include +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(log(max(A)) * m * n) +/// Space Complexity: O(1) +class Solution { + +private: + int m, n; + +public: + int maximumMinimumPath(vector>& A) { + + m = A.size(), n = A[0].size(); + + int min_value = A[0][0], max_value = A[0][0]; + for(int i = 0; i < m; i ++) + for(int j = 0; j < n; j ++) + min_value = min(min_value, A[i][j]), + max_value = max(max_value, A[i][j]); + + int l = min_value, r = max_value; + while(l < r){ + int mid = l + (r - l + 1) / 2; + if(ok(A, mid)) l = mid; + else r = mid - 1; + } + return l; + } + +private: + bool ok(const vector>& A, int K){ + + if(A[0][0] < K || A[m - 1][n - 1] < K) return false; + + const int d[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; + queue q; + q.push(0); + + vector visited(m * n, false); + visited[0] = true; + + while(!q.empty()){ + int cx = q.front() / n, cy = q.front() % n; + q.pop(); + + for(int i = 0; i < 4; i ++){ + int nx = cx + d[i][0], ny = cy + d[i][1]; + int index = nx * n + ny; + if(nx >= 0 && nx < m && ny >= 0 && ny < n && A[nx][ny] >= K && !visited[index]){ + visited[index] = true; + q.push(index); + } + } + } + return visited.back(); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1103-Distribute-Candies-to-People/cpp-1103/CMakeLists.txt b/1001-1500/1103-Distribute-Candies-to-People/cpp-1103/CMakeLists.txt new file mode 100644 index 00000000..b1976006 --- /dev/null +++ b/1001-1500/1103-Distribute-Candies-to-People/cpp-1103/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main2.cpp) \ No newline at end of file diff --git a/1001-1500/1103-Distribute-Candies-to-People/cpp-1103/main.cpp b/1001-1500/1103-Distribute-Candies-to-People/cpp-1103/main.cpp new file mode 100644 index 00000000..95b59190 --- /dev/null +++ b/1001-1500/1103-Distribute-Candies-to-People/cpp-1103/main.cpp @@ -0,0 +1,32 @@ +/// Source : https://leetcode.com/problems/distribute-candies-to-people/ +/// Author : liuyubobobo +/// Time : 2019-06-29 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(sqrt(candies)) +/// Space Complexity: O(1) +class Solution { +public: + vector distributeCandies(int candies, int num_people) { + + vector res(num_people, 0); + for(int c = 1, i = 0; candies; c ++, i ++){ + int x = min(c, candies); + res[i % num_people] += x; + candies -= x; + } + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1103-Distribute-Candies-to-People/cpp-1103/main2.cpp b/1001-1500/1103-Distribute-Candies-to-People/cpp-1103/main2.cpp new file mode 100644 index 00000000..2c5a2f94 --- /dev/null +++ b/1001-1500/1103-Distribute-Candies-to-People/cpp-1103/main2.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/distribute-candies-to-people/ +/// Author : liuyubobobo +/// Time : 2019-07-07 + +#include +#include +#include + +using namespace std; + + +/// Mathematics +/// See here for details: https://leetcode.com/problems/distribute-candies-to-people/solution/ +/// +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + vector distributeCandies(int candies, int num_people) { + + int p = (int)(sqrt(2 * candies + 0.25) - 0.5); + int last_remaining = candies - p * (p + 1) / 2; + int rows = p / num_people, cols = p % num_people; + + vector res(num_people); + for(int i = 0; i < num_people; i ++){ + res[i] = (i + 1) * rows + rows * (rows - 1) / 2 * num_people; + if(i < cols) res[i] += (i + 1) + rows * num_people; + } + res[cols] += last_remaining; + + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1104-Path-In-Zigzag-Labelled-Binary-Tree/cpp-1104/CMakeLists.txt b/1001-1500/1104-Path-In-Zigzag-Labelled-Binary-Tree/cpp-1104/CMakeLists.txt new file mode 100644 index 00000000..3c6ea462 --- /dev/null +++ b/1001-1500/1104-Path-In-Zigzag-Labelled-Binary-Tree/cpp-1104/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1001-1500/1104-Path-In-Zigzag-Labelled-Binary-Tree/cpp-1104/main.cpp b/1001-1500/1104-Path-In-Zigzag-Labelled-Binary-Tree/cpp-1104/main.cpp new file mode 100644 index 00000000..1c74f19c --- /dev/null +++ b/1001-1500/1104-Path-In-Zigzag-Labelled-Binary-Tree/cpp-1104/main.cpp @@ -0,0 +1,55 @@ +/// Source : https://leetcode.com/problems/path-in-zigzag-labelled-binary-tree/ +/// Author : liuyubobobo +/// Time : 2019-06-30 + +#include +#include + +using namespace std; + + +/// Mathematics +/// Time Complexity: O(log(label)) +/// Space Complexity: O(log(label)) +class Solution { +public: + vector pathInZigZagTree(int label) { + + if(label == 1) return {1}; + + vector power2 = {1}; + int e = 1; + for(int i = 1; power2.back() < label; i ++) + e *= 2, power2.push_back(power2.back() + e); + + vector res = {label}; + bool rev = true; + for(int level = power2.size() - 2; res.back() != 1; level --){ + label /= 2; + if(level && rev) + res.push_back(power2[level - 1] + 1 + power2[level] - label); + else + res.push_back(label); + rev = !rev; + } + + reverse(res.begin(), res.end()); + return res; + } +}; + + +void print_vec(const vector& vec){ + for(int e: vec) cout << e << " "; cout << endl; +} + +int main() { + + print_vec(Solution().pathInZigZagTree(14)); + // 1 3 4 14 + + print_vec(Solution().pathInZigZagTree(26)); + // 1 2 6 10 26 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1105-Filling-Bookcase-Shelves/cpp-1105/CMakeLists.txt b/1001-1500/1105-Filling-Bookcase-Shelves/cpp-1105/CMakeLists.txt new file mode 100644 index 00000000..70268b97 --- /dev/null +++ b/1001-1500/1105-Filling-Bookcase-Shelves/cpp-1105/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main2.cpp) \ No newline at end of file diff --git a/1001-1500/1105-Filling-Bookcase-Shelves/cpp-1105/main.cpp b/1001-1500/1105-Filling-Bookcase-Shelves/cpp-1105/main.cpp new file mode 100644 index 00000000..66d1ba16 --- /dev/null +++ b/1001-1500/1105-Filling-Bookcase-Shelves/cpp-1105/main.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/filling-bookcase-shelves/ +/// Author : liuyubobobo +/// Time : 2019-06-30 + +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { + +private: + int n; + +public: + int minHeightShelves(vector>& books, int shelf_width) { + + n = books.size(); + vector dp(n, -1); + return dfs(books, 0, shelf_width, dp); + } + +private: + int dfs(const vector>& books, int index, int shelf_width, + vector& dp){ + + if(index >= n) return 0; + if(dp[index] != -1) return dp[index]; + + int res = INT_MAX, cur_height = 1; + for(int i = index, total_thick = 0; + i < n && total_thick + books[i][0] <= shelf_width; i ++){ + total_thick += books[i][0]; + cur_height = max(cur_height, books[i][1]); + res = min(res, cur_height + dfs(books, i + 1, shelf_width, dp)); + } + return dp[index] = res; + } +}; + + +int main() { + + vector> books = {{1,1},{2,3},{2,3},{1,1},{1,1},{1,1},{1,2}}; + cout << Solution().minHeightShelves(books, 4) << endl; + // 6 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1105-Filling-Bookcase-Shelves/cpp-1105/main2.cpp b/1001-1500/1105-Filling-Bookcase-Shelves/cpp-1105/main2.cpp new file mode 100644 index 00000000..fe895996 --- /dev/null +++ b/1001-1500/1105-Filling-Bookcase-Shelves/cpp-1105/main2.cpp @@ -0,0 +1,41 @@ +/// Source : https://leetcode.com/problems/filling-bookcase-shelves/ +/// Author : liuyubobobo +/// Time : 2019-07-07 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { + +public: + int minHeightShelves(vector>& books, int shelf_width) { + + int n = books.size(); + vector dp(n + 1, INT_MAX); + dp[0] = 0; + for(int i = 0; i < n; i ++){ + for(int j = i, total_thick = 0, cur_height = 0; j >= 0 && total_thick + books[j][0] <= shelf_width; j --){ + total_thick += books[j][0]; + cur_height = max(cur_height, books[j][1]); + dp[i + 1] = min(dp[i + 1], cur_height + dp[j]); + } + } + return dp.back(); + } +}; + + +int main() { + + vector> books = {{1,1},{2,3},{2,3},{1,1},{1,1},{1,1},{1,2}}; + cout << Solution().minHeightShelves(books, 4) << endl; + // 6 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1106-Parsing-A-Boolean-Expression/cpp-1106/CMakeLists.txt b/1001-1500/1106-Parsing-A-Boolean-Expression/cpp-1106/CMakeLists.txt new file mode 100644 index 00000000..89658265 --- /dev/null +++ b/1001-1500/1106-Parsing-A-Boolean-Expression/cpp-1106/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) \ No newline at end of file diff --git a/1001-1500/1106-Parsing-A-Boolean-Expression/cpp-1106/main.cpp b/1001-1500/1106-Parsing-A-Boolean-Expression/cpp-1106/main.cpp new file mode 100644 index 00000000..b7eac6f3 --- /dev/null +++ b/1001-1500/1106-Parsing-A-Boolean-Expression/cpp-1106/main.cpp @@ -0,0 +1,86 @@ +/// Source : https://leetcode.com/problems/parsing-a-boolean-expression/ +/// Author : liuyubobobo +/// Time : 2019-06-30 + +#include +#include +#include + +using namespace std; + + +/// Recursion +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { +public: + bool parseBoolExpr(string exp) { + + return parse(exp, 0, exp.size() - 1); + } + +private: + bool parse(const string& exp, int l, int r){ + + if(l == r) return exp[l] == 't' ? true : false; + + if(exp[l] == '!') return !parse(exp, l + 2, r - 1); + + vector comma = get_comma(exp, l + 2, r - 1); + + if(comma.size() == 0) return parse(exp, l + 2, r - 1); + + vector subs = {parse(exp, l + 2, comma[0] - 1)}; + for(int i = 0; i < comma.size(); i ++) + subs.push_back(parse(exp, comma[i] + 1, i + 1 == comma.size() ? r - 1 : comma[i + 1] - 1)); + + bool res = subs[0]; + if(exp[l] == '&') + for(int i = 1; i < subs.size(); i ++) res = res && subs[i]; + else + for(int i = 1; i < subs.size(); i ++) res = res || subs[i]; + return res; + } + + vector get_comma(const string& exp, int l, int r){ + + vector res; + int stack = 0; + for(int i = l; i <= r; i ++) + if(exp[i] == '(') stack ++; + else if(exp[i] == ')') stack --; + else if(exp[i] == ',' && !stack) res.push_back(i); + return res; + } +}; + + +void print_bool(bool res){ + cout << (res ? "True" : "False") << endl; +} + +int main() { + + string exp1 = "!(f)"; + print_bool(Solution().parseBoolExpr(exp1)); + // true + + string exp2 = "|(f,t)"; + print_bool(Solution().parseBoolExpr(exp2)); + // true + + string exp3 = "&(t,f)"; + print_bool(Solution().parseBoolExpr(exp3)); + // false + + string exp4 = "|(&(t,f,t),!(t))"; + print_bool(Solution().parseBoolExpr(exp4)); + // false + + string exp5 = "!(&(!(t),&(f),|(f)))"; + print_bool(Solution().parseBoolExpr(exp5)); + // true + + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1108-Defanging-an-IP-Address/cpp-1108/CMakeLists.txt b/1001-1500/1108-Defanging-an-IP-Address/cpp-1108/CMakeLists.txt new file mode 100644 index 00000000..afa8217d --- /dev/null +++ b/1001-1500/1108-Defanging-an-IP-Address/cpp-1108/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1001-1500/1108-Defanging-an-IP-Address/cpp-1108/main.cpp b/1001-1500/1108-Defanging-an-IP-Address/cpp-1108/main.cpp new file mode 100644 index 00000000..f0cc82c9 --- /dev/null +++ b/1001-1500/1108-Defanging-an-IP-Address/cpp-1108/main.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/defanging-an-ip-address/ +/// Author : liuyubobobo +/// Time : 2019-07-06 + +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + string defangIPaddr(string address) { + + string res = ""; + for(int start = 0, i = start + 1; i <= address.size(); i ++) + if(i == address.size() || address[i] == '.'){ + res += address.substr(start, i - start); + if(i != address.size()) res += "[.]"; + start = i + 1; + i = start; + } + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1109-Corporate-Flight-Bookings/cpp-1109/CMakeLists.txt b/1001-1500/1109-Corporate-Flight-Bookings/cpp-1109/CMakeLists.txt new file mode 100644 index 00000000..3c6ea462 --- /dev/null +++ b/1001-1500/1109-Corporate-Flight-Bookings/cpp-1109/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1001-1500/1109-Corporate-Flight-Bookings/cpp-1109/main.cpp b/1001-1500/1109-Corporate-Flight-Bookings/cpp-1109/main.cpp new file mode 100644 index 00000000..45b8edc2 --- /dev/null +++ b/1001-1500/1109-Corporate-Flight-Bookings/cpp-1109/main.cpp @@ -0,0 +1,36 @@ +/// Source : https://leetcode.com/problems/corporate-flight-bookings/ +/// Author : liuyubobobo +/// Time : 2019-07-06 + +#include +#include + +using namespace std; + + +/// Dealing with Interview +/// Start and Ending events +/// Time Complexity: O(|bookings| + n) +/// Space Complexity: O(1) +class Solution { +public: + vector corpFlightBookings(vector>& bookings, int n) { + + vector res(n + 1, 0); + for(const vector& booking: bookings){ + res[booking[0] - 1] += booking[2]; + res[booking[1]] -= booking[2]; + } + + for(int i = 1; i <= n; i ++) + res[i] += res[i - 1]; + res.pop_back(); + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1110-Delete-Nodes-And-Return-Forest/cpp-1110/CMakeLists.txt b/1001-1500/1110-Delete-Nodes-And-Return-Forest/cpp-1110/CMakeLists.txt new file mode 100644 index 00000000..70268b97 --- /dev/null +++ b/1001-1500/1110-Delete-Nodes-And-Return-Forest/cpp-1110/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main2.cpp) \ No newline at end of file diff --git a/1001-1500/1110-Delete-Nodes-And-Return-Forest/cpp-1110/main.cpp b/1001-1500/1110-Delete-Nodes-And-Return-Forest/cpp-1110/main.cpp new file mode 100644 index 00000000..131d2f75 --- /dev/null +++ b/1001-1500/1110-Delete-Nodes-And-Return-Forest/cpp-1110/main.cpp @@ -0,0 +1,88 @@ +/// Source : https://leetcode.com/problems/delete-nodes-and-return-forest/ +/// Author : liuyubobobo +/// Time : 2019-07-06 + +#include +#include + +using namespace std; + + +/// Simulations +/// Time Complexity: O(|to_delete| * n) +/// Space Complexity: O(h) + +/// 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: + vector delNodes(TreeNode* root, vector& to_delete) { + + vector res = {root}; + for(int e: to_delete) + res = delNodes(res, e); + return res; + } + +private: + vector delNodes(vector v, int to_delete){ + + vector ret; + bool ok = false; + for(TreeNode* root: v) + if(ok || !delNode(root, NULL, -1, root, to_delete, ret)) + ret.push_back(root); + else + ok = true; + + return ret; + } + + bool delNode(TreeNode* root, TreeNode* parent, int index, TreeNode* node, int to_delete, + vector& ret){ + + if(!node) return false; + if(node->val == to_delete){ + if(node == root){ + if(node->left) ret.push_back(node->left); + if(node->right) ret.push_back(node->right); + } + else{ + if(index == 0) parent->left = NULL; + else parent->right = NULL; + + ret.push_back(root); + if(node->left) ret.push_back(node->left); + if(node->right) ret.push_back(node->right); + } + return true; + } + + if(delNode(root, node, 0, node->left, to_delete, ret)) + return true; + return delNode(root, node, 1, node->right, to_delete, ret); + } +}; + + +int main() { + + TreeNode* root = new TreeNode(1); + root->left = new TreeNode(2); + root->right = new TreeNode(3); + root->left->left = new TreeNode(4); + root->left->right = new TreeNode(5); + root->right->left = new TreeNode(6); + root->right->right = new TreeNode(7); + + vector to_delete = {3, 5}; + Solution().delNodes(root, to_delete); + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1110-Delete-Nodes-And-Return-Forest/cpp-1110/main2.cpp b/1001-1500/1110-Delete-Nodes-And-Return-Forest/cpp-1110/main2.cpp new file mode 100644 index 00000000..d592b78d --- /dev/null +++ b/1001-1500/1110-Delete-Nodes-And-Return-Forest/cpp-1110/main2.cpp @@ -0,0 +1,63 @@ +/// Source : https://leetcode.com/problems/delete-nodes-and-return-forest/ +/// Author : liuyubobobo +/// Time : 2019-07-07 + +#include +#include +#include + +using namespace std; + + +/// Recursion +/// Time Complexity: O(n) +/// Space Complexity: O(h) + +/// 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: + vector delNodes(TreeNode* root, vector& to_delete) { + + unordered_set remove_set(to_delete.begin(), to_delete.end()); + vector res; + remove(root, true, remove_set, res); + return res; + } + +private: + TreeNode* remove(TreeNode* node, bool is_root, + const unordered_set& remove_set, vector& res){ + + if(!node) return NULL; + + bool deleted = remove_set.count(node->val); + if(is_root && !deleted) res.push_back(node); + node->left = remove(node->left, deleted, remove_set, res); + node->right = remove(node->right, deleted, remove_set, res); + return deleted ? NULL : node; + } +}; + + +int main() { + + TreeNode* root = new TreeNode(1); + root->left = new TreeNode(2); + root->right = new TreeNode(3); + root->left->left = new TreeNode(4); + root->left->right = new TreeNode(5); + root->right->left = new TreeNode(6); + root->right->right = new TreeNode(7); + + vector to_delete = {3, 5}; + Solution().delNodes(root, to_delete); + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1111-Maximum-Nesting-Depth-of-Two-Valid-Parentheses-Strings/cpp-1111/CMakeLists.txt b/1001-1500/1111-Maximum-Nesting-Depth-of-Two-Valid-Parentheses-Strings/cpp-1111/CMakeLists.txt new file mode 100644 index 00000000..bee29d53 --- /dev/null +++ b/1001-1500/1111-Maximum-Nesting-Depth-of-Two-Valid-Parentheses-Strings/cpp-1111/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main2.cpp) \ No newline at end of file diff --git a/1001-1500/1111-Maximum-Nesting-Depth-of-Two-Valid-Parentheses-Strings/cpp-1111/main.cpp b/1001-1500/1111-Maximum-Nesting-Depth-of-Two-Valid-Parentheses-Strings/cpp-1111/main.cpp new file mode 100644 index 00000000..6282d848 --- /dev/null +++ b/1001-1500/1111-Maximum-Nesting-Depth-of-Two-Valid-Parentheses-Strings/cpp-1111/main.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/maximum-nesting-depth-of-two-valid-parentheses-strings/ +/// Author : liuyubobobo +/// Time : 2019-07-06 + +#include +#include +#include + +using namespace std; + + +/// Halve max depth +/// Time Complexity: O(2n) +/// Space Complexity: O(1) +class Solution { +public: + vector maxDepthAfterSplit(string s) { + + int bound = get_depth(s) / 2; + + vector res(s.size(), 0); + int stack = 0; + for(int i = 0; i < s.size(); i ++){ + if(s[i] == '(') stack ++, res[i] = (stack > bound); + else res[i] = (stack > bound), stack --; + + } + return res; + } + +private: + int get_depth(const string& s){ + + int res = 0, stack = 0; + for(char c: s) + if(c == '(') stack ++, res = max(res, stack); + else stack --; + assert(!stack); + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1111-Maximum-Nesting-Depth-of-Two-Valid-Parentheses-Strings/cpp-1111/main2.cpp b/1001-1500/1111-Maximum-Nesting-Depth-of-Two-Valid-Parentheses-Strings/cpp-1111/main2.cpp new file mode 100644 index 00000000..51d3afe1 --- /dev/null +++ b/1001-1500/1111-Maximum-Nesting-Depth-of-Two-Valid-Parentheses-Strings/cpp-1111/main2.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/maximum-nesting-depth-of-two-valid-parentheses-strings/ +/// Author : liuyubobobo +/// Time : 2019-07-07 + +#include +#include +#include + +using namespace std; + + +/// Alternatively Assign 0 and 1 +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + vector maxDepthAfterSplit(string s) { + + vector res(s.size(), 0); + + int stack = 0; + for(int i = 0; i < s.size(); i ++) + if(s[i] == '(') stack ++, res[i] = stack % 2; + else res[i] = stack % 2, stack --; + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1118-Number-of-Days-in-a-Month/cpp-1118/CMakeLists.txt b/1001-1500/1118-Number-of-Days-in-a-Month/cpp-1118/CMakeLists.txt new file mode 100644 index 00000000..afa8217d --- /dev/null +++ b/1001-1500/1118-Number-of-Days-in-a-Month/cpp-1118/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1001-1500/1118-Number-of-Days-in-a-Month/cpp-1118/main.cpp b/1001-1500/1118-Number-of-Days-in-a-Month/cpp-1118/main.cpp new file mode 100644 index 00000000..720cdee1 --- /dev/null +++ b/1001-1500/1118-Number-of-Days-in-a-Month/cpp-1118/main.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/number-of-days-in-a-month/ +/// Author : liuyubobobo +/// Time : 2019-07-13 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(1) +/// Space Complexity: O(1) +class Solution { +public: + int numberOfDays(int Y, int M) { + + unordered_set thirtyone = {1, 3, 5, 7, 8, 10, 12}; + if(thirtyone.count(M)) return 31; + if(M == 2) return isLeapYear(Y) ? 29 : 28; + return 30; + } + +private: + bool isLeapYear(int Y){ + return (!(Y % 4) && (Y % 100)) || !(Y % 400); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1119-Remove-Vowels-from-a-String/cpp-1119/CMakeLists.txt b/1001-1500/1119-Remove-Vowels-from-a-String/cpp-1119/CMakeLists.txt new file mode 100644 index 00000000..3c6ea462 --- /dev/null +++ b/1001-1500/1119-Remove-Vowels-from-a-String/cpp-1119/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1001-1500/1119-Remove-Vowels-from-a-String/cpp-1119/main.cpp b/1001-1500/1119-Remove-Vowels-from-a-String/cpp-1119/main.cpp new file mode 100644 index 00000000..53d47545 --- /dev/null +++ b/1001-1500/1119-Remove-Vowels-from-a-String/cpp-1119/main.cpp @@ -0,0 +1,31 @@ +/// Source : https://leetcode.com/problems/remove-vowels-from-a-string/ +/// Author : liuyubobobo +/// Time : 2019-07-13 + +#include +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + string removeVowels(string S) { + + unordered_set vowels = {'a', 'e', 'i', 'o', 'u'}; + string res = ""; + for(char c: S) + if(!vowels.count(c)) + res += c; + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1120-Maximum-Average-Subtree/cpp-1120/CMakeLists.txt b/1001-1500/1120-Maximum-Average-Subtree/cpp-1120/CMakeLists.txt new file mode 100644 index 00000000..a9faeff1 --- /dev/null +++ b/1001-1500/1120-Maximum-Average-Subtree/cpp-1120/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1001-1500/1120-Maximum-Average-Subtree/cpp-1120/main.cpp b/1001-1500/1120-Maximum-Average-Subtree/cpp-1120/main.cpp new file mode 100644 index 00000000..b610c81d --- /dev/null +++ b/1001-1500/1120-Maximum-Average-Subtree/cpp-1120/main.cpp @@ -0,0 +1,70 @@ +/// Source : https://leetcode.com/problems/maximum-average-subtree/ +/// Author : liuyubobobo +/// Time : 2019-07-13 + +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// 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 { + +private: + unordered_map sum; + unordered_map sz; + +public: + double maximumAverageSubtree(TreeNode* root) { + + dfsSum(root); + dfsSz(root); + return dfsRes(root); + } + +private: + int dfsSum(TreeNode* node){ + + if(!node) return 0; + int left = dfsSum(node->left); + int right = dfsSum(node->right); + sum[node] = left + right + node->val; + return sum[node]; + } + + int dfsSz(TreeNode* node){ + + if(!node) return 0; + int left = dfsSz(node->left); + int right = dfsSz(node->right); + sz[node] = left + right + 1; + return sz[node]; + } + + double dfsRes(TreeNode* node){ + + if(!node) return 0; + double left = dfsRes(node->left); + double right = dfsRes(node->right); + return max(max(left, right), (double)sum[node] / sz[node]); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1121-Divide-Array-Into-Increasing-Sequences/cpp-1121/CMakeLists.txt b/1001-1500/1121-Divide-Array-Into-Increasing-Sequences/cpp-1121/CMakeLists.txt new file mode 100644 index 00000000..bee29d53 --- /dev/null +++ b/1001-1500/1121-Divide-Array-Into-Increasing-Sequences/cpp-1121/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main2.cpp) \ No newline at end of file diff --git a/1001-1500/1121-Divide-Array-Into-Increasing-Sequences/cpp-1121/main.cpp b/1001-1500/1121-Divide-Array-Into-Increasing-Sequences/cpp-1121/main.cpp new file mode 100644 index 00000000..94ed3a28 --- /dev/null +++ b/1001-1500/1121-Divide-Array-Into-Increasing-Sequences/cpp-1121/main.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/divide-array-into-increasing-sequences/ +/// Author : liuyubobobo +/// Time : 2019-07-13 + +#include +#include +#include + +using namespace std; + + +/// Using HashMap to calculate freq +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + bool canDivideIntoSubsequences(vector& nums, int K) { + + unordered_map freq; + int count = 0; + for(int e: nums){ + freq[e] ++; + count = max(count, freq[e]); + } + + return nums.size() / count >= K; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1121-Divide-Array-Into-Increasing-Sequences/cpp-1121/main2.cpp b/1001-1500/1121-Divide-Array-Into-Increasing-Sequences/cpp-1121/main2.cpp new file mode 100644 index 00000000..f9243e20 --- /dev/null +++ b/1001-1500/1121-Divide-Array-Into-Increasing-Sequences/cpp-1121/main2.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/divide-array-into-increasing-sequences/ +/// Author : liuyubobobo +/// Time : 2019-07-13 + +#include +#include + +using namespace std; + + +/// Split +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + bool canDivideIntoSubsequences(vector& nums, int K) { + + int count = 0; + for(int start = 0, i = start + 1; i <= nums.size(); i ++) + if(i == nums.size() || nums[i] != nums[start]){ + count = max(count, i - start); + start = i; + i = start; + } + + return nums.size() >= K * count; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1124-Longest-Well-Performing-Interval/cpp-1124/CMakeLists.txt b/1001-1500/1124-Longest-Well-Performing-Interval/cpp-1124/CMakeLists.txt new file mode 100644 index 00000000..fd2e1e0c --- /dev/null +++ b/1001-1500/1124-Longest-Well-Performing-Interval/cpp-1124/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main3.cpp) \ No newline at end of file diff --git a/1001-1500/1124-Longest-Well-Performing-Interval/cpp-1124/main.cpp b/1001-1500/1124-Longest-Well-Performing-Interval/cpp-1124/main.cpp new file mode 100644 index 00000000..52c10eea --- /dev/null +++ b/1001-1500/1124-Longest-Well-Performing-Interval/cpp-1124/main.cpp @@ -0,0 +1,39 @@ +/// Source : https://leetcode.com/problems/longest-well-performing-interval/ +/// Author : liuyubobobo +/// Time : 2019-07-13 + +#include +#include + +using namespace std; + + +/// Presum + Brute Force +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { +public: + int longestWPI(vector& hours) { + + for(int& e: hours) + e = (e > 8 ? 1 : 0); + + int n = hours.size(); + vector presum(n + 1, 0); + for(int i = 1; i <= n; i ++) + presum[i] = presum[i - 1] + hours[i - 1]; + + int best = 0; + for(int end = 0; end < n; end ++) + for(int start = 0; start <= end && end - start + 1 > best; start ++) + if((presum[end + 1] - presum[start]) * 2 > end - start + 1) + best = max(best, end - start + 1); + return best; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1124-Longest-Well-Performing-Interval/cpp-1124/main2.cpp b/1001-1500/1124-Longest-Well-Performing-Interval/cpp-1124/main2.cpp new file mode 100644 index 00000000..275fba3d --- /dev/null +++ b/1001-1500/1124-Longest-Well-Performing-Interval/cpp-1124/main2.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/longest-well-performing-interval/ +/// Author : liuyubobobo +/// Time : 2019-07-15 + +#include +#include + +using namespace std; + + +/// Presum + Binary Search +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int longestWPI(vector& hours) { + + for(int& e: hours) + e = (e > 8 ? 1 : -1); + + int n = hours.size(); + vector presum(n + 1, 0); + for(int i = 1; i <= n; i ++) + presum[i] = presum[i - 1] + hours[i - 1]; + + int l = 0, r = n; + while(l < r){ + int mid = (l + r + 1) / 2; + if(ok(presum, mid)) + l = mid; + else + r = mid - 1; + } + return l; + } + +private: + bool ok(const vector& presum, int len){ + + int minv = INT_MAX; + for(int i = 0; i + len < presum.size(); i ++){ + minv = min(minv, presum[i]); + if(presum[i + len] - minv > 0) + return true; + } + return false; + } +}; + + +int main() { + + vector hours = {9,9,6,0,6,6,9}; + cout << Solution().longestWPI(hours) << endl; + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1124-Longest-Well-Performing-Interval/cpp-1124/main3.cpp b/1001-1500/1124-Longest-Well-Performing-Interval/cpp-1124/main3.cpp new file mode 100644 index 00000000..78331388 --- /dev/null +++ b/1001-1500/1124-Longest-Well-Performing-Interval/cpp-1124/main3.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/longest-well-performing-interval/ +/// Author : liuyubobobo +/// Time : 2019-07-15 + +#include +#include +#include + +using namespace std; + + +/// Presum + Hash Map +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int longestWPI(vector& hours) { + + for(int& e: hours) + e = (e > 8 ? 1 : -1); + + int n = hours.size(); + vector presum(n + 1, 0); + for(int i = 1; i <= n; i ++) + presum[i] = presum[i - 1] + hours[i - 1]; + + unordered_map pos; + int res = 0; + for(int i = 1; i <= n; i ++) + if(presum[i] > 0) res = max(res, i); + else{ + if(!pos.count(presum[i])) pos[presum[i]] = i; + if(pos.count(presum[i] - 1)) res = max(res, i - pos[presum[i] - 1]); + } + return res; + } +}; + + +int main() { + + vector hours = {9,9,6,0,6,6,9}; + cout << Solution().longestWPI(hours) << endl; + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1128-Number-of-Equivalent-Domino-Pairs/cpp-1128/CMakeLists.txt b/1001-1500/1128-Number-of-Equivalent-Domino-Pairs/cpp-1128/CMakeLists.txt new file mode 100644 index 00000000..b1976006 --- /dev/null +++ b/1001-1500/1128-Number-of-Equivalent-Domino-Pairs/cpp-1128/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main2.cpp) \ No newline at end of file diff --git a/1001-1500/1128-Number-of-Equivalent-Domino-Pairs/cpp-1128/main.cpp b/1001-1500/1128-Number-of-Equivalent-Domino-Pairs/cpp-1128/main.cpp new file mode 100644 index 00000000..acf425db --- /dev/null +++ b/1001-1500/1128-Number-of-Equivalent-Domino-Pairs/cpp-1128/main.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/number-of-equivalent-domino-pairs/ +/// Author : liuyubobobo +/// Time : 2019-07-20 + +#include +#include +#include + +using namespace std; + + +/// Using Hash Map +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int numEquivDominoPairs(vector>& dominoes) { + + unordered_map freq; + for(const vector& d: dominoes) + freq[min(d[0], d[1]) * 10 + max(d[0], d[1])] ++; + + int res = 0; + for(const pair& p: freq) + res += p.second * (p.second - 1) / 2; + return res; + } +}; + + +int main() { + + vector> v = {{1,2},{1,2},{1,1},{1,2},{2,2}}; + cout << Solution().numEquivDominoPairs(v) << endl; + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1128-Number-of-Equivalent-Domino-Pairs/cpp-1128/main2.cpp b/1001-1500/1128-Number-of-Equivalent-Domino-Pairs/cpp-1128/main2.cpp new file mode 100644 index 00000000..828115e5 --- /dev/null +++ b/1001-1500/1128-Number-of-Equivalent-Domino-Pairs/cpp-1128/main2.cpp @@ -0,0 +1,43 @@ +/// Source : https://leetcode.com/problems/number-of-equivalent-domino-pairs/ +/// Author : liuyubobobo +/// Time : 2019-07-27 + +#include +#include +#include + +using namespace std; + + +/// Sorting and split +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + int numEquivDominoPairs(vector>& dominoes) { + + vector v; + for(const vector& d: dominoes) + v.push_back(min(d[0], d[1]) * 10 + max(d[0], d[1])); + + sort(v.begin(), v.end()); + int res = 0; + for(int start = 0, i = 1; i <= v.size(); i ++) + if(i == v.size() || v[i] != v[start]){ + int f = i - start; + res += f * (f - 1) / 2; + start = i; + i = start; + } + return res; + } +}; + + +int main() { + + vector> v = {{1,2},{1,2},{1,1},{1,2},{2,2}}; + cout << Solution().numEquivDominoPairs(v) << endl; + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1129-Shortest-Path-with-Alternating-Colors/cpp-1129/CMakeLists.txt b/1001-1500/1129-Shortest-Path-with-Alternating-Colors/cpp-1129/CMakeLists.txt new file mode 100644 index 00000000..3c6ea462 --- /dev/null +++ b/1001-1500/1129-Shortest-Path-with-Alternating-Colors/cpp-1129/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1001-1500/1129-Shortest-Path-with-Alternating-Colors/cpp-1129/main.cpp b/1001-1500/1129-Shortest-Path-with-Alternating-Colors/cpp-1129/main.cpp new file mode 100644 index 00000000..205320a1 --- /dev/null +++ b/1001-1500/1129-Shortest-Path-with-Alternating-Colors/cpp-1129/main.cpp @@ -0,0 +1,90 @@ +/// Source : https://leetcode.com/problems/shortest-path-with-alternating-colors/ +/// Author : liuyubobobo +/// Time : 2019-07-20 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// BFS +/// Time Complexity: O(V + E) +/// Space Complexity: O(V + E) +class Solution { +public: + vector shortestAlternatingPaths(int n, vector>& red_edges, vector>& blue_edges) { + + vector>> g(n); + for(vector& edge: red_edges) + g[edge[0]][edge[1]].insert(1); + for(vector& edge: blue_edges) + g[edge[0]][edge[1]].insert(2); + + queue> q; + unordered_set visited; + vector res(n, -1); + + res[0] = 0; + for(const pair>& p: g[0]) + if(p.first) + for(int color: p.second){ + res[p.first] = 1; + q.push(make_pair(p.first * 10 + color, 1)); + visited.insert(p.first * 10 + color); + } + + while(!q.empty()){ + int cur = q.front().first / 10; + int color = q.front().first % 10; + int step = q.front().second; + q.pop(); + + for(const pair>& p: g[cur]){ + for(int newcolor: p.second){ + int hash = p.first * 10 + newcolor; + if(!visited.count(hash) && newcolor != color){ + q.push(make_pair(hash, step + 1)); + if(res[p.first] == -1) + res[p.first] = step + 1; + visited.insert(hash); + } + } + } + } + return res; + } +}; + + +void print_vec(const vector& vec){ + for(int e: vec) cout << e << " "; cout << endl; +} + +int main() { + + vector > red_edges1 = {{0, 1}, {0, 2}}; + vector > blue_edges1 = {{1, 0}}; + print_vec(Solution().shortestAlternatingPaths(3, red_edges1, blue_edges1)); + // 0 1 1 + + vector > red_edges2 = {{0, 1}}; + vector > blue_edges2 = {{1, 2}}; + print_vec(Solution().shortestAlternatingPaths(3, red_edges2, blue_edges2)); + // 0 1 2 + + vector > red_edges3 = {{0, 1}, {1, 2}, {2, 3}, {3, 4}}; + vector > blue_edges3 = {{1, 2}, {2, 3}, {3, 1}}; + print_vec(Solution().shortestAlternatingPaths(5, red_edges3, blue_edges3)); + // 0 1 2 3 7 + + vector > red_edges4 = {{2, 2}, {0, 1}, {0, 3}, {0, 0}, {0, 4}, {2, 1}, {2, 0}, {1, 4}, {3, 4}}; + vector > blue_edges4 = {{1, 3}, {0, 0}, {0, 3}, {4, 2}, {1, 0}}; + print_vec(Solution().shortestAlternatingPaths(5, red_edges4, blue_edges4)); + // 0 1 2 1 1 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1130-Minimum-Cost-Tree-From-Leaf-Values/cpp-1130/CMakeLists.txt b/1001-1500/1130-Minimum-Cost-Tree-From-Leaf-Values/cpp-1130/CMakeLists.txt new file mode 100644 index 00000000..b170a313 --- /dev/null +++ b/1001-1500/1130-Minimum-Cost-Tree-From-Leaf-Values/cpp-1130/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main4.cpp) \ No newline at end of file diff --git a/1001-1500/1130-Minimum-Cost-Tree-From-Leaf-Values/cpp-1130/main.cpp b/1001-1500/1130-Minimum-Cost-Tree-From-Leaf-Values/cpp-1130/main.cpp new file mode 100644 index 00000000..58802a70 --- /dev/null +++ b/1001-1500/1130-Minimum-Cost-Tree-From-Leaf-Values/cpp-1130/main.cpp @@ -0,0 +1,60 @@ +/// Source : https://leetcode.com/problems/minimum-cost-tree-from-leaf-values/ +/// Author : liuyubobobo +/// Time : 2019-07-20 + +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(n^3) +/// Space Complexity: O(n^2) +class Solution { + +private: + int n; + +public: + int mctFromLeafValues(vector& arr) { + + n = arr.size(); + vector> maxv(n,vector(n)); + for(int i = 0; i < n; i ++) maxv[i][i] = arr[i]; + for(int d = 1; d < n; d ++) + for(int i = 0; i + d < n; i ++) + maxv[i][i + d] = max(maxv[i][i + d - 1], maxv[i + 1][i + d]); + + vector> dp(n, vector(n, -1)); + return search(arr, 0, n - 1, maxv, dp); + } + + int search(const vector& arr, int l, int r, + vector>& maxv, vector>& dp){ + + if(l == r) + return 0; + + if(dp[l][r] != -1) return dp[l][r]; + + int res = INT_MAX; + for(int mid = l; mid < r; mid ++){ + int lres = search(arr, l, mid, maxv, dp); + int rres = search(arr, mid + 1, r, maxv, dp); + res = min(res, lres + rres + maxv[l][mid] * maxv[mid + 1][r]); + } + + return dp[l][r] = res; + } +}; + + +int main() { + + vector vec = {6, 2, 4}; + cout << Solution().mctFromLeafValues(vec) << endl; + // 32 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1130-Minimum-Cost-Tree-From-Leaf-Values/cpp-1130/main2.cpp b/1001-1500/1130-Minimum-Cost-Tree-From-Leaf-Values/cpp-1130/main2.cpp new file mode 100644 index 00000000..26ac6372 --- /dev/null +++ b/1001-1500/1130-Minimum-Cost-Tree-From-Leaf-Values/cpp-1130/main2.cpp @@ -0,0 +1,48 @@ +/// Source : https://leetcode.com/problems/minimum-cost-tree-from-leaf-values/ +/// Author : liuyubobobo +/// Time : 2019-08-22 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(n^3) +/// Space Complexity: O(n^2) +class Solution { + +public: + int mctFromLeafValues(vector& arr) { + + int n = arr.size(); + vector> maxv(n,vector(n)); + for(int i = 0; i < n; i ++) maxv[i][i] = arr[i]; + for(int d = 1; d < n; d ++) + for(int i = 0; i + d < n; i ++) + maxv[i][i + d] = max(maxv[i][i + d - 1], maxv[i + 1][i + d]); + + vector> dp(n, vector(n, INT_MAX)); + for(int i = 0; i < n; i ++) dp[i][i] = 0; + for(int d = 1; d < n; d ++) + for(int i = 0; i + d < n; i ++) + for(int mid = i; mid < i + d; mid ++) + dp[i][i + d] = min(dp[i][i + d], dp[i][mid] + dp[mid + 1][i + d] + maxv[i][mid] * maxv[mid + 1][i + d]); + return dp[0][n - 1]; + } +}; + + +int main() { + + vector vec1 = {6, 2, 4}; + cout << Solution().mctFromLeafValues(vec1) << endl; + // 32 + + vector vec2 = {7, 12, 8, 10}; + cout << Solution().mctFromLeafValues(vec2) << endl; + // 284 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1130-Minimum-Cost-Tree-From-Leaf-Values/cpp-1130/main3.cpp b/1001-1500/1130-Minimum-Cost-Tree-From-Leaf-Values/cpp-1130/main3.cpp new file mode 100644 index 00000000..e87cb74f --- /dev/null +++ b/1001-1500/1130-Minimum-Cost-Tree-From-Leaf-Values/cpp-1130/main3.cpp @@ -0,0 +1,71 @@ +/// Source : https://leetcode.com/problems/minimum-cost-tree-from-leaf-values/ +/// Author : liuyubobobo +/// Time : 2019-08-22 + +#include +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +public: + int mctFromLeafValues(vector& arr) { + + int n = arr.size(); + if(n == 1) return 0; + + stack stack; + stack.push(0); + int res = 0; + for(int i = 1; i < n; i ++){ + while(!stack.empty() && arr[stack.top()] < arr[i]){ + int cur = stack.top(); + stack.pop(); + if(stack.empty()) + res += arr[cur] * arr[i]; + else + res += arr[cur] * min(arr[stack.top()], arr[i]); + } + stack.push(i); + } + + while(stack.size() >= 2){ + int x = arr[stack.top()]; + stack.pop(); + res += x * arr[stack.top()]; + } + return res; + } +}; + + +int main() { + + vector vec1 = {6, 2, 4}; + cout << Solution().mctFromLeafValues(vec1) << endl; + // 32 + + vector vec2 = {7, 12, 8, 10}; + cout << Solution().mctFromLeafValues(vec2) << endl; + // 284 + + vector vec3 = {6, 15, 5, 2}; + cout << Solution().mctFromLeafValues(vec3) << endl; + // 175 + + vector vec4 = {15, 13, 5, 3, 15}; + cout << Solution().mctFromLeafValues(vec4) << endl; + // 500 + + vector vec5 = {6, 9, 6, 15, 15}; + cout << Solution().mctFromLeafValues(vec5) << endl; + // 468 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1130-Minimum-Cost-Tree-From-Leaf-Values/cpp-1130/main4.cpp b/1001-1500/1130-Minimum-Cost-Tree-From-Leaf-Values/cpp-1130/main4.cpp new file mode 100644 index 00000000..80944d2c --- /dev/null +++ b/1001-1500/1130-Minimum-Cost-Tree-From-Leaf-Values/cpp-1130/main4.cpp @@ -0,0 +1,64 @@ +/// Source : https://leetcode.com/problems/minimum-cost-tree-from-leaf-values/ +/// Author : liuyubobobo +/// Time : 2019-08-22 + +#include +#include +#include + +using namespace std; + + +/// Greedy +/// Using sentel to make the logic more concise +/// +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +public: + int mctFromLeafValues(vector& arr) { + + arr.insert(arr.begin(), INT_MAX); + arr.push_back(INT_MAX); + + stack stack; + int res = 0; + for(int i = 0; i < arr.size(); i ++){ + while(!stack.empty() && arr[stack.top()] < arr[i]){ + int cur = stack.top(); + stack.pop(); + int minv = min(arr[stack.top()], arr[i]); + if(minv != INT_MAX) res += arr[cur] * minv; + } + stack.push(i); + } + return res; + } +}; + + +int main() { + + vector vec1 = {6, 2, 4}; + cout << Solution().mctFromLeafValues(vec1) << endl; + // 32 + + vector vec2 = {7, 12, 8, 10}; + cout << Solution().mctFromLeafValues(vec2) << endl; + // 284 + + vector vec3 = {6, 15, 5, 2}; + cout << Solution().mctFromLeafValues(vec3) << endl; + // 175 + + vector vec4 = {15, 13, 5, 3, 15}; + cout << Solution().mctFromLeafValues(vec4) << endl; + // 500 + + vector vec5 = {6, 9, 6, 15, 15}; + cout << Solution().mctFromLeafValues(vec5) << endl; + // 468 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1131-Maximum-of-Absolute-Value-Expression/cpp-1131/CMakeLists.txt b/1001-1500/1131-Maximum-of-Absolute-Value-Expression/cpp-1131/CMakeLists.txt new file mode 100644 index 00000000..b14b41a5 --- /dev/null +++ b/1001-1500/1131-Maximum-of-Absolute-Value-Expression/cpp-1131/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(cpp_1131) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1131 main.cpp) \ No newline at end of file diff --git a/1001-1500/1131-Maximum-of-Absolute-Value-Expression/cpp-1131/main.cpp b/1001-1500/1131-Maximum-of-Absolute-Value-Expression/cpp-1131/main.cpp new file mode 100644 index 00000000..060970b9 --- /dev/null +++ b/1001-1500/1131-Maximum-of-Absolute-Value-Expression/cpp-1131/main.cpp @@ -0,0 +1,42 @@ +/// Source : https://leetcode.com/problems/maximum-of-absolute-value-expression/ +/// Author : liuyubobobo +/// Time : 2019-08-25 + +#include +#include + +using namespace std; + + +/// Mathematics +/// |a - b| = max(a - b, b - a) +/// Time Compelxity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int maxAbsValExpr(vector& arr1, vector& arr2) { + + int n = arr1.size(), res = INT_MIN; + for(int a = -1; a <= 1; a += 2) + for(int b = -1; b <= 1; b += 2) + for(int c = -1; c <= 1; c += 2){ + + int maxv = INT_MIN, minv = INT_MAX; + for(int i = 0; i < n; i ++){ + int x = a * arr1[i] + b * arr2[i] + c * i; + maxv = max(maxv, x); + minv = min(minv, x); + } + res = max(res, maxv - minv); + } + return res; + } +}; + + +int main() { + + vector arr1 = {1, 2, 3, 4}, arr2 = {-1, 4, 5, 6}; + cout << Solution().maxAbsValExpr(arr1, arr2) << endl; + return 0; +} \ No newline at end of file diff --git a/1001-1500/1133-Largest-Unique-Number/cpp-1133/CMakeLists.txt b/1001-1500/1133-Largest-Unique-Number/cpp-1133/CMakeLists.txt new file mode 100644 index 00000000..b1976006 --- /dev/null +++ b/1001-1500/1133-Largest-Unique-Number/cpp-1133/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main2.cpp) \ No newline at end of file diff --git a/1001-1500/1133-Largest-Unique-Number/cpp-1133/main.cpp b/1001-1500/1133-Largest-Unique-Number/cpp-1133/main.cpp new file mode 100644 index 00000000..7d7b784f --- /dev/null +++ b/1001-1500/1133-Largest-Unique-Number/cpp-1133/main.cpp @@ -0,0 +1,32 @@ +/// Source : https://leetcode.com/problems/largest-unique-number/ +/// Author : liuyubobobo +/// Time : 2019-07-25 + +#include +#include +#include + +using namespace std; + + +/// Using HashMap +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int largestUniqueNumber(vector& A) { + + unordered_map freq; + for(int a: A) freq[a] ++; + + int res = -1; + for(const pair& p: freq) + if(p.second == 1) res = max(res, p.first); + return res; + } +}; + + +int main() { + return 0; +} \ No newline at end of file diff --git a/1001-1500/1133-Largest-Unique-Number/cpp-1133/main2.cpp b/1001-1500/1133-Largest-Unique-Number/cpp-1133/main2.cpp new file mode 100644 index 00000000..19476e9a --- /dev/null +++ b/1001-1500/1133-Largest-Unique-Number/cpp-1133/main2.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/largest-unique-number/ +/// Author : liuyubobobo +/// Time : 2019-07-25 + +#include +#include + +using namespace std; + + +/// Sorting and Split +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + int largestUniqueNumber(vector& A) { + + sort(A.begin(), A.end()); + int res = -1; + for(int start = 0, i = 1; i <= A.size(); i ++) + if(i == A.size() || A[i] != A[start]){ + if(i - start == 1) res = A[start]; + start = i; + i = start; + } + return res; + } +}; + + +int main() { + return 0; +} \ No newline at end of file diff --git a/1001-1500/1134-Armstrong-Number/cpp-1134/CMakeLists.txt b/1001-1500/1134-Armstrong-Number/cpp-1134/CMakeLists.txt new file mode 100644 index 00000000..3c6ea462 --- /dev/null +++ b/1001-1500/1134-Armstrong-Number/cpp-1134/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1001-1500/1134-Armstrong-Number/cpp-1134/main.cpp b/1001-1500/1134-Armstrong-Number/cpp-1134/main.cpp new file mode 100644 index 00000000..4eaa1428 --- /dev/null +++ b/1001-1500/1134-Armstrong-Number/cpp-1134/main.cpp @@ -0,0 +1,36 @@ +/// Source : https://leetcode.com/problems/armstrong-number/ +/// Author : liuyubobobo +/// Time : 2019-07-25 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(logN) +/// Space Complexity: O(logN) +class Solution { +public: + bool isArmstrong(int N) { + + int o = N; + + int k = to_string(N).size(); + int sum = 0; + while(N){ + int d = N % 10; + N /= 10; + sum += pow(d, k); + cout << sum << endl; + } + return o == sum; + } +}; + + +int main() { + cout << Solution().isArmstrong(153) << endl; + return 0; +} \ No newline at end of file diff --git a/1001-1500/1135-Connecting-Cities-With-Minimum-Cost/cpp-1135/CMakeLists.txt b/1001-1500/1135-Connecting-Cities-With-Minimum-Cost/cpp-1135/CMakeLists.txt new file mode 100644 index 00000000..70268b97 --- /dev/null +++ b/1001-1500/1135-Connecting-Cities-With-Minimum-Cost/cpp-1135/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main2.cpp) \ No newline at end of file diff --git a/1001-1500/1135-Connecting-Cities-With-Minimum-Cost/cpp-1135/main.cpp b/1001-1500/1135-Connecting-Cities-With-Minimum-Cost/cpp-1135/main.cpp new file mode 100644 index 00000000..0c18089a --- /dev/null +++ b/1001-1500/1135-Connecting-Cities-With-Minimum-Cost/cpp-1135/main.cpp @@ -0,0 +1,90 @@ +/// Source : https://leetcode.com/problems/connecting-cities-with-minimum-cost/ +/// Author : liuyubobobo +/// Time : 2019-07-25 + +#include +#include +#include + +using namespace std; + + +/// Kruskal +/// Time Complexity: O(ElogE) +/// Space Complexity: O(V) +class UF{ + +private: + vector parent; + int sz; + +public: + UF(int n){ + for(int i = 0 ; i < n ; i ++) + parent.push_back(i); + sz = n; + } + + int find(int p){ + if( p != parent[p] ) + parent[p] = find( parent[p] ); + return parent[p]; + } + + bool isConnected(int p , int q){ + return find(p) == find(q); + } + + void unionElements(int p, int q){ + + int pRoot = find(p); + int qRoot = find(q); + + if( pRoot == qRoot ) + return; + + parent[pRoot] = qRoot; + sz --; + } + + int size(){ + return sz; + } +}; + +class Solution { +public: + int minimumCost(int N, vector>& connections) { + + vector> g(N); + for(vector& c: connections){ + g[--c[0]].count(--c[1]); + if(!g[c[0]].count(c[1]) || c[2] < g[c[0]][c[1]]){ + g[c[0]][c[1]] = c[2]; + g[c[1]][c[0]] = c[2]; + } + } + + sort(connections.begin(), connections.end(), + [](const vector& e1, const vector& e2){ + return e1[2] < e2[2]; + }); + + int res = 0; + UF uf(N); + for(const vector& e: connections) + if(!uf.isConnected(e[0], e[1])){ + uf.unionElements(e[0], e[1]); + res += e[2]; + } + return uf.size() == 1 ? res : -1; + } +}; + + +int main() { + + vector> edges1 = {{1, 2, 5}, {1, 3, 6}, {2, 3, 1}}; + cout << Solution().minimumCost(3, edges1) << endl; + return 0; +} \ No newline at end of file diff --git a/1001-1500/1135-Connecting-Cities-With-Minimum-Cost/cpp-1135/main2.cpp b/1001-1500/1135-Connecting-Cities-With-Minimum-Cost/cpp-1135/main2.cpp new file mode 100644 index 00000000..2908b97c --- /dev/null +++ b/1001-1500/1135-Connecting-Cities-With-Minimum-Cost/cpp-1135/main2.cpp @@ -0,0 +1,58 @@ +/// Source : https://leetcode.com/problems/connecting-cities-with-minimum-cost/ +/// Author : liuyubobobo +/// Time : 2019-07-25 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// Prim +/// Time Complexity: O(ElogE) +/// Space Complexity: O(V) +class Solution { +public: + int minimumCost(int N, vector>& connections) { + + vector> g(N); + for(vector& c: connections){ + g[--c[0]].count(--c[1]); + if(!g[c[0]].count(c[1]) || c[2] < g[c[0]][c[1]]){ + g[c[0]][c[1]] = c[2]; + g[c[1]][c[0]] = c[2]; + } + } + + vector visited(N, false); + priority_queue, vector>, greater>> pq; + for(const pair& p: g[0]) + pq.push(make_pair(p.second, p.first)); + visited[0] = true; + int res = 0; + while(!pq.empty()){ + int v = pq.top().second; + int weight = pq.top().first; + pq.pop(); + if(!visited[v]){ + res += weight; + visited[v] = true; + for(const pair& p: g[v]) + if(!visited[p.first]) + pq.push(make_pair(p.second, p.first)); + } + } + return accumulate(visited.begin(), visited.end(), 0) == N ? res : -1; + } +}; + + +int main() { + + vector> edges1 = {{1, 2, 5}, {1, 3, 6}, {2, 3, 1}}; + cout << Solution().minimumCost(3, edges1) << endl; + return 0; +} \ No newline at end of file diff --git a/1001-1500/1136-Parallel-Courses/cpp-1136/CMakeLists.txt b/1001-1500/1136-Parallel-Courses/cpp-1136/CMakeLists.txt new file mode 100644 index 00000000..89658265 --- /dev/null +++ b/1001-1500/1136-Parallel-Courses/cpp-1136/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) \ No newline at end of file diff --git a/1001-1500/1136-Parallel-Courses/cpp-1136/main.cpp b/1001-1500/1136-Parallel-Courses/cpp-1136/main.cpp new file mode 100644 index 00000000..ef021fd7 --- /dev/null +++ b/1001-1500/1136-Parallel-Courses/cpp-1136/main.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/parallel-courses/ +/// Author : liuyubobobo +/// Time : 2019-07-25 + +#include +#include + +using namespace std; + + +/// Topological Sort +/// Time Complexity: O(E) +/// Space Complexity: O(V) +class Solution { +public: + int minimumSemesters(int N, vector>& relations) { + + vector> g(N); + vector degrees(N, 0); + for(vector& e: relations) + g[--e[0]].push_back(--e[1]), degrees[e[1]] ++; + + int num = 0, res = 0; + vector q; + for(int i = 0; i < N; i ++) + if(degrees[i] == 0) q.push_back(i), num ++; + while(!q.empty()){ + vector next; + for(int v: q) + for(int w: g[v]){ + degrees[w] --; + if(!degrees[w]) + next.push_back(w), num ++; + } + res ++; + q = next; + } + return num == N ? res : -1; + } +}; + + +int main() { + vector> relations1 = {{1,3},{2,3}}; + cout << Solution().minimumSemesters(3, relations1) << endl; + return 0; +} \ No newline at end of file diff --git a/1001-1500/1137-N-th-Tribonacci-Number/cpp-1137/CMakeLists.txt b/1001-1500/1137-N-th-Tribonacci-Number/cpp-1137/CMakeLists.txt new file mode 100644 index 00000000..b1976006 --- /dev/null +++ b/1001-1500/1137-N-th-Tribonacci-Number/cpp-1137/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main2.cpp) \ No newline at end of file diff --git a/1001-1500/1137-N-th-Tribonacci-Number/cpp-1137/main.cpp b/1001-1500/1137-N-th-Tribonacci-Number/cpp-1137/main.cpp new file mode 100644 index 00000000..9e7bcdfd --- /dev/null +++ b/1001-1500/1137-N-th-Tribonacci-Number/cpp-1137/main.cpp @@ -0,0 +1,32 @@ +/// Source : https://leetcode.com/problems/alphabet-board-path/ +/// Author : liuyubobobo +/// Time : 2019-07-27 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int tribonacci(int n) { + + if(n == 0) return 0; + if(n == 1 | n == 2) return 1; + vector dp(n + 1, 0); + dp[1] = dp[2] = 1; + for(int i = 3; i <= n; i ++) + dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3]; + return dp[n]; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1137-N-th-Tribonacci-Number/cpp-1137/main2.cpp b/1001-1500/1137-N-th-Tribonacci-Number/cpp-1137/main2.cpp new file mode 100644 index 00000000..9cb00060 --- /dev/null +++ b/1001-1500/1137-N-th-Tribonacci-Number/cpp-1137/main2.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/alphabet-board-path/ +/// Author : liuyubobobo +/// Time : 2019-07-30 + +#include +#include + +using namespace std; + + +/// Dynamic Programming Space Optimized +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int tribonacci(int n) { + + if(n == 0) return 0; + if(n == 1 | n == 2) return 1; + + int a = 0, b = 1, c = 1; + for(int i = 3; i <= n; i ++){ + int d = a + b + c; + a = b, b = c, c = d; + } + return c; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1138-Alphabet-Board-Path/cpp-1138/CMakeLists.txt b/1001-1500/1138-Alphabet-Board-Path/cpp-1138/CMakeLists.txt new file mode 100644 index 00000000..7f3bfb51 --- /dev/null +++ b/1001-1500/1138-Alphabet-Board-Path/cpp-1138/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main2.cpp) \ No newline at end of file diff --git a/1001-1500/1138-Alphabet-Board-Path/cpp-1138/main.cpp b/1001-1500/1138-Alphabet-Board-Path/cpp-1138/main.cpp new file mode 100644 index 00000000..218901f5 --- /dev/null +++ b/1001-1500/1138-Alphabet-Board-Path/cpp-1138/main.cpp @@ -0,0 +1,107 @@ +/// Source : https://leetcode.com/problems/two-sum/description/ +/// Author : liuyubobobo +/// Time : 2019-07-27 + +#include +#include +#include +#include + +using namespace std; + + +/// BFS +/// Time Complexity: O(len(target) * 26) +/// Space Complexity: O(26 * 26) +class Path{ +private: + const int dirs[4][2] = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}}; + vector board = {"abcde", "fghij", "klmno", "pqrst", "uvwxy", "z"}; + vector pre; + int start; + +public: + Path(char c){ + start = c - 'a'; + for(int i = 0; i < 26; i ++) pre.push_back(-1); + + vector visited(26, false); + queue q; + q.push(start); + visited[start] = true; + pre[start] = start; + while(!q.empty()){ + int cur = q.front(); + q.pop(); + + int x = cur / 5, y = cur % 5; + for(int d = 0; d < 4; d ++){ + int nextx = x + dirs[d][0], nexty = y + dirs[d][1]; + int next = nextx * 5 + nexty; + if(inArea(nextx, nexty) && !visited[next]){ + q.push(next); + visited[next] = true; + pre[next] = cur; + } + } + } +// cout << start << " : "; for(int e: pre) cout << e << " "; cout << endl; + } + + string path(char target){ + + string res = ""; + int cur = target - 'a'; + while(cur != start){ + res += get_dir(pre[cur], cur); + cur = pre[cur]; + } + reverse(res.begin(), res.end()); + return res; + } + +private: + bool inArea(int x, int y){ + if(x <= 4) return x >= 0 && x <= 4 && y >= 0 && y < 5; + return x == 5 && y == 0; + } + + char get_dir(int s, int t){ + int sx = s / 5, sy = s % 5; + int tx = t / 5, ty = t % 5; + string res = "URDL"; + for(int i = 0; i < 4; i ++) + if(sx + dirs[i][0] == tx && sy + dirs[i][1] == ty) + return res[i]; + assert(false); + return ' '; + } +}; + +class Solution { +public: + string alphabetBoardPath(string target) { + + vector paths; + for(int i = 0; i < 26; i ++) + paths.push_back(Path('a' + i)); + + target = "a" + target; + string res = ""; + for(int i = 1; i < target.size(); i ++) + res += paths[target[i - 1] - 'a'].path(target[i]) + "!"; + return res; + } +}; + + +int main() { + + cout << Solution().alphabetBoardPath("leet") << endl; + // DDR!UURRR!!DDD! + + cout << Solution().alphabetBoardPath("code") << endl; + // DDR!UURRR!!DDD! + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1138-Alphabet-Board-Path/cpp-1138/main2.cpp b/1001-1500/1138-Alphabet-Board-Path/cpp-1138/main2.cpp new file mode 100644 index 00000000..427372cc --- /dev/null +++ b/1001-1500/1138-Alphabet-Board-Path/cpp-1138/main2.cpp @@ -0,0 +1,56 @@ +/// Source : https://leetcode.com/problems/two-sum/description/ +/// Author : liuyubobobo +/// Time : 2019-07-30 + +#include +#include +#include +#include + +using namespace std; + + +/// Calculate the differant coordinates +/// Time Complexity: O(len(target) * 10) +/// Space Complexity: O(1) +class Solution { +public: + string alphabetBoardPath(string target) { + + target = "a" + target; + string res = ""; + for(int i = 1; i < target.size(); i ++) + res += get_path(target[i - 1], target[i]) + "!"; + return res; + } + +private: + string get_path(const char a, const char b){ + + int x1 = (a - 'a') / 5, y1 = (a - 'a') % 5; + int x2 = (b - 'a') / 5, y2 = (b - 'a') % 5; + + string res = ""; + if(x1 > x2) res += string(x1 - x2, 'U'); + if(y1 > y2) res += string(y1 - y2, 'L'); + if(y1 < y2) res += string(y2 - y1, 'R'); + if(x1 < x2) res += string(x2 - x1, 'D'); + + return res; + } +}; + + +int main() { + + cout << Solution().alphabetBoardPath("leet") << endl; + // DDR!UURRR!!DDD! + + cout << Solution().alphabetBoardPath("code") << endl; + // DDR!UURRR!!DDD! + + cout << Solution().alphabetBoardPath("zdz") << endl; + // "DDDDD!UUUUURRR!DDDDLLLD!" + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1139-Largest-1-Bordered-Square/cpp-1139/CMakeLists.txt b/1001-1500/1139-Largest-1-Bordered-Square/cpp-1139/CMakeLists.txt new file mode 100644 index 00000000..a9faeff1 --- /dev/null +++ b/1001-1500/1139-Largest-1-Bordered-Square/cpp-1139/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1001-1500/1139-Largest-1-Bordered-Square/cpp-1139/main.cpp b/1001-1500/1139-Largest-1-Bordered-Square/cpp-1139/main.cpp new file mode 100644 index 00000000..a7a2775c --- /dev/null +++ b/1001-1500/1139-Largest-1-Bordered-Square/cpp-1139/main.cpp @@ -0,0 +1,66 @@ +/// Source : https://leetcode.com/problems/largest-1-bordered-square/ +/// Author : liuyubobobo +/// Time : 2019-07-27 + +#include +#include + +using namespace std; + + +/// Presum +/// Time Complexity: O(n^3) +/// Space Complexity: O(n^2) +class Solution { +public: + int largest1BorderedSquare(vector>& grid) { + + int r = grid.size(), c = grid[0].size(); + + vector> row(r, vector(c + 1, 0)); + for(int i = 0; i < r; i ++) + for(int j = 0; j < c; j ++) + row[i][j + 1] = row[i][j] + grid[i][j]; +// for(int i = 0; i < r; i ++) { +// for (int j = 0; j <= c; j++) +// cout << row[i][j] << " "; +// cout << endl; +// } +// cout << endl; + + vector> col(r + 1, vector(c, 0)); + for(int j = 0; j < c; j ++) + for(int i = 0; i < r; i ++) + col[i + 1][j] = col[i][j] + grid[i][j]; +// for(int i = 0; i <= r; i ++) { +// for (int j = 0; j < c; j++) +// cout << col[i][j] << " "; +// cout << endl; +// } + + int res = 0; + for(int sx = 0; sx < r; sx ++) + for(int sy = 0; sy < c; sy ++) + for(int sz = 1; sx + sz <= r && sy + sz <= c; sz ++) + if(row[sx][sy + sz] - row[sx][sy] == sz && + row[sx + sz - 1][sy + sz] - row[sx + sz - 1][sy] == sz && + col[sx + sz][sy] - col[sx][sy] == sz && + col[sx + sz][sy + sz - 1] - col[sx][sy + sz - 1] == sz) + res = max(res, sz * sz); + return res; + } +}; + + +int main() { + + vector> grid1 = {{1,1,1},{1,0,1},{1,1,1}}; + cout << Solution().largest1BorderedSquare(grid1) << endl; + // 9 + + vector> grid2 = {{1,1,0,0}}; + cout << Solution().largest1BorderedSquare(grid2) << endl; + // 1 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1140-Stone-Game-II/cpp-1140/CMakeLists.txt b/1001-1500/1140-Stone-Game-II/cpp-1140/CMakeLists.txt new file mode 100644 index 00000000..89658265 --- /dev/null +++ b/1001-1500/1140-Stone-Game-II/cpp-1140/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) \ No newline at end of file diff --git a/1001-1500/1140-Stone-Game-II/cpp-1140/main.cpp b/1001-1500/1140-Stone-Game-II/cpp-1140/main.cpp new file mode 100644 index 00000000..6efac51d --- /dev/null +++ b/1001-1500/1140-Stone-Game-II/cpp-1140/main.cpp @@ -0,0 +1,49 @@ +/// Source : https://leetcode.com/problems/stone-game-ii/ +/// Author : liuyubobobo +/// Time : 2019-07-27 + +#include +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { +private: + int n; + vector sum; + +public: + int stoneGameII(vector& piles) { + + n = piles.size(); + sum.push_back(0); + for(int e: piles) sum.push_back(sum.back() + e); + + vector> dp(n + 1, vector(n + 1, -1)); + return dfs(1, 0, dp); + } + + int dfs(int M, int end, vector>& dp){ + + if(end == n) return 0; + if(dp[M][end] != -1) return dp[M][end]; + + int res = 0; + for(int i = end; i < min(end + 2 * M, n); i ++) + res = max(res, sum[n] - sum[end] - dfs(max(i - end + 1, M), i + 1, dp)); + return dp[M][end] = res; + } +}; + + +int main() { + vector piles = {2, 7, 9, 4, 4}; + cout << Solution().stoneGameII(piles) << endl; + // 10 + return 0; +} \ No newline at end of file diff --git a/1001-1500/1143-Longest-Common-Subsequence/cpp-1143/CMakeLists.txt b/1001-1500/1143-Longest-Common-Subsequence/cpp-1143/CMakeLists.txt new file mode 100644 index 00000000..3474bc11 --- /dev/null +++ b/1001-1500/1143-Longest-Common-Subsequence/cpp-1143/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(cpp_1143) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1143 main3.cpp) \ No newline at end of file diff --git a/1001-1500/1143-Longest-Common-Subsequence/cpp-1143/main.cpp b/1001-1500/1143-Longest-Common-Subsequence/cpp-1143/main.cpp new file mode 100644 index 00000000..92ee2527 --- /dev/null +++ b/1001-1500/1143-Longest-Common-Subsequence/cpp-1143/main.cpp @@ -0,0 +1,43 @@ +/// Source : https://leetcode.com/problems/longest-common-subsequence/ +/// Author : liuyubobobo +/// Time : 2019-08-22 + +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(n * m) +/// Space Complexity: O(n * m) +class Solution { + +private: + int n, m; + +public: + int longestCommonSubsequence(string s1, string s2) { + + n = s1.size(), m = s2.size(); + vector> dp(n, vector(m, -1)); + return dfs(s1, 0, s2, 0, dp); + } + +private: + int dfs(const string& s1, int i, const string& s2, int j, + vector>& dp){ + + if(i >= n || j >= m) return 0; + if(dp[i][j] != -1) return dp[i][j]; + int res = max(dfs(s1, i + 1, s2, j, dp), dfs(s1, i, s2, j + 1, dp)); + if(s1[i] == s2[j]) res = max(res, 1 + dfs(s1, i + 1, s2, j + 1, dp)); + return dp[i][j] = res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1143-Longest-Common-Subsequence/cpp-1143/main2.cpp b/1001-1500/1143-Longest-Common-Subsequence/cpp-1143/main2.cpp new file mode 100644 index 00000000..224f3e1a --- /dev/null +++ b/1001-1500/1143-Longest-Common-Subsequence/cpp-1143/main2.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/longest-common-subsequence/ +/// Author : liuyubobobo +/// Time : 2019-08-22 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(n * m) +/// Space Complexity: O(n * m) +class Solution { + +public: + int longestCommonSubsequence(string s1, string s2) { + + int n = s1.size(), m = s2.size(); + vector> dp(n + 1, vector(m + 1, 0)); + for(int i = 0; i < n; i ++) + for(int j = 0; j < m; j ++){ + dp[i + 1][j + 1] = max(dp[i][j + 1], dp[i + 1][j]); + if(s1[i] == s2[j]) dp[i + 1][j + 1] = max(dp[i + 1][j + 1], 1 + dp[i][j]); + } + return dp[n][m]; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1143-Longest-Common-Subsequence/cpp-1143/main3.cpp b/1001-1500/1143-Longest-Common-Subsequence/cpp-1143/main3.cpp new file mode 100644 index 00000000..f62de9f1 --- /dev/null +++ b/1001-1500/1143-Longest-Common-Subsequence/cpp-1143/main3.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/longest-common-subsequence/ +/// Author : liuyubobobo +/// Time : 2019-08-22 + +#include +#include + +using namespace std; + + +/// Dynamic Programming with Space Optimization +/// Time Complexity: O(n * m) +/// Space Complexity: O(m) +class Solution { + +public: + int longestCommonSubsequence(string s1, string s2) { + + int n = s1.size(), m = s2.size(); + vector> dp(2, vector(m + 1, 0)); + for(int i = 0; i < n; i ++) + for(int j = 0; j < m; j ++){ + dp[(i + 1) % 2][j + 1] = max(dp[i % 2][j + 1], dp[(i + 1) % 2][j]); + if(s1[i] == s2[j]) dp[(i + 1) % 2][j + 1] = max(dp[(i + 1) % 2][j + 1], 1 + dp[i % 2][j]); + } + return dp[n % 2][m]; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1144-Decrease-Elements-To-Make-Array-Zigzag/cpp-1144/CMakeLists.txt b/1001-1500/1144-Decrease-Elements-To-Make-Array-Zigzag/cpp-1144/CMakeLists.txt new file mode 100644 index 00000000..afa8217d --- /dev/null +++ b/1001-1500/1144-Decrease-Elements-To-Make-Array-Zigzag/cpp-1144/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1001-1500/1144-Decrease-Elements-To-Make-Array-Zigzag/cpp-1144/main.cpp b/1001-1500/1144-Decrease-Elements-To-Make-Array-Zigzag/cpp-1144/main.cpp new file mode 100644 index 00000000..608747cc --- /dev/null +++ b/1001-1500/1144-Decrease-Elements-To-Make-Array-Zigzag/cpp-1144/main.cpp @@ -0,0 +1,51 @@ +/// Source : https://leetcode.com/problems/decrease-elements-to-make-array-zigzag/ +/// Author : liuyubobobo +/// Time : 2019-08-03 + +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int movesToMakeZigzag(vector& nums) { + + int res1 = 0; + for(int i = 1; i < nums.size(); i += 2){ + int x = nums[i - 1]; + if(i + 1 < nums.size()) x = min(x, nums[i + 1]); + x --; + res1 += max(nums[i] - x, 0); + } + + int res2 = 0; + for(int i = 0; i < nums.size(); i += 2){ + int x = INT_MAX; + if(i - 1 >= 0) x = min(x, nums[i - 1]); + if(i + 1 < nums.size()) x = min(x, nums[i + 1]); + x --; + res2 += max(nums[i] - x, 0); + } + + return min(res1, res2); + } +}; + + +int main() { + + vector nums1 = {1, 2, 3}; + cout << Solution().movesToMakeZigzag(nums1) << endl; + // 2 + + vector nums2 = {10, 4, 4, 10, 10, 6, 2, 3}; + cout << Solution().movesToMakeZigzag(nums2) << endl; + // 13 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1145-Binary-Tree-Coloring-Game/cpp-1145/CMakeLists.txt b/1001-1500/1145-Binary-Tree-Coloring-Game/cpp-1145/CMakeLists.txt new file mode 100644 index 00000000..7f3bfb51 --- /dev/null +++ b/1001-1500/1145-Binary-Tree-Coloring-Game/cpp-1145/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main2.cpp) \ No newline at end of file diff --git a/1001-1500/1145-Binary-Tree-Coloring-Game/cpp-1145/main.cpp b/1001-1500/1145-Binary-Tree-Coloring-Game/cpp-1145/main.cpp new file mode 100644 index 00000000..089262ce --- /dev/null +++ b/1001-1500/1145-Binary-Tree-Coloring-Game/cpp-1145/main.cpp @@ -0,0 +1,66 @@ +/// Source : https://leetcode.com/problems/binary-tree-coloring-game/ +/// Author : liuyubobobo +/// Time : 2019-08-03 + +#include +#include + +using namespace std; + + +/// Using HashSet to recoder subtree nodes' count +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// 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 { +private: + TreeNode* target = NULL; + unordered_map map; + +public: + bool btreeGameWinningMove(TreeNode* root, int n, int x) { + + dfs(root, x); + int a = map[target], b = n - a; + if(b > a) return true; + + if(target->left){ + a = n - map[target->left], b = n - a; + if(b > a) return true; + } + + if(target->right){ + a = n - map[target->right], b = n - a; + if(b > a) return true; + } + + return false; + } + +private: + int dfs(TreeNode* node, int t){ + + if(!node) return 0; + if(node->val == t) target = node; + + int res = 1; + res += dfs(node->left, t); + res += dfs(node->right, t); + map[node] = res; + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1145-Binary-Tree-Coloring-Game/cpp-1145/main2.cpp b/1001-1500/1145-Binary-Tree-Coloring-Game/cpp-1145/main2.cpp new file mode 100644 index 00000000..bb1fa9d0 --- /dev/null +++ b/1001-1500/1145-Binary-Tree-Coloring-Game/cpp-1145/main2.cpp @@ -0,0 +1,49 @@ +/// Source : https://leetcode.com/problems/binary-tree-coloring-game/ +/// Author : liuyubobobo +/// Time : 2019-08-04 + +#include +#include + +using namespace std; + + +/// Mathematics +/// Time Complexity: O(n) +/// Space Complexity: O(h) + +/// 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 { +private: + int left = 0, right = 0; + +public: + bool btreeGameWinningMove(TreeNode* root, int n, int x) { + + dfs(root, x); + return max(max(left, right), n - left - right - 1) > n / 2; + } + +private: + int dfs(TreeNode* node, int t){ + + if(!node) return 0; + int l = dfs(node->left, t), r = dfs(node->right, t); + if(node->val == t) + left = l, right = r; + return 1 + l + r; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1146-Snapshot-Array/cpp-1146/CMakeLists.txt b/1001-1500/1146-Snapshot-Array/cpp-1146/CMakeLists.txt new file mode 100644 index 00000000..a9faeff1 --- /dev/null +++ b/1001-1500/1146-Snapshot-Array/cpp-1146/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1001-1500/1146-Snapshot-Array/cpp-1146/main.cpp b/1001-1500/1146-Snapshot-Array/cpp-1146/main.cpp new file mode 100644 index 00000000..fe93e889 --- /dev/null +++ b/1001-1500/1146-Snapshot-Array/cpp-1146/main.cpp @@ -0,0 +1,70 @@ +/// Source : https://leetcode.com/problems/snapshot-array/ +/// Author : liuyubobobo +/// Time : 2019-08-03 + +#include +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Comnplexity: init: O(n) +/// set: O(1) +/// snap: O(1) +/// get: O(log(calls)) +class SnapshotArray { + +private: + vector>> data; + int id = 0; + +public: + SnapshotArray(int length) { + + data.resize(length); + for(int i = 0; i < length; i ++) + data[i].push_back(make_pair(-1, 0)); + } + + void set(int index, int val) { + data[index].push_back(make_pair(id, val)); + } + + int snap() { + return id ++; + } + + int get(int index, int snap_id) { + + if(!data[index].size()) return 0; + auto iter = lower_bound(data[index].begin(), data[index].end(), make_pair(snap_id + 1, INT_MIN)); + iter --; + return iter->second; + } +}; + + +int main() { + + SnapshotArray o1(4); + cout << o1.snap() << endl; // 0 + cout << o1.snap() << endl; // 1 + cout << o1.get(3, 1) << endl; // 0 + o1.set(2, 4); + cout << o1.snap() << endl; // 2 + o1.set(1, 4); + + SnapshotArray o2(1); + o2.set(0, 15); + cout << o2.snap() << endl; // 0 + cout << o2.snap() << endl; // 1 + cout << o2.snap() << endl; // 2 + cout << o2.get(0, 2) << endl; // 15 + cout << o2.snap() << endl; // 3 + cout << o2.snap() << endl; // 4 + cout << o2.get(0, 0) << endl; // 15 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1147-Longest-Chunked-Palindrome-Decomposition/cpp-1147/CMakeLists.txt b/1001-1500/1147-Longest-Chunked-Palindrome-Decomposition/cpp-1147/CMakeLists.txt new file mode 100644 index 00000000..9c35c994 --- /dev/null +++ b/1001-1500/1147-Longest-Chunked-Palindrome-Decomposition/cpp-1147/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main4.cpp) \ No newline at end of file diff --git a/1001-1500/1147-Longest-Chunked-Palindrome-Decomposition/cpp-1147/main.cpp b/1001-1500/1147-Longest-Chunked-Palindrome-Decomposition/cpp-1147/main.cpp new file mode 100644 index 00000000..cab982aa --- /dev/null +++ b/1001-1500/1147-Longest-Chunked-Palindrome-Decomposition/cpp-1147/main.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/longest-chunked-palindrome-decomposition/ +/// Author : liuyubobobo +/// Time : 2019-08-03 + +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(n^3) +/// Space Complexity: O(n^2) +class Solution { + +private: + string s; + +public: + int longestDecomposition(string text) { + + int n = text.size(); + vector> dp(n, vector(n, -1)); + s = text; + return go(0, n - 1, dp); + } + +private: + int go(int l, int r, vector>& dp){ + if(l > r) return 0; + if(l == r) return 1; + if(dp[l][r] != -1) return dp[l][r]; + + int len = r - l + 1; + len /= 2; + int res = 1; + for(int ll = 1; ll <= len; ll ++) + if(s.substr(l, ll) == s.substr(r - ll + 1, ll)) + res = max(res, 2 + go(l + ll, r - ll, dp)); + return dp[l][r] = res; + } +}; + + +int main() { + + cout << Solution().longestDecomposition("ghiabcdefhelloadamhelloabcdefghi") << endl; + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1147-Longest-Chunked-Palindrome-Decomposition/cpp-1147/main2.cpp b/1001-1500/1147-Longest-Chunked-Palindrome-Decomposition/cpp-1147/main2.cpp new file mode 100644 index 00000000..87bb6f15 --- /dev/null +++ b/1001-1500/1147-Longest-Chunked-Palindrome-Decomposition/cpp-1147/main2.cpp @@ -0,0 +1,56 @@ +/// Source : https://leetcode.com/problems/longest-chunked-palindrome-decomposition/ +/// Author : liuyubobobo +/// Time : 2019-08-04 + +#include +#include + +using namespace std; + + +/// Memory Search +/// Space Optimized +/// +/// Time Complexity: O(n^3) +/// Space Complexity: O(n) +class Solution { + +private: + string s; + int n; + +public: + int longestDecomposition(string text) { + + n = text.size(); + vector dp(n, -1); + s = text; + return go(0, dp); + } + +private: + int go(int l, vector& dp){ + if(n % 2){ + if(l == n / 2) return 1; + if(l > n /2 ) return 0; + } + else if(l >= n / 2) return 0; + + if(dp[l] != -1) return dp[l]; + + int res = 1; + for(int len = 1; l + len <= n / 2; len ++) + if(s.substr(l, len) == s.substr(n - l - len, len)) + res = max(res, 2 + go(l + len, dp)); + return dp[l] = res; + } +}; + + +int main() { + + cout << Solution().longestDecomposition("ghiabcdefhelloadamhelloabcdefghi") << endl; + cout << Solution().longestDecomposition("aaa") << endl; + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1147-Longest-Chunked-Palindrome-Decomposition/cpp-1147/main3.cpp b/1001-1500/1147-Longest-Chunked-Palindrome-Decomposition/cpp-1147/main3.cpp new file mode 100644 index 00000000..3d3fe5f1 --- /dev/null +++ b/1001-1500/1147-Longest-Chunked-Palindrome-Decomposition/cpp-1147/main3.cpp @@ -0,0 +1,51 @@ +/// Source : https://leetcode.com/problems/longest-chunked-palindrome-decomposition/ +/// Author : liuyubobobo +/// Time : 2019-08-04 + +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { + +private: + string s; + int n; + +public: + int longestDecomposition(string text) { + + n = text.size(); + s = text; + return go(0); + } + +private: + int go(int l){ + + if(n % 2){ + if(l == n / 2) return 1; + if(l > n /2 ) return 0; + } + else if(l >= n / 2) return 0; + + for(int len = 1; l + len <= n / 2; len ++) + if(s.substr(l, len) == s.substr(n - l - len, len)) + return 2 + go(l + len); + return 1; + } +}; + + +int main() { + + cout << Solution().longestDecomposition("ghiabcdefhelloadamhelloabcdefghi") << endl; + cout << Solution().longestDecomposition("aaa") << endl; + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1147-Longest-Chunked-Palindrome-Decomposition/cpp-1147/main4.cpp b/1001-1500/1147-Longest-Chunked-Palindrome-Decomposition/cpp-1147/main4.cpp new file mode 100644 index 00000000..2c7c2747 --- /dev/null +++ b/1001-1500/1147-Longest-Chunked-Palindrome-Decomposition/cpp-1147/main4.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/longest-chunked-palindrome-decomposition/ +/// Author : liuyubobobo +/// Time : 2019-08-04 + +#include +#include + +using namespace std; + + +/// Greedy - Iterative Implementation +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { + +public: + int longestDecomposition(string text) { + + int n = text.size(); + int l = 0, r = n - 1, res = 0; + string ls = "", rs = ""; + while(l < r){ + ls += text[l ++], rs = string(1, text[r --]) + rs; + if(ls == rs) res += 2, ls = rs = ""; + } + return res + (l == r || ls != ""); + } +}; + + +int main() { + + cout << Solution().longestDecomposition("ghiabcdefhelloadamhelloabcdefghi") << endl; + cout << Solution().longestDecomposition("aaa") << endl; + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1150-Check-If-a-Number-Is-Majority-Element-in-a-Sorted-Array/cpp-1150/CMakeLists.txt b/1001-1500/1150-Check-If-a-Number-Is-Majority-Element-in-a-Sorted-Array/cpp-1150/CMakeLists.txt new file mode 100644 index 00000000..afa8217d --- /dev/null +++ b/1001-1500/1150-Check-If-a-Number-Is-Majority-Element-in-a-Sorted-Array/cpp-1150/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1001-1500/1150-Check-If-a-Number-Is-Majority-Element-in-a-Sorted-Array/cpp-1150/main.cpp b/1001-1500/1150-Check-If-a-Number-Is-Majority-Element-in-a-Sorted-Array/cpp-1150/main.cpp new file mode 100644 index 00000000..b4d42024 --- /dev/null +++ b/1001-1500/1150-Check-If-a-Number-Is-Majority-Element-in-a-Sorted-Array/cpp-1150/main.cpp @@ -0,0 +1,28 @@ +/// Source : https://leetcode.com/problems/two-sum/description/ +/// Author : liuyubobobo +/// Time : 2019-08-10 + +#include +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + bool isMajorityElement(vector& nums, int target) { + + int f = 0; + for(int num: nums) + if(target == num) f ++; + return f > nums.size() / 2; + } +}; + + +int main() { + return 0; +} \ No newline at end of file diff --git a/1001-1500/1150-Check-If-a-Number-Is-Majority-Element-in-a-Sorted-Array/cpp-1150/main2.cpp b/1001-1500/1150-Check-If-a-Number-Is-Majority-Element-in-a-Sorted-Array/cpp-1150/main2.cpp new file mode 100644 index 00000000..ceb738db --- /dev/null +++ b/1001-1500/1150-Check-If-a-Number-Is-Majority-Element-in-a-Sorted-Array/cpp-1150/main2.cpp @@ -0,0 +1,27 @@ +/// Source : https://leetcode.com/problems/two-sum/description/ +/// Author : liuyubobobo +/// Time : 2019-08-10 + +#include +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(logn) +/// Space Complexity: O(1) +class Solution { +public: + bool isMajorityElement(vector& nums, int target) { + vector::iterator iter1 = lower_bound(nums.begin(), nums.end(), target); + vector::iterator iter2 = upper_bound(nums.begin(), nums.end(), target); + return iter2 - iter1 > nums.size() / 2; + } +}; + + +int main() { + return 0; +} \ No newline at end of file diff --git a/1001-1500/1151-Minimum-Swaps-to-Group-All-1s-Together/cpp-1151/CMakeLists.txt b/1001-1500/1151-Minimum-Swaps-to-Group-All-1s-Together/cpp-1151/CMakeLists.txt new file mode 100644 index 00000000..3c6ea462 --- /dev/null +++ b/1001-1500/1151-Minimum-Swaps-to-Group-All-1s-Together/cpp-1151/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1001-1500/1151-Minimum-Swaps-to-Group-All-1s-Together/cpp-1151/main.cpp b/1001-1500/1151-Minimum-Swaps-to-Group-All-1s-Together/cpp-1151/main.cpp new file mode 100644 index 00000000..7d9b13e1 --- /dev/null +++ b/1001-1500/1151-Minimum-Swaps-to-Group-All-1s-Together/cpp-1151/main.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/minimum-swaps-to-group-all-1s-together/ +/// Author : liuyubobobo +/// Time : 2019-08-10 + +#include +#include +#include + +using namespace std; + + +/// Presum +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int minSwaps(vector& data) { + + int n = data.size(); + int ones = accumulate(data.begin(), data.end(), 0); + + vector presum(n + 1, 0); + for(int i = 0; i < n; i ++) + presum[i + 1] = presum[i] + data[i]; + + int res = INT_MAX; + for(int i = 0; i + ones <= n; i ++) + res = min(res, ones - (presum[i + ones] - presum[i])); + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1152-Analyze-User-Website-Visit-Pattern/cpp-1152/CMakeLists.txt b/1001-1500/1152-Analyze-User-Website-Visit-Pattern/cpp-1152/CMakeLists.txt new file mode 100644 index 00000000..a9faeff1 --- /dev/null +++ b/1001-1500/1152-Analyze-User-Website-Visit-Pattern/cpp-1152/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1001-1500/1152-Analyze-User-Website-Visit-Pattern/cpp-1152/main.cpp b/1001-1500/1152-Analyze-User-Website-Visit-Pattern/cpp-1152/main.cpp new file mode 100644 index 00000000..6884efb4 --- /dev/null +++ b/1001-1500/1152-Analyze-User-Website-Visit-Pattern/cpp-1152/main.cpp @@ -0,0 +1,76 @@ +/// Source : https://leetcode.com/problems/analyse-user-website-visit-pattern/ +/// Author : liuyubobobo +/// Time : 2019-08-10 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// State Memory +/// for every 3-sequence, record its user +/// +/// Time Complexity: O(n^3) +/// Space Complexity: O(n^3) +class Solution { + +public: + vector mostVisitedPattern(vector& username, vector& timestamp, vector& website) { + + set website_set(website.begin(), website.end()); + + unordered_map>> history; + for(int i = 0; i < username.size(); i ++) + history[username[i]].insert(make_pair(timestamp[i], website[i])); + + unordered_map>>> count; + for(const pair>>& p: history){ + vector v; + for(const pair& e: p.second) + v.push_back(e.second); + for(int i = 0; i < v.size(); i ++) + for(int j = i + 1; j < v.size(); j ++) + for(int k = j + 1; k < v.size(); k ++) + count[v[i]][v[j]][v[k]].insert(p.first); + } + + int best = -1; + vector res; + for(const string& a: website_set) + for(const string& b: website_set) + for(const string& c: website_set) + if((int)count[a][b][c].size() > best){ + best = count[a][b][c].size(); + res = {a, b, c}; + } + + return res; + } +}; + + +void print_vec(const vector& vec){ + + for(const string& e: vec) cout << e << " "; cout << endl; +} + +int main() { + + vector username1 = {"joe","joe","joe","james","james","james","james","mary","mary","mary"}; + vector timestamp1 = {1,2,3,4,5,6,7,8,9,10}; + vector website1 = {"home","about","career","home","cart","maps","home","home","about","career"}; + print_vec(Solution().mostVisitedPattern(username1, timestamp1, website1)); + // home about career + + vector username2 = {"h","eiy","cq","h","cq","txldsscx","cq","txldsscx","h","cq","cq"}; + vector timestamp2 = {527896567,334462937,517687281,134127993,859112386,159548699,51100299,444082139,926837079,317455832,411747930}; + vector website2 = {"hibympufi","hibympufi","hibympufi","hibympufi","hibympufi","hibympufi","hibympufi","hibympufi","yljmntrclw","hibympufi","yljmntrclw"}; + print_vec(Solution().mostVisitedPattern(username2, timestamp2, website2)); + // "hibympufi","hibympufi","yljmntrclw" + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1153-String-Transforms-Into-Another-String/cpp-1153/CMakeLists.txt b/1001-1500/1153-String-Transforms-Into-Another-String/cpp-1153/CMakeLists.txt new file mode 100644 index 00000000..89658265 --- /dev/null +++ b/1001-1500/1153-String-Transforms-Into-Another-String/cpp-1153/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) \ No newline at end of file diff --git a/1001-1500/1153-String-Transforms-Into-Another-String/cpp-1153/main.cpp b/1001-1500/1153-String-Transforms-Into-Another-String/cpp-1153/main.cpp new file mode 100644 index 00000000..9eae25a2 --- /dev/null +++ b/1001-1500/1153-String-Transforms-Into-Another-String/cpp-1153/main.cpp @@ -0,0 +1,45 @@ +/// Source : https://leetcode.com/problems/string-transforms-into-another-string/ +/// Author : liuyubobobo +/// Time : 2019-08-10 + +#include +#include +#include +#include + +using namespace std; + + +/// Using HashMap +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + bool canConvert(string str1, string str2) { + + if(str1 == str2) return true; + + unordered_map map; + for(int i = 0; i < str1.size(); i ++){ + if(map.count(str1[i]) && map[str1[i]] != str2[i]) + return false; + map[str1[i]] = str2[i]; + } + return unordered_set(str2.begin(), str2.end()).size() < 26; + } +}; + + +int main() { + + cout << Solution().canConvert("aabcc", "ccdee") << endl; + // 1 + + cout << Solution().canConvert("leetcode", "codeleet") << endl; + // 0 + + cout << Solution().canConvert("abcde", "zzzzz") << endl; + // 1 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1154-Day-of-the-Year/cpp-1154/CMakeLists.txt b/1001-1500/1154-Day-of-the-Year/cpp-1154/CMakeLists.txt new file mode 100644 index 00000000..afa8217d --- /dev/null +++ b/1001-1500/1154-Day-of-the-Year/cpp-1154/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1001-1500/1154-Day-of-the-Year/cpp-1154/main.cpp b/1001-1500/1154-Day-of-the-Year/cpp-1154/main.cpp new file mode 100644 index 00000000..ad6f4d7a --- /dev/null +++ b/1001-1500/1154-Day-of-the-Year/cpp-1154/main.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/ordinal-number-of-date/discuss/?currentPage=1&orderBy=hot&query= +/// Author : liuyubobobo +/// Time : 2019-08-10 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(12) +/// Space Complexity: O(1) +class Solution { +public: + int dayOfYear(string date) { + + vector a = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; + vector b = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; + + int year = atoi(date.substr(0, 4).c_str()); + int month = atoi(date.substr(5, 2).c_str()); + int day = atoi(date.substr(8, 2).c_str()); + + vector& v = is_leap_year(year) ? b : a; + + int res = 0; + for(int i = 0; i < month - 1; i ++) res += v[i]; + return res + day; + } + +private: + bool is_leap_year(int year){ + return (year % 4 == 0 && year % 100) || (year % 400 == 0); + } +}; + + +int main() { + + cout << Solution().dayOfYear("2019-01-09") << endl; + // 9 + + cout << Solution().dayOfYear("2019-02-10") << endl; + // 41 + + cout << Solution().dayOfYear("2003-03-01") << endl; + // 60 + + cout << Solution().dayOfYear("2004-03-01") << endl; + // 61 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1155-Number-of-Dice-Rolls-With-Target-Sum/cpp-1155/CMakeLists.txt b/1001-1500/1155-Number-of-Dice-Rolls-With-Target-Sum/cpp-1155/CMakeLists.txt new file mode 100644 index 00000000..3c6ea462 --- /dev/null +++ b/1001-1500/1155-Number-of-Dice-Rolls-With-Target-Sum/cpp-1155/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1001-1500/1155-Number-of-Dice-Rolls-With-Target-Sum/cpp-1155/main.cpp b/1001-1500/1155-Number-of-Dice-Rolls-With-Target-Sum/cpp-1155/main.cpp new file mode 100644 index 00000000..93de660d --- /dev/null +++ b/1001-1500/1155-Number-of-Dice-Rolls-With-Target-Sum/cpp-1155/main.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/ +/// Author : liuyubobobo +/// Time : 2019-08-10 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(D * target * F) +/// Space Complexity: O(D * target) +class Solution { + +private: + int MOD = 1e9 + 7; + +public: + int numRollsToTarget(int D, int F, int target) { + + vector> dp(D + 1, vector(target + 1, 0)); + + for(int f = 1; f <= min(F, target); f ++) + dp[1][f] = 1; + + for(int d = 2; d <= D; d ++) + for(int t = 1; t <= target; t ++) + for(int f = 1; f <= F && t - f >= 0; f ++) + dp[d][t] = (dp[d][t] + dp[d - 1][t - f]) % MOD; + return dp[D][target]; + } +}; + + +int main() { + + cout << Solution().numRollsToTarget(1, 6, 3) << endl; + // 1 + + cout << Solution().numRollsToTarget(2, 6, 7) << endl; + // 6 + + cout << Solution().numRollsToTarget(2, 5, 10) << endl; + // 1 + + cout << Solution().numRollsToTarget(1, 2, 3) << endl; + // 0 + + cout << Solution().numRollsToTarget(30, 30, 500) << endl; + // 222616187 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1156-Swap-For-Longest-Repeated-Character-Substring/cpp-1156/CMakeLists.txt b/1001-1500/1156-Swap-For-Longest-Repeated-Character-Substring/cpp-1156/CMakeLists.txt new file mode 100644 index 00000000..70268b97 --- /dev/null +++ b/1001-1500/1156-Swap-For-Longest-Repeated-Character-Substring/cpp-1156/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main2.cpp) \ No newline at end of file diff --git a/1001-1500/1156-Swap-For-Longest-Repeated-Character-Substring/cpp-1156/main.cpp b/1001-1500/1156-Swap-For-Longest-Repeated-Character-Substring/cpp-1156/main.cpp new file mode 100644 index 00000000..be6a2786 --- /dev/null +++ b/1001-1500/1156-Swap-For-Longest-Repeated-Character-Substring/cpp-1156/main.cpp @@ -0,0 +1,78 @@ +/// Source : https://leetcode.com/problems/swap-for-maximum-repeated-substring/ +/// Author : liuyubobobo +/// Time : 2019-08-10 + +#include +#include + +using namespace std; + + +/// Presum +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int maxRepOpt1(string text) { + + int n = text.size(); + vector> occurs(26, vector(n + 1, 0)); + for(int i = 0; i < n; i ++) + for(char c = 'a'; c <= 'z'; c ++) + occurs[c - 'a'][i + 1] = occurs[c - 'a'][i] + (text[i] == c); + + vector split; + for(int start = 0, i = start + 1; i <= n; i ++) + if(i == n || text[i] != text[start]){ + split.push_back(i - start); + start = i; + i = start; + } +// for(int e: split) cout << e << " "; cout << endl; + + vector presum = {0}; + for(int e: split) presum.push_back(presum.back() + e); + + int res = *max_element(split.begin(), split.end()); + for(int i = 2; i < split.size(); i ++) + if(text[presum[i - 2 + 1] - 1] == text[presum[i + 1] - 1] && split[i - 1] == 1){ + int c = text[presum[i - 2 + 1] - 1] - 'a'; + if(occurs[c][n] - occurs[c][presum[i + 1]] || occurs[c][presum[i - 2]]) + res = max(res, split[i - 2] + split[i - 1] + split[i]); + else + res = max(res, split[i - 2] + split[i]); + } + + for(int i = 0; i < split.size(); i ++){ + int c = text[presum[i + 1] - 1] - 'a'; + if(occurs[c][presum[i]]) res = max(res, split[i] + 1); + if(occurs[c][n] - occurs[c][presum[i + 1]]) res = max(res, split[i] + 1); + } + + return res; + } +}; + + +int main() { + + cout << Solution().maxRepOpt1("ababa") << endl; + // 3 + + cout << Solution().maxRepOpt1("aaabaaa") << endl; + // 6 + + cout << Solution().maxRepOpt1("aaabbaaa") << endl; + // 4 + + cout << Solution().maxRepOpt1("aaaaa") << endl; + // 5 + + cout << Solution().maxRepOpt1("abcdef") << endl; + // 1 + + cout << Solution().maxRepOpt1("bbababaaaa") << endl; + // 6 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1156-Swap-For-Longest-Repeated-Character-Substring/cpp-1156/main2.cpp b/1001-1500/1156-Swap-For-Longest-Repeated-Character-Substring/cpp-1156/main2.cpp new file mode 100644 index 00000000..4989f583 --- /dev/null +++ b/1001-1500/1156-Swap-For-Longest-Repeated-Character-Substring/cpp-1156/main2.cpp @@ -0,0 +1,67 @@ +/// Source : https://leetcode.com/problems/swap-for-maximum-repeated-substring/ +/// Author : liuyubobobo +/// Time : 2019-08-10 + +#include +#include + +using namespace std; + + +/// Split and Linear Scan +/// The idea is same as main.cpp but the logic is far more concise +/// +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int maxRepOpt1(string text) { + + int n = text.size(); + vector freq(26, 0); + for(char c: text) freq[c - 'a'] ++; + + vector split; + for(int start = 0, i = start + 1; i <= n; i ++) + if(i == n || text[i] != text[start]){ + split.push_back(text.substr(start, i - start)); + start = i; + i = start; + } + int res = 1; + for(const string& s: split) + res = max(res, (int)s.size() + (freq[s[0] - 'a'] > s.size())); + + for(int i = 1; i + 1 < split.size(); i ++) + if(split[i - 1][0] == split[i + 1][0] && split[i].size() == 1){ + int f = freq[split[i - 1][0] - 'a']; + int sum = split[i - 1].size() + split[i + 1].size(); + res = max(res, sum + (f > sum)); + } + return res; + } +}; + + +int main() { + + cout << Solution().maxRepOpt1("ababa") << endl; + // 3 + + cout << Solution().maxRepOpt1("aaabaaa") << endl; + // 6 + + cout << Solution().maxRepOpt1("aaabbaaa") << endl; + // 4 + + cout << Solution().maxRepOpt1("aaaaa") << endl; + // 5 + + cout << Solution().maxRepOpt1("abcdef") << endl; + // 1 + + cout << Solution().maxRepOpt1("bbababaaaa") << endl; + // 6 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1157-Online-Majority-Element-In-Subarray/cpp-1157/CMakeLists.txt b/1001-1500/1157-Online-Majority-Element-In-Subarray/cpp-1157/CMakeLists.txt new file mode 100644 index 00000000..70e53c5f --- /dev/null +++ b/1001-1500/1157-Online-Majority-Element-In-Subarray/cpp-1157/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main5.cpp) \ No newline at end of file diff --git a/1001-1500/1157-Online-Majority-Element-In-Subarray/cpp-1157/main.cpp b/1001-1500/1157-Online-Majority-Element-In-Subarray/cpp-1157/main.cpp new file mode 100644 index 00000000..f7bd592b --- /dev/null +++ b/1001-1500/1157-Online-Majority-Element-In-Subarray/cpp-1157/main.cpp @@ -0,0 +1,68 @@ +/// Source : https://leetcode.com/problems/online-majority-element-in-subarray/ +/// Author : liuyubobobo +/// Time : 2019-08-11 + +#include +#include +#include +#include + +using namespace std; + + +/// Boyer-Moore Voting Algorithm to Vote +/// and Binary Search to check +/// +/// for details of BM Voting, see here Approach 6: +/// https://leetcode.com/problems/majority-element/solution/ +/// +/// Time Complexity: init: O(n) +/// query: O(n) +/// Space Complexity: O(n) +class MajorityChecker { + +private: + unordered_map> indexes; + vector arr; + +public: + MajorityChecker(vector& arr): arr(arr.begin(), arr.end()){ + + for(int i = 0; i < arr.size(); i ++) + indexes[arr[i]].push_back(i); + } + + int query(int left, int right, int threshold) { + + int e = vote(left, right); + + const vector& v = indexes[e]; + vector:: const_iterator iter1 = lower_bound(v.begin(), v.end(), left); + vector:: const_iterator iter2 = upper_bound(v.begin(), v.end(), right); + if(iter2 - iter1 >= threshold) return e; + return -1; + } + +private: + int vote(int left, int right){ + + int count = 1, res = arr[left]; + for(int i = left + 1; i <= right; i ++){ + if(count == 0) res = arr[i]; + count += (res == arr[i] ? 1 : -1); + } + return res; + } +}; + + +int main() { + + vector arr = {1,1,2,2,1,1}; + MajorityChecker checker(arr); + cout << checker.query(0, 5, 4) << endl; // 1 + cout << checker.query(0, 3, 3) << endl; // -1 + cout << checker.query(2, 3, 2) << endl; // 2 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1157-Online-Majority-Element-In-Subarray/cpp-1157/main2.cpp b/1001-1500/1157-Online-Majority-Element-In-Subarray/cpp-1157/main2.cpp new file mode 100644 index 00000000..ea0792a7 --- /dev/null +++ b/1001-1500/1157-Online-Majority-Element-In-Subarray/cpp-1157/main2.cpp @@ -0,0 +1,80 @@ +/// Source : https://leetcode.com/problems/online-majority-element-in-subarray/ +/// Author : liuyubobobo +/// Time : 2019-08-11 + +#include +#include +#include +#include + +using namespace std; + + +/// Using Boyer-Moore Voting Algorithm when interval is short +/// Check popular elements when interval is longer +/// the bound can be set to be sqrt(n) +/// +/// Time Complexity: init: O(n) +/// query: O(sqrt(n)*logn) +/// Space Complexity: O(n) +class MajorityChecker { + +private: + unordered_map> indexes; + vector arr, popular_nums; + const int LIMIT; + +public: + MajorityChecker(vector& arr): arr(arr.begin(), arr.end()), LIMIT(sqrt(arr.size())){ + + for(int i = 0; i < arr.size(); i ++) + indexes[arr[i]].push_back(i); + + for(const pair>& p: indexes) + if(p.second.size() > LIMIT) + popular_nums.push_back(p.first); + } + + int query(int left, int right, int threshold) { + + if(threshold <= LIMIT){ + int e = vote(left, right); + return get_freq(e, left, right) >= threshold ? e : -1; + } + + for(int e: popular_nums) + if(get_freq(e, left, right) >= threshold) + return e; + return -1; + } + +private: + int get_freq(int e, int left, int right){ + const vector& v = indexes[e]; + vector:: const_iterator iter1 = lower_bound(v.begin(), v.end(), left); + vector:: const_iterator iter2 = upper_bound(v.begin(), v.end(), right); + return iter2 - iter1; + } + + int vote(int left, int right){ + + int count = 1, res = arr[left]; + for(int i = left + 1; i <= right; i ++){ + if(count == 0) res = arr[i]; + count += (res == arr[i] ? 1 : -1); + } + return res; + } +}; + + +int main() { + + vector arr = {1,1,2,2,1,1}; + MajorityChecker checker(arr); + cout << checker.query(0, 5, 4) << endl; // 1 + cout << checker.query(0, 3, 3) << endl; // -1 + cout << checker.query(2, 3, 2) << endl; // 2 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1157-Online-Majority-Element-In-Subarray/cpp-1157/main3.cpp b/1001-1500/1157-Online-Majority-Element-In-Subarray/cpp-1157/main3.cpp new file mode 100644 index 00000000..3305c563 --- /dev/null +++ b/1001-1500/1157-Online-Majority-Element-In-Subarray/cpp-1157/main3.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/online-majority-element-in-subarray/ +/// Author : liuyubobobo +/// Time : 2019-08-11 + +#include +#include +#include +#include + +using namespace std; + + +/// Random Check +/// Time Complexity: init: O(n) +/// query: O(1) +/// Space Complexity: O(n) +class MajorityChecker { + +private: + vector arr; + unordered_map> indexes; + +public: + MajorityChecker(vector& arr): arr(arr.begin(), arr.end()) { + + for(int i = 0; i < arr.size(); i ++) + indexes[arr[i]].push_back(i); + } + + int query(int left, int right, int threshold) { + + for(int k = 0; k < 20; k ++){ + int e = arr[rand() % (right - left + 1) + left]; + vector& v = indexes[e]; + vector:: iterator iter1 = lower_bound(v.begin(), v.end(), left); + vector:: iterator iter2 = upper_bound(v.begin(), v.end(), right); + if(iter2 - iter1 >= threshold) return e; + } + return -1; + } +}; + + +int main() { + + vector arr = {1,1,2,2,1,1}; + MajorityChecker checker(arr); + cout << checker.query(0, 5, 4) << endl; // 1 + cout << checker.query(0, 3, 3) << endl; // -1 + cout << checker.query(2, 3, 2) << endl; // 2 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1157-Online-Majority-Element-In-Subarray/cpp-1157/main4.cpp b/1001-1500/1157-Online-Majority-Element-In-Subarray/cpp-1157/main4.cpp new file mode 100644 index 00000000..e9c47f9e --- /dev/null +++ b/1001-1500/1157-Online-Majority-Element-In-Subarray/cpp-1157/main4.cpp @@ -0,0 +1,92 @@ +/// Source : https://leetcode.com/problems/online-majority-element-in-subarray/ +/// Author : liuyubobobo +/// Time : 2019-08-11 + +#include +#include +#include +#include + +using namespace std; + + +/// Segment Tree +/// if we split the interval [l, r] into several sub-intervals +/// the more than half majority should also be a more than half majority int at least one sub-interval +/// +/// Time Complexity: init: O(nlogn) +/// query: O(logn * logn) +/// Space Complexity: O(n) +class MajorityChecker { + +private: + vector arr, tree; + unordered_map> indexes; + +public: + MajorityChecker(vector& arr): arr(arr.begin(), arr.end()), tree(4 * arr.size(), -1) { + + for(int i = 0; i < arr.size(); i ++) + indexes[arr[i]].push_back(i); + build_tree(0, 0, arr.size() - 1); + } + + int query(int left, int right, int threshold) { + + + int e = query(0, 0, arr.size() - 1, left, right); + if(e != -1 && get_freq(e, left, right) >= threshold) return e; + return -1; + } + +private: + int query(int treeid, int l, int r, int ql, int qr){ + + if(ql == l && qr == r) return tree[treeid]; + + int mid = (l + r) / 2; + if(qr <= mid) return query(treeid * 2 + 1, l, mid, ql, qr); + if(ql >= mid + 1) return query(treeid * 2 + 2, mid + 1, r, ql, qr); + + int a = query(treeid * 2 + 1, l, mid, ql, mid); + int b = query(treeid * 2 + 2, mid + 1, r, mid + 1, qr); + if(get_freq(a, ql, qr) * 2 >= qr - ql + 1) return a; + else if(get_freq(b, ql, qr) * 2 >= qr - ql + 1) return b; + return -1; + } + + void build_tree(int treeid, int l, int r){ + + if(l == r){ + tree[treeid] = arr[l]; + return; + } + + int mid = (l + r) / 2; + build_tree(treeid * 2 + 1, l, mid); + build_tree(treeid * 2 + 2, mid + 1, r); + if(tree[treeid * 2 + 1] && get_freq(tree[treeid * 2 + 1], l, r) * 2 >= r - l + 1) + tree[treeid] = tree[treeid * 2 + 1]; + else if(tree[treeid * 2 + 2] && get_freq(tree[treeid * 2 + 2], l, r) * 2 >= r - l + 1) + tree[treeid] = tree[treeid * 2 + 2]; + } + + int get_freq(int e, int left, int right){ + const vector& v = indexes[e]; + vector:: const_iterator iter1 = lower_bound(v.begin(), v.end(), left); + vector:: const_iterator iter2 = upper_bound(v.begin(), v.end(), right); + return iter2 - iter1; + } +}; + + +int main() { + + vector arr = {1,1,2,2,1,1}; + MajorityChecker checker(arr); + cout << checker.query(0, 5, 4) << endl; // 1 + cout << checker.query(0, 3, 3) << endl; // -1 + cout << checker.query(2, 3, 2) << endl; // 2 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1157-Online-Majority-Element-In-Subarray/cpp-1157/main5.cpp b/1001-1500/1157-Online-Majority-Element-In-Subarray/cpp-1157/main5.cpp new file mode 100644 index 00000000..1aafdd61 --- /dev/null +++ b/1001-1500/1157-Online-Majority-Element-In-Subarray/cpp-1157/main5.cpp @@ -0,0 +1,120 @@ +/// Source : https://leetcode.com/problems/online-majority-element-in-subarray/ +/// Author : liuyubobobo +/// Time : 2019-08-11 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// Bucket +/// if we split the interval [l, r] into several sub-intervals +/// the more than half majority should also be a more than half majority int at least one sub-interval +/// +/// Time Complexity: init: O(nlogn) +/// query: O(sqrt(n) * logn) +/// Space Complexity: O(n) +class MajorityChecker { + +private: + vector arr; + unordered_map> indexes; + + vector bucket; + int bucket_sz; + vector bucket_majority; + +public: + MajorityChecker(vector& arr): arr(arr.begin(), arr.end()), bucket_sz(sqrt(arr.size())){ + + for(int i = 0; i < arr.size(); i ++) + indexes[arr[i]].push_back(i); + + bucket.push_back(0); + while(bucket.back() != arr.size()){ + int l = bucket.back(); + int r = min(bucket.back() + bucket_sz, (int)arr.size()); + bucket.push_back(r); + bucket_majority.push_back(vote(l, r - 1)); + } + +// for(int e: bucket) cout << e << " "; cout << endl; +// for(int e: bucket_majority) cout << e << " "; cout << endl; + } + + int query(int left, int right, int threshold) { + + vector::iterator iter = lower_bound(bucket.begin(), bucket.end(), left); + int b = iter - bucket.begin(); + if(bucket[b] > left) b --; + assert(b >= 0 && b + 1 < bucket.size()); + if(right < bucket[b + 1]){ + int e = vote(left, right); + if(get_freq(e, left, right) >= threshold) return e; + return -1; + } + + while(bucket[b] <= right){ + int f = get_freq(bucket_majority[b], left, right); + int e = bucket_majority[b]; + if(left > bucket[b]){ + e = vote(left, bucket[b + 1]); + f = get_freq(e, left, right); + } + else if(right < bucket[b + 1] - 1){ + e = vote(bucket[b], right); + f = get_freq(e, left, right); + } + if(f >= threshold) return e; + b ++; + } + return -1; + } + +private: + int vote(int left, int right){ + + int count = 1, res = arr[left]; + for(int i = left + 1; i <= right; i ++){ + if(count == 0) res = arr[i]; + count += (res == arr[i] ? 1 : -1); + } + return res; + } + + int get_freq(int e, int left, int right){ + const vector& v = indexes[e]; + vector:: const_iterator iter1 = lower_bound(v.begin(), v.end(), left); + vector:: const_iterator iter2 = upper_bound(v.begin(), v.end(), right); + return iter2 - iter1; + } +}; + + +int main() { + + vector arr1 = {1,1,2,2,1,1}; + MajorityChecker checker1(arr1); + cout << checker1.query(0, 5, 4) << endl; // 1 + cout << checker1.query(0, 3, 3) << endl; // -1 + cout << checker1.query(2, 3, 2) << endl; // 2 + + vector arr2 = {2,2,2,2,1,2,2,1,1,1,2,1,2,1,2,2}; + MajorityChecker checker2(arr2); + cout << checker2.query(0, 13, 10) << endl; // 1 + cout << checker2.query(4, 12, 8) << endl; // -1 + cout << checker2.query(0, 12, 13) << endl; // -1 + cout << checker2.query(4, 14, 10) << endl; // -1 + cout << checker2.query(0, 4, 4) << endl; // 2 + cout << checker2.query(13, 13, 1) << endl; // -1 + cout << checker2.query(10, 13, 3) << endl; // -1 + cout << checker2.query(4, 7, 3) << endl; // -1 + cout << checker2.query(3, 5, 2) << endl; // 2 + cout << checker2.query(6, 14, 7) << endl; // -1 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1160-Find-Words-That-Can-Be-Formed-by-Characters/cpp-1160/CMakeLists.txt b/1001-1500/1160-Find-Words-That-Can-Be-Formed-by-Characters/cpp-1160/CMakeLists.txt new file mode 100644 index 00000000..afa8217d --- /dev/null +++ b/1001-1500/1160-Find-Words-That-Can-Be-Formed-by-Characters/cpp-1160/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1001-1500/1160-Find-Words-That-Can-Be-Formed-by-Characters/cpp-1160/main.cpp b/1001-1500/1160-Find-Words-That-Can-Be-Formed-by-Characters/cpp-1160/main.cpp new file mode 100644 index 00000000..7565f3ff --- /dev/null +++ b/1001-1500/1160-Find-Words-That-Can-Be-Formed-by-Characters/cpp-1160/main.cpp @@ -0,0 +1,45 @@ +/// Source : https://leetcode.com/problems/find-words-that-can-be-formed-by-characters/ +/// Author : liuyubobobo +/// Time : 2019-08-17 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int countCharacters(vector& words, string chars) { + + vector freq(26, 0); + for(char c: chars) + freq[c - 'a'] ++; + + int res = 0; + for(const string& word: words) + if(ok(word, freq)) res += word.size(); + return res; + } + +private: + bool ok(const string& s, const vector& freq){ + + vector f(26, 0); + for(char c: s) + f[c - 'a'] ++; + + for(int i = 0; i < 26; i ++) + if(f[i] > freq[i]) return false; + return true; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1161-Maximum-Level-Sum-of-a-Binary-Tree/cpp-1161/CMakeLists.txt b/1001-1500/1161-Maximum-Level-Sum-of-a-Binary-Tree/cpp-1161/CMakeLists.txt new file mode 100644 index 00000000..7f3bfb51 --- /dev/null +++ b/1001-1500/1161-Maximum-Level-Sum-of-a-Binary-Tree/cpp-1161/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main2.cpp) \ No newline at end of file diff --git a/1001-1500/1161-Maximum-Level-Sum-of-a-Binary-Tree/cpp-1161/main.cpp b/1001-1500/1161-Maximum-Level-Sum-of-a-Binary-Tree/cpp-1161/main.cpp new file mode 100644 index 00000000..3e1a53c8 --- /dev/null +++ b/1001-1500/1161-Maximum-Level-Sum-of-a-Binary-Tree/cpp-1161/main.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/maximum-level-sum-of-a-binary-tree/ +/// Author : liuyubobobo +/// Time : 2019-08-17 + +#include +#include + +using namespace std; + + +/// DFS and Using HashMap +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// 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 { + +private: + map sum; + +public: + int maxLevelSum(TreeNode* root) { + + dfs(root, 1); + int res = -1, best = INT_MIN; + for(const pair& p: sum) + if(p.second > best) + best = p.second, res = p.first; + return res; + } + +private: + void dfs(TreeNode* node, int level){ + + if(!node) return; + sum[level] += node->val; + dfs(node->left, level + 1); + dfs(node->right, level + 1); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1161-Maximum-Level-Sum-of-a-Binary-Tree/cpp-1161/main2.cpp b/1001-1500/1161-Maximum-Level-Sum-of-a-Binary-Tree/cpp-1161/main2.cpp new file mode 100644 index 00000000..22583fa1 --- /dev/null +++ b/1001-1500/1161-Maximum-Level-Sum-of-a-Binary-Tree/cpp-1161/main2.cpp @@ -0,0 +1,61 @@ +/// Source : https://leetcode.com/problems/maximum-level-sum-of-a-binary-tree/ +/// Author : liuyubobobo +/// Time : 2019-08-18 +/// Updated: 2022-06-16 + +#include +#include +#include +#include + +using namespace std; + + +/// BFS +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// 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: + int maxLevelSum(TreeNode* root) { + + if(!root) return 0; + + queue q; + int best = INT_MIN, res = 0, cur_level = 0; + q.push(root); + while(!q.empty()){ + + cur_level ++; + queue q2; + int sum = 0; + while(!q.empty()){ + TreeNode* cur = q.front(); q.pop(); assert(cur); + sum += cur->val; + if(cur->left) q2.push(cur->left); + if(cur->right) q2.push(cur->right); + } + + // cout << cur_level << ' ' << sum << '\n'; + if(sum > best) best = sum, res = cur_level; + + q = q2; + } + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1162-As-Far-from-Land-as-Possible/cpp-1162/CMakeLists.txt b/1001-1500/1162-As-Far-from-Land-as-Possible/cpp-1162/CMakeLists.txt new file mode 100644 index 00000000..a9faeff1 --- /dev/null +++ b/1001-1500/1162-As-Far-from-Land-as-Possible/cpp-1162/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1001-1500/1162-As-Far-from-Land-as-Possible/cpp-1162/main.cpp b/1001-1500/1162-As-Far-from-Land-as-Possible/cpp-1162/main.cpp new file mode 100644 index 00000000..288c2524 --- /dev/null +++ b/1001-1500/1162-As-Far-from-Land-as-Possible/cpp-1162/main.cpp @@ -0,0 +1,67 @@ +/// Source : https://leetcode.com/problems/as-far-from-land-as-possible/ +/// Author : liuyubobobo +/// Time : 2019-08-17 + +#include +#include +#include + +using namespace std; + + +/// BFS +/// Time Complexity: O(n * m) +/// Space Complexity: O(n * m) +class Solution { + +private: + int n, m; + int dirs[4][2] = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}}; + +public: + int maxDistance(vector>& grid) { + + n = grid.size(), m = grid[0].size(); + vector> dis(n, vector(m, -1)); + queue q; + for(int i = 0; i < n; i ++) + for(int j = 0; j < m; j ++) + if(grid[i][j]) + q.push(i * m + j), dis[i][j] = 0; + + int res = 0; + while(!q.empty()){ + int curx = q.front() / m, cury = q.front() % m; + q.pop(); + res = max(res, dis[curx][cury]); + + for(int d = 0; d < 4; d ++){ + int nextx = curx + dirs[d][0], nexty = cury + dirs[d][1]; + if(in_area(nextx, nexty) && dis[nextx][nexty] == -1){ + q.push(nextx * m + nexty); + dis[nextx][nexty] = dis[curx][cury] + 1; + } + } + } + return res ? res : -1; + } + +private: + bool in_area(int x, int y){ + return x >= 0 && x < n && y >= 0 && y < m; + } +}; + + +int main() { + + vector> g1 = {{1, 0, 1}, {0, 0, 0}, {1, 0, 1}}; + cout << Solution().maxDistance(g1) << endl; + // 2 + + vector> g2 = {{1, 0, 0}, {0, 0, 0}, {0, 0, 0}}; + cout << Solution().maxDistance(g2) << endl; + //4 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1163-Last-Substring-in-Lexicographical-Order/cpp-1163/CMakeLists.txt b/1001-1500/1163-Last-Substring-in-Lexicographical-Order/cpp-1163/CMakeLists.txt new file mode 100644 index 00000000..d645976f --- /dev/null +++ b/1001-1500/1163-Last-Substring-in-Lexicographical-Order/cpp-1163/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(cpp_1163) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1163 main.cpp) \ No newline at end of file diff --git a/1001-1500/1163-Last-Substring-in-Lexicographical-Order/cpp-1163/main.cpp b/1001-1500/1163-Last-Substring-in-Lexicographical-Order/cpp-1163/main.cpp new file mode 100644 index 00000000..a083c946 --- /dev/null +++ b/1001-1500/1163-Last-Substring-in-Lexicographical-Order/cpp-1163/main.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/last-substring-in-lexicographical-order/ +/// Author : liuyubobobo +/// Time : 2019-08-22 + +#include + +using namespace std; + + +/// Two Pointers +/// See here for details: +/// https://leetcode.com/problems/last-substring-in-lexicographical-order/discuss/363662/Short-python-code-O(n)-time-and-O(1)-space-with-proof +/// +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + string lastSubstring(string s) { + + int i = 0, j = 1, k = 0; + while(j + k < s.size()){ + + if(s[i + k] == s[j + k]) k ++; + else if(s[i + k] > s[j + k]) j = j + k + 1, k = 0; + else i = max(j, i + k + 1), j = i + 1, k = 0; + } + return s.substr(i); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1165-Single-Row-Keyboard/cpp-1165/CMakeLists.txt b/1001-1500/1165-Single-Row-Keyboard/cpp-1165/CMakeLists.txt new file mode 100644 index 00000000..afa8217d --- /dev/null +++ b/1001-1500/1165-Single-Row-Keyboard/cpp-1165/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1001-1500/1165-Single-Row-Keyboard/cpp-1165/main.cpp b/1001-1500/1165-Single-Row-Keyboard/cpp-1165/main.cpp new file mode 100644 index 00000000..267272e6 --- /dev/null +++ b/1001-1500/1165-Single-Row-Keyboard/cpp-1165/main.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/single-row-keyboard/ +/// Author : liuyubobobo +/// Time : 2019-08-24 + +#include +#include + +using namespace std; + + +/// Using HashMap +/// Time Complexity: O(|word|) +/// Space Complexity: O(1) +class Solution { +public: + int calculateTime(string keyboard, string word) { + + unordered_map map; + for(int i = 0; i < keyboard.size(); i ++) + map[keyboard[i]] = i; + + int cur = 0, res = 0; + for(char c: word) + res += abs(cur - map[c]), cur = map[c]; + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1166-Design-File-System/cpp-1166/CMakeLists.txt b/1001-1500/1166-Design-File-System/cpp-1166/CMakeLists.txt new file mode 100644 index 00000000..3c6ea462 --- /dev/null +++ b/1001-1500/1166-Design-File-System/cpp-1166/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1001-1500/1166-Design-File-System/cpp-1166/main.cpp b/1001-1500/1166-Design-File-System/cpp-1166/main.cpp new file mode 100644 index 00000000..a96380e6 --- /dev/null +++ b/1001-1500/1166-Design-File-System/cpp-1166/main.cpp @@ -0,0 +1,55 @@ +/// Source : https://leetcode.com/problems/design-file-system/ +/// Author : liuyubobobo +/// Time : 2019-08-24 +/// Updated: 2022-04-21 + +#include +#include +#include +#include + +using namespace std; + + +/// Using HashMap +/// Time Complexity: createPath: O(|path|) +/// get: O(|path|) +/// Space Complexity: O(|query| * |path|) +class FileSystem { + +private: + unordered_map map; + +public: + FileSystem() { + map[""] = -1; + } + + bool createPath(string path, int value) { + + if(map.count(path)) return false; + + int last = path.rfind('/'); + if(!map.count(path.substr(0, last))) return false; + + map[path] = value; + return true; + } + + int get(string path) { + return map.count(path) ? map[path] : -1; + } +}; + + +int main() { + + FileSystem fs; + cout << fs.createPath("/leet", 1) << endl; + cout << fs.createPath("/leet/code", 2) << endl; + cout << fs.get("/leet/code") << endl; + cout << fs.createPath("/c/d", 1) << endl; // false + cout << fs.get("/c") << endl; // -1 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1167-Minimum-Cost-to-Connect-Sticks/cpp-1167/CMakeLists.txt b/1001-1500/1167-Minimum-Cost-to-Connect-Sticks/cpp-1167/CMakeLists.txt new file mode 100644 index 00000000..a9faeff1 --- /dev/null +++ b/1001-1500/1167-Minimum-Cost-to-Connect-Sticks/cpp-1167/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1001-1500/1167-Minimum-Cost-to-Connect-Sticks/cpp-1167/main.cpp b/1001-1500/1167-Minimum-Cost-to-Connect-Sticks/cpp-1167/main.cpp new file mode 100644 index 00000000..01e56b84 --- /dev/null +++ b/1001-1500/1167-Minimum-Cost-to-Connect-Sticks/cpp-1167/main.cpp @@ -0,0 +1,44 @@ +/// Source : https://leetcode.com/problems/minimum-cost-to-connect-sticks/ +/// Author : liuyubobobo +/// Time : 2019-08-24 + +#include +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + int connectSticks(vector& sticks) { + + priority_queue, greater> pq; + for(int stick: sticks) pq.push(stick); + int res = 0; + while(pq.size() > 1){ + int cost = pq.top(); + pq.pop(); + cost += pq.top(); + pq.pop(); + + res += cost; + pq.push(cost); + } + return res; + } +}; + + +int main() { + + vector sticks1 = {2, 4, 3}; + cout << Solution().connectSticks(sticks1) << endl; + + vector sticks2 = {1, 8, 3, 5}; + cout << Solution().connectSticks(sticks2) << endl; + return 0; +} \ No newline at end of file diff --git a/1001-1500/1168-Optimize-Water-Distribution-in-a-Village/cpp-1168/CMakeLists.txt b/1001-1500/1168-Optimize-Water-Distribution-in-a-Village/cpp-1168/CMakeLists.txt new file mode 100644 index 00000000..89658265 --- /dev/null +++ b/1001-1500/1168-Optimize-Water-Distribution-in-a-Village/cpp-1168/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) \ No newline at end of file diff --git a/1001-1500/1168-Optimize-Water-Distribution-in-a-Village/cpp-1168/main.cpp b/1001-1500/1168-Optimize-Water-Distribution-in-a-Village/cpp-1168/main.cpp new file mode 100644 index 00000000..3eb077b3 --- /dev/null +++ b/1001-1500/1168-Optimize-Water-Distribution-in-a-Village/cpp-1168/main.cpp @@ -0,0 +1,83 @@ +/// Source : https://leetcode.com/problems/optimize-water-distribution-in-a-village/ +/// Author : liuyubobobo +/// Time : 2019-08-24 + +#include +#include +#include + +using namespace std; + + +/// MST +/// Time Complexity: O(ElogE) +/// Space Complexity: O(V + E) +class UF{ + +private: + vector parent; + +public: + UF(int n){ + for(int i = 0 ; i < n ; i ++) + parent.push_back(i); + } + + int find(int p){ + if( p != parent[p] ) + parent[p] = find( parent[p] ); + return parent[p]; + } + + bool isConnected(int p , int q){ + return find(p) == find(q); + } + + void unionElements(int p, int q){ + + int pRoot = find(p); + int qRoot = find(q); + + if( pRoot == qRoot ) + return; + + parent[pRoot] = qRoot; + } +}; + +class Solution { + +public: + int minCostToSupplyWater(int n, vector& wells, vector>& pipes) { + + for(int i = 0; i < wells.size(); i ++) + pipes.push_back({0, i + 1, wells[i]}); + + sort(pipes.begin(), pipes.end(), [](const vector& v1, const vector& v2){ + return v1[2] < v2[2]; + }); + + UF uf(n + 1); + int res = 0; + for(const vector& v: pipes) + if(!uf.isConnected(v[0], v[1])) + res += v[2], uf.unionElements(v[0], v[1]); + return res; + } +}; + + +int main() { + + vector wells1 = {1,2,2}; + vector> pipes1 = {{1, 2, 1}, {2, 3, 1}}; + cout << Solution().minCostToSupplyWater(3, wells1, pipes1) << endl; + // 3 + + vector wells2 = {46012,72474,64965,751,33304}; + vector> pipes2 = {{2,1,6719},{3,2,75312},{5,3,44918}}; + cout << Solution().minCostToSupplyWater(5, wells2, pipes2) << endl; + // 131704 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1169-Invalid-Transactions/cpp-1169/CMakeLists.txt b/1001-1500/1169-Invalid-Transactions/cpp-1169/CMakeLists.txt new file mode 100644 index 00000000..afa8217d --- /dev/null +++ b/1001-1500/1169-Invalid-Transactions/cpp-1169/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1001-1500/1169-Invalid-Transactions/cpp-1169/main.cpp b/1001-1500/1169-Invalid-Transactions/cpp-1169/main.cpp new file mode 100644 index 00000000..4e6321f0 --- /dev/null +++ b/1001-1500/1169-Invalid-Transactions/cpp-1169/main.cpp @@ -0,0 +1,76 @@ +/// Source : https://leetcode.com/problems/invalid-transactions/ +/// Author : liuyubobobo +/// Time : 2019-08-24 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n^2) +/// Space Complexity: O(1) +class Solution { + +private: + class Transaction{ + + public: + string name, city; + int time, amount; + + Transaction(const string& name, int time, int amount, const string& city): + name(name), time(time), amount(amount), city(city){} + }; + + vector vec; + +public: + vector invalidTransactions(vector& transactions) { + + + for(const string& s: transactions) + vec.push_back(getTransaction(s)); + + vector res; + for(int i = 0; i < vec.size(); i ++) + if(vec[i].amount > 1000 || suspicious(i)) + res.push_back(transactions[i]); + + return res; + } + +private: + bool suspicious(int index){ + + for(int i = 0; i < vec.size(); i ++) + if(i != index && + vec[i].name == vec[index].name && + vec[i].city != vec[index].city && + abs(vec[i].time - vec[index].time) <= 60) return true; + return false; + } + + Transaction getTransaction(const string& s){ + + int name_i = s.find(','); + string name = s.substr(0, name_i); + + int time_i = s.find(',', name_i + 1); + int time = atoi(s.substr(name_i + 1, time_i - (name_i + 1)).c_str()); + + int amount_i = s.find(',', time_i + 1); + int amount = atoi(s.substr(time_i + 1, amount_i - (time_i + 1)).c_str()); + + string city = s.substr(amount_i + 1); + + return Transaction(name, time, amount, city); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1170-Compare-Strings-by-Frequency-of-the-Smallest-Character/cpp-1170/CMakeLists.txt b/1001-1500/1170-Compare-Strings-by-Frequency-of-the-Smallest-Character/cpp-1170/CMakeLists.txt new file mode 100644 index 00000000..3c6ea462 --- /dev/null +++ b/1001-1500/1170-Compare-Strings-by-Frequency-of-the-Smallest-Character/cpp-1170/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1001-1500/1170-Compare-Strings-by-Frequency-of-the-Smallest-Character/cpp-1170/main.cpp b/1001-1500/1170-Compare-Strings-by-Frequency-of-the-Smallest-Character/cpp-1170/main.cpp new file mode 100644 index 00000000..722d9307 --- /dev/null +++ b/1001-1500/1170-Compare-Strings-by-Frequency-of-the-Smallest-Character/cpp-1170/main.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/compare-strings-by-frequency-of-the-smallest-character/ +/// Author : liuyubobobo +/// Time : 2019-08-24 + +#include +#include + +using namespace std; + + +/// Presum +/// Time Complexity: O(|words| + |queries|) +/// Space Complexity: O(1) +class Solution { +public: + vector numSmallerByFrequency(vector& queries, vector& words) { + + vector vec(11, 0); + for(const string& word: words) + vec[f(word)] ++; + + for(int i = vec.size() - 1; i >= 1; i --) + vec[i - 1] += vec[i]; + + vector res; + for(const string& q: queries) + res.push_back(vec[f(q) + 1]); + return res; + } + +private: + int f(const string& s){ + vector freq(26, 0); + for(char c: s) + freq[c - 'a'] ++; + for(int e: freq) if(e) return e; + return 0; + } +}; + + +void print_vec(const vector& vec){ + for(int e: vec) cout << e << " "; cout << endl; +} + +int main() { + + vector queries1 = {"cbd"}, words1 = {"zaaaz"}; + print_vec(Solution().numSmallerByFrequency(queries1, words1)); + // {1} + + vector queries2 = {"bbb","cc"}, words2 = {"a","aa","aaa","aaaa"}; + print_vec(Solution().numSmallerByFrequency(queries2, words2)); + // {1, 2} + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1171-Remove-Zero-Sum-Consecutive-Nodes-from-Linked-List/cpp-1171/CMakeLists.txt b/1001-1500/1171-Remove-Zero-Sum-Consecutive-Nodes-from-Linked-List/cpp-1171/CMakeLists.txt new file mode 100644 index 00000000..c8263b40 --- /dev/null +++ b/1001-1500/1171-Remove-Zero-Sum-Consecutive-Nodes-from-Linked-List/cpp-1171/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp main2.cpp) \ No newline at end of file diff --git a/1001-1500/1171-Remove-Zero-Sum-Consecutive-Nodes-from-Linked-List/cpp-1171/main.cpp b/1001-1500/1171-Remove-Zero-Sum-Consecutive-Nodes-from-Linked-List/cpp-1171/main.cpp new file mode 100644 index 00000000..b838d612 --- /dev/null +++ b/1001-1500/1171-Remove-Zero-Sum-Consecutive-Nodes-from-Linked-List/cpp-1171/main.cpp @@ -0,0 +1,49 @@ +/// Source : https://leetcode.com/problems/remove-zero-sum-consecutive-nodes-from-linked-list/ +/// Author : liuyubobobo +/// Time : 2020-04-11 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n^2) +/// Space Complexity: O(1) + +/// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} +}; + +class Solution { +public: + ListNode* removeZeroSumSublists(ListNode* head) { + + ListNode* dummyHead = new ListNode(0); + dummyHead->next = head; + + for(ListNode* prev = dummyHead; prev->next;){ + + int sum = 0; + for(ListNode* node = prev->next; node; node = node->next){ + sum += node->val; + if(sum == 0){ + prev->next = node->next; + break; + } + } + if(sum) prev = prev->next; + } + return dummyHead->next; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1171-Remove-Zero-Sum-Consecutive-Nodes-from-Linked-List/cpp-1171/main2.cpp b/1001-1500/1171-Remove-Zero-Sum-Consecutive-Nodes-from-Linked-List/cpp-1171/main2.cpp new file mode 100644 index 00000000..bce7ee12 --- /dev/null +++ b/1001-1500/1171-Remove-Zero-Sum-Consecutive-Nodes-from-Linked-List/cpp-1171/main2.cpp @@ -0,0 +1,56 @@ +/// Source : https://leetcode.com/problems/remove-zero-sum-consecutive-nodes-from-linked-list/ +/// Author : liuyubobobo +/// Time : 2019-08-25 +/// Updated: 2020-04-11 + +#include +#include + +using namespace std; + + +/// Using HashMap +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} +}; + +class Solution { +public: + ListNode* removeZeroSumSublists(ListNode* head) { + + ListNode* dummyHead = new ListNode(0); + dummyHead->next = head; + + unordered_map map; + ListNode* cur = dummyHead; + int presum = 0; + while(cur){ + presum += cur->val; + if(map.count(presum)){ + + int erase_sum = presum; + for(ListNode* node = map[presum]->next; node != cur; node = node->next){ + erase_sum += node->val; + map.erase(erase_sum); + } + map[presum]->next = cur->next; + } + else + map[presum] = cur; + cur = cur->next; + } + return dummyHead->next; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1172-Dinner-Plate-Stacks/cpp-1172/CMakeLists.txt b/1001-1500/1172-Dinner-Plate-Stacks/cpp-1172/CMakeLists.txt new file mode 100644 index 00000000..89658265 --- /dev/null +++ b/1001-1500/1172-Dinner-Plate-Stacks/cpp-1172/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) \ No newline at end of file diff --git a/1001-1500/1172-Dinner-Plate-Stacks/cpp-1172/main.cpp b/1001-1500/1172-Dinner-Plate-Stacks/cpp-1172/main.cpp new file mode 100644 index 00000000..e4ffa198 --- /dev/null +++ b/1001-1500/1172-Dinner-Plate-Stacks/cpp-1172/main.cpp @@ -0,0 +1,69 @@ +/// Source : https://leetcode.com/problems/dinner-plate-stacks/ +/// Author : liuyubobobo +/// Time : 2019-08-25 + +#include +#include +#include +#include + +using namespace std; + + +/// Using TreeSet +/// Time Complexity: init: O(1) +/// push: O(|stacks|) +/// pop: O(|stacks|) +/// Space Complexity: O(num_of_elements + |stacks|) +class DinnerPlates { + +private: + int C; + vector> stacks; + set nonFullStack, nonEmptyStack; + +public: + DinnerPlates(int capacity): C(capacity){} + + void push(int val) { + if(nonFullStack.size()){ + int index = *nonFullStack.begin(); + stacks[index].push(val); + if(stacks[index].size() == C) nonFullStack.erase(index); + nonEmptyStack.insert(index); + } + else{ + if(stacks.empty() || stacks.back().size() == C) + stacks.push_back(stack()); + stacks.back().push(val); + nonEmptyStack.insert(stacks.size() - 1); + } + } + + int pop() { + + if(nonEmptyStack.size() == 0) return -1; + int index = *nonEmptyStack.rbegin(); + int ret = stacks[index].top(); + stacks[index].pop(); + nonFullStack.insert(index); + if(!stacks[index].size()) nonEmptyStack.erase(index); + return ret; + } + + int popAtStack(int index) { + if(index < 0 || index >= stacks.size()) return -1; + if(!stacks[index].size()) return -1; + int ret = stacks[index].top(); + stacks[index].pop(); + nonFullStack.insert(index); + if(!stacks[index].size()) nonEmptyStack.erase(index); + return ret; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1175-Prime-Arrangements/cpp-1175/CMakeLists.txt b/1001-1500/1175-Prime-Arrangements/cpp-1175/CMakeLists.txt new file mode 100644 index 00000000..afa8217d --- /dev/null +++ b/1001-1500/1175-Prime-Arrangements/cpp-1175/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1001-1500/1175-Prime-Arrangements/cpp-1175/main.cpp b/1001-1500/1175-Prime-Arrangements/cpp-1175/main.cpp new file mode 100644 index 00000000..b2069e82 --- /dev/null +++ b/1001-1500/1175-Prime-Arrangements/cpp-1175/main.cpp @@ -0,0 +1,59 @@ +/// Source : https://leetcode.com/problems/prime-arrangements/ +/// Author : liuyubobobo +/// Time : 2019-08-31 + +#include + +using namespace std; + + +/// Mathematics +/// Time Complexity: O(n*sqrt(n)) +/// Space Complexity: O(1) +class Solution { + +private: + long long MOD = 1e9 + 7; + +public: + int numPrimeArrangements(int n) { + + if(n <= 2) return 1; + + int primes = 1; + for(int i = 3; i <= n; i += 2) + primes += isprime(i); + return fac(primes) * fac(n - primes) % MOD; + } + +private: + bool isprime(int x){ + + if(x % 2 == 0) return true; + for(int i = 3; i * i <= x; i += 2) + if(x % i == 0) return false; + return true; + } + + long long fac(int n){ + long long res = 1ll; + for(long long i = 2ll; i <= n; i ++) + res = res * i % MOD; + return res; + } +}; + + +int main() { + + cout << Solution().numPrimeArrangements(5) << endl; + // 12 + + cout << Solution().numPrimeArrangements(100) << endl; + // 682289015 + + cout << Solution().numPrimeArrangements(2) << endl; + // 1 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1176-Diet-Plan-Performance/cpp-1176/CMakeLists.txt b/1001-1500/1176-Diet-Plan-Performance/cpp-1176/CMakeLists.txt new file mode 100644 index 00000000..3c6ea462 --- /dev/null +++ b/1001-1500/1176-Diet-Plan-Performance/cpp-1176/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1001-1500/1176-Diet-Plan-Performance/cpp-1176/main.cpp b/1001-1500/1176-Diet-Plan-Performance/cpp-1176/main.cpp new file mode 100644 index 00000000..900a2134 --- /dev/null +++ b/1001-1500/1176-Diet-Plan-Performance/cpp-1176/main.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/diet-plan-performance/ +/// Author : liuyubobobo +/// Time : 2019-08-31 + +#include +#include +#include + +using namespace std; + + +/// Sliding Window +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int dietPlanPerformance(vector& calories, int k, int lower, int upper) { + + int n = calories.size(); + int res = 0; + int cur = accumulate(calories.begin(), calories.begin() + (k - 1), 0); + for(int i = k - 1; i < n; i ++){ + cur += calories[i]; + if(cur < lower) res --; + else if(cur > upper) res ++; + cur -= calories[i - (k - 1)]; + } + return res; + } +}; + + +int main() { + + vector calories1 = {1,2,3,4,5}; + cout << Solution().dietPlanPerformance(calories1, 1, 3, 3) << endl; + // 0 + + vector calories2 = {3, 2}; + cout << Solution().dietPlanPerformance(calories2, 2, 0, 1) << endl; + // 1 + + vector calories3 = {6, 5, 0, 0}; + cout << Solution().dietPlanPerformance(calories3, 2, 1, 5) << endl; + // 0 + + vector calories4 = {6,13,8,7,10,1,12,11}; + cout << Solution().dietPlanPerformance(calories4, 6, 5, 37) << endl; + // 3 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1177-Can-Make-Palindrome-from-Substring/cpp-1177/CMakeLists.txt b/1001-1500/1177-Can-Make-Palindrome-from-Substring/cpp-1177/CMakeLists.txt new file mode 100644 index 00000000..a9faeff1 --- /dev/null +++ b/1001-1500/1177-Can-Make-Palindrome-from-Substring/cpp-1177/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1001-1500/1177-Can-Make-Palindrome-from-Substring/cpp-1177/main.cpp b/1001-1500/1177-Can-Make-Palindrome-from-Substring/cpp-1177/main.cpp new file mode 100644 index 00000000..c7faef03 --- /dev/null +++ b/1001-1500/1177-Can-Make-Palindrome-from-Substring/cpp-1177/main.cpp @@ -0,0 +1,59 @@ +/// Source : https://leetcode.com/problems/can-make-palindrome-from-substring/ +/// Author : liuyubobobo +/// Time : 2019-08-31 + +#include +#include +#include + +using namespace std; + + +/// Presum +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector canMakePaliQueries(string s, vector>& queries) { + vector> presum(s.size() + 1, vector(26, 0)); + for(int i = 0; i < s.size(); i ++){ + presum[i + 1] = presum[i]; + presum[i + 1][s[i] - 'a'] ++; + } + + vector res; + for(const vector& q: queries) + res.push_back(query(presum, q[0], q[1], q[2])); + return res; + } + +private: + bool query(const vector>& presum, int left, int right, int k){ + + vector freq(26, 0); + for(int i = 0; i < 26; i ++) + freq[i] = presum[right + 1][i] - presum[left][i]; +// for(int f: freq) cout << f << " "; cout << endl; + + int len = accumulate(freq.begin(), freq.end(), 0); + int res = 0; + for(int f: freq) + res += f % 2; + return (len % 2 ? res - 1 : res) / 2 <= k; + } +}; + + +void print_vec(const vector& vec){ + for(bool e: vec) cout << e << " "; cout << endl; +} + +int main() { + + string s = "abcda"; + vector> queries = {{3,3,0},{1,2,0},{0,3,1},{0,3,2},{0,4,1}}; + print_vec(Solution().canMakePaliQueries(s, queries)); + // 1 0 0 1 1 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1178-Number-of-Valid-Words-for-Each-Puzzle/cpp-1178/CMakeLists.txt b/1001-1500/1178-Number-of-Valid-Words-for-Each-Puzzle/cpp-1178/CMakeLists.txt new file mode 100644 index 00000000..bee29d53 --- /dev/null +++ b/1001-1500/1178-Number-of-Valid-Words-for-Each-Puzzle/cpp-1178/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main2.cpp) \ No newline at end of file diff --git a/1001-1500/1178-Number-of-Valid-Words-for-Each-Puzzle/cpp-1178/main.cpp b/1001-1500/1178-Number-of-Valid-Words-for-Each-Puzzle/cpp-1178/main.cpp new file mode 100644 index 00000000..e94043a1 --- /dev/null +++ b/1001-1500/1178-Number-of-Valid-Words-for-Each-Puzzle/cpp-1178/main.cpp @@ -0,0 +1,73 @@ +/// Source : https://leetcode.com/problems/number-of-valid-words-for-each-puzzle/ +/// Author : liuyubobobo +/// Time : 2019-08-31 + +#include +#include + +using namespace std; + + +/// Bit-Compression + Brute Force +/// Time Complexity: O(|words| * |puzzles|) +/// Space Complexity: O(|words|) +class Solution { + +private: + vector v; + +public: + vector findNumOfValidWords(vector& words, vector& puzzles) { + + for(const string& word: words){ + int hash = gethash(word); + int b = bitnum(hash); + if(b <= 7) v.push_back(hash); + } + + vector res; + for(const string& puzzle: puzzles){ + int hash = gethash(puzzle), r = 0; + for(int e: v) + if((e | hash) == hash && (e & (1 << (puzzle[0] - 'a')))) + r ++; + res.push_back(r); + } + return res; + } + +private: + int gethash(const string& s){ + int hash = 0; + for(char c: s) + hash |= (1 << (c - 'a')); + return hash; + } + + int bitnum(int hash){ + int res = 0; + for(int i = 0; i < 26; i ++) + res += ((hash & (1 << i)) != 0); + return res; + } +}; + + +void print_vec(const vector& vec){ + for(int e: vec) cout << e << " "; cout << endl; +} + +int main() { + + vector words1 = {"aaaa","asas","able","ability","actt","actor","access"}; + vector puzzles1 = {"aboveyz","abrodyz","abslute","absoryz","actresz","gaswxyz"}; + print_vec(Solution().findNumOfValidWords(words1, puzzles1)); + // 1,1,3,2,4,0 + + vector words2 = {"apple","pleas","please"}; + vector puzzles2 = {"aelwxyz","aelpxyz","aelpsxy","saelpxy","xaelpsy"}; + print_vec(Solution().findNumOfValidWords(words2, puzzles2)); + // 0,1,3,2,0 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1178-Number-of-Valid-Words-for-Each-Puzzle/cpp-1178/main2.cpp b/1001-1500/1178-Number-of-Valid-Words-for-Each-Puzzle/cpp-1178/main2.cpp new file mode 100644 index 00000000..1c1907da --- /dev/null +++ b/1001-1500/1178-Number-of-Valid-Words-for-Each-Puzzle/cpp-1178/main2.cpp @@ -0,0 +1,79 @@ +/// Source : https://leetcode.com/problems/number-of-valid-words-for-each-puzzle/ +/// Author : liuyubobobo +/// Time : 2019-08-31 + +#include +#include +#include + +using namespace std; + + +/// Bit-Compression +/// Because |puzzles[i]| == 7, we can iterate all possible combinations in puzzle[i] +/// Time Complexity: O(|words| + |puzzles|) +/// Space Complexity: O(|words|) +class Solution { + +private: + unordered_map freq; + +public: + vector findNumOfValidWords(vector& words, vector& puzzles) { + + for(const string& word: words){ + int hash = gethash(word); + int b = bitnum(hash); + if(b <= 7) freq[hash] ++; + } + + vector res; + for(const string& puzzle: puzzles){ + int r = 0; + for(int i = 64; i < 128; i ++){ + int hash = 0; + for(int j = 0; j < 7; j ++) + if(i & (1 << j)) + hash += (1 << (puzzle[6 - j] - 'a')); + r += freq[hash]; + } + res.push_back(r); + } + return res; + } + +private: + int gethash(const string& s){ + int hash = 0; + for(char c: s) + hash |= (1 << (c - 'a')); + return hash; + } + + int bitnum(int hash){ + int res = 0; + for(int i = 0; i < 26; i ++) + res += ((hash & (1 << i)) != 0); + return res; + } +}; + + +void print_vec(const vector& vec){ + for(int e: vec) cout << e << " "; cout << endl; +} + +int main() { + + vector words1 = {"aaaa","asas","able","ability","actt","actor","access"}; + vector puzzles1 = {"aboveyz","abrodyz","abslute","absoryz","actresz","gaswxyz"}; + print_vec(Solution().findNumOfValidWords(words1, puzzles1)); + // 1,1,3,2,4,0 + + vector words2 = {"apple","pleas","please"}; + vector puzzles2 = {"aelwxyz","aelpxyz","aelpsxy","saelpxy","xaelpsy"}; + print_vec(Solution().findNumOfValidWords(words2, puzzles2)); + // 0,1,3,2,0 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1180-Count-Substrings-with-Only-One-Distinct-Letter/cpp-1180/CMakeLists.txt b/1001-1500/1180-Count-Substrings-with-Only-One-Distinct-Letter/cpp-1180/CMakeLists.txt new file mode 100644 index 00000000..b1976006 --- /dev/null +++ b/1001-1500/1180-Count-Substrings-with-Only-One-Distinct-Letter/cpp-1180/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main2.cpp) \ No newline at end of file diff --git a/1001-1500/1180-Count-Substrings-with-Only-One-Distinct-Letter/cpp-1180/main.cpp b/1001-1500/1180-Count-Substrings-with-Only-One-Distinct-Letter/cpp-1180/main.cpp new file mode 100644 index 00000000..22aef5db --- /dev/null +++ b/1001-1500/1180-Count-Substrings-with-Only-One-Distinct-Letter/cpp-1180/main.cpp @@ -0,0 +1,39 @@ +/// Source : https://leetcode.com/problems/count-substrings-with-only-one-distinct-letter/ +/// Author : liuyubobobo +/// Time : 2019-09-07 + +#include + +using namespace std; + + +/// Split and Mathematics +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int countLetters(string S) { + + int res = 0; + for(int start = 0, i = start + 1; i <= S.size(); i ++) + if(i == S.size() || S[i] != S[start]){ + int n = i - start; + res += (1 + n) * n / 2; + start = i; + i = start; + } + return res; + } +}; + + +int main() { + + cout << Solution().countLetters("aaaba") << endl; + // 8 + + cout << Solution().countLetters("aaaaaaaaaa") << endl; + // 55 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1180-Count-Substrings-with-Only-One-Distinct-Letter/cpp-1180/main2.cpp b/1001-1500/1180-Count-Substrings-with-Only-One-Distinct-Letter/cpp-1180/main2.cpp new file mode 100644 index 00000000..1cd0c998 --- /dev/null +++ b/1001-1500/1180-Count-Substrings-with-Only-One-Distinct-Letter/cpp-1180/main2.cpp @@ -0,0 +1,36 @@ +/// Source : https://leetcode.com/problems/count-substrings-with-only-one-distinct-letter/ +/// Author : liuyubobobo +/// Time : 2019-09-07 + +#include +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int countLetters(string S) { + + vector res(S.size(), 1); + for(int i = 1; i < S.size(); i ++) + if(S[i] == S[i - 1]) res[i] += res[i - 1]; + return accumulate(res.begin(), res.end(), 0); + } +}; + + +int main() { + + cout << Solution().countLetters("aaaba") << endl; + // 8 + + cout << Solution().countLetters("aaaaaaaaaa") << endl; + // 55 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1181-Before-and-After-Puzzle/cpp-1181/CMakeLists.txt b/1001-1500/1181-Before-and-After-Puzzle/cpp-1181/CMakeLists.txt new file mode 100644 index 00000000..3c6ea462 --- /dev/null +++ b/1001-1500/1181-Before-and-After-Puzzle/cpp-1181/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1001-1500/1181-Before-and-After-Puzzle/cpp-1181/main.cpp b/1001-1500/1181-Before-and-After-Puzzle/cpp-1181/main.cpp new file mode 100644 index 00000000..bc974b0f --- /dev/null +++ b/1001-1500/1181-Before-and-After-Puzzle/cpp-1181/main.cpp @@ -0,0 +1,81 @@ +/// Source : https://leetcode.com/problems/before-and-after-puzzle/ +/// Author : liuyubobobo +/// Time : 2019-09-07 + +#include +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n^2 * (|s| + logn)) +/// Space Complexity: O(n * |s|) +class Solution { +public: + vector beforeAndAfterPuzzles(vector& phrases) { + + int n = phrases.size(); + + set res; + for(int i = 0; i < n; i ++) + for(int j = i + 1; j < n; j ++){ + string m = merge(phrases[i], phrases[j]); + if(m != "") res.insert(m); + m = merge(phrases[j], phrases[i]); + if(m != "") res.insert(m); + } + + return vector(res.begin(), res.end()); + } + +private: + string merge(const string& s1, const string& s2){ + + vector v1 = split(s1), v2 = split(s2); + if(v1.back() != v2[0]) return ""; + for(int i = 1; i < v2.size(); i ++) v1.push_back(v2[i]); + string res = v1[0]; + for(int i = 1; i < v1.size(); i ++) res += " " + v1[i]; + return res; + } + + vector split(const string& s){ + + vector res; + for(int start = 0, i = 1; i <= s.size(); i ++) + if(i == s.size() || s[i] == ' '){ + res.push_back(s.substr(start, i - start)); + start = i + 1; + i = start; + } + return res; + } +}; + + +void print_vec(const vector& vec){ + for(const string& e: vec) cout << e << endl; cout << endl; +} + +int main() { + + vector phrases1 = {"writing code","code rocks"}; + print_vec(Solution().beforeAndAfterPuzzles(phrases1)); + + cout << endl; + + vector phrases2 = {"mission statement", + "a quick bite to eat", + "a chip off the old block", + "chocolate bar", + "mission impossible", + "a man on a mission", + "block party", + "eat my words", + "bar of soap"}; + print_vec(Solution().beforeAndAfterPuzzles(phrases2)); + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1182-Shortest-Distance-to-Target-Color/cpp-1182/CMakeLists.txt b/1001-1500/1182-Shortest-Distance-to-Target-Color/cpp-1182/CMakeLists.txt new file mode 100644 index 00000000..70268b97 --- /dev/null +++ b/1001-1500/1182-Shortest-Distance-to-Target-Color/cpp-1182/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main2.cpp) \ No newline at end of file diff --git a/1001-1500/1182-Shortest-Distance-to-Target-Color/cpp-1182/main.cpp b/1001-1500/1182-Shortest-Distance-to-Target-Color/cpp-1182/main.cpp new file mode 100644 index 00000000..ebca3eb4 --- /dev/null +++ b/1001-1500/1182-Shortest-Distance-to-Target-Color/cpp-1182/main.cpp @@ -0,0 +1,68 @@ +/// Source : https://leetcode.com/problems/shortest-distance-to-target-color/ +/// Author : liuyubobobo +/// Time : 2019-09-07 + +#include +#include + +using namespace std; + + +/// Preprocess and Binary Search +/// Time Complexity: O(nlogn + q) +/// SpaceComplexity: O(n) +class Solution { +public: + vector shortestDistanceColor(vector& colors, vector>& queries) { + + int n = colors.size(); + + vector> forward = get(colors); + reverse(colors.begin(), colors.end()); + vector> backward = get(colors); + + vector res; + for(const vector& q: queries){ + int a = forward[q[1]][q[0]]; + int b = backward[q[1]][n - 1 - q[0]]; + if(a == -1) res.push_back(b); + else if(b == -1) res.push_back(a); + else res.push_back(min(a, b)); + } + return res; + } + +private: + vector> get(const vector& colors){ + + int n = colors.size(); + + vector> pos(4); + for(int i = 0; i < n; i ++) + pos[colors[i]].push_back(i); + + vector> res(4, vector(n, -1)); + for(int i = 0; i < n; i ++) + for(int color = 1; color <= 3; color ++){ + vector::iterator iter = lower_bound(pos[color].begin(), pos[color].end(), i); + if(iter != pos[color].end()) + res[color][i] = *iter - i; + } + return res; + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << " "; cout << endl; +} + +int main() { + + vector colors1 = {1,1,2,1,3,2,2,3,3}; + vector> queries1 = {{1, 3}, {2, 2}, {6, 1}}; + print_vec(Solution().shortestDistanceColor(colors1, queries1)); + // 3 0 3 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1182-Shortest-Distance-to-Target-Color/cpp-1182/main2.cpp b/1001-1500/1182-Shortest-Distance-to-Target-Color/cpp-1182/main2.cpp new file mode 100644 index 00000000..46ded7a0 --- /dev/null +++ b/1001-1500/1182-Shortest-Distance-to-Target-Color/cpp-1182/main2.cpp @@ -0,0 +1,59 @@ +/// Source : https://leetcode.com/problems/shortest-distance-to-target-color/ +/// Author : liuyubobobo +/// Time : 2019-09-07 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(n + q) +/// SpaceComplexity: O(n) +class Solution { +public: + vector shortestDistanceColor(vector& colors, vector>& queries) { + + int n = colors.size(); + + vector> forward(4, vector(n, -1)); + for(int color = 1; color <= 3; color ++) + for(int i = 0; i < n; i ++) + if(colors[i] == color) forward[color][i] = 0; + else if(i - 1 >= 0 && forward[color][i - 1] != -1) + forward[color][i] = forward[color][i - 1] + 1; + + vector> backward(4, vector(n, -1)); + for(int color = 1; color <= 3; color ++) + for(int i = n - 1; i >= 0; i --) + if(colors[i] == color) backward[color][i] = 0; + else if(i + 1 < n && backward[color][i + 1] != -1) + backward[color][i] = backward[color][i + 1] + 1; + + vector res; + for(const vector& q: queries){ + int a = forward[q[1]][q[0]]; + int b = backward[q[1]][q[0]]; + if(a == -1) res.push_back(b); + else if(b == -1) res.push_back(a); + else res.push_back(min(a, b)); + } + return res; + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << " "; cout << endl; +} + +int main() { + + vector colors1 = {1,1,2,1,3,2,2,3,3}; + vector> queries1 = {{1, 3}, {2, 2}, {6, 1}}; + print_vec(Solution().shortestDistanceColor(colors1, queries1)); + // 3 0 3 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1183-Maximum-Number-of-Ones/cpp-1183/CMakeLists.txt b/1001-1500/1183-Maximum-Number-of-Ones/cpp-1183/CMakeLists.txt new file mode 100644 index 00000000..89658265 --- /dev/null +++ b/1001-1500/1183-Maximum-Number-of-Ones/cpp-1183/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) \ No newline at end of file diff --git a/1001-1500/1183-Maximum-Number-of-Ones/cpp-1183/main.cpp b/1001-1500/1183-Maximum-Number-of-Ones/cpp-1183/main.cpp new file mode 100644 index 00000000..1364a2b5 --- /dev/null +++ b/1001-1500/1183-Maximum-Number-of-Ones/cpp-1183/main.cpp @@ -0,0 +1,45 @@ +/// Source : https://leetcode.com/problems/maximum-number-of-ones/ +/// Author : liuyubobobo +/// Time : 2019-09-07 + +#include +#include +#include + +using namespace std; + + +/// Mathematics +/// Time Complexity: O(width * height + (side ^ 2)log(side^2) + maxOnes) +/// Space Complexity: O((side ^ 2)log(side^2)) +class Solution { +public: + int maximumNumberOfOnes(int width, int height, int side, int maxOnes) { + + vector pattern(side * side, 0); + for(int i = 0; i < width; i ++) + for(int j = 0; j < height; j ++) + pattern[i % side * side + j % side] ++; + + sort(pattern.begin(), pattern.end(), greater()); + return accumulate(pattern.begin(), pattern.begin() + maxOnes, 0); + } +}; + + +int main() { + + cout << Solution().maximumNumberOfOnes(3, 3, 2, 1) << endl; + // 4 + + cout << Solution().maximumNumberOfOnes(3, 3, 2, 2) << endl; + // 6 + + cout << Solution().maximumNumberOfOnes(68, 86, 63, 1474) << endl; + // 3178 + + cout << Solution().maximumNumberOfOnes(86, 32, 3, 4) << endl; + // 1276 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1184-Distance-Between-Bus-Stops/cpp-1184/CMakeLists.txt b/1001-1500/1184-Distance-Between-Bus-Stops/cpp-1184/CMakeLists.txt new file mode 100644 index 00000000..afa8217d --- /dev/null +++ b/1001-1500/1184-Distance-Between-Bus-Stops/cpp-1184/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1001-1500/1184-Distance-Between-Bus-Stops/cpp-1184/main.cpp b/1001-1500/1184-Distance-Between-Bus-Stops/cpp-1184/main.cpp new file mode 100644 index 00000000..1ea0847e --- /dev/null +++ b/1001-1500/1184-Distance-Between-Bus-Stops/cpp-1184/main.cpp @@ -0,0 +1,43 @@ +/// Source : https://leetcode.com/problems/distance-between-bus-stops/ +/// Author : liuyubobobo +/// Time : 2019-09-07 + +#include +#include +#include + +using namespace std; + + +/// Mathematics +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int distanceBetweenBusStops(vector& distance, int start, int destination) { + + int sum = accumulate(distance.begin(), distance.end(), 0); + + if(start > destination) swap(start, destination); + int x = 0; + for(int i = start; i < destination; i ++) + x += distance[i]; + return min(x, sum - x); + } +}; + + +int main() { + + vector dis = {1, 2, 3, 4}; + cout << Solution().distanceBetweenBusStops(dis, 0, 1) << endl; + // 1 + + cout << Solution().distanceBetweenBusStops(dis, 0, 2) << endl; + // 3 + + cout << Solution().distanceBetweenBusStops(dis, 0, 3) << endl; + // 4 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1185-Day-of-the-Week/cpp-1185/CMakeLists.txt b/1001-1500/1185-Day-of-the-Week/cpp-1185/CMakeLists.txt new file mode 100644 index 00000000..8d6aa1b9 --- /dev/null +++ b/1001-1500/1185-Day-of-the-Week/cpp-1185/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(cpp_1185) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1185 main.cpp) \ No newline at end of file diff --git a/1001-1500/1185-Day-of-the-Week/cpp-1185/main.cpp b/1001-1500/1185-Day-of-the-Week/cpp-1185/main.cpp new file mode 100644 index 00000000..afe3ad63 --- /dev/null +++ b/1001-1500/1185-Day-of-the-Week/cpp-1185/main.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/day-of-the-week/ +/// Author : liuyubobobo +/// Time : 2019-09-08 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(year + month + day) +/// Space Complexity: O(1) +class Solution { +public: + string dayOfTheWeek(int day, int month, int year) { + + int x = 0; + for(int i = 1971; i < year; i ++) + if(isLeapYear(i)) x += 366; + else x += 365; + + vector months = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; + if(isLeapYear(year)) months[1] = 29; + for(int i = 1; i < month; i ++) x += months[i - 1]; + + x += day; + + string res[7] = {"Thursday", "Friday", "Saturday", "Sunday", "Monday", "Tuesday", "Wednesday"}; + return res[x % 7]; + } + +private: + bool isLeapYear(int year){ + return year % 400 == 0 || (year % 4 == 0 && year % 100 != 0); + } +}; + + +int main() { + + cout << Solution().dayOfTheWeek(31, 8, 2019) << endl; + // Saturday + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1186-Maximum-Subarray-Sum-with-One-Deletion/cpp-1186/CMakeLists.txt b/1001-1500/1186-Maximum-Subarray-Sum-with-One-Deletion/cpp-1186/CMakeLists.txt new file mode 100644 index 00000000..b170a313 --- /dev/null +++ b/1001-1500/1186-Maximum-Subarray-Sum-with-One-Deletion/cpp-1186/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main4.cpp) \ No newline at end of file diff --git a/1001-1500/1186-Maximum-Subarray-Sum-with-One-Deletion/cpp-1186/main.cpp b/1001-1500/1186-Maximum-Subarray-Sum-with-One-Deletion/cpp-1186/main.cpp new file mode 100644 index 00000000..858ed5a7 --- /dev/null +++ b/1001-1500/1186-Maximum-Subarray-Sum-with-One-Deletion/cpp-1186/main.cpp @@ -0,0 +1,63 @@ +/// Source : https://leetcode.com/problems/maximum-subarray-sum-with-one-deletion/ +/// Author : liuyubobobo +/// Time : 2019-09-08 + +#include +#include +#include + +using namespace std; + + +/// Forward and Backward Maximum Subarray +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int maximumSum(vector& arr) { + + int n = arr.size(); + if(n == 1) return arr[0]; + + vector dp1(n, 0); + dp1[0] = arr[0]; + for(int i = 1; i < n; i ++) + if(dp1[i - 1] <= 0) dp1[i] = arr[i]; + else dp1[i] = arr[i] + dp1[i - 1]; + + int res = *max_element(dp1.begin(), dp1.end()); + vector dp2(n, 0); + dp2[n - 1] = arr[n - 1]; + for(int i = n - 2; i >= 0; i --) { + if (dp2[i + 1] <= 0) dp2[i] = arr[i]; + else dp2[i] = arr[i] + dp2[i + 1]; + + if(i - 1 >= 0) + res = max(res, dp2[i + 1] + dp1[i - 1]); + } + + return res; + } +}; + + +int main() { + + vector arr1 = {1, -2, 0, 3}; + cout << Solution().maximumSum(arr1) << endl; + // 4 + + vector arr2 = {1, -2, -2, 3}; + cout << Solution().maximumSum(arr2) << endl; + // 3 + + vector arr3 = {-1, -1, -1, -1}; + cout << Solution().maximumSum(arr3) << endl; + // -1 + + vector arr4 = {8, -1, 6, -7, -4, 5, -4, 7, -6}; + cout << Solution().maximumSum(arr4) << endl; + // 17 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1186-Maximum-Subarray-Sum-with-One-Deletion/cpp-1186/main2.cpp b/1001-1500/1186-Maximum-Subarray-Sum-with-One-Deletion/cpp-1186/main2.cpp new file mode 100644 index 00000000..f44f3852 --- /dev/null +++ b/1001-1500/1186-Maximum-Subarray-Sum-with-One-Deletion/cpp-1186/main2.cpp @@ -0,0 +1,62 @@ +/// Source : https://leetcode.com/problems/maximum-subarray-sum-with-one-deletion/ +/// Author : liuyubobobo +/// Time : 2019-09-07 + +#include +#include +#include + +using namespace std; + + +/// Two Pass DP, dropped and nondropped +/// Nondropped is Maximum Subarray Problem +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int maximumSum(vector& arr) { + + int n = arr.size(); + if(n == 1) return arr[0]; + + vector undropped(n, 0); + undropped[0] = arr[0]; + for(int i = 1; i < n; i ++) + if(undropped[i - 1] <= 0) undropped[i] = arr[i]; + else undropped[i] = arr[i] + undropped[i - 1]; +// cout << "dp1 : "; for(int e: dp1) cout << e << " "; cout << endl; + + int res = *max_element(undropped.begin(), undropped.end()); + vector dropped(n, 0); + dropped[1] = arr[1]; + for(int i = 2; i < n; i ++) + dropped[i] = max(arr[i] + dropped[i - 1], arr[i] + undropped[i - 2]); +// cout << "dp2 : "; for(int e: dp2) cout << e << " "; cout << endl; + + res = max(res, *max_element(dropped.begin() + 1, dropped.end())); + return res; + } +}; + + +int main() { + + vector arr1 = {1, -2, 0, 3}; + cout << Solution().maximumSum(arr1) << endl; + // 4 + + vector arr2 = {1, -2, -2, 3}; + cout << Solution().maximumSum(arr2) << endl; + // 3 + + vector arr3 = {-1, -1, -1, -1}; + cout << Solution().maximumSum(arr3) << endl; + // -1 + + vector arr4 = {8, -1, 6, -7, -4, 5, -4, 7, -6}; + cout << Solution().maximumSum(arr4) << endl; + // 17 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1186-Maximum-Subarray-Sum-with-One-Deletion/cpp-1186/main3.cpp b/1001-1500/1186-Maximum-Subarray-Sum-with-One-Deletion/cpp-1186/main3.cpp new file mode 100644 index 00000000..6f977c6c --- /dev/null +++ b/1001-1500/1186-Maximum-Subarray-Sum-with-One-Deletion/cpp-1186/main3.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/maximum-subarray-sum-with-one-deletion/ +/// Author : liuyubobobo +/// Time : 2019-09-11 + +#include +#include + +using namespace std; + + +/// Dropped and nondropped DP, make two pass in one pass +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int maximumSum(vector& arr) { + + int n = arr.size(); + if(n == 1) return arr[0]; + + vector undropped(n, 0), dropped(n, 0); + undropped[0] = arr[0], undropped[1] = max(arr[0] + arr[1], arr[1]); + dropped[1] = max(arr[0], arr[1]); + int res = max(undropped[1], dropped[1]); + for(int i = 2; i < n; i ++){ + if(undropped[i - 1] <= 0) undropped[i] = arr[i]; + else undropped[i] = arr[i] + undropped[i - 1]; + res = max(res, undropped[i]); + + dropped[i] = max(undropped[i - 1], dropped[i - 1] + arr[i]); + res = max(res, dropped[i]); + } + return res; + } +}; + + +int main() { + + vector arr1 = {1, -2, 0, 3}; + cout << Solution().maximumSum(arr1) << endl; + // 4 + + vector arr2 = {1, -2, -2, 3}; + cout << Solution().maximumSum(arr2) << endl; + // 3 + + vector arr3 = {-1, -1, -1, -1}; + cout << Solution().maximumSum(arr3) << endl; + // -1 + + vector arr4 = {8, -1, 6, -7, -4, 5, -4, 7, -6}; + cout << Solution().maximumSum(arr4) << endl; + // 17 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1186-Maximum-Subarray-Sum-with-One-Deletion/cpp-1186/main4.cpp b/1001-1500/1186-Maximum-Subarray-Sum-with-One-Deletion/cpp-1186/main4.cpp new file mode 100644 index 00000000..4aa1c2e2 --- /dev/null +++ b/1001-1500/1186-Maximum-Subarray-Sum-with-One-Deletion/cpp-1186/main4.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/maximum-subarray-sum-with-one-deletion/ +/// Author : liuyubobobo +/// Time : 2019-09-11 + +#include +#include + +using namespace std; + + +/// Dropped and nondropped DP, make two pass in one pass +/// Optimized in O(1) space; +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int maximumSum(vector& arr) { + + int n = arr.size(); + if(n == 1) return arr[0]; + + int undropped = max(arr[0] + arr[1], arr[1]); + int dropped = max(arr[0], arr[1]); + int res = max(undropped, dropped); + for(int i = 2; i < n; i ++){ + dropped = max(undropped, dropped + arr[i]); + res = max(res, dropped); + + if(undropped <= 0) undropped = arr[i]; + else undropped = arr[i] + undropped; + res = max(res, undropped); + } + return res; + } +}; + + +int main() { + + vector arr1 = {1, -2, 0, 3}; + cout << Solution().maximumSum(arr1) << endl; + // 4 + + vector arr2 = {1, -2, -2, 3}; + cout << Solution().maximumSum(arr2) << endl; + // 3 + + vector arr3 = {-1, -1, -1, -1}; + cout << Solution().maximumSum(arr3) << endl; + // -1 + + vector arr4 = {8, -1, 6, -7, -4, 5, -4, 7, -6}; + cout << Solution().maximumSum(arr4) << endl; + // 17 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1187-Make-Array-Strictly-Increasing/cpp-1187/CMakeLists.txt b/1001-1500/1187-Make-Array-Strictly-Increasing/cpp-1187/CMakeLists.txt new file mode 100644 index 00000000..bee29d53 --- /dev/null +++ b/1001-1500/1187-Make-Array-Strictly-Increasing/cpp-1187/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main2.cpp) \ No newline at end of file diff --git a/1001-1500/1187-Make-Array-Strictly-Increasing/cpp-1187/main.cpp b/1001-1500/1187-Make-Array-Strictly-Increasing/cpp-1187/main.cpp new file mode 100644 index 00000000..160d7d7a --- /dev/null +++ b/1001-1500/1187-Make-Array-Strictly-Increasing/cpp-1187/main.cpp @@ -0,0 +1,68 @@ +/// Source : https://leetcode.com/problems/make-array-strictly-increasing/ +/// Author : liuyubobobo +/// Time : 2019-09-07 + +#include +#include +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(n*m*logm) +/// Space Complexity: O(n*m) +class Solution { + +private: + map, int> dp; + +public: + int makeArrayIncreasing(vector& arr1, vector& arr2) { + + set set; + for(int e: arr2) set.insert(e); + + int res = go(arr1, vector(set.begin(), set.end()), 0, -1); + return res == INT_MAX ? -1 : res; + } + +private: + int go(const vector& arr1, const vector& arr2, int index, int last){ + + if(index == arr1.size()) return 0; + pair hash = make_pair(index, last); + if(dp.count(hash)) return dp[hash]; + + int res = INT_MAX; + if(arr1[index] > last) res = min(res, go(arr1, arr2, index + 1, arr1[index])); + + vector::const_iterator iter = upper_bound(arr2.begin(), arr2.end(), last); + if(iter != arr2.end()){ + int i = iter - arr2.begin(); + int t = go(arr1, arr2, index + 1, arr2[i]); + if(t != INT_MAX) + res = min(res, 1 + t); + } + + return dp[hash] = res; + } +}; + + +int main() { + + vector a1 = {1, 5, 3, 6, 7}, b1 = {1, 3, 2, 4}; + cout << Solution().makeArrayIncreasing(a1, b1) << endl; + // 1 + + vector a2 = {1, 5, 3, 6, 7}, b2 = {4, 3, 1}; + cout << Solution().makeArrayIncreasing(a2, b2) << endl; + // 2 + + vector a3 = {1, 5, 3, 6, 7}, b3 = {1, 6, 3, 3}; + cout << Solution().makeArrayIncreasing(a3, b3) << endl; + // -1 + return 0; +} \ No newline at end of file diff --git a/1001-1500/1187-Make-Array-Strictly-Increasing/cpp-1187/main2.cpp b/1001-1500/1187-Make-Array-Strictly-Increasing/cpp-1187/main2.cpp new file mode 100644 index 00000000..83895759 --- /dev/null +++ b/1001-1500/1187-Make-Array-Strictly-Increasing/cpp-1187/main2.cpp @@ -0,0 +1,73 @@ +/// Source : https://leetcode.com/problems/make-array-strictly-increasing/ +/// Author : liuyubobobo +/// Time : 2019-09-07 + +#include +#include +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(n*m*logm) +/// Space Complexity: O(n*m) +class Solution { + +private: + int MAX; + +public: + int makeArrayIncreasing(vector& arr1, vector& arr2) { + + set set; + for(int e: arr2) set.insert(e); + + arr2 = vector(set.begin(), set.end()); + MAX = arr2.size() + 1; + + vector> dp(arr1.size(), vector(arr2.size() + 1, -1)); + int res = go(arr1, arr2, 0, 0, dp); + for(int j = 0; j < arr2.size(); j ++) + res = min(res, (arr1[0] != arr2[0]) + go(arr1, arr2, 0, j + 1, dp)); + return res >= MAX ? -1 : res; + } + +private: + int go(const vector& arr1, const vector& arr2, int i, int j, + vector>& dp){ + + if(i + 1 == arr1.size()) return 0; + if(dp[i][j] != -1) return dp[i][j]; + + int last = j == 0 ? arr1[i] : arr2[j - 1]; + int res = MAX; + if(arr1[i + 1] > last) + res = min(res, go(arr1, arr2, i + 1, 0, dp)); + + vector::const_iterator iter = upper_bound(arr2.begin(), arr2.end(), last); + if(iter != arr2.end()){ + int jj = iter - arr2.begin(); + res = min(res, 1 + go(arr1, arr2, i + 1, jj + 1, dp)); + } + return dp[i][j] = res; + } +}; + + +int main() { + + vector a1 = {1, 5, 3, 6, 7}, b1 = {1, 3, 2, 4}; + cout << Solution().makeArrayIncreasing(a1, b1) << endl; + // 1 + + vector a2 = {1, 5, 3, 6, 7}, b2 = {4, 3, 1}; + cout << Solution().makeArrayIncreasing(a2, b2) << endl; + // 2 + + vector a3 = {1, 5, 3, 6, 7}, b3 = {1, 6, 3, 3}; + cout << Solution().makeArrayIncreasing(a3, b3) << endl; + // -1 + return 0; +} \ No newline at end of file diff --git a/1001-1500/1189-Maximum-Number-of-Balloons/cpp-1189/CMakeLists.txt b/1001-1500/1189-Maximum-Number-of-Balloons/cpp-1189/CMakeLists.txt new file mode 100644 index 00000000..afa8217d --- /dev/null +++ b/1001-1500/1189-Maximum-Number-of-Balloons/cpp-1189/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1001-1500/1189-Maximum-Number-of-Balloons/cpp-1189/main.cpp b/1001-1500/1189-Maximum-Number-of-Balloons/cpp-1189/main.cpp new file mode 100644 index 00000000..86e8b611 --- /dev/null +++ b/1001-1500/1189-Maximum-Number-of-Balloons/cpp-1189/main.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/maximum-number-of-balloons/ +/// Author : liuyubobobo +/// Time : 2019-09-14 + +#include +#include + +using namespace std; + + +/// HashMap Counting +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int maxNumberOfBalloons(string text) { + + vector freq(26, 0); + for(char c: text) freq[c - 'a'] ++; + + int res = freq['b' - 'a']; + res = min(res, freq['a' - 'a']); + res = min(res, freq['l' - 'a'] / 2); + res = min(res, freq['o' - 'a'] / 2); + res = min(res, freq['n' - 'a']); + return res; + } +}; + + +int main() { + + cout << Solution().maxNumberOfBalloons("loonbalxballpoon") << endl; + // 2 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1190-Reverse-Substrings-Between-Each-Pair-of-Parentheses/cpp-1190/CMakeLists.txt b/1001-1500/1190-Reverse-Substrings-Between-Each-Pair-of-Parentheses/cpp-1190/CMakeLists.txt new file mode 100644 index 00000000..7f3bfb51 --- /dev/null +++ b/1001-1500/1190-Reverse-Substrings-Between-Each-Pair-of-Parentheses/cpp-1190/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main2.cpp) \ No newline at end of file diff --git a/1001-1500/1190-Reverse-Substrings-Between-Each-Pair-of-Parentheses/cpp-1190/main.cpp b/1001-1500/1190-Reverse-Substrings-Between-Each-Pair-of-Parentheses/cpp-1190/main.cpp new file mode 100644 index 00000000..ae7b0f10 --- /dev/null +++ b/1001-1500/1190-Reverse-Substrings-Between-Each-Pair-of-Parentheses/cpp-1190/main.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/reverse-substrings-between-each-pair-of-parentheses/ +/// Author : liuyubobobo +/// Time : 2019-09-14 + +#include +#include + +using namespace std; + + +/// Using Stack +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { +public: + string reverseParentheses(string s) { + + string p = "", res = ""; + stack stack; + for(int i = 0; i < s.size(); i ++) + if(s[i] == ')'){ +// cout << stack.top() << endl; + string t = p.substr(stack.top() + 1); + reverse(t.begin(), t.end()); + p = p.substr(0, p.size() - (t.size() + 1)); + p += t; + stack.pop(); + } + else{ + p += s[i]; + if(s[i] == '(') stack.push(p.size() - 1); + } + return p; + } +}; + + +int main() { + + cout << Solution().reverseParentheses("(abcd)") << endl; + // dcba + + cout << Solution().reverseParentheses("(u(love)i)") << endl; + // iloveu + + cout << Solution().reverseParentheses("(ed(et(oc))el)") << endl; + // leetcode + + cout << Solution().reverseParentheses("a(bcdefghijkl(mno)p)q") << endl; + // apmnolkjihgfedcbq + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1190-Reverse-Substrings-Between-Each-Pair-of-Parentheses/cpp-1190/main2.cpp b/1001-1500/1190-Reverse-Substrings-Between-Each-Pair-of-Parentheses/cpp-1190/main2.cpp new file mode 100644 index 00000000..3978adbb --- /dev/null +++ b/1001-1500/1190-Reverse-Substrings-Between-Each-Pair-of-Parentheses/cpp-1190/main2.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/reverse-substrings-between-each-pair-of-parentheses/ +/// Author : liuyubobobo +/// Time : 2019-09-15 + +#include +#include + +using namespace std; + + +/// Recursion +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { +public: + string reverseParentheses(string s) { + + int start; + for(int i = 0; i < s.size(); i ++) + if(s[i] == '(') start = i; + else if(s[i] == ')'){ + string t = s.substr(start + 1, i - (start + 1)); + reverse(t.begin(), t.end()); + return reverseParentheses(s.substr(0, start) + t + s.substr(i + 1)); + } + return s; + } +}; + + +int main() { + + cout << Solution().reverseParentheses("(abcd)") << endl; + // dcba + + cout << Solution().reverseParentheses("(u(love)i)") << endl; + // iloveu + + cout << Solution().reverseParentheses("(ed(et(oc))el)") << endl; + // leetcode + + cout << Solution().reverseParentheses("a(bcdefghijkl(mno)p)q") << endl; + // apmnolkjihgfedcbq + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1191-K-Concatenation-Maximum-Sum/cpp-1191/CMakeLists.txt b/1001-1500/1191-K-Concatenation-Maximum-Sum/cpp-1191/CMakeLists.txt new file mode 100644 index 00000000..a9faeff1 --- /dev/null +++ b/1001-1500/1191-K-Concatenation-Maximum-Sum/cpp-1191/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1001-1500/1191-K-Concatenation-Maximum-Sum/cpp-1191/main.cpp b/1001-1500/1191-K-Concatenation-Maximum-Sum/cpp-1191/main.cpp new file mode 100644 index 00000000..77e8e47a --- /dev/null +++ b/1001-1500/1191-K-Concatenation-Maximum-Sum/cpp-1191/main.cpp @@ -0,0 +1,86 @@ +/// Source : https://leetcode.com/problems/k-concatenation-maximum-sum/ +/// Author : liuyubobobo +/// Time : 2019-09-14 + +#include +#include +#include + +using namespace std; + + +/// Max Subarrray Problem + Presum +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +private: + long long MOD = 1e9 + 7; + +public: + int kConcatenationMaxSum(vector& arr, int k) { + + long long res = max(max_subarray(arr), 0); + if(k == 1) return res % MOD; + + vector psum(arr.size(), arr[0]), max_psum(arr.size(), arr[0]); + for(int i = 1; i < arr.size(); i ++) + psum[i] = psum[i - 1] + arr[i], + max_psum[i] = max(max_psum[i - 1], psum[i]); + + vector ssum(arr.size(), arr.back()), max_ssum(arr.size(), arr.back()); + for(int i = (int)arr.size() - 2; i >= 0; i --) + ssum[i] = ssum[i + 1] + arr[i], + max_ssum[i] = max(max_ssum[i + 1], ssum[i]); + + long long sum = accumulate(arr.begin(), arr.end(), 0); + for(int i = 1; i + 1 < arr.size(); i ++){ + long long t = max_psum[i - 1] + max_ssum[i + 1]; + res = max(res, t); + } + + if(sum > 0) { + res = max(res, sum * k); + res = max(res, (long long) max(0, *max_element(ssum.begin(), ssum.end())) + + sum * (long long) (k - 2) + + (long long) max(0, *max_element(psum.begin(), psum.end()))); + } + return res % MOD; + } + +private: + int max_subarray(const vector& arr){ + + vector dp(arr.size(), arr[0]); + for(int i = 1; i < arr.size(); i ++) + if(dp[i - 1] < 0) dp[i] = arr[i]; + else dp[i] = dp[i - 1] + arr[i]; + return *max_element(dp.begin(), dp.end()); + } +}; + + +int main() { + + vector arr1 = {1, 2}; + cout << Solution().kConcatenationMaxSum(arr1, 3) << endl; + // 9 + + vector arr2 = {1, -2, 1}; + cout << Solution().kConcatenationMaxSum(arr2, 5) << endl; + // 2 + + vector arr3 = {-1, -2}; + cout << Solution().kConcatenationMaxSum(arr3, 7) << endl; + // 0 + + vector arr4 = {-5, 4, -4, -3, 5, -3}; + cout << Solution().kConcatenationMaxSum(arr4, 3) << endl; + // 5 + + vector arr5 = {-5, -2, 0, 0, 3, 9, -2, -5, 4}; + cout << Solution().kConcatenationMaxSum(arr5, 5) << endl; + // 20 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1192-Critical-Connections-in-a-Network/cpp-1192/CMakeLists.txt b/1001-1500/1192-Critical-Connections-in-a-Network/cpp-1192/CMakeLists.txt new file mode 100644 index 00000000..89658265 --- /dev/null +++ b/1001-1500/1192-Critical-Connections-in-a-Network/cpp-1192/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) \ No newline at end of file diff --git a/1001-1500/1192-Critical-Connections-in-a-Network/cpp-1192/main.cpp b/1001-1500/1192-Critical-Connections-in-a-Network/cpp-1192/main.cpp new file mode 100644 index 00000000..104de1e2 --- /dev/null +++ b/1001-1500/1192-Critical-Connections-in-a-Network/cpp-1192/main.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/critical-connections-in-a-network/ +/// Author : liuyubobobo +/// Time : 2019-09-14 + +#include +#include +#include + +using namespace std; + + +/// Finding Bridge Algorithm (Cut-Edge) +/// Time Complexity: O(V+E) +/// Space Complexity: O(V) +class Solution { + +private: + vector> res; + vector order, low; + int cnt = 0; + +public: + vector> criticalConnections(int n, vector>& connections) { + + vector> g(n); + for(const vector& e: connections) + g[e[0]].insert(e[1]), g[e[1]].insert(e[0]); + + order.resize(n, -1); + low.resize(n, -1); + cnt = 0; + dfs(g, 0, -1); + return res; + } + +private: + void dfs(const vector>& g, int v, int parent){ + + order[v] = cnt ++; + low[v] = order[v]; + for(int w: g[v]) + if(order[w] == -1){ + dfs(g, w, v); + low[v] = min(low[v], low[w]); + if(low[w] > order[v]) + res.push_back({v, w}); + } + else if(w != parent) + low[v] = min(low[v], low[w]); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1196-How-Many-Apples-Can-You-Put-into-the-Basket/cpp-1196/CMakeLists.txt b/1001-1500/1196-How-Many-Apples-Can-You-Put-into-the-Basket/cpp-1196/CMakeLists.txt new file mode 100644 index 00000000..8c857ca0 --- /dev/null +++ b/1001-1500/1196-How-Many-Apples-Can-You-Put-into-the-Basket/cpp-1196/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(cpp_1196) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1196 main3.cpp) \ No newline at end of file diff --git a/1001-1500/1196-How-Many-Apples-Can-You-Put-into-the-Basket/cpp-1196/main.cpp b/1001-1500/1196-How-Many-Apples-Can-You-Put-into-the-Basket/cpp-1196/main.cpp new file mode 100644 index 00000000..72657431 --- /dev/null +++ b/1001-1500/1196-How-Many-Apples-Can-You-Put-into-the-Basket/cpp-1196/main.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/how-many-apples-can-you-put-into-the-basket/ +/// Author : liuyubobobo +/// Time : 2019-09-21 + +#include +#include + +using namespace std; + + +/// Dynamic Progrramming +/// Time Complexity: O(5000n) +/// Space Complexity: O(5000n) +class Solution { +public: + int maxNumberOfApples(vector& arr) { + + vector> dp(arr.size(), vector(5001, 0)); + for(int j = arr[0]; j <= 5000; j ++) + dp[0][j] = 1; + for(int i = 1; i < arr.size(); i ++){ + for(int j = 0; j < arr[i]; j ++) + dp[i][j] = dp[i - 1][j]; + for(int j = arr[i]; j <= 5000; j ++) + dp[i][j] = max(dp[i - 1][j], 1 + dp[i - 1][j - arr[i]]); + } + return *max_element(dp.back().begin(), dp.back().end()); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1196-How-Many-Apples-Can-You-Put-into-the-Basket/cpp-1196/main2.cpp b/1001-1500/1196-How-Many-Apples-Can-You-Put-into-the-Basket/cpp-1196/main2.cpp new file mode 100644 index 00000000..07d91ce0 --- /dev/null +++ b/1001-1500/1196-How-Many-Apples-Can-You-Put-into-the-Basket/cpp-1196/main2.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/how-many-apples-can-you-put-into-the-basket/ +/// Author : liuyubobobo +/// Time : 2019-09-21 + +#include +#include + +using namespace std; + + +/// Dynamic Progrramming with Space Optimization +/// Time Complexity: O(5000n) +/// Space Complexity: O(n) +class Solution { +public: + int maxNumberOfApples(vector& arr) { + + vector dp(5001, 0); + for(int j = arr[0]; j <= 5000; j ++) + dp[j] = 1; + for(int i = 1; i < arr.size(); i ++){ + vector dp2 = dp; + for(int j = arr[i]; j <= 5000; j ++) + dp2[j] = max(dp[j], 1 + dp[j - arr[i]]); + dp = dp2; + } + return *max_element(dp.begin(), dp.end()); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1196-How-Many-Apples-Can-You-Put-into-the-Basket/cpp-1196/main3.cpp b/1001-1500/1196-How-Many-Apples-Can-You-Put-into-the-Basket/cpp-1196/main3.cpp new file mode 100644 index 00000000..3b8d442f --- /dev/null +++ b/1001-1500/1196-How-Many-Apples-Can-You-Put-into-the-Basket/cpp-1196/main3.cpp @@ -0,0 +1,36 @@ +/// Source : https://leetcode.com/problems/how-many-apples-can-you-put-into-the-basket/ +/// Author : liuyubobobo +/// Time : 2019-09-21 + +#include +#include + +using namespace std; + + +/// Dynamic Progrramming with Space Optimization +/// Time Complexity: O(5000n) +/// Space Complexity: O(n) +class Solution { +public: + int maxNumberOfApples(vector& arr) { + + int n = arr.size(); + vector> dp(2, vector(5001, 0)); + for(int j = arr[0]; j <= 5000; j ++) + dp[0][j] = 1; + for(int i = 1; i < n; i ++){ + for(int j = 0; j < arr[i]; j ++) + dp[i & 1][j] = dp[(i - 1) & 1][j]; + for(int j = arr[i]; j <= 5000; j ++) + dp[i & 1][j] = max(dp[(i - 1) & 1][j], 1 + dp[(i - 1) & 1][j - arr[i]]); + } + return *max_element(dp[(n - 1) & 1].begin(), dp[(n - 1) & 1].end()); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1197-Minimum-Knight-Moves/cpp-1197/CMakeLists.txt b/1001-1500/1197-Minimum-Knight-Moves/cpp-1197/CMakeLists.txt new file mode 100644 index 00000000..613240cc --- /dev/null +++ b/1001-1500/1197-Minimum-Knight-Moves/cpp-1197/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(cpp_1197) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1197 main.cpp) \ No newline at end of file diff --git a/1001-1500/1197-Minimum-Knight-Moves/cpp-1197/main.cpp b/1001-1500/1197-Minimum-Knight-Moves/cpp-1197/main.cpp new file mode 100644 index 00000000..54212dcf --- /dev/null +++ b/1001-1500/1197-Minimum-Knight-Moves/cpp-1197/main.cpp @@ -0,0 +1,55 @@ +/// Source : https://leetcode.com/problems/minimum-knight-moves/ +/// Author : liuyubobobo +/// Time : 2019-09-21 + +#include +#include +#include + +using namespace std; + + +/// BFS +/// Time Complexity: O(|x| * |y|) +/// Space Complexity: O(|x| * |y|) +class Solution { + +private: + const int dirs[8][2] = {{1, 2}, {1, -2}, {-1, 2}, {-1, -2}, + {2, 1}, {2, -1}, {-2, 1}, {-2, -1}}; + +public: + int minKnightMoves(int x, int y) { + + x = abs(x), y = abs(y); + map, int> map; + map[make_pair(0, 0)] = 0; + queue> q; + q.push(make_pair(0, 0)); + + while(!q.empty()){ + pair cur = q.front(); + q.pop(); + if(cur.first == x && cur.second == y) return map[cur]; + + for(int d = 0; d < 8; d ++){ + int nextx = cur.first + dirs[d][0], nexty = cur.second + dirs[d][1]; + pair next = make_pair(nextx, nexty); + if(in_area(nextx, nexty, x, y) && !map.count(next)) + map[next] = map[cur] + 1, q.push(next); + } + } + return -1; + } + +private: + bool in_area(int x, int y, int X, int Y){ + return -5 <= x && x <= X + 5 && -5 <= y && y <= Y + 5; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1198-Find-Smallest-Common-Element-in-All-Rows/cpp-1198/CMakeLists.txt b/1001-1500/1198-Find-Smallest-Common-Element-in-All-Rows/cpp-1198/CMakeLists.txt new file mode 100644 index 00000000..8046473e --- /dev/null +++ b/1001-1500/1198-Find-Smallest-Common-Element-in-All-Rows/cpp-1198/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(cpp_1198) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1198 main4.cpp) \ No newline at end of file diff --git a/1001-1500/1198-Find-Smallest-Common-Element-in-All-Rows/cpp-1198/main.cpp b/1001-1500/1198-Find-Smallest-Common-Element-in-All-Rows/cpp-1198/main.cpp new file mode 100644 index 00000000..29afae99 --- /dev/null +++ b/1001-1500/1198-Find-Smallest-Common-Element-in-All-Rows/cpp-1198/main.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/find-smallest-common-element-in-all-rows/ +/// Author : liuyubobobo +/// Time : 2019-09-21 + +#include +#include +#include + +using namespace std; + + +/// Using TreeSet +/// Time Complexity: O(m * n * log m * n) +/// Space Complexity: O(m * n) +class Solution { +public: + int smallestCommonElement(vector>& mat) { + + set set1; + for(int e: mat[0]) set1.insert(e); + + for(int i = 1; i < mat.size(); i ++){ + + set set2; + for(int e: mat[i]) if(set1.count(e)) set2.insert(e); + set1 = set2; + } + + return set1.size() ? *set1.begin() : -1; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1198-Find-Smallest-Common-Element-in-All-Rows/cpp-1198/main2.cpp b/1001-1500/1198-Find-Smallest-Common-Element-in-All-Rows/cpp-1198/main2.cpp new file mode 100644 index 00000000..153e5d1f --- /dev/null +++ b/1001-1500/1198-Find-Smallest-Common-Element-in-All-Rows/cpp-1198/main2.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/find-smallest-common-element-in-all-rows/ +/// Author : liuyubobobo +/// Time : 2019-09-21 + +#include +#include +#include + +using namespace std; + + +/// Using HashSet +/// Time Complexity: O(m * n) +/// Space Complexity: O(m * n) +class Solution { +public: + int smallestCommonElement(vector>& mat) { + + unordered_set set1; + for(int e: mat[0]) set1.insert(e); + + for(int i = 1; i < mat.size(); i ++){ + + unordered_set set2; + for(int e: mat[i]) if(set1.count(e)) set2.insert(e); + set1 = set2; + } + + return set1.size() ? *min_element(set1.begin(), set1.end()) : -1; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1198-Find-Smallest-Common-Element-in-All-Rows/cpp-1198/main3.cpp b/1001-1500/1198-Find-Smallest-Common-Element-in-All-Rows/cpp-1198/main3.cpp new file mode 100644 index 00000000..2c5597a9 --- /dev/null +++ b/1001-1500/1198-Find-Smallest-Common-Element-in-All-Rows/cpp-1198/main3.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/find-smallest-common-element-in-all-rows/ +/// Author : liuyubobobo +/// Time : 2019-09-21 + +#include +#include +#include + +using namespace std; + + +/// Brute Force Count +/// Time Complexity: O(m * n) +/// Space Complexity: O(max(value)) +class Solution { +public: + int smallestCommonElement(vector>& mat) { + + vector cnt(10001, 0); + for(int i = 0; i < mat.size(); i ++) + for(int j = 0; j < mat[i].size(); j ++){ + cnt[mat[i][j]] ++; + if(cnt[mat[i][j]] == mat.size()) return mat[i][j]; + } + return -1; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1198-Find-Smallest-Common-Element-in-All-Rows/cpp-1198/main4.cpp b/1001-1500/1198-Find-Smallest-Common-Element-in-All-Rows/cpp-1198/main4.cpp new file mode 100644 index 00000000..39817984 --- /dev/null +++ b/1001-1500/1198-Find-Smallest-Common-Element-in-All-Rows/cpp-1198/main4.cpp @@ -0,0 +1,42 @@ +/// Source : https://leetcode.com/problems/find-smallest-common-element-in-all-rows/ +/// Author : liuyubobobo +/// Time : 2019-09-21 + +#include +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(m * n * log m * n) +/// Space Complexity: O(1) +class Solution { +public: + int smallestCommonElement(vector>& mat) { + + for(int e: mat[0]){ + + int i; + for(i = 1; i < mat.size(); i ++){ + vector::const_iterator iter = lower_bound(mat[i].begin(), mat[i].end(), e); + if(iter == mat[i].end() || *iter != e) break; + } + + if(i == mat.size()) return e; + } + return -1; + } +}; + + +int main() { + + vector> mat1 = { + {1,2,3,4,5},{2,4,5,8,10},{3,5,7,9,11},{1,3,5,7,9} + }; + cout << Solution().smallestCommonElement(mat1) << endl; + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1199-Minimum-Time-to-Build-Blocks/cpp-1199/CMakeLists.txt b/1001-1500/1199-Minimum-Time-to-Build-Blocks/cpp-1199/CMakeLists.txt new file mode 100644 index 00000000..ce8794cb --- /dev/null +++ b/1001-1500/1199-Minimum-Time-to-Build-Blocks/cpp-1199/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(cpp_1199) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1199 main.cpp) \ No newline at end of file diff --git a/1001-1500/1199-Minimum-Time-to-Build-Blocks/cpp-1199/main.cpp b/1001-1500/1199-Minimum-Time-to-Build-Blocks/cpp-1199/main.cpp new file mode 100644 index 00000000..0817aa98 --- /dev/null +++ b/1001-1500/1199-Minimum-Time-to-Build-Blocks/cpp-1199/main.cpp @@ -0,0 +1,51 @@ +/// Source : https://leetcode.com/problems/minimum-time-to-build-blocks/ +/// Author : liuyubobobo +/// Time : 2019-09-21 + +#include +#include +#include + +using namespace std; + + +/// Huffman's Algorithm +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { + +public: + int minBuildTime(vector& blocks, int split) { + + priority_queue, greater> pq; + for(int e: blocks) pq.push(e); + while(pq.size() >= 2){ + int a = pq.top();pq.pop(); + int b = pq.top(); pq.pop(); + pq.push(b + split); + } + return pq.top(); + } +}; + + +int main() { + + vector blocks1 = {1}; + cout << Solution().minBuildTime(blocks1, 1) << endl; + // 1 + + vector blocks2 = {1, 2}; + cout << Solution().minBuildTime(blocks2, 5) << endl; + // 7 + + vector blocks3 = {1, 2, 3}; + cout << Solution().minBuildTime(blocks3, 1) << endl; + // 4 + + vector blocks4 = {94961,39414,41263,7809,41473}; + cout << Solution().minBuildTime(blocks4, 90) << endl; + // 95051 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1200-Minimum-Absolute-Difference/cpp-1200/CMakeLists.txt b/1001-1500/1200-Minimum-Absolute-Difference/cpp-1200/CMakeLists.txt new file mode 100644 index 00000000..afa8217d --- /dev/null +++ b/1001-1500/1200-Minimum-Absolute-Difference/cpp-1200/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1001-1500/1200-Minimum-Absolute-Difference/cpp-1200/main.cpp b/1001-1500/1200-Minimum-Absolute-Difference/cpp-1200/main.cpp new file mode 100644 index 00000000..a6815669 --- /dev/null +++ b/1001-1500/1200-Minimum-Absolute-Difference/cpp-1200/main.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/minimum-absolute-difference/ +/// Author : liuyubobobo +/// Time : 2019-09-21 + +#include +#include + +using namespace std; + + +/// Sorting and Two Passes +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + vector> minimumAbsDifference(vector& arr) { + + sort(arr.begin(), arr.end()); + int diff = INT_MAX; + for(int i = 1; i < arr.size(); i ++) + diff = min(diff, arr[i] - arr[i - 1]); + + vector> res; + for(int i = 1; i < arr.size(); i ++) + if(arr[i] - arr[i - 1] == diff) res.push_back({arr[i - 1], arr[i]}); + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1201-Ugly-Number-III/cpp-1201/CMakeLists.txt b/1001-1500/1201-Ugly-Number-III/cpp-1201/CMakeLists.txt new file mode 100644 index 00000000..7f3bfb51 --- /dev/null +++ b/1001-1500/1201-Ugly-Number-III/cpp-1201/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main2.cpp) \ No newline at end of file diff --git a/1001-1500/1201-Ugly-Number-III/cpp-1201/main.cpp b/1001-1500/1201-Ugly-Number-III/cpp-1201/main.cpp new file mode 100644 index 00000000..608eac81 --- /dev/null +++ b/1001-1500/1201-Ugly-Number-III/cpp-1201/main.cpp @@ -0,0 +1,69 @@ +/// Source : https://leetcode.com/problems/ugly-number-iii/ +/// Author : liuyubobobo +/// Time : 2019-09-21 + +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(max*log(max)*min(a, b, c)) where max = 2e9 +/// Space Complexity: O(1) +class Solution { +public: + int nthUglyNumber(int n, int a, int b, int c) { + + long long l = 1ll, r = 2000000000ll; + while(l <= r){ + long long mid = (l + r) / 2; + int pos = get_pos(mid, a, b, c); + if(pos == n){ + while(mid % a && mid % b && mid % c) mid --; + return mid; + } + else if(pos < n) l = mid + 1; + else r = mid - 1; + } + return -1; + } + +private: + int get_pos(long long num, long long a, long long b, long long c){ + + long long res = 0; + res = num / a + num / b + num / c; + res -= (num / lcm(a, b) + num / lcm(b, c) + num / lcm(a, c)); + res += num / lcm(lcm(a, b), c); + return res; + } + + long long lcm(long long a, long long b){ + return a / gcd(a, b) * b; + } + + long long gcd(long long a, long long b){ + + if(a < b) swap(a, b); + if(a % b == 0) return b; + return gcd(b, a % b); + } +}; + + +int main() { + + cout << Solution().nthUglyNumber(3, 2, 3, 5) << endl; + // 4 + + cout << Solution().nthUglyNumber(4, 2, 3, 4) << endl; + // 6 + + cout << Solution().nthUglyNumber(5, 2, 11, 13) << endl; + // 10 + + cout << Solution().nthUglyNumber(1000000000, 2, 217983653, 336916467) << endl; + // 1999999984 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1201-Ugly-Number-III/cpp-1201/main2.cpp b/1001-1500/1201-Ugly-Number-III/cpp-1201/main2.cpp new file mode 100644 index 00000000..b6f60c4a --- /dev/null +++ b/1001-1500/1201-Ugly-Number-III/cpp-1201/main2.cpp @@ -0,0 +1,65 @@ +/// Source : https://leetcode.com/problems/ugly-number-iii/ +/// Author : liuyubobobo +/// Time : 2019-09-22 + +#include + +using namespace std; + + +/// Binary Search (Lower Bound) +/// Time Complexity: O(max*log(max)) where max = 2e9 +/// Space Complexity: O(1) +class Solution { +public: + int nthUglyNumber(int n, int a, int b, int c) { + + long long l = 1ll, r = 2000000000ll; + while(l < r){ + long long mid = (l + r) / 2; + int pos = get_pos(mid, a, b, c); + if(pos < n) l = mid + 1; + else r = mid; + } + return l; + } + +private: + int get_pos(long long num, long long a, long long b, long long c){ + + long long res = 0; + res = num / a + num / b + num / c; + res -= (num / lcm(a, b) + num / lcm(b, c) + num / lcm(a, c)); + res += num / lcm(lcm(a, b), c); + return res; + } + + long long lcm(long long a, long long b){ + return a / gcd(a, b) * b; + } + + long long gcd(long long a, long long b){ + + if(a < b) swap(a, b); + if(a % b == 0) return b; + return gcd(b, a % b); + } +}; + + +int main() { + + cout << Solution().nthUglyNumber(3, 2, 3, 5) << endl; + // 4 + + cout << Solution().nthUglyNumber(4, 2, 3, 4) << endl; + // 6 + + cout << Solution().nthUglyNumber(5, 2, 11, 13) << endl; + // 10 + + cout << Solution().nthUglyNumber(1000000000, 2, 217983653, 336916467) << endl; + // 1999999984 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1202-Smallest-String-With-Swaps/cpp-1202/CMakeLists.txt b/1001-1500/1202-Smallest-String-With-Swaps/cpp-1202/CMakeLists.txt new file mode 100644 index 00000000..70268b97 --- /dev/null +++ b/1001-1500/1202-Smallest-String-With-Swaps/cpp-1202/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main2.cpp) \ No newline at end of file diff --git a/1001-1500/1202-Smallest-String-With-Swaps/cpp-1202/main.cpp b/1001-1500/1202-Smallest-String-With-Swaps/cpp-1202/main.cpp new file mode 100644 index 00000000..d1ec2644 --- /dev/null +++ b/1001-1500/1202-Smallest-String-With-Swaps/cpp-1202/main.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/smallest-string-with-swaps/ +/// Author : liuyubobobo +/// Time : 2019-09-21 + +#include +#include +#include + +using namespace std; + + +/// DFS CC + Greedy +/// Time Complexity: O(|s| + |pairs| + |s|log|s|) +/// Space Complexity: O(|s| + |pairs|) +class Solution { +public: + string smallestStringWithSwaps(string s, vector>& pairs) { + + vector> g(s.size()); + for(const vector& p: pairs) + g[p[0]].insert(p[1]), g[p[1]].insert(p[0]); + + vector cc(s.size(), -1); + int ccid = 0; + for(int i = 0; i < s.size(); i ++) + if(cc[i] == -1) dfs(g, i, ccid ++, cc); + + vector> poses(ccid); + vector order(ccid, ""); + for(int i = 0; i < cc.size(); i ++) + poses[cc[i]].push_back(i), order[cc[i]] += s[i]; + + for(string& s: order) sort(s.begin(), s.end()); + + for(int id = 0; id < ccid; id ++){ + + int index = 0; + for(int pos: poses[id]) s[pos] = order[id][index ++]; + } + return s; + } + +private: + void dfs(const vector>& g, int v, int ccid, + vector& cc){ + + cc[v] = ccid; + for(int w: g[v]) + if(cc[w] == -1) dfs(g, w, ccid, cc); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1202-Smallest-String-With-Swaps/cpp-1202/main2.cpp b/1001-1500/1202-Smallest-String-With-Swaps/cpp-1202/main2.cpp new file mode 100644 index 00000000..4baf79bf --- /dev/null +++ b/1001-1500/1202-Smallest-String-With-Swaps/cpp-1202/main2.cpp @@ -0,0 +1,78 @@ +/// Source : https://leetcode.com/problems/smallest-string-with-swaps/ +/// Author : liuyubobobo +/// Time : 2019-09-21 + +#include +#include +#include + +using namespace std; + + +/// UF CC + Greedy +/// Time Complexity: O(|s| + |pairs| + |s|log|s|) +/// Space Complexity: O(|s| + |pairs|) +class Solution { + +private: + class UF{ + + private: + vector parent; + + public: + UF(int n){ + for(int i = 0 ; i < n ; i ++) + parent.push_back(i); + } + + int find(int p){ + if( p != parent[p] ) + parent[p] = find( parent[p] ); + return parent[p]; + } + + bool isConnected(int p , int q){ + return find(p) == find(q); + } + + void unionElements(int p, int q){ + + int pRoot = find(p); + int qRoot = find(q); + + if( pRoot == qRoot ) + return; + + parent[pRoot] = qRoot; + } + }; + +public: + string smallestStringWithSwaps(string s, vector>& pairs) { + + UF uf(s.size()); + for(const vector& p: pairs) + uf.unionElements(p[0], p[1]); + + unordered_map> poses; + unordered_map order; + for(int i = 0; i < s.size(); i ++) + poses[uf.find(i)].push_back(i), order[uf.find(i)] += s[i]; + + for(const pair& p: order) + sort(order[p.first].begin(), order[p.first].end()); + + for(const pair& p: order){ + int index = 0; + for(int pos: poses[p.first]) s[pos] = p.second[index ++]; + } + return s; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1203-Sort-Items-by-Groups-Respecting-Dependencies/cpp-1203/CMakeLists.txt b/1001-1500/1203-Sort-Items-by-Groups-Respecting-Dependencies/cpp-1203/CMakeLists.txt new file mode 100644 index 00000000..89658265 --- /dev/null +++ b/1001-1500/1203-Sort-Items-by-Groups-Respecting-Dependencies/cpp-1203/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) \ No newline at end of file diff --git a/1001-1500/1203-Sort-Items-by-Groups-Respecting-Dependencies/cpp-1203/main.cpp b/1001-1500/1203-Sort-Items-by-Groups-Respecting-Dependencies/cpp-1203/main.cpp new file mode 100644 index 00000000..0c7924d4 --- /dev/null +++ b/1001-1500/1203-Sort-Items-by-Groups-Respecting-Dependencies/cpp-1203/main.cpp @@ -0,0 +1,113 @@ +/// Source : https://leetcode.com/problems/sort-items-by-groups-respecting-dependencies/ +/// Author : liuyubobobo +/// Time : 2019-09-21 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// Two Level Topological Sorting +/// Time Complexity: O(n) +/// Space Complexity: O(n + sum(|beforeItems[i]|)) +class Solution { +public: + vector sortItems(int n, int m, vector& group, vector>& beforeItems) { + + for(int& e: group) if(e == -1) e = m ++; + + vector> groupG(m); + vector> from(m); + vector> groupv(m); + for(int i = 0; i < n; i ++){ + groupv[group[i]].insert(i); + if(!beforeItems[i].empty()){ + for(int e: beforeItems[i]){ + if(group[e] != group[i]){ + groupG[group[e]].insert(group[i]); + from[group[i]].insert(group[e]); + } + } + } + } + + vector indegrees(m, 0); + for(int i = 0; i < m; i ++) + indegrees[i] = from[i].size(); + + queue q; + for(int i = 0; i < m; i ++) + if(indegrees[i] == 0) q.push(i); + + vector res; + while(!q.empty()){ + int groupid = q.front(); + q.pop(); + + if(!organize(groupv[groupid], beforeItems, res)) + return {}; + + for(int e: groupG[groupid]){ + indegrees[e] --; + if(indegrees[e] == 0) + q.push(e); + } + } + + return res.size() == n ? res : vector(); + } + +private: + bool organize(const unordered_set& points, const vector>& beforeItems, + vector& res){ + + unordered_map> g; + unordered_map indegrees; + for(int p: points) indegrees[p] = 0, g[p] = {}; + for(int p: points) + if(!beforeItems[p].empty()){ + for(int e: beforeItems[p]) + if(points.count(e)) + g[e].insert(p), indegrees[p] ++; + } + + queue q; + for(const pair& indegree: indegrees) + if(indegree.second == 0) q.push(indegree.first); + + vector r; + while(!q.empty()){ + int cur = q.front(); + q.pop(); + r.push_back(cur); + + for(int e: g[cur]){ + indegrees[e] --; + if(indegrees[e] == 0) q.push(e); + } + } + + if(r.size() != points.size()) return false; + + for(int e: r) res.push_back(e); + return true; + } +}; + + +void print_vector(const vector& vec){ + for(int e: vec) cout << e << " "; cout << endl; +} + +int main() { + + vector group1 = {-1,-1,1,0,0,1,0,-1}; + vector> beforItems1 = {{},{6},{5},{6},{3,6},{},{},{}}; + print_vector(Solution().sortItems(8, 2, group1, beforItems1)); + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1207-Unique-Number-of-Occurrences/cpp-1207/CMakeLists.txt b/1001-1500/1207-Unique-Number-of-Occurrences/cpp-1207/CMakeLists.txt new file mode 100644 index 00000000..9c0b049b --- /dev/null +++ b/1001-1500/1207-Unique-Number-of-Occurrences/cpp-1207/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1001-1500/1207-Unique-Number-of-Occurrences/cpp-1207/main.cpp b/1001-1500/1207-Unique-Number-of-Occurrences/cpp-1207/main.cpp new file mode 100644 index 00000000..1caddd82 --- /dev/null +++ b/1001-1500/1207-Unique-Number-of-Occurrences/cpp-1207/main.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/unique-number-of-occurrences/ +/// Author : liuyubobobo +/// Time : 2019-09-28 + +#include +#include +#include + +using namespace std; + + +/// Using HashMap +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + bool uniqueOccurrences(vector& arr) { + + unordered_map freq; + for(int e: arr) freq[e] ++; + + unordered_map res; + for(const pair& p: freq) + if(res.count(p.second)) return false; + else res[p.second] ++; + return true; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1208-Get-Equal-Substrings-Within-Budget/cpp-1208/CMakeLists.txt b/1001-1500/1208-Get-Equal-Substrings-Within-Budget/cpp-1208/CMakeLists.txt new file mode 100644 index 00000000..c3e75f47 --- /dev/null +++ b/1001-1500/1208-Get-Equal-Substrings-Within-Budget/cpp-1208/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main2.cpp) \ No newline at end of file diff --git a/1001-1500/1208-Get-Equal-Substrings-Within-Budget/cpp-1208/main.cpp b/1001-1500/1208-Get-Equal-Substrings-Within-Budget/cpp-1208/main.cpp new file mode 100644 index 00000000..feb3247e --- /dev/null +++ b/1001-1500/1208-Get-Equal-Substrings-Within-Budget/cpp-1208/main.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/get-equal-substrings-within-budget/ +/// Author : liuyubobobo +/// Time : 2019-09-28 + +#include +#include + +using namespace std; + + +/// Sliding Window +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int equalSubstring(string s, string t, int maxCost) { + + vector v; + for(int i = 0; i < s.size(); i ++) + v.push_back(abs(s[i] - t[i])); + + int l = 0, r = -1, cur = 0, res = 0; // Sliding Window : [l, r] + while(l < v.size()){ + if(cur <= maxCost) res = max(res, r - l + 1); + + if(cur <= maxCost && r + 1 < v.size()) cur += v[++ r]; + else cur -= v[l ++]; + } + return res; + } +}; + + +int main() { + + cout << Solution().equalSubstring("abcd", "bcdf", 3) << endl; + // 3 + + cout << Solution().equalSubstring("abcd", "cdef", 3) << endl; + // 1 + + cout << Solution().equalSubstring("abcd", "acde", 0) << endl; + // 1 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1208-Get-Equal-Substrings-Within-Budget/cpp-1208/main2.cpp b/1001-1500/1208-Get-Equal-Substrings-Within-Budget/cpp-1208/main2.cpp new file mode 100644 index 00000000..cc31a480 --- /dev/null +++ b/1001-1500/1208-Get-Equal-Substrings-Within-Budget/cpp-1208/main2.cpp @@ -0,0 +1,42 @@ +/// Source : https://leetcode.com/problems/get-equal-substrings-within-budget/ +/// Author : liuyubobobo +/// Time : 2019-09-30 + +#include +#include + +using namespace std; + + +/// Sliding Window without using int vector +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int equalSubstring(string s, string t, int maxCost) { + + int l = 0, r = -1, cur = 0, res = 0; // Sliding Window : [l, r] + while(l < s.size()){ + if(cur <= maxCost) res = max(res, r - l + 1); + + if(cur <= maxCost && r + 1 < s.size()) cur += abs(s[++ r] - t[r]); + else cur -= abs(s[l] - t[l ++]); + } + return res; + } +}; + + +int main() { + + cout << Solution().equalSubstring("abcd", "bcdf", 3) << endl; + // 3 + + cout << Solution().equalSubstring("abcd", "cdef", 3) << endl; + // 1 + + cout << Solution().equalSubstring("abcd", "acde", 0) << endl; + // 1 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1209-Remove-All-Adjacent-Duplicates-in-String-II/cpp-1209/CMakeLists.txt b/1001-1500/1209-Remove-All-Adjacent-Duplicates-in-String-II/cpp-1209/CMakeLists.txt new file mode 100644 index 00000000..0b46ca4b --- /dev/null +++ b/1001-1500/1209-Remove-All-Adjacent-Duplicates-in-String-II/cpp-1209/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1001-1500/1209-Remove-All-Adjacent-Duplicates-in-String-II/cpp-1209/main.cpp b/1001-1500/1209-Remove-All-Adjacent-Duplicates-in-String-II/cpp-1209/main.cpp new file mode 100644 index 00000000..f3da73ca --- /dev/null +++ b/1001-1500/1209-Remove-All-Adjacent-Duplicates-in-String-II/cpp-1209/main.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string-ii/ +/// Author : liuyubobobo +/// Time : 2019-09-28 + +#include +#include + +using namespace std; + + +/// Using Stack +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + string removeDuplicates(string s, int k) { + + stack> stack; + for(char c: s){ + if(!stack.empty() && stack.top().first == c) + stack.top().second ++; + else + stack.push(make_pair(c, 1)); + + if(stack.top().second == k) + stack.pop(); + } + + string res = ""; + while(!stack.empty()) + res += string(stack.top().second, stack.top().first), stack.pop(); + reverse(res.begin(), res.end()); + return res; + } +}; + + +int main() { + + cout << Solution().removeDuplicates("abcd", 2) << endl; + // abcd + + cout << Solution().removeDuplicates("deeedbbcccbdaa", 3) << endl; + // aa + + cout << Solution().removeDuplicates("pbbcggttciiippooaais", 2) << endl; + // ps + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1210-Minimum-Moves-to-Reach-Target-with-Rotations/cpp-1210/CMakeLists.txt b/1001-1500/1210-Minimum-Moves-to-Reach-Target-with-Rotations/cpp-1210/CMakeLists.txt new file mode 100644 index 00000000..ed89229b --- /dev/null +++ b/1001-1500/1210-Minimum-Moves-to-Reach-Target-with-Rotations/cpp-1210/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) \ No newline at end of file diff --git a/1001-1500/1210-Minimum-Moves-to-Reach-Target-with-Rotations/cpp-1210/main.cpp b/1001-1500/1210-Minimum-Moves-to-Reach-Target-with-Rotations/cpp-1210/main.cpp new file mode 100644 index 00000000..b03ae81e --- /dev/null +++ b/1001-1500/1210-Minimum-Moves-to-Reach-Target-with-Rotations/cpp-1210/main.cpp @@ -0,0 +1,124 @@ +/// Source : https://leetcode.com/problems/minimum-moves-to-reach-target-with-rotations/ +/// Author : liuyubobobo +/// Time : 2019-09-28 + +#include +#include +#include +#include + +using namespace std; + + +/// BFS +/// Time Complexity: O(R * C) +/// Space Complexity: O(R * C) +class Solution { + +private: + const int dirs[2][2] = {{1, 0}, {0, 1}}; + int R, C; + +public: + int minimumMoves(vector>& grid) { + + R = grid.size(), C = grid[0].size(); + unordered_map visited; + visited[0] = 0; + queue q; + q.push(0); + while(!q.empty()){ + const int curcode = q.front(); + int cur = curcode; + q.pop(); + + const int d = cur % 10; cur /= 10; + const int y1 = cur % 1000, x1 = cur / 1000; + + int x2, y2; + if(d == 0) x2 = x1, y2 = y1 + 1; + else x2 = x1 + 1, y2 = y1; + + for(int dir = 0; dir < 3; dir ++){ + + int nextx1 = -1, nexty1 = -1, nextx2 = -1, nexty2 = -1, nextcode = -1; + if(dir < 2){ + nextx1 = x1 + dirs[dir][0], nexty1 = y1 + dirs[dir][1]; + nextx2 = x2 + dirs[dir][0], nexty2 = y2 + dirs[dir][1]; + nextcode = nextx1 * 10000 + nexty1 * 10 + d; + } + else if(d == 0 && in_area(x1 + 1, y1) && in_area(x1 + 1, y1 + 1) + && !grid[x1 + 1][y1] && !grid[x1 + 1][y1 + 1]){ + nextx1 = x1, nexty1= y1; + nextx2 = x1 + 1, nexty2 = y1; + nextcode = nextx1 * 10000 + nexty1 * 10 + 1; + } + else if(d == 1 && in_area(x1, y1 + 1) && in_area(x1 + 1, y1 + 1) + && !grid[x1][y1 + 1] && !grid[x1 + 1][y1 + 1]){ + nextx1 = x1, nexty1 = y1; + nextx2 = x1, nexty2 = y1 + 1; + nextcode = nextx1 * 10000 + nexty1 * 10 + 0; + } + + if(in_area(nextx1, nexty1) && in_area(nextx2, nexty2) + && !grid[nextx1][nexty1] && !grid[nextx2][nexty2] && !visited.count(nextcode)){ + + visited[nextcode] = visited[curcode] + 1; + q.push(nextcode); + + if(nextx1 == R - 1 && nexty1 == C - 2 && nextx2 == R - 1 && nexty2 == C - 1) + return visited[nextcode]; + } + } + } + return -1; + } + +private: + bool in_area(int x, int y){ + return x >= 0 && x < R && y >= 0 && y < C; + } +}; + + +int main() { + + vector> grid1 = { + {0,0,0,0,0,1}, + {1,1,0,0,1,0}, + {0,0,0,0,1,1}, + {0,0,1,0,1,0}, + {0,1,1,0,0,0}, + {0,1,1,0,0,0} + }; + cout << Solution().minimumMoves(grid1) << endl; + // 11 + + vector> grid2 = { + {0,0,1,1,1,1}, + {0,0,0,0,1,1}, + {1,1,0,0,0,1}, + {1,1,1,0,0,1}, + {1,1,1,0,0,1}, + {1,1,1,0,0,0} + }; + cout << Solution().minimumMoves(grid2) << endl; + // 9 + + vector> grid3 = { + {0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, + {0, 1, 0, 0, 0, 0, 0, 1, 0, 1}, + {1, 0, 0, 1, 0, 0, 1, 0, 1, 0}, + {0, 0, 0, 1, 0, 1, 0, 1, 0, 0}, + {0, 0, 0, 0, 1, 0, 0, 0, 0, 1}, + {0, 0, 1, 0, 0, 0, 0, 0, 0, 0}, + {1, 0, 0, 1, 0, 0, 0, 0, 0, 0}, + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, + {1, 1, 0, 0, 0, 0, 0, 0, 0, 0} + }; + cout << Solution().minimumMoves(grid3) << endl; + // -1 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1213-Intersection-of-Three-Sorted-Arrays/cpp-1213/CMakeLists.txt b/1001-1500/1213-Intersection-of-Three-Sorted-Arrays/cpp-1213/CMakeLists.txt new file mode 100644 index 00000000..905a4101 --- /dev/null +++ b/1001-1500/1213-Intersection-of-Three-Sorted-Arrays/cpp-1213/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(cpp_1213) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1213 main2.cpp) \ No newline at end of file diff --git a/1001-1500/1213-Intersection-of-Three-Sorted-Arrays/cpp-1213/main.cpp b/1001-1500/1213-Intersection-of-Three-Sorted-Arrays/cpp-1213/main.cpp new file mode 100644 index 00000000..d33a29bc --- /dev/null +++ b/1001-1500/1213-Intersection-of-Three-Sorted-Arrays/cpp-1213/main.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/intersection-of-three-sorted-arrays/ +/// Author : liuyubobobo +/// Time : 2019-10-06 + +#include +#include +#include + +using namespace std; + + +/// Using Set +/// Time Complexity: O(|arr1| + |arr2| + |arr3|) +/// Space Complexity: O(|arr1| + |arr2| + |arr3|) +class Solution { +public: + vector arraysIntersection(vector& arr1, vector& arr2, vector& arr3) { + + set set1(arr1.begin(), arr1.end()); + set set2; + for(int e: arr2) if(set1.count(e)) set2.insert(e); + + vector res; + for(int e: arr3) if(set2.count(e)) res.push_back(e); + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1213-Intersection-of-Three-Sorted-Arrays/cpp-1213/main2.cpp b/1001-1500/1213-Intersection-of-Three-Sorted-Arrays/cpp-1213/main2.cpp new file mode 100644 index 00000000..8631cc27 --- /dev/null +++ b/1001-1500/1213-Intersection-of-Three-Sorted-Arrays/cpp-1213/main2.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/intersection-of-three-sorted-arrays/ +/// Author : liuyubobobo +/// Time : 2019-10-06 + +#include +#include +#include + +using namespace std; + + +/// Tree Pointers +/// Time Complexity: O(|arr1| + |arr2| + |arr3|) +/// Space Complexity: O(1) +class Solution { +public: + vector arraysIntersection(vector& arr1, vector& arr2, vector& arr3) { + + vector res; + int i = 0, j = 0, k = 0; + while(i < arr1.size() && j < arr2.size() && k < arr3.size()){ + if(arr1[i] == arr2[j] && arr2[j] == arr3[k]) + res.push_back(arr1[i]), i ++, j ++, k ++; + else if(arr1[i] <= arr2[j] && arr1[i] <= arr3[k]) i ++; + else if(arr2[j] <= arr1[i] && arr2[j] <= arr3[k]) j ++; + else k ++; + } + return res; + } +}; + + +int main() { + + vector arr1 = {1,2,3,4,5}; + vector arr2 = {1,2,5,7,9}; + vector arr3 = {1,3,4,5,8}; + Solution().arraysIntersection(arr1, arr2, arr3); + return 0; +} \ No newline at end of file diff --git a/1001-1500/1214-Two-Sum-BSTs/cpp-1214/CMakeLists.txt b/1001-1500/1214-Two-Sum-BSTs/cpp-1214/CMakeLists.txt new file mode 100644 index 00000000..8a50d4b0 --- /dev/null +++ b/1001-1500/1214-Two-Sum-BSTs/cpp-1214/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(cpp_1214) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1214 main2.cpp) \ No newline at end of file diff --git a/1001-1500/1214-Two-Sum-BSTs/cpp-1214/main.cpp b/1001-1500/1214-Two-Sum-BSTs/cpp-1214/main.cpp new file mode 100644 index 00000000..31fc2a43 --- /dev/null +++ b/1001-1500/1214-Two-Sum-BSTs/cpp-1214/main.cpp @@ -0,0 +1,48 @@ +/// Source : https://leetcode.com/problems/two-sum-bsts/ +/// Author : liuyubobobo +/// Time : 2019-10-06 + +#include +#include + +using namespace std; + + +/// DFS and store every value in Set +/// Time Complexity: O(|root1| + |root2|) +/// Space Complexity: O(|root1| + |root2|) + +/// 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: + bool twoSumBSTs(TreeNode* root1, TreeNode* root2, int target) { + + set set1, set2; + if(root1) dfs(root1, set1); + if(root2) dfs(root2, set2); + + for(int e: set1) if(set2.count(target - e)) return true; + return false; + } + +private: + void dfs(TreeNode* root, set& set){ + + set.insert(root->val); + if(root->left) dfs(root->left, set); + if(root->right) dfs(root->right, set); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1214-Two-Sum-BSTs/cpp-1214/main2.cpp b/1001-1500/1214-Two-Sum-BSTs/cpp-1214/main2.cpp new file mode 100644 index 00000000..dd8461db --- /dev/null +++ b/1001-1500/1214-Two-Sum-BSTs/cpp-1214/main2.cpp @@ -0,0 +1,48 @@ +/// Source : https://leetcode.com/problems/two-sum-bsts/ +/// Author : liuyubobobo +/// Time : 2019-10-06 + +#include +#include + +using namespace std; + + +/// DFS in root1 and search in root 2 +/// Time Complexity: O(|root1|log|root2|) +/// Space Complexity: O(|h1| + |h2|) + +/// 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: + bool twoSumBSTs(TreeNode* root1, TreeNode* root2, int target) { + + if(!root1) return false; + if(search(root2, target - root1->val)) return true; + if(twoSumBSTs(root1->left, root2, target)) return true; + if(twoSumBSTs(root1->right, root2, target)) return true; + return false; + } + +private: + bool search(TreeNode* root, int num){ + + if(!root) return false; + if(root->val == num) return true; + else if(num < root->val) return search(root->left, num); + return search(root->right, num); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1215-Stepping-Numbers/CMakeLists.txt b/1001-1500/1215-Stepping-Numbers/CMakeLists.txt new file mode 100644 index 00000000..04eca873 --- /dev/null +++ b/1001-1500/1215-Stepping-Numbers/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(1215_Stepping_Numbers) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(1215_Stepping_Numbers main2.cpp) \ No newline at end of file diff --git a/1001-1500/1215-Stepping-Numbers/main.cpp b/1001-1500/1215-Stepping-Numbers/main.cpp new file mode 100644 index 00000000..5efba204 --- /dev/null +++ b/1001-1500/1215-Stepping-Numbers/main.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/stepping-numbers/ +/// Author : liuyubobobo +/// Time : 2019-10-06 + +#include +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(2^10) +/// Space Complexity: O(2^10) +class Solution { +public: + vector countSteppingNumbers(int low, int high) { + + set set; + if(low == 0) set.insert(0); + for (int start = 1; start <= 9; start++) + dfs(to_string(high).size(), 1, (long long) start, low, high, set); + + + return vector(set.begin(), set.end()); + } + +private: + void dfs(int len, int index, long long num, long long low, long long high, + set& set){ + + if(low <= num && num <= high) set.insert(num); + + if(index < len){ + int last = num % 10; + if(last - 1 >= 0) dfs(len, index + 1, num * 10ll + (last - 1ll), low, high, set); + if(last + 1 <= 9) dfs(len, index + 1, num * 10ll + (last + 1ll), low, high, set); + } + } +}; + + +void print_vec(const vector& vec){ + for(int e: vec) cout << e << " "; cout << endl; +} + +int main() { + + print_vec(Solution().countSteppingNumbers(0, 21)); + // 0,1,2,3,4,5,6,7,8,9,10,12,21 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1215-Stepping-Numbers/main2.cpp b/1001-1500/1215-Stepping-Numbers/main2.cpp new file mode 100644 index 00000000..a3263785 --- /dev/null +++ b/1001-1500/1215-Stepping-Numbers/main2.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/stepping-numbers/ +/// Author : liuyubobobo +/// Time : 2019-10-06 + +#include +#include +#include +#include + +using namespace std; + + +/// BFS +/// Time Complexity: O(2^10) +/// Space Complexity: O(2^10) +class Solution { +public: + vector countSteppingNumbers(long long low, long long high) { + + set set; + if(low == 0) set.insert(0); + + queue q; + for(int i = 1; i <= 9; i ++) q.push(i); + while(!q.empty()){ + long long num = q.front(); + q.pop(); + + if(low <= num && num <= high) set.insert(num); + else if(num > high) continue; + + int last = num % 10; + if(last - 1 >= 0) q.push(num * 10ll + (last - 1ll)); + if(last + 1 <= 9) q.push(num * 10ll + (last + 1ll)); + } + + return vector(set.begin(), set.end()); + } +}; + + +void print_vec(const vector& vec){ + for(int e: vec) cout << e << " "; cout << endl; +} + +int main() { + + print_vec(Solution().countSteppingNumbers(0, 21)); + // 0,1,2,3,4,5,6,7,8,9,10,12,21 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1216-Valid-Palindrome-III/cpp-1216/CMakeLists.txt b/1001-1500/1216-Valid-Palindrome-III/cpp-1216/CMakeLists.txt new file mode 100644 index 00000000..d0fb10b4 --- /dev/null +++ b/1001-1500/1216-Valid-Palindrome-III/cpp-1216/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(cpp_1216) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1216 main2.cpp) \ No newline at end of file diff --git a/1001-1500/1216-Valid-Palindrome-III/cpp-1216/main.cpp b/1001-1500/1216-Valid-Palindrome-III/cpp-1216/main.cpp new file mode 100644 index 00000000..a9c2cda2 --- /dev/null +++ b/1001-1500/1216-Valid-Palindrome-III/cpp-1216/main.cpp @@ -0,0 +1,43 @@ +/// Source : https://leetcode.com/problems/valid-palindrome-iii/ +/// Author : liuyubobobo +/// Time : 2019-10-06 + +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(|s|^2) +/// Space Complexity: O(|s|^2) +class Solution { +public: + bool isValidPalindrome(string s, int k) { + + vector> dp(s.size(), vector(s.size(), -1)); + return dfs(s, 0, s.size() - 1, dp) <= k; + } + +private: + int dfs(const string& s, int l, int r, vector>& dp){ + + if(l == r) return 0; + if(l + 1 == r) return s[l] == s[r] ? 0 : 1; + + if(dp[l][r] != -1) return dp[l][r]; + + int res = 1 + min(dfs(s, l + 1, r, dp), dfs(s, l, r - 1, dp)); + if(s[l] == s[r]) res = min(res, dfs(s, l + 1, r - 1, dp)); +// cout << l << " - " << r << " : " << res << endl; + return dp[l][r] = res; + } +}; + + +int main() { + + cout << Solution().isValidPalindrome("abcdeca", 2) << endl; + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1216-Valid-Palindrome-III/cpp-1216/main2.cpp b/1001-1500/1216-Valid-Palindrome-III/cpp-1216/main2.cpp new file mode 100644 index 00000000..f471d77e --- /dev/null +++ b/1001-1500/1216-Valid-Palindrome-III/cpp-1216/main2.cpp @@ -0,0 +1,38 @@ +/// Source : https://leetcode.com/problems/valid-palindrome-iii/ +/// Author : liuyubobobo +/// Time : 2019-10-06 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(|s|^2) +/// Space Complexity: O(|s|^2) +class Solution { +public: + bool isValidPalindrome(string s, int k) { + + vector> dp(s.size(), vector(s.size() + 1, 0)); + for(int i = 0; i + 1 < s.size(); i ++) + dp[i][2] = (s[i] == s[i + 1] ? 0 : 1); + + for(int len = 3; len <= s.size(); len ++) + for(int i = 0; i + len <= s.size(); i ++){ + dp[i][len] = 1 + min(dp[i][len - 1], dp[i + 1][len - 1]); + if(s[i] == s[i + len - 1]) + dp[i][len] = min(dp[i][len], dp[i + 1][len - 2]); + } + return dp[0][s.size()] <= k; + } +}; + + +int main() { + + cout << Solution().isValidPalindrome("abcdeca", 2) << endl; + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1217-Play-with-Chips/cpp-1217/CMakeLists.txt b/1001-1500/1217-Play-with-Chips/cpp-1217/CMakeLists.txt new file mode 100644 index 00000000..9c0b049b --- /dev/null +++ b/1001-1500/1217-Play-with-Chips/cpp-1217/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1001-1500/1217-Play-with-Chips/cpp-1217/main.cpp b/1001-1500/1217-Play-with-Chips/cpp-1217/main.cpp new file mode 100644 index 00000000..4f47d373 --- /dev/null +++ b/1001-1500/1217-Play-with-Chips/cpp-1217/main.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/play-with-chips/ +/// Author : liuyubobobo +/// Time : 2019-10-05 + +#include +#include + +using namespace std; + + +/// Mathematics +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int minCostToMoveChips(vector& chips) { + + int odd = 0, even = 0; + for(int e: chips) + if(e % 2) odd ++; + else even ++; + return min(odd, even); + } +}; + + +int main() { + + vector chip1 = {1, 2, 3}; + cout << Solution().minCostToMoveChips(chip1) << endl; + // 1 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1218-Longest-Arithmetic-Subsequence-of-Given-Difference/cpp-1218/CMakeLists.txt b/1001-1500/1218-Longest-Arithmetic-Subsequence-of-Given-Difference/cpp-1218/CMakeLists.txt new file mode 100644 index 00000000..c3e75f47 --- /dev/null +++ b/1001-1500/1218-Longest-Arithmetic-Subsequence-of-Given-Difference/cpp-1218/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main2.cpp) \ No newline at end of file diff --git a/1001-1500/1218-Longest-Arithmetic-Subsequence-of-Given-Difference/cpp-1218/main.cpp b/1001-1500/1218-Longest-Arithmetic-Subsequence-of-Given-Difference/cpp-1218/main.cpp new file mode 100644 index 00000000..d9d5d885 --- /dev/null +++ b/1001-1500/1218-Longest-Arithmetic-Subsequence-of-Given-Difference/cpp-1218/main.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/longest-arithmetic-subsequence-of-given-difference/ +/// Author : liuyubobobo +/// Time : 2019-10-05 + +#include +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int longestSubsequence(vector& arr, int difference) { + + map pos; + vector dp(arr.size(), 1); + for(int i = 0; i < arr.size(); i ++){ + int pre = arr[i] - difference; + if(pos.count(pre)) + dp[i] = max(dp[i], dp[pos[pre]] + 1); + pos[arr[i]] = i; + } + return *max_element(dp.begin(), dp.end()); + } +}; + + +int main() { + + vector arr1 = {1,2,3,4}; + cout << Solution().longestSubsequence(arr1, 1) << endl; + // 4 + + vector arr2 = {1,3,5,7}; + cout << Solution().longestSubsequence(arr2, 1) << endl; + // 1 + + vector arr3 = {1,5,7,8,5,3,4,2,1}; + cout << Solution().longestSubsequence(arr3, -2) << endl; + // 4 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1218-Longest-Arithmetic-Subsequence-of-Given-Difference/cpp-1218/main2.cpp b/1001-1500/1218-Longest-Arithmetic-Subsequence-of-Given-Difference/cpp-1218/main2.cpp new file mode 100644 index 00000000..82deae95 --- /dev/null +++ b/1001-1500/1218-Longest-Arithmetic-Subsequence-of-Given-Difference/cpp-1218/main2.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/longest-arithmetic-subsequence-of-given-difference/ +/// Author : liuyubobobo +/// Time : 2019-10-06 + +#include +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// More Concise Logic +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int longestSubsequence(vector& arr, int difference) { + + map dp; + int res = 1; + for(int i = 0; i < arr.size(); i ++){ + dp[arr[i]] = max(dp[arr[i]], dp[arr[i] - difference] + 1); + res = max(res, dp[arr[i]]); + } + return res; + } +}; + + +int main() { + + vector arr1 = {1,2,3,4}; + cout << Solution().longestSubsequence(arr1, 1) << endl; + // 4 + + vector arr2 = {1,3,5,7}; + cout << Solution().longestSubsequence(arr2, 1) << endl; + // 1 + + vector arr3 = {1,5,7,8,5,3,4,2,1}; + cout << Solution().longestSubsequence(arr3, -2) << endl; + // 4 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1219-Path-with-Maximum-Gold/cpp-1219/CMakeLists.txt b/1001-1500/1219-Path-with-Maximum-Gold/cpp-1219/CMakeLists.txt new file mode 100644 index 00000000..0b46ca4b --- /dev/null +++ b/1001-1500/1219-Path-with-Maximum-Gold/cpp-1219/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1001-1500/1219-Path-with-Maximum-Gold/cpp-1219/main.cpp b/1001-1500/1219-Path-with-Maximum-Gold/cpp-1219/main.cpp new file mode 100644 index 00000000..7f2ce40f --- /dev/null +++ b/1001-1500/1219-Path-with-Maximum-Gold/cpp-1219/main.cpp @@ -0,0 +1,61 @@ +/// Source : https://leetcode.com/problems/path-with-maximum-gold/ +/// Author : liuyubobobo +/// Time : 2019-10-05 + +#include +#include + +using namespace std; + + +/// Backtrcking +/// Time Complexity: O(2^(m*n)) +/// Space Complexity: O(m*n) +class Solution { + +private: + int R, C; + const int dirs[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; + +public: + int getMaximumGold(vector>& grid) { + + R = grid.size(), C = grid[0].size(); +// vector> visited(R, vector(C, false)); + int res = 0; + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++) + if(grid[i][j]) + res = max(res, dfs(grid, i, j)); + return res; + } + +private: + int dfs(vector>& grid, int x, int y){ + + int res = grid[x][y]; + int o = grid[x][y]; + grid[x][y] = 0; + for(int d = 0; d < 4; d ++){ + int nextx = x + dirs[d][0], nexty = y + dirs[d][1]; + if(nextx >= 0 && nextx < R && nexty >= 0 && nexty < C && grid[nextx][nexty]) + res = max(res, o + dfs(grid, nextx, nexty)); + } + grid[x][y] = o; + return res; + } +}; + + +int main() { + + vector> grid1 = {{0,6,0},{5,8,7},{0,9,0}}; + cout << Solution().getMaximumGold(grid1) << endl; + // 24 + + vector> grid2 = {{1,0,7},{2,0,6},{3,4,5},{0,3,0},{9,0,20}}; + cout << Solution().getMaximumGold(grid2) << endl; + // 28 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1220-Count-Vowels-Permutation/cpp-1220/CMakeLists.txt b/1001-1500/1220-Count-Vowels-Permutation/cpp-1220/CMakeLists.txt new file mode 100644 index 00000000..9d6d832b --- /dev/null +++ b/1001-1500/1220-Count-Vowels-Permutation/cpp-1220/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main3.cpp) \ No newline at end of file diff --git a/1001-1500/1220-Count-Vowels-Permutation/cpp-1220/main.cpp b/1001-1500/1220-Count-Vowels-Permutation/cpp-1220/main.cpp new file mode 100644 index 00000000..d1d176e2 --- /dev/null +++ b/1001-1500/1220-Count-Vowels-Permutation/cpp-1220/main.cpp @@ -0,0 +1,64 @@ +/// Source : https://leetcode.com/problems/count-vowels-permutation/ +/// Author : liuyubobobo +/// Time : 2019-10-05 + +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +private: + int MOD = 1e9 + 7; + vector> g = { + //a e i o u + {0, 1, 0, 0, 0}, // a + {1, 0, 1, 0, 0}, // e + {1, 1, 0, 1, 1}, // i + {0, 0, 1, 0, 1}, // o + {1, 0, 0, 0, 0} // u + }; + +public: + int countVowelPermutation(int n) { + + vector> dp(5, vector(n, -1)); + int res = 0; + for(int i = 0; i < 5; i ++) + res += dfs(i, n - 1, dp), res %= MOD; + return res; + } + +private: + int dfs(int cur, int left, vector>& dp){ + + if(!left) return 1; + if(dp[cur][left] != -1) return dp[cur][left]; + + int res = 0; + for(int i = 0; i < 5; i ++) + if(g[cur][i]) + res += dfs(i, left - 1, dp), res %= MOD; + return dp[cur][left] = res; + } +}; + + +int main() { + + cout << Solution().countVowelPermutation(1) << endl; + // 5 + + cout << Solution().countVowelPermutation(2) << endl; + // 10 + + cout << Solution().countVowelPermutation(5) << endl; + // 68 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1220-Count-Vowels-Permutation/cpp-1220/main2.cpp b/1001-1500/1220-Count-Vowels-Permutation/cpp-1220/main2.cpp new file mode 100644 index 00000000..ff3fd700 --- /dev/null +++ b/1001-1500/1220-Count-Vowels-Permutation/cpp-1220/main2.cpp @@ -0,0 +1,61 @@ +/// Source : https://leetcode.com/problems/count-vowels-permutation/ +/// Author : liuyubobobo +/// Time : 2019-10-06 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +private: + int MOD = 1e9 + 7; + vector> g = { + //a e i o u + {0, 1, 0, 0, 0}, // a + {1, 0, 1, 0, 0}, // e + {1, 1, 0, 1, 1}, // i + {0, 0, 1, 0, 1}, // o + {1, 0, 0, 0, 0} // u + }; + +public: + int countVowelPermutation(int n) { + + vector> dp(5, vector(n, 0)); + for(int i = 0; i < 5; i ++) + dp[i][n - 1] = 1; + + for(int j = n - 2; j >= 0; j --) + for(int i = 0; i < 5; i ++){ + for(int k = 0; k < 5; k ++) + if(g[i][k]) + dp[i][j] += dp[k][j + 1], dp[i][j] %= MOD; + } + + int res = 0; + for(int i = 0; i < 5; i ++) + res += dp[i][0], res %= MOD; + return res; + } +}; + + +int main() { + + cout << Solution().countVowelPermutation(1) << endl; + // 5 + + cout << Solution().countVowelPermutation(2) << endl; + // 10 + + cout << Solution().countVowelPermutation(5) << endl; + // 68 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1220-Count-Vowels-Permutation/cpp-1220/main3.cpp b/1001-1500/1220-Count-Vowels-Permutation/cpp-1220/main3.cpp new file mode 100644 index 00000000..ea1c2749 --- /dev/null +++ b/1001-1500/1220-Count-Vowels-Permutation/cpp-1220/main3.cpp @@ -0,0 +1,62 @@ +/// Source : https://leetcode.com/problems/count-vowels-permutation/ +/// Author : liuyubobobo +/// Time : 2019-10-06 + +#include +#include + +using namespace std; + + +/// Dynamic Programming with Space Optimization +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { + +private: + int MOD = 1e9 + 7; + vector> g = { + //a e i o u + {0, 1, 0, 0, 0}, // a + {1, 0, 1, 0, 0}, // e + {1, 1, 0, 1, 1}, // i + {0, 0, 1, 0, 1}, // o + {1, 0, 0, 0, 0} // u + }; + +public: + int countVowelPermutation(int n) { + + vector dp(5, 1); + + for(int j = n - 2; j >= 0; j --){ + vector dp2(5, 0); + for(int i = 0; i < 5; i ++){ + for(int k = 0; k < 5; k ++) + if(g[i][k]) + dp2[i] += dp[k], dp2[i] %= MOD; + } + dp = dp2; + } + + int res = 0; + for(int e: dp) + res += e, res %= MOD; + return res; + } +}; + + +int main() { + + cout << Solution().countVowelPermutation(1) << endl; + // 5 + + cout << Solution().countVowelPermutation(2) << endl; + // 10 + + cout << Solution().countVowelPermutation(5) << endl; + // 68 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1221-Split-a-String-in-Balanced-Strings/cpp-1221/CMakeLists.txt b/1001-1500/1221-Split-a-String-in-Balanced-Strings/cpp-1221/CMakeLists.txt new file mode 100644 index 00000000..9c0b049b --- /dev/null +++ b/1001-1500/1221-Split-a-String-in-Balanced-Strings/cpp-1221/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1001-1500/1221-Split-a-String-in-Balanced-Strings/cpp-1221/main.cpp b/1001-1500/1221-Split-a-String-in-Balanced-Strings/cpp-1221/main.cpp new file mode 100644 index 00000000..1d8d1b8d --- /dev/null +++ b/1001-1500/1221-Split-a-String-in-Balanced-Strings/cpp-1221/main.cpp @@ -0,0 +1,38 @@ +/// Source : https://leetcode.com/problems/split-a-string-in-balanced-strings/ +/// Author : liuyubobobo +/// Time : 2019-10-12 + +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int balancedStringSplit(string s) { + + int l = 0, r = 0, res = 0; + for(char c: s){ + if(c == 'L') l ++; + else r ++; + + if(l == r) res ++, l = r = 0; + } + return res; + } +}; + + +int main() { + + cout << Solution().balancedStringSplit("RLRRLLRLRL") << endl; + // 4 + + cout << Solution().balancedStringSplit("RLLLLRRRLR") << endl; + // 3 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1222-Queens-That-Can-Attack-the-King/cpp-1222/CMakeLists.txt b/1001-1500/1222-Queens-That-Can-Attack-the-King/cpp-1222/CMakeLists.txt new file mode 100644 index 00000000..f3359f29 --- /dev/null +++ b/1001-1500/1222-Queens-That-Can-Attack-the-King/cpp-1222/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1001-1500/1222-Queens-That-Can-Attack-the-King/cpp-1222/main.cpp b/1001-1500/1222-Queens-That-Can-Attack-the-King/cpp-1222/main.cpp new file mode 100644 index 00000000..403b3459 --- /dev/null +++ b/1001-1500/1222-Queens-That-Can-Attack-the-King/cpp-1222/main.cpp @@ -0,0 +1,43 @@ +/// Source : https://leetcode.com/problems/queens-that-can-attack-the-king/ +/// Author : liuyubobobo +/// Time : 2019-10-12 + +#include +#include +#include + +using namespace std; + + +/// Using Set +/// Time Complexity: O(64) +/// Space Complexity: O(queens) +class Solution { + +private: + const int dirs[8][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}, + {1, 1}, {1, -1}, {-1, 1}, {-1, -1}}; + +public: + vector> queensAttacktheKing(vector>& queens, vector& king) { + + vector> res; + set> set(queens.begin(), queens.end()); + for(int d = 0; d < 8; d ++){ + int x = king[0], y = king[1]; + for(int l = 1; l <= 8; l ++){ + if(set.count({x + l * dirs[d][0], y + l * dirs[d][1]})){ + res.push_back({x + l * dirs[d][0], y + l * dirs[d][1]}); + break; + } + } + } + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1223-Dice-Roll-Simulation/cpp-1223/CMakeLists.txt b/1001-1500/1223-Dice-Roll-Simulation/cpp-1223/CMakeLists.txt new file mode 100644 index 00000000..2ce40a6e --- /dev/null +++ b/1001-1500/1223-Dice-Roll-Simulation/cpp-1223/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main3.cpp) \ No newline at end of file diff --git a/1001-1500/1223-Dice-Roll-Simulation/cpp-1223/main.cpp b/1001-1500/1223-Dice-Roll-Simulation/cpp-1223/main.cpp new file mode 100644 index 00000000..3cc770c3 --- /dev/null +++ b/1001-1500/1223-Dice-Roll-Simulation/cpp-1223/main.cpp @@ -0,0 +1,66 @@ +/// Source : https://leetcode.com/problems/dice-roll-simulation/ +/// Author : liuyubobobo +/// Time : 2019-10-12 + +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(n * 6 * max(rollMax) * 6) +/// Space Complexity: O(n * 6 * max(rollMax)) +class Solution { + +private: + const int MOD = 1e9 + 7; + +public: + int dieSimulator(int n, vector& rollMax) { + + vector>> dp(n, vector>(*max_element(rollMax.begin(), rollMax.end()) + 1, vector(6, -1))); + int res = 0; + for(int i = 0; i < 6; i ++) + res = (res + dfs(n, 1, 1, i, rollMax, dp))% MOD; + return res; + } + +private: + int dfs(int n, int index, int lastfreq, int lastnum, + const vector& rollMax, vector>>& dp){ + + if(index == n) return 1; + if(dp[index][lastfreq][lastnum] != -1) return dp[index][lastfreq][lastnum]; + + int res = 0; + for(int i = 0; i < 6; i ++) + if(i != lastnum) + res = (res + dfs(n, index + 1, 1, i, rollMax, dp)) % MOD; + else if(lastfreq + 1 <= rollMax[i]) + res = (res + dfs(n, index + 1, lastfreq + 1, i, rollMax, dp)) % MOD; + return dp[index][lastfreq][lastnum] = res; + } +}; + + +int main() { + + vector rollMax1 = {1, 1, 2, 2, 2, 3}; + cout << Solution().dieSimulator(2, rollMax1) << endl; + // 34 + + vector rollMax2 = {1, 1, 1, 1, 1, 1}; + cout << Solution().dieSimulator(2, rollMax2) << endl; + // 30 + + vector rollMax3 = {1, 1, 1, 2, 2, 3}; + cout << Solution().dieSimulator(3, rollMax3) << endl; + // 181 + + vector rollMax4 = {13, 3, 12, 14, 11, 11}; + cout << Solution().dieSimulator(5000, rollMax4) << endl; + // 538400505 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1223-Dice-Roll-Simulation/cpp-1223/main2.cpp b/1001-1500/1223-Dice-Roll-Simulation/cpp-1223/main2.cpp new file mode 100644 index 00000000..eb03e866 --- /dev/null +++ b/1001-1500/1223-Dice-Roll-Simulation/cpp-1223/main2.cpp @@ -0,0 +1,69 @@ +/// Source : https://leetcode.com/problems/dice-roll-simulation/ +/// Author : liuyubobobo +/// Time : 2019-10-12 + +#include +#include + +using namespace std; + + +/// Memory Search - State Compression +/// Time Complexity: O(n * 6 * max(rollMax) * 6) +/// Space Complexity: O(n * 6 * max(rollMax)) +class Solution { + +private: + const int MOD = 1e9 + 7; + +public: + int dieSimulator(int n, vector& rollMax) { + + vector dp(1600000, -1); + int res = 0; + for(int i = 0; i < 6; i ++) + res = (res + dfs(n, 100000 + i * 10000 + 1, rollMax, dp))% MOD; + return res; + } + +private: + int dfs(int n, int state, const vector& rollMax, vector& dp){ + + if(dp[state] != -1) return dp[state]; + + int index = state % 10000; + if(index == n) return 1; + + int lastnum = state / 10000 % 10; + int lastfreq = state / 100000; + int res = 0; + for(int i = 0; i < 6; i ++) + if(i != lastnum) + res = (res + dfs(n, 100000 + i * 10000 + index + 1, rollMax, dp)) % MOD; + else if(lastfreq + 1 <= rollMax[i]) + res = (res + dfs(n, (lastfreq + 1) * 100000 + i * 10000 + index + 1, rollMax, dp)) % MOD; + return dp[state] = res; + } +}; + + +int main() { + + vector rollMax1 = {1, 1, 2, 2, 2, 3}; + cout << Solution().dieSimulator(2, rollMax1) << endl; + // 34 + + vector rollMax2 = {1, 1, 1, 1, 1, 1}; + cout << Solution().dieSimulator(2, rollMax2) << endl; + // 30 + + vector rollMax3 = {1, 1, 1, 2, 2, 3}; + cout << Solution().dieSimulator(3, rollMax3) << endl; + // 181 + + vector rollMax4 = {13, 3, 12, 14, 11, 11}; + cout << Solution().dieSimulator(5000, rollMax4) << endl; + // 538400505 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1223-Dice-Roll-Simulation/cpp-1223/main3.cpp b/1001-1500/1223-Dice-Roll-Simulation/cpp-1223/main3.cpp new file mode 100644 index 00000000..060b133b --- /dev/null +++ b/1001-1500/1223-Dice-Roll-Simulation/cpp-1223/main3.cpp @@ -0,0 +1,65 @@ +/// Source : https://leetcode.com/problems/dice-roll-simulation/ +/// Author : liuyubobobo +/// Time : 2019-10-12 + +#include +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(n * 6 * max(rollMax) * 6) +/// Space Complexity: O(n * 6 * max(rollMax)) +class Solution { + +public: + int dieSimulator(int n, vector& rollMax) { + + const int MOD = 1e9 + 7; + + vector>> dp(n, vector>(*max_element(rollMax.begin(), rollMax.end()) + 1, vector(6, 0))); + for(int i = 0; i < 6; i ++) + dp[0][1][i] = 1; + + for(int index = 1; index < n; index ++) + for(int lastnum = 0; lastnum < 6; lastnum ++) + for(int lastfreq = 0; lastfreq <= rollMax[lastnum]; lastfreq ++) + for(int i = 0; i < 6; i ++) + if(i != lastnum) + dp[index][1][i] += dp[index - 1][lastfreq][lastnum], + dp[index][1][i] %= MOD; + else if(lastfreq + 1 <= rollMax[lastnum]) + dp[index][lastfreq + 1][i] += dp[index - 1][lastfreq][lastnum], + dp[index][lastfreq + 1][i] %= MOD; + + int res = 0; + for(int i = 0; i < dp[n - 1].size(); i ++) + for(int e: dp[n - 1][i]) + res = (res + e) % MOD; + return res; + } +}; + + +int main() { + + vector rollMax1 = {1, 1, 2, 2, 2, 3}; + cout << Solution().dieSimulator(2, rollMax1) << endl; + // 34 + + vector rollMax2 = {1, 1, 1, 1, 1, 1}; + cout << Solution().dieSimulator(2, rollMax2) << endl; + // 30 + + vector rollMax3 = {1, 1, 1, 2, 2, 3}; + cout << Solution().dieSimulator(3, rollMax3) << endl; + // 181 + + vector rollMax4 = {13, 3, 12, 14, 11, 11}; + cout << Solution().dieSimulator(5000, rollMax4) << endl; + // 538400505 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1224-Maximum-Equal-Frequency/cpp-1224/CMakeLists.txt b/1001-1500/1224-Maximum-Equal-Frequency/cpp-1224/CMakeLists.txt new file mode 100644 index 00000000..c0c37cc3 --- /dev/null +++ b/1001-1500/1224-Maximum-Equal-Frequency/cpp-1224/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main2.cpp) \ No newline at end of file diff --git a/1001-1500/1224-Maximum-Equal-Frequency/cpp-1224/main.cpp b/1001-1500/1224-Maximum-Equal-Frequency/cpp-1224/main.cpp new file mode 100644 index 00000000..acd09db5 --- /dev/null +++ b/1001-1500/1224-Maximum-Equal-Frequency/cpp-1224/main.cpp @@ -0,0 +1,90 @@ +/// Source : https://leetcode.com/problems/maximum-equal-frequency/ +/// Author : liuyubobobo +/// Time : 2019-10-12 + +#include +#include +#include + +using namespace std; + + +/// Using Map to record freq and the freq of freq number +/// Time Complexity: O(|nums|) +/// Space Complexity: O(|nums|) +class Solution { +public: + int maxEqualFreq(vector& nums) { + + if(nums.size() <= 3) return nums.size(); + + map freq; + for(int i = 0; i < 3; i ++) + freq[nums[i]] ++; + + map freqnum; + for(const pair& p: freq) + freqnum[p.second] ++; + + int res = 3; + for(int i = 3; i < nums.size(); i ++){ + int o_f = freq[nums[i]]; + if(o_f) { + freqnum[o_f]--; + if (freqnum[o_f] == 0) freqnum.erase(o_f); + } + freq[nums[i]] ++; + int new_f = freq[nums[i]]; + freqnum[new_f] ++; + +// cout << i << " : "; +// for(const pair& p: freqnum) cout << "(" << p.first << "," << p.second << ")"; +// cout << endl; + + if(freqnum.size() == 1 && (freqnum.begin()->first == 1 || freqnum.begin()->second == 1)) res = i + 1; + else if(freqnum.size() == 2){ + + map::iterator iter1 = freqnum.begin(); + map::iterator iter2 = freqnum.begin(); + iter2 ++; + if((iter1->first == 1 && iter1->second == 1) || + (iter2->second == 1 && iter2->first - iter1->first == 1)) res = i + 1; + } + } + return res; + } +}; + + +int main() { + + vector nums1 = {2,2,1,1,5,3,3,5}; + cout << Solution().maxEqualFreq(nums1) << endl; + // 7 + + vector nums2 = {1,1,1,2,2,2,3,3,3,4,4,4,5}; + cout << Solution().maxEqualFreq(nums2) << endl; + // 13 + + vector nums3 = {1,1,1,2,2,2}; + cout << Solution().maxEqualFreq(nums3) << endl; + // 5 + + vector nums4 = {10,2,8,9,3,8,1,5,2,3,7,6}; + cout << Solution().maxEqualFreq(nums4) << endl; + // 8 + + vector nums5 = {1,2,3,4,5,6,7,8,9}; + cout << Solution().maxEqualFreq(nums5) << endl; + // 9 + + vector nums6 = {1,1,1,1,1,1}; + cout << Solution().maxEqualFreq(nums6) << endl; + // 6 + + vector nums7 = {2,2,1,1,5,3,3,5}; + cout << Solution().maxEqualFreq(nums7) << endl; + // 7 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1224-Maximum-Equal-Frequency/cpp-1224/main2.cpp b/1001-1500/1224-Maximum-Equal-Frequency/cpp-1224/main2.cpp new file mode 100644 index 00000000..f267fb21 --- /dev/null +++ b/1001-1500/1224-Maximum-Equal-Frequency/cpp-1224/main2.cpp @@ -0,0 +1,77 @@ +/// Source : https://leetcode.com/problems/maximum-equal-frequency/ +/// Author : liuyubobobo +/// Time : 2019-10-12 + +#include +#include + +using namespace std; + + +/// Using Arraay to record freq and the freq of freq number +/// And make the logic more concise +/// Time Complexity: O(|nums|) +/// Space Complexity: O(|nums|) +class Solution { +public: + int maxEqualFreq(vector& nums) { + + if(nums.size() <= 3) return nums.size(); + + vector freq(*max_element(nums.begin(), nums.end()) + 1, 0); + vector freqnum(nums.size() + 1, 0); + + int res = 0; + for(int i = 0; i < nums.size(); i ++){ + int o_f = freq[nums[i]]; + if(o_f) freqnum[o_f]--; + freq[nums[i]] ++; + + int new_f = freq[nums[i]]; + freqnum[new_f] ++; + + if(freqnum[new_f] * new_f == i + 1 && i + 1 < nums.size()) + res = i + 2; + else{ + int left = i + 1 - new_f * freqnum[new_f]; + if((left == new_f + 1 || left == 1) && freqnum[left] == 1) + res = i + 1; + } + } + return res; + } +}; + + +int main() { + + vector nums1 = {2,2,1,1,5,3,3,5}; + cout << Solution().maxEqualFreq(nums1) << endl; + // 7 + + vector nums2 = {1,1,1,2,2,2,3,3,3,4,4,4,5}; + cout << Solution().maxEqualFreq(nums2) << endl; + // 13 + + vector nums3 = {1,1,1,2,2,2}; + cout << Solution().maxEqualFreq(nums3) << endl; + // 5 + + vector nums4 = {10,2,8,9,3,8,1,5,2,3,7,6}; + cout << Solution().maxEqualFreq(nums4) << endl; + // 8 + + vector nums5 = {1,2,3,4,5,6,7,8,9}; + cout << Solution().maxEqualFreq(nums5) << endl; + // 9 + + vector nums6 = {1,1,1,1,1,1}; + cout << Solution().maxEqualFreq(nums6) << endl; + // 6 + + vector nums7 = {2,2,1,1,5,3,3,5}; + cout << Solution().maxEqualFreq(nums7) << endl; + // 7 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1228-Missing-Number-In-Arithmetic-Progression/cpp-1228/CMakeLists.txt b/1001-1500/1228-Missing-Number-In-Arithmetic-Progression/cpp-1228/CMakeLists.txt new file mode 100644 index 00000000..6533b1b9 --- /dev/null +++ b/1001-1500/1228-Missing-Number-In-Arithmetic-Progression/cpp-1228/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(cpp_1228) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1228 main3.cpp) \ No newline at end of file diff --git a/1001-1500/1228-Missing-Number-In-Arithmetic-Progression/cpp-1228/main.cpp b/1001-1500/1228-Missing-Number-In-Arithmetic-Progression/cpp-1228/main.cpp new file mode 100644 index 00000000..dcf2d6aa --- /dev/null +++ b/1001-1500/1228-Missing-Number-In-Arithmetic-Progression/cpp-1228/main.cpp @@ -0,0 +1,32 @@ +/// Source : https://leetcode.com/problems/missing-number-in-arithmetic-progression/ +/// Author : liuyubobobo +/// Time : 2019-10-19 + +#include +#include + +using namespace std; + + +/// Linear Scan and find the max gap between numbers +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int missingNumber(vector& arr) { + + int maxGap = arr[1] - arr[0], start = 0; + for(int i = 2; i < arr.size(); i ++) + if(abs(arr[i] - arr[i - 1]) > abs(maxGap)){ + maxGap = arr[i] - arr[i - 1]; + start = i -1; + } + return arr[start] + maxGap / 2; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1228-Missing-Number-In-Arithmetic-Progression/cpp-1228/main2.cpp b/1001-1500/1228-Missing-Number-In-Arithmetic-Progression/cpp-1228/main2.cpp new file mode 100644 index 00000000..e71ae147 --- /dev/null +++ b/1001-1500/1228-Missing-Number-In-Arithmetic-Progression/cpp-1228/main2.cpp @@ -0,0 +1,36 @@ +/// Source : https://leetcode.com/problems/missing-number-in-arithmetic-progression/ +/// Author : liuyubobobo +/// Time : 2019-10-19 + +#include +#include +#include + +using namespace std; + + +/// Using mathematics to calculate difference first +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int missingNumber(vector& arr) { + + int d = (arr.back() - arr[0]) / (int)arr.size(); + for(int i = 1; i < arr.size(); i ++) + if(arr[i] != arr[i - 1] + d) return arr[i - 1] + d; + + // a tricky case is d == 0 + assert(d == 0); + return arr[0]; + } +}; + + +int main() { + + vector arr1 = {15, 13, 12}; + cout << Solution().missingNumber(arr1) << endl; + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1228-Missing-Number-In-Arithmetic-Progression/cpp-1228/main3.cpp b/1001-1500/1228-Missing-Number-In-Arithmetic-Progression/cpp-1228/main3.cpp new file mode 100644 index 00000000..052dd5fd --- /dev/null +++ b/1001-1500/1228-Missing-Number-In-Arithmetic-Progression/cpp-1228/main3.cpp @@ -0,0 +1,41 @@ +/// Source : https://leetcode.com/problems/missing-number-in-arithmetic-progression/ +/// Author : liuyubobobo +/// Time : 2019-10-19 + +#include +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(logn) +/// Space Complexity: O(1) +class Solution { +public: + int missingNumber(vector& arr) { + + int d = (arr.back() - arr[0]) / (int)arr.size(); + int l = 0, r = arr.size() - 1; + while(l < r){ + int mid = (l + r) / 2; + int num = arr[0] + mid * d; + if(num != arr[mid]) + r = mid; + else + l = mid + 1; + } + return arr[l] - d; + } +}; + + +int main() { + + vector arr1 = {15, 13, 12}; + cout << Solution().missingNumber(arr1) << endl; + // 14 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1229-Meeting-Scheduler/cpp-1229/CMakeLists.txt b/1001-1500/1229-Meeting-Scheduler/cpp-1229/CMakeLists.txt new file mode 100644 index 00000000..f8c28f70 --- /dev/null +++ b/1001-1500/1229-Meeting-Scheduler/cpp-1229/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(cpp_1229) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1229 main2.cpp) \ No newline at end of file diff --git a/1001-1500/1229-Meeting-Scheduler/cpp-1229/main.cpp b/1001-1500/1229-Meeting-Scheduler/cpp-1229/main.cpp new file mode 100644 index 00000000..d8b3f443 --- /dev/null +++ b/1001-1500/1229-Meeting-Scheduler/cpp-1229/main.cpp @@ -0,0 +1,59 @@ +/// Source : https://leetcode.com/problems/meeting-scheduler/ +/// Author : liuyubobobo +/// Time : 2019-10-19 +/// Updated: 2021-04-29 + +#include +#include + +using namespace std; + + +/// Sorting and Two Pointers +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + vector minAvailableDuration(vector>& slots1, vector>& slots2, int duration) { + + sort(slots1.begin(), slots1.end(), [](const vector& a, const vector& b){ + if(a[0] != b[0]) return a[0] < b[0]; + return a[1] < b[1]; + }); + + sort(slots2.begin(), slots2.end(), [](const vector& a, const vector& b){ + if(a[0] != b[0]) return a[0] < b[0]; + return a[1] < b[1]; + }); + + int i = 0, j = 0; + while(i < slots1.size() && j < slots2.size()){ + + int a = max(slots1[i][0], slots2[j][0]); + int b = min(slots1[i][1], slots2[j][1]); + if(b > a && b - a >= duration) return {a, a + duration}; + + if(slots1[i][1] > b) j ++; + else if(slots2[j][1] > b) i ++; + else if(slots1[i][0] < slots2[j][0]) i ++; + else if(slots1[i][0] > slots2[j][0]) j ++; + else if(slots1[i][1] < slots1[j][1]) i ++; + else j ++; + } + return {}; + } +}; + + +void print_vec(const vector& vec){ + + for(int e: vec) cout << e << " "; cout << endl; +} + +int main() { + + vector> slot1 = {{10, 60}}, slot2 = {{12, 17}, {21, 50}}; + print_vec(Solution().minAvailableDuration(slot1, slot2, 8)); + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1229-Meeting-Scheduler/cpp-1229/main2.cpp b/1001-1500/1229-Meeting-Scheduler/cpp-1229/main2.cpp new file mode 100644 index 00000000..b5719b56 --- /dev/null +++ b/1001-1500/1229-Meeting-Scheduler/cpp-1229/main2.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/meeting-scheduler/ +/// Author : liuyubobobo +/// Time : 2019-10-19 +/// Updated: 2021-04-29 + +#include +#include +#include + +using namespace std; + + +/// Using Priority Queue +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + vector minAvailableDuration(vector>& slots1, vector>& slots2, int duration) { + + priority_queue, vector>, greater>> pq1; + for(const vector& p: slots1) + pq1.push(make_pair(p[0], p[1])); + + priority_queue, vector>, greater>> pq2; + for(const vector& p: slots2) + pq2.push(make_pair(p[0], p[1])); + + while(!pq1.empty() && !pq2.empty()){ + pair p1 = pq1.top(); + pair p2 = pq2.top(); + + int a = max(p1.first, p2.first); + int b = min(p1.second, p2.second); + if(a <= b && a + duration <= b) return {a, a + duration}; + + if(p1.second < p2.second) pq1.pop(); + else if(p2.second < p1.second) pq2.pop(); + else if(p1 < p2) pq1.pop(); + else pq2.pop(); + } + return {}; + } +}; + + +void print_vec(const vector& vec){ + + for(int e: vec) cout << e << " "; cout << endl; +} + +int main() { + + vector> slot1 = {{10, 60}}, slot2 = {{12, 17}, {21, 50}}; + print_vec(Solution().minAvailableDuration(slot1, slot2, 8)); + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1230-Toss-Strange-Coins/cpp-1230/CMakeLists.txt b/1001-1500/1230-Toss-Strange-Coins/cpp-1230/CMakeLists.txt new file mode 100644 index 00000000..6ed49253 --- /dev/null +++ b/1001-1500/1230-Toss-Strange-Coins/cpp-1230/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(cpp_1230) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1230 main3.cpp) \ No newline at end of file diff --git a/1001-1500/1230-Toss-Strange-Coins/cpp-1230/main.cpp b/1001-1500/1230-Toss-Strange-Coins/cpp-1230/main.cpp new file mode 100644 index 00000000..7f7a7d18 --- /dev/null +++ b/1001-1500/1230-Toss-Strange-Coins/cpp-1230/main.cpp @@ -0,0 +1,44 @@ +/// Source : https://leetcode.com/problems/toss-strange-coins/ +/// Author : liuyubobobo +/// Time : 2019-10-19 + +#include +#include + +using namespace std; + + +/// Dynamaic Programming +/// Time Complexity: O(|prob| * target) +/// Space Complexity: O(|prob| * target) +class Solution { + +public: + double probabilityOfHeads(vector& prob, int target) { + + int n = prob.size(); + vector> dp(n, vector(target + 1, 0.0)); + if(target) dp[0][1] = prob[0]; + dp[0][0] = 1.0 - prob[0]; + for(int i = 1; i < n; i ++){ + dp[i][0] = dp[i - 1][0] * (1 - prob[i]); + for(int j = 1; j <= target; j ++) + dp[i][j] = dp[i - 1][j] * (1 - prob[i]) + dp[i - 1][j - 1] * prob[i]; + } + return dp[n - 1][target]; + } +}; + + +int main() { + + vector prob1 = {0.4}; + cout << Solution().probabilityOfHeads(prob1, 1) << endl; + // 0.4 + + vector prob2 = {0.5,0.5,0.5,0.5,0.5}; + cout << Solution().probabilityOfHeads(prob2, 0) << endl; + // 0.03125 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1230-Toss-Strange-Coins/cpp-1230/main2.cpp b/1001-1500/1230-Toss-Strange-Coins/cpp-1230/main2.cpp new file mode 100644 index 00000000..85021497 --- /dev/null +++ b/1001-1500/1230-Toss-Strange-Coins/cpp-1230/main2.cpp @@ -0,0 +1,44 @@ +/// Source : https://leetcode.com/problems/toss-strange-coins/ +/// Author : liuyubobobo +/// Time : 2019-10-19 + +#include +#include + +using namespace std; + + +/// Dynamaic Programming with Space Optimization +/// Time Complexity: O(|prob| * target) +/// Space Complexity: O(target) +class Solution { + +public: + double probabilityOfHeads(vector& prob, int target) { + + int n = prob.size(); + vector> dp(2, vector(target + 1, 0.0)); + if(target) dp[0][1] = prob[0]; + dp[0][0] = 1.0 - prob[0]; + for(int i = 1; i < n; i ++){ + dp[i % 2][0] = dp[(i - 1) % 2][0] * (1 - prob[i]); + for(int j = 1; j <= target; j ++) + dp[i % 2][j] = dp[(i - 1) % 2][j] * (1 - prob[i]) + dp[(i - 1) % 2][j - 1] * prob[i]; + } + return dp[(n - 1) % 2][target]; + } +}; + + +int main() { + + vector prob1 = {0.4}; + cout << Solution().probabilityOfHeads(prob1, 1) << endl; + // 0.4 + + vector prob2 = {0.5,0.5,0.5,0.5,0.5}; + cout << Solution().probabilityOfHeads(prob2, 0) << endl; + // 0.03125 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1230-Toss-Strange-Coins/cpp-1230/main3.cpp b/1001-1500/1230-Toss-Strange-Coins/cpp-1230/main3.cpp new file mode 100644 index 00000000..0372c0a1 --- /dev/null +++ b/1001-1500/1230-Toss-Strange-Coins/cpp-1230/main3.cpp @@ -0,0 +1,45 @@ +/// Source : https://leetcode.com/problems/toss-strange-coins/ +/// Author : liuyubobobo +/// Time : 2019-10-19 + +#include +#include + +using namespace std; + + +/// Dynamaic Programming with Space Optimization +/// Time Complexity: O(|prob| * target) +/// Space Complexity: O(target) +class Solution { + +public: + double probabilityOfHeads(vector& prob, int target) { + + int n = prob.size(); + vector dp(target + 1, 0.0); + + if(target) dp[1] = prob[0]; + dp[0] = 1.0 - prob[0]; + for(int i = 1; i < n; i ++){ + for(int j = target; j >= 1; j --) + dp[j] = dp[j] * (1 - prob[i]) + dp[j - 1] * prob[i]; + dp[0] = dp[0] * (1 - prob[i]); + } + return dp[target]; + } +}; + + +int main() { + + vector prob1 = {0.4}; + cout << Solution().probabilityOfHeads(prob1, 1) << endl; + // 0.4 + + vector prob2 = {0.5,0.5,0.5,0.5,0.5}; + cout << Solution().probabilityOfHeads(prob2, 0) << endl; + // 0.03125 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1231-Divide-Chocolate/cpp-1231/CMakeLists.txt b/1001-1500/1231-Divide-Chocolate/cpp-1231/CMakeLists.txt new file mode 100644 index 00000000..ec18b09f --- /dev/null +++ b/1001-1500/1231-Divide-Chocolate/cpp-1231/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(cpp_1231) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1231 main.cpp) \ No newline at end of file diff --git a/1001-1500/1231-Divide-Chocolate/cpp-1231/main.cpp b/1001-1500/1231-Divide-Chocolate/cpp-1231/main.cpp new file mode 100644 index 00000000..43ac4ef4 --- /dev/null +++ b/1001-1500/1231-Divide-Chocolate/cpp-1231/main.cpp @@ -0,0 +1,56 @@ +/// Source : https://leetcode.com/problems/divide-chocolate/ +/// Author : liuyubobobo +/// Time : 2019-10-20 + +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(n * log(10^9)) +/// Spaace Complexity: O(1) +class Solution { +public: + int maximizeSweetness(vector& sweetness, int K) { + + int l = 0, r = 1e9; + while(l < r){ + int mid = l + (r - l + 1) / 2; + if(ok(sweetness, K + 1, mid)) l = mid; + else r = mid - 1; + } + return l; + } + +private: + int ok(const vector& sweetness, int K, int sum){ + + int n = 0, cur = 0; + for(int e: sweetness){ + if(cur < sum) cur += e; + else n ++, cur = e; + } + if(cur >= sum) n ++; + return n >= K; + } +}; + + +int main() { + + vector sweetness1 = {1, 2, 3, 4, 5, 6, 7, 8, 9}; + cout << Solution().maximizeSweetness(sweetness1, 5) << endl; + // 6 + + vector sweetness2 = {5,6,7,8,9,1,2,3,4}; + cout << Solution().maximizeSweetness(sweetness2, 8) << endl; + // 1 + + vector sweetness3 = {1,2,2,1,2,2,1,2,2}; + cout << Solution().maximizeSweetness(sweetness3, 2) << endl; + // 5 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1232-Check-If-It-Is-a-Straight-Line/cpp-1232/CMakeLists.txt b/1001-1500/1232-Check-If-It-Is-a-Straight-Line/cpp-1232/CMakeLists.txt new file mode 100644 index 00000000..9c0b049b --- /dev/null +++ b/1001-1500/1232-Check-If-It-Is-a-Straight-Line/cpp-1232/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1001-1500/1232-Check-If-It-Is-a-Straight-Line/cpp-1232/main.cpp b/1001-1500/1232-Check-If-It-Is-a-Straight-Line/cpp-1232/main.cpp new file mode 100644 index 00000000..d5d43325 --- /dev/null +++ b/1001-1500/1232-Check-If-It-Is-a-Straight-Line/cpp-1232/main.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/check-if-it-is-a-straight-line/ +/// Author : liuyubobobo +/// Time : 2019-10-19 + +#include +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + bool checkStraightLine(vector>& coordinates) { + + int a = coordinates[1][1] - coordinates[0][1]; + int b = coordinates[1][0] - coordinates[0][0]; + for(int i = 2; i < coordinates.size(); i ++){ + int y = coordinates[i][1] - coordinates[0][1]; + int x = coordinates[i][0] - coordinates[0][0]; + if(y * b != x * a) return false; + } + return true; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1233-Remove-Sub-Folders-from-the-Filesystem/cpp-1233/CMakeLists.txt b/1001-1500/1233-Remove-Sub-Folders-from-the-Filesystem/cpp-1233/CMakeLists.txt new file mode 100644 index 00000000..c3e75f47 --- /dev/null +++ b/1001-1500/1233-Remove-Sub-Folders-from-the-Filesystem/cpp-1233/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main2.cpp) \ No newline at end of file diff --git a/1001-1500/1233-Remove-Sub-Folders-from-the-Filesystem/cpp-1233/main.cpp b/1001-1500/1233-Remove-Sub-Folders-from-the-Filesystem/cpp-1233/main.cpp new file mode 100644 index 00000000..824cbd99 --- /dev/null +++ b/1001-1500/1233-Remove-Sub-Folders-from-the-Filesystem/cpp-1233/main.cpp @@ -0,0 +1,92 @@ +/// Source : https://leetcode.com/problems/remove-sub-folders-from-the-filesystem/ +/// Author : liuyubobobo +/// Time : 2019-10-19 + +#include +#include +#include +#include + +using namespace std; + + +/// Trie +/// Time Complexity: O(total splits) +/// Space Complexity: O(total splits) +class Solution { + +private: + class Node{ + + public: + string s; + map next; + + Node(): s(""){} + }; + + Node* trie = NULL; + +public: + vector removeSubfolders(vector& folder) { + + trie = new Node(); + for(const string& s: folder){ + vector vec = split(s); +// for(const string e: vec) cout << e << " "; cout << endl; + + Node* cur = trie; + for(const string& f: vec) { + if (!cur->next.count(f)) cur->next[f] = new Node(); + cur = cur->next[f]; + } + cur->s = s; + } + + set set(folder.begin(), folder.end()); + dfs(trie, false, set); + return vector(set.begin(), set.end()); + } + +private: + void dfs(Node* node, bool parent, set& set){ + + if(node->s != "" && parent) set.erase(node->s); + + for(const pair& p: node->next) + dfs(p.second, parent || node->s != "", set); + } + + vector split(const string& s){ + vector res; + for(int start = 1, i = start + 1; i <= s.size(); i ++) + if(i == s.size() || s[i] == '/'){ + res.push_back(s.substr(start, i - start)); + start = i + 1; + i = start; + } + return res; + } +}; + + +void print_vec(const vector& v){ + for(const string& s: v) cout << s << " "; cout << endl; +} + +int main() { + + vector folders1 = {"/a","/a/b","/c/d","/c/d/e","/c/f"}; + print_vec(Solution().removeSubfolders(folders1)); + // "/a","/c/d","/c/f" + + vector folders2 = {"/a","/a/b/c","/a/b/d"}; + print_vec(Solution().removeSubfolders(folders2)); + // "/a" + + vector folders3 = {"/a/b/c","/a/b/ca","/a/b/d"}; + print_vec(Solution().removeSubfolders(folders3)); + // "/a/b/c" "/a/b/ca" "/a/b/d" + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1233-Remove-Sub-Folders-from-the-Filesystem/cpp-1233/main2.cpp b/1001-1500/1233-Remove-Sub-Folders-from-the-Filesystem/cpp-1233/main2.cpp new file mode 100644 index 00000000..1f0f8c2b --- /dev/null +++ b/1001-1500/1233-Remove-Sub-Folders-from-the-Filesystem/cpp-1233/main2.cpp @@ -0,0 +1,65 @@ +/// Source : https://leetcode.com/problems/remove-sub-folders-from-the-filesystem/ +/// Author : liuyubobobo +/// Time : 2019-10-20 + +#include +#include +#include +#include + +using namespace std; + + +/// Sorting +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { + +public: + vector removeSubfolders(vector& folder) { + + sort(folder.begin(), folder.end()); + + vector res; + for(int t = 0, i = 1; i <= folder.size(); i ++) + if(i == folder.size() || !isSubfolder(folder[t], folder[i])){ + res.push_back(folder[t]); + t = i; + i = t; + } + return res; + } + +private: + bool isSubfolder(const string& p, const string& s){ + if(p.size() > s.size()) return false; + if(p.size() == s.size()) return p == s; + return s.substr(0, p.size()) == p && s[p.size()] == '/'; + } +}; + + +void print_vec(const vector& v){ + for(const string& s: v) cout << s << " "; cout << endl; +} + +int main() { + + vector folders1 = {"/a","/a/b","/c/d","/c/d/e","/c/f"}; + print_vec(Solution().removeSubfolders(folders1)); + // "/a","/c/d","/c/f" + + vector folders2 = {"/a","/a/b/c","/a/b/d"}; + print_vec(Solution().removeSubfolders(folders2)); + // "/a" + + vector folders3 = {"/a/b/c","/a/b/ca","/a/b/d"}; + print_vec(Solution().removeSubfolders(folders3)); + // "/a/b/c" "/a/b/ca" "/a/b/d" + + vector folders4 = {"/a/b/c","/a/b/ca","/a/b/d"}; + print_vec(Solution().removeSubfolders(folders4)); + // "/a/b/c","/a/b/ca","/a/b/d" + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1234-Replace-the-Substring-for-Balanced-String/cpp-1234/CMakeLists.txt b/1001-1500/1234-Replace-the-Substring-for-Balanced-String/cpp-1234/CMakeLists.txt new file mode 100644 index 00000000..0b46ca4b --- /dev/null +++ b/1001-1500/1234-Replace-the-Substring-for-Balanced-String/cpp-1234/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1001-1500/1234-Replace-the-Substring-for-Balanced-String/cpp-1234/main.cpp b/1001-1500/1234-Replace-the-Substring-for-Balanced-String/cpp-1234/main.cpp new file mode 100644 index 00000000..168d83f5 --- /dev/null +++ b/1001-1500/1234-Replace-the-Substring-for-Balanced-String/cpp-1234/main.cpp @@ -0,0 +1,70 @@ +/// Source : https://leetcode.com/problems/replace-the-substring-for-balanced-string/ +/// Author : liuyubobobo +/// Time : 2019-10-19 + +#include +#include +#include + +using namespace std; + + +/// Sliding Window +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { + +private: + vector charv = {'Q', 'W', 'E', 'R'}; + +public: + int balancedString(string s) { + + map freq; + for(char c: charv) freq[c] = 0; + for(char c: s) freq[c] ++; + + int m = s.size() / 4; + for(const pair& p: freq) + if(p.second >= m) freq[p.first] -= m; + else freq[p.first] = 0; + + map cur; + for(char c: charv) cur[c] = 0; + int l = 0, r = -1, res = INT_MAX; + while(l < s.size()){ + if(ok(cur, freq)) res = min(res, r - l + 1), cur[s[l ++]] --; + else if(r + 1 < s.size()) cur[s[++r]] ++; + else break; + } + return res; + } + +private: + bool ok(map& cur, map& demand){ + for(char c: charv) + if(cur[c] < demand[c]) return false; + return true; + } +}; + + +int main() { + + cout << Solution().balancedString("QWER") << endl; + // 0 + + cout << Solution().balancedString("QQWE") << endl; + // 1 + + cout << Solution().balancedString("QQQW") << endl; + // 2 + + cout << Solution().balancedString("QQQQ") << endl; + // 3 + + cout << Solution().balancedString("WQWRQQQW") << endl; + // 3 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1235-Maximum-Profit-in-Job-Scheduling/cpp-1235/CMakeLists.txt b/1001-1500/1235-Maximum-Profit-in-Job-Scheduling/cpp-1235/CMakeLists.txt new file mode 100644 index 00000000..c0c37cc3 --- /dev/null +++ b/1001-1500/1235-Maximum-Profit-in-Job-Scheduling/cpp-1235/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main2.cpp) \ No newline at end of file diff --git a/1001-1500/1235-Maximum-Profit-in-Job-Scheduling/cpp-1235/main.cpp b/1001-1500/1235-Maximum-Profit-in-Job-Scheduling/cpp-1235/main.cpp new file mode 100644 index 00000000..5dfbfa5b --- /dev/null +++ b/1001-1500/1235-Maximum-Profit-in-Job-Scheduling/cpp-1235/main.cpp @@ -0,0 +1,67 @@ +/// Source : https://leetcode.com/problems/maximum-profit-in-job-scheduling/ +/// Author : liuyubobobo +/// Time : 2019-10-19 + +#include +#include +#include + +using namespace std; + + +/// Dynamic Programming + Binary Search +/// Backwards +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + int jobScheduling(vector& startTime, vector& endTime, vector& profit) { + + int n = startTime.size(); + + vector, int>> vec; + for(int i = 0; i < n; i ++) + vec.push_back(make_pair(make_pair(startTime[i], endTime[i]), profit[i])); + sort(vec.begin(), vec.end()); + + vector dp(n, vec.back().second); + for(int i = n - 2; i >= 0; i --){ + + dp[i] = dp[i + 1]; + + int nextstart = vec[i].first.second; + vector, int>>::iterator iter = + lower_bound(vec.begin() + (i + 1), vec.end(), make_pair(make_pair(nextstart, INT_MIN), INT_MIN)); + if(iter != vec.end()) + dp[i] = max(dp[i], vec[i].second + dp[iter - vec.begin()]); + else + dp[i] = max(dp[i], vec[i].second); + } + + return dp[0]; + } +}; + + +int main() { + + vector startTime1 = {1,2,3,3}; + vector endTime1 = {3,4,5,6}; + vector profit1 = {50,10,40,70}; + cout << Solution().jobScheduling(startTime1, endTime1, profit1) << endl; + // 120 + + vector startTime2 = {1,2,3,4,6}; + vector endTime2 = {3,5,10,6,9}; + vector profit2 = {20,20,100,70,60}; + cout << Solution().jobScheduling(startTime2, endTime2, profit2) << endl; + // 150 + + vector startTime3 = {1,1,1}; + vector endTime3 = {2,3,4}; + vector profit3 = {5,6,4}; + cout << Solution().jobScheduling(startTime3, endTime3, profit3) << endl; + // 6 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1235-Maximum-Profit-in-Job-Scheduling/cpp-1235/main2.cpp b/1001-1500/1235-Maximum-Profit-in-Job-Scheduling/cpp-1235/main2.cpp new file mode 100644 index 00000000..d26129a9 --- /dev/null +++ b/1001-1500/1235-Maximum-Profit-in-Job-Scheduling/cpp-1235/main2.cpp @@ -0,0 +1,73 @@ +/// Source : https://leetcode.com/problems/maximum-profit-in-job-scheduling/ +/// Author : liuyubobobo +/// Time : 2019-10-20 + +#include +#include +#include + +using namespace std; + + +/// Dynamic Programming + Binary Search +/// Forwards +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + int jobScheduling(vector& startTime, vector& endTime, vector& profit) { + + int n = startTime.size(); + + vector, int>> vec; + for(int i = 0; i < n; i ++) + vec.push_back(make_pair(make_pair(endTime[i], startTime[i]), profit[i])); + sort(vec.begin(), vec.end()); + + vector dp(n, vec[0].second); + for(int i = 1; i < n; i ++){ + + dp[i] = max(dp[i - 1], vec[i].second); + + int preend = vec[i].first.second; + vector, int>>::iterator iter = + lower_bound(vec.begin(), vec.begin() + i, make_pair(make_pair(preend, INT_MAX), INT_MAX)); + if(iter == vec.begin() + i) iter--; + else if(iter->first.first > preend && iter != vec.begin()) iter --; + if(iter->first.first <= preend) + dp[i] = max(dp[i], vec[i].second + dp[iter - vec.begin()]); + } + + return dp[n - 1]; + } +}; + + +int main() { + + vector startTime1 = {1,2,3,3}; + vector endTime1 = {3,4,5,6}; + vector profit1 = {50,10,40,70}; + cout << Solution().jobScheduling(startTime1, endTime1, profit1) << endl; + // 120 + + vector startTime2 = {1,2,3,4,6}; + vector endTime2 = {3,5,10,6,9}; + vector profit2 = {20,20,100,70,60}; + cout << Solution().jobScheduling(startTime2, endTime2, profit2) << endl; + // 150 + + vector startTime3 = {1,1,1}; + vector endTime3 = {2,3,4}; + vector profit3 = {5,6,4}; + cout << Solution().jobScheduling(startTime3, endTime3, profit3) << endl; + // 6 + + vector startTime4 = {4,2,4,8,2}; + vector endTime4 = {5,5,5,10,8}; + vector profit4 = {1,2,8,10,4}; + cout << Solution().jobScheduling(startTime4, endTime4, profit4) << endl; + // 18 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1236-Web-Crawler/cpp-1236/CMakeLists.txt b/1001-1500/1236-Web-Crawler/cpp-1236/CMakeLists.txt new file mode 100644 index 00000000..96241cea --- /dev/null +++ b/1001-1500/1236-Web-Crawler/cpp-1236/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_1236) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_1236 main.cpp) diff --git a/1001-1500/1236-Web-Crawler/cpp-1236/main.cpp b/1001-1500/1236-Web-Crawler/cpp-1236/main.cpp new file mode 100644 index 00000000..0ba3d9c0 --- /dev/null +++ b/1001-1500/1236-Web-Crawler/cpp-1236/main.cpp @@ -0,0 +1,55 @@ +/// Source : https://leetcode.com/problems/web-crawler/description/ +/// Author : liuyubobobo +/// Time : 2023-03-24 + +#include +#include +#include +#include + +using namespace std; + + +// This is the HtmlParser's API interface. +// You should not implement it, or speculate about its implementation +class HtmlParser { + public: + vector getUrls(string url); +}; + + +/// BFS +/// Time Complexity: O(V + E) +/// Space Complexity: O(V) +class Solution { +public: + vector crawl(string startUrl, HtmlParser htmlParser) { + + string hostname = startUrl.substr(7); + int pos = hostname.find("/"); + if(pos != string::npos) + hostname = hostname.substr(0, pos); + + set visited; + queue q; + q.push(startUrl); + visited.insert(startUrl); + while(!q.empty()){ + string url = q.front(); + q.pop(); + vector urls = htmlParser.getUrls(url); + for(auto u : urls){ + if(visited.find(u) == visited.end() && u.find(hostname) != string::npos){ + visited.insert(u); + q.push(u); + } + } + } + return vector(visited.begin(), visited.end()); + } +}; + +int main() { + + return 0; +} diff --git a/1001-1500/1237-Find-Positive-Integer-Solution-for-a-Given-Equation/cpp-1237/CMakeLists.txt b/1001-1500/1237-Find-Positive-Integer-Solution-for-a-Given-Equation/cpp-1237/CMakeLists.txt new file mode 100644 index 00000000..d98c23f5 --- /dev/null +++ b/1001-1500/1237-Find-Positive-Integer-Solution-for-a-Given-Equation/cpp-1237/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main3.cpp) \ No newline at end of file diff --git a/1001-1500/1237-Find-Positive-Integer-Solution-for-a-Given-Equation/cpp-1237/main.cpp b/1001-1500/1237-Find-Positive-Integer-Solution-for-a-Given-Equation/cpp-1237/main.cpp new file mode 100644 index 00000000..0f8cf23f --- /dev/null +++ b/1001-1500/1237-Find-Positive-Integer-Solution-for-a-Given-Equation/cpp-1237/main.cpp @@ -0,0 +1,30 @@ +/// Source : https://leetcode.com/problems/find-positive-integer-solution-for-a-given-equation/ +/// Author : liuyubobobo +/// Time : 2019-10-26 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(1000 * 1000) +/// Space Complexity: O(1) +class Solution { +public: + vector> findSolution(CustomFunction& customfunction, int z) { + + vector> res; + for(int x = 1; x <= 1000; x ++) + for(int y = 1; y <= 1000; y ++) + if(customfunction.f(x, y) == z) res.push_back({x, y}); + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1237-Find-Positive-Integer-Solution-for-a-Given-Equation/cpp-1237/main2.cpp b/1001-1500/1237-Find-Positive-Integer-Solution-for-a-Given-Equation/cpp-1237/main2.cpp new file mode 100644 index 00000000..5cc60373 --- /dev/null +++ b/1001-1500/1237-Find-Positive-Integer-Solution-for-a-Given-Equation/cpp-1237/main2.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/find-positive-integer-solution-for-a-given-equation/ +/// Author : liuyubobobo +/// Time : 2019-11-01 + +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(1000 * log(1000)) +/// Space Complexity: O(1) +class Solution { +public: + vector> findSolution(CustomFunction& customfunction, int z) { + + vector> res; + for(int x = 1; x <= z; x ++){ + int l = 1, r = 1000; + while(l <= r){ + int mid = (l + r) / 2; + int v = customfunction.f(x, mid); + if(v == z){ + res.push_back({x, mid}); + break; + } + else if(v < z) l = mid + 1; + else r = mid - 1; + } + } + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1237-Find-Positive-Integer-Solution-for-a-Given-Equation/cpp-1237/main3.cpp b/1001-1500/1237-Find-Positive-Integer-Solution-for-a-Given-Equation/cpp-1237/main3.cpp new file mode 100644 index 00000000..07bdebf4 --- /dev/null +++ b/1001-1500/1237-Find-Positive-Integer-Solution-for-a-Given-Equation/cpp-1237/main3.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/find-positive-integer-solution-for-a-given-equation/ +/// Author : liuyubobobo +/// Time : 2019-11-03 + +#include +#include + +using namespace std; + + +/// Two Pointers +/// Time Complexity: O(1000) +/// Space Complexity: O(1) +class Solution { +public: + vector> findSolution(CustomFunction& customfunction, int z) { + + vector> res; + for(int x = 1, y = 1000; x <= 1000 && y >= 1;){ + int v = customfunction.f(x, y); + if(v == z) res.push_back({x ++, y --}; + else if(v < z) y --; + else x ++; + } + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1238-Circular-Permutation-in-Binary-Representation/cpp-1238/CMakeLists.txt b/1001-1500/1238-Circular-Permutation-in-Binary-Representation/cpp-1238/CMakeLists.txt new file mode 100644 index 00000000..500a0b5c --- /dev/null +++ b/1001-1500/1238-Circular-Permutation-in-Binary-Representation/cpp-1238/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main3.cpp) \ No newline at end of file diff --git a/1001-1500/1238-Circular-Permutation-in-Binary-Representation/cpp-1238/main.cpp b/1001-1500/1238-Circular-Permutation-in-Binary-Representation/cpp-1238/main.cpp new file mode 100644 index 00000000..10569d09 --- /dev/null +++ b/1001-1500/1238-Circular-Permutation-in-Binary-Representation/cpp-1238/main.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/circular-permutation-in-binary-representation/ +/// Author : liuyubobobo +/// Time : 2019-10-26 + +#include +#include + +using namespace std; + + +/// Get all gray code first and then find the start +/// Time Complexity: O(2^n) +/// Space Complexity: O(2^n) +class Solution { +public: + vector circularPermutation(int n, int start) { + + vector res = gray(n); + + vector ret; + for(int i = 0; i < res.size(); i ++) + if(res[i] == start){ + int index = i, sz = 0; + while(ret.size() < res.size()) + ret.push_back(res[index ++ % res.size()]); + break; + } + return ret; + } + +private: + vector gray(int n){ + + if(n == 1) return {0, 1}; + + vector res = gray(n - 1); + for(int i = res.size() - 1; i >= 0; i --) + res.push_back(res[i] + (1 << (n - 1))); + return res; + } +}; + + +void print_vec(const vector& res){ + + for(int e: res) cout << e << " "; cout << endl; +} + +int main() { + + print_vec(Solution().circularPermutation(2,3)); + // 3 2 0 1 + + print_vec(Solution().circularPermutation(3,2)); + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1238-Circular-Permutation-in-Binary-Representation/cpp-1238/main2.cpp b/1001-1500/1238-Circular-Permutation-in-Binary-Representation/cpp-1238/main2.cpp new file mode 100644 index 00000000..bad4dbee --- /dev/null +++ b/1001-1500/1238-Circular-Permutation-in-Binary-Representation/cpp-1238/main2.cpp @@ -0,0 +1,56 @@ +/// Source : https://leetcode.com/problems/circular-permutation-in-binary-representation/ +/// Author : liuyubobobo +/// Time : 2019-10-26 + +#include +#include + +using namespace std; + + +/// Get all gray code first and then find the start +/// Just using reverse to get the result in place +/// Time Complexity: O(2^n) +/// Space Complexity: O(1) +class Solution { +public: + vector circularPermutation(int n, int start) { + + vector ret = gray(n); + + for(int i = 0; i < ret.size(); i ++) + if(ret[i] == start){ + reverse(ret.begin(), ret.begin() + (i + 1)); + reverse(ret.begin() + (i + 1), ret.end()); + break; + } + return ret; + } + +private: + vector gray(int n){ + + if(n == 1) return {0, 1}; + + vector res = gray(n - 1); + for(int i = res.size() - 1; i >= 0; i --) + res.push_back(res[i] + (1 << (n - 1))); + return res; + } +}; + + +void print_vec(const vector& res){ + + for(int e: res) cout << e << " "; cout << endl; +} + +int main() { + + print_vec(Solution().circularPermutation(2,3)); + // 3 2 0 1 + + print_vec(Solution().circularPermutation(3,2)); + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1238-Circular-Permutation-in-Binary-Representation/cpp-1238/main3.cpp b/1001-1500/1238-Circular-Permutation-in-Binary-Representation/cpp-1238/main3.cpp new file mode 100644 index 00000000..86f44f76 --- /dev/null +++ b/1001-1500/1238-Circular-Permutation-in-Binary-Representation/cpp-1238/main3.cpp @@ -0,0 +1,39 @@ +/// Source : https://leetcode.com/problems/circular-permutation-in-binary-representation/ +/// Author : liuyubobobo +/// Time : 2019-11-06 + +#include +#include + +using namespace std; + + +/// Gray Code Formula +/// Time Complexity: O(2^n) +/// Space Complexity: O(1) +class Solution { +public: + vector circularPermutation(int n, int start) { + + vector res; + for(int i = 0; i < (1 << n); i ++) + res.push_back(start ^ i ^ (i >> 1)); + return res; + } +}; + + +void print_vec(const vector& res){ + + for(int e: res) cout << e << " "; cout << endl; +} + +int main() { + + print_vec(Solution().circularPermutation(2,3)); + // 3 2 0 1 + + print_vec(Solution().circularPermutation(3,2)); + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1239-Maximum-Length-of-a-Concatenated-String-with-Unique-Characters/cpp-1239/CMakeLists.txt b/1001-1500/1239-Maximum-Length-of-a-Concatenated-String-with-Unique-Characters/cpp-1239/CMakeLists.txt new file mode 100644 index 00000000..64f6c751 --- /dev/null +++ b/1001-1500/1239-Maximum-Length-of-a-Concatenated-String-with-Unique-Characters/cpp-1239/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main2.cpp) \ No newline at end of file diff --git a/1001-1500/1239-Maximum-Length-of-a-Concatenated-String-with-Unique-Characters/cpp-1239/main.cpp b/1001-1500/1239-Maximum-Length-of-a-Concatenated-String-with-Unique-Characters/cpp-1239/main.cpp new file mode 100644 index 00000000..4235d00e --- /dev/null +++ b/1001-1500/1239-Maximum-Length-of-a-Concatenated-String-with-Unique-Characters/cpp-1239/main.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/ +/// Author : liuyubobobo +/// Time : 2019-10-26 + +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(2^n) +/// Space Complexity: O(n) +class Solution { +public: + int maxLength(vector& arr) { + + vector v; + for(const string& s: arr) + if(is_unique(s)) v.push_back(s); + + return dfs(v, 0, ""); + } + +private: + int dfs(const vector& v, int index, const string& cur){ + + if(index == v.size()) return 0; + + int res = dfs(v, index + 1, cur); + + if(is_unique(cur + v[index])) + res = max(res, (int)v[index].size() + dfs(v, index + 1, cur + v[index])); + return res; + } + + bool is_unique(const string& s){ + + vector visited(26); + for(char e: s) { + if (visited[e - 'a']) return false; + visited[e - 'a'] = true; + } + return true; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1239-Maximum-Length-of-a-Concatenated-String-with-Unique-Characters/cpp-1239/main2.cpp b/1001-1500/1239-Maximum-Length-of-a-Concatenated-String-with-Unique-Characters/cpp-1239/main2.cpp new file mode 100644 index 00000000..d60c97ba --- /dev/null +++ b/1001-1500/1239-Maximum-Length-of-a-Concatenated-String-with-Unique-Characters/cpp-1239/main2.cpp @@ -0,0 +1,59 @@ +/// Source : https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/ +/// Author : liuyubobobo +/// Time : 2019-11-08 + +#include +#include + +using namespace std; + + +/// DFS and using bit +/// Time Complexity: O(2^n) +/// Space Complexity: O(n) +class Solution { +public: + int maxLength(vector& arr) { + + vector v, lens; + for(const string& s: arr){ + int x = get_num(s); + if(x >= 0){ + v.push_back(x); + int len = 0; + while(x) len += x & 1, x >>= 1; + lens.push_back(len); + } + } + + return dfs(v, lens, 0, 0); + } + +private: + int dfs(const vector& v, const vector& lens, int index, int cur){ + + if(index == v.size()) return 0; + + int res = dfs(v, lens, index + 1, cur); + + if(!(cur & v[index])) + res = max(res, lens[index] + dfs(v, lens, index + 1, cur | v[index])); + return res; + } + + int get_num(const string& s){ + + int x = 0; + for(char c: s) { + if (x & (1 << (c - 'a'))) return -1; + x += (1 << (c - 'a')); + } + return x; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1240-Tiling-a-Rectangle-with-the-Fewest-Squares/cpp-1240/CMakeLists.txt b/1001-1500/1240-Tiling-a-Rectangle-with-the-Fewest-Squares/cpp-1240/CMakeLists.txt new file mode 100644 index 00000000..c0c37cc3 --- /dev/null +++ b/1001-1500/1240-Tiling-a-Rectangle-with-the-Fewest-Squares/cpp-1240/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main2.cpp) \ No newline at end of file diff --git a/1001-1500/1240-Tiling-a-Rectangle-with-the-Fewest-Squares/cpp-1240/main.cpp b/1001-1500/1240-Tiling-a-Rectangle-with-the-Fewest-Squares/cpp-1240/main.cpp new file mode 100644 index 00000000..664848fb --- /dev/null +++ b/1001-1500/1240-Tiling-a-Rectangle-with-the-Fewest-Squares/cpp-1240/main.cpp @@ -0,0 +1,64 @@ +/// Source : https://leetcode.com/problems/tiling-a-rectangle-with-the-fewest-squares/ +/// Author : liuyubobobo +/// Time : 2019-10-26 + +#include +#include +#include + +using namespace std; + + +/// Memory Searrch with Special case check +/// Time Complexity: O(n * m) +/// Space Complexity: O(n * m) +class Solution { + +public: + int tilingRectangle(int n, int m) { + + vector> dp(max(n, m) + 1, vector(min(n, m) + 1, -1)); + return dfs(n, m, dp); + } + +private: + int dfs(int n, int m, vector>& dp){ + if(n < m) swap(n, m); + + if(n == m) return 1; + if(m == 1) return n; + if(n == 13 && m == 11) return 6; // Special case + if(dp[n][m] != -1) return dp[n][m]; + + int g = gcd(n, m); + if(g != 1) return tilingRectangle(n / g, m / g); + + int ret = INT_MAX; + for(int i = 1; i < n; i ++) + ret = min(ret, dfs(i, m, dp) + dfs(n - i, m, dp)); + for(int i = 1; i < m; i ++) + ret = min(ret, dfs(n, i, dp) + dfs(n, m - i, dp)); +// cout << "solve " << n << " " << m << " : " << ret << endl; + return dp[n][m] = ret; + } + + int gcd(int a, int b){ + if(a % b == 0) return b; + return gcd(b, a % b); + } +}; + + +int main() { + + cout << Solution().tilingRectangle(2, 3) << endl; + // 3 + + cout << Solution().tilingRectangle(5, 8) << endl; + // 5 + + cout << Solution().tilingRectangle(11, 13) << endl; + // 6 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1240-Tiling-a-Rectangle-with-the-Fewest-Squares/cpp-1240/main2.cpp b/1001-1500/1240-Tiling-a-Rectangle-with-the-Fewest-Squares/cpp-1240/main2.cpp new file mode 100644 index 00000000..94a1de9c --- /dev/null +++ b/1001-1500/1240-Tiling-a-Rectangle-with-the-Fewest-Squares/cpp-1240/main2.cpp @@ -0,0 +1,51 @@ +/// Source : https://leetcode.com/problems/tiling-a-rectangle-with-the-fewest-squares/ +/// Author : liuyubobobo +/// Time : 2019-11-08 + +#include +#include +#include + +using namespace std; + + +/// Memory Searrch with Special case check +/// Time Complexity: O(n * m * max(n, m)) +/// Space Complexity: O(n * m * max(n, m)) +class Solution { + +public: + int tilingRectangle(int n, int m) { + + vector> dp(n + 1, vector(m + 1, INT_MAX)); + for(int j = 1; j <= m; j ++) dp[1][j] = j; + for(int i = 2; i <= n; i ++){ + dp[i][1] = i; + for(int j = 2; j <= m; j ++){ + if(i == j){dp[i][j] = 1;continue;} + if((i == 11 && j == 13) || (i == 13 && j == 11)){dp[i][j] = 6;continue;} + + for(int k = 1; k < i; k ++) + dp[i][j] = min(dp[i][j], dp[k][j] + dp[i - k][j]); + for(int k = 1; k < j; k ++) + dp[i][j] = min(dp[i][j], dp[i][k] + dp[i][j - k]); + } + } + return dp[n][m]; + } +}; + + +int main() { + + cout << Solution().tilingRectangle(2, 3) << endl; + // 3 + + cout << Solution().tilingRectangle(5, 8) << endl; + // 5 + + cout << Solution().tilingRectangle(11, 13) << endl; + // 6 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1243-Array-Transformation/cpp-1243/CMakeLists.txt b/1001-1500/1243-Array-Transformation/cpp-1243/CMakeLists.txt new file mode 100644 index 00000000..2920efb3 --- /dev/null +++ b/1001-1500/1243-Array-Transformation/cpp-1243/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(cpp_1243) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1243 main.cpp) \ No newline at end of file diff --git a/1001-1500/1243-Array-Transformation/cpp-1243/main.cpp b/1001-1500/1243-Array-Transformation/cpp-1243/main.cpp new file mode 100644 index 00000000..34802b76 --- /dev/null +++ b/1001-1500/1243-Array-Transformation/cpp-1243/main.cpp @@ -0,0 +1,36 @@ +/// Source : https://leetcode.com/problems/array-transformation/ +/// Author : liuyubobobo +/// Time : 2019-11-08 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(max(arr) * |arr|) +/// Space Complexity: O(|arr|) +class Solution { +public: + vector transformArray(vector& arr) { + + vector t = arr; + bool change = false; + do{ + change = false; + arr = t; + for(int i = 1; i < arr.size() - 1; i ++) + if(t[i - 1] > t[i] && t[i + 1] > t[i]){arr[i] ++; change = true;} + else if(t[i - 1] < t[i] && t[i + 1] < t[i]){arr[i] --; change = true;} + t = arr; + }while(change); + return arr; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1244-Design-A-Leaderboard/cpp-1244/CMakeLists.txt b/1001-1500/1244-Design-A-Leaderboard/cpp-1244/CMakeLists.txt new file mode 100644 index 00000000..b5a0aa6e --- /dev/null +++ b/1001-1500/1244-Design-A-Leaderboard/cpp-1244/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(cpp_1244) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1244 main.cpp) \ No newline at end of file diff --git a/1001-1500/1244-Design-A-Leaderboard/cpp-1244/main.cpp b/1001-1500/1244-Design-A-Leaderboard/cpp-1244/main.cpp new file mode 100644 index 00000000..c484b7df --- /dev/null +++ b/1001-1500/1244-Design-A-Leaderboard/cpp-1244/main.cpp @@ -0,0 +1,64 @@ +/// Source : https://leetcode.com/problems/design-a-leaderboard/ +/// Author : liuyubobobo +/// Time : 2020-05-07 + +#include +#include +#include + +using namespace std; + + +/// Using Map +/// Time Complexity: addScore: O(logn) +/// top: O(K) +/// reset: O(logn) +/// Space Complexity: O(n) +class Leaderboard { + +private: + unordered_map scores; // id -> score + map rscores; // score -> freq + +public: + Leaderboard() {} + + void addScore(int playerId, int score) { + + if(scores.count(playerId)) score += scores[playerId]; + reset(playerId); + + scores[playerId] = score; + rscores[-score] ++; + } + + int top(int K) { + int res = 0, k = 0; + for(const pair& p: rscores){ + for(int i = 0; i < p.second; i ++){ + res += -p.first; + k ++; + if(k == K) return res; + } + } + assert(false); + return -1; + } + + void reset(int playerId) { + + if(scores.count(playerId)){ + int score = scores[playerId]; + rscores[-score] --; + if(rscores[-score] == 0) rscores.erase(-score); + + scores.erase(playerId); + } + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1245-Tree-Diameter/cpp-1245/CMakeLists.txt b/1001-1500/1245-Tree-Diameter/cpp-1245/CMakeLists.txt new file mode 100644 index 00000000..6e033044 --- /dev/null +++ b/1001-1500/1245-Tree-Diameter/cpp-1245/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1245) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1245 main.cpp) \ No newline at end of file diff --git a/1001-1500/1245-Tree-Diameter/cpp-1245/main.cpp b/1001-1500/1245-Tree-Diameter/cpp-1245/main.cpp new file mode 100644 index 00000000..418edf3c --- /dev/null +++ b/1001-1500/1245-Tree-Diameter/cpp-1245/main.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/tree-diameter/ +/// Author : liuyubobobo +/// Time : 2020-10-15 + +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(h) +class Solution { + +private: + int res = 0; + +public: + int treeDiameter(vector>& edges) { + + int n = edges.size() + 1; + vector> g(n); + for(const vector& e: edges) + g[e[0]].push_back(e[1]), g[e[1]].push_back(e[0]); + + res = 0; + dfs(g, -1, 0); + return res; + } + +private: + int dfs(const vector>& g, int parent, int v){ + + int first = 0, second = 0; + for(int w: g[v]) + if(w != parent){ + int t = 1 + dfs(g, v, w); + if(t >= first) second = first, first = t; + else if(t > second) second = t; + } + + res = max(res, first + second); + return first; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1247-Minimum-Swaps-to-Make-Strings-Equal/cpp-1247/CMakeLists.txt b/1001-1500/1247-Minimum-Swaps-to-Make-Strings-Equal/cpp-1247/CMakeLists.txt new file mode 100644 index 00000000..98b83287 --- /dev/null +++ b/1001-1500/1247-Minimum-Swaps-to-Make-Strings-Equal/cpp-1247/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_1247) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_1247 main.cpp) diff --git a/1001-1500/1247-Minimum-Swaps-to-Make-Strings-Equal/cpp-1247/main.cpp b/1001-1500/1247-Minimum-Swaps-to-Make-Strings-Equal/cpp-1247/main.cpp new file mode 100644 index 00000000..2df53c62 --- /dev/null +++ b/1001-1500/1247-Minimum-Swaps-to-Make-Strings-Equal/cpp-1247/main.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/minimum-swaps-to-make-strings-equal/description/ +/// Author : liuyubobobo +/// Time : 2023-02-24 + +#include +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int minimumSwap(string s1, string s2) { + + int x1 = 0, y1 = 0, x2 = 0, y2 = 0; + for(char c: s1) if(c == 'x') x1 ++; else y1 ++; + for(char c: s2) if(c == 'x') x2 ++; else y2 ++; + + if((x1 + x2) & 1) return -1; + if((y1 + y2) & 1) return -1; + + int xy = 0, yx = 0; + for(int i = 0; i < s1.size(); i ++){ + if(s1[i] == 'x' && s2[i] == 'y') xy ++; + if(s1[i] == 'y' && s2[i] == 'x') yx ++; + } + + int res = 0; + res += xy / 2; xy %= 2; + res += yx / 2; yx %= 2; + if(xy){ + assert(yx); + res += 2; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1248-Count-Number-of-Nice-Subarrays/cpp-1248/CMakeLists.txt b/1001-1500/1248-Count-Number-of-Nice-Subarrays/cpp-1248/CMakeLists.txt new file mode 100644 index 00000000..b041bdce --- /dev/null +++ b/1001-1500/1248-Count-Number-of-Nice-Subarrays/cpp-1248/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_1248) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1248 main2.cpp) diff --git a/1001-1500/1248-Count-Number-of-Nice-Subarrays/cpp-1248/main.cpp b/1001-1500/1248-Count-Number-of-Nice-Subarrays/cpp-1248/main.cpp new file mode 100644 index 00000000..4a1b5948 --- /dev/null +++ b/1001-1500/1248-Count-Number-of-Nice-Subarrays/cpp-1248/main.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/count-number-of-nice-subarrays/ +/// Author : liuyubobobo +/// Time : 2022-02-04 + +#include +#include +#include + +using namespace std; + + +/// Presum + Map +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int numberOfSubarrays(vector& nums, int k) { + + // table[i] 存储的是当前看到有多少个位置,满足从 0 到这个位置,包含的奇数个数为 i + // table[3] == 5,表示当前已经看到有 5 个位置,从 0 到这个位置包含有 3 个奇数 + unordered_map table; // odd_num -> freq + + // 初始的空区间,包含有 0 个奇数 + table[0] = 1; + + // cur 记录 [0, i] 区间一共有多少个奇数 + int cur = 0, res = 0; + for(int i = 0; i < nums.size(); i ++){ + cur += nums[i] % 2; // 如果 nums[i] 是奇数,cur ++ + + // 查找 cur 之前有多少个位置,其奇数个数位 cur - k。 + // 那么从 这些位置 + 1,到 cur,就一共有 k 个奇数 + // 有 k 个奇数的区间数量 += table[cur - k] + if(table.count(cur - k)) + res += table[cur - k]; + + // 把 i 这个位置计算到 table 中 + // 因为 [0, i] 中有 cur 个奇数,所以 table[cur] ++ + table[cur] ++; + } + return res; + } +}; + + +int main() { + + vector nums1 = {1, 1, 2, 1, 1}; + cout << Solution().numberOfSubarrays(nums1, 3) << endl; + // 2 + + return 0; +} diff --git a/1001-1500/1248-Count-Number-of-Nice-Subarrays/cpp-1248/main2.cpp b/1001-1500/1248-Count-Number-of-Nice-Subarrays/cpp-1248/main2.cpp new file mode 100644 index 00000000..458d240f --- /dev/null +++ b/1001-1500/1248-Count-Number-of-Nice-Subarrays/cpp-1248/main2.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/count-number-of-nice-subarrays/ +/// Author : liuyubobobo +/// Time : 2022-02-04 + +#include +#include + +using namespace std; + + +/// Presum + Sliding Window +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int numberOfSubarrays(vector& nums, int k) { + + int n = nums.size(); + return f(n, nums, k) - f(n, nums, k - 1); + } + +private: + long long f(int n, const vector& nums, int k){ + + int l = 0, r = -1, cur_odd = 0; + long long res = 0; + while(l < n){ + if(r + 1 < n && cur_odd + nums[r + 1] % 2 <= k){ + r ++; + res += (r - l + 1); + cur_odd += nums[r] % 2; + } + else{ + cur_odd -= nums[l] % 2; + l ++; + } + } + return res; + } +}; + + +int main() { + + vector nums1 = {1, 1, 2, 1, 1}; + cout << Solution().numberOfSubarrays(nums1, 3) << endl; + // 2 + + return 0; +} diff --git a/1001-1500/1248-Count-Number-of-Nice-Subarrays/java-1248/src/Solution.java b/1001-1500/1248-Count-Number-of-Nice-Subarrays/java-1248/src/Solution.java new file mode 100644 index 00000000..9567a325 --- /dev/null +++ b/1001-1500/1248-Count-Number-of-Nice-Subarrays/java-1248/src/Solution.java @@ -0,0 +1,29 @@ +/// Source : https://leetcode.com/problems/count-number-of-nice-subarrays/ +/// Author : liuyubobobo +/// Time : 2022-02-06 + +import java.util.*; + + +/// Presum + Map +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + public int numberOfSubarrays(int[] nums, int k) { + + HashMap table = new HashMap<>(); + table.put(0, 1); + + int cur = 0, res = 0; + for(int i = 0; i < nums.length; i ++){ + + cur += nums[i] % 2; + + if(table.containsKey(cur - k)) + res += table.get(cur - k); + + table.put(cur, table.getOrDefault(cur, 0) + 1); + } + return res; + } +} diff --git a/1001-1500/1249-Minimum-Remove-to-Make-Valid-Parentheses/cpp-1249/CMakeLists.txt b/1001-1500/1249-Minimum-Remove-to-Make-Valid-Parentheses/cpp-1249/CMakeLists.txt new file mode 100644 index 00000000..fd2abe3a --- /dev/null +++ b/1001-1500/1249-Minimum-Remove-to-Make-Valid-Parentheses/cpp-1249/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1249) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1249 main2.cpp) \ No newline at end of file diff --git a/1001-1500/1249-Minimum-Remove-to-Make-Valid-Parentheses/cpp-1249/main.cpp b/1001-1500/1249-Minimum-Remove-to-Make-Valid-Parentheses/cpp-1249/main.cpp new file mode 100644 index 00000000..47017026 --- /dev/null +++ b/1001-1500/1249-Minimum-Remove-to-Make-Valid-Parentheses/cpp-1249/main.cpp @@ -0,0 +1,79 @@ +/// Source : https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/ +/// Author : liuyubobobo +/// Time : 2021-02-19 + +#include +#include + +using namespace std; + + +/// Stack - get braces pattern first +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + string minRemoveToMakeValid(string s) { + + string temp = ""; + for(char c: s) + if(!isalpha(c)) temp += c; + + string pattern = get_pattern(temp); +// cout << pattern << endl; + + string res = ""; + int p = 0; + for(char c: s) + if(isalpha(c)) + res += c; + else if(p < pattern.size() && pattern[p] == c) + res += c, p ++; + return res; + } + +private: + string get_pattern(const string& t){ + + vector ok(t.size(), false); + vector stack; + for(int i = 0; i < t.size(); i ++) + if(t[i] == '(') stack.push_back(i); + else if(!stack.empty()){ + ok[i] = ok[stack.back()] = true; + stack.pop_back(); + } + + string res = ""; + for(int i = 0; i < t.size(); i ++) + if(ok[i]) res += t[i]; + return res; + } +}; + + +int main() { + + cout << Solution().minRemoveToMakeValid("lee(t(c)o)de)") << endl; + // "lee(t(c)o)de" + + cout << Solution().minRemoveToMakeValid("a)b(c)d") << endl; + // "ab(c)d" + + cout << Solution().minRemoveToMakeValid("))((") << endl; + // "" + + cout << Solution().minRemoveToMakeValid("(a(b(c)d)") << endl; + // "a(b(c)d)" + + cout << Solution().minRemoveToMakeValid("())()(((") << endl; + // "()()" + + cout << Solution().minRemoveToMakeValid(")i()()((fm(((()") << endl; + // "i()()fm()" + + cout << Solution().minRemoveToMakeValid(")((((()v))(()((s(())") << endl; + // "((()v))()((s))" + + return 0; +} diff --git a/1001-1500/1249-Minimum-Remove-to-Make-Valid-Parentheses/cpp-1249/main2.cpp b/1001-1500/1249-Minimum-Remove-to-Make-Valid-Parentheses/cpp-1249/main2.cpp new file mode 100644 index 00000000..d17b484c --- /dev/null +++ b/1001-1500/1249-Minimum-Remove-to-Make-Valid-Parentheses/cpp-1249/main2.cpp @@ -0,0 +1,61 @@ +/// Source : https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/ +/// Author : liuyubobobo +/// Time : 2021-02-19 + +#include +#include + +using namespace std; + + +/// Stack - process on s directly +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + string minRemoveToMakeValid(string s) { + + vector ok(s.size(), false); + vector stack; + + for(int i = 0; i < s.size(); i ++) + if(isalpha(s[i])) ok[i] = true; + else if(s[i] == '(') stack.push_back(i); + else if(!stack.empty()){ + ok[i] = ok[stack.back()] = true; + stack.pop_back(); + } + + string res = ""; + for(int i = 0; i < s.size(); i ++) + if(ok[i]) res += s[i]; + return res; + } +}; + + +int main() { + + cout << Solution().minRemoveToMakeValid("lee(t(c)o)de)") << endl; + // "lee(t(c)o)de" + + cout << Solution().minRemoveToMakeValid("a)b(c)d") << endl; + // "ab(c)d" + + cout << Solution().minRemoveToMakeValid("))((") << endl; + // "" + + cout << Solution().minRemoveToMakeValid("(a(b(c)d)") << endl; + // "a(b(c)d)" + + cout << Solution().minRemoveToMakeValid("())()(((") << endl; + // "()()" + + cout << Solution().minRemoveToMakeValid(")i()()((fm(((()") << endl; + // "i()()fm()" + + cout << Solution().minRemoveToMakeValid(")((((()v))(()((s(())") << endl; + // "((()v))()((s))" + + return 0; +} diff --git a/1001-1500/1250-Check-If-It-Is-a-Good-Array/cpp-1250/CMakeLists.txt b/1001-1500/1250-Check-If-It-Is-a-Good-Array/cpp-1250/CMakeLists.txt new file mode 100644 index 00000000..3d294d36 --- /dev/null +++ b/1001-1500/1250-Check-If-It-Is-a-Good-Array/cpp-1250/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_1250) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_1250 main.cpp) diff --git a/1001-1500/1250-Check-If-It-Is-a-Good-Array/cpp-1250/main.cpp b/1001-1500/1250-Check-If-It-Is-a-Good-Array/cpp-1250/main.cpp new file mode 100644 index 00000000..c11ec797 --- /dev/null +++ b/1001-1500/1250-Check-If-It-Is-a-Good-Array/cpp-1250/main.cpp @@ -0,0 +1,36 @@ +/// Source : https://leetcode.com/problems/check-if-it-is-a-good-array/description/ +/// Author : liuyubobobo +/// Time : 2023-02-14 + +#include +#include + +using namespace std; + + +/// Math +/// Time Complexity: O(nlog(MAX_NUM)) +/// Space Complexity: O(log(MAX_NUM)) +class Solution { +public: + bool isGoodArray(vector& nums) { + + int n = nums.size(), g = nums[0]; + for(int i = 1; i < n && g > 1; i ++) + g = gcd(g, nums[i]); + return g == 1; + } + +private: + int gcd(int a, int b){ + if(a > b) swap(a, b); + if (a == 0) return b; + return gcd(b % a, a); + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1252-Cells-with-Odd-Values-in-a-Matrix/cpp-1252/CMakeLists.txt b/1001-1500/1252-Cells-with-Odd-Values-in-a-Matrix/cpp-1252/CMakeLists.txt new file mode 100644 index 00000000..4c5ee0e1 --- /dev/null +++ b/1001-1500/1252-Cells-with-Odd-Values-in-a-Matrix/cpp-1252/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_1252) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1252 main.cpp) diff --git a/1001-1500/1252-Cells-with-Odd-Values-in-a-Matrix/cpp-1252/main.cpp b/1001-1500/1252-Cells-with-Odd-Values-in-a-Matrix/cpp-1252/main.cpp new file mode 100644 index 00000000..fd2fe062 --- /dev/null +++ b/1001-1500/1252-Cells-with-Odd-Values-in-a-Matrix/cpp-1252/main.cpp @@ -0,0 +1,36 @@ +/// Source : https://leetcode.com/problems/cells-with-odd-values-in-a-matrix/ +/// Author : liuyubobobo +/// Time : 2022-07-11 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(m * n * (m + n)) +/// Space Complexity: O(m * n) +class Solution { +public: + int oddCells(int R, int C, vector>& indices) { + + vector> matrix(R, vector(C, 0)); + for(const vector& e: indices){ + int r = e[0], c = e[1]; + for(int j = 0; j < C; j ++) matrix[r][j] ++; + for(int i = 0; i < R; i ++) matrix[i][c] ++; + } + + int res = 0; + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++) res += matrix[i][j] % 2; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1253-Reconstruct-a-2-Row-Binary-Matrix/cpp-1253/CMakeLists.txt b/1001-1500/1253-Reconstruct-a-2-Row-Binary-Matrix/cpp-1253/CMakeLists.txt new file mode 100644 index 00000000..83e42998 --- /dev/null +++ b/1001-1500/1253-Reconstruct-a-2-Row-Binary-Matrix/cpp-1253/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_1253) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_1253 main.cpp) diff --git a/1001-1500/1253-Reconstruct-a-2-Row-Binary-Matrix/cpp-1253/main.cpp b/1001-1500/1253-Reconstruct-a-2-Row-Binary-Matrix/cpp-1253/main.cpp new file mode 100644 index 00000000..9511cf16 --- /dev/null +++ b/1001-1500/1253-Reconstruct-a-2-Row-Binary-Matrix/cpp-1253/main.cpp @@ -0,0 +1,56 @@ +/// Source : https://leetcode.com/problems/reconstruct-a-2-row-binary-matrix/description/ +/// Author : liuyubobobo +/// Time : 2023-06-29 + +#include +#include +#include + +using namespace std; + + +/// Using PQ +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + vector> reconstructMatrix(int upper, int lower, vector& colsum) { + + int n = colsum.size(); + + vector> res(2, vector(n, 0)); + priority_queue> pq; + for(int i = 0; i < n; i ++) + if(colsum[i]) pq.push({colsum[i], i}); + + while(!pq.empty()){ + int sum = pq.top().first, index = pq.top().second; + pq.pop(); + + if(sum == 2){ + res[0][index] = res[1][index] = 1; + upper --, lower --; + if(upper < 0 || lower < 0) return vector>(0); + } + else{ + if(upper) + res[0][index] = 1, upper --; + else if(lower) + res[1][index] = 1, lower --; + else return vector>(0); + } + } + + if(upper || lower) return vector>(0); + return res; + } +}; + + +int main() { + + vector colsum1 = {2,1,2,0,1,0,1,2,0,1}; + Solution().reconstructMatrix(5, 5, colsum1); + + return 0; +} diff --git a/1001-1500/1254-Number-of-Closed-Islands/cpp-1254/CMakeLists.txt b/1001-1500/1254-Number-of-Closed-Islands/cpp-1254/CMakeLists.txt new file mode 100644 index 00000000..6eaa78e4 --- /dev/null +++ b/1001-1500/1254-Number-of-Closed-Islands/cpp-1254/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_1254) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_1254 main.cpp) diff --git a/1001-1500/1254-Number-of-Closed-Islands/cpp-1254/main.cpp b/1001-1500/1254-Number-of-Closed-Islands/cpp-1254/main.cpp new file mode 100644 index 00000000..0e465ba6 --- /dev/null +++ b/1001-1500/1254-Number-of-Closed-Islands/cpp-1254/main.cpp @@ -0,0 +1,59 @@ +/// Source : https://leetcode.com/problems/number-of-closed-islands/description/ +/// Author : liuyubobobo +/// Time : 2023-04-06 + +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(m * n) +/// Space Complexity: O(m * n) +class Solution { + +private: + int R, C; + const int dirs[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; + +public: + int closedIsland(vector>& grid) { + + R = grid.size(), C = grid[0].size(); + + vector> visited(R, vector(C, false)); + int res = 0; + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++){ + if(visited[i][j] || grid[i][j] == 1) continue; + res += !dfs(grid, i, j, visited); + } + return res; + } + +private: + bool dfs(const vector>& grid, int x, int y, vector>& visited){ + + bool ret = false; + visited[x][y] = true; + + for(int d = 0; d < 4; d ++){ + int nx = x + dirs[d][0], ny = y + dirs[d][1]; + if(in_area(nx, ny) && !visited[nx][ny] && grid[nx][ny] == 0) + ret |= dfs(grid, nx, ny, visited); + else if(!in_area(nx, ny)) + ret = true; + } + return ret; + } + + bool in_area(int x, int y){ + return 0 <= x && x < R && 0 <= y && y < C; + } +}; + +int main() { + + return 0; +} diff --git a/1001-1500/1255-Maximum-Score-Words-Formed-by-Letters/cpp-1255/CMakeLists.txt b/1001-1500/1255-Maximum-Score-Words-Formed-by-Letters/cpp-1255/CMakeLists.txt new file mode 100644 index 00000000..9b275a2f --- /dev/null +++ b/1001-1500/1255-Maximum-Score-Words-Formed-by-Letters/cpp-1255/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_1255) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_1255 main.cpp) diff --git a/1001-1500/1255-Maximum-Score-Words-Formed-by-Letters/cpp-1255/main.cpp b/1001-1500/1255-Maximum-Score-Words-Formed-by-Letters/cpp-1255/main.cpp new file mode 100644 index 00000000..6c04b837 --- /dev/null +++ b/1001-1500/1255-Maximum-Score-Words-Formed-by-Letters/cpp-1255/main.cpp @@ -0,0 +1,51 @@ +/// Source : https://leetcode.com/problems/maximum-score-words-formed-by-letters/description/ +/// Author : liuyubobobo +/// Time : 2023-02-25 + +#include +#include + +using namespace std; + + +/// State Compression DP +/// Time Complexity: O(2^n * max_word_len) +/// Space Complexity: O(1) +class Solution { +public: + int maxScoreWords(vector& words, vector& letters, vector& score) { + + int n = words.size(); + + vector f(26, 0); + for(char c: letters) f[c - 'a'] ++; + + int res = 0; + for(int state = 0; state < (1 << n); state ++){ + + vector curf(26, 0); + for(int i = 0; i < n; i ++){ + if((state >> i) & 1) for(char c: words[i]) curf[c - 'a'] ++; + } + + if(ok(curf, f)){ + int cur_score = 0; + for(int i = 0; i < 26; i ++) cur_score += score[i] * curf[i]; + res = max(res, cur_score); + } + } + return res; + } + +private: + bool ok(const vector& v, const vector& f){ + for(int i = 0; i < 26; i ++) if(v[i] > f[i]) return false; + return true; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1259-Handshakes-That-Dont-Cross/cpp-1259/CMakeLists.txt b/1001-1500/1259-Handshakes-That-Dont-Cross/cpp-1259/CMakeLists.txt new file mode 100644 index 00000000..2fd7d011 --- /dev/null +++ b/1001-1500/1259-Handshakes-That-Dont-Cross/cpp-1259/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_1259) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_1259 main.cpp) diff --git a/1001-1500/1259-Handshakes-That-Dont-Cross/cpp-1259/main.cpp b/1001-1500/1259-Handshakes-That-Dont-Cross/cpp-1259/main.cpp new file mode 100644 index 00000000..269305c1 --- /dev/null +++ b/1001-1500/1259-Handshakes-That-Dont-Cross/cpp-1259/main.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/handshakes-that-dont-cross/description/ +/// Author : liuyubobobo +/// Time : 2023-02-22 + +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { + +private: + const long long MOD = 1e9 + 7; + +public: + int numberOfWays(int numPeople) { + + vector dp(numPeople + 1, 0); + dp[0] = 1; + for(int i = 2; i <= numPeople; i ++){ + if(i % 2) continue; + for(int j = 1; j < i; j ++){ + int len = j - 1; + if(len & 1) continue; + dp[i] += dp[len] * dp[i - (len + 2)] % MOD; + } + dp[i] %= MOD; + } + return dp.back(); + } +}; + +int main() { + + return 0; +} diff --git a/1001-1500/1260-Shift-2D-Grid/cpp-1260/CMakeLists.txt b/1001-1500/1260-Shift-2D-Grid/cpp-1260/CMakeLists.txt new file mode 100644 index 00000000..3731f44a --- /dev/null +++ b/1001-1500/1260-Shift-2D-Grid/cpp-1260/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main2.cpp) \ No newline at end of file diff --git a/1001-1500/1260-Shift-2D-Grid/cpp-1260/main.cpp b/1001-1500/1260-Shift-2D-Grid/cpp-1260/main.cpp new file mode 100644 index 00000000..4054a3b0 --- /dev/null +++ b/1001-1500/1260-Shift-2D-Grid/cpp-1260/main.cpp @@ -0,0 +1,42 @@ +/// Source : https://leetcode.com/contest/weekly-contest-163/problems/shift-2d-grid/ +/// Author : liuyubobobo +/// Time : 2019-11-16 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(k * m * n) +/// Space Complexity: O(1) +class Solution { +public: + vector> shiftGrid(vector>& grid, int k) { + + int n = grid.size(), m = grid[0].size(); + vector> res = grid; + while(k --) + res = go(res, n, m); + return res; + } + +private: + vector> go(const vector>& g, int n, int m){ + + vector> res(n, vector(m)); + for(int i = 0; i < n; i ++){ + res[i][0] = g[(i - 1 + n) % n][m - 1]; + for(int j = 1; j < m; j ++) + res[i][j] = g[i][j - 1]; + } + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1260-Shift-2D-Grid/cpp-1260/main2.cpp b/1001-1500/1260-Shift-2D-Grid/cpp-1260/main2.cpp new file mode 100644 index 00000000..696f0732 --- /dev/null +++ b/1001-1500/1260-Shift-2D-Grid/cpp-1260/main2.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/contest/weekly-contest-163/problems/shift-2d-grid/ +/// Author : liuyubobobo +/// Time : 2020-02-17 + +#include +#include + +using namespace std; + + +/// Mathematics +/// Time Complexity: O(m * n) +/// Space Complexity: O(1) +class Solution { +public: + vector> shiftGrid(vector>& grid, int k) { + + int n = grid.size(), m = grid[0].size(); + k = k % (n * m); + + vector> res(n, vector(m)); + for(int i = 0; i < n; i ++) + for(int j = 0; j < m; j ++){ + int index = (i * m + j + k) % (n * m); + res[index / m][index % m] = grid[i][j]; + } + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1261-Find-Elements-in-a-Contaminated-Binary-Tree/cpp-1261/CMakeLists.txt b/1001-1500/1261-Find-Elements-in-a-Contaminated-Binary-Tree/cpp-1261/CMakeLists.txt new file mode 100644 index 00000000..f3359f29 --- /dev/null +++ b/1001-1500/1261-Find-Elements-in-a-Contaminated-Binary-Tree/cpp-1261/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1001-1500/1261-Find-Elements-in-a-Contaminated-Binary-Tree/cpp-1261/main.cpp b/1001-1500/1261-Find-Elements-in-a-Contaminated-Binary-Tree/cpp-1261/main.cpp new file mode 100644 index 00000000..61aee37b --- /dev/null +++ b/1001-1500/1261-Find-Elements-in-a-Contaminated-Binary-Tree/cpp-1261/main.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/contest/weekly-contest-163/problems/find-elements-in-a-contaminated-binary-tree/ +/// Author : liuyubobobo +/// Time : 2019-11-16 + +#include +#include + +using namespace std; + + +/// DFS and Using Hash Set +/// Time Complexity: init: O(n) +/// find: O(1) +/// Space Complexity: O(1) + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +class FindElements { + +private: + set vals; + +public: + FindElements(TreeNode* root) { + if(root) dfs(root, 0); + } + + bool find(int target) { + return vals.find(target) != vals.end(); + } + +private: + void dfs(TreeNode* node, int val){ + + node->val = val; + vals.insert(val); + if(node->left) dfs(node->left, val * 2 + 1); + if(node->right) dfs(node->right, val * 2 + 2); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1262-Greatest-Sum-Divisible-by-Three/cpp-1262/CMakeLists.txt b/1001-1500/1262-Greatest-Sum-Divisible-by-Three/cpp-1262/CMakeLists.txt new file mode 100644 index 00000000..e363f271 --- /dev/null +++ b/1001-1500/1262-Greatest-Sum-Divisible-by-Three/cpp-1262/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(cpp_1262) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1262 main2.cpp) \ No newline at end of file diff --git a/1001-1500/1262-Greatest-Sum-Divisible-by-Three/cpp-1262/main.cpp b/1001-1500/1262-Greatest-Sum-Divisible-by-Three/cpp-1262/main.cpp new file mode 100644 index 00000000..accfe9c1 --- /dev/null +++ b/1001-1500/1262-Greatest-Sum-Divisible-by-Three/cpp-1262/main.cpp @@ -0,0 +1,45 @@ +/// Source : https://leetcode.com/problems/greatest-sum-divisible-by-three/ +/// Author : liuyubobobo +/// Time : 2020-02-17 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(3n) +/// Space Complexity: O(1) +class Solution { +public: + int maxSumDivThree(vector& nums) { + + vector res(3, 0), t(3, 0); + for(int e: nums){ + for(int mod = 0; mod < 3; mod ++) + t[(res[mod] + e) % 3] = max(t[(res[mod] + e) % 3], res[mod] + e); + res = t; + } + + return res[0]; + } +}; + + +int main() { + + vector nums1 = {3,6,5,1,8}; + cout << Solution().maxSumDivThree(nums1) << endl; + // 18 + + vector nums2 = {1,2,3,4,4}; + cout << Solution().maxSumDivThree(nums2) << endl; + // 12 + + vector nums3 = {2,3,36,8,32,38,3,30,13,40}; + cout << Solution().maxSumDivThree(nums3) << endl; + // 195 + + return 0; +} diff --git a/1001-1500/1262-Greatest-Sum-Divisible-by-Three/cpp-1262/main2.cpp b/1001-1500/1262-Greatest-Sum-Divisible-by-Three/cpp-1262/main2.cpp new file mode 100644 index 00000000..79334f2f --- /dev/null +++ b/1001-1500/1262-Greatest-Sum-Divisible-by-Three/cpp-1262/main2.cpp @@ -0,0 +1,51 @@ +/// Source : https://leetcode.com/problems/greatest-sum-divisible-by-three/ +/// Author : liuyubobobo +/// Time : 2020-02-17 + +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(3n) +/// Space Complexity: O(3n) +class Solution { +public: + int maxSumDivThree(vector& nums) { + + vector> dp(nums.size(), vector(3, -1)); + return dfs(nums, 0, 0, dp); + } + +private: + int dfs(const vector& nums, int index, int mod, vector>& dp){ + + if(index == nums.size()) return mod == 0 ? 0 : -1; + if(dp[index][mod] != -1) return dp[index][mod]; + + int res = dfs(nums, index + 1, mod, dp); + int t = dfs(nums, index + 1, (mod - nums[index] % 3 + 3) % 3, dp); + if(t >= 0) res = max(res, nums[index] + t); + return dp[index][mod] = res; + } +}; + + +int main() { + + vector nums1 = {3,6,5,1,8}; + cout << Solution().maxSumDivThree(nums1) << endl; + // 18 + + vector nums2 = {1,2,3,4,4}; + cout << Solution().maxSumDivThree(nums2) << endl; + // 12 + + vector nums3 = {2,3,36,8,32,38,3,30,13,40}; + cout << Solution().maxSumDivThree(nums3) << endl; + // 195 + + return 0; +} diff --git a/1001-1500/1263-Minimum-Moves-to-Move-a-Box-to-Their-Target-Location/cpp-1263/CMakeLists.txt b/1001-1500/1263-Minimum-Moves-to-Move-a-Box-to-Their-Target-Location/cpp-1263/CMakeLists.txt new file mode 100644 index 00000000..8ec1abf1 --- /dev/null +++ b/1001-1500/1263-Minimum-Moves-to-Move-a-Box-to-Their-Target-Location/cpp-1263/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(cpp_1263) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1263 main.cpp) \ No newline at end of file diff --git a/1001-1500/1263-Minimum-Moves-to-Move-a-Box-to-Their-Target-Location/cpp-1263/main.cpp b/1001-1500/1263-Minimum-Moves-to-Move-a-Box-to-Their-Target-Location/cpp-1263/main.cpp new file mode 100644 index 00000000..58b51b68 --- /dev/null +++ b/1001-1500/1263-Minimum-Moves-to-Move-a-Box-to-Their-Target-Location/cpp-1263/main.cpp @@ -0,0 +1,150 @@ +/// Source : https://leetcode.com/problems/minimum-moves-to-move-a-box-to-their-target-location/ +/// Author : liuyubobobo +/// Time : 2020-02-18 + +#include +#include +#include +#include + +using namespace std; + + +/// BFS +/// Time Complexity: O(m * n * m * n) +/// Space Complexity: O(m * n) +class Solution { + +private: + int R, C, M; + const int dirs[4][2] = {{1, 0}, {0, -1}, {-1, 0}, {0, 1}}; + +public: + int minPushBox(vector>& grid) { + + R = grid.size(), C = grid[0].size(), M = R * C; + int start = -1, end = -1, box = -1; + for(int i = 0; i < R * C; i ++) + if(grid[i / C][i % C] == 'S') + start = i, grid[i / C][i % C] = '.'; + else if(grid[i / C][i % C] == 'B') + box = i, grid[i / C][i % C] = '.'; + else if(grid[i / C][i % C] == 'T') + end = i, grid[i / C][i % C] = '.'; + return bfs(grid, start, end, box); + } + +private: + int bfs(vector>& grid, int start, int end, int box){ + + int start_hashcode = start * M + box; + queue q; + q.push(start_hashcode); + + map visited; + visited[start_hashcode] = 0; + + while(!q.empty()){ + + int curhash = q.front(); + q.pop(); + + int s = curhash / M, b = curhash % M, step = visited[curhash]; + + if(b == end) return step; + + int bx = b / C, by = b % C; + for(int d = 0; d < 4; d ++){ + int nextx = bx + dirs[d][0], nexty = by + dirs[d][1]; + if(in_area(nextx, nexty) && grid[nextx][nexty] != '#' && ok(grid, s, nextx * C + nexty, b)){ + + int nextbx = bx + dirs[(d + 2) % 4][0], nextby = by + dirs[(d + 2) % 4][1]; + if(in_area(nextbx, nextby) && grid[nextbx][nextby] != '#'){ + int nexthash = (nextx * C + nexty) * M + (nextbx * C + nextby); + if(!visited.count(nexthash)) { + q.push(nexthash); + visited[nexthash] = step + 1; + } + } + } + } + } + return -1; + } + +private: + bool in_area(int x, int y){ + return x >= 0 && x < R && y >= 0 && y < C; + } + + bool ok(vector>& grid, int start, int end, int box){ + + vector visited(R * C, false); + queue q; + + q.push(start); + visited[start] = true; + + while(!q.empty()){ + + int cur = q.front(); + q.pop(); + + if(cur == end) return true; + + int curx = cur / C, cury = cur % C; + for(int d = 0; d < 4; d ++){ + int nextx = curx + dirs[d][0], nexty = cury + dirs[d][1]; + if(in_area(nextx, nexty) && grid[nextx][nexty] == '.' + && nextx * C + nexty != box && !visited[nextx * C + nexty]){ + q.push(nextx * C + nexty); + visited[nextx * C + nexty] = true; + } + } + } + return false; + } +}; + + +int main() { + + vector> grid1 = { + {'#','#','#','#','#','#'}, + {'#','T','#','#','#','#'}, + {'#','.','.','B','.','#'}, + {'#','.','#','#','.','#'}, + {'#','.','.','.','S','#'}, + {'#','#','#','#','#','#'} + }; + cout << Solution().minPushBox(grid1) << endl; + // 3 + + vector> grid2 = { + {'#','#','#','#','#','#'}, + {'#','T','.','.','#','#'}, + {'#','.','#','B','.','#'}, + {'#','.','.','.','.','#'}, + {'#','.','.','.','S','#'}, + {'#','#','#','#','#','#'} + }; + cout << Solution().minPushBox(grid2) << endl; + // 5 + + vector> grid3 = { + {'.','.','#','.','.','.','.','.','.','.'}, + {'.','#','.','#','B','#','.','#','.','.'}, + {'.','#','.','.','.','.','.','.','T','.'}, + {'#','.','.','.','.','.','.','.','.','.'}, + {'.','.','.','.','.','.','.','.','.','#'}, + {'.','.','.','.','.','.','.','.','#','.'}, + {'.','.','.','#','.','.','#','#','.','.'}, + {'.','.','.','.','#','.','.','#','.','.'}, + {'.','#','.','S','.','.','.','.','.','.'}, + {'#','.','.','#','.','.','.','.','.','#'} + }; + cout << Solution().minPushBox(grid3) << endl; + // 5 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1272-Remove-Interval/cpp-1272/CMakeLists.txt b/1001-1500/1272-Remove-Interval/cpp-1272/CMakeLists.txt new file mode 100644 index 00000000..4d99d4d7 --- /dev/null +++ b/1001-1500/1272-Remove-Interval/cpp-1272/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_1272) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1272 main.cpp) diff --git a/1001-1500/1272-Remove-Interval/cpp-1272/main.cpp b/1001-1500/1272-Remove-Interval/cpp-1272/main.cpp new file mode 100644 index 00000000..2b93a482 --- /dev/null +++ b/1001-1500/1272-Remove-Interval/cpp-1272/main.cpp @@ -0,0 +1,49 @@ +/// Source : https://leetcode.com/problems/remove-interval/ +/// Author : liuyubobobo +/// Time : 2022-09-23 + +#include +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + vector> removeInterval(vector>& intervals, vector& toBeRemoved) { + + sort(intervals.begin(), intervals.end()); + + int x = toBeRemoved[0], y = toBeRemoved[1] - 1; + + vector> res; + for(const vector& v: intervals){ + int a = v[0], b = v[1] - 1; + if(x < a){ + if(y < a) res.push_back({a, b + 1}); + else if(y <= b - 1) res.push_back({y + 1, b + 1}); + else continue; + } + else if(x == a){ + if(y <= b - 1) res.push_back({y + 1, b + 1}); + else continue; + } + else if(x <= b){ + if(y <= b - 1) res.push_back({a, x}), res.push_back({y + 1, b + 1}); + else res.push_back({a, x}); + } + else res.push_back({a, b + 1}); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1275-Find-Winner-on-a-Tic-Tac-Toe-Game/cpp-1275/CMakeLists.txt b/1001-1500/1275-Find-Winner-on-a-Tic-Tac-Toe-Game/cpp-1275/CMakeLists.txt new file mode 100644 index 00000000..2683c6a4 --- /dev/null +++ b/1001-1500/1275-Find-Winner-on-a-Tic-Tac-Toe-Game/cpp-1275/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_1275) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1275 main.cpp) \ No newline at end of file diff --git a/1001-1500/1275-Find-Winner-on-a-Tic-Tac-Toe-Game/cpp-1275/main.cpp b/1001-1500/1275-Find-Winner-on-a-Tic-Tac-Toe-Game/cpp-1275/main.cpp new file mode 100644 index 00000000..583326fd --- /dev/null +++ b/1001-1500/1275-Find-Winner-on-a-Tic-Tac-Toe-Game/cpp-1275/main.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/find-winner-on-a-tic-tac-toe-game/ +/// Author : liuyubobobo +/// Time : 2021-05-22 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(|moves|) +/// Space Complexity: O(1) +class Solution { +public: + string tictactoe(vector>& moves) { + + vector> board(3, vector(3, 0)); + for(int i = 0; i < moves.size(); i ++){ + int x = moves[i][0], y = moves[i][1], player = i % 2 + 1; + board[x][y] = player; + if(win(board, x, y)) return player == 1 ? "A" : "B"; + } + return moves.size() == 9 ? "Draw" : "Pending"; + } + +private: + bool win(const vector>& board, int x, int y){ + + if(board[x][0] == board[x][1] && board[x][1] == board[x][2]) + return true; + + if(board[0][y] == board[1][y] && board[1][y] == board[2][y]) + return true; + + if(x == y && board[0][0] == board[1][1] && board[1][1] == board[2][2]) + return true; + + if(x + y == 2 && board[0][2] == board[1][1] && board[1][1] == board[2][0]) + return true; + + return false; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1277-Count-Square-Submatrices-with-All-Ones/cpp-1277/CMakeLists.txt b/1001-1500/1277-Count-Square-Submatrices-with-All-Ones/cpp-1277/CMakeLists.txt new file mode 100644 index 00000000..aa98adbb --- /dev/null +++ b/1001-1500/1277-Count-Square-Submatrices-with-All-Ones/cpp-1277/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(cpp_1277) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1277 main2.cpp) \ No newline at end of file diff --git a/1001-1500/1277-Count-Square-Submatrices-with-All-Ones/cpp-1277/main.cpp b/1001-1500/1277-Count-Square-Submatrices-with-All-Ones/cpp-1277/main.cpp new file mode 100644 index 00000000..a8400e6b --- /dev/null +++ b/1001-1500/1277-Count-Square-Submatrices-with-All-Ones/cpp-1277/main.cpp @@ -0,0 +1,49 @@ +/// Source : https://leetcode.com/problems/count-square-submatrices-with-all-ones/ +/// Author : liuyubobobo +/// Time : 2020-05-21 + +#include +#include + +using namespace std; + + +/// Presum in 2D +/// Time Compelxity: O(m * n * min(m, n)) +/// Space Complexity: O(m * n) +class Solution { +public: + int countSquares(vector>& matrix) { + + int m = matrix.size(), n = matrix[0].size(); + vector> presum(m + 1, vector(n + 1, 0)); + for(int i = 0; i < m; i ++) + for(int j = 0; j < n; j ++) + presum[i + 1][j + 1] = presum[i][j + 1] + presum[i + 1][j] - presum[i][j] + matrix[i][j]; + + int res = 0; + for(int i = 0; i < m; i ++) + for(int j = 0; j < n; j ++) + for(int len = 1; len <= min(i + 1, j + 1); len ++){ + if(presum[i + 1][j + 1] - presum[i + 1 - len][j + 1] - presum[i + 1][j + 1 - len] + presum[i + 1 - len][j + 1 - len] == len * len) + res ++; + else + break; + } + return res; + } +}; + + +int main() { + + vector> matrix1 = { + {0,1,1,1}, + {1,1,1,1}, + {0,1,1,1} + }; + cout << Solution().countSquares(matrix1) << endl; + // 15 + + return 0; +} diff --git a/1001-1500/1277-Count-Square-Submatrices-with-All-Ones/cpp-1277/main2.cpp b/1001-1500/1277-Count-Square-Submatrices-with-All-Ones/cpp-1277/main2.cpp new file mode 100644 index 00000000..cf12aa56 --- /dev/null +++ b/1001-1500/1277-Count-Square-Submatrices-with-All-Ones/cpp-1277/main2.cpp @@ -0,0 +1,43 @@ +/// Source : https://leetcode.com/problems/count-square-submatrices-with-all-ones/ +/// Author : liuyubobobo +/// Time : 2020-05-21 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Compelxity: O(m * n) +/// Space Complexity: O(m * n) +class Solution { +public: + int countSquares(vector>& matrix) { + + int m = matrix.size(), n = matrix[0].size(); + vector> dp(m + 1, vector(n + 1, 0)); + + int res = 0; + for(int i = 0; i < m; i ++) + for(int j = 0; j < n; j ++) + if(matrix[i][j]) + dp[i + 1][j + 1] = min(min(dp[i + 1][j], dp[i][j + 1]), dp[i][j]) + 1, + res += dp[i + 1][j + 1]; + return res; + } +}; + + +int main() { + + vector> matrix1 = { + {0,1,1,1}, + {1,1,1,1}, + {0,1,1,1} + }; + cout << Solution().countSquares(matrix1) << endl; + // 15 + + return 0; +} diff --git a/1001-1500/1278-Palindrome-Partitioning-III/cpp-1278/CMakeLists.txt b/1001-1500/1278-Palindrome-Partitioning-III/cpp-1278/CMakeLists.txt new file mode 100644 index 00000000..da7ba25c --- /dev/null +++ b/1001-1500/1278-Palindrome-Partitioning-III/cpp-1278/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1278) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1278 main.cpp) \ No newline at end of file diff --git a/1001-1500/1278-Palindrome-Partitioning-III/cpp-1278/main.cpp b/1001-1500/1278-Palindrome-Partitioning-III/cpp-1278/main.cpp new file mode 100644 index 00000000..13f54ef0 --- /dev/null +++ b/1001-1500/1278-Palindrome-Partitioning-III/cpp-1278/main.cpp @@ -0,0 +1,66 @@ +/// Source : https://leetcode.com/problems/palindrome-partitioning-iii/ +/// Author : liuyubobobo +/// Time : 2021-01-30 + +#include +#include + +using namespace std; + + +/// DP +/// Time Complexiity: O(n^3) +/// Space Complexity: O(n^2) +class Solution { + +private: + const int INF = 1e9; + int n; + +public: + int palindromePartition(string s, int k) { + + n = s.size(); + vector> table(n, vector(n, 0)); + for(int i = 0; i < n; i ++) table[i][i] = 0; + for(int i = 0; i + 1 < n; i ++) table[i][i + 1] = (s[i] != s[i + 1]); + for(int sz = 3; sz <= n; sz ++) + for(int i = 0; i + sz <= n; i ++) + table[i][i + sz - 1] = (s[i] != s[i + sz - 1]) + table[i + 1][i + sz - 2]; + + vector> dp(n, vector(k + 1, INF)); + return dfs(s, 0, k, table, dp); + } + +private: + int dfs(const string& s, int index, int k, const vector>& table, + vector>& dp){ + + if(index == n) return k == 0 ? 0 : INF; + if(k <= 0) return INF; + if(dp[index][k] != INF) return dp[index][k]; + + int res = INF; + for(int end = index; n - end >= k; end ++) + res = min(res, table[index][end] + dfs(s, end + 1, k - 1, table, dp)); + return dp[index][k] = res; + } +}; + + +int main() { + + cout << Solution().palindromePartition("abc", 2) << endl; + // 1 + + cout << Solution().palindromePartition("aabbc", 3) << endl; + // 0 + + cout << Solution().palindromePartition("leetcode", 8) << endl; + // 0 + + cout << Solution().palindromePartition("faaglagedtwnejzpuarkgwgoefwra", 27) << endl; + // 0 + + return 0; +} diff --git a/1001-1500/1281-Subtract-the-Product-and-Sum-of-Digits-of-an-Integer/cpp-1281/CMakeLists.txt b/1001-1500/1281-Subtract-the-Product-and-Sum-of-Digits-of-an-Integer/cpp-1281/CMakeLists.txt new file mode 100644 index 00000000..d0b72c2f --- /dev/null +++ b/1001-1500/1281-Subtract-the-Product-and-Sum-of-Digits-of-an-Integer/cpp-1281/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_1281) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_1281 main.cpp) diff --git a/1001-1500/1281-Subtract-the-Product-and-Sum-of-Digits-of-an-Integer/cpp-1281/main.cpp b/1001-1500/1281-Subtract-the-Product-and-Sum-of-Digits-of-an-Integer/cpp-1281/main.cpp new file mode 100644 index 00000000..19514ed8 --- /dev/null +++ b/1001-1500/1281-Subtract-the-Product-and-Sum-of-Digits-of-an-Integer/cpp-1281/main.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/description/ +/// Author : liuyubobobo +/// Time : 2023-08-08 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(logn) +/// Space Complexity: O(1) +class Solution { +public: + int subtractProductAndSum(int n) { + return product(n) - sum(n); + } + +private: + int product(int x){ + int res = 1; + while(x) + res *= x % 10, x /= 10; + return res; + } + + int sum(int x){ + int res = 0; + while(x) + res += x % 10, x /= 10; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1282-Group-the-People-Given-the-Group-Size-They-Belong-To/cpp-1282/CMakeLists.txt b/1001-1500/1282-Group-the-People-Given-the-Group-Size-They-Belong-To/cpp-1282/CMakeLists.txt new file mode 100644 index 00000000..86e9a69b --- /dev/null +++ b/1001-1500/1282-Group-the-People-Given-the-Group-Size-They-Belong-To/cpp-1282/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_1282) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1282 main.cpp) diff --git a/1001-1500/1282-Group-the-People-Given-the-Group-Size-They-Belong-To/cpp-1282/main.cpp b/1001-1500/1282-Group-the-People-Given-the-Group-Size-They-Belong-To/cpp-1282/main.cpp new file mode 100644 index 00000000..18321ad5 --- /dev/null +++ b/1001-1500/1282-Group-the-People-Given-the-Group-Size-They-Belong-To/cpp-1282/main.cpp @@ -0,0 +1,41 @@ +/// Source : https://leetcode.com/problems/group-the-people-given-the-group-size-they-belong-to/ +/// Author : liuyubobobo +/// Time : 2022-08-11 + +#include +#include +#include +#include + +using namespace std; + + +/// Using Map +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector> groupThePeople(vector& groupSizes) { + + map> groups; + for(int i = 0; i < groupSizes.size(); i ++) + groups[groupSizes[i]].push_back(i); + + vector> res; + for(const pair>& p: groups){ + int sz = p.first; + const vector& v = p.second; + assert(v.size() % sz == 0); + + for(int i = 0; i < v.size(); i += sz) + res.push_back(vector(v.begin() + i, v.begin() + i + sz)); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1286-Iterator-for-Combination/cpp-1286/CMakeLists.txt b/1001-1500/1286-Iterator-for-Combination/cpp-1286/CMakeLists.txt new file mode 100644 index 00000000..365c6894 --- /dev/null +++ b/1001-1500/1286-Iterator-for-Combination/cpp-1286/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_1286) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1286 main.cpp) diff --git a/1001-1500/1286-Iterator-for-Combination/cpp-1286/main.cpp b/1001-1500/1286-Iterator-for-Combination/cpp-1286/main.cpp new file mode 100644 index 00000000..98a14b8e --- /dev/null +++ b/1001-1500/1286-Iterator-for-Combination/cpp-1286/main.cpp @@ -0,0 +1,48 @@ +/// Source : https://leetcode.com/problems/iterator-for-combination/ +/// Author : liuyubobobo +/// Time : 2021-11-14 + +#include +#include + +using namespace std; + + +/// Time Complexity: init: O(2^n * n) +/// next, has_next: O(1) +/// Space Complexity: O(2^n) +class CombinationIterator { + +private: + vector table; + int cur = 0; + +public: + CombinationIterator(string characters, int combinationLength){ + + int n = characters.size(); + for(int state = 1; state < (1 << n); state ++) + if(__builtin_popcount(state) == combinationLength){ + string s = ""; + for(int i = 0; i < n; i ++) + if(state & (1 << i)) s += characters[i]; + table.push_back(s); + } + sort(table.begin(), table.end()); + } + + string next() { + + return table[cur ++]; + } + + bool hasNext() { + return cur < table.size(); + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1288-Remove-Covered-Intervals/cpp-1288/CMakeLists.txt b/1001-1500/1288-Remove-Covered-Intervals/cpp-1288/CMakeLists.txt new file mode 100644 index 00000000..379b231c --- /dev/null +++ b/1001-1500/1288-Remove-Covered-Intervals/cpp-1288/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_1288) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1288 main.cpp) diff --git a/1001-1500/1288-Remove-Covered-Intervals/cpp-1288/main.cpp b/1001-1500/1288-Remove-Covered-Intervals/cpp-1288/main.cpp new file mode 100644 index 00000000..ec766b8f --- /dev/null +++ b/1001-1500/1288-Remove-Covered-Intervals/cpp-1288/main.cpp @@ -0,0 +1,43 @@ +/// Source : https://leetcode.com/problems/remove-covered-intervals/ +/// Author : liuyubobobo +/// Time : 2022-02-19 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(nlogn + n^2) +/// Space Complexity: O(n) +class Solution { +public: + int removeCoveredIntervals(vector>& intervals) { + + sort(intervals.begin(), intervals.end(), + [](const vector& va, const vector& vb){ + if(va[1] - va[0] != vb[1] - vb[0]) + return va[1] - va[0] > vb[1] - vb[0]; + return va[0] < vb[0]; + }); + + vector> res; + for(const vector& v: intervals) + if(!contains(res, v)) res.push_back(v); + return res.size(); + } + +private: + bool contains(const vector>& res, const vector& a){ + + for(const vector& v: res) + if(v[0] <= a[0] && a[1] <= v[1]) return true; + return false; + } +}; + +int main() { + + return 0; +} diff --git a/1001-1500/1289-Minimum-Falling-Path-Sum-II/cpp-1289/CMakeLists.txt b/1001-1500/1289-Minimum-Falling-Path-Sum-II/cpp-1289/CMakeLists.txt new file mode 100644 index 00000000..601bd10a --- /dev/null +++ b/1001-1500/1289-Minimum-Falling-Path-Sum-II/cpp-1289/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_1289) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_1289 main.cpp) diff --git a/1001-1500/1289-Minimum-Falling-Path-Sum-II/cpp-1289/main.cpp b/1001-1500/1289-Minimum-Falling-Path-Sum-II/cpp-1289/main.cpp new file mode 100644 index 00000000..fcba1da7 --- /dev/null +++ b/1001-1500/1289-Minimum-Falling-Path-Sum-II/cpp-1289/main.cpp @@ -0,0 +1,43 @@ +/// Source : https://leetcode.com/problems/minimum-falling-path-sum-ii/ +/// Author : liuyubobobo +/// Time : 2023-08-09 + +#include +#include + +using namespace std; + + +/// Memoization +/// Time Complexity: O(n^3) +/// Space Complexity: O(n^2) +class Solution { +public: + int minFallingPathSum(vector>& grid) { + + int n = grid.size(); + + vector> dp(n, vector(n + 1, -1)); + return dfs(n, grid, 0, n, dp); + } + +private: + int dfs(int n, const vector>& grid, int row, int last_c, vector>& dp) { + + if (row == n) return 0; + if (dp[row][last_c] != -1) return dp[row][last_c]; + + int res = INT_MAX; + for (int j = 0; j < n; j ++) { + if (j == last_c) continue; + res = min(res, grid[row][j] + dfs(n, grid, row + 1, j, dp)); + } + return dp[row][last_c] = res; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1290-Convert-Binary-Number-in-a-Linked-List-to-Integer/cpp-1290/CMakeLists.txt b/1001-1500/1290-Convert-Binary-Number-in-a-Linked-List-to-Integer/cpp-1290/CMakeLists.txt new file mode 100644 index 00000000..28d39a09 --- /dev/null +++ b/1001-1500/1290-Convert-Binary-Number-in-a-Linked-List-to-Integer/cpp-1290/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_1290) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1290 main.cpp) diff --git a/1001-1500/1290-Convert-Binary-Number-in-a-Linked-List-to-Integer/cpp-1290/main.cpp b/1001-1500/1290-Convert-Binary-Number-in-a-Linked-List-to-Integer/cpp-1290/main.cpp new file mode 100644 index 00000000..ef1c611a --- /dev/null +++ b/1001-1500/1290-Convert-Binary-Number-in-a-Linked-List-to-Integer/cpp-1290/main.cpp @@ -0,0 +1,38 @@ +/// Source : https://leetcode.com/problems/convert-binary-number-in-a-linked-list-to-integer/ +/// Author : liuyubobobo +/// Time : 2021-12-06 + +#include + + +/// Linked List +/// Time Complexity: O(n) +/// Space Complexity: O(1) + +/// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode() : val(0), next(nullptr) {} + ListNode(int x) : val(x), next(nullptr) {} + ListNode(int x, ListNode *next) : val(x), next(next) {} +}; + +class Solution { +public: + int getDecimalValue(ListNode* head) { + + int cur = 0; + while(head){ + cur = cur * 2 + head->val; + head = head->next; + } + return cur; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1291-Sequential-Digits/cpp-1291/CMakeLists.txt b/1001-1500/1291-Sequential-Digits/cpp-1291/CMakeLists.txt new file mode 100644 index 00000000..7ed65672 --- /dev/null +++ b/1001-1500/1291-Sequential-Digits/cpp-1291/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_1291) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1291 main.cpp) diff --git a/1001-1500/1291-Sequential-Digits/cpp-1291/main.cpp b/1001-1500/1291-Sequential-Digits/cpp-1291/main.cpp new file mode 100644 index 00000000..483454f9 --- /dev/null +++ b/1001-1500/1291-Sequential-Digits/cpp-1291/main.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/sequential-digits/ +/// Author : liuyubobobo +/// Time : 2022-01-22 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(1) +/// Space Complexity: O(1) +class Solution { +public: + vector sequentialDigits(int low, int high) { + + vector res; + for(int start = 1; start < 9; start ++){ + long long cur = 0; + for(int d = start; d <= 9 && cur <= high; d ++){ + cur = cur * 10 + d; + if(cur >= low && cur <= high) res.push_back(cur); + } + } + sort(res.begin(), res.end()); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1293-Shortest-Path-in-a-Grid-with-Obstacles-Elimination/cpp-1293/CMakeLists.txt b/1001-1500/1293-Shortest-Path-in-a-Grid-with-Obstacles-Elimination/cpp-1293/CMakeLists.txt new file mode 100644 index 00000000..af1fcd58 --- /dev/null +++ b/1001-1500/1293-Shortest-Path-in-a-Grid-with-Obstacles-Elimination/cpp-1293/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_1293) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1293 main.cpp) diff --git a/1001-1500/1293-Shortest-Path-in-a-Grid-with-Obstacles-Elimination/cpp-1293/main.cpp b/1001-1500/1293-Shortest-Path-in-a-Grid-with-Obstacles-Elimination/cpp-1293/main.cpp new file mode 100644 index 00000000..28ac1096 --- /dev/null +++ b/1001-1500/1293-Shortest-Path-in-a-Grid-with-Obstacles-Elimination/cpp-1293/main.cpp @@ -0,0 +1,63 @@ +/// Source : https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/ +/// Author : liuyubobobo +/// Time : 2021-09-25 + +#include +#include +#include + +using namespace std; + + +/// BFS +/// Time Complexity: O(R * C * K) +/// Space Complexity: O(R * C * K) +class Solution { + +private: + const int dirs[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; + int R, C; + +public: + int shortestPath(vector>& grid, int k) { + + R = grid.size(), C = grid[0].size(); + + vector> dis(R * C, vector(k + 1, -1)); + dis[0][k] = 0; + queue> q; + q.push({0, k}); + + while(!q.empty()){ + int cpos = q.front().first, left = q.front().second; + int cx = cpos / C, cy = cpos % C; + q.pop(); + + if(cpos == R * C - 1) return dis[cpos][left]; + + for(int d = 0; d < 4; d ++){ + int nx = cx + dirs[d][0], ny = cy + dirs[d][1]; + if(!in_area(nx, ny)) continue; + if(left == 0 && grid[nx][ny]) continue; + + int npos = nx * C + ny, nleft = left - grid[nx][ny]; + if(dis[npos][nleft] != -1) continue; + + dis[npos][nleft] = dis[cpos][left] + 1; + q.push({npos, nleft}); + } + } + return -1; + } + +private: + bool in_area(int x, int y){ + return 0 <= x && x < R && 0 <= y && y < C; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1302-Deepest-Leaves-Sum/cpp-1302/CMakeLists.txt b/1001-1500/1302-Deepest-Leaves-Sum/cpp-1302/CMakeLists.txt new file mode 100644 index 00000000..32f52552 --- /dev/null +++ b/1001-1500/1302-Deepest-Leaves-Sum/cpp-1302/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_1302) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1302 main.cpp) \ No newline at end of file diff --git a/1001-1500/1302-Deepest-Leaves-Sum/cpp-1302/main.cpp b/1001-1500/1302-Deepest-Leaves-Sum/cpp-1302/main.cpp new file mode 100644 index 00000000..d3aea162 --- /dev/null +++ b/1001-1500/1302-Deepest-Leaves-Sum/cpp-1302/main.cpp @@ -0,0 +1,51 @@ +/// Source : https://leetcode.com/problems/deepest-leaves-sum/ +/// Author : liuyubobobo +/// Time : 2021-04-11 + +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(h) + +/// 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: + int deepestLeavesSum(TreeNode* root) { + + int sum = 0, maxd = 0; + dfs(root, sum, 0, maxd); + return sum; + } + +private: + void dfs(TreeNode* node, int& sum, int curd, int& maxd){ + + if(!node) return; + + if(curd == maxd) sum += node->val; + else if(curd > maxd) sum = node->val, maxd = curd; + + dfs(node->left, sum, curd + 1, maxd); + dfs(node->right, sum, curd + 1, maxd); + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1304-Find-N-Unique-Integers-Sum-up-to-Zero/cpp-1304/CMakeLists.txt b/1001-1500/1304-Find-N-Unique-Integers-Sum-up-to-Zero/cpp-1304/CMakeLists.txt new file mode 100644 index 00000000..0bf4330f --- /dev/null +++ b/1001-1500/1304-Find-N-Unique-Integers-Sum-up-to-Zero/cpp-1304/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(cpp_1304) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1304 main.cpp) \ No newline at end of file diff --git a/1001-1500/1304-Find-N-Unique-Integers-Sum-up-to-Zero/cpp-1304/main.cpp b/1001-1500/1304-Find-N-Unique-Integers-Sum-up-to-Zero/cpp-1304/main.cpp new file mode 100644 index 00000000..4d7f5b11 --- /dev/null +++ b/1001-1500/1304-Find-N-Unique-Integers-Sum-up-to-Zero/cpp-1304/main.cpp @@ -0,0 +1,29 @@ +/// Source : https://leetcode.com/problems/find-n-unique-integers-sum-up-to-zero/ +/// Author : liuyubobobo +/// Time : 2020-01-10 + +#include +#include + +using namespace std; + + +/// Generative +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + vector sumZero(int n) { + + vector res; + if(n % 2) res.push_back(0), n --; + while(n) res.push_back(n), res.push_back(-n), n -= 2; + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1305-All-Elements-in-Two-Binary-Search-Trees/cpp-1305/CMakeLists.txt b/1001-1500/1305-All-Elements-in-Two-Binary-Search-Trees/cpp-1305/CMakeLists.txt new file mode 100644 index 00000000..703c1cdd --- /dev/null +++ b/1001-1500/1305-All-Elements-in-Two-Binary-Search-Trees/cpp-1305/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(cpp_1305) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1305 main2.cpp) \ No newline at end of file diff --git a/1001-1500/1305-All-Elements-in-Two-Binary-Search-Trees/cpp-1305/main.cpp b/1001-1500/1305-All-Elements-in-Two-Binary-Search-Trees/cpp-1305/main.cpp new file mode 100644 index 00000000..1b7c4d92 --- /dev/null +++ b/1001-1500/1305-All-Elements-in-Two-Binary-Search-Trees/cpp-1305/main.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/all-elements-in-two-binary-search-trees/ +/// Author : liuyubobobo +/// Time : 2020-01-11 + +#include +#include + +using namespace std; + + +/// DFS and Sorting +/// Time Complexity: O(m + n + (m + n)log(m + n)) +/// Space Complexity: O(m + n) + +/// 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 { + +private: + vector res; + +public: + vector getAllElements(TreeNode* root1, TreeNode* root2) { + + res.clear(); + dfs(root1); + dfs(root2); + sort(res.begin(), res.end()); + return res; + } + +private: + void dfs(TreeNode* node){ + + if(!node) return; + res.push_back(node->val); + dfs(node->left); + dfs(node->right); + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1305-All-Elements-in-Two-Binary-Search-Trees/cpp-1305/main2.cpp b/1001-1500/1305-All-Elements-in-Two-Binary-Search-Trees/cpp-1305/main2.cpp new file mode 100644 index 00000000..3a5a5852 --- /dev/null +++ b/1001-1500/1305-All-Elements-in-Two-Binary-Search-Trees/cpp-1305/main2.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/all-elements-in-two-binary-search-trees/ +/// Author : liuyubobobo +/// Time : 2020-01-11 + +#include +#include + +using namespace std; + + +/// Inorder DFS and Merge +/// Time Complexity: O(m + n) +/// Space Complexity: O(m + n) + +/// 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: + vector getAllElements(TreeNode* root1, TreeNode* root2) { + + vector res1, res2; + dfs(root1, res1); + dfs(root2, res2); + + vector res; + int i = 0, j = 0; + while(i < res1.size() && j < res2.size()){ + if(res1[i] < res2[j]) res.push_back(res1[i ++]); + else res.push_back(res2[j ++]); + } + while(i < res1.size()) res.push_back(res1[i ++]); + while(j < res2.size()) res.push_back(res2[j ++]); + return res; + } + +private: + void dfs(TreeNode* node, vector& res){ + + if(!node) return; + dfs(node->left, res); + res.push_back(node->val); + dfs(node->right, res); + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1306-Jump-Game-III/cpp-1306/CMakeLists.txt b/1001-1500/1306-Jump-Game-III/cpp-1306/CMakeLists.txt new file mode 100644 index 00000000..d51672d1 --- /dev/null +++ b/1001-1500/1306-Jump-Game-III/cpp-1306/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(cpp_1306) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1306 main.cpp) \ No newline at end of file diff --git a/1001-1500/1306-Jump-Game-III/cpp-1306/main.cpp b/1001-1500/1306-Jump-Game-III/cpp-1306/main.cpp new file mode 100644 index 00000000..a6e0cffc --- /dev/null +++ b/1001-1500/1306-Jump-Game-III/cpp-1306/main.cpp @@ -0,0 +1,43 @@ +/// Source : https://leetcode.com/problems/jump-game-iii/ +/// Author : liuyubobobo +/// Time : 2020-01-11 + +#include +#include +#include + +using namespace std; + + +/// BFS +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + bool canReach(vector& arr, int start) { + + queue q; + vector visited(arr.size(), false); + + q.push(start); + visited[start] = true; + while(!q.empty()){ + int cur = q.front(); + q.pop(); + + if(!arr[cur]) return true; + + if(cur - arr[cur] >= 0 && !visited[cur - arr[cur]]) + q.push(cur - arr[cur]), visited[cur - arr[cur]] = true; + if(cur + arr[cur] < arr.size() && !visited[cur + arr[cur]]) + q.push(cur + arr[cur]), visited[cur + arr[cur]] = true; + } + return false; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1307-Verbal-Arithmetic-Puzzle/cpp-1307/CMakeLists.txt b/1001-1500/1307-Verbal-Arithmetic-Puzzle/cpp-1307/CMakeLists.txt new file mode 100644 index 00000000..65a25698 --- /dev/null +++ b/1001-1500/1307-Verbal-Arithmetic-Puzzle/cpp-1307/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1307) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1307 main2.cpp) \ No newline at end of file diff --git a/1001-1500/1307-Verbal-Arithmetic-Puzzle/cpp-1307/main.cpp b/1001-1500/1307-Verbal-Arithmetic-Puzzle/cpp-1307/main.cpp new file mode 100644 index 00000000..0954346c --- /dev/null +++ b/1001-1500/1307-Verbal-Arithmetic-Puzzle/cpp-1307/main.cpp @@ -0,0 +1,119 @@ +/// Source : https://leetcode.com/problems/verbal-arithmetic-puzzle/ +/// Author : liuyubobobo +/// Time : 2020-09-14 + +#include +#include + +using namespace std; + + +/// Backtracking +/// Time Complexity: O(10^10) +/// Space Complexity: O(|words| * max_len_of_words) +class Solution { + +private: + vector pow10; + +public: + bool isSolvable(vector& words, string result) { + + pow10 = {1}; + for(int i = 1; i <= 9; i ++) + pow10.push_back(pow10[i - 1] * 10); + + int maxlen = 0; + for(string& word: words) { + reverse(word.begin(), word.end()); + maxlen = max(maxlen, (int)word.size()); + } + reverse(result.begin(), result.end()); + maxlen = max(maxlen, (int)result.size()); + + vector letters(26, -1); // map from letter to digit + vector used(10, false); // whether digit x is used + return dfs(words, result, maxlen, letters, used, 0, 0); + } + +private: + bool dfs(const vector& words, const string& result, int maxlen, + vector& letters, vector& used, int p, int index){ + + // end of search, check leading zeros + if(index == maxlen){ + for(const string& word: words) + if(letters[word.back() - 'A'] == 0) return false; + if(letters[result.back() - 'A'] == 0) return false; + return true; + } + + // if p == words.size(), check result + if(p == words.size()){ + + int res = 0; + for(const string& word: words){ + int num = 0; + for(int i = 0; i < min(index + 1, (int)word.size()); i ++) + num += letters[word[i] - 'A'] * pow10[i]; + res += num; + } + + string res_str = to_string(res); + + reverse(res_str.begin(), res_str.end()); + int x = index < res_str.size() ? res_str[index] - '0' : 0; + + if(letters[result[index] - 'A'] != -1){ + if(letters[result[index] - 'A'] != x) return false; + return dfs(words, result, maxlen, letters, used, 0, index + 1); + } + + if(used[x]) return false; + + letters[result[index] - 'A'] = x; + used[x] = true; + if(dfs(words, result, maxlen, letters, used, 0, index + 1)) return true; + letters[result[index] - 'A'] = -1; + used[x] = false; + return false; + } + + if(index >= words[p].size() || letters[words[p][index] - 'A'] != -1) + return dfs(words, result, maxlen, letters, used, p + 1, index); + + for(int i = 0; i < 10; i ++) + if(!used[i]){ + letters[words[p][index] - 'A'] = i; + used[i] = true; + + if(dfs(words, result, maxlen, letters, used, p + 1, index)) return true; + + letters[words[p][index] - 'A'] = -1; + used[i] = false; + } + return false; + } +}; + + +int main() { + + vector words1 = {"SEND", "MORE"}; + cout << Solution().isSolvable(words1, "MONEY") << endl; + // 1 + + vector words2 = {"SIX","SEVEN","SEVEN"}; + cout << Solution().isSolvable(words2, "TWENTY") << endl; + // 1 + + vector words3 = {"THIS","IS","TOO"}; + cout << Solution().isSolvable(words3, "FUNNY") << endl; + // 1 + + vector words4 = {"LEET","CODE"}; + cout << Solution().isSolvable(words4, "POINT") << endl; + // 0 + + return 0; +} diff --git a/1001-1500/1307-Verbal-Arithmetic-Puzzle/cpp-1307/main2.cpp b/1001-1500/1307-Verbal-Arithmetic-Puzzle/cpp-1307/main2.cpp new file mode 100644 index 00000000..e68d6dd2 --- /dev/null +++ b/1001-1500/1307-Verbal-Arithmetic-Puzzle/cpp-1307/main2.cpp @@ -0,0 +1,126 @@ +/// Source : https://leetcode.com/problems/verbal-arithmetic-puzzle/ +/// Author : liuyubobobo +/// Time : 2020-09-14 + +#include +#include +#include + +using namespace std; + + +/// Backtracking +/// Make leading-zero check during searching +/// Time Complexity: O(10^10) +/// Space Complexity: O(|words| * max_len_of_words) +class Solution { + +private: + vector pow10; + unordered_set leading_letters; + +public: + bool isSolvable(vector& words, string result) { + + pow10 = {1}; + for(int i = 1; i <= 9; i ++) + pow10.push_back(pow10[i - 1] * 10); + + leading_letters.clear(); + for(const string& word: words) + leading_letters.insert(word[0]); + leading_letters.insert(result[0]); + + int maxlen = 0; + for(string& word: words) { + reverse(word.begin(), word.end()); + maxlen = max(maxlen, (int)word.size()); + } + reverse(result.begin(), result.end()); + maxlen = max(maxlen, (int)result.size()); + + vector letters(26, -1); // map from letter to digit + vector used(10, false); // whether digit x is used + return dfs(words, result, maxlen, letters, used, 0, 0); + } + +private: + bool dfs(const vector& words, const string& result, int maxlen, + vector& letters, vector& used, int p, int index){ + + if(index == maxlen) return true; + + // if p == words.size(), check result + if(p == words.size()){ + + int res = 0; + for(const string& word: words){ + int num = 0; + for(int i = 0; i < min(index + 1, (int)word.size()); i ++) + num += letters[word[i] - 'A'] * pow10[i]; + res += num; + } + + string res_str = to_string(res); + + reverse(res_str.begin(), res_str.end()); + int x = index < res_str.size() ? res_str[index] - '0' : 0; + + if(letters[result[index] - 'A'] != -1){ + if(letters[result[index] - 'A'] != x) return false; + return dfs(words, result, maxlen, letters, used, 0, index + 1); + } + + if(used[x]) return false; + + if(x == 0 && leading_letters.count(result[index])) return false; + + letters[result[index] - 'A'] = x; + used[x] = true; + if(dfs(words, result, maxlen, letters, used, 0, index + 1)) return true; + letters[result[index] - 'A'] = -1; + used[x] = false; + return false; + } + + if(index >= words[p].size() || letters[words[p][index] - 'A'] != -1) + return dfs(words, result, maxlen, letters, used, p + 1, index); + + for(int i = 0; i < 10; i ++) + if(!used[i]){ + + if(i == 0 && leading_letters.count(words[p][index])) continue; + + letters[words[p][index] - 'A'] = i; + used[i] = true; + + if(dfs(words, result, maxlen, letters, used, p + 1, index)) return true; + + letters[words[p][index] - 'A'] = -1; + used[i] = false; + } + return false; + } +}; + + +int main() { + + vector words1 = {"SEND", "MORE"}; + cout << Solution().isSolvable(words1, "MONEY") << endl; + // 1 + + vector words2 = {"SIX","SEVEN","SEVEN"}; + cout << Solution().isSolvable(words2, "TWENTY") << endl; + // 1 + + vector words3 = {"THIS","IS","TOO"}; + cout << Solution().isSolvable(words3, "FUNNY") << endl; + // 1 + + vector words4 = {"LEET","CODE"}; + cout << Solution().isSolvable(words4, "POINT") << endl; + // 0 + + return 0; +} diff --git a/1001-1500/1309-Decrypt-String-from-Alphabet-to-Integer-Mapping/cpp-1309/CMakeLists.txt b/1001-1500/1309-Decrypt-String-from-Alphabet-to-Integer-Mapping/cpp-1309/CMakeLists.txt new file mode 100644 index 00000000..9c0b049b --- /dev/null +++ b/1001-1500/1309-Decrypt-String-from-Alphabet-to-Integer-Mapping/cpp-1309/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1001-1500/1309-Decrypt-String-from-Alphabet-to-Integer-Mapping/cpp-1309/main.cpp b/1001-1500/1309-Decrypt-String-from-Alphabet-to-Integer-Mapping/cpp-1309/main.cpp new file mode 100644 index 00000000..9f1dabe4 --- /dev/null +++ b/1001-1500/1309-Decrypt-String-from-Alphabet-to-Integer-Mapping/cpp-1309/main.cpp @@ -0,0 +1,44 @@ +/// Source : https://leetcode.com/problems/decrypt-string-from-alphabet-to-integer-mapping/ +/// Author : liuyubobobo +/// Time : 2020-01-04 + +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + string freqAlphabets(string s) { + + string res = ""; + for(int i = 0; i < s.size();) + if(s[i] <= '2' && i + 2 < s.size() && s[i + 2] == '#'){ + res += (s[i] - '0') * 10 + (s[i + 1] - '0') - 1 + 'a'; + i += 3; + } + else{ + res += (s[i] - '0') - 1 + 'a'; + i ++; + } + return res; + } +}; + + +int main() { + + cout << Solution().freqAlphabets("10#11#12") << endl; + // jkab + + cout << Solution().freqAlphabets("1326#") << endl; + // acz + + cout << Solution().freqAlphabets("25#") << endl; + // y + + return 0; +} diff --git a/1001-1500/1310-XOR-Queries-of-a-Subarray/cpp-1310/CMakeLists.txt b/1001-1500/1310-XOR-Queries-of-a-Subarray/cpp-1310/CMakeLists.txt new file mode 100644 index 00000000..f3359f29 --- /dev/null +++ b/1001-1500/1310-XOR-Queries-of-a-Subarray/cpp-1310/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1001-1500/1310-XOR-Queries-of-a-Subarray/cpp-1310/main.cpp b/1001-1500/1310-XOR-Queries-of-a-Subarray/cpp-1310/main.cpp new file mode 100644 index 00000000..befb3dc5 --- /dev/null +++ b/1001-1500/1310-XOR-Queries-of-a-Subarray/cpp-1310/main.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/xor-queries-of-a-subarray/ +/// Author : liuyubobobo +/// Time : 2020-01-04 + +#include +#include + +using namespace std; + + +/// Pre Sum +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector xorQueries(vector& arr, vector>& queries) { + + vector sum = {0, arr[0]}; + for(int i = 1; i < arr.size(); i ++) + sum.push_back(sum.back() ^ arr[i]); + + vector res; + for(const vector& q: queries) + res.push_back(sum[q[1] + 1] ^ sum[q[0]]); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1311-Get-Watched-Videos-by-Your-Friends/cpp-1311/CMakeLists.txt b/1001-1500/1311-Get-Watched-Videos-by-Your-Friends/cpp-1311/CMakeLists.txt new file mode 100644 index 00000000..0b46ca4b --- /dev/null +++ b/1001-1500/1311-Get-Watched-Videos-by-Your-Friends/cpp-1311/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1001-1500/1311-Get-Watched-Videos-by-Your-Friends/cpp-1311/main.cpp b/1001-1500/1311-Get-Watched-Videos-by-Your-Friends/cpp-1311/main.cpp new file mode 100644 index 00000000..ed6f13db --- /dev/null +++ b/1001-1500/1311-Get-Watched-Videos-by-Your-Friends/cpp-1311/main.cpp @@ -0,0 +1,83 @@ +/// Source : https://leetcode.com/problems/get-watched-videos-by-your-friends/ +/// Author : liuyubobobo +/// Time : 2020-01-04 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// BFS +/// Time Complexity: O(V + E + vlogv) +/// Space Complexity: O(V + v) +class Solution { +public: + vector watchedVideosByFriends(vector>& watchedVideos, vector>& friends, int id, int level) { + + vector> g(friends.size()); + for(int i = 0; i < friends.size(); i ++) + for(int k: friends[i]) + g[i].insert(k), g[k].insert(i); + + set level_friends = bfs(g, id, level); + map freq; + for(int f: level_friends) + for(string video: watchedVideos[f]) + freq[video] ++; + + vector> tres; + for(const pair& p: freq) + tres.push_back(make_pair(p.second, p.first)); + sort(tres.begin(), tres.end()); + + vector res; + for(const pair& p: tres) + res.push_back(p.second); + return res; + } + +private: + set bfs(const vector>& g, int s, int k){ + + queue q; + vector visited(g.size(), false); + vector step(g.size(), 0); + set res; + + q.push(s); + visited[s] = true; + while(!q.empty()){ + int cur = q.front(); + q.pop(); + + for(int next: g[cur]) + if(!visited[next]){ + step[next] = step[cur] + 1; + visited[next] = true; + if(step[next] == k) res.insert(next); + q.push(next); + } + } + return res; + } +}; + + +void print_vec(const vector& v){ + for(const string& e: v) cout << e << " "; cout << endl; +} + +int main() { + + vector> watchedVideos = {{"A","B"},{"C"},{"B","C"},{"D"}}; + vector> friends = {{1,2},{0,3},{0,3},{1,2}}; + vector res = Solution().watchedVideosByFriends(watchedVideos, friends, 0, 2); + print_vec(res); + // D + + return 0; +} diff --git a/1001-1500/1312-Minimum-Insertion-Steps-to-Make-a-String-Palindrome/cpp-1312/CMakeLists.txt b/1001-1500/1312-Minimum-Insertion-Steps-to-Make-a-String-Palindrome/cpp-1312/CMakeLists.txt new file mode 100644 index 00000000..c0c37cc3 --- /dev/null +++ b/1001-1500/1312-Minimum-Insertion-Steps-to-Make-a-String-Palindrome/cpp-1312/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main2.cpp) \ No newline at end of file diff --git a/1001-1500/1312-Minimum-Insertion-Steps-to-Make-a-String-Palindrome/cpp-1312/main.cpp b/1001-1500/1312-Minimum-Insertion-Steps-to-Make-a-String-Palindrome/cpp-1312/main.cpp new file mode 100644 index 00000000..bc5a400c --- /dev/null +++ b/1001-1500/1312-Minimum-Insertion-Steps-to-Make-a-String-Palindrome/cpp-1312/main.cpp @@ -0,0 +1,48 @@ +/// Source : https://leetcode.com/problems/minimum-insertion-steps-to-make-a-string-palindrome/ +/// Author : liuyubobobo +/// Time : 2020-01-14 + +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(n^2) +/// Space Complexity: O(n^2) +class Solution { +public: + int minInsertions(string s) { + + vector> dp(s.size(), vector(s.size(), INT_MAX)); + return dfs(s, 0, s.size() - 1, dp); + } + +private: + int dfs(const string& s, int a, int b, vector>& dp){ + + if(a >= b) return 0; + if(dp[a][b] != INT_MAX) return dp[a][b]; + + int res = INT_MAX; + if(s[a] == s[b]) res = min(res, dp[a][b] = dfs(s, a + 1, b - 1, dp)); + res = min(res, 1 + min(dfs(s, a + 1, b, dp), dfs(s, a, b - 1, dp))); + return dp[a][b] = res; + } +}; + + +int main() { + + cout << Solution().minInsertions("zzazz") << endl; + // 0 + + cout << Solution().minInsertions("mbadm") << endl; + // 2 + + cout << Solution().minInsertions("leetcode") << endl; + // 5 + + return 0; +} diff --git a/1001-1500/1312-Minimum-Insertion-Steps-to-Make-a-String-Palindrome/cpp-1312/main2.cpp b/1001-1500/1312-Minimum-Insertion-Steps-to-Make-a-String-Palindrome/cpp-1312/main2.cpp new file mode 100644 index 00000000..432d3032 --- /dev/null +++ b/1001-1500/1312-Minimum-Insertion-Steps-to-Make-a-String-Palindrome/cpp-1312/main2.cpp @@ -0,0 +1,45 @@ +/// Source : https://leetcode.com/problems/minimum-insertion-steps-to-make-a-string-palindrome/ +/// Author : liuyubobobo +/// Time : 2020-01-14 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(n^2) +/// Space Complexity: O(n^2) +class Solution { +public: + int minInsertions(string s) { + + vector> dp(s.size(), vector(s.size(), INT_MAX)); + for(int i = 0; i < s.size(); i ++) dp[i][i] = 0; + for(int i = 0; i + 1 < s.size(); i ++) dp[i][i + 1] = s[i] == s[i + 1] ? 0 : 1; + for(int len = 3; len <= s.size(); len ++) + for(int i = 0; i + len - 1 < s.size(); i ++) + dp[i][len + i - 1] = s[i] == s[len + i - 1] ? dp[i + 1][len + i - 2] : + 1 + min(dp[i + 1][len + i - 1], dp[i][len + i - 2]); + return dp[0][s.size() - 1]; + } +}; + + +int main() { + + cout << Solution().minInsertions("zzazz") << endl; + // 0 + + cout << Solution().minInsertions("mbadm") << endl; + // 2 + + cout << Solution().minInsertions("leetcode") << endl; + // 5 + + cout << Solution().minInsertions("zjveiiwvc") << endl; + // 5 + + return 0; +} diff --git a/1001-1500/1317-Convert-Integer-to-the-Sum-of-Two-No-Zero-Integers/cpp-1317/CMakeLists.txt b/1001-1500/1317-Convert-Integer-to-the-Sum-of-Two-No-Zero-Integers/cpp-1317/CMakeLists.txt new file mode 100644 index 00000000..9c0b049b --- /dev/null +++ b/1001-1500/1317-Convert-Integer-to-the-Sum-of-Two-No-Zero-Integers/cpp-1317/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1001-1500/1317-Convert-Integer-to-the-Sum-of-Two-No-Zero-Integers/cpp-1317/main.cpp b/1001-1500/1317-Convert-Integer-to-the-Sum-of-Two-No-Zero-Integers/cpp-1317/main.cpp new file mode 100644 index 00000000..9b4a7644 --- /dev/null +++ b/1001-1500/1317-Convert-Integer-to-the-Sum-of-Two-No-Zero-Integers/cpp-1317/main.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/convert-integer-to-the-sum-of-two-no-zero-integers/ +/// Author : liuyubobobo +/// Time : 2020-01-11 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + vector getNoZeroIntegers(int n) { + + for(int i = 1; i <= n / 2; i ++) + if(ok(i) && ok(n - i)) return {i, n - i}; + return {}; + } + +private: + bool ok(int x){ + while(x){ + if(x % 10 == 0) return false; + x /= 10; + } + return true; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1318-Minimum-Flips-to-Make-a-OR-b-Equal-to-c/cpp-1318/CMakeLists.txt b/1001-1500/1318-Minimum-Flips-to-Make-a-OR-b-Equal-to-c/cpp-1318/CMakeLists.txt new file mode 100644 index 00000000..c3e75f47 --- /dev/null +++ b/1001-1500/1318-Minimum-Flips-to-Make-a-OR-b-Equal-to-c/cpp-1318/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main2.cpp) \ No newline at end of file diff --git a/1001-1500/1318-Minimum-Flips-to-Make-a-OR-b-Equal-to-c/cpp-1318/main.cpp b/1001-1500/1318-Minimum-Flips-to-Make-a-OR-b-Equal-to-c/cpp-1318/main.cpp new file mode 100644 index 00000000..c87dcce2 --- /dev/null +++ b/1001-1500/1318-Minimum-Flips-to-Make-a-OR-b-Equal-to-c/cpp-1318/main.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/minimum-flips-to-make-a-or-b-equal-to-c/ +/// Author : liuyubobobo +/// Time : 2020-01-11 + +#include +#include + +using namespace std; + + +/// Convert every number into binary representation +/// Using array to store +/// Time Complexity: O(log(max(a, b, c))) +/// Space Complexity: O(log(max(a, b, c))) +class Solution { +public: + int minFlips(int a, int b, int c) { + + vector av = convert(a), bv = convert(b), cv = convert(c); + + int n = max(av.size(), max(bv.size(), cv.size())); + while(av.size() < n) av.push_back(0); + while(bv.size() < n) bv.push_back(0); + while(cv.size() < n) cv.push_back(0); + + int res = 0; + for(int i = 0; i < n; i ++) + if(cv[i] == 0) res += av[i] + bv[i]; + else res += (av[i] || bv[i]) ? 0 : 1; + return res; + } + +private: + vector convert(int x){ + vector res; + while(x) res.push_back(x % 2), x /= 2; + return res; + } +}; + + +int main() { + + cout << Solution().minFlips(2, 6, 5) << endl; + // 3 + + cout << Solution().minFlips(4, 2, 7) << endl; + // 1 + + cout << Solution().minFlips(1, 2, 3) << endl; + // 0 + + return 0; +} diff --git a/1001-1500/1318-Minimum-Flips-to-Make-a-OR-b-Equal-to-c/cpp-1318/main2.cpp b/1001-1500/1318-Minimum-Flips-to-Make-a-OR-b-Equal-to-c/cpp-1318/main2.cpp new file mode 100644 index 00000000..4d845115 --- /dev/null +++ b/1001-1500/1318-Minimum-Flips-to-Make-a-OR-b-Equal-to-c/cpp-1318/main2.cpp @@ -0,0 +1,43 @@ +/// Source : https://leetcode.com/problems/minimum-flips-to-make-a-or-b-equal-to-c/ +/// Author : liuyubobobo +/// Time : 2020-01-11 + +#include +#include + +using namespace std; + + +/// Convert every number into binary representation in the run +/// Time Complexity: O(log(max(a, b, c))) +/// Space Complexity: O(1) +class Solution { +public: + int minFlips(int a, int b, int c) { + + int res = 0; + while(a || b || c){ + int abit = a & 1, bbit = b & 1, cbit = c & 1; + a >>= 1, b >>= 1, c >>= 1; + + if(cbit == 0) res += abit + bbit; + else res += (abit | bbit) ? 0 : 1; + } + return res; + } +}; + + +int main() { + + cout << Solution().minFlips(2, 6, 5) << endl; + // 3 + + cout << Solution().minFlips(4, 2, 7) << endl; + // 1 + + cout << Solution().minFlips(1, 2, 3) << endl; + // 0 + + return 0; +} diff --git a/1001-1500/1319-Number-of-Operations-to-Make-Network-Connected/cpp-1319/CMakeLists.txt b/1001-1500/1319-Number-of-Operations-to-Make-Network-Connected/cpp-1319/CMakeLists.txt new file mode 100644 index 00000000..64f6c751 --- /dev/null +++ b/1001-1500/1319-Number-of-Operations-to-Make-Network-Connected/cpp-1319/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main2.cpp) \ No newline at end of file diff --git a/1001-1500/1319-Number-of-Operations-to-Make-Network-Connected/cpp-1319/main.cpp b/1001-1500/1319-Number-of-Operations-to-Make-Network-Connected/cpp-1319/main.cpp new file mode 100644 index 00000000..4e5514df --- /dev/null +++ b/1001-1500/1319-Number-of-Operations-to-Make-Network-Connected/cpp-1319/main.cpp @@ -0,0 +1,73 @@ +/// Source : https://leetcode.com/problems/number-of-operations-to-make-network-connected/ +/// Author : liuyubobobo +/// Time : 2020-01-11 + +#include +#include +#include + +using namespace std; + + +/// Count Vertex number and Edge number for every CC +/// Time Complexity: O(V + E) +/// Space Complexity: O(V + E) +class Solution { + +public: + int makeConnected(int n, vector>& connections) { + + vector> g(n); + for(const vector& e: connections) + g[e[0]].insert(e[1]), g[e[1]].insert(e[0]); + + vector visited(n, false); + int com_num = 0, left = 0; + for(int i = 0; i < n; i ++) + if(!visited[i]){ + int v_num = 0; + int e_num = 0; + dfs(g, i, visited, v_num, e_num); + com_num ++; + left += e_num / 2 - (v_num - 1); + } + + if(left >= com_num - 1) return com_num - 1; + return -1; + } + +private: + void dfs(const vector>& g, int v, vector& visited, + int& v_num, int& e_num){ + + visited[v] = true; + v_num ++; + + for(int next: g[v]){ + e_num ++; + if(!visited[next]) dfs(g, next, visited, v_num, e_num); + } + } +}; + + +int main() { + + vector> c1 = {{0, 1}, {0, 2}, {1, 2}}; + cout << Solution().makeConnected(4, c1) << endl; + // 1 + + vector> c2 = {{0, 1}, {0, 2}, {0, 3}, {1, 2}, {1, 3}}; + cout << Solution().makeConnected(6, c2) << endl; + // 2 + + vector> c3 = {{0, 1}, {0, 2}, {0, 3}, {1, 2}}; + cout << Solution().makeConnected(6, c3) << endl; + // -1 + + vector> c4 = {{0, 1}, {0, 2}, {3, 4}, {2, 3}}; + cout << Solution().makeConnected(5, c4) << endl; + // 0 + + return 0; +} diff --git a/1001-1500/1319-Number-of-Operations-to-Make-Network-Connected/cpp-1319/main2.cpp b/1001-1500/1319-Number-of-Operations-to-Make-Network-Connected/cpp-1319/main2.cpp new file mode 100644 index 00000000..da7475d2 --- /dev/null +++ b/1001-1500/1319-Number-of-Operations-to-Make-Network-Connected/cpp-1319/main2.cpp @@ -0,0 +1,65 @@ +/// Source : https://leetcode.com/problems/number-of-operations-to-make-network-connected/ +/// Author : liuyubobobo +/// Time : 2020-01-11 + +#include +#include +#include + +using namespace std; + + +/// Just count CC number would be enough! +/// Time Complexity: O(V + E) +/// Space Complexity: O(V + E) +class Solution { + +public: + int makeConnected(int n, vector>& connections) { + + if(n - 1 > connections.size()) return -1; + + vector> g(n); + for(const vector& e: connections) + g[e[0]].insert(e[1]), g[e[1]].insert(e[0]); + + vector visited(n, false); + int cc = 0; + for(int i = 0; i < n; i ++) + if(!visited[i]) + dfs(g, i, visited), cc ++; + + return cc - 1; + } + +private: + void dfs(const vector>& g, int v, vector& visited){ + + visited[v] = true; + for(int next: g[v]) + if(!visited[next]) + dfs(g, next, visited); + } +}; + + +int main() { + + vector> c1 = {{0, 1}, {0, 2}, {1, 2}}; + cout << Solution().makeConnected(4, c1) << endl; + // 1 + + vector> c2 = {{0, 1}, {0, 2}, {0, 3}, {1, 2}, {1, 3}}; + cout << Solution().makeConnected(6, c2) << endl; + // 2 + + vector> c3 = {{0, 1}, {0, 2}, {0, 3}, {1, 2}}; + cout << Solution().makeConnected(6, c3) << endl; + // -1 + + vector> c4 = {{0, 1}, {0, 2}, {3, 4}, {2, 3}}; + cout << Solution().makeConnected(5, c4) << endl; + // 0 + + return 0; +} diff --git a/1001-1500/1323-Maximum-69-Number/cpp-1323/CMakeLists.txt b/1001-1500/1323-Maximum-69-Number/cpp-1323/CMakeLists.txt new file mode 100644 index 00000000..39d32ac5 --- /dev/null +++ b/1001-1500/1323-Maximum-69-Number/cpp-1323/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_1323) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1323 main.cpp) diff --git a/1001-1500/1323-Maximum-69-Number/cpp-1323/main.cpp b/1001-1500/1323-Maximum-69-Number/cpp-1323/main.cpp new file mode 100644 index 00000000..295d2468 --- /dev/null +++ b/1001-1500/1323-Maximum-69-Number/cpp-1323/main.cpp @@ -0,0 +1,31 @@ +/// Source : https://leetcode.com/problems/maximum-69-number/description/ +/// Author : liuyubobobo +/// Time : 2022-11-07 + +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(log(num)) +/// Space Complexity: O(log(num)) +class Solution { +public: + int maximum69Number (int num) { + + string s = to_string(num); + for(char& c: s) + if(c == '6'){ + c = '9'; + break; + } + return atoi(s.c_str()); + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1326-Minimum-Number-of-Taps-to-Open-to-Water-a-Garden/cpp-1326/CMakeLists.txt b/1001-1500/1326-Minimum-Number-of-Taps-to-Open-to-Water-a-Garden/cpp-1326/CMakeLists.txt new file mode 100644 index 00000000..eef8b694 --- /dev/null +++ b/1001-1500/1326-Minimum-Number-of-Taps-to-Open-to-Water-a-Garden/cpp-1326/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_1326) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_1326 main.cpp) diff --git a/1001-1500/1326-Minimum-Number-of-Taps-to-Open-to-Water-a-Garden/cpp-1326/main.cpp b/1001-1500/1326-Minimum-Number-of-Taps-to-Open-to-Water-a-Garden/cpp-1326/main.cpp new file mode 100644 index 00000000..a8c09eaa --- /dev/null +++ b/1001-1500/1326-Minimum-Number-of-Taps-to-Open-to-Water-a-Garden/cpp-1326/main.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/minimum-number-of-taps-to-open-to-water-a-garden/description/ +/// Author : liuyubobobo +/// Time : 2023-02-20 + +#include +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(n * max_range) +/// Space Complexity: O(n) +class Solution { +public: + int minTaps(int n, vector& ranges) { + + vector dp(n, INT_MAX / 2); + for(int i = 0; i <= n; i ++){ + int l = max(0, i - ranges[i]), r = min(n, i + ranges[i]); + for(int j = l; j < r; j ++) + dp[j] = min(dp[j], (l - 1 >= 0 ? dp[l - 1] : 0) + 1); + } + return dp.back() == INT_MAX / 2 ? -1 : dp.back(); + } +}; + +int main() { + + vector ranges1 = {0, 0, 0, 0}; + cout << Solution().minTaps(3, ranges1) << '\n'; + + return 0; +} diff --git a/1001-1500/1328-Break-a-Palindrome/cpp-1328/CMakeLists.txt b/1001-1500/1328-Break-a-Palindrome/cpp-1328/CMakeLists.txt new file mode 100644 index 00000000..d93549b4 --- /dev/null +++ b/1001-1500/1328-Break-a-Palindrome/cpp-1328/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_1328) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1328 main.cpp) diff --git a/1001-1500/1328-Break-a-Palindrome/cpp-1328/main.cpp b/1001-1500/1328-Break-a-Palindrome/cpp-1328/main.cpp new file mode 100644 index 00000000..088203b0 --- /dev/null +++ b/1001-1500/1328-Break-a-Palindrome/cpp-1328/main.cpp @@ -0,0 +1,42 @@ +/// Source : https://leetcode.com/problems/break-a-palindrome/ +/// Author : liuyubobobo +/// Time : 2021-09-23 + +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + string breakPalindrome(string palindrome) { + + if(palindrome == "a") return ""; + + int n = palindrome.size(); + for(int i = 0; i < n; i ++) + if(palindrome[i] > 'a'){ + if(n % 2 == 1 && i == n / 2) continue; + palindrome[i] = 'a'; + return palindrome; + } + + for(int i = palindrome.size() - 1; i >= 0; i --) + if(palindrome[i] < 'z'){ + if(n % 2 == 1 && i == n / 2) continue; + palindrome[i] = 'b'; + return palindrome; + } + + return ""; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1329-Sort-the-Matrix-Diagonally/cpp-1329/CMakeLists.txt b/1001-1500/1329-Sort-the-Matrix-Diagonally/cpp-1329/CMakeLists.txt new file mode 100644 index 00000000..0b0ade05 --- /dev/null +++ b/1001-1500/1329-Sort-the-Matrix-Diagonally/cpp-1329/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1329) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1329 main.cpp) \ No newline at end of file diff --git a/1001-1500/1329-Sort-the-Matrix-Diagonally/cpp-1329/main.cpp b/1001-1500/1329-Sort-the-Matrix-Diagonally/cpp-1329/main.cpp new file mode 100644 index 00000000..9401cc51 --- /dev/null +++ b/1001-1500/1329-Sort-the-Matrix-Diagonally/cpp-1329/main.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/sort-the-matrix-diagonally/ +/// Author : liuyubobobo +/// Time : 2021-01-24 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(R * C * log(max(R, C))) +/// Space Complexity: O(1) +class Solution { + +private: + int R, C; + +public: + vector> diagonalSort(vector>& mat) { + + R = mat.size(), C = mat[0].size(); + for(int j = 0; j < C; j ++) deal(mat, 0, j); + for(int i = 1; i < R; i ++) deal(mat, i, 0); + return mat; + } + +private: + void deal(vector>& mat, int x, int y){ + + vector v; + for(int d = 0; x + d < R && y + d < C; d ++) + v.push_back(mat[x + d][y + d]); + + sort(v.begin(), v.end()); + + for(int d = 0; x + d < R && y + d < C; d ++) + mat[x + d][y + d] = v[d]; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1330-Reverse-Subarray-To-Maximize-Array-Value/cpp-1330/CMakeLists.txt b/1001-1500/1330-Reverse-Subarray-To-Maximize-Array-Value/cpp-1330/CMakeLists.txt new file mode 100644 index 00000000..d06b08c3 --- /dev/null +++ b/1001-1500/1330-Reverse-Subarray-To-Maximize-Array-Value/cpp-1330/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_1330) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_1330 main.cpp) diff --git a/1001-1500/1330-Reverse-Subarray-To-Maximize-Array-Value/cpp-1330/main.cpp b/1001-1500/1330-Reverse-Subarray-To-Maximize-Array-Value/cpp-1330/main.cpp new file mode 100644 index 00000000..775235e1 --- /dev/null +++ b/1001-1500/1330-Reverse-Subarray-To-Maximize-Array-Value/cpp-1330/main.cpp @@ -0,0 +1,60 @@ +/// Source : https://leetcode.com/problems/reverse-subarray-to-maximize-array-value/description/ +/// Author : liuyubobobo +/// Time : 2023-05-12 + +#include +#include + +using namespace std; + + +/// Absolute Value Expression +/// |a - b| = max(a - b, b - a) +/// max(a, b) - c = max(a - c, b - c) +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int maxValueAfterReverse(vector& nums) { + + int n = nums.size(); + if(n == 1) return 0; + + long long base = 0; + for(int i = 1; i < n; i ++) base += abs(nums[i] - nums[i - 1]); + + long long res = base; + for(int i = 1; i < n; i ++) + res = max(res, base - abs(nums[i] - nums[i - 1]) + abs(nums[i] - nums[0])); + for(int i = n - 2; i >= 0; i --) + res = max(res, base - abs(nums[i] - nums[i + 1]) + abs(nums[i] - nums[n - 1])); + + vector dp(4); + dp[0] = nums[0] + nums[1] - abs(nums[0] - nums[1]); + dp[1] = nums[0] - nums[1] - abs(nums[0] - nums[1]); + dp[2] = - nums[0] + nums[1] - abs(nums[0] - nums[1]); + dp[3] = - nums[0] - nums[1] - abs(nums[0] - nums[1]); + + for(int i = 1; i + 1 < n; i ++){ + int d = 0, x= nums[i], y = nums[i + 1]; + d = max(d, dp[0] - (x + y) - abs(x - y)); + d = max(d, dp[1] - (x - y) - abs(x - y)); + d = max(d, dp[2] - (- x + y) - abs(x - y)); + d = max(d, dp[3] - (- x - y) - abs(x - y)); + + res = max(res, base + d); + + dp[0] = max(dp[0], x + y - abs(x - y)); + dp[1] = max(dp[1], x - y - abs(x - y)); + dp[2] = max(dp[2], - x + y - abs(x - y)); + dp[3] = max(dp[3], - x - y - abs(x - y)); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1331-Rank-Transform-of-an-Array/cpp-1331/CMakeLists.txt b/1001-1500/1331-Rank-Transform-of-an-Array/cpp-1331/CMakeLists.txt new file mode 100644 index 00000000..8c4a7b96 --- /dev/null +++ b/1001-1500/1331-Rank-Transform-of-an-Array/cpp-1331/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_1331) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1331 main.cpp) diff --git a/1001-1500/1331-Rank-Transform-of-an-Array/cpp-1331/main.cpp b/1001-1500/1331-Rank-Transform-of-an-Array/cpp-1331/main.cpp new file mode 100644 index 00000000..156d4d23 --- /dev/null +++ b/1001-1500/1331-Rank-Transform-of-an-Array/cpp-1331/main.cpp @@ -0,0 +1,38 @@ +/// Source : https://leetcode.com/problems/rank-transform-of-an-array/ +/// Author : liuyubobobo +/// Time : 2022-07-27 + +#include +#include +#include + +using namespace std; + + +/// Using Map +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + vector arrayRankTransform(vector& arr) { + + map rank; + for(int e: arr) rank[e] = 0; + + int r = 1; + for(const pair& p: rank){ + rank[p.first] = r ++; + } + + vector res(arr.size()); + for(int i = 0; i < arr.size(); i ++) + res[i] = rank[arr[i]]; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1332-Remove-Palindromic-Subsequences/cpp-1332/CMakeLists.txt b/1001-1500/1332-Remove-Palindromic-Subsequences/cpp-1332/CMakeLists.txt new file mode 100644 index 00000000..e1446cc5 --- /dev/null +++ b/1001-1500/1332-Remove-Palindromic-Subsequences/cpp-1332/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(cpp_1332) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1332 main.cpp) \ No newline at end of file diff --git a/1001-1500/1332-Remove-Palindromic-Subsequences/cpp-1332/main.cpp b/1001-1500/1332-Remove-Palindromic-Subsequences/cpp-1332/main.cpp new file mode 100644 index 00000000..2d2b277c --- /dev/null +++ b/1001-1500/1332-Remove-Palindromic-Subsequences/cpp-1332/main.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/remove-palindromic-subsequences/ +/// Author : liuyubobobo +/// Time : 2020-02-21 + +#include + +using namespace std; + + +/// Mathematics +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int removePalindromeSub(string s) { + + if(s == "") return 0; + return isPalindrome(s) ? 1 : 2; + } + +private: + bool isPalindrome(const string& s){ + + for(int i = 0, j = s.size() - 1; i < j; i ++, j --) + if(s[i] != s[j]) return false; + return true; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1333-Filter-Restaurants-by-Vegan-Friendly-Price-and-Distance/cpp-1333/CMakeLists.txt b/1001-1500/1333-Filter-Restaurants-by-Vegan-Friendly-Price-and-Distance/cpp-1333/CMakeLists.txt new file mode 100644 index 00000000..eae8e7dc --- /dev/null +++ b/1001-1500/1333-Filter-Restaurants-by-Vegan-Friendly-Price-and-Distance/cpp-1333/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(cpp_1333) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1333 main.cpp) \ No newline at end of file diff --git a/1001-1500/1333-Filter-Restaurants-by-Vegan-Friendly-Price-and-Distance/cpp-1333/main.cpp b/1001-1500/1333-Filter-Restaurants-by-Vegan-Friendly-Price-and-Distance/cpp-1333/main.cpp new file mode 100644 index 00000000..c067b9e5 --- /dev/null +++ b/1001-1500/1333-Filter-Restaurants-by-Vegan-Friendly-Price-and-Distance/cpp-1333/main.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/filter-restaurants-by-vegan-friendly-price-and-distance/ +/// Author : liuyubobobo +/// Time : 2020-02-29 + +#include +#include +#include + +using namespace std; + + +/// Sorting +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + vector filterRestaurants(vector>& restaurants, int veganFriendly, int maxPrice, int maxDistance) { + + vector> res; + for(const vector& r: restaurants) + if((!veganFriendly || r[2]) && maxPrice >= r[3] && maxDistance >= r[4]) + res.push_back(make_pair(r[1], r[0])); + + sort(res.begin(), res.end(), greater>()); + + vector ret; + for(const pair& p: res) ret.push_back(p.second); + return ret; + } +}; + + +void print_vec(const vector vec){ + for(int e: vec) cout << e << " "; cout << endl; +} + +int main() { + + vector> restaurants = { + {1,4,1,40,10}, + {2,8,0,50,5}, + {3,8,1,30,4}, + {4,10,0,10,3}, + {5,1,1,15,1} + }; + print_vec(Solution().filterRestaurants(restaurants, 0, 50, 10)); + // 4 3 2 1 5 + + return 0; +} diff --git a/1001-1500/1334-Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance/cpp-1334/CMakeLists.txt b/1001-1500/1334-Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance/cpp-1334/CMakeLists.txt new file mode 100644 index 00000000..b66cb1bd --- /dev/null +++ b/1001-1500/1334-Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance/cpp-1334/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(cpp_1334) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1334 main2.cpp) \ No newline at end of file diff --git a/1001-1500/1334-Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance/cpp-1334/main.cpp b/1001-1500/1334-Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance/cpp-1334/main.cpp new file mode 100644 index 00000000..ee46a157 --- /dev/null +++ b/1001-1500/1334-Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance/cpp-1334/main.cpp @@ -0,0 +1,73 @@ +/// Source : https://leetcode.com/problems/find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/ +/// Author : liuyubobobo +/// Time : 2020-03-06 + +#include +#include +#include +#include + +using namespace std; + + +/// Dijkstra +/// Time Complexity: O(VElogE) +/// Space Complexity: O(V) +class Solution { +public: + int findTheCity(int n, vector>& edges, int distanceThreshold) { + + vector> g(n); + for(const vector& v: edges) + g[v[0]][v[1]] = v[2], g[v[1]][v[0]] = v[2]; + + int minNum = INT_MAX, res = -1; + for(int i = 0; i < n; i ++){ + int num = dij(g, i, distanceThreshold); +// cout << i << " : " << num << endl; + if(num <= minNum) minNum = num, res = i; + } + return res; + } + +private: + int dij(const vector>& g, int v, int distanceThreshold){ + + int n = g.size(); + vector dis(n, INT_MAX); + vector visited(n, false); + + dis[v] = 0; + priority_queue> pq; + pq.push(make_pair(0, v)); + while(!pq.empty()){ + int cur = pq.top().second, d = -pq.top().first; + pq.pop(); + + if(visited[cur]) continue; + visited[cur] = true; + for(const pair& p: g[cur]) + if(!visited[p.first] && d + p.second < dis[p.first]){ + dis[p.first] = d + p.second; + pq.push(make_pair(- dis[p.first], p.first)); + } + } + + int res = 0; + for(int e: dis) res += (e <= distanceThreshold); +// cout << v << " dis : "; for(int e: dis) cout << e << " "; cout << endl; + return res; + } +}; + + +int main() { + + vector> edges = { + {0,1,2},{0,4,8},{1,2,3},{1,4,2},{2,3,1},{3,4,1} + }; + cout << Solution().findTheCity(5, edges, 2) << endl; + // 0 + + return 0; +} diff --git a/1001-1500/1334-Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance/cpp-1334/main2.cpp b/1001-1500/1334-Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance/cpp-1334/main2.cpp new file mode 100644 index 00000000..f9c57159 --- /dev/null +++ b/1001-1500/1334-Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance/cpp-1334/main2.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/ +/// Author : liuyubobobo +/// Time : 2020-03-06 + +#include +#include +#include +#include + +using namespace std; + + +/// Floyed +/// Time Complexity: O(V^3) +/// Space Complexity: O(V^2) +class Solution { +public: + int findTheCity(int n, vector>& edges, int distanceThreshold) { + + vector> dis(n, vector(n, INT_MAX)); + for(const vector& e: edges) + dis[e[0]][e[1]] = dis[e[1]][e[0]] = e[2]; + + for(int i = 0; i < n; i ++) dis[i][i] = 0; + for(int t = 0; t < n; t ++) + for(int v = 0; v < n; v ++) + for(int w = 0; w < n; w ++) + if(dis[v][t] != INT_MAX && dis[t][w] != INT_MAX) + dis[v][w] = min(dis[v][w], dis[v][t] + dis[t][w]); + + int minNum = INT_MAX, res = -1; + for(int i = 0; i < n; i ++){ + int num = 0; + for(int v = 0; v < n; v ++) + if(v != i) num += (dis[i][v] <= distanceThreshold); + if(num <= minNum) minNum = num, res = i; + } + return res; + } +}; + + +int main() { + + vector> edges = { + {0,1,2},{0,4,8},{1,2,3},{1,4,2},{2,3,1},{3,4,1} + }; + cout << Solution().findTheCity(5, edges, 2) << endl; + // 0 + + return 0; +} diff --git a/1001-1500/1335-Minimum-Difficulty-of-a-Job-Schedule/cpp-1335/CMakeLists.txt b/1001-1500/1335-Minimum-Difficulty-of-a-Job-Schedule/cpp-1335/CMakeLists.txt new file mode 100644 index 00000000..661d85c5 --- /dev/null +++ b/1001-1500/1335-Minimum-Difficulty-of-a-Job-Schedule/cpp-1335/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(cpp_1335) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1335 main2.cpp) \ No newline at end of file diff --git a/1001-1500/1335-Minimum-Difficulty-of-a-Job-Schedule/cpp-1335/main.cpp b/1001-1500/1335-Minimum-Difficulty-of-a-Job-Schedule/cpp-1335/main.cpp new file mode 100644 index 00000000..e34bdf79 --- /dev/null +++ b/1001-1500/1335-Minimum-Difficulty-of-a-Job-Schedule/cpp-1335/main.cpp @@ -0,0 +1,75 @@ +/// Source : https://leetcode.com/problems/minimum-difficulty-of-a-job-schedule/ +/// Author : liuyubobobo +/// Time : 2020-05-07 + +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(d * n^2) +/// Space Complexity: O(d * n) +class Solution { + +private: + const int INF = 1e9; + int n; + +public: + int minDifficulty(vector& jobDifficulty, int d) { + + n = jobDifficulty.size(); + if(d > n) return -1; + + vector> dp(d + 1, vector(n, -1)); + return dfs(jobDifficulty, 0, d, dp); + } + +private: + int dfs(const vector& nums, int start, int d, vector>& dp){ + +// if(start == nums.size()) return d == 0 ? 0 : INF; + if(dp[d][start] != -1) return dp[d][start]; + + if(d == 1) return dp[d][start] = *max_element(nums.begin() + start, nums.end()); + + int curmax = nums[start], res = curmax + dfs(nums, start + 1, d - 1, dp); + for(int i = start + 1; i + d <= nums.size(); i ++){ + curmax = max(curmax, nums[i]); + res = min(res, curmax + dfs(nums, i + 1, d - 1, dp)); + } + return dp[d][start] = res; + } +}; + + +int main() { + + vector job1 = {6,5,4,3,2,1}; + cout << Solution().minDifficulty(job1, 2) << endl; + // 7 + + vector job2 = {9, 9, 9}; + cout << Solution().minDifficulty(job2, 4) << endl; + // -1 + + vector job3 = {1, 1, 1}; + cout << Solution().minDifficulty(job3, 3) << endl; + // 3 + + vector job4 = {7,1,7,1,7,1}; + cout << Solution().minDifficulty(job4, 3) << endl; + // 15 + + vector job5 = {11,111,22,222,33,333,44,444}; + cout << Solution().minDifficulty(job5, 6) << endl; + // 843 + + vector job6 = {42,35,957,671,87,222,524,5,280,878,242,398,610,984,649,513,563,997,786,223,413,961,208,189,519,606,504,406,994,475,940,476,762,283,218,404,715,755,689,457,20,403,749,68,17,763,78,695,445,338,643,400,615,29,866,861,103,665,743,361,798,236,255,15,326,124,14,588,711,992,501,731,538,619,765,8,477,854,243,95,627,480,505,800,818,722,194,717,305,810,497,686,704,322,532,22,234,290,885,416,155,428,161,315,152,441,730,926,175,536,646,922,951,101,107,233,61,735,669,512,28,569,447,982,916,321,1000,754,483,482,811,654,47,344,772,978,467,308,472,269,0,252,131,834,303,945,469,785,537,188,449,675,528,733,271,541,822,328,904,876,889,55,16,853,154,767,573,925,279,697,525,431,375,958,836,911,166,965,523,709,923,587,603,226,354,641,620,316,110,292,529,943,1,151,737,959,27,56,353,681,26,677,337,723,12,914,955,134,370,260,490,684,364,618,232,870,985,196,225,359,129,58,341,67,494,757,229,323,256,21,783,692,642,37,909,248,81,345,425,478,651,309,435,10,534,450,576,144,201,496,267,609,11,454,531,966,156,176,190,542,856,365,983,947,758,950,388,820,867,833,605,741,34,663,884,65,628,969,864,664,718,805,891,657,863,960,518,71,300,756,613,667,228,274,971,970,552,556,648,251}; + cout << Solution().minDifficulty(job6, 10) << endl; + // 3044 + + return 0; +} diff --git a/1001-1500/1335-Minimum-Difficulty-of-a-Job-Schedule/cpp-1335/main2.cpp b/1001-1500/1335-Minimum-Difficulty-of-a-Job-Schedule/cpp-1335/main2.cpp new file mode 100644 index 00000000..17480922 --- /dev/null +++ b/1001-1500/1335-Minimum-Difficulty-of-a-Job-Schedule/cpp-1335/main2.cpp @@ -0,0 +1,69 @@ +/// Source : https://leetcode.com/problems/minimum-difficulty-of-a-job-schedule/ +/// Author : liuyubobobo +/// Time : 2020-05-07 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(d * n^2) +/// Space Complexity: O(d * n) +class Solution { + +public: + int minDifficulty(vector& jobDifficulty, int d) { + + int n = jobDifficulty.size(); + if(d > n) return -1; + + vector> dp(d, vector(n)); + dp[0][n - 1] = jobDifficulty[n - 1]; + for(int i = n - 2; i >= 0; i --) + dp[0][i] = max(dp[0][i + 1], jobDifficulty[i]); + + for(int i = 1; i < d; i ++){ + for(int j = 0; j + i < n; j ++){ + int curmax = jobDifficulty[j]; + dp[i][j] = curmax + dp[i - 1][j + 1]; + for(int k = j + 1; k + i < n; k ++){ + curmax= max(curmax, jobDifficulty[k]); + dp[i][j] = min(dp[i][j], curmax + dp[i - 1][k + 1]); + } + } + } + return dp[d - 1][0]; + } +}; + + +int main() { + + vector job1 = {6,5,4,3,2,1}; + cout << Solution().minDifficulty(job1, 2) << endl; + // 7 + + vector job2 = {9, 9, 9}; + cout << Solution().minDifficulty(job2, 4) << endl; + // -1 + + vector job3 = {1, 1, 1}; + cout << Solution().minDifficulty(job3, 3) << endl; + // 3 + + vector job4 = {7,1,7,1,7,1}; + cout << Solution().minDifficulty(job4, 3) << endl; + // 15 + + vector job5 = {11,111,22,222,33,333,44,444}; + cout << Solution().minDifficulty(job5, 6) << endl; + // 843 + + vector job6 = {42,35,957,671,87,222,524,5,280,878,242,398,610,984,649,513,563,997,786,223,413,961,208,189,519,606,504,406,994,475,940,476,762,283,218,404,715,755,689,457,20,403,749,68,17,763,78,695,445,338,643,400,615,29,866,861,103,665,743,361,798,236,255,15,326,124,14,588,711,992,501,731,538,619,765,8,477,854,243,95,627,480,505,800,818,722,194,717,305,810,497,686,704,322,532,22,234,290,885,416,155,428,161,315,152,441,730,926,175,536,646,922,951,101,107,233,61,735,669,512,28,569,447,982,916,321,1000,754,483,482,811,654,47,344,772,978,467,308,472,269,0,252,131,834,303,945,469,785,537,188,449,675,528,733,271,541,822,328,904,876,889,55,16,853,154,767,573,925,279,697,525,431,375,958,836,911,166,965,523,709,923,587,603,226,354,641,620,316,110,292,529,943,1,151,737,959,27,56,353,681,26,677,337,723,12,914,955,134,370,260,490,684,364,618,232,870,985,196,225,359,129,58,341,67,494,757,229,323,256,21,783,692,642,37,909,248,81,345,425,478,651,309,435,10,534,450,576,144,201,496,267,609,11,454,531,966,156,176,190,542,856,365,983,947,758,950,388,820,867,833,605,741,34,663,884,65,628,969,864,664,718,805,891,657,863,960,518,71,300,756,613,667,228,274,971,970,552,556,648,251}; + cout << Solution().minDifficulty(job6, 10) << endl; + // 3044 + + return 0; +} diff --git a/1001-1500/1337-The-K-Weakest-Rows-in-a-Matrix/cpp-1337/CMakeLists.txt b/1001-1500/1337-The-K-Weakest-Rows-in-a-Matrix/cpp-1337/CMakeLists.txt new file mode 100644 index 00000000..3731f44a --- /dev/null +++ b/1001-1500/1337-The-K-Weakest-Rows-in-a-Matrix/cpp-1337/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main2.cpp) \ No newline at end of file diff --git a/1001-1500/1337-The-K-Weakest-Rows-in-a-Matrix/cpp-1337/main.cpp b/1001-1500/1337-The-K-Weakest-Rows-in-a-Matrix/cpp-1337/main.cpp new file mode 100644 index 00000000..21fa0867 --- /dev/null +++ b/1001-1500/1337-The-K-Weakest-Rows-in-a-Matrix/cpp-1337/main.cpp @@ -0,0 +1,36 @@ +/// Source : https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/ +/// Author : liuyubobobo +/// Time : 2020-02-01 + +#include +#include +#include + +using namespace std; + + +/// Sorting +/// Time Complexity: O(m * n + nlogn) +/// Space Complexity: O(n) +class Solution { +public: + vector kWeakestRows(vector>& mat, int k) { + + vector> res; + for(int i = 0; i < mat.size(); i ++) + res.push_back(make_pair(accumulate(mat[i].begin(), mat[i].end(), 0), i)); + + sort(res.begin(), res.end()); + + vector ret; + for(int i = 0; i < k; i ++) + ret.push_back(res[i].second); + return ret; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1337-The-K-Weakest-Rows-in-a-Matrix/cpp-1337/main2.cpp b/1001-1500/1337-The-K-Weakest-Rows-in-a-Matrix/cpp-1337/main2.cpp new file mode 100644 index 00000000..043b6a05 --- /dev/null +++ b/1001-1500/1337-The-K-Weakest-Rows-in-a-Matrix/cpp-1337/main2.cpp @@ -0,0 +1,38 @@ +/// Source : https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/ +/// Author : liuyubobobo +/// Time : 2020-02-10 + +#include +#include +#include + +using namespace std; + + +/// Scan column by column +/// Time Complexity: O(m * n) +/// Space Complexity: O(n) +class Solution { +public: + vector kWeakestRows(vector>& mat, int k) { + + for(int i = 0; i < mat.size(); i ++) + mat[i].push_back(0); + + vector res; + vector visited(mat.size(), false); + for(int j = 0; j < mat[0].size(); j ++) + for(int i = 0; i < mat.size(); i ++) + if(!mat[i][j] && !visited[i]){ + res.push_back(i), visited[i] = true; + if(res.size() == k) return res; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1338-Reduce-Array-Size-to-The-Half/cpp-1338/CMakeLists.txt b/1001-1500/1338-Reduce-Array-Size-to-The-Half/cpp-1338/CMakeLists.txt new file mode 100644 index 00000000..f3359f29 --- /dev/null +++ b/1001-1500/1338-Reduce-Array-Size-to-The-Half/cpp-1338/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1001-1500/1338-Reduce-Array-Size-to-The-Half/cpp-1338/main.cpp b/1001-1500/1338-Reduce-Array-Size-to-The-Half/cpp-1338/main.cpp new file mode 100644 index 00000000..649fd359 --- /dev/null +++ b/1001-1500/1338-Reduce-Array-Size-to-The-Half/cpp-1338/main.cpp @@ -0,0 +1,41 @@ +/// Source : https://leetcode.com/problems/reduce-array-size-to-the-half/ +/// Author : liuyubobobo +/// Time : 2019-02-01 + +#include +#include +#include + +using namespace std; + + +/// Sorting +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + int minSetSize(vector& arr) { + + map freq; + for(int e: arr) freq[e] ++; + + vector f; + for(const pair& p: freq) + f.push_back(-p.second); + sort(f.begin(), f.end()); + + int n = arr.size() / 2 + arr.size() % 2, k = 0, res = 0; + for(int e: f){ + k += - e; + res ++; + if(k >= n) return res; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1339-Maximum-Product-of-Splitted-Binary-Tree/cpp-1339/CMakeLists.txt b/1001-1500/1339-Maximum-Product-of-Splitted-Binary-Tree/cpp-1339/CMakeLists.txt new file mode 100644 index 00000000..0b46ca4b --- /dev/null +++ b/1001-1500/1339-Maximum-Product-of-Splitted-Binary-Tree/cpp-1339/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1001-1500/1339-Maximum-Product-of-Splitted-Binary-Tree/cpp-1339/main.cpp b/1001-1500/1339-Maximum-Product-of-Splitted-Binary-Tree/cpp-1339/main.cpp new file mode 100644 index 00000000..23c82d7d --- /dev/null +++ b/1001-1500/1339-Maximum-Product-of-Splitted-Binary-Tree/cpp-1339/main.cpp @@ -0,0 +1,66 @@ +/// Source : https://leetcode.com/problems/maximum-product-of-splitted-binary-tree/ +/// Author : liuyubobobo +/// Time : 2020-02-01 + +#include + +using namespace std; + + +/// Two DFS +/// Time Complexity: O(n) +/// Space Complexity: O(logn) + +/// 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 { + +private: + long long MOD = 1e9 + 7; + +public: + int maxProduct(TreeNode* root) { + + dfs1(root); + + long long res = 0ll; + dfs2(root, root, res); + return res % MOD; + } + +private: + int dfs1(TreeNode* node){ + + if(!node) return 0; + + int x = dfs1(node->left); + int y = dfs1(node->right); + node->val += (x + y); + return node->val; + } + + void dfs2(TreeNode* root, TreeNode* node, long long& res){ + + if(node->left){ + res = max(res, (long long)(root->val - node->left->val) * (long long)node->left->val); + dfs2(root, node->left, res); + } + + if(node->right){ + res = max(res, (long long)(root->val - node->right->val) * (long long)node->right->val); + dfs2(root, node->right, res); + } + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1340-Jump-Game-V/cpp-1340/CMakeLists.txt b/1001-1500/1340-Jump-Game-V/cpp-1340/CMakeLists.txt new file mode 100644 index 00000000..c0c37cc3 --- /dev/null +++ b/1001-1500/1340-Jump-Game-V/cpp-1340/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main2.cpp) \ No newline at end of file diff --git a/1001-1500/1340-Jump-Game-V/cpp-1340/main.cpp b/1001-1500/1340-Jump-Game-V/cpp-1340/main.cpp new file mode 100644 index 00000000..1fc25c93 --- /dev/null +++ b/1001-1500/1340-Jump-Game-V/cpp-1340/main.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/jump-game-v/ +/// Author : liuyubobobo +/// Time : 2019-02-01 + +#include +#include + +using namespace std; + + +/// Memorized Search +/// Time Complexity: O(n * d) +/// Space Complexity: O(n) +class Solution { +public: + int maxJumps(vector& arr, int d) { + + vector dp(arr.size(), -1); + for(int i = 0; i < arr.size(); i ++) + dfs(arr, d, i, dp); +// for(int e: dp) cout << e << " "; cout << endl; + return *max_element(dp.begin(), dp.end()); + } + +private: + int dfs(const vector& arr, int d, int pos, vector& dp){ + + if(dp[pos] != -1) return dp[pos]; + + int res = 1; + for(int i = pos - 1; i >= 0 && i >= pos - d; i --) + if(arr[i] < arr[pos]) + res = max(res, 1 + dfs(arr, d, i, dp)); + else break; + + for(int i = pos + 1; i < arr.size() && i <= pos + d; i ++) + if(arr[i] < arr[pos]) + res = max(res, 1 + dfs(arr, d, i, dp)); + else break; + + return dp[pos] = res; + } +}; + + +int main() { + + vector arr1 = {6,4,14,6,8,13,9,7,10,6,12}; + cout << Solution().maxJumps(arr1, 2) << endl; + // 4 + + return 0; +} diff --git a/1001-1500/1340-Jump-Game-V/cpp-1340/main2.cpp b/1001-1500/1340-Jump-Game-V/cpp-1340/main2.cpp new file mode 100644 index 00000000..11ec7ef8 --- /dev/null +++ b/1001-1500/1340-Jump-Game-V/cpp-1340/main2.cpp @@ -0,0 +1,60 @@ +/// Source : https://leetcode.com/problems/jump-game-v/ +/// Author : liuyubobobo +/// Time : 2019-02-10 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(nlogn + n * d) +/// Space Complexity: O(n) +class Solution { +public: + int maxJumps(vector& arr, int d) { + + vector order; + for(int i = 0; i < arr.size(); i ++) order.push_back(i); + sort(order.begin(), order.end(), [arr](int a, int b){ + return arr[a] < arr[b]; + }); +// for(int e: order) cout << e << " "; cout << endl; + + vector dp(arr.size(), 1); + for(int pos: order){ + + int maxv = arr[pos], maxi = pos; + for(int i = pos - 1; i >= 0 && i >= pos - d; i --){ + if(arr[i] > maxv) + dp[i] = max(dp[i], 1 + dp[maxi]), maxv = arr[i], maxi = i; + } + + maxv = arr[pos], maxi = pos; + for(int i = pos + 1; i < arr.size() && i <= pos + d; i ++) { + if (arr[i] > maxv) + dp[i] = max(dp[i], 1 + dp[maxi]), maxv = arr[i], maxi = i; + } + +// cout << pos << " : "; +// for(int e: dp) cout << e << " "; cout << endl; + } + + return *max_element(dp.begin(), dp.end()); + } +}; + + +int main() { + + vector arr1 = {6,4,14,6,8,13,9,7,10,6,12}; + cout << Solution().maxJumps(arr1, 2) << endl; + // 4 + + vector arr2 = {22,29,52,97,29,75,78,2,92,70,90,12,43,17,97,18,58,100,41,32}; + cout << Solution().maxJumps(arr2, 17) << endl; + // 6 + + return 0; +} diff --git a/1001-1500/1342-Number-of-Steps-to-Reduce-a-Number-to-Zero/cpp-1342/CMakeLists.txt b/1001-1500/1342-Number-of-Steps-to-Reduce-a-Number-to-Zero/cpp-1342/CMakeLists.txt new file mode 100644 index 00000000..5a256f1c --- /dev/null +++ b/1001-1500/1342-Number-of-Steps-to-Reduce-a-Number-to-Zero/cpp-1342/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(cpp_1342) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1342 main.cpp) \ No newline at end of file diff --git a/1001-1500/1342-Number-of-Steps-to-Reduce-a-Number-to-Zero/cpp-1342/main.cpp b/1001-1500/1342-Number-of-Steps-to-Reduce-a-Number-to-Zero/cpp-1342/main.cpp new file mode 100644 index 00000000..e03d9a69 --- /dev/null +++ b/1001-1500/1342-Number-of-Steps-to-Reduce-a-Number-to-Zero/cpp-1342/main.cpp @@ -0,0 +1,31 @@ +/// Source : https://leetcode.com/problems/number-of-steps-to-reduce-a-number-to-zero/ +/// Author : liuyubobobo +/// Time : 2020-02-18 + +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(logn) +/// Space Complexity: O(1) +class Solution { +public: + int numberOfSteps (int num) { + + int res = 0; + while(num){ + if(num % 2) num --; + else num /= 2; + res ++; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1343-Number-of-Sub-arrays-of-Size-K-and-Average-Greater-than-or-Equal-to-Threshold/cpp-1343/CMakeLists.txt b/1001-1500/1343-Number-of-Sub-arrays-of-Size-K-and-Average-Greater-than-or-Equal-to-Threshold/cpp-1343/CMakeLists.txt new file mode 100644 index 00000000..cba3245c --- /dev/null +++ b/1001-1500/1343-Number-of-Sub-arrays-of-Size-K-and-Average-Greater-than-or-Equal-to-Threshold/cpp-1343/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(cpp_1343) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1343 main.cpp) \ No newline at end of file diff --git a/1001-1500/1343-Number-of-Sub-arrays-of-Size-K-and-Average-Greater-than-or-Equal-to-Threshold/cpp-1343/main.cpp b/1001-1500/1343-Number-of-Sub-arrays-of-Size-K-and-Average-Greater-than-or-Equal-to-Threshold/cpp-1343/main.cpp new file mode 100644 index 00000000..3136cb85 --- /dev/null +++ b/1001-1500/1343-Number-of-Sub-arrays-of-Size-K-and-Average-Greater-than-or-Equal-to-Threshold/cpp-1343/main.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/ +/// Author : liuyubobobo +/// Time : 2020-02-19 + +#include +#include +#include + +using namespace std; + + +/// Sliding Window +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int numOfSubarrays(vector& arr, int k, int threshold) { + + int sum = accumulate(arr.begin(), arr.begin() + (k - 1), 0), res = 0; + for(int i = k - 1; i < arr.size(); i ++){ + sum += arr[i]; + if(sum >= k * threshold) res ++; + sum -= arr[i - (k - 1)]; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1344-Angle-Between-Hands-of-a-Clock/cpp-1344/CMakeLists.txt b/1001-1500/1344-Angle-Between-Hands-of-a-Clock/cpp-1344/CMakeLists.txt new file mode 100644 index 00000000..e2f7601a --- /dev/null +++ b/1001-1500/1344-Angle-Between-Hands-of-a-Clock/cpp-1344/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(cpp_1344) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1344 main.cpp) \ No newline at end of file diff --git a/1001-1500/1344-Angle-Between-Hands-of-a-Clock/cpp-1344/main.cpp b/1001-1500/1344-Angle-Between-Hands-of-a-Clock/cpp-1344/main.cpp new file mode 100644 index 00000000..f90d9ee9 --- /dev/null +++ b/1001-1500/1344-Angle-Between-Hands-of-a-Clock/cpp-1344/main.cpp @@ -0,0 +1,30 @@ +/// Source : https://leetcode.com/problems/angle-between-hands-of-a-clock/ +/// Author : liuyubobobo +/// Time : 2020-02-19 + +#include + +using namespace std; + + +/// Mathematics +/// Time Complexity: O(1) +/// Space Complexity: O(1) +class Solution { +public: + double angleClock(int hour, int minutes) { + + hour %= 12; + double a = (hour + minutes / 60.0) * 30; + double b = minutes * 6.0; + double res = a - b; + if(res < 0) res += 360.0; + return res <= 180.0 ? res : 360.0 - res; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1345-Jump-Game-IV/cpp-1345/CMakeLists.txt b/1001-1500/1345-Jump-Game-IV/cpp-1345/CMakeLists.txt new file mode 100644 index 00000000..bce311e6 --- /dev/null +++ b/1001-1500/1345-Jump-Game-IV/cpp-1345/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(cpp_1345) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1345 main.cpp) \ No newline at end of file diff --git a/1001-1500/1345-Jump-Game-IV/cpp-1345/main.cpp b/1001-1500/1345-Jump-Game-IV/cpp-1345/main.cpp new file mode 100644 index 00000000..55e4e1c2 --- /dev/null +++ b/1001-1500/1345-Jump-Game-IV/cpp-1345/main.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/jump-game-iv/ +/// Author : liuyubobobo +/// Time : 2017-05-05 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// BFS +/// Time Complexity: O(n + m) +/// Space Complexity: O(n) +class Solution { +public: + int minJumps(vector& arr) { + + if(arr.size() == 1) return 0; + + map> pos; + for(int i = 0; i < arr.size(); i ++) + pos[arr[i]].push_back(i); + + vector step(arr.size(), -1); + queue q; + q.push(0); + step[0] = 0; + while(!q.empty()){ + int cur = q.front(); + q.pop(); + if(cur == arr.size() - 1) return step[cur]; + + if(cur - 1 >= 0 && step[cur - 1] == -1) + q.push(cur - 1), step[cur - 1] = step[cur] + 1; + if(cur + 1 < arr.size() && step[cur + 1] == -1) + q.push(cur + 1), step[cur + 1] = step[cur] + 1; + for(int p: pos[arr[cur]]) + if((p < cur - 1 || p > cur + 1) && step[p] == -1) + q.push(p), step[p] = step[cur] + 1; + pos.erase(arr[cur]); + } + return -1; + } +}; + + +int main() { + + vector arr1 = {100,-23,-23,404,100,23,23,23,3,404}; + cout << Solution().minJumps(arr1) << endl; + // 3 + + return 0; +} diff --git a/1001-1500/1346-Check-If-N-and-Its-Double-Exist/cpp-1346/CMakeLists.txt b/1001-1500/1346-Check-If-N-and-Its-Double-Exist/cpp-1346/CMakeLists.txt new file mode 100644 index 00000000..36e6e925 --- /dev/null +++ b/1001-1500/1346-Check-If-N-and-Its-Double-Exist/cpp-1346/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(cpp_1346) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1346 main2.cpp) \ No newline at end of file diff --git a/1001-1500/1346-Check-If-N-and-Its-Double-Exist/cpp-1346/main.cpp b/1001-1500/1346-Check-If-N-and-Its-Double-Exist/cpp-1346/main.cpp new file mode 100644 index 00000000..ec0e6d26 --- /dev/null +++ b/1001-1500/1346-Check-If-N-and-Its-Double-Exist/cpp-1346/main.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/simplify-path/ +/// Author : liuyubobobo +/// Time : 2019-02-10 + +#include +#include +#include + +using namespace std; + + +/// Using map +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + bool checkIfExist(vector& arr) { + + map map; + for(int e: arr) map[e] ++; + + for(const pair& p: map) + if(!p.first){ + if(p.second >= 2) return true; + } + else if(map.count(p.first * 2)) return true; + return false; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1346-Check-If-N-and-Its-Double-Exist/cpp-1346/main2.cpp b/1001-1500/1346-Check-If-N-and-Its-Double-Exist/cpp-1346/main2.cpp new file mode 100644 index 00000000..29af8a85 --- /dev/null +++ b/1001-1500/1346-Check-If-N-and-Its-Double-Exist/cpp-1346/main2.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/simplify-path/ +/// Author : liuyubobobo +/// Time : 2019-02-10 + +#include +#include +#include + +using namespace std; + + +/// Using set +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + bool checkIfExist(vector& arr) { + + set set; + for(int e: arr) { + if (e % 2 == 0 && set.count(e / 2)) return true; + else if (set.count(e * 2)) return true; + set.insert(e); + } + return false; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1347-Minimum-Number-of-Steps-to-Make-Two-Strings-Anagram/cpp-1347/CMakeLists.txt b/1001-1500/1347-Minimum-Number-of-Steps-to-Make-Two-Strings-Anagram/cpp-1347/CMakeLists.txt new file mode 100644 index 00000000..eea91262 --- /dev/null +++ b/1001-1500/1347-Minimum-Number-of-Steps-to-Make-Two-Strings-Anagram/cpp-1347/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(cpp_1347) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1347 main.cpp) \ No newline at end of file diff --git a/1001-1500/1347-Minimum-Number-of-Steps-to-Make-Two-Strings-Anagram/cpp-1347/main.cpp b/1001-1500/1347-Minimum-Number-of-Steps-to-Make-Two-Strings-Anagram/cpp-1347/main.cpp new file mode 100644 index 00000000..97fca841 --- /dev/null +++ b/1001-1500/1347-Minimum-Number-of-Steps-to-Make-Two-Strings-Anagram/cpp-1347/main.cpp @@ -0,0 +1,32 @@ +/// Source : https://leetcode.com/problems/minimum-number-of-steps-to-make-two-strings-anagram/ +/// Author : liuyubobobo +/// Time : 2019-02-10 + +#include +#include + +using namespace std; + + +/// Using HashMap +/// Time Complexity: O(|s| + |t|) +/// Space Complexity: O(1) +class Solution { +public: + int minSteps(string s, string t) { + + vector v(26, 0); + for(char c: s) v[c - 'a'] ++; + for(char c: t) v[c - 'a'] --; + + int res = 0; + for(int e: v) res += abs(e); + return res / 2; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1348-Tweet-Counts-Per-Frequency/cpp-1348/CMakeLists.txt b/1001-1500/1348-Tweet-Counts-Per-Frequency/cpp-1348/CMakeLists.txt new file mode 100644 index 00000000..864deaeb --- /dev/null +++ b/1001-1500/1348-Tweet-Counts-Per-Frequency/cpp-1348/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(cpp_1348) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1348 main.cpp) \ No newline at end of file diff --git a/1001-1500/1348-Tweet-Counts-Per-Frequency/cpp-1348/main.cpp b/1001-1500/1348-Tweet-Counts-Per-Frequency/cpp-1348/main.cpp new file mode 100644 index 00000000..2be2e1ba --- /dev/null +++ b/1001-1500/1348-Tweet-Counts-Per-Frequency/cpp-1348/main.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/tweet-counts-per-frequency/ +/// Author : liuyubobobo +/// Time : 2019-02-10 + +#include +#include +#include + +using namespace std; + + +/// Using TreeMap +/// Time Complexity: init: O(1) +/// recordTweet: O(1) +/// getTweetCountsPerFrequency: O(logn + n) +/// Space Complexity: O(n) +class TweetCounts { + +private: + map> record; + +public: + TweetCounts() {} + + void recordTweet(string tweetName, int time) { + record[tweetName][time] ++; + } + + vector getTweetCountsPerFrequency(string freq, string tweetName, int startTime, int endTime) { + + int interval = freq == "minute" ? 60 : (freq == "hour" ? 60 * 60 : 24 * 60 * 60); + map::iterator iter = record[tweetName].lower_bound(startTime); + + vector res((endTime - startTime + 1)/ interval + !!((endTime - startTime + 1) % interval)); + while(iter != record[tweetName].end() && iter->first <= endTime){ + res[(iter->first - startTime) / interval] += iter->second; + iter ++; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1349-Maximum-Students-Taking-Exam/cpp-1349/CMakeLists.txt b/1001-1500/1349-Maximum-Students-Taking-Exam/cpp-1349/CMakeLists.txt new file mode 100644 index 00000000..08536e0c --- /dev/null +++ b/1001-1500/1349-Maximum-Students-Taking-Exam/cpp-1349/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(cpp_1349) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1349 main.cpp) \ No newline at end of file diff --git a/1001-1500/1349-Maximum-Students-Taking-Exam/cpp-1349/main.cpp b/1001-1500/1349-Maximum-Students-Taking-Exam/cpp-1349/main.cpp new file mode 100644 index 00000000..ec1d6f58 --- /dev/null +++ b/1001-1500/1349-Maximum-Students-Taking-Exam/cpp-1349/main.cpp @@ -0,0 +1,91 @@ +/// Source : https://leetcode.com/problems/maximum-students-taking-exam/ +/// Author : liuyubobobo +/// Time : 2020-02-11 + +#include +#include +#include + +using namespace std; + + +/// Memory Search + State Compression +/// Time Complexity: O(m * 2 ^ n) +/// Space Complexity: O(m * 2 ^ n) +class Solution { + +private: + int m, n; + +public: + int maxStudents(vector>& seats) { + + m = seats.size(), n = seats[0].size(); + vector> dp(m, vector(1 << n, -1)); + return dfs(seats, 0, -1, dp); + } + +private: + int dfs(const vector>& seats, int row, int last, + vector>& dp){ + + if(row == m) return 0; + + if(last != -1 && dp[row][last] != -1) return dp[row][last]; + + int res = 0; + for(int cur = 0; cur < (1 << n); cur ++) + if(ok(seats[row], cur, last)){ + int x = get_bits(cur); + res = max(res, x + dfs(seats, row + 1, cur, dp)); + } + // cout << row << " " << last << " " << res << endl; + if(last == -1) return res; + return dp[row][last] = res; + } + + bool ok(const vector& seats, int cur, int last){ + + vector vcur; + for(int i = 0; i < n; i ++) vcur.push_back(cur % 2), cur /= 2; + assert(vcur.size() == n); + + for(int i = 0; i < n; i ++) + if(seats[i] == '#' && vcur[i]) return false; + + for(int i = 1; i < n; i ++) + if(vcur[i - 1] && vcur[i]) return false; + + if(last != -1){ + vector vlast; + for(int i = 0; i < n; i ++) vlast.push_back(last % 2), last /= 2; + assert(vlast.size() == n); + + for(int i = 0; i < n; i ++) + if(vcur[i]){ + if(i - 1 >= 0 && vlast[i - 1]) return false; + if(i + 1 < n && vlast[i + 1]) return false; + } + } + return true; + } + + int get_bits(int x){ + int res = 0; + while(x) res += x % 2, x /= 2; + return res; + } +}; + + +int main() { + + vector> seats1 = { + {'#','.','#','#','.','#'}, + {'.','#','#','#','#','.'}, + {'#','.','#','#','.','#'} + }; + cout << Solution().maxStudents(seats1) << endl; + + return 0; +} diff --git a/1001-1500/1351-Count-Negative-Numbers-in-a-Sorted-Matrix/cpp-1351/CMakeLists.txt b/1001-1500/1351-Count-Negative-Numbers-in-a-Sorted-Matrix/cpp-1351/CMakeLists.txt new file mode 100644 index 00000000..d98c23f5 --- /dev/null +++ b/1001-1500/1351-Count-Negative-Numbers-in-a-Sorted-Matrix/cpp-1351/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main3.cpp) \ No newline at end of file diff --git a/1001-1500/1351-Count-Negative-Numbers-in-a-Sorted-Matrix/cpp-1351/main.cpp b/1001-1500/1351-Count-Negative-Numbers-in-a-Sorted-Matrix/cpp-1351/main.cpp new file mode 100644 index 00000000..1129e979 --- /dev/null +++ b/1001-1500/1351-Count-Negative-Numbers-in-a-Sorted-Matrix/cpp-1351/main.cpp @@ -0,0 +1,29 @@ +/// Source : https://leetcode.com/problems/count-negative-numbers-in-a-sorted-matrix/ +/// Author : liuyubobobo +/// Time : 2019-02-15 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(m * n) +/// Space Complexity: O(1) +class Solution { +public: + int countNegatives(vector>& grid) { + + int res = 0; + for(int i = 0; i < grid.size(); i ++) + for(int e: grid[i]) res += (e < 0); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1351-Count-Negative-Numbers-in-a-Sorted-Matrix/cpp-1351/main2.cpp b/1001-1500/1351-Count-Negative-Numbers-in-a-Sorted-Matrix/cpp-1351/main2.cpp new file mode 100644 index 00000000..de8d0bc9 --- /dev/null +++ b/1001-1500/1351-Count-Negative-Numbers-in-a-Sorted-Matrix/cpp-1351/main2.cpp @@ -0,0 +1,29 @@ +/// Source : https://leetcode.com/problems/count-negative-numbers-in-a-sorted-matrix/ +/// Author : liuyubobobo +/// Time : 2019-02-16 + +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(m * logn) +/// Space Complexity: O(1) +class Solution { +public: + int countNegatives(vector>& grid) { + + int res = 0; + for(int i = 0; i < grid.size(); i ++) + res += upper_bound(grid[i].rbegin(), grid[i].rend(), -1) - grid[i].rbegin(); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1351-Count-Negative-Numbers-in-a-Sorted-Matrix/cpp-1351/main3.cpp b/1001-1500/1351-Count-Negative-Numbers-in-a-Sorted-Matrix/cpp-1351/main3.cpp new file mode 100644 index 00000000..23d06396 --- /dev/null +++ b/1001-1500/1351-Count-Negative-Numbers-in-a-Sorted-Matrix/cpp-1351/main3.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/count-negative-numbers-in-a-sorted-matrix/ +/// Author : liuyubobobo +/// Time : 2019-02-16 + +#include +#include + +using namespace std; + + +/// Search Break Points +/// Time Complexity: O(m * n) +/// Space Complexity: O(1) +class Solution { +public: + int countNegatives(vector>& grid) { + + int res = 0, m = grid.size(), n = grid[0].size(); + int c = n - 1; + for(int r = 0; r < m; r ++){ + while(c >= 0 && grid[r][c] < 0) c --; + res += (n - c - 1); + } + return res; + } +}; + + +int main() { + + vector> g1 = {{5, 1, 0}, {-5, -5, -5}}; + cout << Solution().countNegatives(g1) << endl; + + return 0; +} diff --git a/1001-1500/1352-Product-of-the-Last-K-Numbers/cpp-1352/CMakeLists.txt b/1001-1500/1352-Product-of-the-Last-K-Numbers/cpp-1352/CMakeLists.txt new file mode 100644 index 00000000..c3e75f47 --- /dev/null +++ b/1001-1500/1352-Product-of-the-Last-K-Numbers/cpp-1352/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main2.cpp) \ No newline at end of file diff --git a/1001-1500/1352-Product-of-the-Last-K-Numbers/cpp-1352/main.cpp b/1001-1500/1352-Product-of-the-Last-K-Numbers/cpp-1352/main.cpp new file mode 100644 index 00000000..e5f2faf6 --- /dev/null +++ b/1001-1500/1352-Product-of-the-Last-K-Numbers/cpp-1352/main.cpp @@ -0,0 +1,45 @@ +/// Source : https://leetcode.com/problems/product-of-the-last-k-numbers/ +/// Author : liuyubobobo +/// Time : 2019-02-15 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: add: O(1) +/// getProduct: O(k) +/// Space Complexity: O(1) +class ProductOfNumbers { + +private: + vector v; + +public: + ProductOfNumbers() {} + + void add(int num) { + + v.push_back(num); + } + + int getProduct(int k) { + + int res = 1; + for(int i = v.size() - 1; i >= (int)v.size() - k; i --) + res *= v[i]; + return res; + } +}; + + +int main() { + + ProductOfNumbers p; + p.add(1); + cout << p.getProduct(1) << endl; + + return 0; +} diff --git a/1001-1500/1352-Product-of-the-Last-K-Numbers/cpp-1352/main2.cpp b/1001-1500/1352-Product-of-the-Last-K-Numbers/cpp-1352/main2.cpp new file mode 100644 index 00000000..bbe4e22e --- /dev/null +++ b/1001-1500/1352-Product-of-the-Last-K-Numbers/cpp-1352/main2.cpp @@ -0,0 +1,42 @@ +/// Source : https://leetcode.com/problems/product-of-the-last-k-numbers/ +/// Author : liuyubobobo +/// Time : 2019-02-17 + +#include +#include + +using namespace std; + + +/// Prefix Product +/// Time Complexity: add: O(1) +/// getProduct: O(1) +/// Space Complexity: O(n) +class ProductOfNumbers { + +private: + vector pre; + +public: + ProductOfNumbers() {} + + void add(int num) { + + if(!num) pre = {1}; + else pre.push_back(pre.back() * num); + } + + int getProduct(int k) { + return k + 1 <= pre.size() ? pre.back() / pre[pre.size() - k - 1] : 0; + } +}; + + +int main() { + + ProductOfNumbers p; + p.add(1); + cout << p.getProduct(1) << endl; + + return 0; +} diff --git a/1001-1500/1353-Maximum-Number-of-Events-That-Can-Be-Attended/cpp-1353/CMakeLists.txt b/1001-1500/1353-Maximum-Number-of-Events-That-Can-Be-Attended/cpp-1353/CMakeLists.txt new file mode 100644 index 00000000..2ce40a6e --- /dev/null +++ b/1001-1500/1353-Maximum-Number-of-Events-That-Can-Be-Attended/cpp-1353/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main3.cpp) \ No newline at end of file diff --git a/1001-1500/1353-Maximum-Number-of-Events-That-Can-Be-Attended/cpp-1353/main.cpp b/1001-1500/1353-Maximum-Number-of-Events-That-Can-Be-Attended/cpp-1353/main.cpp new file mode 100644 index 00000000..caad3e0e --- /dev/null +++ b/1001-1500/1353-Maximum-Number-of-Events-That-Can-Be-Attended/cpp-1353/main.cpp @@ -0,0 +1,74 @@ +/// Source : https://leetcode.com/problems/maximum-number-of-events-that-can-be-attended/ +/// Author : liuyubobobo +/// Time : 2019-02-15 + +#include +#include +#include + +using namespace std; + + +/// Using map to simulate priority queue +/// Time Complexity: O(t * logn) +/// Space Complexity: O(n) +class Solution { +public: + int maxEvents(vector>& events) { + + map, int> q; + for(const vector& e: events) + q[make_pair(e[0], e[1])] ++; + + int res = 0; + for(int i = 0; i <= 100000 && !q.empty(); i ++){ + + map, int>::iterator iter = q.begin(); + if(i >= iter->first.first && i <= iter->first.second){ + res ++; + iter->second --; + if(iter->second == 0) q.erase(iter); + + vector> v; + for(map, int>::iterator iter = q.begin(); iter != q.end(); iter ++) + if(iter->first.first <= i) + v.push_back(iter->first); + else + break; + + for(const pair& p: v){ + int num = q[p]; + q.erase(p); + if(i + 1 <= p.second){ + pair newp = make_pair(i + 1, p.second); + if(q.count(newp)) q[newp] += num; + else q[newp] = num; + } + } + } + } + return res; + } +}; + + +int main() { + + vector> events1 = {{1, 2}, {2, 3}, {3, 4}, {1, 2}}; + cout << Solution().maxEvents(events1) << endl; + // 4 + + vector> events2 = {{1, 4}, {4, 4}, {2, 2}, {3, 4}, {1, 1}}; + cout << Solution().maxEvents(events2) << endl; + // 4 + + vector> events3 = {{1, 5}, {1, 5}, {1, 5}, {2, 3}, {2, 3}}; + cout << Solution().maxEvents(events3) << endl; + // 5 + + vector> events4 = {{7, 11}, {7, 11}, {7, 11}, {9, 10}, {9, 11}}; + cout << Solution().maxEvents(events4) << endl; + // 5 + + return 0; +} diff --git a/1001-1500/1353-Maximum-Number-of-Events-That-Can-Be-Attended/cpp-1353/main2.cpp b/1001-1500/1353-Maximum-Number-of-Events-That-Can-Be-Attended/cpp-1353/main2.cpp new file mode 100644 index 00000000..a946f38b --- /dev/null +++ b/1001-1500/1353-Maximum-Number-of-Events-That-Can-Be-Attended/cpp-1353/main2.cpp @@ -0,0 +1,65 @@ +/// Source : https://leetcode.com/problems/maximum-number-of-events-that-can-be-attended/ +/// Author : liuyubobobo +/// Time : 2019-02-17 + +#include +#include +#include + +using namespace std; + + +/// Using priority queue +/// Time Complexity: O(t * logn) +/// Space Complexity: O(n) +class Solution { +public: + int maxEvents(vector>& events) { + + priority_queue, vector>, greater>> pq; + for(const vector& e: events) + pq.push(make_pair(e[0], e[1])); + + int res = 0; + for(int i = 0; i <= 100000 && !pq.empty(); i ++){ + + pair e = pq.top(); + if(i >= e.first && i <= e.second){ + res ++; + pq.pop(); + + while(!pq.empty() && pq.top().first <= i){ + pair t = pq.top(); + pq.pop(); + if(i + 1 <= t.second){ + t.first = i + 1; + pq.push(t); + } + } + } + } + return res; + } +}; + + +int main() { + + vector> events1 = {{1, 2}, {2, 3}, {3, 4}, {1, 2}}; + cout << Solution().maxEvents(events1) << endl; + // 4 + + vector> events2 = {{1, 4}, {4, 4}, {2, 2}, {3, 4}, {1, 1}}; + cout << Solution().maxEvents(events2) << endl; + // 4 + + vector> events3 = {{1, 5}, {1, 5}, {1, 5}, {2, 3}, {2, 3}}; + cout << Solution().maxEvents(events3) << endl; + // 5 + + vector> events4 = {{7, 11}, {7, 11}, {7, 11}, {9, 10}, {9, 11}}; + cout << Solution().maxEvents(events4) << endl; + // 5 + + return 0; +} diff --git a/1001-1500/1353-Maximum-Number-of-Events-That-Can-Be-Attended/cpp-1353/main3.cpp b/1001-1500/1353-Maximum-Number-of-Events-That-Can-Be-Attended/cpp-1353/main3.cpp new file mode 100644 index 00000000..1713740a --- /dev/null +++ b/1001-1500/1353-Maximum-Number-of-Events-That-Can-Be-Attended/cpp-1353/main3.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/maximum-number-of-events-that-can-be-attended/ +/// Author : liuyubobobo +/// Time : 2019-02-17 + +#include +#include +#include + +using namespace std; + + +/// Using priority queue to only record the end date +/// Time Complexity: O(t * logn) +/// Space Complexity: O(n) +class Solution { +public: + int maxEvents(vector>& events) { + + sort(events.begin(), events.end()); + + priority_queue, greater> pq; + + int res = 0, e = 0; + for(int i = 0; i <= 100000; i ++){ + while(e < events.size() && events[e][0] == i) pq.push(events[e ++][1]); + while(!pq.empty() && pq.top() < i) pq.pop(); + if(!pq.empty()) res ++, pq.pop(); + } + return res; + } +}; + + +int main() { + + vector> events1 = {{1, 2}, {2, 3}, {3, 4}, {1, 2}}; + cout << Solution().maxEvents(events1) << endl; + // 4 + + vector> events2 = {{1, 4}, {4, 4}, {2, 2}, {3, 4}, {1, 1}}; + cout << Solution().maxEvents(events2) << endl; + // 4 + + vector> events3 = {{1, 5}, {1, 5}, {1, 5}, {2, 3}, {2, 3}}; + cout << Solution().maxEvents(events3) << endl; + // 5 + + vector> events4 = {{7, 11}, {7, 11}, {7, 11}, {9, 10}, {9, 11}}; + cout << Solution().maxEvents(events4) << endl; + // 5 + + return 0; +} diff --git a/1001-1500/1354-Construct-Target-Array-With-Multiple-Sums/cpp-1354/CMakeLists.txt b/1001-1500/1354-Construct-Target-Array-With-Multiple-Sums/cpp-1354/CMakeLists.txt new file mode 100644 index 00000000..c0c37cc3 --- /dev/null +++ b/1001-1500/1354-Construct-Target-Array-With-Multiple-Sums/cpp-1354/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main2.cpp) \ No newline at end of file diff --git a/1001-1500/1354-Construct-Target-Array-With-Multiple-Sums/cpp-1354/main.cpp b/1001-1500/1354-Construct-Target-Array-With-Multiple-Sums/cpp-1354/main.cpp new file mode 100644 index 00000000..b4a34df8 --- /dev/null +++ b/1001-1500/1354-Construct-Target-Array-With-Multiple-Sums/cpp-1354/main.cpp @@ -0,0 +1,61 @@ +/// Source : https://leetcode.com/problems/construct-target-array-with-multiple-sums/ +/// Author : liuyubobobo +/// Time : 2019-02-15 + +#include +#include +#include +#include + +using namespace std; + + +/// Using map to simulate priority queue +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + bool isPossible(vector& target) { + + map q; + for(int e: target) q[-e]++; + + long long sum = accumulate(target.begin(), target.end(), 0ll); + while(q.begin()->first != -1ll){ + long long k = q.begin()->first; + long long v = -k; + + long long leftsum = sum - v; + if(v <= leftsum) return false; + else{ + q[k] --; + if(q[k] == 0ll) q.erase(k); + q[- v % leftsum] ++; + sum -= v - v % leftsum; + } + } + return true; + } +}; + + +int main() { + + vector v1 = {9, 3, 5}; + cout << Solution().isPossible(v1) << endl; + // 1 + + vector v2 = {1, 1, 1, 2}; + cout << Solution().isPossible(v2) << endl; + // 0 + + vector v3 = {8, 5}; + cout << Solution().isPossible(v3) << endl; + // 1 + + vector v4 = {1, 1000}; + cout << Solution().isPossible(v4) << endl; + // 1 + + return 0; +} diff --git a/1001-1500/1354-Construct-Target-Array-With-Multiple-Sums/cpp-1354/main2.cpp b/1001-1500/1354-Construct-Target-Array-With-Multiple-Sums/cpp-1354/main2.cpp new file mode 100644 index 00000000..c4ff017c --- /dev/null +++ b/1001-1500/1354-Construct-Target-Array-With-Multiple-Sums/cpp-1354/main2.cpp @@ -0,0 +1,62 @@ +/// Source : https://leetcode.com/problems/construct-target-array-with-multiple-sums/ +/// Author : liuyubobobo +/// Time : 2019-02-17 + +#include +#include +#include +#include + +using namespace std; + + +/// Using priority queue +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + bool isPossible(vector& target) { + + if(target.size() == 2 && (target[0] == 1 || target[1] == 1)) return true; + + priority_queue pq; + for(int e: target) pq.push(e); + + long long sum = accumulate(target.begin(), target.end(), 0ll); + while(!pq.empty() && pq.top() != 1ll){ + long long v = pq.top(); + + long long leftsum = sum - v; + if(v <= leftsum || leftsum == 0) return false; + else{ + pq.pop(); + + pq.push(v % leftsum); + sum -= v - v % leftsum; + } + } + return true; + } +}; + + +int main() { + + vector v1 = {9, 3, 5}; + cout << Solution().isPossible(v1) << endl; + // 1 + + vector v2 = {1, 1, 1, 2}; + cout << Solution().isPossible(v2) << endl; + // 0 + + vector v3 = {8, 5}; + cout << Solution().isPossible(v3) << endl; + // 1 + + vector v4 = {1, 1000}; + cout << Solution().isPossible(v4) << endl; + // 1 + + return 0; +} diff --git a/1001-1500/1356-Sort-Integers-by-The-Number-of-1-Bits/cpp-1356/CMakeLists.txt b/1001-1500/1356-Sort-Integers-by-The-Number-of-1-Bits/cpp-1356/CMakeLists.txt new file mode 100644 index 00000000..3be3558a --- /dev/null +++ b/1001-1500/1356-Sort-Integers-by-The-Number-of-1-Bits/cpp-1356/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(cpp_1356) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1356 main.cpp) \ No newline at end of file diff --git a/1001-1500/1356-Sort-Integers-by-The-Number-of-1-Bits/cpp-1356/main.cpp b/1001-1500/1356-Sort-Integers-by-The-Number-of-1-Bits/cpp-1356/main.cpp new file mode 100644 index 00000000..b6b1e3f3 --- /dev/null +++ b/1001-1500/1356-Sort-Integers-by-The-Number-of-1-Bits/cpp-1356/main.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/ +/// Author : liuyubobobo +/// Time : 2020-02-22 + +#include +#include + +using namespace std; + + +/// Sorting +/// Time Complexity: O(nlognlog(num)) +/// Space Complexity: O(1) +class Solution { +public: + vector sortByBits(vector& arr) { + + sort(arr.begin(), arr.end(), [](int a, int b){ + + int abits = bits_num(a), bbits = bits_num(b); + if(abits != bbits) return abits < bbits; + return a < b; + }); + return arr; + } + +private: + static int bits_num(int x){ + + int res = 0; + while(x) res += x % 2, x /= 2; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1357-Apply-Discount-Every-n-Orders/cpp-1357/CMakeLists.txt b/1001-1500/1357-Apply-Discount-Every-n-Orders/cpp-1357/CMakeLists.txt new file mode 100644 index 00000000..bef79c46 --- /dev/null +++ b/1001-1500/1357-Apply-Discount-Every-n-Orders/cpp-1357/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(cpp_1357) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1357 main.cpp) \ No newline at end of file diff --git a/1001-1500/1357-Apply-Discount-Every-n-Orders/cpp-1357/main.cpp b/1001-1500/1357-Apply-Discount-Every-n-Orders/cpp-1357/main.cpp new file mode 100644 index 00000000..d3bb7587 --- /dev/null +++ b/1001-1500/1357-Apply-Discount-Every-n-Orders/cpp-1357/main.cpp @@ -0,0 +1,48 @@ +/// Source : https://leetcode.com/problems/apply-discount-every-n-orders/ +/// Author : liuyubobobo +/// Time : 2020-02-22 + +#include +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: init: O(n) +/// getBill: O(m) +/// Space Complexity: O(n) +class Cashier { + +private: + int n, discount; + map price; + int index = 1; + +public: + Cashier(int n, int discount, vector& products, vector& prices) : n(n), discount(discount) { + for(int i = 0; i < products.size(); i ++) + price[products[i]] = prices[i]; + } + + double getBill(vector product, vector amount) { + + double res = 0.0; + for(int i = 0; i < product.size(); i ++) + res += price[product[i]] * amount[i]; + + if(index % n == 0) + res -= discount * res / 100; + + index ++; + + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1358-Number-of-Substrings-Containing-All-Three-Characters/cpp-1358/CMakeLists.txt b/1001-1500/1358-Number-of-Substrings-Containing-All-Three-Characters/cpp-1358/CMakeLists.txt new file mode 100644 index 00000000..a36b5356 --- /dev/null +++ b/1001-1500/1358-Number-of-Substrings-Containing-All-Three-Characters/cpp-1358/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(cpp_1358) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1358 main.cpp) \ No newline at end of file diff --git a/1001-1500/1358-Number-of-Substrings-Containing-All-Three-Characters/cpp-1358/main.cpp b/1001-1500/1358-Number-of-Substrings-Containing-All-Three-Characters/cpp-1358/main.cpp new file mode 100644 index 00000000..c9a95a5c --- /dev/null +++ b/1001-1500/1358-Number-of-Substrings-Containing-All-Three-Characters/cpp-1358/main.cpp @@ -0,0 +1,39 @@ +/// Source : https://leetcode.com/problems/number-of-substrings-containing-all-three-characters/ +/// Author : liuyubobobo +/// Time : 2020-02-23 + +#include +#include + +using namespace std; + + +/// Sliding Window +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int numberOfSubstrings(string s) { + + int n = s.size(); + + vector freq(3, 0); + int l = 0, r = -1, res = 0; + while(l < n && r + 1 < n){ + freq[s[++ r] - 'a'] ++; + while(l < n && freq[0] && freq[1] && freq[2]){ + res += n - r; + freq[s[l ++] - 'a'] --; + } + } + return res; + } +}; + + +int main() { + + cout << Solution().numberOfSubstrings("abcabc") << endl; + + return 0; +} diff --git a/1001-1500/1359-Count-All-Valid-Pickup-and-Delivery-Options/cpp-1359/CMakeLists.txt b/1001-1500/1359-Count-All-Valid-Pickup-and-Delivery-Options/cpp-1359/CMakeLists.txt new file mode 100644 index 00000000..d282b1de --- /dev/null +++ b/1001-1500/1359-Count-All-Valid-Pickup-and-Delivery-Options/cpp-1359/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(cpp_1359) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1359 main3.cpp) \ No newline at end of file diff --git a/1001-1500/1359-Count-All-Valid-Pickup-and-Delivery-Options/cpp-1359/main.cpp b/1001-1500/1359-Count-All-Valid-Pickup-and-Delivery-Options/cpp-1359/main.cpp new file mode 100644 index 00000000..3bf41025 --- /dev/null +++ b/1001-1500/1359-Count-All-Valid-Pickup-and-Delivery-Options/cpp-1359/main.cpp @@ -0,0 +1,49 @@ +/// Source : https://leetcode.com/problems/count-all-valid-pickup-and-delivery-options/ +/// Author : liuyubobobo +/// Time : 2020-02-23 + +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(n * n) +/// Space Complxity: O(n * n) +class Solution { + +private: + long long MOD = 1e9 + 7; + +public: + int countOrders(int n) { + + vector> dp(n + 1, vector(n + 1, -1)); + return dfs(0, 0, n, dp); + } + +private: + int dfs(int open, int close, int n, vector>& dp){ + + if(open == n && close == n) return 1; + if(dp[open][close] != -1) return dp[open][close]; + + int res = 0; + if(open < n) res += (long long)(n - open) * (long long)dfs(open + 1, close, n, dp) % MOD; + if(close < open) res += (long long)(open - close) * (long long)dfs(open, close + 1, n, dp) % MOD; + return dp[open][close] = res % MOD; + } +}; + + +int main() { + + cout << Solution().countOrders(1) << endl; + // 1 + + cout << Solution().countOrders(2) << endl; + // 6 + + return 0; +} diff --git a/1001-1500/1359-Count-All-Valid-Pickup-and-Delivery-Options/cpp-1359/main2.cpp b/1001-1500/1359-Count-All-Valid-Pickup-and-Delivery-Options/cpp-1359/main2.cpp new file mode 100644 index 00000000..fd90030a --- /dev/null +++ b/1001-1500/1359-Count-All-Valid-Pickup-and-Delivery-Options/cpp-1359/main2.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/count-all-valid-pickup-and-delivery-options/ +/// Author : liuyubobobo +/// Time : 2020-02-23 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(n * n) +/// Space Complxity: O(n * n) +class Solution { + +private: + long long MOD = 1e9 + 7; + +public: + int countOrders(int n) { + + vector> dp(n + 1, vector(n + 1, 0)); + dp[1][0] = dp[1][1] = n; + for(int i = 2; i <= n; i ++) + dp[i][0] = (long long)dp[i - 1][0] * (long long)(n - i + 1) % MOD; + + for(int i = 2; i <= n; i ++) + for(int j = 1; j <= i; j ++){ + dp[i][j] = 0; + dp[i][j] += (long long)(n - i + 1) * (long long)dp[i - 1][j] % MOD; + dp[i][j] += (long long)(i - j + 1) * (long long)dp[i][j - 1] % MOD; + } + return dp[n][n]; + } +}; + + +int main() { + + cout << Solution().countOrders(1) << endl; + // 1 + + cout << Solution().countOrders(2) << endl; + // 6 + + return 0; +} diff --git a/1001-1500/1359-Count-All-Valid-Pickup-and-Delivery-Options/cpp-1359/main3.cpp b/1001-1500/1359-Count-All-Valid-Pickup-and-Delivery-Options/cpp-1359/main3.cpp new file mode 100644 index 00000000..daf17a5a --- /dev/null +++ b/1001-1500/1359-Count-All-Valid-Pickup-and-Delivery-Options/cpp-1359/main3.cpp @@ -0,0 +1,39 @@ +/// Source : https://leetcode.com/problems/count-all-valid-pickup-and-delivery-options/ +/// Author : liuyubobobo +/// Time : 2020-02-23 + +#include +#include + +using namespace std; + + +/// Mathematics +/// Time Complexity: O(n) +/// Space Complxity: O(1) +class Solution { + +private: + long long MOD = 1e9 + 7; + +public: + int countOrders(int n) { + + int res = 1; + for(int i = 0; i + 1 < n; i ++) + res = (long long)res * (long long)(n - i) * (long long)(2 * (n - i) - 1) % MOD; + return res; + } +}; + + +int main() { + + cout << Solution().countOrders(1) << endl; + // 1 + + cout << Solution().countOrders(2) << endl; + // 6 + + return 0; +} diff --git a/1001-1500/1360-Number-of-Days-Between-Two-Dates/cpp-1360/CMakeLists.txt b/1001-1500/1360-Number-of-Days-Between-Two-Dates/cpp-1360/CMakeLists.txt new file mode 100644 index 00000000..9c0b049b --- /dev/null +++ b/1001-1500/1360-Number-of-Days-Between-Two-Dates/cpp-1360/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1001-1500/1360-Number-of-Days-Between-Two-Dates/cpp-1360/main.cpp b/1001-1500/1360-Number-of-Days-Between-Two-Dates/cpp-1360/main.cpp new file mode 100644 index 00000000..53a41cbb --- /dev/null +++ b/1001-1500/1360-Number-of-Days-Between-Two-Dates/cpp-1360/main.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/number-of-days-between-two-dates/ +/// Author : liuyubobobo +/// Time : 2020-02-22 + +#include +#include + +using namespace std; + + +/// Date Counting +/// Time Complexity: O(1) +/// Space Complexity: O(1) +class Solution { +public: + int daysBetweenDates(string date1, string date2) { + + if(date1 > date2) swap(date1, date2); + int a = getDays(atoi(date1.substr(0, 4).c_str()), + atoi(date1.substr(5, 2).c_str()), + atoi(date1.substr(8, 2).c_str())); + int b = getDays(atoi(date2.substr(0, 4).c_str()), + atoi(date2.substr(5, 2).c_str()), + atoi(date2.substr(8, 2).c_str())); + return b - a; + } + +private: + int getDays(int Y, int M, int D){ + int res = 0; + for(int i = 1970; i < Y; i ++) + res += isLeapYear(i) ? 366 : 365; + + vector months = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; + for(int i = 0; i < M - 1; i ++){ + res += months[i]; + if(i == 1) res += isLeapYear(Y); + } + + return res + D; + } + + bool isLeapYear(int Y){ + return (Y % 4 == 0 && Y % 100 != 0 ) || Y % 400 == 0; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1361-Validate-Binary-Tree-Nodes/cpp-1361/CMakeLists.txt b/1001-1500/1361-Validate-Binary-Tree-Nodes/cpp-1361/CMakeLists.txt new file mode 100644 index 00000000..f3359f29 --- /dev/null +++ b/1001-1500/1361-Validate-Binary-Tree-Nodes/cpp-1361/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1001-1500/1361-Validate-Binary-Tree-Nodes/cpp-1361/main.cpp b/1001-1500/1361-Validate-Binary-Tree-Nodes/cpp-1361/main.cpp new file mode 100644 index 00000000..9e52d2ed --- /dev/null +++ b/1001-1500/1361-Validate-Binary-Tree-Nodes/cpp-1361/main.cpp @@ -0,0 +1,77 @@ +/// Source : https://leetcode.com/problems/validate-binary-tree-nodes/ +/// Author : liuyubobobo +/// Time : 2020-02-22 +/// Updated: 2023-10-31 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// topo sort +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + bool validateBinaryTreeNodes(int n, vector& leftChild, vector& rightChild) { + + vector> g(n); + vector indegrees(n, 0); + for(int i = 0; i < n; i ++){ + if(leftChild[i] != -1){ + g[i].insert(leftChild[i]); + indegrees[leftChild[i]] ++; + } + if(rightChild[i] != -1){ + if(g[i].count(rightChild[i])) return false; + g[i].insert(rightChild[i]); + indegrees[rightChild[i]] ++; + } + } + + return topo_sort(n, g, indegrees); + } + +private: + bool topo_sort(int n, const vector>& g, vector& indegrees){ + + for(int i = 0; i < n; i ++) + if(indegrees[i] > 1 || g[i].size() > 2) return false; + + queue q; + vector visited(n, false); + + for(int i = 0; i < n; i ++) + if(indegrees[i] == 0){ + q.push(i); + visited[i] = true; + } + + if(q.size() != 1) return false; + + while(!q.empty()){ + int cur = q.front(); q.pop(); + for(int next: g[cur]){ + if(visited[next]) return false; + visited[next] = true; + q.push(next); + } + } + + return accumulate(visited.begin(), visited.end(), 0) == n; + } +}; + + +int main() { + + vector leftChild1 = {1, -1, 3, -1}, rightChild1 = {2, -1, -1, -1}; + cout << Solution().validateBinaryTreeNodes(4, leftChild1, rightChild1) << endl; + // 1 + + return 0; +} diff --git a/1001-1500/1362-Closest-Divisors/cpp-1362/CMakeLists.txt b/1001-1500/1362-Closest-Divisors/cpp-1362/CMakeLists.txt new file mode 100644 index 00000000..0b46ca4b --- /dev/null +++ b/1001-1500/1362-Closest-Divisors/cpp-1362/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1001-1500/1362-Closest-Divisors/cpp-1362/main.cpp b/1001-1500/1362-Closest-Divisors/cpp-1362/main.cpp new file mode 100644 index 00000000..a09c262c --- /dev/null +++ b/1001-1500/1362-Closest-Divisors/cpp-1362/main.cpp @@ -0,0 +1,55 @@ +/// Source : https://leetcode.com/problems/closest-divisors/ +/// Author : liuyubobobo +/// Time : 2020-02-22 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(sqrt(num)) +/// Space Complexity: O(1) +class Solution { +public: + vector closestDivisors(int num) { + + vector v1= getDivisors(num + 1); + vector v2 = getDivisors(num + 2); + + return v1[1] - v1[0] < v2[1] - v2[0] ? v1 : v2; + } + +private: + vector getDivisors(int x){ + + vector res = {1, x}; + for(int i = 2; i * i <= x; i ++) + if(x % i == 0) + res = {i, x / i}; + return res; + } +}; + + +void print_vec(const vector& vec){ + for(int e: vec) cout << e << " "; cout << endl; +} + +int main() { + + print_vec(Solution().closestDivisors(8)); + // 3 3 + + print_vec(Solution().closestDivisors(123)); + // 5 25 + + print_vec(Solution().closestDivisors(999)); + // 40 25 + + print_vec(Solution().closestDivisors(170967091)); + // 10754 15898 + + return 0; +} diff --git a/1001-1500/1363-Largest-Multiple-of-Three/cpp-1363/CMakeLists.txt b/1001-1500/1363-Largest-Multiple-of-Three/cpp-1363/CMakeLists.txt new file mode 100644 index 00000000..ed89229b --- /dev/null +++ b/1001-1500/1363-Largest-Multiple-of-Three/cpp-1363/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) \ No newline at end of file diff --git a/1001-1500/1363-Largest-Multiple-of-Three/cpp-1363/main.cpp b/1001-1500/1363-Largest-Multiple-of-Three/cpp-1363/main.cpp new file mode 100644 index 00000000..ab1fb342 --- /dev/null +++ b/1001-1500/1363-Largest-Multiple-of-Three/cpp-1363/main.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/largest-multiple-of-three/ +/// Author : liuyubobobo +/// Time : 2020-02-22 + +#include +#include +#include + +using namespace std; + + +/// Sorting and Greedy +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + string largestMultipleOfThree(vector& digits) { + + vector> mod(3); + int sum = 0; + for(int d: digits) + mod[d % 3].push_back(d), sum += d; + + for(int i = 0; i < 3; i ++) + sort(mod[i].begin(), mod[i].end(), greater()); + + if(sum % 3 == 1){ + if(mod[1].size()) mod[1].pop_back(); + else if(mod[2].size() >= 2) mod[2].pop_back(), mod[2].pop_back(); + else return ""; + } + else if(sum % 3 == 2){ + if(mod[2].size()) mod[2].pop_back(); + else if(mod[1].size() >= 2) mod[1].pop_back(), mod[1].pop_back(); + else return ""; + } + + vector v; + for(int i = 0; i < 3; i ++) for(int d: mod[i]) v.push_back(d); + sort(v.begin(), v.end(), greater()); + + string res = ""; + for(int d: v) res += ('0' + d); + return res[0] == '0' ? "0" : res; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1365-How-Many-Numbers-Are-Smaller-Than-the-Current-Number/cpp-1365/CMakeLists.txt b/1001-1500/1365-How-Many-Numbers-Are-Smaller-Than-the-Current-Number/cpp-1365/CMakeLists.txt new file mode 100644 index 00000000..3731f44a --- /dev/null +++ b/1001-1500/1365-How-Many-Numbers-Are-Smaller-Than-the-Current-Number/cpp-1365/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main2.cpp) \ No newline at end of file diff --git a/1001-1500/1365-How-Many-Numbers-Are-Smaller-Than-the-Current-Number/cpp-1365/main.cpp b/1001-1500/1365-How-Many-Numbers-Are-Smaller-Than-the-Current-Number/cpp-1365/main.cpp new file mode 100644 index 00000000..8ae2de43 --- /dev/null +++ b/1001-1500/1365-How-Many-Numbers-Are-Smaller-Than-the-Current-Number/cpp-1365/main.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/ +/// Author : liuyubobobo +/// Time : 2020-02-29 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n^2) +/// Space Complexity: O(1) +class Solution { +public: + vector smallerNumbersThanCurrent(vector& nums) { + + vector res; + for(int i = 0; i < nums.size(); i ++){ + int e = 0; + for(int j = 0; j < nums.size(); j ++) + e += (nums[j] < nums[i]); + res.push_back(e); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1365-How-Many-Numbers-Are-Smaller-Than-the-Current-Number/cpp-1365/main2.cpp b/1001-1500/1365-How-Many-Numbers-Are-Smaller-Than-the-Current-Number/cpp-1365/main2.cpp new file mode 100644 index 00000000..82cd6798 --- /dev/null +++ b/1001-1500/1365-How-Many-Numbers-Are-Smaller-Than-the-Current-Number/cpp-1365/main2.cpp @@ -0,0 +1,32 @@ +/// Source : https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/ +/// Author : liuyubobobo +/// Time : 2020-03-01 + +#include +#include + +using namespace std; + + +/// Counting +/// Time Complexity: O(n) +/// Space Complexity: O(max(nums)) +class Solution { +public: + vector smallerNumbersThanCurrent(vector& nums) { + + vector count(101, 0); + for(int e: nums) count[e] ++; + for(int i = 1; i <= 100; i ++) count[i] += count[i - 1]; + + vector res; + for(int num: nums) res.push_back(num ? count[num - 1] : 0); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1366-Rank-Teams-by-Votes/cpp-1366/CMakeLists.txt b/1001-1500/1366-Rank-Teams-by-Votes/cpp-1366/CMakeLists.txt new file mode 100644 index 00000000..f3359f29 --- /dev/null +++ b/1001-1500/1366-Rank-Teams-by-Votes/cpp-1366/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1001-1500/1366-Rank-Teams-by-Votes/cpp-1366/main.cpp b/1001-1500/1366-Rank-Teams-by-Votes/cpp-1366/main.cpp new file mode 100644 index 00000000..76690b6e --- /dev/null +++ b/1001-1500/1366-Rank-Teams-by-Votes/cpp-1366/main.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/rank-teams-by-votes/ +/// Author : liuyubobobo +/// Time : 2020-02-29 + +#include +#include +#include + +using namespace std; + + +/// Sorting +/// Time Complexity: O(26log26 * n) +/// Space Complexity: O(26^2) +class Solution { +public: + string rankTeams(vector& votes) { + + vector> freq(26, vector(26, 0)); + for(const string& s: votes) + for(int i = 0; i < s.size(); i ++) + freq[s[i] - 'A'][i] ++; + + vector vec; + for(char c: votes[0]) vec.push_back(c); + sort(vec.begin(), vec.end(), [freq](char a, char b){ + for(int i = 0; i < 26; i ++) + if(freq[a - 'A'][i] != freq[b - 'A'][i]) + return freq[a - 'A'][i] > freq[b - 'A'][i]; + return a < b; + }); + + string res = ""; + for(char c: vec) res += c; + return res; + } +}; + + +int main() { + + vector votes = {"ABC","ACB","ABC","ACB","ACB"}; + cout << Solution().rankTeams(votes) << endl; + + return 0; +} diff --git a/1001-1500/1367-Linked-List-in-Binary-Tree/cpp-1367/CMakeLists.txt b/1001-1500/1367-Linked-List-in-Binary-Tree/cpp-1367/CMakeLists.txt new file mode 100644 index 00000000..0b46ca4b --- /dev/null +++ b/1001-1500/1367-Linked-List-in-Binary-Tree/cpp-1367/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1001-1500/1367-Linked-List-in-Binary-Tree/cpp-1367/main.cpp b/1001-1500/1367-Linked-List-in-Binary-Tree/cpp-1367/main.cpp new file mode 100644 index 00000000..5ac97155 --- /dev/null +++ b/1001-1500/1367-Linked-List-in-Binary-Tree/cpp-1367/main.cpp @@ -0,0 +1,63 @@ +/// Source : https://leetcode.com/problems/linked-list-in-binary-tree/ +/// Author : liuyubobobo +/// Time : 2020-02-29 + +#include + +using namespace std; + + +/// Recursion +/// Time Complexity: O(treenodes * listnodes) +/// Space Compelxity: O(h) + +/// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} +}; + +/// 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: + bool isSubPath(ListNode* head, TreeNode* root) { + + return go(root, head); + } + +private: + bool go(TreeNode* node, ListNode* head){ + + if(ok(node, head)) return true; + + if(node->left && go(node->left, head)) return true; + if(node->right && go(node->right, head)) return true; + return false; + } + + bool ok(TreeNode* node, ListNode* head){ + + if(!head) return true; + if(!node) return false; + if(node->val != head->val) return false; + if(!head->next) return true; + + if(node->left && ok(node->left, head->next)) return true; + if(node->right && ok(node->right, head->next)) return true; + return false; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1368-Minimum-Cost-to-Make-at-Least-One-Valid-Path-in-a-Grid/cpp-1368/CMakeLists.txt b/1001-1500/1368-Minimum-Cost-to-Make-at-Least-One-Valid-Path-in-a-Grid/cpp-1368/CMakeLists.txt new file mode 100644 index 00000000..ed89229b --- /dev/null +++ b/1001-1500/1368-Minimum-Cost-to-Make-at-Least-One-Valid-Path-in-a-Grid/cpp-1368/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) \ No newline at end of file diff --git a/1001-1500/1368-Minimum-Cost-to-Make-at-Least-One-Valid-Path-in-a-Grid/cpp-1368/main.cpp b/1001-1500/1368-Minimum-Cost-to-Make-at-Least-One-Valid-Path-in-a-Grid/cpp-1368/main.cpp new file mode 100644 index 00000000..98530bc8 --- /dev/null +++ b/1001-1500/1368-Minimum-Cost-to-Make-at-Least-One-Valid-Path-in-a-Grid/cpp-1368/main.cpp @@ -0,0 +1,79 @@ +/// Source : https://leetcode.com/problems/minimum-cost-to-make-at-least-one-valid-path-in-a-grid/ +/// Author : liuyubobobo +/// Time : 2020-03-01 + +#include +#include +#include + +using namespace std; + + +/// BFS +/// Time Compelxity: O(m * n) +/// Space Complexity: O(m * n) +class Solution { + +private: + const int dirs[4][2] = {{-1, 0}, {0, 1}, {0, -1}, {1, 0}}; + int m, n; + +public: + int minCost(vector>& grid) { + + for(vector& row: grid) + for(int& e: row) if(e == 4) e = 0; + + m = grid.size(), n = grid[0].size(); + vector> dp(m, vector(n, -1)); + + queue q; + dfs(grid, 0, 0, 0, dp, q); + while(!q.empty()){ + int x = q.front() / n, y = q.front() % n; + q.pop(); + + for(int d = 0; d < 4; d ++) + if(d != grid[x][y]){ + int nextx = x + dirs[d][0], nexty = y + dirs[d][1]; + if(in_area(nextx, nexty) && dp[nextx][nexty] == -1) + dfs(grid, nextx, nexty, dp[x][y] + 1, dp, q); + } + } + return dp[m - 1][n - 1]; + } + +private: + void dfs(const vector>& grid, int x, int y, int cost, + vector>& dp, queue& q){ + + if(dp[x][y] != -1) return; + dp[x][y] = cost; + q.push(x * n + y); + + if(in_area(x + dirs[grid[x][y]][0], y + dirs[grid[x][y]][1])) + dfs(grid, x + dirs[grid[x][y]][0], y + dirs[grid[x][y]][1], cost, dp, q); + return; + } + + bool in_area(int x, int y){ + return x >= 0 && x < m && y >= 0 && y < n; + } +}; + + +int main() { + + vector> grid1 = {{1,1,1,1},{2,2,2,2},{1,1,1,1},{2,2,2,2}}; + cout << Solution().minCost(grid1) << endl; + // 3 + + vector> grid2 = {{1,1,3},{3,2,2},{1,1,4}}; + cout << Solution().minCost(grid2) << endl; + // 0 + + // [[3,4,3],[2,2,2],[2,1,1],[4,3,2],[2,1,4],[2,4,1],[3,3,3],[1,4,2],[2,2,1],[2,1,1],[3,3,1],[4,1,4],[2,1,4],[3,2,2],[3,3,1],[4,4,1],[1,2,2],[1,1,1],[1,3,4],[1,2,1],[2,2,4],[2,1,3],[1,2,1],[4,3,2],[3,3,4],[2,2,1],[3,4,3],[4,2,3],[4,4,4]] + // 18 + + return 0; +} diff --git a/1001-1500/1370-Increasing-Decreasing-String/cpp-1370/CMakeLists.txt b/1001-1500/1370-Increasing-Decreasing-String/cpp-1370/CMakeLists.txt new file mode 100644 index 00000000..2546a484 --- /dev/null +++ b/1001-1500/1370-Increasing-Decreasing-String/cpp-1370/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(cpp_1370) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1370 main.cpp) \ No newline at end of file diff --git a/1001-1500/1370-Increasing-Decreasing-String/cpp-1370/main.cpp b/1001-1500/1370-Increasing-Decreasing-String/cpp-1370/main.cpp new file mode 100644 index 00000000..87105164 --- /dev/null +++ b/1001-1500/1370-Increasing-Decreasing-String/cpp-1370/main.cpp @@ -0,0 +1,36 @@ +/// Source : https://leetcode.com/problems/increasing-decreasing-string/ +/// Author : liuyubobobo +/// Time : 2020-03-07 + +#include +#include + +using namespace std; + + +/// Hash Map +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + string sortString(string s) { + + vector freq(26, 0); + for(char c: s) freq[c - 'a'] ++; + + string res = ""; + while(res.size() != s.size()){ + for(int i = 0; i < 26; i ++) + if(freq[i]) res += ('a' + i), freq[i] --; + for(int i = 25; i >= 0; i --) + if(freq[i]) res += ('a' + i), freq[i] --; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1371-Find-the-Longest-Substring-Containing-Vowels-in-Even-Counts/cpp-1371/CMakeLists.txt b/1001-1500/1371-Find-the-Longest-Substring-Containing-Vowels-in-Even-Counts/cpp-1371/CMakeLists.txt new file mode 100644 index 00000000..871f5c97 --- /dev/null +++ b/1001-1500/1371-Find-the-Longest-Substring-Containing-Vowels-in-Even-Counts/cpp-1371/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(cpp_1371) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1371 main.cpp) \ No newline at end of file diff --git a/1001-1500/1371-Find-the-Longest-Substring-Containing-Vowels-in-Even-Counts/cpp-1371/main.cpp b/1001-1500/1371-Find-the-Longest-Substring-Containing-Vowels-in-Even-Counts/cpp-1371/main.cpp new file mode 100644 index 00000000..25660b6a --- /dev/null +++ b/1001-1500/1371-Find-the-Longest-Substring-Containing-Vowels-in-Even-Counts/cpp-1371/main.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/find-the-longest-substring-containing-vowels-in-even-counts/ +/// Author : liuyubobobo +/// Time : 2020-03-14 +/// Updated: 2020-05-05 + +#include +#include +#include + +using namespace std; + + +/// State Compression +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int findTheLongestSubstring(string s) { + + unordered_map vowels = {{'a', 0}, {'e', 1}, {'i', 2}, {'o', 3}, {'u', 4}}; + + int state = 0; + vector pos(1 << 5, -1); + vector visited(1 << 5, false); + visited[0] = true; + int res = 0; + for(int i = 0; i < s.size(); i ++){ + if(vowels.count(s[i])) { + if(state & (1 << vowels[s[i]])) state -= (1 << vowels[s[i]]); + else state += (1 << vowels[s[i]]); + } + if(visited[state]) res = max(res, i - pos[state]); + else pos[state] = i, visited[state] = true; + } + return res; + } +}; + + +int main() { + + cout << Solution().findTheLongestSubstring("leetcodeisgreat") << endl; + // 5 + + return 0; +} diff --git a/1001-1500/1372-Longest-ZigZag-Path-in-a-Binary-Tree/cpp-1372/CMakeLists.txt b/1001-1500/1372-Longest-ZigZag-Path-in-a-Binary-Tree/cpp-1372/CMakeLists.txt new file mode 100644 index 00000000..79771db8 --- /dev/null +++ b/1001-1500/1372-Longest-ZigZag-Path-in-a-Binary-Tree/cpp-1372/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(cpp_1372) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1372 main.cpp) \ No newline at end of file diff --git a/1001-1500/1372-Longest-ZigZag-Path-in-a-Binary-Tree/cpp-1372/main.cpp b/1001-1500/1372-Longest-ZigZag-Path-in-a-Binary-Tree/cpp-1372/main.cpp new file mode 100644 index 00000000..e91f78e8 --- /dev/null +++ b/1001-1500/1372-Longest-ZigZag-Path-in-a-Binary-Tree/cpp-1372/main.cpp @@ -0,0 +1,59 @@ +/// Source : https://leetcode.com/problems/longest-zigzag-path-in-a-binary-tree/ +/// Author : liuyubobobo +/// Time : 2020-05-05 + +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(h) + +/// 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 { + +private: + int LEFT = 0; + int RIGHT = 1; + int res; + +public: + int longestZigZag(TreeNode* root) { + + if(!root) return 0; + + res = 0; + dfs(root, LEFT, 0); + dfs(root, RIGHT, 0); + return res; + } + +private: + void dfs(TreeNode* node, int d, int len){ + + if(!node) return; + + res = max(res, len); + + dfs(d == LEFT ? node->left : node->right, 1 - d, len + 1); + dfs(d == LEFT ? node->right : node->left, d, 1); + return; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1373-Maximum-Sum-BST-in-Binary-Tree/cpp-1373/CMakeLists.txt b/1001-1500/1373-Maximum-Sum-BST-in-Binary-Tree/cpp-1373/CMakeLists.txt new file mode 100644 index 00000000..f647b386 --- /dev/null +++ b/1001-1500/1373-Maximum-Sum-BST-in-Binary-Tree/cpp-1373/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(cpp_1373) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1373 main.cpp) \ No newline at end of file diff --git a/1001-1500/1373-Maximum-Sum-BST-in-Binary-Tree/cpp-1373/main.cpp b/1001-1500/1373-Maximum-Sum-BST-in-Binary-Tree/cpp-1373/main.cpp new file mode 100644 index 00000000..902b4dd5 --- /dev/null +++ b/1001-1500/1373-Maximum-Sum-BST-in-Binary-Tree/cpp-1373/main.cpp @@ -0,0 +1,79 @@ +/// Source : https://leetcode.com/problems/maximum-sum-bst-in-binary-tree/ +/// Author : liuyubobobo +/// Time : 2020-10-17 + +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// 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 { + +private: + unordered_map sum_table, max_table, min_table; + unordered_map isBST; + +public: + int maxSumBST(TreeNode* root) { + + dfs(root); + + int res = 0; + for(const pair& p: sum_table) + if(isBST[p.first]) res = max(res, p.second); + return res; + } + +private: + void dfs(TreeNode* node){ + + if(!node) return; + + dfs(node->left); + dfs(node->right); + + int sum = node->val, maxv = node->val, minv = node->val; + if(node->left) + sum += sum_table[node->left], + maxv = max(maxv, max_table[node->left]), + minv = min(minv, min_table[node->left]); + if(node->right) + sum += sum_table[node->right], + maxv = max(maxv, max_table[node->right]), + minv = min(minv, min_table[node->right]); + + sum_table[node] = sum; + max_table[node] = maxv; + min_table[node] = minv; + + bool ok = true; + if(node->left && node->val <= max_table[node->left]) ok = false; + if(node->left && !isBST[node->left]) ok = false; + if(node->right && node->val >= min_table[node->right]) ok = false; + if(node->right && !isBST[node->right]) ok = false; + isBST[node] = ok; + + return; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1374-Generate-a-String-With-Characters-That-Have-Odd-Counts/cpp-1374/CMakeLists.txt b/1001-1500/1374-Generate-a-String-With-Characters-That-Have-Odd-Counts/cpp-1374/CMakeLists.txt new file mode 100644 index 00000000..9c0b049b --- /dev/null +++ b/1001-1500/1374-Generate-a-String-With-Characters-That-Have-Odd-Counts/cpp-1374/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1001-1500/1374-Generate-a-String-With-Characters-That-Have-Odd-Counts/cpp-1374/main.cpp b/1001-1500/1374-Generate-a-String-With-Characters-That-Have-Odd-Counts/cpp-1374/main.cpp new file mode 100644 index 00000000..ebfcaeb4 --- /dev/null +++ b/1001-1500/1374-Generate-a-String-With-Characters-That-Have-Odd-Counts/cpp-1374/main.cpp @@ -0,0 +1,26 @@ +/// Source : https://leetcode.com/problems/generate-a-string-with-characters-that-have-odd-counts/ +/// Author : liuyubobobo +/// Time : 2020-03-07 + +#include + +using namespace std; + + +/// Mathematics +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + string generateTheString(int n) { + + if(n % 2) return string(n, 'a'); + return string(1, 'a') + string(n - 1, 'b'); + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1375-Bulb-Switcher-III/cpp-1375/CMakeLists.txt b/1001-1500/1375-Bulb-Switcher-III/cpp-1375/CMakeLists.txt new file mode 100644 index 00000000..f3359f29 --- /dev/null +++ b/1001-1500/1375-Bulb-Switcher-III/cpp-1375/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1001-1500/1375-Bulb-Switcher-III/cpp-1375/main.cpp b/1001-1500/1375-Bulb-Switcher-III/cpp-1375/main.cpp new file mode 100644 index 00000000..8bf47841 --- /dev/null +++ b/1001-1500/1375-Bulb-Switcher-III/cpp-1375/main.cpp @@ -0,0 +1,56 @@ +/// Source : https://leetcode.com/problems/bulb-switcher-iii/ +/// Author : liuyubobobo +/// Time : 2020-03-07 + +#include +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int numTimesAllBlue(vector& light) { + + int res = 0, start = 0, minv = 1, maxv = 0; + for(int i = 0; i < light.size(); i ++){ + maxv = max(light[i], maxv); + if(i - start + 1 == maxv - minv + 1) + res ++, minv = maxv + 1, maxv = 0, start = i + 1; + } + return res; + } +}; + + +int main() { + + vector light1 = {2, 1, 3, 5, 4}; + cout << Solution().numTimesAllBlue(light1) << endl; + // 3 + + vector light2 = {3, 2, 4, 1, 5}; + cout << Solution().numTimesAllBlue(light2) << endl; + // 2 + + vector light3 = {1, 2, 3, 4, 5, 6}; + cout << Solution().numTimesAllBlue(light3) << endl; + // 6 + + vector light4 = {2, 1, 4, 3, 6, 5}; + cout << Solution().numTimesAllBlue(light4) << endl; + // 3 + + vector light5 = {4, 1, 2, 3}; + cout << Solution().numTimesAllBlue(light5) << endl; + // 1 + + vector light6 = {1,2,3,4,5,6,18,8,30,10,11,12,13,14,17,16,15,7,19,20,41,22,23,24,33,26,27,25,29,9,31,32,28,34,35,36,37,38,39,40,21,42}; + cout << Solution().numTimesAllBlue(light6) << endl; + // 8 + + return 0; +} diff --git a/1001-1500/1376-Time-Needed-to-Inform-All-Employees/cpp-1376/CMakeLists.txt b/1001-1500/1376-Time-Needed-to-Inform-All-Employees/cpp-1376/CMakeLists.txt new file mode 100644 index 00000000..0b46ca4b --- /dev/null +++ b/1001-1500/1376-Time-Needed-to-Inform-All-Employees/cpp-1376/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1001-1500/1376-Time-Needed-to-Inform-All-Employees/cpp-1376/main.cpp b/1001-1500/1376-Time-Needed-to-Inform-All-Employees/cpp-1376/main.cpp new file mode 100644 index 00000000..244b0609 --- /dev/null +++ b/1001-1500/1376-Time-Needed-to-Inform-All-Employees/cpp-1376/main.cpp @@ -0,0 +1,59 @@ +/// Source : https://leetcode.com/problems/time-needed-to-inform-all-employees/ +/// Author : liuyubobobo +/// Time : 2020-03-07 + +#include +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(V + E) +/// Space Complexity: O(V + E) +class Solution { +public: + int numOfMinutes(int n, int headID, vector& manager, vector& informTime) { + + vector> g(n, set()); + for(int i = 0; i < n; i ++) + if(i != headID) g[i].insert(manager[i]), g[manager[i]].insert(i); + + vector visited(n, false); + return dfs(g, n, headID, visited, informTime); + } + +private: + int dfs(const vector>& g, int n, int node, + vector& visited, const vector& informTime){ + + visited[node] = true; + int res = 0; + for(int next: g[node]) + if(!visited[next]) + res = max(res, dfs(g, n, next, visited, informTime)); + return res + informTime[node]; + } +}; + + +int main() { + + vector manager1 = {-1}; + vector informTime1 = {0}; + cout << Solution().numOfMinutes(1, 0, manager1, informTime1) << endl; + // 0 + + vector manager2 = {2,2,-1,2,2,2}; + vector informTime2 = {0,0,1,0,0,0}; + cout << Solution().numOfMinutes(6, 2, manager2, informTime2) << endl; + // 1 + + vector manager3 = {1,2,3,4,5,6,-1}; + vector informTime3 = {0,6,5,4,3,2,1}; + cout << Solution().numOfMinutes(7, 6, manager3, informTime3) << endl; + // 21 + + return 0; +} diff --git a/1001-1500/1377-Frog-Position-After-T-Seconds/cpp-1377/CMakeLists.txt b/1001-1500/1377-Frog-Position-After-T-Seconds/cpp-1377/CMakeLists.txt new file mode 100644 index 00000000..c0c37cc3 --- /dev/null +++ b/1001-1500/1377-Frog-Position-After-T-Seconds/cpp-1377/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main2.cpp) \ No newline at end of file diff --git a/1001-1500/1377-Frog-Position-After-T-Seconds/cpp-1377/main.cpp b/1001-1500/1377-Frog-Position-After-T-Seconds/cpp-1377/main.cpp new file mode 100644 index 00000000..af82b689 --- /dev/null +++ b/1001-1500/1377-Frog-Position-After-T-Seconds/cpp-1377/main.cpp @@ -0,0 +1,81 @@ +/// Source : https://leetcode.com/problems/frog-position-after-t-seconds/ +/// Author : liuyubobobo +/// Time : 2020-03-07 + +#include +#include +#include + +using namespace std; + + +/// DFS to get the path +/// Time Complexity: O(V + E) +/// Space Complexity: O(V + E) +class Solution { +public: + double frogPosition(int n, vector>& edges, int t, int target) { + + vector> g(n, set()); + for(const vector& e: edges) + g[e[0] - 1].insert(e[1] - 1), g[e[1] - 1].insert(e[0] - 1); + + vector path; + target --; + dfs(g, 0, -1, target, path); +// for(int e: path) cout << e << " "; cout << endl; + if(t + 1 < path.size()) return 0.0; + if(t + 1 > path.size() && (target == 0 && g[target].size() || g[target].size() > 1)) return 0.0; + + double res = 1.0; + for(int i = 0; i + 1 < path.size(); i ++){ +// cout << g[path[i]].size() << endl; + res /= (double)(g[path[i]].size() - !!i); + } + return res; + } + +private: + bool dfs(const vector>& g, int cur, int parent, int target, + vector& path){ + + path.push_back(cur); + if(cur == target) return true; + for(int next: g[cur]) + if(next != parent){ + if(dfs(g, next, cur, target, path)) return true; + } + path.pop_back(); + return false; + } +}; + + +int main() { + + vector> edges1 = { + {1,2},{1,3},{1,7},{2,4},{2,6},{3,5} + }; + cout << Solution().frogPosition(7, edges1, 2, 4) << endl; + // 0.166666 + + vector> edges2 = { + {2,1},{3,2},{4,1},{5,1},{6,4},{7,1},{8,7} + }; + cout << Solution().frogPosition(8, edges2, 7, 7) << endl; + // 0.0 + + vector> edges3 = { + {1,2},{1,3},{1,7},{2,4},{2,6},{3,5} + }; + cout << Solution().frogPosition(7, edges3, 20, 6) << endl; + // 0.16666 + + vector> edges4 = { + {2,1},{3,2},{4,3},{5,3},{6,5},{7,3}, {8, 4}, {9, 5} + }; + cout << Solution().frogPosition(9, edges4, 9, 1) << endl; + // 0 + + return 0; +} diff --git a/1001-1500/1377-Frog-Position-After-T-Seconds/cpp-1377/main2.cpp b/1001-1500/1377-Frog-Position-After-T-Seconds/cpp-1377/main2.cpp new file mode 100644 index 00000000..1116c6af --- /dev/null +++ b/1001-1500/1377-Frog-Position-After-T-Seconds/cpp-1377/main2.cpp @@ -0,0 +1,82 @@ +/// Source : https://leetcode.com/problems/frog-position-after-t-seconds/ +/// Author : liuyubobobo +/// Time : 2020-03-14 + +#include +#include +#include + +using namespace std; + + +/// DFS directly +/// Time Complexity: O(V + E) +/// Space Complexity: O(V + E) +class Solution { +public: + double frogPosition(int n, vector>& edges, int t, int target) { + + if(n == 1) return 1.0; + + vector> g(n, set()); + for(const vector& e: edges) + g[e[0] - 1].insert(e[1] - 1), g[e[1] - 1].insert(e[0] - 1); + + target --; + return dfs(g, 0, -1, target, t); + } + +private: + double dfs(const vector>& g, int cur, int parent, int target, int t){ + + if(g[cur].size() == 1 && *g[cur].begin() == parent) + return cur == target; + + if(cur == target) return t == 0; + + if(t == 0) return 0; + + double res = 0.0; + for(int next: g[cur]) + if(next != parent){ + res += (1.0 / (g[cur].size() - (parent != -1))) * dfs(g, next, cur, target, t - 1); + } + return res; + } +}; + + +int main() { + + vector> edges1 = { + {1,2},{1,3},{1,7},{2,4},{2,6},{3,5} + }; + cout << Solution().frogPosition(7, edges1, 2, 4) << endl; + // 0.166666 + + vector> edges2 = { + {2,1},{3,2},{4,1},{5,1},{6,4},{7,1},{8,7} + }; + cout << Solution().frogPosition(8, edges2, 7, 7) << endl; + // 0.0 + + vector> edges3 = { + {1,2},{1,3},{1,7},{2,4},{2,6},{3,5} + }; + cout << Solution().frogPosition(7, edges3, 20, 6) << endl; + // 0.16666 + + vector> edges4 = { + {2,1},{3,2},{4,3},{5,3},{6,5},{7,3}, {8, 4}, {9, 5} + }; + cout << Solution().frogPosition(9, edges4, 9, 1) << endl; + // 0 + + vector> edges5 = { + {2,1},{3,2} + }; + cout << Solution().frogPosition(3, edges5, 1, 2) << endl; + // 1.0 + + return 0; +} diff --git a/1001-1500/1379-Find-a-Corresponding-Node-of-a-Binary-Tree-in-a-Clone-of-That-Tree/cpp-1379/CMakeLists.txt b/1001-1500/1379-Find-a-Corresponding-Node-of-a-Binary-Tree-in-a-Clone-of-That-Tree/cpp-1379/CMakeLists.txt new file mode 100644 index 00000000..8fbb8a63 --- /dev/null +++ b/1001-1500/1379-Find-a-Corresponding-Node-of-a-Binary-Tree-in-a-Clone-of-That-Tree/cpp-1379/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(cpp_1379) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1379 main.cpp main2.cpp) \ No newline at end of file diff --git a/1001-1500/1379-Find-a-Corresponding-Node-of-a-Binary-Tree-in-a-Clone-of-That-Tree/cpp-1379/main.cpp b/1001-1500/1379-Find-a-Corresponding-Node-of-a-Binary-Tree-in-a-Clone-of-That-Tree/cpp-1379/main.cpp new file mode 100644 index 00000000..7d4c4e89 --- /dev/null +++ b/1001-1500/1379-Find-a-Corresponding-Node-of-a-Binary-Tree-in-a-Clone-of-That-Tree/cpp-1379/main.cpp @@ -0,0 +1,48 @@ +/// Source : https://leetcode.com/problems/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/ +/// Author : liuyubobobo +/// Time : 2020-03-14 + +#include +#include + +using namespace std; + + +/// Non-Recursion +/// Time Complexity: O(n) +/// Space Complexity: O(h) + +/// 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* getTargetCopy(TreeNode* original, TreeNode* cloned, TreeNode* target) { + + stack stack1, stack2; + stack1.push(original); + stack2.push(cloned); + while(!stack1.empty()){ + TreeNode* node1 = stack1.top(); stack1.pop(); + TreeNode* node2 = stack2.top(); stack2.pop(); + + if(node1 == target) return node2; + + if(node1->left) stack1.push(node1->left), stack2.push(node2->left); + if(node1->right) stack1.push(node1->right), stack2.push(node2->right); + } + return NULL; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1379-Find-a-Corresponding-Node-of-a-Binary-Tree-in-a-Clone-of-That-Tree/cpp-1379/main2.cpp b/1001-1500/1379-Find-a-Corresponding-Node-of-a-Binary-Tree-in-a-Clone-of-That-Tree/cpp-1379/main2.cpp new file mode 100644 index 00000000..91dda255 --- /dev/null +++ b/1001-1500/1379-Find-a-Corresponding-Node-of-a-Binary-Tree-in-a-Clone-of-That-Tree/cpp-1379/main2.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/ +/// Author : liuyubobobo +/// Time : 2020-03-14 + +#include +#include + +using namespace std; + + +/// Recursion +/// Time Complexity: O(n) +/// Space Complexity: O(h) + +/// 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* getTargetCopy(TreeNode* original, TreeNode* cloned, TreeNode* target) { + + if(original == target) return cloned; + if(!original) return NULL; + + TreeNode* node1 = getTargetCopy(original->left, cloned->left, target); + return node1 ? node1 : getTargetCopy(original->right, cloned->right, target); + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1383-Maximum-Performance-of-a-Team/cpp-1383/CMakeLists.txt b/1001-1500/1383-Maximum-Performance-of-a-Team/cpp-1383/CMakeLists.txt new file mode 100644 index 00000000..904c432d --- /dev/null +++ b/1001-1500/1383-Maximum-Performance-of-a-Team/cpp-1383/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(cpp_1383) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1383 main.cpp) \ No newline at end of file diff --git a/1001-1500/1383-Maximum-Performance-of-a-Team/cpp-1383/main.cpp b/1001-1500/1383-Maximum-Performance-of-a-Team/cpp-1383/main.cpp new file mode 100644 index 00000000..4915dc3e --- /dev/null +++ b/1001-1500/1383-Maximum-Performance-of-a-Team/cpp-1383/main.cpp @@ -0,0 +1,73 @@ +/// Source : https://leetcode.com/problems/maximum-performance-of-a-team/ +/// Author : liuyubobobo +/// Time : 2020-05-05 + +#include +#include +#include + +using namespace std; + + +/// Greedy + Priority Queue +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { + +private: + long long MOD = 1e9 + 7; + +public: + int maxPerformance(int n, vector& speed, vector& efficiency, int k) { + + vector> vec; + for(int i = 0; i < n; i ++) vec.push_back({speed[i], efficiency[i]}); + sort(vec.begin(), vec.end(), [](const pair& p1, const pair& p2){ + return p1.second > p2.second; + }); + + long long res = (long long)vec[0].first * vec[0].second; + long long speedsum = vec[0].first; + priority_queue, vector>, greater>> pq; + pq.push(vec[0]); + for(int i = 1; i < n; i ++){ + if(i < k){ + res = max(res, (long long)vec[i].second * (speedsum + vec[i].first)); + speedsum += vec[i].first; + pq.push(vec[i]); + } + else{ + long long tres = (long long)vec[i].second * (speedsum - pq.top().first + vec[i].first); + res = max(res, tres); + if(pq.top().first < vec[i].first){ + speedsum = speedsum - pq.top().first + vec[i].first; + pq.pop(); + pq.push(vec[i]); + } + } + } + + return res % MOD; + } +}; + + +int main() { + + vector speed1 = {2,10,3,1,5,8}; + vector efficiency1 = {5,4,3,9,7,2}; + cout << Solution().maxPerformance(6, speed1, efficiency1, 2) << endl; + // 60 + + vector speed2 = {2,10,3,1,5,8}; + vector efficiency2 = {5,4,3,9,7,2}; + cout << Solution().maxPerformance(6, speed2, efficiency2, 3) << endl; + // 68 + + vector speed3 = {2,10,3,1,5,8}; + vector efficiency3 = {5,4,3,9,7,2}; + cout << Solution().maxPerformance(6, speed3, efficiency3, 4) << endl; + // 72 + + return 0; +} diff --git a/1001-1500/1389-Create-Target-Array-in-the-Given-Order/cpp-1389/CMakeLists.txt b/1001-1500/1389-Create-Target-Array-in-the-Given-Order/cpp-1389/CMakeLists.txt new file mode 100644 index 00000000..0856fec0 --- /dev/null +++ b/1001-1500/1389-Create-Target-Array-in-the-Given-Order/cpp-1389/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp main2.cpp) \ No newline at end of file diff --git a/1001-1500/1389-Create-Target-Array-in-the-Given-Order/cpp-1389/main.cpp b/1001-1500/1389-Create-Target-Array-in-the-Given-Order/cpp-1389/main.cpp new file mode 100644 index 00000000..edb16b69 --- /dev/null +++ b/1001-1500/1389-Create-Target-Array-in-the-Given-Order/cpp-1389/main.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/create-target-array-in-the-given-order/ +/// Author : liuyubobobo +/// Time : 2020-03-21 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n^2) +/// Space Complexity: O(1) +class Solution { +public: + vector createTargetArray(vector& nums, vector& index) { + + vector res(nums.size()); + for(int i = 0; i < nums.size(); i ++){ + + for(int j = i - 1; j >= index[i]; j --) + res[j + 1] = res[j]; + res[index[i]] = nums[i]; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1389-Create-Target-Array-in-the-Given-Order/cpp-1389/main2.cpp b/1001-1500/1389-Create-Target-Array-in-the-Given-Order/cpp-1389/main2.cpp new file mode 100644 index 00000000..a14d9f57 --- /dev/null +++ b/1001-1500/1389-Create-Target-Array-in-the-Given-Order/cpp-1389/main2.cpp @@ -0,0 +1,29 @@ +/// Source : https://leetcode.com/problems/create-target-array-in-the-given-order/ +/// Author : liuyubobobo +/// Time : 2020-03-27 + +#include +#include + +using namespace std; + + +/// Simulation, Using STL +/// Time Complexity: O(n^2) +/// Space Complexity: O(1) +class Solution { +public: + vector createTargetArray(vector& nums, vector& index) { + + vector res; + for(int i = 0; i < nums.size(); i ++) + res.insert(res.begin() + index[i], nums[i]); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1390-Four-Divisors/cpp-1390/CMakeLists.txt b/1001-1500/1390-Four-Divisors/cpp-1390/CMakeLists.txt new file mode 100644 index 00000000..f3359f29 --- /dev/null +++ b/1001-1500/1390-Four-Divisors/cpp-1390/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1001-1500/1390-Four-Divisors/cpp-1390/main.cpp b/1001-1500/1390-Four-Divisors/cpp-1390/main.cpp new file mode 100644 index 00000000..a4315167 --- /dev/null +++ b/1001-1500/1390-Four-Divisors/cpp-1390/main.cpp @@ -0,0 +1,49 @@ +/// Source : https://leetcode.com/problems/four-divisors/ +/// Author : liuyubobobo +/// Time : 2020-03-21 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n * sqrt(num)) +/// Space Complexity: O(1) +class Solution { +public: + int sumFourDivisors(vector& nums) { + + int res = 0; + for(int num: nums){ + int x = 0; + if(ok(num, x)) res += x; + } + return res; + } + +private: + bool ok(int num, int& res){ + + int cnt = 2; + res += 1 + num; + for(int x = 2; x * x <= num; x ++) + if(num % x == 0){ + if(x * x == num) return false; + res += (x + num / x); + cnt += 2; + if(cnt > 4) return false; + } + return cnt == 4; + } +}; + + +int main() { + + vector nums1 = {21, 4, 7}; + cout << Solution().sumFourDivisors(nums1) << endl; + + return 0; +} diff --git a/1001-1500/1391-Check-if-There-is-a-Valid-Path-in-a-Grid/cpp-1391/CMakeLists.txt b/1001-1500/1391-Check-if-There-is-a-Valid-Path-in-a-Grid/cpp-1391/CMakeLists.txt new file mode 100644 index 00000000..64f6c751 --- /dev/null +++ b/1001-1500/1391-Check-if-There-is-a-Valid-Path-in-a-Grid/cpp-1391/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main2.cpp) \ No newline at end of file diff --git a/1001-1500/1391-Check-if-There-is-a-Valid-Path-in-a-Grid/cpp-1391/main.cpp b/1001-1500/1391-Check-if-There-is-a-Valid-Path-in-a-Grid/cpp-1391/main.cpp new file mode 100644 index 00000000..965ae0db --- /dev/null +++ b/1001-1500/1391-Check-if-There-is-a-Valid-Path-in-a-Grid/cpp-1391/main.cpp @@ -0,0 +1,88 @@ +/// Source : https://leetcode.com/problems/check-if-there-is-a-valid-path-in-a-grid/ +/// Author : liuyubobobo +/// Time : 2020-03-21 + +#include +#include +#include + +using namespace std; + + +/// DFS +/// Attention: DFS can not get AC in leetcode-cn +/// Time Complexity: O(m * n) +/// Space Complexity: O(m * n) +class Solution { + +private: + int m, n; + vector>> next = {{{0, 1},{0, -1}}, + {{1, 0}, {-1, 0}}, + {{1, 0},{0, -1}}, + {{1, 0}, {0, 1}}, + {{0, -1},{-1, 0}}, + {{-1, 0},{0, 1}}}; + +public: + bool hasValidPath(vector>& grid) { + + m = grid.size(), n = grid[0].size(); + vector> visited(m, vector(n, false)); + return dfs(grid, 0, 0, -1, -1, visited); + } + +private: + bool dfs(const vector>& grid, int x, int y, int px, int py, + vector>& visited){ + + if(in_area(px, py) && !connected(grid, x, y, px, py)) return false; + if(x == m - 1 && y == n - 1) return true; + + visited[x][y] = true; + + int v = grid[x][y] - 1; + + int nextx = x + next[v][0].first, nexty = y + next[v][0].second; + if(in_area(nextx, nexty) && !visited[nextx][nexty] && dfs(grid, nextx, nexty, x, y, visited)) + return true; + + nextx = x + next[v][1].first, nexty = y + next[v][1].second; + if(in_area(nextx, nexty) && !visited[nextx][nexty] && dfs(grid, nextx, nexty, x, y, visited)) + return true; + + return false; + } + + bool connected(const vector>& grid, int x1, int y1, int x2, int y2){ + + pair p = make_pair(x2 - x1, y2 - y1); + return next[grid[x1][y1] - 1][0] == p || next[grid[x1][y1] - 1][1] == p; + } + + bool in_area(int x, int y){ + return x >= 0 && x < m && y >= 0 && y < n; + } +}; + + +int main() { + + vector> grid1 = {{2,4,3},{6,5,2}}; + cout << Solution().hasValidPath(grid1) << endl; + // 1 + + vector> grid2 = {{1,2,1},{1,2,1}}; + cout << Solution().hasValidPath(grid2) << endl; + // 0 + + vector> grid3 = {{1,1,2}}; + cout << Solution().hasValidPath(grid3) << endl; + // 0 + + vector> grid4 = {{1,1,1,1,1,1,3}}; + cout << Solution().hasValidPath(grid4) << endl; +// 1 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1391-Check-if-There-is-a-Valid-Path-in-a-Grid/cpp-1391/main2.cpp b/1001-1500/1391-Check-if-There-is-a-Valid-Path-in-a-Grid/cpp-1391/main2.cpp new file mode 100644 index 00000000..afd5804c --- /dev/null +++ b/1001-1500/1391-Check-if-There-is-a-Valid-Path-in-a-Grid/cpp-1391/main2.cpp @@ -0,0 +1,86 @@ +/// Source : https://leetcode.com/problems/check-if-there-is-a-valid-path-in-a-grid/ +/// Author : liuyubobobo +/// Time : 2020-03-21 + +#include +#include +#include + +using namespace std; + + +/// BFS +/// Time Complexity: O(m * n) +/// Space Complexity: O(m * n) +class Solution { + +private: + int m, n; + vector>> next = {{{0, 1},{0, -1}}, + {{1, 0}, {-1, 0}}, + {{1, 0},{0, -1}}, + {{1, 0}, {0, 1}}, + {{0, -1},{-1, 0}}, + {{-1, 0},{0, 1}}}; + +public: + bool hasValidPath(vector>& grid) { + + m = grid.size(), n = grid[0].size(); + vector> visited(m, vector(n, false)); + + queue> q; + q.push(make_pair(0, 0)); + visited[0][0] = true; + while(!q.empty()){ + int x = q.front().first, y = q.front().second; + if(x == m - 1 && y == n - 1) return true; + + q.pop(); + + int v = grid[x][y] - 1; + int nextx = x + next[v][0].first, nexty = y + next[v][0].second; + if(in_area(nextx, nexty) && !visited[nextx][nexty] && connected(grid, nextx, nexty, x, y)) + visited[nextx][nexty] = true, q.push(make_pair(nextx, nexty)); + + nextx = x + next[v][1].first, nexty = y + next[v][1].second; + if(in_area(nextx, nexty) && !visited[nextx][nexty] && connected(grid, nextx, nexty, x, y)) + visited[nextx][nexty] = true, q.push(make_pair(nextx, nexty)); + } + return false; + } + +private: + bool connected(const vector>& grid, int x1, int y1, int x2, int y2){ + + pair p = make_pair(x2 - x1, y2 - y1); + int v = grid[x1][y1] - 1; + return next[v][0] == p || next[v][1] == p; + } + + bool in_area(int x, int y){ + return x >= 0 && x < m && y >= 0 && y < n; + } +}; + + +int main() { + + vector> grid1 = {{2,4,3},{6,5,2}}; + cout << Solution().hasValidPath(grid1) << endl; + // 1 + + vector> grid2 = {{1,2,1},{1,2,1}}; + cout << Solution().hasValidPath(grid2) << endl; + // 0 + + vector> grid3 = {{1,1,2}}; + cout << Solution().hasValidPath(grid3) << endl; + // 0 + + vector> grid4 = {{1,1,1,1,1,1,3}}; + cout << Solution().hasValidPath(grid4) << endl; + // 1 + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1392-Longest-Happy-Prefix/cpp-1392/CMakeLists.txt b/1001-1500/1392-Longest-Happy-Prefix/cpp-1392/CMakeLists.txt new file mode 100644 index 00000000..c0c37cc3 --- /dev/null +++ b/1001-1500/1392-Longest-Happy-Prefix/cpp-1392/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main2.cpp) \ No newline at end of file diff --git a/1001-1500/1392-Longest-Happy-Prefix/cpp-1392/main.cpp b/1001-1500/1392-Longest-Happy-Prefix/cpp-1392/main.cpp new file mode 100644 index 00000000..9fe45e5c --- /dev/null +++ b/1001-1500/1392-Longest-Happy-Prefix/cpp-1392/main.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/longest-happy-prefix/ +/// Author : liuyubobobo +/// Time : 2020-03-21 + +#include +#include + +using namespace std; + + +/// KMP-based method +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + string longestPrefix(string s) { + + int n = s.size(); + vector lps(n, 0); + + int len = 0; + for(int i = 1; i < n; i ++){ + while(len && s[i] != s[len]) + len = lps[len - 1]; + + if(s[i] == s[len]) + lps[i] = ++ len; + } + + return s.substr(0, lps.back()); + } +}; + + +int main() { + + cout << Solution().longestPrefix("level") << endl; + // l + + cout << Solution().longestPrefix("ababab") << endl; + // abab + + cout << Solution().longestPrefix("leetcodeleet") << endl; + // leet + + cout << Solution().longestPrefix("a") << endl; + // empty + + return 0; +} diff --git a/1001-1500/1392-Longest-Happy-Prefix/cpp-1392/main2.cpp b/1001-1500/1392-Longest-Happy-Prefix/cpp-1392/main2.cpp new file mode 100644 index 00000000..aceecabd --- /dev/null +++ b/1001-1500/1392-Longest-Happy-Prefix/cpp-1392/main2.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/longest-happy-prefix/ +/// Author : liuyubobobo +/// Time : 2020-03-29 + +#include +#include + +using namespace std; + + +/// Rolling Hash +/// Not very convincing that it's 100% correct +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +private: + long long MOD = 1e9 + 7; + +public: + string longestPrefix(string s) { + + int n = s.size(); + long long pre_hash = 0, post_hash = 0, pow26 = 1ll; + int reslen = 0; + for(int i = 0; i + 1 < n; i ++){ + pre_hash = (pre_hash * 26 + (s[i] - 'a')) % MOD; + post_hash = ((s[n - i - 1] - 'a') * pow26 + post_hash) % MOD; + pow26 = pow26 * 26ll % MOD; + if(pre_hash == post_hash /*&& s.substr(0, i + 1) == s.substr(n - i - 1)*/) + reslen = i + 1; + } + return s.substr(0, reslen); + } +}; + + +int main() { + + cout << Solution().longestPrefix("level") << endl; + // l + + cout << Solution().longestPrefix("ababab") << endl; + // abab + + cout << Solution().longestPrefix("leetcodeleet") << endl; + // leet + + cout << Solution().longestPrefix("a") << endl; + // empty + + return 0; +} diff --git a/1001-1500/1394-Find-Lucky-Integer-in-an-Array/cpp-1394/CMakeLists.txt b/1001-1500/1394-Find-Lucky-Integer-in-an-Array/cpp-1394/CMakeLists.txt new file mode 100644 index 00000000..9c0b049b --- /dev/null +++ b/1001-1500/1394-Find-Lucky-Integer-in-an-Array/cpp-1394/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1001-1500/1394-Find-Lucky-Integer-in-an-Array/cpp-1394/main.cpp b/1001-1500/1394-Find-Lucky-Integer-in-an-Array/cpp-1394/main.cpp new file mode 100644 index 00000000..61b23ff3 --- /dev/null +++ b/1001-1500/1394-Find-Lucky-Integer-in-an-Array/cpp-1394/main.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/find-lucky-integer-in-an-array/ +/// Author : liuyubobobo +/// Time : 2020-03-28 + +#include +#include +#include + +using namespace std; + + +/// Using Hash Map +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int findLucky(vector& arr) { + + map freq; + for(int e: arr) freq[e] ++; + + int res = -1; + for(const pair& p: freq) + if(p.first == p.second) res = max(res, p.first); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1395-Count-Number-of-Teams/cpp-1395/CMakeLists.txt b/1001-1500/1395-Count-Number-of-Teams/cpp-1395/CMakeLists.txt new file mode 100644 index 00000000..c3e75f47 --- /dev/null +++ b/1001-1500/1395-Count-Number-of-Teams/cpp-1395/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main2.cpp) \ No newline at end of file diff --git a/1001-1500/1395-Count-Number-of-Teams/cpp-1395/main.cpp b/1001-1500/1395-Count-Number-of-Teams/cpp-1395/main.cpp new file mode 100644 index 00000000..5f5794ed --- /dev/null +++ b/1001-1500/1395-Count-Number-of-Teams/cpp-1395/main.cpp @@ -0,0 +1,32 @@ +/// Source : https://leetcode.com/problems/count-number-of-teams/ +/// Author : liuyubobobo +/// Time : 2020-03-28 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n^3) +/// Space Complexity: O(1) +class Solution { +public: + int numTeams(vector& rating) { + + int res = 0; + for(int i = 0; i < rating.size(); i ++) + for(int j = i + 1; j < rating.size(); j ++) + for(int k = j + 1; k < rating.size(); k ++) + res += (rating[i] > rating[j] && rating[j] > rating[k]) || + (rating[i] < rating[j] && rating[j] < rating[k]); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1395-Count-Number-of-Teams/cpp-1395/main2.cpp b/1001-1500/1395-Count-Number-of-Teams/cpp-1395/main2.cpp new file mode 100644 index 00000000..bbbad157 --- /dev/null +++ b/1001-1500/1395-Count-Number-of-Teams/cpp-1395/main2.cpp @@ -0,0 +1,51 @@ +/// Source : https://leetcode.com/problems/count-number-of-teams/ +/// Author : liuyubobobo +/// Time : 2020-03-29 + +#include +#include + +using namespace std; + + +/// Presum-like +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { +public: + int numTeams(vector& rating) { + + int n = rating.size(); + + vector right(n, 0), left(n, 0); + for(int i = 0; i < n; i ++) + for(int j = i + 1; j < n; j ++) + right[i] += (rating[j] > rating[i]); +// for(int e: greater) cout << e << " "; cout << endl; + + for(int i = n - 1; i >= 0; i --) + for(int j = i - 1; j >= 0; j --) + left[i] += (rating[j] > rating[i]); +// for(int e: less) cout << e << " "; cout << endl; + + int res = 0; + for(int i = 0; i < n; i ++) + for(int j = i + 1; j < n; j ++) + if(rating[j] > rating[i]) res += right[j]; + + for(int i = n - 1; i >= 0; i --) + for(int j = i - 1; j >= 0; j --) + if(rating[j] > rating[i]) res += left[j]; + + return res; + } +}; + + +int main() { + + vector rating1 = {2, 5, 3, 4, 1}; + cout << Solution().numTeams(rating1) << endl; + + return 0; +} diff --git a/1001-1500/1396-Design-Underground-System/cpp-1396/CMakeLists.txt b/1001-1500/1396-Design-Underground-System/cpp-1396/CMakeLists.txt new file mode 100644 index 00000000..0b46ca4b --- /dev/null +++ b/1001-1500/1396-Design-Underground-System/cpp-1396/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1001-1500/1396-Design-Underground-System/cpp-1396/main.cpp b/1001-1500/1396-Design-Underground-System/cpp-1396/main.cpp new file mode 100644 index 00000000..d90f039e --- /dev/null +++ b/1001-1500/1396-Design-Underground-System/cpp-1396/main.cpp @@ -0,0 +1,48 @@ +/// Source : https://leetcode.com/problems/design-underground-system/ +/// Author : liuyubobobo +/// Time : 2020-05-09 + +#include +#include + +using namespace std; + + +/// Using HashMap +/// Time Complexity: init: O(1) +/// checkIn: O(1) +/// checkout: O(1) +/// getAverageTime: O(1) +/// Space Complexity: O(n^2) +class UndergroundSystem { + +private: + unordered_map> in; + unordered_map>> trip; + +public: + UndergroundSystem() {} + + void checkIn(int id, string stationName, int t) { + in[id][stationName] = t; + } + + void checkOut(int id, string stationName, int t) { + assert(in.count(id)); + trip[in[id].begin()->first][stationName].first += t - in[id].begin()->second; + trip[in[id].begin()->first][stationName].second ++; + } + + double getAverageTime(string startStation, string endStation) { + + if(trip.count(startStation) && trip[startStation].count(endStation)) + return trip[startStation][endStation].first / trip[startStation][endStation].second; + return 0.0; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1397-Find-All-Good-Strings/cpp-1397/CMakeLists.txt b/1001-1500/1397-Find-All-Good-Strings/cpp-1397/CMakeLists.txt new file mode 100644 index 00000000..2bd68909 --- /dev/null +++ b/1001-1500/1397-Find-All-Good-Strings/cpp-1397/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(cpp_1397) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1397 main.cpp) \ No newline at end of file diff --git a/1001-1500/1397-Find-All-Good-Strings/cpp-1397/main.cpp b/1001-1500/1397-Find-All-Good-Strings/cpp-1397/main.cpp new file mode 100644 index 00000000..53d015d2 --- /dev/null +++ b/1001-1500/1397-Find-All-Good-Strings/cpp-1397/main.cpp @@ -0,0 +1,106 @@ +/// Source : https://leetcode.com/problems/find-all-good-strings/ +/// Author : liuyubobobo +/// Time : 2020-04-08 + +#include +#include + +using namespace std; + + +/// Digit DP + KMP +/// Time Complexity: O(n * |evil|) +/// Space Complexity: O(n * |evil|) +class Solution { + +private: + vector lps; + int MOD = 1e9 + 7; + +public: + int findGoodStrings(int n, string s1, string s2, string evil) { + + lps = getLPS(evil); + + vector>> dp1(n, vector>(evil.size(), vector(2, -1))); + int a = dfs(0, 0, 1, evil, s1, dp1); +// cout << "a = " << a << endl; + + vector>> dp2(n, vector>(evil.size(), vector(2, -1))); + int b = dfs(0, 0, 1, evil, s2, dp2); +// cout << "b = " << b << endl; + + int res = b - a + (s1.find(evil) == string::npos); + if(res < 0) res += MOD; + return res; + } + +private: + int dfs(int index, int state, int limit, const string& evil, const string& s, + vector>>& dp){ + + if(index == s.size()) return 1; + if(dp[index][state][limit] != -1) return dp[index][state][limit]; + + char bound = limit ? s[index] : 'z'; + int res = 0; + for(char i = 'a'; i <= bound; i ++){ + if(i == evil[state] && state + 1 == evil.size()) continue; + + int next_state = 0; + if(i == evil[state]) next_state = state + 1; + else{ + next_state = state; + while(next_state){ + next_state = lps[next_state - 1]; + if(i == evil[next_state]){ + next_state ++; + break; + } + } + } + + res += dfs(index + 1, next_state, limit && i == s[index], evil, s, dp); + res %= MOD; + } + return dp[index][state][limit] = res; + } + + vector getLPS(const string& pattern){ + + vector lps(pattern.size(), 0); + + int len = 0; + for(int i = 1; i < pattern.size(); i ++){ + while(len && pattern[i] != pattern[len]) + len = lps[len - 1]; + + if(pattern[i] == pattern[len]) + lps[i] = ++ len; + } + return lps; + } +}; + + +int main() { + + cout << Solution().findGoodStrings(2, "aa", "da", "b") << endl; + // 51 + + cout << Solution().findGoodStrings(8, "leetcode", "leetgoes", "leet") << endl; + // 0 + + cout << Solution().findGoodStrings(2, "gx", "gz", "x") << endl; + // 2 + + cout << Solution().findGoodStrings(8, "pzdanyao", "wgpmtywi", "sdka") << endl; + // 500543753 + + cout << Solution().findGoodStrings(81, "ithrfztwiwvtkyzgufoxtofywlyhwwjdmpfbtyvpqtkitfhhoyhjrmoipdcaaksgfuzaersicuarqbyng", + "uxmmpikhthamnhicxsseiqeeojmdgvchkdbzagbwxovdwdmpmfhosgwksgbzpmjmyeamvbmeojbbeidca", + "uexivgvomkuiiuuhhbszsflntwruqblr"); + + + return 0; +} diff --git a/1001-1500/1399-Count-Largest-Group/cpp-1399/CMakeLists.txt b/1001-1500/1399-Count-Largest-Group/cpp-1399/CMakeLists.txt new file mode 100644 index 00000000..c052eb3c --- /dev/null +++ b/1001-1500/1399-Count-Largest-Group/cpp-1399/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(cpp_1399) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1399 main.cpp) \ No newline at end of file diff --git a/1001-1500/1399-Count-Largest-Group/cpp-1399/main.cpp b/1001-1500/1399-Count-Largest-Group/cpp-1399/main.cpp new file mode 100644 index 00000000..bdb6bdb1 --- /dev/null +++ b/1001-1500/1399-Count-Largest-Group/cpp-1399/main.cpp @@ -0,0 +1,44 @@ +/// Source : https://leetcode.com/problems/count-largest-group/ +/// Author : liuyubobobo +/// Time : 2020-04-04 + +#include +#include + +using namespace std; + + +/// Using Hash Map +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int countLargestGroup(int n) { + + map group; + for(int i = 1; i <= n; i ++) + group[sum(i)] ++; + + map res; + for(const pair& p: group) + res[p.second] ++; + + return res.rbegin()->second; + } + +private: + int sum(int x){ + int res = 0; + while(x) res += x % 10, x /= 10; + return res; + } +}; + + +int main() { + + cout << Solution().countLargestGroup(13) << endl; + // 4 + + return 0; +} diff --git a/1001-1500/1400-Construct-K-Palindrome-Strings/cpp-1400/CMakeLists.txt b/1001-1500/1400-Construct-K-Palindrome-Strings/cpp-1400/CMakeLists.txt new file mode 100644 index 00000000..12c25b89 --- /dev/null +++ b/1001-1500/1400-Construct-K-Palindrome-Strings/cpp-1400/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(cpp_1400) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1400 main.cpp) \ No newline at end of file diff --git a/1001-1500/1400-Construct-K-Palindrome-Strings/cpp-1400/main.cpp b/1001-1500/1400-Construct-K-Palindrome-Strings/cpp-1400/main.cpp new file mode 100644 index 00000000..c8cb806d --- /dev/null +++ b/1001-1500/1400-Construct-K-Palindrome-Strings/cpp-1400/main.cpp @@ -0,0 +1,45 @@ +/// Source : https://leetcode.com/problems/construct-k-palindrome-strings/ +/// Author : liuyubobobo +/// Time : 2020-04-04 + +#include +#include + +using namespace std; + + +/// Using Hash Map +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + bool canConstruct(string s, int k) { + + if(s.size() < k) return false; + if(s.size() == k) return true; + + vector freq(26, 0); + for(char c: s) freq[c - 'a'] ++; + + int odd = 0; + for(int e: freq) if(e % 2) odd ++; + + while(odd && k) k --, odd --; + return odd < 1; + } +}; + + +int main() { + + cout << Solution().canConstruct("annabelle", 2) << endl; + // true + + cout << Solution().canConstruct("leetcode", 3) << endl; + // false + + cout << Solution().canConstruct("abcdefghijklmnopqrstuvwxyz", 25) << endl; + // false + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1401-Circle-and-Rectangle-Overlapping/cpp-1401/CMakeLists.txt b/1001-1500/1401-Circle-and-Rectangle-Overlapping/cpp-1401/CMakeLists.txt new file mode 100644 index 00000000..b20c5a4e --- /dev/null +++ b/1001-1500/1401-Circle-and-Rectangle-Overlapping/cpp-1401/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(cpp_1401) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1401 main2.cpp) \ No newline at end of file diff --git a/1001-1500/1401-Circle-and-Rectangle-Overlapping/cpp-1401/main.cpp b/1001-1500/1401-Circle-and-Rectangle-Overlapping/cpp-1401/main.cpp new file mode 100644 index 00000000..8c4d73ff --- /dev/null +++ b/1001-1500/1401-Circle-and-Rectangle-Overlapping/cpp-1401/main.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/circle-and-rectangle-overlapping/ +/// Author : liuyubobobo +/// Time : 2020-04-08 + +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(N) +/// Space Complexity: O(1) +class Solution { +public: + bool checkOverlap(int radius, int x_center, int y_center, int x1, int y1, int x2, int y2) { + + if(x_center >= x1 && x_center <= x2 && y_center >= y1 && y_center <= y2) return true; + + int N = 1000000; + for(int i = 0; i < N; i ++){ + if(in_circle(x1 + (double)i / N * (x2 - x1), y2, x_center, y_center, radius)) + return true; + if(in_circle(x2, y2 - (double)i / N * (y2 - y1), x_center, y_center, radius)) + return true; + if(in_circle(x2 - (double)i / N * (x2 - x1), y1, x_center, y_center, radius)) + return true; + if(in_circle(x1, y1 + (double)i / N * (y2 - y1), x_center, y_center, radius)) + return true; + } + return false; + } + +private: + bool in_circle(double tx, double ty, double cx, double cy, double r){ + return (cx - tx) * (cx - tx) + (cy - ty) * (cy - ty) <= r * r + 1e-8; + } +}; + + +int main() { + + cout << Solution().checkOverlap(2, 2, 1, 4, 1, 5, 5) << endl; + // true + + return 0; +} diff --git a/1001-1500/1401-Circle-and-Rectangle-Overlapping/cpp-1401/main2.cpp b/1001-1500/1401-Circle-and-Rectangle-Overlapping/cpp-1401/main2.cpp new file mode 100644 index 00000000..9cdcbe95 --- /dev/null +++ b/1001-1500/1401-Circle-and-Rectangle-Overlapping/cpp-1401/main2.cpp @@ -0,0 +1,39 @@ +/// Source : https://leetcode.com/problems/circle-and-rectangle-overlapping/ +/// Author : liuyubobobo +/// Time : 2020-04-08 + +#include + +using namespace std; + + +/// Recenter the circle and use Mathematics +/// Time Complexity: O(1) +/// Space Complexity: O(1) +class Solution { +public: + bool checkOverlap(int r, int x_center, int y_center, int x1, int y1, int x2, int y2) { + + x1 -= x_center, y1 -= y_center; + x2 -= x_center, y2 -= y_center; + + int minx = 0; + if(x1 >= 0 && x2 >= 0) minx = x1; + else if(x1 <= 0 && x2 <= 0) minx = x2; + + int miny = 0; + if(y1 >= 0 && y2 >= 0) miny = y1; + else if(y1 <= 0 && y2 <= 0) miny = y2; + + return minx * minx + miny * miny <= r * r; + } +}; + + +int main() { + + cout << Solution().checkOverlap(2, 2, 1, 4, 1, 5, 5) << endl; + // true + + return 0; +} diff --git a/1001-1500/1402-Reducing-Dishes/cpp-1402/CMakeLists.txt b/1001-1500/1402-Reducing-Dishes/cpp-1402/CMakeLists.txt new file mode 100644 index 00000000..2d8b885a --- /dev/null +++ b/1001-1500/1402-Reducing-Dishes/cpp-1402/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(cpp_1402) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1402 main3.cpp) \ No newline at end of file diff --git a/1001-1500/1402-Reducing-Dishes/cpp-1402/main.cpp b/1001-1500/1402-Reducing-Dishes/cpp-1402/main.cpp new file mode 100644 index 00000000..de2bba3c --- /dev/null +++ b/1001-1500/1402-Reducing-Dishes/cpp-1402/main.cpp @@ -0,0 +1,42 @@ +/// Source : https://leetcode.com/problems/reducing-dishes/ +/// Author : liuyubobobo +/// Time : 2020-04-11 + +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(nlogn + n^2) +/// Space Complexity: O(n^2) +class Solution { +public: + int maxSatisfaction(vector& satisfaction) { + + sort(satisfaction.begin(), satisfaction.end()); + + int n = satisfaction.size(); + vector> dp(n, vector(n + 1, INT_MIN)); + return max(0, dfs(satisfaction, 0, 1, dp)); + } + +private: + int dfs(const vector& v, int index, int t, vector>& dp){ + + if(index == v.size()) return 0; + if(dp[index][t] != INT_MIN) return dp[index][t]; + return dp[index][t] = max(t * v[index] + dfs(v, index + 1, t + 1, dp), + dfs(v, index + 1, t, dp)); + } +}; + + +int main() { + + vector nums1 = {-1,-8,0,5,-9}; + cout << Solution().maxSatisfaction(nums1) << endl; + + return 0; +} diff --git a/1001-1500/1402-Reducing-Dishes/cpp-1402/main2.cpp b/1001-1500/1402-Reducing-Dishes/cpp-1402/main2.cpp new file mode 100644 index 00000000..4939c1f6 --- /dev/null +++ b/1001-1500/1402-Reducing-Dishes/cpp-1402/main2.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/reducing-dishes/ +/// Author : liuyubobobo +/// Time : 2020-04-11 + +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(nlogn + n^2) +/// Space Complexity: O(n^2) +class Solution { +public: + int maxSatisfaction(vector& satisfaction) { + + sort(satisfaction.begin(), satisfaction.end()); + + int n = satisfaction.size(); + vector> dp(n, vector(n + 1, INT_MIN)); + for(int i = 0; i < n; i ++) dp[i][n] = satisfaction[i] * n; + + for(int t = n - 1; t > 0; t --){ + dp[n - 1][t] = satisfaction[n - 1] * t; + for(int i = n - 2; i >= 0; i --) + dp[i][t] = max(satisfaction[i] * t + dp[i + 1][t + 1], dp[i + 1][t]); + } + return max(0, dp[0][1]); + } +}; + + +int main() { + + vector nums1 = {-1,-8,0,5,-9}; + cout << Solution().maxSatisfaction(nums1) << endl; + + return 0; +} diff --git a/1001-1500/1402-Reducing-Dishes/cpp-1402/main3.cpp b/1001-1500/1402-Reducing-Dishes/cpp-1402/main3.cpp new file mode 100644 index 00000000..4314a664 --- /dev/null +++ b/1001-1500/1402-Reducing-Dishes/cpp-1402/main3.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/reducing-dishes/ +/// Author : liuyubobobo +/// Time : 2020-04-11 + +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(nlogn + n) +/// Space Complexity: O(1) +class Solution { +public: + int maxSatisfaction(vector& satisfaction) { + + sort(satisfaction.begin(), satisfaction.end(), greater()); + + int n = satisfaction.size(); + int res = 0, sum = 0; + for(int e: satisfaction){ + if(sum + e > 0) sum += e, res += sum; + else break; + } + return res; + } +}; + + +int main() { + + vector nums1 = {-1,-8,0,5,-9}; + cout << Solution().maxSatisfaction(nums1) << endl; + + return 0; +} diff --git a/1001-1500/1403-Minimum-Subsequence-in-Non-Increasing-Order/cpp-1403/CMakeLists.txt b/1001-1500/1403-Minimum-Subsequence-in-Non-Increasing-Order/cpp-1403/CMakeLists.txt new file mode 100644 index 00000000..9c0b049b --- /dev/null +++ b/1001-1500/1403-Minimum-Subsequence-in-Non-Increasing-Order/cpp-1403/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1001-1500/1403-Minimum-Subsequence-in-Non-Increasing-Order/cpp-1403/main.cpp b/1001-1500/1403-Minimum-Subsequence-in-Non-Increasing-Order/cpp-1403/main.cpp new file mode 100644 index 00000000..11167f57 --- /dev/null +++ b/1001-1500/1403-Minimum-Subsequence-in-Non-Increasing-Order/cpp-1403/main.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/minimum-subsequence-in-non-increasing-order/ +/// Author : liuyubobobo +/// Time : 2020-04-04 + +#include +#include +#include + +using namespace std; + + +/// Sorting and Greedy +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + vector minSubsequence(vector& nums) { + + int sum = accumulate(nums.begin(), nums.end(), 0); + + sort(nums.begin(), nums.end(), greater()); + + vector res; + int cur = 0; + for(int e: nums){ + cur += e; + res.push_back(e); + if(cur > sum - cur) break; + } + return res; + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << " "; cout << endl; +} + +int main() { + + vector nums1 = {4, 3, 10, 9, 8}; + print_vec(Solution().minSubsequence(nums1)); + // 10 9 + + vector nums2 = {4, 4, 7, 6, 7}; + print_vec(Solution().minSubsequence(nums2)); + // 7 7 6 + + vector nums3 = {6}; + print_vec(Solution().minSubsequence(nums3)); + // 6 + + return 0; +} diff --git a/1001-1500/1404-Number-of-Steps-to-Reduce-a-Number-in-Binary-Representation-to-One/cpp-1404/CMakeLists.txt b/1001-1500/1404-Number-of-Steps-to-Reduce-a-Number-in-Binary-Representation-to-One/cpp-1404/CMakeLists.txt new file mode 100644 index 00000000..f3359f29 --- /dev/null +++ b/1001-1500/1404-Number-of-Steps-to-Reduce-a-Number-in-Binary-Representation-to-One/cpp-1404/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1001-1500/1404-Number-of-Steps-to-Reduce-a-Number-in-Binary-Representation-to-One/cpp-1404/main.cpp b/1001-1500/1404-Number-of-Steps-to-Reduce-a-Number-in-Binary-Representation-to-One/cpp-1404/main.cpp new file mode 100644 index 00000000..abdae463 --- /dev/null +++ b/1001-1500/1404-Number-of-Steps-to-Reduce-a-Number-in-Binary-Representation-to-One/cpp-1404/main.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/number-of-steps-to-reduce-a-number-in-binary-representation-to-one/ +/// Author : liuyubobobo +/// Time : 2020-04-04 + +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + int numSteps(string s) { + + int res = 0; + while(s != "1"){ + if(s.back() == '1') s = addone(s); + else s = s.substr(0, s.size() - 1); + res ++; + } + return res; + } + +private: + string addone(string s){ + + reverse(s.begin(), s.end()); + s[0] += 1; + int carry = 0; + for(int i = 0; i < s.size(); i ++){ + s[i] += carry; + if(s[i] == '2') s[i] = '0', carry = 1; + else carry = 0; + } + + if(carry) s += '1'; + reverse(s.begin(), s.end()); + return s; + } +}; + + +int main() { + + cout << Solution().numSteps("1101") << endl; + // 6 + + cout << Solution().numSteps("10") << endl; + // 1 + + return 0; +} diff --git a/1001-1500/1405-Longest-Happy-String/cpp-1405/CMakeLists.txt b/1001-1500/1405-Longest-Happy-String/cpp-1405/CMakeLists.txt new file mode 100644 index 00000000..64f6c751 --- /dev/null +++ b/1001-1500/1405-Longest-Happy-String/cpp-1405/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main2.cpp) \ No newline at end of file diff --git a/1001-1500/1405-Longest-Happy-String/cpp-1405/main.cpp b/1001-1500/1405-Longest-Happy-String/cpp-1405/main.cpp new file mode 100644 index 00000000..40a7ccc0 --- /dev/null +++ b/1001-1500/1405-Longest-Happy-String/cpp-1405/main.cpp @@ -0,0 +1,101 @@ +/// Source : https://leetcode.com/problems/longest-happy-string/ +/// Author : liuyubobobo +/// Time : 2020-04-08 + +#include +#include +#include +#include + +using namespace std; + + +/// Generate a template and fill the redundant most characters +/// Time Complexity: O(a + b + c) +/// Space Complexity: O(1) +class Solution { +public: + string longestDiverseString(int a, int b, int c) { + + vector> v; + v.push_back(make_pair(a, 'a')); + v.push_back(make_pair(b, 'b')); + v.push_back(make_pair(c, 'c')); + + string t = generate_template(v); +// cout << "template = "<< t << endl; + + map left; + for(const pair& p: v) + left[p.second] = p.first; + + string res = ""; + for(char ch: t){ + res += ch; + if(left[ch]) res += ch, left[ch] --; + } + return res; + } + +private: + string generate_template(vector>& v){ + + sort(v.begin(), v.end(), greater>()); + + string tres = ""; + + /// if a >= b >= c, then, b = 0 + while(v[0].first){ + tres += v[0].second; + v[0].first --; + if(v[1].first) tres += v[1].second, v[1].first --; + else if(v[2].first) tres += v[2].second, v[2].first --; + else break; + } + assert(v[1].first == 0); + + // deal with c + string res = ""; + int i = 0; + for(i = 0; i < tres.size() && v[2].first; i ++) + if(tres[i] != v[2].second) res += v[2].second, res += tres[i], v[2].first --; + else break; + return res + tres.substr(i); + } +}; + + +int main() { + + cout << Solution().longestDiverseString(1, 1, 7) << endl; + cout << "ccaccbcc" << endl; + // ccaccbcc + cout << endl; + + cout << Solution().longestDiverseString(2, 2, 1) << endl; + cout << "aabbc" << endl; + // aabbc + cout << endl; + + cout << Solution().longestDiverseString(7, 1, 0) << endl; + cout << "aabaa" << endl; + // aabaa + cout << endl; + + cout << Solution().longestDiverseString(0, 8, 11) << endl; + cout << "ccbccbbccbbccbbccbc" << endl; + // ccbccbbccbbccbbccbc + cout << endl; + + cout << Solution().longestDiverseString(4, 4, 3) << endl; + cout << "aabbccaabbc" << endl; + // aabbccaabbc + cout << endl; + + cout << Solution().longestDiverseString(1, 1, 7) << endl; + cout << "ccaccbcc" << endl; + // ccaccbcc + cout << endl; + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1405-Longest-Happy-String/cpp-1405/main2.cpp b/1001-1500/1405-Longest-Happy-String/cpp-1405/main2.cpp new file mode 100644 index 00000000..c43dcd57 --- /dev/null +++ b/1001-1500/1405-Longest-Happy-String/cpp-1405/main2.cpp @@ -0,0 +1,90 @@ +/// Source : https://leetcode.com/problems/longest-happy-string/ +/// Author : liuyubobobo +/// Time : 2020-04-08 + +#include +#include +#include +#include + +using namespace std; + + +/// Greedy with a priority queue +/// Time Complexity: O(a + b + c) +/// Space Complexity: O(1) +class Solution { +public: + string longestDiverseString(int a, int b, int c) { + + priority_queue> pq; + if(a) pq.push(make_pair(a, 'a')); + if(b) pq.push(make_pair(b, 'b')); + if(c) pq.push(make_pair(c, 'c')); + + string res = ""; + while(!pq.empty()){ + char a = pq.top().second; + int aleft = pq.top().first; + pq.pop(); + + if(res.size() && res.back() == a) break; + + int anum = min(aleft, 2); + res += string(anum, a); + aleft -= anum; + + if(pq.empty()) break; + + char b = pq.top().second; + int bleft = pq.top().first; + pq.pop(); + + if(bleft){ + int bnum = (bleft >= 2 && aleft < bleft) ? 2 : 1; + res += string(bnum, b); + bleft -= bnum; + } + + if(aleft) pq.push(make_pair(aleft, a)); + if(bleft) pq.push(make_pair(bleft, b)); + } + return res; + } +}; + + +int main() { + + cout << Solution().longestDiverseString(1, 1, 7) << endl; + cout << "ccaccbcc" << endl; + // ccaccbcc + cout << endl; + + cout << Solution().longestDiverseString(2, 2, 1) << endl; + cout << "aabbc" << endl; + // aabbc + cout << endl; + + cout << Solution().longestDiverseString(7, 1, 0) << endl; + cout << "aabaa" << endl; + // aabaa + cout << endl; + + cout << Solution().longestDiverseString(0, 8, 11) << endl; + cout << "ccbccbbccbbccbbccbc" << endl; + // ccbccbbccbbccbbccbc + cout << endl; + + cout << Solution().longestDiverseString(4, 4, 3) << endl; + cout << "aabbccaabbc" << endl; + // aabbccaabbc + cout << endl; + + cout << Solution().longestDiverseString(1, 1, 7) << endl; + cout << "ccaccbcc" << endl; + // ccaccbcc + cout << endl; + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1406-Stone-Game-III/cpp-1406/CMakeLists.txt b/1001-1500/1406-Stone-Game-III/cpp-1406/CMakeLists.txt new file mode 100644 index 00000000..7cd48a0b --- /dev/null +++ b/1001-1500/1406-Stone-Game-III/cpp-1406/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main4.cpp) \ No newline at end of file diff --git a/1001-1500/1406-Stone-Game-III/cpp-1406/main.cpp b/1001-1500/1406-Stone-Game-III/cpp-1406/main.cpp new file mode 100644 index 00000000..1b4d1f88 --- /dev/null +++ b/1001-1500/1406-Stone-Game-III/cpp-1406/main.cpp @@ -0,0 +1,74 @@ +/// Source : https://leetcode.com/problems/stone-game-iii/ +/// Author : liuyubobobo +/// Time : 2020-04-04 + +#include +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + string stoneGameIII(vector& stoneValue) { + + int n = stoneValue.size(); + + vector postsum(n + 1, 0); + for(int i = n - 1; i >= 0; i --) postsum[i] = postsum[i + 1] + stoneValue[i]; + + vector> dp(2, vector(stoneValue.size(), INT_MIN)); + int x = dfs(stoneValue, 0, 0, dp, postsum); +// cout << x << endl; + if(x > postsum[0] - x) return "Alice"; + else if(x < postsum[0] - x) return "Bob"; + return "Tie"; + } + +private: + int dfs(const vector& values, int index, int player, + vector>& dp, const vector& postsum){ + + if(index >= values.size()) return 0; + if(dp[player][index] != INT_MIN) return dp[player][index]; + + int sum = 0, res = INT_MIN; + for(int i = 0; i < 3 && index + i < values.size(); i ++){ + sum += values[index + i]; + int tres = sum + postsum[index + i + 1] - dfs(values, index + i + 1, 1 - player, dp, postsum); +// cout << "playe = " << player << " ; index = " << index << " : " << tres << endl; + res = max(res, tres); + } + return dp[player][index] = res; + } +}; + + +int main() { + + vector values1 = {1, 2, 3, 7}; + cout << Solution().stoneGameIII(values1) << endl; + // Bob + + vector values2 = {1, 2, 3, -9}; + cout << Solution().stoneGameIII(values2) << endl; + // Alice + + vector values3 = {1, 2, 3, 6}; + cout << Solution().stoneGameIII(values3) << endl; + // Tie + + vector values4 = {1,2,3,-1,-2,-3,7}; + cout << Solution().stoneGameIII(values4) << endl; + // Alice + + vector values5 = {-1, -2, -3}; + cout << Solution().stoneGameIII(values5) << endl; + // Tie + + return 0; +} diff --git a/1001-1500/1406-Stone-Game-III/cpp-1406/main2.cpp b/1001-1500/1406-Stone-Game-III/cpp-1406/main2.cpp new file mode 100644 index 00000000..aa3e2edf --- /dev/null +++ b/1001-1500/1406-Stone-Game-III/cpp-1406/main2.cpp @@ -0,0 +1,68 @@ +/// Source : https://leetcode.com/problems/stone-game-iii/ +/// Author : liuyubobobo +/// Time : 2020-04-08 + +#include +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + string stoneGameIII(vector& stoneValue) { + + int n = stoneValue.size(); + + vector postsum(n + 1, 0); + for(int i = n - 1; i >= 0; i --) postsum[i] = postsum[i + 1] + stoneValue[i]; + + vector> dp(2, vector(n + 1, INT_MIN)); + dp[0][n] = dp[1][n] = 0; + dp[0][n - 1] = dp[1][n - 1] = stoneValue[n - 1]; + + for(int start = n - 2; start >= 0; start --) + for(int player = 0; player <= 1; player ++){ + int sum = 0; + for(int i = 0; i < 3 && start + i < n; i ++){ + sum += stoneValue[start + i]; + dp[player][start] = max(dp[player][start], + sum + postsum[start + i + 1] - dp[1 - player][start + i + 1]); + } + } + + if(dp[0][0] > postsum[0] - dp[0][0]) return "Alice"; + else if(dp[0][0] < postsum[0] - dp[0][0]) return "Bob"; + return "Tie"; + } +}; + + +int main() { + + vector values1 = {1, 2, 3, 7}; + cout << Solution().stoneGameIII(values1) << endl; + // Bob + + vector values2 = {1, 2, 3, -9}; + cout << Solution().stoneGameIII(values2) << endl; + // Alice + + vector values3 = {1, 2, 3, 6}; + cout << Solution().stoneGameIII(values3) << endl; + // Tie + + vector values4 = {1,2,3,-1,-2,-3,7}; + cout << Solution().stoneGameIII(values4) << endl; + // Alice + + vector values5 = {-1, -2, -3}; + cout << Solution().stoneGameIII(values5) << endl; + // Tie + + return 0; +} diff --git a/1001-1500/1406-Stone-Game-III/cpp-1406/main3.cpp b/1001-1500/1406-Stone-Game-III/cpp-1406/main3.cpp new file mode 100644 index 00000000..df6c6adf --- /dev/null +++ b/1001-1500/1406-Stone-Game-III/cpp-1406/main3.cpp @@ -0,0 +1,62 @@ +/// Source : https://leetcode.com/problems/stone-game-iii/ +/// Author : liuyubobobo +/// Time : 2020-04-08 + +#include +#include +#include + +using namespace std; + + +/// One dimensional DP without postsum +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + string stoneGameIII(vector& stoneValue) { + + int n = stoneValue.size(); + vector dp(n + 1, INT_MIN); + dp[n] = 0; + dp[n - 1] = stoneValue[n - 1]; + + for(int start = n - 2; start >= 0; start --){ + int sum = 0; + for(int i = 0; i < 3 && start + i < n; i ++){ + sum += stoneValue[start + i]; + dp[start] = max(dp[start], sum - dp[start + i + 1]); + } + } + + if(dp[0] > 0) return "Alice"; + else if(dp[0] < 0) return "Bob"; + return "Tie"; + } +}; + + +int main() { + + vector values1 = {1, 2, 3, 7}; + cout << Solution().stoneGameIII(values1) << endl; + // Bob + + vector values2 = {1, 2, 3, -9}; + cout << Solution().stoneGameIII(values2) << endl; + // Alice + + vector values3 = {1, 2, 3, 6}; + cout << Solution().stoneGameIII(values3) << endl; + // Tie + + vector values4 = {1,2,3,-1,-2,-3,7}; + cout << Solution().stoneGameIII(values4) << endl; + // Alice + + vector values5 = {-1, -2, -3}; + cout << Solution().stoneGameIII(values5) << endl; + // Tie + + return 0; +} diff --git a/1001-1500/1406-Stone-Game-III/cpp-1406/main4.cpp b/1001-1500/1406-Stone-Game-III/cpp-1406/main4.cpp new file mode 100644 index 00000000..bca74bb9 --- /dev/null +++ b/1001-1500/1406-Stone-Game-III/cpp-1406/main4.cpp @@ -0,0 +1,61 @@ +/// Source : https://leetcode.com/problems/stone-game-iii/ +/// Author : liuyubobobo +/// Time : 2020-04-08 + +#include +#include +#include + +using namespace std; + + +/// One dimensional DP without postsum +/// Space Optimized +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + string stoneGameIII(vector& stoneValue) { + + int n = stoneValue.size(); + vector dp(4, 0); + for(int start = n - 1; start >= 0; start --){ + int sum = 0; + dp[start % 4] = INT_MIN; + for(int i = 0; i < 3 && start + i < n; i ++){ + sum += stoneValue[start + i]; + dp[start % 4] = max(dp[start % 4], sum - (start + i + 1 < n ? dp[(start + i + 1) % 4] : 0)); + } + } + + if(dp[0] > 0) return "Alice"; + else if(dp[0] < 0) return "Bob"; + return "Tie"; + } +}; + + +int main() { + + vector values1 = {1, 2, 3, 7}; + cout << Solution().stoneGameIII(values1) << endl; + // Bob + + vector values2 = {1, 2, 3, -9}; + cout << Solution().stoneGameIII(values2) << endl; + // Alice + + vector values3 = {1, 2, 3, 6}; + cout << Solution().stoneGameIII(values3) << endl; + // Tie + + vector values4 = {1,2,3,-1,-2,-3,7}; + cout << Solution().stoneGameIII(values4) << endl; + // Alice + + vector values5 = {-1, -2, -3}; + cout << Solution().stoneGameIII(values5) << endl; + // Tie + + return 0; +} diff --git a/1001-1500/1408-String-Matching-in-an-Array/cpp-1408/CMakeLists.txt b/1001-1500/1408-String-Matching-in-an-Array/cpp-1408/CMakeLists.txt new file mode 100644 index 00000000..9c0b049b --- /dev/null +++ b/1001-1500/1408-String-Matching-in-an-Array/cpp-1408/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1001-1500/1408-String-Matching-in-an-Array/cpp-1408/main.cpp b/1001-1500/1408-String-Matching-in-an-Array/cpp-1408/main.cpp new file mode 100644 index 00000000..74b16dce --- /dev/null +++ b/1001-1500/1408-String-Matching-in-an-Array/cpp-1408/main.cpp @@ -0,0 +1,44 @@ +/// Source : https://leetcode.com/problems/string-matching-in-an-array/ +/// Author : liuyubobobo +/// Time : 2020-04-11 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n^2 * |word|) +/// Space Complexity: O(1) +class Solution { +public: + vector stringMatching(vector& words) { + + vector res; + for(int i = 0; i < words.size(); i ++){ + + for(int j = 0; j < words.size(); j ++) + if(i != j){ + if(words[i].size() <= words[j].size() && words[j].find(words[i]) != string::npos){ + res.push_back(words[i]); + break; + } + } + } + return res; + } +}; + + +void print_vec(const vector& vec){ + for(const string& e: vec) cout << e << " "; cout << endl; +} + +int main() { + + vector words1 = {"mass","as","hero","superhero"}; + print_vec(Solution().stringMatching(words1)); + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1409-Queries-on-a-Permutation-With-Key/cpp-1409/CMakeLists.txt b/1001-1500/1409-Queries-on-a-Permutation-With-Key/cpp-1409/CMakeLists.txt new file mode 100644 index 00000000..f3359f29 --- /dev/null +++ b/1001-1500/1409-Queries-on-a-Permutation-With-Key/cpp-1409/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1001-1500/1409-Queries-on-a-Permutation-With-Key/cpp-1409/main.cpp b/1001-1500/1409-Queries-on-a-Permutation-With-Key/cpp-1409/main.cpp new file mode 100644 index 00000000..b1dc71c3 --- /dev/null +++ b/1001-1500/1409-Queries-on-a-Permutation-With-Key/cpp-1409/main.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/queries-on-a-permutation-with-key/ +/// Author : liuyubobobo +/// Time : 2020-04-11 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(m^2) +/// Space Complexity: O(m) +class Solution { +public: + vector processQueries(vector& queries, int m) { + + vector p(m); + for(int i = 1; i <= m; i ++) p[i - 1] = i; + + vector res; + for(int q: queries){ + + int i = 0; + for(; i < m; i ++) if(p[i] == q){res.push_back(i); break;} + for(int j = i - 1; j >= 0; j --) p[j + 1] = p[j]; + p[0] = q; + } + return res; + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << " "; cout << endl; +} + +int main() { + + vector q1 = {3, 1, 2, 1}; + print_vec(Solution().processQueries(q1, 5)); + // 2 1 2 1 + + vector q2 = {4, 1, 2, 2}; + print_vec(Solution().processQueries(q2, 4)); + // 3 1 2 0 + + vector q3 = {7,5,5,8,3}; + print_vec(Solution().processQueries(q3, 8)); + // 6,5,0,7,5 + + return 0; +} diff --git a/1001-1500/1410-HTML-Entity-Parser/cpp-1410/CMakeLists.txt b/1001-1500/1410-HTML-Entity-Parser/cpp-1410/CMakeLists.txt new file mode 100644 index 00000000..0b46ca4b --- /dev/null +++ b/1001-1500/1410-HTML-Entity-Parser/cpp-1410/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1001-1500/1410-HTML-Entity-Parser/cpp-1410/main.cpp b/1001-1500/1410-HTML-Entity-Parser/cpp-1410/main.cpp new file mode 100644 index 00000000..93ef39d4 --- /dev/null +++ b/1001-1500/1410-HTML-Entity-Parser/cpp-1410/main.cpp @@ -0,0 +1,45 @@ +/// Source : https://leetcode.com/problems/html-entity-parser/ +/// Author : liuyubobobo +/// Time : 2020-04-11 + +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(|text|) +/// Space Complexity: O(|text|) +class Solution { +public: + string entityParser(string text) { + + string res = ""; + for(int i = 0; i < text.size(); ) + if(text[i] == '&'){ + if(i + 5 < text.size() && text.substr(i, 6) == """) + res += '"', i += 6; + else if(i + 5 < text.size() && text.substr(i, 6) == "'") + res += '\'', i += 6; + else if(i + 4 < text.size() && text.substr(i, 5) == "&") + res += '&', i += 5; + else if(i + 3 < text.size() && text.substr(i, 4) == ">") + res += '>', i += 4; + else if(i + 3 < text.size() && text.substr(i, 4) == "<") + res += '<', i += 4; + else if(i + 6 < text.size() && text.substr(i, 7) == "⁄") + res += '/', i += 7; + else res += text[i], i ++; + } + else res += text[i], i ++; + return res; + } +}; + + +int main() { + + cout << Solution().entityParser("& is an HTML entity but &ambassador; is not.") << endl; + + return 0; +} diff --git a/1001-1500/1411-Number-of-Ways-to-Paint-Nx3-Grid/cpp-1411/CMakeLists.txt b/1001-1500/1411-Number-of-Ways-to-Paint-Nx3-Grid/cpp-1411/CMakeLists.txt new file mode 100644 index 00000000..7cd48a0b --- /dev/null +++ b/1001-1500/1411-Number-of-Ways-to-Paint-Nx3-Grid/cpp-1411/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.15) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main4.cpp) \ No newline at end of file diff --git a/1001-1500/1411-Number-of-Ways-to-Paint-Nx3-Grid/cpp-1411/main.cpp b/1001-1500/1411-Number-of-Ways-to-Paint-Nx3-Grid/cpp-1411/main.cpp new file mode 100644 index 00000000..76595562 --- /dev/null +++ b/1001-1500/1411-Number-of-Ways-to-Paint-Nx3-Grid/cpp-1411/main.cpp @@ -0,0 +1,67 @@ +/// Source : https://leetcode.com/problems/number-of-ways-to-paint-n-3-grid/ +/// Author : liuyubobobo +/// Time : 2020-04-11 + +#include +#include + +using namespace std; + + +/// State Compression and Memory Search +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +private: + int MOD = 1e9 + 7; + +public: + int numOfWays(int n) { + + vector> dp(n, vector(27, -1)); + + int res = 0; + for(int i = 0; i < 27; i ++){ + int a = i % 3, b = i / 3 % 3, c = i / 9; + if(a != b && b != c) + res += dfs(1, i, n, dp), res %= MOD; + } + return res; + } + +private: + int dfs(int index, int state, int n, vector>& dp){ + + if(index == n) return 1; + if(dp[index][state] != -1) return dp[index][state]; + + int a = state % 3, b = state / 3 % 3, c = state / 9; + + int res = 0; + for(int i = 0; i < 27; i ++){ + int a2 = i % 3, b2 = i / 3 % 3, c2 = i / 9; + if(a2 != a && b2 != b && c2 != c && a2 != b2 && b2 != c2) + res += dfs(index + 1, i, n, dp), res %= MOD; + } + return dp[index][state] = res; + } +}; + + +int main() { + + cout << Solution().numOfWays(2) << endl; + // 54 + + cout << Solution().numOfWays(3) << endl; + // 246 + + cout << Solution().numOfWays(7) << endl; + // 106494 + + cout << Solution().numOfWays(5000) << endl; + // 30228214 + + return 0; +} diff --git a/1001-1500/1411-Number-of-Ways-to-Paint-Nx3-Grid/cpp-1411/main2.cpp b/1001-1500/1411-Number-of-Ways-to-Paint-Nx3-Grid/cpp-1411/main2.cpp new file mode 100644 index 00000000..412edf5c --- /dev/null +++ b/1001-1500/1411-Number-of-Ways-to-Paint-Nx3-Grid/cpp-1411/main2.cpp @@ -0,0 +1,63 @@ +/// Source : https://leetcode.com/problems/number-of-ways-to-paint-n-3-grid/ +/// Author : liuyubobobo +/// Time : 2020-04-14 + +#include +#include + +using namespace std; + + +/// State Compression and DP +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +private: + int MOD = 1e9 + 7; + +public: + int numOfWays(int n) { + + vector> dp(n, vector(27, 0)); + for(int state = 0; state < 27; state ++){ + int a = state % 3, b = state / 3 % 3, c = state / 9; + if(a != b && b != c) dp[0][state] = 1; + } + + for(int i = 1; i < n; i ++) + for(int state = 0; state < 27; state ++){ + int a = state % 3, b = state / 3 % 3, c = state / 9; + if(a != b && b != c) + for(int state2 = 0; state2 < 27; state2 ++){ + int a2 = state2 % 3, b2 = state2 / 3 % 3, c2 = state2 / 9; + if(a != a2 && b != b2 && c != c2) + dp[i][state] += dp[i - 1][state2], + dp[i][state] %= MOD; + } + } + + int res = 0; + for(int state = 0; state < 27; state ++) + res += dp[n - 1][state], res %= MOD; + return res; + } +}; + + +int main() { + + cout << Solution().numOfWays(2) << endl; + // 54 + + cout << Solution().numOfWays(3) << endl; + // 246 + + cout << Solution().numOfWays(7) << endl; + // 106494 + + cout << Solution().numOfWays(5000) << endl; + // 30228214 + + return 0; +} diff --git a/1001-1500/1411-Number-of-Ways-to-Paint-Nx3-Grid/cpp-1411/main3.cpp b/1001-1500/1411-Number-of-Ways-to-Paint-Nx3-Grid/cpp-1411/main3.cpp new file mode 100644 index 00000000..fb731c42 --- /dev/null +++ b/1001-1500/1411-Number-of-Ways-to-Paint-Nx3-Grid/cpp-1411/main3.cpp @@ -0,0 +1,64 @@ +/// Source : https://leetcode.com/problems/number-of-ways-to-paint-n-3-grid/ +/// Author : liuyubobobo +/// Time : 2020-04-14 + +#include +#include + +using namespace std; + + +/// State Compression and DP +/// Space Optimized +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { + +private: + int MOD = 1e9 + 7; + +public: + int numOfWays(int n) { + + vector> dp(2, vector(27, 0)); + for(int state = 0; state < 27; state ++){ + int a = state % 3, b = state / 3 % 3, c = state / 9; + if(a != b && b != c) dp[0][state] = 1; + } + + for(int i = 1; i < n; i ++) + for(int state = 0; state < 27; state ++){ + int a = state % 3, b = state / 3 % 3, c = state / 9; + dp[i % 2][state] = 0; + if(a != b && b != c) + for(int state2 = 0; state2 < 27; state2 ++){ + int a2 = state2 % 3, b2 = state2 / 3 % 3, c2 = state2 / 9; + if(a != a2 && b != b2 && c != c2) + dp[i % 2][state] += dp[1 - i % 2][state2], dp[i % 2][state] %= MOD; + } + } + + int res = 0; + for(int state = 0; state < 27; state ++) + res += dp[(n - 1) % 2][state], res %= MOD; + return res; + } +}; + + +int main() { + + cout << Solution().numOfWays(2) << endl; + // 54 + + cout << Solution().numOfWays(3) << endl; + // 246 + + cout << Solution().numOfWays(7) << endl; + // 106494 + + cout << Solution().numOfWays(5000) << endl; + // 30228214 + + return 0; +} diff --git a/1001-1500/1411-Number-of-Ways-to-Paint-Nx3-Grid/cpp-1411/main4.cpp b/1001-1500/1411-Number-of-Ways-to-Paint-Nx3-Grid/cpp-1411/main4.cpp new file mode 100644 index 00000000..d748a842 --- /dev/null +++ b/1001-1500/1411-Number-of-Ways-to-Paint-Nx3-Grid/cpp-1411/main4.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/number-of-ways-to-paint-n-3-grid/ +/// Author : liuyubobobo +/// Time : 2020-04-14 + +#include +#include + +using namespace std; + + +/// State Compression and DP +/// Space Optimized +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { + +private: + int MOD = 1e9 + 7; + +public: + int numOfWays(int n) { + + long long abc = 6ll, aba = 6ll; + for(int i = 1; i < n; i ++){ + long long aba2 = 3 * aba + 2 * abc; + long long abc2 = 2 * aba + 2 * abc; + abc = abc2 % MOD; + aba = aba2 % MOD; + } + return (aba + abc) % MOD; + } +}; + + +int main() { + + cout << Solution().numOfWays(2) << endl; + // 54 + + cout << Solution().numOfWays(3) << endl; + // 246 + + cout << Solution().numOfWays(7) << endl; + // 106494 + + cout << Solution().numOfWays(5000) << endl; + // 30228214 + + return 0; +} diff --git a/1001-1500/1413-Minimum-Value-to-Get-Positive-Step-by-Step-Sum/cpp-1413/CMakeLists.txt b/1001-1500/1413-Minimum-Value-to-Get-Positive-Step-by-Step-Sum/cpp-1413/CMakeLists.txt new file mode 100644 index 00000000..8bfb9cdb --- /dev/null +++ b/1001-1500/1413-Minimum-Value-to-Get-Positive-Step-by-Step-Sum/cpp-1413/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(cpp_1413) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1413 main.cpp) \ No newline at end of file diff --git a/1001-1500/1413-Minimum-Value-to-Get-Positive-Step-by-Step-Sum/cpp-1413/main.cpp b/1001-1500/1413-Minimum-Value-to-Get-Positive-Step-by-Step-Sum/cpp-1413/main.cpp new file mode 100644 index 00000000..854d079c --- /dev/null +++ b/1001-1500/1413-Minimum-Value-to-Get-Positive-Step-by-Step-Sum/cpp-1413/main.cpp @@ -0,0 +1,29 @@ +/// Source : https://leetcode.com/problems/minimum-value-to-get-positive-step-by-step-sum/ +/// Author : liuyubobobo +/// Time : 2020-04-18 + +#include +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int minStartValue(vector& nums) { + + int cur = 0, res = 0; + for(int e: nums) + cur += e, res = min(res, cur); + return -res + 1; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1414-Find-the-Minimum-Number-of-Fibonacci-Numbers-Whose-Sum-Is-K/cpp-1414/CMakeLists.txt b/1001-1500/1414-Find-the-Minimum-Number-of-Fibonacci-Numbers-Whose-Sum-Is-K/cpp-1414/CMakeLists.txt new file mode 100644 index 00000000..56afbe8b --- /dev/null +++ b/1001-1500/1414-Find-the-Minimum-Number-of-Fibonacci-Numbers-Whose-Sum-Is-K/cpp-1414/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(cpp_1414) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1414 main.cpp) \ No newline at end of file diff --git a/1001-1500/1414-Find-the-Minimum-Number-of-Fibonacci-Numbers-Whose-Sum-Is-K/cpp-1414/main.cpp b/1001-1500/1414-Find-the-Minimum-Number-of-Fibonacci-Numbers-Whose-Sum-Is-K/cpp-1414/main.cpp new file mode 100644 index 00000000..b0337877 --- /dev/null +++ b/1001-1500/1414-Find-the-Minimum-Number-of-Fibonacci-Numbers-Whose-Sum-Is-K/cpp-1414/main.cpp @@ -0,0 +1,44 @@ +/// Source : https://leetcode.com/problems/find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/ +/// Author : liuyubobobo +/// Time : 2020-04-18 + +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(logk^2) +/// Space Complexity: O(logk) +class Solution { +public: + int findMinFibonacciNumbers(int k) { + + int a = 1, b = 1, c; + set fibs = {1}; + while(a + b <= 1e9){ + c = a + b; + fibs.insert(c); + a = b, b = c; + } + + int res = 0; + while(k){ + set::iterator iter = fibs.lower_bound(k); + if(!(iter != fibs.end() && *iter == k)) iter --; + res ++; + k -= *iter; + } + return res; + } +}; + + +int main() { + + cout << Solution().findMinFibonacciNumbers(7) << endl; + // 2 + + return 0; +} diff --git a/1001-1500/1415-The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n/cpp-1415/CMakeLists.txt b/1001-1500/1415-The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n/cpp-1415/CMakeLists.txt new file mode 100644 index 00000000..18d2d3d8 --- /dev/null +++ b/1001-1500/1415-The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n/cpp-1415/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(cpp_1415) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1415 main.cpp) \ No newline at end of file diff --git a/1001-1500/1415-The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n/cpp-1415/main.cpp b/1001-1500/1415-The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n/cpp-1415/main.cpp new file mode 100644 index 00000000..7c1905c3 --- /dev/null +++ b/1001-1500/1415-The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n/cpp-1415/main.cpp @@ -0,0 +1,60 @@ +/// Source : https://leetcode.com/problems/the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/ +/// Author : liuyubobobo +/// Time : 2020-04-19 + +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(3^n) +/// Space Complexity:O(n) +class Solution { +public: + string getHappyString(int n, int k) { + + string res(n, ' '); + int i = 0; + if(dfs(res, 0, i, n, k)) return res; + return ""; + } + +private: + bool dfs(string& s, int index, int& cnt, int n, int k){ + + if(index == n){ + cnt ++; +// cout << s << endl; + return cnt == k; + } + + for(char c: {'a', 'b', 'c'}) + if(!index || c != s[index - 1]){ + s[index] = c; + if(dfs(s, index + 1, cnt, n, k)) return true; + } + return false; + } +}; + + +int main() { + + cout << Solution().getHappyString(1, 3) << endl; + // c + + cout << Solution().getHappyString(1, 4) << endl; + // "" + + cout << Solution().getHappyString(3, 9) << endl; + // cab + + cout << Solution().getHappyString(2, 7) << endl; + // "" + + cout << Solution().getHappyString(10, 100) << endl; + // abacbabacb + + return 0; +} diff --git a/1001-1500/1416-Restore-The-Array/cpp-1416/CMakeLists.txt b/1001-1500/1416-Restore-The-Array/cpp-1416/CMakeLists.txt new file mode 100644 index 00000000..1244c85e --- /dev/null +++ b/1001-1500/1416-Restore-The-Array/cpp-1416/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(cpp_1416) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1416 main2.cpp) \ No newline at end of file diff --git a/1001-1500/1416-Restore-The-Array/cpp-1416/main.cpp b/1001-1500/1416-Restore-The-Array/cpp-1416/main.cpp new file mode 100644 index 00000000..e2cab95f --- /dev/null +++ b/1001-1500/1416-Restore-The-Array/cpp-1416/main.cpp @@ -0,0 +1,63 @@ +/// Source : https://leetcode.com/problems/restore-the-array/ +/// Author : liuyubobobo +/// Time : 2020-04-19 + +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +private: + int MOD = 1e9 + 7; + +public: + int numberOfArrays(string s, int k) { + + vector dp(s.size(), -1); + return dfs(s, 0, k, dp); + } + +private: + int dfs(const string& s, int index, int k, vector& dp){ + + if(index == s.size()) return 1; + if(dp[index] != -1) return dp[index]; + if(s[index] == '0') return dp[index] = 0; + + int res = 0; + for(int i = index; i < s.size(); i ++){ + if(i + 1 - index == 10 && s[index] >= '2') break; + int tnum = atoi(s.substr(index, i + 1 - index).c_str()); + if(tnum > k) break; + res = (res + dfs(s, i + 1, k, dp)) % MOD; + } + return dp[index] = res; + } +}; + + +int main() { + + cout << Solution().numberOfArrays("1000", 10000) << endl; + // 1 + + cout << Solution().numberOfArrays("1000", 10) << endl; + // 0 + + cout << Solution().numberOfArrays("1317", 2000) << endl; + // 8 + + cout << Solution().numberOfArrays("2020", 30) << endl; + // 1 + + cout << Solution().numberOfArrays("1234567890", 90) << endl; + // 34 + + return 0; +} diff --git a/1001-1500/1416-Restore-The-Array/cpp-1416/main2.cpp b/1001-1500/1416-Restore-The-Array/cpp-1416/main2.cpp new file mode 100644 index 00000000..d3cbca06 --- /dev/null +++ b/1001-1500/1416-Restore-The-Array/cpp-1416/main2.cpp @@ -0,0 +1,56 @@ +/// Source : https://leetcode.com/problems/restore-the-array/ +/// Author : liuyubobobo +/// Time : 2020-04-19 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +private: + int MOD = 1e9 + 7; + +public: + int numberOfArrays(string s, int k) { + + vector dp(s.size() + 1, 0); + dp[s.size()] = 1; + for(int i = s.size() - 1; i >= 0; i --) + if(s[i] != '0'){ + for(int j = i; j < s.size(); j ++){ + if(j + 1 - i == 10 && s[i] >= '2') break; + int tnum = atoi(s.substr(i, j + 1 - i).c_str()); + if(tnum > k) break; + dp[i] = (dp[i] + dp[j + 1]) % MOD; + } + } + return dp[0]; + } +}; + + +int main() { + + cout << Solution().numberOfArrays("1000", 10000) << endl; + // 1 + + cout << Solution().numberOfArrays("1000", 10) << endl; + // 0 + + cout << Solution().numberOfArrays("1317", 2000) << endl; + // 8 + + cout << Solution().numberOfArrays("2020", 30) << endl; + // 1 + + cout << Solution().numberOfArrays("1234567890", 90) << endl; + // 34 + + return 0; +} diff --git a/1001-1500/1417-Reformat-The-String/cpp-1417/CMakeLists.txt b/1001-1500/1417-Reformat-The-String/cpp-1417/CMakeLists.txt new file mode 100644 index 00000000..cb89cda6 --- /dev/null +++ b/1001-1500/1417-Reformat-The-String/cpp-1417/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1001-1500/1417-Reformat-The-String/cpp-1417/main.cpp b/1001-1500/1417-Reformat-The-String/cpp-1417/main.cpp new file mode 100644 index 00000000..440611de --- /dev/null +++ b/1001-1500/1417-Reformat-The-String/cpp-1417/main.cpp @@ -0,0 +1,43 @@ +/// Source : https://leetcode.com/problems/reformat-the-string/ +/// Author : liuyubobobo +/// Time : 2020-04-18 + +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + string reformat(string s) { + + string a, b; + for(char c: s) + if(c >= '0' && c <= '9') a += c; + else b += c; + + if(abs((int)a.size() - (int)b.size()) >= 2) return ""; + + if(a.size() < b.size()) swap(a, b); + string res = ""; + for(int i = 0; i < b.size(); i ++){ + res += a[i]; + res += b[i]; + } + + if(a.size() > b.size()) res += a.back(); + return res; + } +}; + + +int main() { + + cout << Solution().reformat("covid2019") << endl; + + return 0; +} diff --git a/1001-1500/1418-Display-Table-of-Food-Orders-in-a-Restaurant/cpp-1418/CMakeLists.txt b/1001-1500/1418-Display-Table-of-Food-Orders-in-a-Restaurant/cpp-1418/CMakeLists.txt new file mode 100644 index 00000000..545e47b8 --- /dev/null +++ b/1001-1500/1418-Display-Table-of-Food-Orders-in-a-Restaurant/cpp-1418/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1001-1500/1418-Display-Table-of-Food-Orders-in-a-Restaurant/cpp-1418/main.cpp b/1001-1500/1418-Display-Table-of-Food-Orders-in-a-Restaurant/cpp-1418/main.cpp new file mode 100644 index 00000000..59e2bd74 --- /dev/null +++ b/1001-1500/1418-Display-Table-of-Food-Orders-in-a-Restaurant/cpp-1418/main.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/display-table-of-food-orders-in-a-restaurant/ +/// Author : liuyubobobo +/// Time : 2020-04-18 + +#include +#include +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(|orders| + |tables| * |foods|) +/// Space Complexity: O(|tables| * |foods|) +class Solution { +public: + vector> displayTable(vector>& orders) { + + map> data; + set table_numbers; + set food_names; + for(const vector& order: orders){ + int num = atoi(order[1].c_str()); + data[num][order[2]] ++; + + table_numbers.insert(num); + food_names.insert(order[2]); + } + + vector> res; + map food_to_index; + vector header = {"Table"}; + + int i = 1; + for(const string& food_name: food_names){ + header.push_back(food_name); + food_to_index[food_name] = i ++; + } + res.push_back(header); + + for(const pair>& p: data){ + vector row(food_names.size() + 1, "0"); + row[0] = to_string(p.first); + for(const pair& p2: p.second) + row[food_to_index[p2.first]] = to_string(p2.second); + res.push_back(row); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1419-Minimum-Number-of-Frogs-Croaking/cpp-1419/CMakeLists.txt b/1001-1500/1419-Minimum-Number-of-Frogs-Croaking/cpp-1419/CMakeLists.txt new file mode 100644 index 00000000..94acd016 --- /dev/null +++ b/1001-1500/1419-Minimum-Number-of-Frogs-Croaking/cpp-1419/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1001-1500/1419-Minimum-Number-of-Frogs-Croaking/cpp-1419/main.cpp b/1001-1500/1419-Minimum-Number-of-Frogs-Croaking/cpp-1419/main.cpp new file mode 100644 index 00000000..4611f59c --- /dev/null +++ b/1001-1500/1419-Minimum-Number-of-Frogs-Croaking/cpp-1419/main.cpp @@ -0,0 +1,61 @@ +/// Source : https://leetcode.com/problems/minimum-number-of-frogs-croaking/ +/// Author : liuyubobobo +/// Time : 2020-04-18 +/// Updated: 2023-05-05 + +#include +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int minNumberOfFrogs(string s) { + + if(s.size() % 5) return -1; + + for(char& c: s) + if(c == 'c') c = 'a'; + else if(c == 'r') c = 'b'; + else if(c == 'o') c = 'c'; + else if(c == 'a') c = 'd'; + else if(c == 'k') c = 'e'; + else return -1; + + vector waitfor(5, 0); + int res = 0; + for(char c: s){ + + int v = c - 'a'; + if(v == 0 && waitfor[0] == 0) res ++, waitfor[1] ++; + else{ + if(waitfor[v] == 0) return -1; + waitfor[v] --; + waitfor[(v + 1) % 5] ++; + } + } + return waitfor[0] == res ? res : -1; + } +}; + + +int main() { + + cout << Solution().minNumberOfFrogs("croakcroak") << endl; + // 1 + + cout << Solution().minNumberOfFrogs("crcoakroak") << endl; + // 2 + + cout << Solution().minNumberOfFrogs("croakcrook") << endl; + // -1 + + cout << Solution().minNumberOfFrogs("croakcroa") << endl; + // -1 + + return 0; +} diff --git a/1001-1500/1420-Build-Array-Where-You-Can-Find-The-Maximum-Exactly-K-Comparisons/cpp-1420/CMakeLists.txt b/1001-1500/1420-Build-Array-Where-You-Can-Find-The-Maximum-Exactly-K-Comparisons/cpp-1420/CMakeLists.txt new file mode 100644 index 00000000..ffce3872 --- /dev/null +++ b/1001-1500/1420-Build-Array-Where-You-Can-Find-The-Maximum-Exactly-K-Comparisons/cpp-1420/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main2.cpp) \ No newline at end of file diff --git a/1001-1500/1420-Build-Array-Where-You-Can-Find-The-Maximum-Exactly-K-Comparisons/cpp-1420/main.cpp b/1001-1500/1420-Build-Array-Where-You-Can-Find-The-Maximum-Exactly-K-Comparisons/cpp-1420/main.cpp new file mode 100644 index 00000000..86ff063e --- /dev/null +++ b/1001-1500/1420-Build-Array-Where-You-Can-Find-The-Maximum-Exactly-K-Comparisons/cpp-1420/main.cpp @@ -0,0 +1,63 @@ +/// Source : https://leetcode.com/problems/build-array-where-you-can-find-the-maximum-exactly-k-comparisons/ +/// Author : liuyubobobo +/// Time : 2020-04-18 + +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(n * m * m * k) +/// Space Complexity: O(n * m * k) +class Solution { + +private: + int MOD = 1e9 + 7; + +public: + int numOfArrays(int n, int m, int k) { + + int res = 0; + vector>> dp(n, vector>(m, vector(k, -1))); + for(int i = 0; i < m; i ++) + res = (res + dfs(0, i, k - 1, n, m, dp)) % MOD; + return res; + } + +private: + int dfs(int index, int cur_max, int k, int n, int m, vector>>& dp){ + + if(index + 1 == n) return k == 0; + if(dp[index][cur_max][k] != -1) return dp[index][cur_max][k]; + + int res = 0; + for(int i = 0; i < m; i ++) + if(i <= cur_max) res = (res + dfs(index + 1, cur_max, k, n, m, dp)) % MOD; + else if(k - 1 >= 0) res = (res + dfs(index + 1, i, k - 1, n, m, dp)) % MOD; + else break; + return dp[index][cur_max][k] = res; + } +}; + + +int main() { + + cout << Solution().numOfArrays(2, 3, 1) << endl; + // 6 + + cout << Solution().numOfArrays(5, 2, 3) << endl; + // 0 + + cout << Solution().numOfArrays(9, 1, 1) << endl; + // 1 + + cout << Solution().numOfArrays(50, 100, 25) << endl; + // 34549172 + + cout << Solution().numOfArrays(37, 17, 7) << endl; + // 418930126 + + return 0; +} diff --git a/1001-1500/1420-Build-Array-Where-You-Can-Find-The-Maximum-Exactly-K-Comparisons/cpp-1420/main2.cpp b/1001-1500/1420-Build-Array-Where-You-Can-Find-The-Maximum-Exactly-K-Comparisons/cpp-1420/main2.cpp new file mode 100644 index 00000000..af574204 --- /dev/null +++ b/1001-1500/1420-Build-Array-Where-You-Can-Find-The-Maximum-Exactly-K-Comparisons/cpp-1420/main2.cpp @@ -0,0 +1,64 @@ +/// Source : https://leetcode.com/problems/build-array-where-you-can-find-the-maximum-exactly-k-comparisons/ +/// Author : liuyubobobo +/// Time : 2020-04-18 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(n * m * m * k) +/// Space Complexity: O(n * m * k) +class Solution { + +private: + int MOD = 1e9 + 7; + +public: + int numOfArrays(int n, int m, int k) { + + vector>> dp(n, vector>(m, vector(k, 0))); + + for(int cur_max = 0; cur_max < m; cur_max ++) + dp[n - 1][cur_max][0] = 1; + + for(int i = n - 2; i >= 0; i --) + for(int cur_max = 0; cur_max < m; cur_max ++) + for(int j = 0; j < k; j ++){ + + for(int p = 0; p < m; p ++) + if(p <= cur_max) + dp[i][cur_max][j] = (dp[i][cur_max][j] + dp[i + 1][cur_max][j]) % MOD; + else if(j) + dp[i][cur_max][j] = (dp[i][cur_max][j] + dp[i + 1][p][j - 1]) % MOD; + } + + int res =0; + for(int x = 0; x < m; x ++) + res = (res + dp[0][x][k - 1]) % MOD; + return res; + } +}; + + +int main() { + + cout << Solution().numOfArrays(2, 3, 1) << endl; + // 6 + + cout << Solution().numOfArrays(5, 2, 3) << endl; + // 0 + + cout << Solution().numOfArrays(9, 1, 1) << endl; + // 1 + + cout << Solution().numOfArrays(50, 100, 25) << endl; + // 34549172 + + cout << Solution().numOfArrays(37, 17, 7) << endl; + // 418930126 + + return 0; +} diff --git a/1001-1500/1422-Maximum-Score-After-Splitting-a-String/cpp-1422/CMakeLists.txt b/1001-1500/1422-Maximum-Score-After-Splitting-a-String/cpp-1422/CMakeLists.txt new file mode 100644 index 00000000..446d8265 --- /dev/null +++ b/1001-1500/1422-Maximum-Score-After-Splitting-a-String/cpp-1422/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main2.cpp) \ No newline at end of file diff --git a/1001-1500/1422-Maximum-Score-After-Splitting-a-String/cpp-1422/main.cpp b/1001-1500/1422-Maximum-Score-After-Splitting-a-String/cpp-1422/main.cpp new file mode 100644 index 00000000..4bf39f21 --- /dev/null +++ b/1001-1500/1422-Maximum-Score-After-Splitting-a-String/cpp-1422/main.cpp @@ -0,0 +1,45 @@ +/// Source : https://leetcode.com/problems/maximum-score-after-splitting-a-string/ +/// Author : liuyubobobo +/// Time : 2020-04-25 + +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n^2) +/// Space Complexity: O(1) +class Solution { +public: + int maxScore(string s) { + + int res = 0; + for(int i = 1; i < s.size(); i ++){ + + int tres = 0; + for(int j = 0; j < i; j ++) tres += (s[j] == '0'); + for(int j = i; j < s.size(); j ++) tres += (s[j] == '1'); + res = max(res, tres); + } + return res; + } +}; + + +int main() { + + cout << Solution().maxScore("011101") << endl; + // 5 + + cout << Solution().maxScore("00111") << endl; + // 5 + + cout << Solution().maxScore("1111") << endl; + // 3 + + cout << Solution().maxScore("00") << endl; + // 1 + + return 0; +} diff --git a/1001-1500/1422-Maximum-Score-After-Splitting-a-String/cpp-1422/main2.cpp b/1001-1500/1422-Maximum-Score-After-Splitting-a-String/cpp-1422/main2.cpp new file mode 100644 index 00000000..dbfd7a05 --- /dev/null +++ b/1001-1500/1422-Maximum-Score-After-Splitting-a-String/cpp-1422/main2.cpp @@ -0,0 +1,49 @@ +/// Source : https://leetcode.com/problems/maximum-score-after-splitting-a-string/ +/// Author : liuyubobobo +/// Time : 2020-04-27 + +#include +#include + +using namespace std; + + +/// Presum and Postsum +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int maxScore(string s) { + + vector presum(s.size() + 1, 0); + for(int i = 0; i < s.size(); i ++) + presum[i + 1] = presum[i] + (s[i] == '0'); + + vector postsum(s.size() + 1, 0); + for(int i = s.size() - 1; i >= 0; i --) + postsum[i] = postsum[i + 1] + (s[i] == '1'); + + int res = 0; + for(int i = 1; i < s.size(); i ++) + res = max(res, presum[i] + postsum[i]); + return res; + } +}; + + +int main() { + + cout << Solution().maxScore("011101") << endl; + // 5 + + cout << Solution().maxScore("00111") << endl; + // 5 + + cout << Solution().maxScore("1111") << endl; + // 3 + + cout << Solution().maxScore("00") << endl; + // 1 + + return 0; +} diff --git a/1001-1500/1423-Maximum-Points-You-Can-Obtain-from-Cards/cpp-1423/CMakeLists.txt b/1001-1500/1423-Maximum-Points-You-Can-Obtain-from-Cards/cpp-1423/CMakeLists.txt new file mode 100644 index 00000000..e6f5d34c --- /dev/null +++ b/1001-1500/1423-Maximum-Points-You-Can-Obtain-from-Cards/cpp-1423/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main2.cpp) \ No newline at end of file diff --git a/1001-1500/1423-Maximum-Points-You-Can-Obtain-from-Cards/cpp-1423/main.cpp b/1001-1500/1423-Maximum-Points-You-Can-Obtain-from-Cards/cpp-1423/main.cpp new file mode 100644 index 00000000..7eb7a1ae --- /dev/null +++ b/1001-1500/1423-Maximum-Points-You-Can-Obtain-from-Cards/cpp-1423/main.cpp @@ -0,0 +1,61 @@ +/// Source : https://leetcode.com/problems/maximum-points-you-can-obtain-from-cards/ +/// Author : liuyubobobo +/// Time : 2020-04-25 + +#include +#include + +using namespace std; + + +/// Presum + Postsum +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int maxScore(vector& cardPoints, int k) { + + int n = cardPoints.size(); + + vector presum(n + 1, 0); + for(int i = 0; i < n; i ++) presum[i + 1] = presum[i] + cardPoints[i]; + + vector postsum(n + 1, 0); + for(int i = n - 1; i >= 0; i --) postsum[i] = postsum[i + 1] + cardPoints[i]; + + int res = 0; + for(int i = 0; i <= k; i ++) + res = max(res, presum[i] + postsum[n - (k - i)]); + return res; + } +}; + + +int main() { + + vectorcardPoints1 = {1,2,3,4,5,6,1}; + cout << Solution().maxScore(cardPoints1, 3) << endl; + // 12 + + vectorcardPoints2 = {2, 2, 2}; + cout << Solution().maxScore(cardPoints2, 2) << endl; + // 4 + + vectorcardPoints3 = {9,7,7,9,7,7,9}; + cout << Solution().maxScore(cardPoints3, 7) << endl; + // 55 + + vectorcardPoints4 = {1,1000,1}; + cout << Solution().maxScore(cardPoints4, 1) << endl; + // 1 + + vectorcardPoints5 = {1,79,80,1,1,1,200,1}; + cout << Solution().maxScore(cardPoints5, 3) << endl; + // 202 + + vectorcardPoints6 = {1}; + cout << Solution().maxScore(cardPoints6, 1) << endl; + // 1 + + return 0; +} diff --git a/1001-1500/1423-Maximum-Points-You-Can-Obtain-from-Cards/cpp-1423/main2.cpp b/1001-1500/1423-Maximum-Points-You-Can-Obtain-from-Cards/cpp-1423/main2.cpp new file mode 100644 index 00000000..2cd62eb1 --- /dev/null +++ b/1001-1500/1423-Maximum-Points-You-Can-Obtain-from-Cards/cpp-1423/main2.cpp @@ -0,0 +1,61 @@ +/// Source : https://leetcode.com/problems/maximum-points-you-can-obtain-from-cards/ +/// Author : liuyubobobo +/// Time : 2020-04-27 + +#include +#include +#include + +using namespace std; + + +/// Sliding Window +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int maxScore(vector& cardPoints, int k) { + + int n = cardPoints.size(); + int sum = accumulate(cardPoints.begin(), cardPoints.end(), 0); + if(k == n) return sum; + + int window = 0, l = 0, r = -1, res = 0; + while(r + 1 < n){ + window += cardPoints[++r]; + if(r - l + 1 == n - k) + res = max(res, sum - window), window -= cardPoints[l++]; + } + return res; + } +}; + + +int main() { + + vectorcardPoints1 = {1,2,3,4,5,6,1}; + cout << Solution().maxScore(cardPoints1, 3) << endl; + // 12 + + vectorcardPoints2 = {2, 2, 2}; + cout << Solution().maxScore(cardPoints2, 2) << endl; + // 4 + + vectorcardPoints3 = {9,7,7,9,7,7,9}; + cout << Solution().maxScore(cardPoints3, 7) << endl; + // 55 + + vectorcardPoints4 = {1,1000,1}; + cout << Solution().maxScore(cardPoints4, 1) << endl; + // 1 + + vectorcardPoints5 = {1,79,80,1,1,1,200,1}; + cout << Solution().maxScore(cardPoints5, 3) << endl; + // 202 + + vectorcardPoints6 = {1}; + cout << Solution().maxScore(cardPoints6, 1) << endl; + // 1 + + return 0; +} diff --git a/1001-1500/1424-Diagonal-Traverse-II/cpp-1424/CMakeLists.txt b/1001-1500/1424-Diagonal-Traverse-II/cpp-1424/CMakeLists.txt new file mode 100644 index 00000000..26e63018 --- /dev/null +++ b/1001-1500/1424-Diagonal-Traverse-II/cpp-1424/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main2.cpp) \ No newline at end of file diff --git a/1001-1500/1424-Diagonal-Traverse-II/cpp-1424/main.cpp b/1001-1500/1424-Diagonal-Traverse-II/cpp-1424/main.cpp new file mode 100644 index 00000000..284b368b --- /dev/null +++ b/1001-1500/1424-Diagonal-Traverse-II/cpp-1424/main.cpp @@ -0,0 +1,48 @@ +/// Source : https://leetcode.com/problems/diagonal-traverse-ii/ +/// Author : liuyubobobo +/// Time : 2020-04-25 + +#include +#include + +using namespace std; + + +/// Sorting +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + vector findDiagonalOrder(vector>& nums) { + + vector, int>> v; + for(int i = 0; i < nums.size(); i ++) + for(int j = 0; j < nums[i].size(); j ++) + v.push_back(make_pair(make_pair(i, j), nums[i][j])); + + sort(v.begin(), v.end(), + [](const pair, int>& p1, const pair, int>& p2){ + + if(p1.first.first + p1.first.second != p2.first.first + p2.first.second) + return p1.first.first + p1.first.second < p2.first.first + p2.first.second; + return p1.first.first > p2.first.first; + }); + + vector res; + for(const pair, int>& p: v) res.push_back(p.second); + return res; + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << " "; cout << endl; +} + +int main() { + + vector> nums = {{1,2,3},{4,5,6},{7,8,9}}; + print_vec(Solution().findDiagonalOrder(nums)); + + return 0; +} diff --git a/1001-1500/1424-Diagonal-Traverse-II/cpp-1424/main2.cpp b/1001-1500/1424-Diagonal-Traverse-II/cpp-1424/main2.cpp new file mode 100644 index 00000000..9d47d2ac --- /dev/null +++ b/1001-1500/1424-Diagonal-Traverse-II/cpp-1424/main2.cpp @@ -0,0 +1,43 @@ +/// Source : https://leetcode.com/problems/diagonal-traverse-ii/ +/// Author : liuyubobobo +/// Time : 2020-04-25 + +#include +#include + +using namespace std; + + +/// Using Bucket +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector findDiagonalOrder(vector>& nums) { + + vector> buckets; + for(int i = 0; i < nums.size(); i ++) + for(int j = 0; j < nums[i].size(); j ++){ + if(i + j >= buckets.size()) buckets.push_back({}); + buckets[i + j].push_back(nums[i][j]); + } + + vector res; + for(const vector& v: buckets) + for(int i = v.size() - 1; i >= 0; i --) res.push_back(v[i]); + return res; + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << " "; cout << endl; +} + +int main() { + + vector> nums = {{1,2,3},{4,5,6},{7,8,9}}; + print_vec(Solution().findDiagonalOrder(nums)); + + return 0; +} diff --git a/1001-1500/1425-Constrained-Subset-Sum/cpp-1425/CMakeLists.txt b/1001-1500/1425-Constrained-Subset-Sum/cpp-1425/CMakeLists.txt new file mode 100644 index 00000000..a965d66f --- /dev/null +++ b/1001-1500/1425-Constrained-Subset-Sum/cpp-1425/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main3.cpp) \ No newline at end of file diff --git a/1001-1500/1425-Constrained-Subset-Sum/cpp-1425/main.cpp b/1001-1500/1425-Constrained-Subset-Sum/cpp-1425/main.cpp new file mode 100644 index 00000000..3205b91b --- /dev/null +++ b/1001-1500/1425-Constrained-Subset-Sum/cpp-1425/main.cpp @@ -0,0 +1,62 @@ +/// Source : https://leetcode.com/problems/constrained-subset-sum/ +/// Author : liuyubobobo +/// Time : 2020-04-27 + +#include +#include +#include + +using namespace std; + + +/// DP + Using Map as a Priority Queue to Optimize +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + int constrainedSubsetSum(vector& nums, int k) { + + int max_value = *max_element(nums.begin(), nums.end()); + if(max_value <= 0) return max_value; + + int n = nums.size(), res = 0; + vector dp(n); + map tree; + for(int l = 0, r = 0; r < n; r ++){ + dp[r] = nums[r]; + if(tree.size()) + dp[r] = max(dp[r], nums[r] + tree.rbegin()->first); + res = max(res, dp[r]); + + tree[dp[r]] ++; + if(r - l >= k){ + tree[dp[l]] --; + if(tree[dp[l]] == 0) tree.erase(dp[l]); + l ++; + } + } + return res; + } +}; + + +int main() { + + vector nums1 = {10,2,-10,5,20}; + cout << Solution().constrainedSubsetSum(nums1, 2) << endl; + // 37 + + vector nums2 = {-1, -2, -3}; + cout << Solution().constrainedSubsetSum(nums2, 1) << endl; + // -1 + + vector nums3 = {10,-2,-10,-5,20}; + cout << Solution().constrainedSubsetSum(nums3, 2) << endl; + // 23 + + vector nums4 = {-8269,3217,-4023,-4138,-683,6455,-3621,9242,4015,-3790}; + cout << Solution().constrainedSubsetSum(nums4, 1) << endl; + // 16091 + + return 0; +} diff --git a/1001-1500/1425-Constrained-Subset-Sum/cpp-1425/main2.cpp b/1001-1500/1425-Constrained-Subset-Sum/cpp-1425/main2.cpp new file mode 100644 index 00000000..15047965 --- /dev/null +++ b/1001-1500/1425-Constrained-Subset-Sum/cpp-1425/main2.cpp @@ -0,0 +1,103 @@ +/// Source : https://leetcode.com/problems/constrained-subset-sum/ +/// Author : liuyubobobo +/// Time : 2020-04-27 + +#include +#include +#include + +using namespace std; + + +/// DP + Segment Tree to Optimize +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class SegmentTree{ + +private: + int n; + vector tree; + +public: + SegmentTree(int n): n(n), tree(4 * n){} + + int query(int qL, int qR){ + return query(0, 0, n-1, qL, qR); + } + + void update(int index, int value){ + update(0, 0, n - 1, index, value); + } + +private: + void update(int treeID, int l, int r, int index, int value){ + + if(l == r){ + assert(l == index); + tree[treeID] = value; + return; + } + + int mid = (l + r) / 2; + if(index <= mid) update(treeID * 2 + 1, l, mid, index, value); + else update(treeID * 2 + 2, mid + 1, r, index, value); + + tree[treeID] = max(tree[treeID * 2 + 1], tree[treeID * 2 + 2]); + return; + } + + int query(int treeID, int treeL, int treeR, int qL, int qR){ + + if(treeL > qR || treeR < qL) return 0; + + if(qL <= treeL && qR >= treeR) + return tree[treeID]; + + int mid = (treeL + treeR) / 2; + int leftRes = query(2 * treeID + 1, treeL, mid, qL, qR); + int rightRes = query(2 * treeID + 2, mid + 1, treeR, qL, qR); + return max(leftRes, rightRes); + } +}; + +class Solution { +public: + int constrainedSubsetSum(vector& nums, int k) { + + int max_value = *max_element(nums.begin(), nums.end()); + if(max_value <= 0) return max_value; + + int n = nums.size(), res = 0; + vector dp(n); + SegmentTree tree(n); + for(int i = 0; i < n; i ++){ + dp[i] = nums[i]; + if(i) dp[i] = max(dp[i], nums[i] + tree.query(max(0, i - k), i - 1)); + res = max(res, dp[i]); + tree.update(i, dp[i]); + } + return res; + } +}; + + +int main() { + + vector nums1 = {10,2,-10,5,20}; + cout << Solution().constrainedSubsetSum(nums1, 2) << endl; + // 37 + + vector nums2 = {-1, -2, -3}; + cout << Solution().constrainedSubsetSum(nums2, 1) << endl; + // -1 + + vector nums3 = {10,-2,-10,-5,20}; + cout << Solution().constrainedSubsetSum(nums3, 2) << endl; + // 23 + + vector nums4 = {-8269,3217,-4023,-4138,-683,6455,-3621,9242,4015,-3790}; + cout << Solution().constrainedSubsetSum(nums4, 1) << endl; + // 16091 + + return 0; +} diff --git a/1001-1500/1425-Constrained-Subset-Sum/cpp-1425/main3.cpp b/1001-1500/1425-Constrained-Subset-Sum/cpp-1425/main3.cpp new file mode 100644 index 00000000..727fc1bf --- /dev/null +++ b/1001-1500/1425-Constrained-Subset-Sum/cpp-1425/main3.cpp @@ -0,0 +1,62 @@ +/// Source : https://leetcode.com/problems/constrained-subset-sum/ +/// Author : liuyubobobo +/// Time : 2020-04-27 + +#include +#include +#include + +using namespace std; + + +/// DP + Using Deque to Optimize +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int constrainedSubsetSum(vector& nums, int k) { + + int max_value = *max_element(nums.begin(), nums.end()); + if(max_value <= 0) return max_value; + + int n = nums.size(), res = 0; + vector dp(n); + deque q; + for(int i = 0; i < n; i ++){ + dp[i] = nums[i]; + if(q.size()) + dp[i] = max(dp[i], nums[i] + q.front()); + res = max(res, dp[i]); + + while(!q.empty() && q.back() < dp[i]) + q.pop_back(); + q.push_back(dp[i]); + + if(i >= k && q.front() == dp[i - k]) + q.pop_front(); + } + return res; + } +}; + + +int main() { + + vector nums1 = {10,2,-10,5,20}; + cout << Solution().constrainedSubsetSum(nums1, 2) << endl; + // 37 + + vector nums2 = {-1, -2, -3}; + cout << Solution().constrainedSubsetSum(nums2, 1) << endl; + // -1 + + vector nums3 = {10,-2,-10,-5,20}; + cout << Solution().constrainedSubsetSum(nums3, 2) << endl; + // 23 + + vector nums4 = {-8269,3217,-4023,-4138,-683,6455,-3621,9242,4015,-3790}; + cout << Solution().constrainedSubsetSum(nums4, 1) << endl; + // 16091 + + return 0; +} diff --git a/1001-1500/1426-Counting-Elements/cpp-1426/CMakeLists.txt b/1001-1500/1426-Counting-Elements/cpp-1426/CMakeLists.txt new file mode 100644 index 00000000..5960f0f7 --- /dev/null +++ b/1001-1500/1426-Counting-Elements/cpp-1426/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(cpp_1426) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1426 main2.cpp) \ No newline at end of file diff --git a/1001-1500/1426-Counting-Elements/cpp-1426/main.cpp b/1001-1500/1426-Counting-Elements/cpp-1426/main.cpp new file mode 100644 index 00000000..ae359884 --- /dev/null +++ b/1001-1500/1426-Counting-Elements/cpp-1426/main.cpp @@ -0,0 +1,31 @@ +/// Source : https://leetcode.com/problems/counting-elements/ +/// Author : liuyubobobo +/// Time : 2020-05-02 + +#include +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n^2) +/// Space Complexity: O(1) +class Solution { +public: + int countElements(vector& arr) { + + int res = 0; + for(int e: arr) + if(find(arr.begin(), arr.end(), e + 1) != arr.end()) + res ++; + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1426-Counting-Elements/cpp-1426/main2.cpp b/1001-1500/1426-Counting-Elements/cpp-1426/main2.cpp new file mode 100644 index 00000000..17c32aa7 --- /dev/null +++ b/1001-1500/1426-Counting-Elements/cpp-1426/main2.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/counting-elements/ +/// Author : liuyubobobo +/// Time : 2020-05-02 + +#include +#include +#include + +using namespace std; + + +/// Sorting and Binary Search +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + int countElements(vector& arr) { + + sort(arr.begin(), arr.end()); + + int res = 0; + for(int e: arr){ + vector::iterator iter = lower_bound(arr.begin(), arr.end(), e + 1); + if(iter != arr.end() && *iter == e + 1) + res ++; + } + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1426-Counting-Elements/cpp-1426/main3.cpp b/1001-1500/1426-Counting-Elements/cpp-1426/main3.cpp new file mode 100644 index 00000000..7fff9d4e --- /dev/null +++ b/1001-1500/1426-Counting-Elements/cpp-1426/main3.cpp @@ -0,0 +1,32 @@ +/// Source : https://leetcode.com/problems/counting-elements/ +/// Author : liuyubobobo +/// Time : 2020-05-02 + +#include +#include +#include + +using namespace std; + + +/// Using HashSet +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int countElements(vector& arr) { + + unordered_set set; + for(int e: arr) set.insert(e); + + int res = 0; + for(int e: arr) if(set.count(e + 1)) res ++; + return res; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1427-Perform-String-Shifts/cpp-1427/CMakeLists.txt b/1001-1500/1427-Perform-String-Shifts/cpp-1427/CMakeLists.txt new file mode 100644 index 00000000..1c72e57e --- /dev/null +++ b/1001-1500/1427-Perform-String-Shifts/cpp-1427/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(cpp_1427) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1427 main.cpp) \ No newline at end of file diff --git a/1001-1500/1427-Perform-String-Shifts/cpp-1427/main.cpp b/1001-1500/1427-Perform-String-Shifts/cpp-1427/main.cpp new file mode 100644 index 00000000..2ac57ef0 --- /dev/null +++ b/1001-1500/1427-Perform-String-Shifts/cpp-1427/main.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/perform-string-shifts/ +/// Author : liuyubobobo +/// Time : 2020-05-02 + +#include +#include + +using namespace std; + + +/// Mathematically to compute the net shifts +/// Time Complexity: O(|shift| + |s|) +/// Time Complexity: O(|s|) +class Solution { +public: + string stringShift(string s, vector>& shift) { + + int right = 0; + for(const vector& v: shift) + if(v[0]) right += v[1]; + else right -= v[1]; + + if(right > 0){ + int offset = right % s.size(); + return s.substr(s.size() - offset) + s.substr(0, s.size() - offset); + } + + int offset = (-right) % s.size(); + return s.substr(offset) + s.substr(0, offset); + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1428-Leftmost-Column-with-at-Least-a-One/cpp-1428/CMakeLists.txt b/1001-1500/1428-Leftmost-Column-with-at-Least-a-One/cpp-1428/CMakeLists.txt new file mode 100644 index 00000000..1b72a6be --- /dev/null +++ b/1001-1500/1428-Leftmost-Column-with-at-Least-a-One/cpp-1428/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(cpp_1428) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1428 main3.cpp) \ No newline at end of file diff --git a/1001-1500/1428-Leftmost-Column-with-at-Least-a-One/cpp-1428/main.cpp b/1001-1500/1428-Leftmost-Column-with-at-Least-a-One/cpp-1428/main.cpp new file mode 100644 index 00000000..21ab5bf8 --- /dev/null +++ b/1001-1500/1428-Leftmost-Column-with-at-Least-a-One/cpp-1428/main.cpp @@ -0,0 +1,45 @@ +#include +#include + +using namespace std; + + +/// This is the BinaryMatrix's API interface. +/// You should not implement it, or speculate about its implementation +class BinaryMatrix { +public: + int get(int row, int col); + vector dimensions(); +}; + + +/// Binary Search +/// Time Complexity: O(R * log(C)) +/// Space Complexity: O(1) +class Solution { +public: + int leftMostColumnWithOne(BinaryMatrix &binaryMatrix) { + + vector dim = binaryMatrix.dimensions(); + int R = dim[0], C = dim[1]; + + int res = C; + for(int i = 0; i < R; i ++){ + + int l = 0, r = C; + while(l < r){ + int mid = (l + r) / 2; + if(binaryMatrix.get(i, mid)) r = mid; + else l = mid + 1; + } + res = min(res, l); + } + return res == C ? -1 : res; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1428-Leftmost-Column-with-at-Least-a-One/cpp-1428/main2.cpp b/1001-1500/1428-Leftmost-Column-with-at-Least-a-One/cpp-1428/main2.cpp new file mode 100644 index 00000000..ad9dbba2 --- /dev/null +++ b/1001-1500/1428-Leftmost-Column-with-at-Least-a-One/cpp-1428/main2.cpp @@ -0,0 +1,41 @@ +#include +#include + +using namespace std; + + +/// This is the BinaryMatrix's API interface. +/// You should not implement it, or speculate about its implementation +class BinaryMatrix { +public: + int get(int row, int col); + vector dimensions(); +}; + + +/// Search from Top Right to Bottom Left +/// Time Complexity: O(R + C) +/// Space Complexity: O(1) +class Solution { +public: + int leftMostColumnWithOne(BinaryMatrix &binaryMatrix) { + + vector dim = binaryMatrix.dimensions(); + int R = dim[0], C = dim[1]; + + int res = C, j = C - 1; + for(int i = 0; i < R; i ++){ + + for(; j >= 0; j --) + if(binaryMatrix.get(i, j)) res = j; + else break; + } + return res == C ? -1 : res; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1428-Leftmost-Column-with-at-Least-a-One/cpp-1428/main3.cpp b/1001-1500/1428-Leftmost-Column-with-at-Least-a-One/cpp-1428/main3.cpp new file mode 100644 index 00000000..fc79ac3c --- /dev/null +++ b/1001-1500/1428-Leftmost-Column-with-at-Least-a-One/cpp-1428/main3.cpp @@ -0,0 +1,47 @@ +#include +#include + +using namespace std; + + +/// This is the BinaryMatrix's API interface. +/// You should not implement it, or speculate about its implementation +class BinaryMatrix { +public: + int get(int row, int col); + vector dimensions(); +}; + + +/// Search from Top Right to Bottom Left + Binary Search +/// Time Complexity: O(R + C) +/// Space Complexity: O(1) +class Solution { +public: + int leftMostColumnWithOne(BinaryMatrix &binaryMatrix) { + + vector dim = binaryMatrix.dimensions(); + int R = dim[0], C = dim[1]; + + int res = C, j = C - 1; + for(int i = 0; i < R; i ++){ + + int l = 0, r = j + 1; + while(l < r){ + int mid = (l + r) / 2; + if(binaryMatrix.get(i, mid)) r = mid; + else l = mid + 1; + } + + res = min(res, l); + j = l - 1; + } + return res == C ? -1 : res; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1429-First-Unique-Number/cpp-1429/CMakeLists.txt b/1001-1500/1429-First-Unique-Number/cpp-1429/CMakeLists.txt new file mode 100644 index 00000000..93d4f799 --- /dev/null +++ b/1001-1500/1429-First-Unique-Number/cpp-1429/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(cpp_1429) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1429 main2.cpp) \ No newline at end of file diff --git a/1001-1500/1429-First-Unique-Number/cpp-1429/main.cpp b/1001-1500/1429-First-Unique-Number/cpp-1429/main.cpp new file mode 100644 index 00000000..b162180c --- /dev/null +++ b/1001-1500/1429-First-Unique-Number/cpp-1429/main.cpp @@ -0,0 +1,59 @@ +/// Source : https://leetcode.com/problems/first-unique-number/ +/// Author : liuyubobobo +/// Time : 2020-05-02 + +#include +#include +#include + +using namespace std; + + +/// Using HashSet +/// Time Complexity: init: O(n) +/// showFirstUnique: O(1) +/// add: O(n), amortized: O(1) +/// Space Complexity: O(n) +class FirstUnique { + +private: + unordered_set unique; + unordered_set duplicates; + vector data; + int res; + +public: + FirstUnique(vector& nums) : data(nums) { + + for(int num: nums) + if(!duplicates.count(num)){ + if(unique.count(num)) unique.erase(num), duplicates.insert(num); + else unique.insert(num); + } + + for(res = 0; res < nums.size(); res ++) + if(unique.count(nums[res])) break; + } + + int showFirstUnique() { + if(res < data.size()) return data[res]; + return -1; + } + + void add(int num) { + + data.push_back(num); + if(!duplicates.count(num)){ + if(unique.count(num)) unique.erase(num), duplicates.insert(num); + else unique.insert(num); + } + + while(res < data.size() && !unique.count(data[res])) res ++; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1429-First-Unique-Number/cpp-1429/main2.cpp b/1001-1500/1429-First-Unique-Number/cpp-1429/main2.cpp new file mode 100644 index 00000000..2cff0764 --- /dev/null +++ b/1001-1500/1429-First-Unique-Number/cpp-1429/main2.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/first-unique-number/ +/// Author : liuyubobobo +/// Time : 2020-05-02 + +#include +#include +#include +#include + +using namespace std; + + +/// Using HashMap + Queue +/// Time Complexity: init: O(n) +/// showFirstUnique: O(1) +/// add: O(n), amortized: O(1) +/// Space Complexity: O(n) +class FirstUnique { + +private: + unordered_map is_unique; + queue q; + +public: + FirstUnique(vector& nums) { + + for(int num: nums) add(num); + } + + int showFirstUnique() { + if(!q.empty()) return q.front(); + return -1; + } + + void add(int num) { + + if (!is_unique.count(num)) is_unique[num] = true; + else is_unique[num] = false; + + if(is_unique.count(num) && is_unique[num]) + q.push(num); + + while(!q.empty() && is_unique.count(q.front()) && !is_unique[q.front()]) + q.pop(); + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1430-Check-If-a-String-Is-a-Valid-Sequence-from-Root-to-Leaves-Path-in-a-Binary-Tree/cpp-1430/CMakeLists.txt b/1001-1500/1430-Check-If-a-String-Is-a-Valid-Sequence-from-Root-to-Leaves-Path-in-a-Binary-Tree/cpp-1430/CMakeLists.txt new file mode 100644 index 00000000..d05bc170 --- /dev/null +++ b/1001-1500/1430-Check-If-a-String-Is-a-Valid-Sequence-from-Root-to-Leaves-Path-in-a-Binary-Tree/cpp-1430/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(cpp_1430) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1430 main.cpp) \ No newline at end of file diff --git a/1001-1500/1430-Check-If-a-String-Is-a-Valid-Sequence-from-Root-to-Leaves-Path-in-a-Binary-Tree/cpp-1430/main.cpp b/1001-1500/1430-Check-If-a-String-Is-a-Valid-Sequence-from-Root-to-Leaves-Path-in-a-Binary-Tree/cpp-1430/main.cpp new file mode 100644 index 00000000..88d2f5cd --- /dev/null +++ b/1001-1500/1430-Check-If-a-String-Is-a-Valid-Sequence-from-Root-to-Leaves-Path-in-a-Binary-Tree/cpp-1430/main.cpp @@ -0,0 +1,51 @@ +/// Source : https://leetcode.com/problems/check-if-a-string-is-a-valid-sequence-from-root-to-leaves-path-in-a-binary-tree/ +/// Author : liuyubobobo +/// Time : 2020-05-02 + +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(|num|) + +/// 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 isValidSequence(TreeNode* root, vector& arr) { + + if(!root) return false; + if(root->val != arr[0]) return false; + return ok(root, arr, 0); + } + +private: + bool ok(TreeNode* node, vector& arr, int index){ + + if(index + 1 == arr.size()) return !node->left && !node->right; + if(node->left && node->left->val == arr[index + 1] && + ok(node->left, arr, index + 1)) return true; + if(node->right && node->right->val == arr[index + 1] && + ok(node->right, arr, index + 1)) return true; + return false; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1431-Kids-With-the-Greatest-Number-of-Candies/cpp-1431/CMakeLists.txt b/1001-1500/1431-Kids-With-the-Greatest-Number-of-Candies/cpp-1431/CMakeLists.txt new file mode 100644 index 00000000..fcc78bd6 --- /dev/null +++ b/1001-1500/1431-Kids-With-the-Greatest-Number-of-Candies/cpp-1431/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(cpp_1431) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1431 main.cpp) \ No newline at end of file diff --git a/1001-1500/1431-Kids-With-the-Greatest-Number-of-Candies/cpp-1431/main.cpp b/1001-1500/1431-Kids-With-the-Greatest-Number-of-Candies/cpp-1431/main.cpp new file mode 100644 index 00000000..c30d08e2 --- /dev/null +++ b/1001-1500/1431-Kids-With-the-Greatest-Number-of-Candies/cpp-1431/main.cpp @@ -0,0 +1,30 @@ +/// Source : https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/ +/// Author : liuyubobobo +/// Time : 2020-05-02 + +#include +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + vector kidsWithCandies(vector& candies, int extraCandies) { + + vector res; + int maxv = *max_element(candies.begin(), candies.end()); + for(int e: candies) + res.push_back(e + extraCandies >= maxv); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1432-Max-Difference-You-Can-Get-From-Changing-an-Integer/cpp-1432/CMakeLists.txt b/1001-1500/1432-Max-Difference-You-Can-Get-From-Changing-an-Integer/cpp-1432/CMakeLists.txt new file mode 100644 index 00000000..2c6b202e --- /dev/null +++ b/1001-1500/1432-Max-Difference-You-Can-Get-From-Changing-an-Integer/cpp-1432/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(cpp_1432) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1432 main.cpp) \ No newline at end of file diff --git a/1001-1500/1432-Max-Difference-You-Can-Get-From-Changing-an-Integer/cpp-1432/main.cpp b/1001-1500/1432-Max-Difference-You-Can-Get-From-Changing-an-Integer/cpp-1432/main.cpp new file mode 100644 index 00000000..902a485e --- /dev/null +++ b/1001-1500/1432-Max-Difference-You-Can-Get-From-Changing-an-Integer/cpp-1432/main.cpp @@ -0,0 +1,44 @@ +/// Source : https://leetcode.com/problems/max-difference-you-can-get-from-changing-an-integer/ +/// Author : liuyubobobo +/// Time : 2020-05-02 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(9 * 9 ( lognum) +/// Space Complexity: O(1) +class Solution { +public: + int maxDiff(int num) { + + vector v; + while(num) v.push_back(num % 10), num /= 10; + reverse(v.begin(), v.end()); + + int minv = INT_MAX, maxv = INT_MIN; + for(int x = 0; x <= 9; x ++) + for(int y = 0; y <= 9; y ++){ + vector t = v; + for(int& e: t) if(e == x) e = y; + if(t[0] == 0) continue; + + int x = 0; + for(int e: t) x = x * 10 + e; + minv = min(minv, x); + maxv = max(maxv, x); + } + return maxv - minv; + } +}; + + +int main() { + + cout << Solution().maxDiff(555) << endl; + + return 0; +} diff --git a/1001-1500/1433-Check-If-a-String-Can-Break-Another-String/cpp-1433/CMakeLists.txt b/1001-1500/1433-Check-If-a-String-Can-Break-Another-String/cpp-1433/CMakeLists.txt new file mode 100644 index 00000000..93d79e86 --- /dev/null +++ b/1001-1500/1433-Check-If-a-String-Can-Break-Another-String/cpp-1433/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(cpp_1433) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1433 main2.cpp) \ No newline at end of file diff --git a/1001-1500/1433-Check-If-a-String-Can-Break-Another-String/cpp-1433/main.cpp b/1001-1500/1433-Check-If-a-String-Can-Break-Another-String/cpp-1433/main.cpp new file mode 100644 index 00000000..c453a30e --- /dev/null +++ b/1001-1500/1433-Check-If-a-String-Can-Break-Another-String/cpp-1433/main.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/check-if-a-string-can-break-another-string/ +/// Author : liuyubobobo +/// Time : 2020-05-02 + +#include + +using namespace std; + + +/// Sorting and Greedy +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + bool checkIfCanBreak(string s1, string s2) { + + int n = s1.size(); + + sort(s1.begin(), s1.end()); + sort(s2.begin(), s2.end()); + + int i = 0; + for(i = 0; i < n; i ++) if(s1[i] < s2[i]) break; + if(i == n) return true; + + i = 0; + for(i = 0; i < n; i ++) if(s2[i] < s1[i]) break; + if(i == n) return true; + + return false; + } +}; + + +int main() { + + cout << Solution().checkIfCanBreak("abc", "xya") << endl; + // 1 + + cout << Solution().checkIfCanBreak("abe", "acd") << endl; + // 0 + + cout << Solution().checkIfCanBreak("leetcodee", "interview") << endl; + // 1 + + return 0; +} diff --git a/1001-1500/1433-Check-If-a-String-Can-Break-Another-String/cpp-1433/main2.cpp b/1001-1500/1433-Check-If-a-String-Can-Break-Another-String/cpp-1433/main2.cpp new file mode 100644 index 00000000..eac9e421 --- /dev/null +++ b/1001-1500/1433-Check-If-a-String-Can-Break-Another-String/cpp-1433/main2.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/check-if-a-string-can-break-another-string/ +/// Author : liuyubobobo +/// Time : 2020-05-02 + +#include +#include + +using namespace std; + + +/// Using HahsMap and Greedy +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + bool checkIfCanBreak(string s1, string s2) { + + int n = s1.size(); + + vector set1(26, 0); + for(char c: s1) set1[c - 'a'] ++; + + vector set2(26, 0); + for(char c: s2) set2[c - 'a'] ++; + + return cover(set1, set2) || cover(set2, set1); + } + +private: + bool cover(const vector& set1, const vector& set2){ + + int a = 0, b = 0; + for(int i = 0; i < 26; i ++){ + a += set1[i], b += set2[i]; + if(a < b) return false; + } + return true; + } +}; + + +int main() { + + cout << Solution().checkIfCanBreak("abc", "xya") << endl; + // 1 + + cout << Solution().checkIfCanBreak("abe", "acd") << endl; + // 0 + + cout << Solution().checkIfCanBreak("leetcodee", "interview") << endl; + // 1 + + return 0; +} diff --git a/1001-1500/1434-Number-of-Ways-to-Wear-Different-Hats-to-Each-Other/cpp-1434/CMakeLists.txt b/1001-1500/1434-Number-of-Ways-to-Wear-Different-Hats-to-Each-Other/cpp-1434/CMakeLists.txt new file mode 100644 index 00000000..0a80182e --- /dev/null +++ b/1001-1500/1434-Number-of-Ways-to-Wear-Different-Hats-to-Each-Other/cpp-1434/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(cpp_1434) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1434 main3.cpp) \ No newline at end of file diff --git a/1001-1500/1434-Number-of-Ways-to-Wear-Different-Hats-to-Each-Other/cpp-1434/main.cpp b/1001-1500/1434-Number-of-Ways-to-Wear-Different-Hats-to-Each-Other/cpp-1434/main.cpp new file mode 100644 index 00000000..55f693fa --- /dev/null +++ b/1001-1500/1434-Number-of-Ways-to-Wear-Different-Hats-to-Each-Other/cpp-1434/main.cpp @@ -0,0 +1,62 @@ +/// Source : https://leetcode.com/problems/number-of-ways-to-wear-different-hats-to-each-other/ +/// Author : liuyubobobo +/// Time : 2020-05-02 + +#include +#include + +using namespace std; + + +/// State Compression + Memory Search +/// Time Complexity: O(n * 40 * (1 << n)) +/// Space Complexity: O(n + 40 * (1 << n)) +class Solution { + +private: + const int MOD = 1e9 + 7; + int n; + +public: + int numberWays(vector>& hats) { + + n = hats.size(); + for(vector& v: hats) for(int& e: v) e --; + + vector> g(40, vector()); + for(int i = 0; i < hats.size(); i ++) + for(int hat: hats[i]) g[hat].push_back(i); + + vector> dp(40, vector(1 << n, -1)); + return dfs(g, 0, 0, dp); + } + +private: + int dfs(const vector>& g, int index, int state, + vector>& dp){ + + if(state == (1 << n) - 1) return 1; + if(index == 40) return 0; + if(dp[index][state] != -1) return dp[index][state]; + + int res = dfs(g, index + 1, state, dp); + for(int e: g[index]) + if((state & (1 << e)) == 0) + res = (res + dfs(g, index + 1, state | (1 << e), dp)) % MOD; + return dp[index][state] = res; + } +}; + + +int main() { + + vector> hats1 = {{3,4},{4,5},{5}}; + cout << Solution().numberWays(hats1) << endl; + // 1 + + vector> hats2 = {{3,5, 1},{3,5}}; + cout << Solution().numberWays(hats2) << endl; + // 4 + + return 0; +} diff --git a/1001-1500/1434-Number-of-Ways-to-Wear-Different-Hats-to-Each-Other/cpp-1434/main2.cpp b/1001-1500/1434-Number-of-Ways-to-Wear-Different-Hats-to-Each-Other/cpp-1434/main2.cpp new file mode 100644 index 00000000..23665dd2 --- /dev/null +++ b/1001-1500/1434-Number-of-Ways-to-Wear-Different-Hats-to-Each-Other/cpp-1434/main2.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/number-of-ways-to-wear-different-hats-to-each-other/ +/// Author : liuyubobobo +/// Time : 2020-05-02 + +#include +#include + +using namespace std; + + +/// State Compression + DP +/// Time Complexity: O(n * 40 * (1 << n)) +/// Space Complexity: O(n + 40 * (1 << n)) +class Solution { + +private: + const int MOD = 1e9 + 7; + +public: + int numberWays(vector>& hats) { + + int n = hats.size(); + for(vector& v: hats) for(int& e: v) e --; + + vector> g(40, vector()); + for(int i = 0; i < hats.size(); i ++) + for(int hat: hats[i]) g[hat].push_back(i); + + vector> dp(40, vector(1 << n, 0)); + dp[0][0] = 1; + for(int e: g[0]) dp[0][1 << e] = 1; + for(int index = 1; index < 40; index ++) + for(int state = 0; state < (1 << n); state ++){ + dp[index][state] = dp[index - 1][state]; + for(int e: g[index]) + if((1 << e) & state){ + dp[index][state] += dp[index - 1][state - (1 << e)]; + dp[index][state] %= MOD; + } + } + return dp[39][(1 << n) - 1]; + } +}; + + +int main() { + + vector> hats1 = {{3,4},{4,5},{5}}; + cout << Solution().numberWays(hats1) << endl; + // 1 + + vector> hats2 = {{3,5, 1},{3,5}}; + cout << Solution().numberWays(hats2) << endl; + // 4 + + return 0; +} diff --git a/1001-1500/1434-Number-of-Ways-to-Wear-Different-Hats-to-Each-Other/cpp-1434/main3.cpp b/1001-1500/1434-Number-of-Ways-to-Wear-Different-Hats-to-Each-Other/cpp-1434/main3.cpp new file mode 100644 index 00000000..6f103ad9 --- /dev/null +++ b/1001-1500/1434-Number-of-Ways-to-Wear-Different-Hats-to-Each-Other/cpp-1434/main3.cpp @@ -0,0 +1,58 @@ +/// Source : https://leetcode.com/problems/number-of-ways-to-wear-different-hats-to-each-other/ +/// Author : liuyubobobo +/// Time : 2020-05-02 + +#include +#include + +using namespace std; + + +/// State Compression + DP +/// Space Optimized +/// Time Complexity: O(n * 40 * (1 << n)) +/// Space Complexity: O(n + (1 << n)) +class Solution { + +private: + const int MOD = 1e9 + 7; + +public: + int numberWays(vector>& hats) { + + int n = hats.size(); + for(vector& v: hats) for(int& e: v) e --; + + vector> g(40, vector()); + for(int i = 0; i < hats.size(); i ++) + for(int hat: hats[i]) g[hat].push_back(i); + + vector> dp(2, vector(1 << n, 0)); + dp[0][0] = 1; + for(int e: g[0]) dp[0][1 << e] = 1; + for(int index = 1; index < 40; index ++) + for(int state = 0; state < (1 << n); state ++){ + dp[index & 1][state] = dp[(index - 1) & 1][state]; + for(int e: g[index]) + if((1 << e) & state){ + dp[index & 1][state] += dp[(index - 1) & 1][state - (1 << e)]; + dp[index & 1][state] %= MOD; + } + } + return dp[1][(1 << n) - 1]; + } +}; + + +int main() { + + vector> hats1 = {{3,4},{4,5},{5}}; + cout << Solution().numberWays(hats1) << endl; + // 1 + + vector> hats2 = {{3,5, 1},{3,5}}; + cout << Solution().numberWays(hats2) << endl; + // 4 + + return 0; +} diff --git a/1001-1500/1436-Destination-City/cpp-1436/CMakeLists.txt b/1001-1500/1436-Destination-City/cpp-1436/CMakeLists.txt new file mode 100644 index 00000000..446d8265 --- /dev/null +++ b/1001-1500/1436-Destination-City/cpp-1436/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main2.cpp) \ No newline at end of file diff --git a/1001-1500/1436-Destination-City/cpp-1436/main.cpp b/1001-1500/1436-Destination-City/cpp-1436/main.cpp new file mode 100644 index 00000000..e5e33501 --- /dev/null +++ b/1001-1500/1436-Destination-City/cpp-1436/main.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/destination-city/ +/// Author : liuyubobobo +/// Time : 2020-05-02 + +#include +#include +#include + +using namespace std; + + +/// Graph Construction +/// Time Complexity:O(n) +/// Space Complexity: O(n) +class Solution { +public: + string destCity(vector>& paths) { + + unordered_map> g; + for(vector& path: paths) + g[path[0]].push_back(path[1]), g[path[1]]; + + for(const pair>& p: g) + if(p.second.size() == 0) return p.first; + return ""; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1436-Destination-City/cpp-1436/main2.cpp b/1001-1500/1436-Destination-City/cpp-1436/main2.cpp new file mode 100644 index 00000000..28ad7cf4 --- /dev/null +++ b/1001-1500/1436-Destination-City/cpp-1436/main2.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/destination-city/ +/// Author : liuyubobobo +/// Time : 2020-05-03 + +#include +#include +#include + +using namespace std; + + +/// Calculate outdegree +/// Time Complexity:O(n) +/// Space Complexity: O(n) +class Solution { +public: + string destCity(vector>& paths) { + + unordered_map g; + for(vector& path: paths) + g[path[0]] ++, g[path[1]]; + + for(const pair& p: g) + if(p.second == 0) return p.first; + return ""; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1437-Check-If-All-1s-Are-at-Least-Length-K-Places-Away/cpp-1437/CMakeLists.txt b/1001-1500/1437-Check-If-All-1s-Are-at-Least-Length-K-Places-Away/cpp-1437/CMakeLists.txt new file mode 100644 index 00000000..545e47b8 --- /dev/null +++ b/1001-1500/1437-Check-If-All-1s-Are-at-Least-Length-K-Places-Away/cpp-1437/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1001-1500/1437-Check-If-All-1s-Are-at-Least-Length-K-Places-Away/cpp-1437/main.cpp b/1001-1500/1437-Check-If-All-1s-Are-at-Least-Length-K-Places-Away/cpp-1437/main.cpp new file mode 100644 index 00000000..5cd716ab --- /dev/null +++ b/1001-1500/1437-Check-If-All-1s-Are-at-Least-Length-K-Places-Away/cpp-1437/main.cpp @@ -0,0 +1,31 @@ +/// Source : https://leetcode.com/problems/check-if-all-1s-are-at-least-length-k-places-away/ +/// Author : liuyubobobo +/// Time : 2020-05-02 + +#include +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + bool kLengthApart(vector& nums, int k) { + + for(int start = -1, i = 0; i < nums.size(); i ++) + if(nums[i] == 1){ + if(start >= 0 && i - start - 1 < k) return false; + start = i; + } + return true; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1438-Longest-Continuous-Subarray-With-Absolute-Diff-Less-Than-or-Equal-to-Limit/cpp-1438/CMakeLists.txt b/1001-1500/1438-Longest-Continuous-Subarray-With-Absolute-Diff-Less-Than-or-Equal-to-Limit/cpp-1438/CMakeLists.txt new file mode 100644 index 00000000..664de921 --- /dev/null +++ b/1001-1500/1438-Longest-Continuous-Subarray-With-Absolute-Diff-Less-Than-or-Equal-to-Limit/cpp-1438/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main4.cpp) \ No newline at end of file diff --git a/1001-1500/1438-Longest-Continuous-Subarray-With-Absolute-Diff-Less-Than-or-Equal-to-Limit/cpp-1438/main.cpp b/1001-1500/1438-Longest-Continuous-Subarray-With-Absolute-Diff-Less-Than-or-Equal-to-Limit/cpp-1438/main.cpp new file mode 100644 index 00000000..c1dbc278 --- /dev/null +++ b/1001-1500/1438-Longest-Continuous-Subarray-With-Absolute-Diff-Less-Than-or-Equal-to-Limit/cpp-1438/main.cpp @@ -0,0 +1,60 @@ +/// Source : https://leetcode.com/problems/longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/ +/// Author : liuyubobobo +/// Time : 2020-05-02 + +#include +#include +#include + +using namespace std; + + +/// Sliding Window + Map +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + int longestSubarray(vector& nums, int limit) { + + map tree; + tree[nums[0]] ++; + + int res = 1; + for(int l = 0, i = 1; i < nums.size(); i ++){ + tree[nums[i]] ++; + + if(abs(tree.rbegin()->first - tree.begin()->first) <= limit) + res = max(res, i - l + 1); + else{ + while(!tree.empty() && abs(tree.rbegin()->first - tree.begin()->first) > limit){ + tree[nums[l]] --; + if(tree[nums[l]] == 0) tree.erase(nums[l]); + l ++; + } + } + } + return res; + } +}; + + +int main() { + + vector nums1 = {8, 2, 4, 7}; + cout << Solution().longestSubarray(nums1, 4) << endl; + // 2 + + vector nums2 = {10,1,2,4,7,2}; + cout << Solution().longestSubarray(nums2, 5) << endl; + // 4 + + vector nums3 = {4,2,2,2,4,4,2,2}; + cout << Solution().longestSubarray(nums3, 0) << endl; + // 3 + + vector nums4 = {4,10,2,6,1}; + cout << Solution().longestSubarray(nums4, 10) << endl; + // 5 + + return 0; +} diff --git a/1001-1500/1438-Longest-Continuous-Subarray-With-Absolute-Diff-Less-Than-or-Equal-to-Limit/cpp-1438/main2.cpp b/1001-1500/1438-Longest-Continuous-Subarray-With-Absolute-Diff-Less-Than-or-Equal-to-Limit/cpp-1438/main2.cpp new file mode 100644 index 00000000..30c4b8f5 --- /dev/null +++ b/1001-1500/1438-Longest-Continuous-Subarray-With-Absolute-Diff-Less-Than-or-Equal-to-Limit/cpp-1438/main2.cpp @@ -0,0 +1,119 @@ +/// Source : https://leetcode.com/problems/longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/ +/// Author : liuyubobobo +/// Time : 2020-05-02 + +#include +#include +#include + +using namespace std; + + +/// Sliding Window + Segment Tree +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class SegmentTree{ + +private: + int n; + vector data, maxtree, mintree; + +public: + SegmentTree(const vector& initData): data(initData.begin(), + initData.end()), n(initData.size()), maxtree(4 * n, 0), mintree(4 * n, 0){ + buildSegTree(0, 0, n - 1); + } + + int query_min(int l, int r){ + return query_min(0, 0, n - 1, l, r); + } + + int query_max(int l, int r){ + return query_max(0, 0, n - 1, l, r); + } + +private: + void buildSegTree(int treeID, int l, int r){ + + if(l == r){ + mintree[treeID] = maxtree[treeID] = data[l]; + return; + } + + int mid = (l + r) / 2; + buildSegTree(treeID * 2 + 1, l, mid); + buildSegTree(treeID * 2 + 2, mid + 1, r); + mintree[treeID] = min(mintree[treeID * 2 + 1], mintree[treeID * 2 + 2]); + maxtree[treeID] = max(maxtree[treeID * 2 + 1], maxtree[treeID * 2 + 2]); + return; + } + + int query_min(int treeID, int l, int r, int ql, int qr){ + + if(ql == l && qr == r) + return mintree[treeID]; + + int mid = (l + r) / 2; + if(qr <= mid) return query_min(treeID * 2 + 1, l, mid, ql, qr); + else if(ql > mid) return query_min(treeID * 2 + 2, mid + 1, r, ql, qr); + + int resl = query_min(treeID * 2 + 1, l, mid, ql, mid); + int resr = query_min(treeID * 2 + 2, mid + 1, r, mid + 1, qr); + return min(resl, resr); + } + + int query_max(int treeID, int l, int r, int ql, int qr){ + + if(ql == l && qr == r) + return maxtree[treeID]; + + int mid = (l + r) / 2; + if(qr <= mid) return query_max(treeID * 2 + 1, l, mid, ql, qr); + else if(ql > mid) return query_max(treeID * 2 + 2, mid + 1, r, ql, qr); + + int resl = query_max(treeID * 2 + 1, l, mid, ql, mid); + int resr = query_max(treeID * 2 + 2, mid + 1, r, mid + 1, qr); + return max(resl, resr); + } +}; + +class Solution { +public: + int longestSubarray(vector& nums, int limit) { + + SegmentTree tree(nums); + int res = 1; + for(int l = 0, i = 1; i < nums.size(); i ++){ + + if(tree.query_max(l, i ) - tree.query_min(l, i) <= limit) + res = max(res, i - l + 1); + else{ + while(tree.query_max(l, i) - tree.query_min(l, i) > limit) + l ++; + } + } + return res; + } +}; + + +int main() { + + vector nums1 = {8, 2, 4, 7}; + cout << Solution().longestSubarray(nums1, 4) << endl; + // 2 + + vector nums2 = {10,1,2,4,7,2}; + cout << Solution().longestSubarray(nums2, 5) << endl; + // 4 + + vector nums3 = {4,2,2,2,4,4,2,2}; + cout << Solution().longestSubarray(nums3, 0) << endl; + // 3 + + vector nums4 = {4,10,2,6,1}; + cout << Solution().longestSubarray(nums4, 10) << endl; + // 5 + + return 0; +} diff --git a/1001-1500/1438-Longest-Continuous-Subarray-With-Absolute-Diff-Less-Than-or-Equal-to-Limit/cpp-1438/main3.cpp b/1001-1500/1438-Longest-Continuous-Subarray-With-Absolute-Diff-Less-Than-or-Equal-to-Limit/cpp-1438/main3.cpp new file mode 100644 index 00000000..8ab2a30f --- /dev/null +++ b/1001-1500/1438-Longest-Continuous-Subarray-With-Absolute-Diff-Less-Than-or-Equal-to-Limit/cpp-1438/main3.cpp @@ -0,0 +1,119 @@ +/// Source : https://leetcode.com/problems/longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/ +/// Author : liuyubobobo +/// Time : 2020-05-02 + +#include +#include +#include +#include + +using namespace std; + + +/// Sliding Window + Sqrt Decomposition +/// Time Complexity: O(n*sqrt(n)) +/// Space Complexity: O(n) +class SQRTDecomposition{ + +private: + vector data; + int n; + int block_size; + + vector minblocks, maxblocks; + +public: + SQRTDecomposition(vector& data) : data(data.begin(), data.end()), + n(data.size()), block_size((int)ceil(sqrt(n))){ + + int cur_min, cur_max; + for(int i = 0; i < data.size(); i ++){ + if(i % block_size == block_size - 1){ + minblocks.push_back(cur_min); + maxblocks.push_back(cur_max); + cur_min = INT_MAX, cur_max = INT_MIN; + } + cur_min = min(cur_min, data[i]); + cur_max = max(cur_max, data[i]); + } + } + + int query_min(int l, int r){ + + int block_l = l / block_size, block_r = r / block_size; + + int res = data[l]; + if(block_l == block_r){ + for(int i = l + 1; i <= r; i ++) + res = min(res, data[i]); + } + else{ + int limit = (block_l + 1) * block_size; + for(int i = l + 1; i < limit; i ++) + res = min(res, data[i]); + for(int i = block_l + 1; i < block_r; i ++) + res = min(res, minblocks[i]); + for(int i = block_r * block_size; i <= r; i ++) + res = min(res, data[i]); + } + return res; + } + + int query_max(int l, int r){ + + int block_l = l / block_size, block_r = r / block_size; + + int res = data[l]; + if(block_l == block_r){ + for(int i = l + 1; i <= r; i ++) + res = max(res, data[i]); + } + else{ + int limit = (block_l + 1) * block_size; + for(int i = l + 1; i < limit; i ++) + res = max(res, data[i]); + for(int i = block_l + 1; i < block_r; i ++) + res = max(res, maxblocks[i]); + for(int i = block_r * block_size; i <= r; i ++) + res = max(res, data[i]); + } + return res; + } +}; + +class Solution { +public: + int longestSubarray(vector& nums, int limit) { + + SQRTDecomposition decom(nums); + int res = 1; + for(int l = 0, i = 1; i < nums.size(); i ++){ + if(decom.query_max(l, i ) - decom.query_min(l, i) <= limit) + res = max(res, i - l + 1); + else while(decom.query_max(l, i) - decom.query_min(l, i) > limit) l ++; + } + return res; + } +}; + + +int main() { + + vector nums1 = {8, 2, 4, 7}; + cout << Solution().longestSubarray(nums1, 4) << endl; + // 2 + + vector nums2 = {10,1,2,4,7,2}; + cout << Solution().longestSubarray(nums2, 5) << endl; + // 4 + + vector nums3 = {4,2,2,2,4,4,2,2}; + cout << Solution().longestSubarray(nums3, 0) << endl; + // 3 + + vector nums4 = {4,10,2,6,1}; + cout << Solution().longestSubarray(nums4, 10) << endl; + // 5 + + return 0; +} diff --git a/1001-1500/1438-Longest-Continuous-Subarray-With-Absolute-Diff-Less-Than-or-Equal-to-Limit/cpp-1438/main4.cpp b/1001-1500/1438-Longest-Continuous-Subarray-With-Absolute-Diff-Less-Than-or-Equal-to-Limit/cpp-1438/main4.cpp new file mode 100644 index 00000000..d8c33d63 --- /dev/null +++ b/1001-1500/1438-Longest-Continuous-Subarray-With-Absolute-Diff-Less-Than-or-Equal-to-Limit/cpp-1438/main4.cpp @@ -0,0 +1,62 @@ +/// Source : https://leetcode.com/problems/longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/ +/// Author : liuyubobobo +/// Time : 2020-05-02 + +#include +#include +#include + +using namespace std; + + +/// Sliding Window + Mono Queue +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int longestSubarray(vector& nums, int limit) { + + deque inc = {0}, dec = {0}; + int res = 1; + for(int l = 0, i = 1; i < nums.size(); i ++){ + while(!inc.empty() && nums[i] < nums[inc.back()]) inc.pop_back(); + inc.push_back(i); + + while(!dec.empty() && nums[i] > nums[dec.back()]) dec.pop_back(); + dec.push_back(i); + + if(abs(nums[inc.front()] - nums[dec.front()]) <= limit) + res = max(res, i - l + 1); + else{ + while(!inc.empty() && !dec.empty() && abs(nums[inc.front()] - nums[dec.front()]) > limit){ + if(!inc.empty() && inc.front() == l) inc.pop_front(); + if(!dec.empty() && dec.front() == l) dec.pop_front(); + l ++; + } + } + } + return res; + } +}; + + +int main() { + + vector nums1 = {8, 2, 4, 7}; + cout << Solution().longestSubarray(nums1, 4) << endl; + // 2 + + vector nums2 = {10,1,2,4,7,2}; + cout << Solution().longestSubarray(nums2, 5) << endl; + // 4 + + vector nums3 = {4,2,2,2,4,4,2,2}; + cout << Solution().longestSubarray(nums3, 0) << endl; + // 3 + + vector nums4 = {4,10,2,6,1}; + cout << Solution().longestSubarray(nums4, 10) << endl; + // 5 + + return 0; +} diff --git a/1001-1500/1439-Find-the-Kth-Smallest-Sum-of-a-Matrix-With-Sorted-Rows/cpp-1439/CMakeLists.txt b/1001-1500/1439-Find-the-Kth-Smallest-Sum-of-a-Matrix-With-Sorted-Rows/cpp-1439/CMakeLists.txt new file mode 100644 index 00000000..a965d66f --- /dev/null +++ b/1001-1500/1439-Find-the-Kth-Smallest-Sum-of-a-Matrix-With-Sorted-Rows/cpp-1439/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main3.cpp) \ No newline at end of file diff --git a/1001-1500/1439-Find-the-Kth-Smallest-Sum-of-a-Matrix-With-Sorted-Rows/cpp-1439/main.cpp b/1001-1500/1439-Find-the-Kth-Smallest-Sum-of-a-Matrix-With-Sorted-Rows/cpp-1439/main.cpp new file mode 100644 index 00000000..e5e9b5ae --- /dev/null +++ b/1001-1500/1439-Find-the-Kth-Smallest-Sum-of-a-Matrix-With-Sorted-Rows/cpp-1439/main.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/ +/// Author : liuyubobobo +/// Time : 2020-05-03 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Keep first k elements int every row +/// Time Complexity: O(m * (n * k + n * k * log(n * k))) +/// Space Complexity: O(n * k) +class Solution { + +public: + int kthSmallest(vector>& mat, int k) { + + vector res = {0}; + for(const vector& row: mat){ + + vector tres; + for(int a: res) for(int b: row) tres.push_back(a + b); + sort(tres.begin(), tres.end()); + while(tres.size() > k) tres.pop_back(); + res = tres; + } + return res.back(); + } +}; + + +int main() { + + vector> mat1 = {{1, 3, 11}, {2, 4, 6}}; + cout << Solution().kthSmallest(mat1, 5) << endl; + // 7 + + vector> mat2 = {{1, 3, 11}, {2, 4, 6}}; + cout << Solution().kthSmallest(mat2, 9) << endl; + // 17 + + vector> mat3 = {{1, 10, 10}, {1, 4, 5}, {2, 3, 6}}; + cout << Solution().kthSmallest(mat3, 7) << endl; + // 9 + + vector> mat4 = {{1, 1, 10}, {2, 2, 9}}; + cout << Solution().kthSmallest(mat4, 7) << endl; + // 12 + + return 0; +} diff --git a/1001-1500/1439-Find-the-Kth-Smallest-Sum-of-a-Matrix-With-Sorted-Rows/cpp-1439/main2.cpp b/1001-1500/1439-Find-the-Kth-Smallest-Sum-of-a-Matrix-With-Sorted-Rows/cpp-1439/main2.cpp new file mode 100644 index 00000000..55d4310b --- /dev/null +++ b/1001-1500/1439-Find-the-Kth-Smallest-Sum-of-a-Matrix-With-Sorted-Rows/cpp-1439/main2.cpp @@ -0,0 +1,55 @@ +/// Source : https://leetcode.com/problems/find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/ +/// Author : liuyubobobo +/// Time : 2020-05-03 + +#include +#include +#include + +using namespace std; + + +/// Brute Force - Using Priority Queue to optimize +/// Keep first k elements int every row +/// Time Complexity: O(m * (n * k + n * k * logk)) +/// Space Complexity: O(n * k) +class Solution { + +public: + int kthSmallest(vector>& mat, int k) { + + vector res = {0}; + priority_queue pq; + for(const vector& row: mat){ + for(int a: res) for(int b: row){ + pq.push(a + b); + if(pq.size() > k) pq.pop(); + } + res.clear(); + while (!pq.empty()) res.push_back(pq.top()), pq.pop(); + } + return res[0]; + } +}; + + +int main() { + + vector> mat1 = {{1, 3, 11}, {2, 4, 6}}; + cout << Solution().kthSmallest(mat1, 5) << endl; + // 7 + + vector> mat2 = {{1, 3, 11}, {2, 4, 6}}; + cout << Solution().kthSmallest(mat2, 9) << endl; + // 17 + + vector> mat3 = {{1, 10, 10}, {1, 4, 5}, {2, 3, 6}}; + cout << Solution().kthSmallest(mat3, 7) << endl; + // 9 + + vector> mat4 = {{1, 1, 10}, {2, 2, 9}}; + cout << Solution().kthSmallest(mat4, 7) << endl; + // 12 + + return 0; +} diff --git a/1001-1500/1439-Find-the-Kth-Smallest-Sum-of-a-Matrix-With-Sorted-Rows/cpp-1439/main3.cpp b/1001-1500/1439-Find-the-Kth-Smallest-Sum-of-a-Matrix-With-Sorted-Rows/cpp-1439/main3.cpp new file mode 100644 index 00000000..21b93c06 --- /dev/null +++ b/1001-1500/1439-Find-the-Kth-Smallest-Sum-of-a-Matrix-With-Sorted-Rows/cpp-1439/main3.cpp @@ -0,0 +1,85 @@ +/// Source : https://leetcode.com/problems/find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/ +/// Author : liuyubobobo +/// Time : 2020-05-02 + +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(log(maxnum - minnum) * k) +/// Space Complexity: O(R) +class Solution { + +private: + int R, C; + +public: + int kthSmallest(vector>& mat, int k) { + + R = mat.size(), C = mat[0].size(); + + int minv = 0; + for(int i = 0; i < R; i ++) minv += mat[i][0]; + + if(C == 1) return minv; + + int maxv = 0; + for(int i = 0; i < R; i ++) maxv += mat[i].back(); + + int l = minv, r = maxv; + while(l < r){ + int mid = (l + r) / 2; + if(count(mat, mid) >= k) r = mid; + else l = mid + 1; + } + return l; + } + +private: + int count(const vector>& mat, int x){ + return count(mat, 0, x); + } + + int count(const vector>& mat, int start, int x){ + + if(start == R) return 1; + + int sum = 0; + + int i, j; + for(i = R - 1; i > start; i --) sum += mat[i][0]; + for(j = C - 1; j >= 0; j --) if(mat[start][j] <= x - sum) break; + + int res = 0; + for(; j >= 0; j --) { + res += count(mat, start + 1, x - mat[start][j]); + if(res > 200) return res; + } + return res; + } +}; + + +int main() { + + vector> mat1 = {{1, 3, 11}, {2, 4, 6}}; + cout << Solution().kthSmallest(mat1, 5) << endl; + // 7 + + vector> mat2 = {{1, 3, 11}, {2, 4, 6}}; + cout << Solution().kthSmallest(mat2, 9) << endl; + // 17 + + vector> mat3 = {{1, 10, 10}, {1, 4, 5}, {2, 3, 6}}; + cout << Solution().kthSmallest(mat3, 7) << endl; + // 9 + + vector> mat4 = {{1, 1, 10}, {2, 2, 9}}; + cout << Solution().kthSmallest(mat4, 7) << endl; + // 12 + + return 0; +} diff --git a/1001-1500/1441-Build-an-Array-With-Stack-Operations/cpp-1441/CMakeLists.txt b/1001-1500/1441-Build-an-Array-With-Stack-Operations/cpp-1441/CMakeLists.txt new file mode 100644 index 00000000..cb89cda6 --- /dev/null +++ b/1001-1500/1441-Build-an-Array-With-Stack-Operations/cpp-1441/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1001-1500/1441-Build-an-Array-With-Stack-Operations/cpp-1441/main.cpp b/1001-1500/1441-Build-an-Array-With-Stack-Operations/cpp-1441/main.cpp new file mode 100644 index 00000000..31488f16 --- /dev/null +++ b/1001-1500/1441-Build-an-Array-With-Stack-Operations/cpp-1441/main.cpp @@ -0,0 +1,32 @@ +/// Source : https://leetcode.com/problems/build-an-array-with-stack-operations/ +/// Author : liuyubobobo +/// Time : 2020-05-10 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + vector buildArray(vector& target, int n) { + + vector res; + int next = 1; + for(int t: target){ + while(t != next) res.push_back("Push"), res.push_back("Pop"), next ++; + res.push_back("Push"), next ++; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1442-Count-Triplets-That-Can-Form-Two-Arrays-of-Equal-XOR/cpp-1442/CMakeLists.txt b/1001-1500/1442-Count-Triplets-That-Can-Form-Two-Arrays-of-Equal-XOR/cpp-1442/CMakeLists.txt new file mode 100644 index 00000000..e6f5d34c --- /dev/null +++ b/1001-1500/1442-Count-Triplets-That-Can-Form-Two-Arrays-of-Equal-XOR/cpp-1442/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main2.cpp) \ No newline at end of file diff --git a/1001-1500/1442-Count-Triplets-That-Can-Form-Two-Arrays-of-Equal-XOR/cpp-1442/main.cpp b/1001-1500/1442-Count-Triplets-That-Can-Form-Two-Arrays-of-Equal-XOR/cpp-1442/main.cpp new file mode 100644 index 00000000..26292415 --- /dev/null +++ b/1001-1500/1442-Count-Triplets-That-Can-Form-Two-Arrays-of-Equal-XOR/cpp-1442/main.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/count-triplets-that-can-form-two-arrays-of-equal-xor/ +/// Author : liuyubobobo +/// Time : 2020-05-09 + +#include +#include + +using namespace std; + + +/// Presum + Brute Force +/// Time Complexity: O(n^3) +/// Space Complexity: O(n) +class Solution { +public: + int countTriplets(vector& arr) { + + int n = arr.size(); + vector pre(n + 1, 0); + for(int i = 0; i < arr.size(); i ++) + pre[i + 1] = pre[i] ^ arr[i]; + + int res = 0; + for(int i = 0; i < n; i ++) + for(int j = i + 1; j < n; j ++) + for(int k = j; k < n; k ++) + if(pre[j] ^ pre[i] == pre[k + 1] ^ pre[j]) + res ++; + return res; + } +}; + + +int main() { + + vector nums1 = {2, 3, 1, 6, 7}; + cout << Solution().countTriplets(nums1) << endl; + // 4 + + vector nums2 = {1, 1, 1, 1, 1}; + cout << Solution().countTriplets(nums2) << endl; + // 10 + + vector nums3 = {2, 3}; + cout << Solution().countTriplets(nums3) << endl; + // 0 + + vector nums4 = {7,11,12,9,5,2,7,17,22}; + cout << Solution().countTriplets(nums4) << endl; + // 8 + + return 0; +} diff --git a/1001-1500/1442-Count-Triplets-That-Can-Form-Two-Arrays-of-Equal-XOR/cpp-1442/main2.cpp b/1001-1500/1442-Count-Triplets-That-Can-Form-Two-Arrays-of-Equal-XOR/cpp-1442/main2.cpp new file mode 100644 index 00000000..c5e4c05e --- /dev/null +++ b/1001-1500/1442-Count-Triplets-That-Can-Form-Two-Arrays-of-Equal-XOR/cpp-1442/main2.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/count-triplets-that-can-form-two-arrays-of-equal-xor/ +/// Author : liuyubobobo +/// Time : 2020-05-10 + +#include +#include + +using namespace std; + + +/// Presum +/// Check equal xor sum, since a == b means a ^ a == b ^ a => a ^ b == 0 +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { +public: + int countTriplets(vector& arr) { + + int n = arr.size(); + vector pre(n + 1, 0); + for(int i = 0; i < arr.size(); i ++) + pre[i + 1] = pre[i] ^ arr[i]; + + int res = 0; + for(int i = 0; i < n; i ++) + for(int j = i + 1; j < n; j ++) + if(pre[j + 1] == pre[i]) + res += j - i; + return res; + } +}; + + +int main() { + + vector nums1 = {2, 3, 1, 6, 7}; + cout << Solution().countTriplets(nums1) << endl; + // 4 + + vector nums2 = {1, 1, 1, 1, 1}; + cout << Solution().countTriplets(nums2) << endl; + // 10 + + vector nums3 = {2, 3}; + cout << Solution().countTriplets(nums3) << endl; + // 0 + + vector nums4 = {7,11,12,9,5,2,7,17,22}; + cout << Solution().countTriplets(nums4) << endl; + // 8 + + return 0; +} diff --git a/1001-1500/1443-Minimum-Time-to-Collect-All-Apples-in-a-Tree/cpp-1443/CMakeLists.txt b/1001-1500/1443-Minimum-Time-to-Collect-All-Apples-in-a-Tree/cpp-1443/CMakeLists.txt new file mode 100644 index 00000000..94acd016 --- /dev/null +++ b/1001-1500/1443-Minimum-Time-to-Collect-All-Apples-in-a-Tree/cpp-1443/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1001-1500/1443-Minimum-Time-to-Collect-All-Apples-in-a-Tree/cpp-1443/main.cpp b/1001-1500/1443-Minimum-Time-to-Collect-All-Apples-in-a-Tree/cpp-1443/main.cpp new file mode 100644 index 00000000..03cfc680 --- /dev/null +++ b/1001-1500/1443-Minimum-Time-to-Collect-All-Apples-in-a-Tree/cpp-1443/main.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/minimum-time-to-collect-all-apples-in-a-tree/ +/// Author : liuyubobobo +/// Time : 2020-05-09 + +#include +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +private: + int apple = 0; + +public: + int minTime(int n, vector>& edges, vector& hasApple) { + + vector> g(n); + for(const vector& edge: edges) + g[edge[0]].insert(edge[1]), g[edge[1]].insert(edge[0]); + + return dfs(n, g, 0, -1, hasApple); + } + +private: + int dfs(int n, vector>& g, int v, int p, const vector& hasApple){ + + apple += hasApple[v]; + + int res = 0; + int cur = apple; + for(int next: g[v]) + if(next != p){ + int tres = dfs(n, g, next, v, hasApple); + if(apple != cur){ + res += 2 + tres; + cur = apple; + } + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1444-Number-of-Ways-of-Cutting-a-Pizza/cpp-1444/CMakeLists.txt b/1001-1500/1444-Number-of-Ways-of-Cutting-a-Pizza/cpp-1444/CMakeLists.txt new file mode 100644 index 00000000..2879627e --- /dev/null +++ b/1001-1500/1444-Number-of-Ways-of-Cutting-a-Pizza/cpp-1444/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main4.cpp) \ No newline at end of file diff --git a/1001-1500/1444-Number-of-Ways-of-Cutting-a-Pizza/cpp-1444/main.cpp b/1001-1500/1444-Number-of-Ways-of-Cutting-a-Pizza/cpp-1444/main.cpp new file mode 100644 index 00000000..4cf404f6 --- /dev/null +++ b/1001-1500/1444-Number-of-Ways-of-Cutting-a-Pizza/cpp-1444/main.cpp @@ -0,0 +1,74 @@ +/// Source : https://leetcode.com/problems/number-of-ways-of-cutting-a-pizza/ +/// Author : liuyubobobo +/// Time : 2020-05-09 + +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(k * R * C * (R + C)) +/// Space Complexity: O(k * R * C) +class Solution { + +private: + const int MOD = 1e9 + 7; + int R, C; + +public: + int ways(vector& pizza, int k) { + + R = pizza.size(), C = pizza[0].size(); + vector> cnt(R + 1, vector(C + 1, 0)); + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++) + cnt[i + 1][j + 1] = cnt[i][j + 1] + cnt[i + 1][j] - cnt[i][j] + (pizza[i][j] == 'A'); + + vector> dp(k, vector(R * C, -1)); + return dfs(k - 1, 0, cnt, dp); + } + +private: + int dfs(int k, int pos, const vector> &cnt, vector>& dp){ + + if(dp[k][pos] != -1) return dp[k][pos]; + + int x = pos / C, y = pos % C; + if(!k) return dp[k][pos] = ok(cnt, x, y, R - 1, C - 1); + + int res = 0; + for(int i = x + 1; i < R; i ++) + if(ok(cnt, x, y, i - 1, C - 1)) + res += dfs(k - 1, i * C + y, cnt, dp), res %= MOD; + + for(int j = y + 1; j < C; j ++) + if(ok(cnt, x, y, R - 1, j - 1)) + res += dfs(k - 1, x * C + j, cnt, dp), res %= MOD; + + return dp[k][pos] = res; + } + + bool ok(const vector>& cnt, int x1, int y1, int x2, int y2){ + return cnt[x2 + 1][y2 + 1] - cnt[x2 + 1][y1] - cnt[x1][y2 + 1] + cnt[x1][y1]; + } +}; + + +int main() { + + vector pizza1 = {"A..","AAA","..."}; + cout << Solution().ways(pizza1, 3) << endl; + // 3 + + vector pizza2 = {"A..","AA.","..."}; + cout << Solution().ways(pizza2, 3) << endl; + // 1 + + vector pizza3 = {"A..","A..","..."}; + cout << Solution().ways(pizza3, 1) << endl; + // 1 + + return 0; +} diff --git a/1001-1500/1444-Number-of-Ways-of-Cutting-a-Pizza/cpp-1444/main2.cpp b/1001-1500/1444-Number-of-Ways-of-Cutting-a-Pizza/cpp-1444/main2.cpp new file mode 100644 index 00000000..31e37b84 --- /dev/null +++ b/1001-1500/1444-Number-of-Ways-of-Cutting-a-Pizza/cpp-1444/main2.cpp @@ -0,0 +1,73 @@ +/// Source : https://leetcode.com/problems/number-of-ways-of-cutting-a-pizza/ +/// Author : liuyubobobo +/// Time : 2020-05-10 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(k * R * C * (R + C)) +/// Space Complexity: O(k * R * C) +class Solution { + +private: + const int MOD = 1e9 + 7; + int R, C; + +public: + int ways(vector& pizza, int k) { + + R = pizza.size(), C = pizza[0].size(); + vector> cnt(R + 1, vector(C + 1, 0)); + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++) + cnt[i + 1][j + 1] = cnt[i][j + 1] + cnt[i + 1][j] - cnt[i][j] + (pizza[i][j] == 'A'); + + vector> dp(k, vector(R * C, 0)); + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++) + dp[0][i * C + j] = ok(cnt, i, j, R - 1, C - 1); + + for(int t = 1; t < k; t ++) + for(int r = 0; r < R; r ++) + for(int c = 0; c < C; c ++){ + + for(int i = r + 1; i < R; i ++) + if(ok(cnt, r, c, i - 1, C - 1)) + dp[t][r * C + c] += dp[t - 1][i * C + c], + dp[t][r * C + c] %= MOD; + + for(int j = c + 1; j < C; j ++) + if(ok(cnt, r, c, R - 1, j - 1)) + dp[t][r * C + c] += dp[t - 1][r * C + j], + dp[t][r * C + c] %= MOD; + } + return dp[k-1][0]; + } + +private: + bool ok(const vector>& cnt, int x1, int y1, int x2, int y2){ + return cnt[x2 + 1][y2 + 1] - cnt[x2 + 1][y1] - cnt[x1][y2 + 1] + cnt[x1][y1]; + } +}; + + +int main() { + + vector pizza1 = {"A..","AAA","..."}; + cout << Solution().ways(pizza1, 3) << endl; + // 3 + + vector pizza2 = {"A..","AA.","..."}; + cout << Solution().ways(pizza2, 3) << endl; + // 1 + + vector pizza3 = {"A..","A..","..."}; + cout << Solution().ways(pizza3, 1) << endl; + // 1 + + return 0; +} diff --git a/1001-1500/1444-Number-of-Ways-of-Cutting-a-Pizza/cpp-1444/main3.cpp b/1001-1500/1444-Number-of-Ways-of-Cutting-a-Pizza/cpp-1444/main3.cpp new file mode 100644 index 00000000..f4724ddf --- /dev/null +++ b/1001-1500/1444-Number-of-Ways-of-Cutting-a-Pizza/cpp-1444/main3.cpp @@ -0,0 +1,74 @@ +/// Source : https://leetcode.com/problems/number-of-ways-of-cutting-a-pizza/ +/// Author : liuyubobobo +/// Time : 2020-05-10 + +#include +#include + +using namespace std; + + +/// Dynamic Programming with Space Optimization +/// Time Complexity: O(k * R * C * (R + C)) +/// Space Complexity: O(R * C) +class Solution { + +private: + const int MOD = 1e9 + 7; + int R, C; + +public: + int ways(vector& pizza, int k) { + + R = pizza.size(), C = pizza[0].size(); + vector> cnt(R + 1, vector(C + 1, 0)); + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++) + cnt[i + 1][j + 1] = cnt[i][j + 1] + cnt[i + 1][j] - cnt[i][j] + (pizza[i][j] == 'A'); + + vector> dp(2, vector(R * C, 0)); + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++) + dp[0][i * C + j] = ok(cnt, i, j, R - 1, C - 1); + + for(int t = 1; t < k; t ++) + for(int r = 0; r < R; r ++) + for(int c = 0; c < C; c ++){ + + dp[t % 2][r * C + c] = 0; + for(int i = r + 1; i < R; i ++) + if(ok(cnt, r, c, i - 1, C - 1)) + dp[t % 2][r * C + c] += dp[(t - 1) % 2][i * C + c], + dp[t % 2][r * C + c] %= MOD; + + for(int j = c + 1; j < C; j ++) + if(ok(cnt, r, c, R - 1, j - 1)) + dp[t % 2][r * C + c] += dp[(t - 1) % 2][r * C + j], + dp[t % 2][r * C + c] %= MOD; + } + return dp[(k - 1) % 2][0]; + } + +private: + bool ok(const vector>& cnt, int x1, int y1, int x2, int y2){ + return cnt[x2 + 1][y2 + 1] - cnt[x2 + 1][y1] - cnt[x1][y2 + 1] + cnt[x1][y1]; + } +}; + + +int main() { + + vector pizza1 = {"A..","AAA","..."}; + cout << Solution().ways(pizza1, 3) << endl; + // 3 + + vector pizza2 = {"A..","AA.","..."}; + cout << Solution().ways(pizza2, 3) << endl; + // 1 + + vector pizza3 = {"A..","A..","..."}; + cout << Solution().ways(pizza3, 1) << endl; + // 1 + + return 0; +} diff --git a/1001-1500/1444-Number-of-Ways-of-Cutting-a-Pizza/cpp-1444/main4.cpp b/1001-1500/1444-Number-of-Ways-of-Cutting-a-Pizza/cpp-1444/main4.cpp new file mode 100644 index 00000000..8f13c155 --- /dev/null +++ b/1001-1500/1444-Number-of-Ways-of-Cutting-a-Pizza/cpp-1444/main4.cpp @@ -0,0 +1,76 @@ +/// Source : https://leetcode.com/problems/number-of-ways-of-cutting-a-pizza/ +/// Author : liuyubobobo +/// Time : 2020-05-10 + +#include +#include + +using namespace std; + + +/// Dynamic Programming with Space Optimization +/// Time Complexity: O(k * R * C * (R + C)) +/// Space Complexity: O(R * C) +class Solution { + +private: + const int MOD = 1e9 + 7; + int R, C; + +public: + int ways(vector& pizza, int k) { + + R = pizza.size(), C = pizza[0].size(); + vector> cnt(R + 1, vector(C + 1, 0)); + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++) + cnt[i + 1][j + 1] = cnt[i][j + 1] + cnt[i + 1][j] - cnt[i][j] + (pizza[i][j] == 'A'); + + vector dp(R * C, 0); + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++) + dp[i * C + j] = ok(cnt, i, j, R - 1, C - 1); + + for(int t = 1; t < k; t ++){ + vector tdp(R * C, 0); + for(int r = 0; r < R; r ++) + for(int c = 0; c < C; c ++){ + + for(int i = r + 1; i < R; i ++) + if(ok(cnt, r, c, i - 1, C - 1)) + tdp[r * C + c] += dp[i * C + c], + tdp[r * C + c] %= MOD; + + for(int j = c + 1; j < C; j ++) + if(ok(cnt, r, c, R - 1, j - 1)) + tdp[r * C + c] += dp[r * C + j], + tdp[r * C + c] %= MOD; + } + dp = tdp; + } + return dp[0]; + } + +private: + bool ok(const vector>& cnt, int x1, int y1, int x2, int y2){ + return cnt[x2 + 1][y2 + 1] - cnt[x2 + 1][y1] - cnt[x1][y2 + 1] + cnt[x1][y1]; + } +}; + + +int main() { + + vector pizza1 = {"A..","AAA","..."}; + cout << Solution().ways(pizza1, 3) << endl; + // 3 + + vector pizza2 = {"A..","AA.","..."}; + cout << Solution().ways(pizza2, 3) << endl; + // 1 + + vector pizza3 = {"A..","A..","..."}; + cout << Solution().ways(pizza3, 1) << endl; + // 1 + + return 0; +} diff --git a/1001-1500/1446-Consecutive-Characters/cpp-1446/CMakeLists.txt b/1001-1500/1446-Consecutive-Characters/cpp-1446/CMakeLists.txt new file mode 100644 index 00000000..10194b8c --- /dev/null +++ b/1001-1500/1446-Consecutive-Characters/cpp-1446/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(cpp_1446) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1446 main.cpp) \ No newline at end of file diff --git a/1001-1500/1446-Consecutive-Characters/cpp-1446/main.cpp b/1001-1500/1446-Consecutive-Characters/cpp-1446/main.cpp new file mode 100644 index 00000000..6bd5a536 --- /dev/null +++ b/1001-1500/1446-Consecutive-Characters/cpp-1446/main.cpp @@ -0,0 +1,32 @@ +/// Source : https://leetcode.com/problems/consecutive-characters/ +/// Author : liuyubobobo +/// Time : 2020-05-16 + +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int maxPower(string s) { + + int res = 0; + for(int start = 0, i = 1; i <= s.size(); i ++) + if(i == s.size() || s[i] != s[start]){ + res = max(res, i - start); + start = i; + i = start; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1447-Simplified-Fractions/cpp-1447/CMakeLists.txt b/1001-1500/1447-Simplified-Fractions/cpp-1447/CMakeLists.txt new file mode 100644 index 00000000..dfd653a4 --- /dev/null +++ b/1001-1500/1447-Simplified-Fractions/cpp-1447/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(cpp_1447) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1447 main2.cpp) \ No newline at end of file diff --git a/1001-1500/1447-Simplified-Fractions/cpp-1447/main.cpp b/1001-1500/1447-Simplified-Fractions/cpp-1447/main.cpp new file mode 100644 index 00000000..1101a614 --- /dev/null +++ b/1001-1500/1447-Simplified-Fractions/cpp-1447/main.cpp @@ -0,0 +1,38 @@ +/// Source : https://leetcode.com/problems/simplified-fractions/ +/// Author : liuyubobobo +/// Time : 2020-05-16 + +#include +#include +#include + +using namespace std; + + +/// Brute Force + GCD + HashSet +/// Time Complexity: O(n^2) +/// Space Complexity: O(n^2) +class Solution { +public: + vector simplifiedFractions(int n) { + + unordered_set res; + for(int d = 2; d <= n; d ++) + for(int i = 1; i < d; i ++){ + int g = gcd(d, i); + res.insert(to_string(i / g) + "/" + to_string(d / g)); + } + return vector(res.begin(), res.end()); + } + +private: + int gcd(int a, int b){ + return b == 0 ? a : gcd(b, a % b); + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1447-Simplified-Fractions/cpp-1447/main2.cpp b/1001-1500/1447-Simplified-Fractions/cpp-1447/main2.cpp new file mode 100644 index 00000000..e7731168 --- /dev/null +++ b/1001-1500/1447-Simplified-Fractions/cpp-1447/main2.cpp @@ -0,0 +1,39 @@ +/// Source : https://leetcode.com/problems/simplified-fractions/ +/// Author : liuyubobobo +/// Time : 2020-05-16 + +#include +#include +#include + +using namespace std; + + +/// Brute Force + GCD +/// Time Complexity: O(n^2) +/// Space Complexity: O(n^2) +class Solution { +public: + vector simplifiedFractions(int n) { + + vector res; + for(int d = 2; d <= n; d ++) + for(int i = 1; i < d; i ++){ + int g = gcd(d, i); + if(g == 1) + res.push_back(to_string(i) + "/" + to_string(d)); + } + return res; + } + +private: + int gcd(int a, int b){ + return b == 0 ? a : gcd(b, a % b); + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1448-Count-Good-Nodes-in-Binary-Tree/cpp-1448/CMakeLists.txt b/1001-1500/1448-Count-Good-Nodes-in-Binary-Tree/cpp-1448/CMakeLists.txt new file mode 100644 index 00000000..fa9819cb --- /dev/null +++ b/1001-1500/1448-Count-Good-Nodes-in-Binary-Tree/cpp-1448/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(cpp_1448) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1448 main.cpp) \ No newline at end of file diff --git a/1001-1500/1448-Count-Good-Nodes-in-Binary-Tree/cpp-1448/main.cpp b/1001-1500/1448-Count-Good-Nodes-in-Binary-Tree/cpp-1448/main.cpp new file mode 100644 index 00000000..ba0a6672 --- /dev/null +++ b/1001-1500/1448-Count-Good-Nodes-in-Binary-Tree/cpp-1448/main.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/count-good-nodes-in-binary-tree/ +/// Author : liuyubobobo +/// Time : 2020-05-16 + +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(h) + +/// 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: + int goodNodes(TreeNode* root) { + return dfs(root, INT_MIN); + } + +private: + int dfs(TreeNode* node, int cur_max){ + + if(!node) return 0; + + int res = node->val >= cur_max; + res += dfs(node->left, max(node->val, cur_max)); + res += dfs(node->right, max(node->val, cur_max)); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1449-Form-Largest-Integer-With-Digits-That-Add-up-to-Target/cpp-1449/CMakeLists.txt b/1001-1500/1449-Form-Largest-Integer-With-Digits-That-Add-up-to-Target/cpp-1449/CMakeLists.txt new file mode 100644 index 00000000..3b84cd00 --- /dev/null +++ b/1001-1500/1449-Form-Largest-Integer-With-Digits-That-Add-up-to-Target/cpp-1449/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(cpp_1449) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1449 main3.cpp) \ No newline at end of file diff --git a/1001-1500/1449-Form-Largest-Integer-With-Digits-That-Add-up-to-Target/cpp-1449/main.cpp b/1001-1500/1449-Form-Largest-Integer-With-Digits-That-Add-up-to-Target/cpp-1449/main.cpp new file mode 100644 index 00000000..7306be6f --- /dev/null +++ b/1001-1500/1449-Form-Largest-Integer-With-Digits-That-Add-up-to-Target/cpp-1449/main.cpp @@ -0,0 +1,61 @@ +/// Source : https://leetcode.com/problems/form-largest-integer-with-digits-that-add-up-to-target/ +/// Author : liuyubobobo +/// Time : 2020-05-16 + +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(target) +/// Space Complexity: O(target * |s|) +class Solution { +public: + string largestNumber(vector& cost, int target) { + + vector dp(target + 1); + vector visited(target + 1); + string res = dfs(cost, target, dp, visited); + return res.size() ? res : "0"; + } + +private: + string dfs(const vector& cost, int target, + vector& dp, vector& visited){ + + if(visited[target]) return dp[target]; + + string res = ""; + for(int i = 8; i >= 0; i --) + if(target > cost[i]){ + string tres = dfs(cost, target - cost[i], dp, visited); + if(tres != "" && tres.size() + 1 > res.size()) + res = string(1, '0' + (1 + i)) + tres; + } + else if(target == cost[i] && res.size() == 0) + res += ('0' + (1 + i)); + + visited[target] = true; + return dp[target] = res; + } +}; + + +int main() { + + vector cost1 = {4,3,2,5,6,7,2,5,5}; + cout << Solution().largestNumber(cost1, 9) << endl; + // 7772 + + vector cost2 = {7,6,5,5,5,6,8,7,8}; + cout << Solution().largestNumber(cost2, 12) << endl; + // 85 + + vector cost3 = {210,77,91,105,378,333,316,323,353}; + cout << Solution().largestNumber(cost3, 1217) << endl; + // 9944443 + + return 0; +} diff --git a/1001-1500/1449-Form-Largest-Integer-With-Digits-That-Add-up-to-Target/cpp-1449/main2.cpp b/1001-1500/1449-Form-Largest-Integer-With-Digits-That-Add-up-to-Target/cpp-1449/main2.cpp new file mode 100644 index 00000000..b92be2bd --- /dev/null +++ b/1001-1500/1449-Form-Largest-Integer-With-Digits-That-Add-up-to-Target/cpp-1449/main2.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/form-largest-integer-with-digits-that-add-up-to-target/ +/// Author : liuyubobobo +/// Time : 2020-05-16 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(target) +/// Space Complexity: O(target * |s|) +class Solution { +public: + string largestNumber(vector& cost, int target) { + + vector dp(target + 1, ""); + for(int i = 0; i < 9; i ++) + if(cost[i] <= target) dp[cost[i]] = string(1, '0' + (1 + i)); + + for(int k = 1; k <= target; k ++) + for(int i = 8; i >= 0; i --) + if(k > cost[i] && dp[k - cost[i]] != "" && 1 + dp[k - cost[i]].size() > dp[k].size()) + dp[k] = string(1, '0' + (1 + i)) + dp[k - cost[i]]; + return dp[target].size() ? dp[target] : "0"; + } +}; + + +int main() { + + vector cost1 = {4,3,2,5,6,7,2,5,5}; + cout << Solution().largestNumber(cost1, 9) << endl; + // 7772 + + vector cost2 = {7,6,5,5,5,6,8,7,8}; + cout << Solution().largestNumber(cost2, 12) << endl; + // 85 + + vector cost3 = {210,77,91,105,378,333,316,323,353}; + cout << Solution().largestNumber(cost3, 1217) << endl; + // 9944443 + + return 0; +} diff --git a/1001-1500/1449-Form-Largest-Integer-With-Digits-That-Add-up-to-Target/cpp-1449/main3.cpp b/1001-1500/1449-Form-Largest-Integer-With-Digits-That-Add-up-to-Target/cpp-1449/main3.cpp new file mode 100644 index 00000000..38e7b5f5 --- /dev/null +++ b/1001-1500/1449-Form-Largest-Integer-With-Digits-That-Add-up-to-Target/cpp-1449/main3.cpp @@ -0,0 +1,63 @@ +/// Source : https://leetcode.com/problems/form-largest-integer-with-digits-that-add-up-to-target/ +/// Author : liuyubobobo +/// Time : 2020-05-16 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Calculate the result string's length first +/// and construct this result string afterwards +/// Time Complexity: O(target) +/// Space Complexity: O(target) +class Solution { +public: + string largestNumber(vector& cost, int target) { + + vector dp(target + 1, 0); + for(int i = 0; i < 9; i ++) + if(cost[i] <= target) dp[cost[i]] = 1; + + for(int k = 1; k <= target; k ++) + for(int i = 8; i >= 0; i --) + if(k > cost[i] && dp[k - cost[i]] && 1 + dp[k - cost[i]] > dp[k]) + dp[k] = 1 + dp[k - cost[i]]; + + if(!dp[target]) return "0"; + +// for(int e: dp) cout << e << " "; cout << endl; + string res = ""; + int cur = target; + while(cur){ + for(int i = 8; i >= 0; i --) + if(cur >= cost[i] && dp[cur] == 1 + dp[cur - cost[i]]){ + if(dp[cur] == 1 && cur != cost[i]) continue; + res += string(1, ('0' + (i + 1))); + cur -= cost[i]; + break; + } + } + return res; + } +}; + + +int main() { + + vector cost1 = {4,3,2,5,6,7,2,5,5}; + cout << Solution().largestNumber(cost1, 9) << endl; + // 7772 + + vector cost2 = {7,6,5,5,5,6,8,7,8}; + cout << Solution().largestNumber(cost2, 12) << endl; + // 85 + + vector cost3 = {210,77,91,105,378,333,316,323,353}; + cout << Solution().largestNumber(cost3, 1217) << endl; + // 9944443 + + return 0; +} diff --git a/1001-1500/1450-Number-of-Students-Doing-Homework-at-a-Given-Time/cpp-1450/CMakeLists.txt b/1001-1500/1450-Number-of-Students-Doing-Homework-at-a-Given-Time/cpp-1450/CMakeLists.txt new file mode 100644 index 00000000..cb89cda6 --- /dev/null +++ b/1001-1500/1450-Number-of-Students-Doing-Homework-at-a-Given-Time/cpp-1450/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1001-1500/1450-Number-of-Students-Doing-Homework-at-a-Given-Time/cpp-1450/main.cpp b/1001-1500/1450-Number-of-Students-Doing-Homework-at-a-Given-Time/cpp-1450/main.cpp new file mode 100644 index 00000000..42dbc601 --- /dev/null +++ b/1001-1500/1450-Number-of-Students-Doing-Homework-at-a-Given-Time/cpp-1450/main.cpp @@ -0,0 +1,29 @@ +/// Source : Number of Students Doing Homework at a Given Time +/// Author : liuyubobobo +/// Time : 2020-05-16 + +#include +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int busyStudent(vector& startTime, vector& endTime, int queryTime) { + + int res = 0; + for(int i = 0; i < startTime.size(); i ++) + if(startTime[i] <= queryTime && queryTime <= endTime[i]) res ++; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1451-Rearrange-Words-in-a-Sentence/cpp-1451/CMakeLists.txt b/1001-1500/1451-Rearrange-Words-in-a-Sentence/cpp-1451/CMakeLists.txt new file mode 100644 index 00000000..68c42346 --- /dev/null +++ b/1001-1500/1451-Rearrange-Words-in-a-Sentence/cpp-1451/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main3.cpp) \ No newline at end of file diff --git a/1001-1500/1451-Rearrange-Words-in-a-Sentence/cpp-1451/main.cpp b/1001-1500/1451-Rearrange-Words-in-a-Sentence/cpp-1451/main.cpp new file mode 100644 index 00000000..75c00d1d --- /dev/null +++ b/1001-1500/1451-Rearrange-Words-in-a-Sentence/cpp-1451/main.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/rearrange-words-in-a-sentence/ +/// Author : liuyubobobo +/// Time : 2020-05-16 + +#include +#include + +using namespace std; + + +/// Split + Sort +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + string arrangeWords(string text) { + + text[0] = tolower(text[0]); + vector> words; + int cnt = 0; + for(int start = 0, i = 0; i <= text.size(); i ++) + if(i == text.size() || text[i] == ' '){ + words.push_back({text.substr(start, i - start), cnt ++}); + start = i + 1; + i = start; + } + + sort(words.begin(), words.end(), + [](const pair& p1, const pair& p2){ + if(p1.first.size() != p2.first.size()) return p1.first.size() < p2.first.size(); + return p1.second < p2.second; + }); + + string res = words[0].first; + for(int i = 1; i < words.size(); i ++) + res += " " + words[i].first; + res[0] = toupper(res[0]); + return res; + } +}; + + +int main() { + + cout << Solution().arrangeWords("Leetcode is cool") << endl; + + cout << Solution().arrangeWords("Keep calm and code on") << endl; + + cout << Solution().arrangeWords("To be or not to be") << endl; + + return 0; +} diff --git a/1001-1500/1451-Rearrange-Words-in-a-Sentence/cpp-1451/main2.cpp b/1001-1500/1451-Rearrange-Words-in-a-Sentence/cpp-1451/main2.cpp new file mode 100644 index 00000000..48b002e6 --- /dev/null +++ b/1001-1500/1451-Rearrange-Words-in-a-Sentence/cpp-1451/main2.cpp @@ -0,0 +1,49 @@ +/// Source : https://leetcode.com/problems/rearrange-words-in-a-sentence/ +/// Author : liuyubobobo +/// Time : 2020-05-16 + +#include +#include + +using namespace std; + + +/// Split + Stable Sort +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + string arrangeWords(string text) { + + text[0] = tolower(text[0]); + vector words; + int cnt = 0; + for(int start = 0, i = 0; i <= text.size(); i ++) + if(i == text.size() || text[i] == ' '){ + words.push_back(text.substr(start, i - start)); + start = i + 1; + i = start; + } + + stable_sort(words.begin(), words.end(), + [](const string& s1, const string& s2){ return s1.size() < s2.size(); }); + + string res = words[0]; + for(int i = 1; i < words.size(); i ++) + res += " " + words[i]; + res[0] = toupper(res[0]); + return res; + } +}; + + +int main() { + + cout << Solution().arrangeWords("Leetcode is cool") << endl; + + cout << Solution().arrangeWords("Keep calm and code on") << endl; + + cout << Solution().arrangeWords("To be or not to be") << endl; + + return 0; +} diff --git a/1001-1500/1451-Rearrange-Words-in-a-Sentence/cpp-1451/main3.cpp b/1001-1500/1451-Rearrange-Words-in-a-Sentence/cpp-1451/main3.cpp new file mode 100644 index 00000000..d2e214b6 --- /dev/null +++ b/1001-1500/1451-Rearrange-Words-in-a-Sentence/cpp-1451/main3.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/rearrange-words-in-a-sentence/ +/// Author : liuyubobobo +/// Time : 2020-05-16 + +#include +#include +#include + +using namespace std; + + +/// Split + Bucket Sort +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + string arrangeWords(string text) { + + text[0] = tolower(text[0]); + + map> buckets; + int cnt = 0; + for(int start = 0, i = 0; i <= text.size(); i ++) + if(i == text.size() || text[i] == ' '){ + buckets[i - start].push_back(text.substr(start, i - start)); + start = i + 1; + i = start; + } + + string res = ""; + for(const pair>& p: buckets) + for(const string& s: p.second) + res += s + ' '; + res[0] = toupper(res[0]); + res.pop_back(); + return res; + } +}; + + +int main() { + + cout << Solution().arrangeWords("Leetcode is cool") << endl; + + cout << Solution().arrangeWords("Keep calm and code on") << endl; + + cout << Solution().arrangeWords("To be or not to be") << endl; + + return 0; +} diff --git a/1001-1500/1452-People-Whose-List-of-Favorite-Companies-Is-Not-a-Subset-of-Another-List/cpp-1452/CMakeLists.txt b/1001-1500/1452-People-Whose-List-of-Favorite-Companies-Is-Not-a-Subset-of-Another-List/cpp-1452/CMakeLists.txt new file mode 100644 index 00000000..56aa84f9 --- /dev/null +++ b/1001-1500/1452-People-Whose-List-of-Favorite-Companies-Is-Not-a-Subset-of-Another-List/cpp-1452/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main3.cpp) \ No newline at end of file diff --git a/1001-1500/1452-People-Whose-List-of-Favorite-Companies-Is-Not-a-Subset-of-Another-List/cpp-1452/main.cpp b/1001-1500/1452-People-Whose-List-of-Favorite-Companies-Is-Not-a-Subset-of-Another-List/cpp-1452/main.cpp new file mode 100644 index 00000000..83e62a04 --- /dev/null +++ b/1001-1500/1452-People-Whose-List-of-Favorite-Companies-Is-Not-a-Subset-of-Another-List/cpp-1452/main.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/ +/// Author : liuyubobobo +/// Time : 2020-05-16 + +#include +#include +#include + +using namespace std; + + +/// Brute Force + HashSet to check subset +/// Time Complexity: O(n^2 * m * |s|) +/// Space Complexity: O(n * m) +class Solution { +public: + vector peopleIndexes(vector>& favoriteCompanies) { + + int n = favoriteCompanies.size(); + + vector> setv; + for(const vector& v: favoriteCompanies) + setv.push_back(unordered_set(v.begin(), v.end())); + + vector res; + for(int i = 0; i < n; i ++){ + bool is_sub = false; + for(int j = 0; j < n; j ++) + if(j != i && setv[i].size() < setv[j].size() && isSub(setv[i], setv[j])){ + is_sub = true; + break; + } + + if(!is_sub) res.push_back(i); + } + return res; + } + +private: + // see if a is subset of b + bool isSub(const unordered_set& a, const unordered_set& b){ + + for(string e: a) + if(!b.count(e)) return false; + return true; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1452-People-Whose-List-of-Favorite-Companies-Is-Not-a-Subset-of-Another-List/cpp-1452/main2.cpp b/1001-1500/1452-People-Whose-List-of-Favorite-Companies-Is-Not-a-Subset-of-Another-List/cpp-1452/main2.cpp new file mode 100644 index 00000000..d12e8b41 --- /dev/null +++ b/1001-1500/1452-People-Whose-List-of-Favorite-Companies-Is-Not-a-Subset-of-Another-List/cpp-1452/main2.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/ +/// Author : liuyubobobo +/// Time : 2020-05-16 + +#include +#include +#include + +using namespace std; + + +/// Brute Force + Binary Search to check subset +/// Time Complexity: O(n^2 * m * logm * |s|) +/// Space Complexity: O(n * m) +class Solution { +public: + vector peopleIndexes(vector>& favoriteCompanies) { + + int n = favoriteCompanies.size(); + for(int i = 0; i < n; i ++) + sort(favoriteCompanies[i].begin(), favoriteCompanies[i].end()); + + vector res; + for(int i = 0; i < n; i ++){ + bool is_sub = false; + for(int j = 0; j < n; j ++) + if(j != i && favoriteCompanies[i].size() < favoriteCompanies[j].size() && + isSub(favoriteCompanies[i], favoriteCompanies[j])){ + is_sub = true; + break; + } + + if(!is_sub) res.push_back(i); + } + return res; + } + +private: + // see if a is subset of b + bool isSub(const vector& a, const vector& b){ + + for(string e: a){ + vector::const_iterator iter = lower_bound(b.begin(), b.end(), e); + if(iter == b.end() || *iter != e) return false; + } + return true; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1452-People-Whose-List-of-Favorite-Companies-Is-Not-a-Subset-of-Another-List/cpp-1452/main3.cpp b/1001-1500/1452-People-Whose-List-of-Favorite-Companies-Is-Not-a-Subset-of-Another-List/cpp-1452/main3.cpp new file mode 100644 index 00000000..e7719c0e --- /dev/null +++ b/1001-1500/1452-People-Whose-List-of-Favorite-Companies-Is-Not-a-Subset-of-Another-List/cpp-1452/main3.cpp @@ -0,0 +1,63 @@ +/// Source : https://leetcode.com/problems/people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/ +/// Author : liuyubobobo +/// Time : 2020-05-16 + +#include +#include +#include +#include + +using namespace std; + + +/// Brute Force + Using String to Int Set to check subset +/// Time Complexity: O(n * m * |s| + n^2 * m) +/// Space Complexity: O(n * m) +class Solution { +public: + vector peopleIndexes(vector>& favoriteCompanies) { + + int n = favoriteCompanies.size(); + + unordered_map map; + int index = 0; + + vector> mapv; + for(const vector& v: favoriteCompanies){ + unordered_set tv; + for(const string& s: v){ + if(!map.count(s)) map[s] = index ++; + tv.insert(map[s]); + } + mapv.push_back(tv); + } + + vector res; + for(int i = 0; i < n; i ++){ + bool is_sub = false; + for(int j = 0; j < n; j ++) + if(j != i && mapv[i].size() <= mapv[j].size() && isSub(mapv[i], mapv[j])){ + is_sub = true; + break; + } + + if(!is_sub) res.push_back(i); + } + return res; + } + +private: + // see if a is subset of b + bool isSub(const unordered_set& a, const unordered_set& b){ + + for(int e: a) + if(!b.count(e)) return false; + return true; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1453-Maximum-Number-of-Darts-Inside-of-a-Circular-Dartboard/cpp-1453/CMakeLists.txt b/1001-1500/1453-Maximum-Number-of-Darts-Inside-of-a-Circular-Dartboard/cpp-1453/CMakeLists.txt new file mode 100644 index 00000000..b07a4ffa --- /dev/null +++ b/1001-1500/1453-Maximum-Number-of-Darts-Inside-of-a-Circular-Dartboard/cpp-1453/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) \ No newline at end of file diff --git a/1001-1500/1453-Maximum-Number-of-Darts-Inside-of-a-Circular-Dartboard/cpp-1453/main.cpp b/1001-1500/1453-Maximum-Number-of-Darts-Inside-of-a-Circular-Dartboard/cpp-1453/main.cpp new file mode 100644 index 00000000..266248cb --- /dev/null +++ b/1001-1500/1453-Maximum-Number-of-Darts-Inside-of-a-Circular-Dartboard/cpp-1453/main.cpp @@ -0,0 +1,73 @@ +/// Source : https://leetcode.com/problems/maximum-number-of-darts-inside-of-a-circular-dartboard/ +/// Author : liuyubobobo +/// Time : 2020-05-16 + +#include +#include +#include + +using namespace std; + + +/// Brute Force + Greedy +/// Time Complexity: O(n^3) +/// Space Complexity: O(1) +class Solution { + +private: + double e = 1e-6; + +public: + int numPoints(vector>& points, int r) { + + int res = 1; + for(int i = 0; i < points.size(); i ++) + for(int j = i + 1; j < points.size(); j ++){ + + double x1 = points[i][0], y1 = points[i][1], + x2 = points[j][0], y2 = points[j][1]; + double x0 = (x1 + x2) / 2, y0 = (y1 + y2) / 2; + double d = sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); + double h = sqrt(r * r - d * d / 4.0); + + double xc = x0 - h * (y2 - y1) / d, yc = y0 - h * (x1 - x2) / d; + res = max(res, get(points, xc, yc, r)); + + double xd = x0 + h * (y2 - y1) / d, yd = y0 + h * (x1 - x2) / d; + res = max(res, get(points, xd, yd, r)); + } + return res; + } + +private: + int get(const vector>& points, double x, double y, double r){ + + int res = 0; + for(const vector& p: points) + if((p[0] - x) * (p[0] - x) + (p[1] - y) * (p[1] - y) <= r * r + e) + res ++; + return res; + } +}; + + +int main() { + + vector> points1 = {{-2,0},{2,0},{0,2},{0,-2}}; + cout << Solution().numPoints(points1, 2) << endl; + // 4 + + vector> points2 = {{-3,0},{3,0},{2,6},{5,4},{0,9},{7,8}}; + cout << Solution().numPoints(points2, 5) << endl; + // 5 + + vector> points3 = {{1,2},{3,5},{1,-1},{2,3},{4,1},{1,3}}; + cout << Solution().numPoints(points3, 2) << endl; + // 4 + + vector> points4 = {{4,-4},{-2,0},{0,2},{-3,1},{2,3},{2,4},{1,1}}; + cout << Solution().numPoints(points4, 3) << endl; + // 6 + + return 0; +} diff --git a/1001-1500/1455-Check-If-a-Word-Occurs-As-a-Prefix-of-Any-Word-in-a-Sentence/cpp-1455/CMakeLists.txt b/1001-1500/1455-Check-If-a-Word-Occurs-As-a-Prefix-of-Any-Word-in-a-Sentence/cpp-1455/CMakeLists.txt new file mode 100644 index 00000000..cb89cda6 --- /dev/null +++ b/1001-1500/1455-Check-If-a-Word-Occurs-As-a-Prefix-of-Any-Word-in-a-Sentence/cpp-1455/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1001-1500/1455-Check-If-a-Word-Occurs-As-a-Prefix-of-Any-Word-in-a-Sentence/cpp-1455/main.cpp b/1001-1500/1455-Check-If-a-Word-Occurs-As-a-Prefix-of-Any-Word-in-a-Sentence/cpp-1455/main.cpp new file mode 100644 index 00000000..e836e1f5 --- /dev/null +++ b/1001-1500/1455-Check-If-a-Word-Occurs-As-a-Prefix-of-Any-Word-in-a-Sentence/cpp-1455/main.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/ +/// Author : liuyubobobo +/// Time : 2020-05-23 + +#include +#include + +using namespace std; + + +/// Brute Force: Split and Compare +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int isPrefixOfWord(string sentence, string searchWord) { + + int index = 1; + for(int start = 0, i = start + 1; i <= sentence.size(); i ++) + if(i == sentence.size() || sentence[i] == ' '){ + string word = sentence.substr(start, i - start); + if(searchWord.size() <= word.size() && word.substr(0, searchWord.size()) == searchWord) + return index; + index ++; + + start = i + 1; + i = start; + } + return -1; + } +}; + + +int main() { + + cout << Solution().isPrefixOfWord("i love eating burger", "burg") << endl; + // 4 + + cout << Solution().isPrefixOfWord("this problem is an easy problem", "pro") << endl; + // 2 + + cout << Solution().isPrefixOfWord("i am tired", "you") << endl; + // -1 + + cout << Solution().isPrefixOfWord("i use triple pillow", "pill") << endl; + // 4 + + cout << Solution().isPrefixOfWord("hello from the other side", "they") << endl; + // -1 + + return 0; +} diff --git a/1001-1500/1456-Maximum-Number-of-Vowels-in-a-Substring-of-Given-Length/cpp-1456/CMakeLists.txt b/1001-1500/1456-Maximum-Number-of-Vowels-in-a-Substring-of-Given-Length/cpp-1456/CMakeLists.txt new file mode 100644 index 00000000..545e47b8 --- /dev/null +++ b/1001-1500/1456-Maximum-Number-of-Vowels-in-a-Substring-of-Given-Length/cpp-1456/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1001-1500/1456-Maximum-Number-of-Vowels-in-a-Substring-of-Given-Length/cpp-1456/main.cpp b/1001-1500/1456-Maximum-Number-of-Vowels-in-a-Substring-of-Given-Length/cpp-1456/main.cpp new file mode 100644 index 00000000..aee6becb --- /dev/null +++ b/1001-1500/1456-Maximum-Number-of-Vowels-in-a-Substring-of-Given-Length/cpp-1456/main.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/maximum-number-of-vowels-in-a-substring-of-given-length/ +/// Author : liuyubobobo +/// Time : 2020-05-23 + +#include + +using namespace std; + + +/// Sliding Window +/// Time Complexity: O(|s|) +/// Space Complexity: O(1) +class Solution { +public: + int maxVowels(string s, int k) { + + int res = 0, cur = 0; + for(int i = 0; i < k - 1 && i < s.size(); i ++) + cur += is_vowel(s[i]); + + for(int i = k - 1; i < s.size(); i ++){ + cur += is_vowel(s[i]); + res = max(res, cur); + cur -= is_vowel(s[i - (k - 1)]); + } + return res; + } + +private: + bool is_vowel(char c){ + return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'; + } +}; + + +int main() { + + cout << Solution().maxVowels("abciiidef", 3) << endl; + // 3 + + cout << Solution().maxVowels("aeiou", 2) << endl; + // 2 + + cout << Solution().maxVowels("leetcode", 3) << endl; + // 2 + + cout << Solution().maxVowels("rhythms", 4) << endl; + // 0 + + cout << Solution().maxVowels("tryhard", 4) << endl; + // 1 + + return 0; +} diff --git a/1001-1500/1457-Pseudo-Palindromic-Paths-in-a-Binary-Tree/cpp-1457/CMakeLists.txt b/1001-1500/1457-Pseudo-Palindromic-Paths-in-a-Binary-Tree/cpp-1457/CMakeLists.txt new file mode 100644 index 00000000..94acd016 --- /dev/null +++ b/1001-1500/1457-Pseudo-Palindromic-Paths-in-a-Binary-Tree/cpp-1457/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1001-1500/1457-Pseudo-Palindromic-Paths-in-a-Binary-Tree/cpp-1457/main.cpp b/1001-1500/1457-Pseudo-Palindromic-Paths-in-a-Binary-Tree/cpp-1457/main.cpp new file mode 100644 index 00000000..aee65b94 --- /dev/null +++ b/1001-1500/1457-Pseudo-Palindromic-Paths-in-a-Binary-Tree/cpp-1457/main.cpp @@ -0,0 +1,64 @@ +/// Source : https://leetcode.com/problems/pseudo-palindromic-paths-in-a-binary-tree/ +/// Author : liuyubobobo +/// Time : 2020-05-23 + +#include +#include + +using namespace std; + + +/// DFS + HashSet +/// Time Complexity: O(n) +/// Space Complexity: O(n + h) + +/// 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: + int pseudoPalindromicPaths (TreeNode* root) { + + unordered_map freq; + return dfs(root, freq); + } + +private: + int dfs(TreeNode* node, unordered_map& freq){ + + freq[node->val] ++; + + int res = 0; + if(!node->left && !node->right) res = ok(freq); + else { + if (node->left) res += dfs(node->left, freq); + if (node->right) res += dfs(node->right, freq); + } + + freq[node->val] --; + if(freq[node->val] == 0) freq.erase(node->val); + + return res; + } + + bool ok(unordered_map& freq){ + + int odd = 0; + for(const pair& p: freq) + odd += p.second % 2; + return odd <= 1; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1458-Max-Dot-Product-of-Two-Subsequences/cpp-1458/CMakeLists.txt b/1001-1500/1458-Max-Dot-Product-of-Two-Subsequences/cpp-1458/CMakeLists.txt new file mode 100644 index 00000000..a965d66f --- /dev/null +++ b/1001-1500/1458-Max-Dot-Product-of-Two-Subsequences/cpp-1458/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main3.cpp) \ No newline at end of file diff --git a/1001-1500/1458-Max-Dot-Product-of-Two-Subsequences/cpp-1458/main.cpp b/1001-1500/1458-Max-Dot-Product-of-Two-Subsequences/cpp-1458/main.cpp new file mode 100644 index 00000000..584657a7 --- /dev/null +++ b/1001-1500/1458-Max-Dot-Product-of-Two-Subsequences/cpp-1458/main.cpp @@ -0,0 +1,69 @@ +/// Source : https://leetcode.com/problems/max-dot-product-of-two-subsequences/ +/// Author : liuyubobobo +/// Time : 2020-05-23 + +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(n1 * n2) +/// Space Complexity: O(n1 * n2) +class Solution { + +public: + int maxDotProduct(vector& nums1, vector& nums2) { + + vector> dp(nums1.size(), vector(nums2.size(), INT_MIN)); + int res = dfs(nums1, nums2, 0, 0, dp); + return res; + } + +private: + int dfs(const vector& nums1, const vector& nums2, int index1, int index2, + vector>& dp){ + + if(index1 == nums1.size() || index2 == nums2.size()) return -1e9; + if(dp[index1][index2] != INT_MIN) return dp[index1][index2]; + + int res = nums1[index1] * nums2[index2]; + res = max(res, nums1[index1] * nums2[index2] + dfs(nums1, nums2, index1 + 1, index2 + 1, dp)); + res = max(res, dfs(nums1, nums2, index1 + 1, index2, dp)); + res = max(res, dfs(nums1, nums2, index1, index2 + 1, dp)); + res = max(res, dfs(nums1, nums2, index1 + 1, index2 + 1, dp)); + + return dp[index1][index2] = res; + } +}; + + +int main() { + + vector nums11 = {2,1,-2,5}, nums21 = {3,0,-6}; + cout << Solution().maxDotProduct(nums11, nums21) << endl; + // 18 + + vector nums12 = {3, -2}, nums22 = {2, -6, 7}; + cout << Solution().maxDotProduct(nums12, nums22) << endl; + // 21 + + vector nums13 = {-1, -1}, nums23 = {1, 1}; + cout << Solution().maxDotProduct(nums13, nums23) << endl; + // -1 + + vector nums14 = {-5, -1, -2}, nums24 = {3, 3, 5, 5}; + cout << Solution().maxDotProduct(nums14, nums24) << endl; + // -3 + + vector nums15 = {-5, -1, -2}, nums25 = {3, 5}; + cout << Solution().maxDotProduct(nums15, nums25) << endl; + // -3 + + vector nums16 = {5, -4, -3}, nums26 = {-4, -3, 0, -4, 2}; + cout << Solution().maxDotProduct(nums16, nums26) << endl; + // 28 + + return 0; +} diff --git a/1001-1500/1458-Max-Dot-Product-of-Two-Subsequences/cpp-1458/main2.cpp b/1001-1500/1458-Max-Dot-Product-of-Two-Subsequences/cpp-1458/main2.cpp new file mode 100644 index 00000000..bac0d0a9 --- /dev/null +++ b/1001-1500/1458-Max-Dot-Product-of-Two-Subsequences/cpp-1458/main2.cpp @@ -0,0 +1,64 @@ +/// Source : https://leetcode.com/problems/max-dot-product-of-two-subsequences/ +/// Author : liuyubobobo +/// Time : 2020-05-23 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(n1 * n2) +/// Space Complexity: O(n1 * n2) +class Solution { + +public: + int maxDotProduct(vector& nums1, vector& nums2) { + + int n1 = nums1.size(), n2 = nums2.size(); + vector> dp(n1 + 1, vector(n2 + 1, -1e9)); + + for(int i = 0; i < n1; i ++) + for(int j = 0; j < n2; j ++){ + dp[i + 1][j + 1] = nums1[i] * nums2[j]; + dp[i + 1][j + 1] = max(dp[i + 1][j + 1], nums1[i] * nums2[j] + dp[i][j]); + dp[i + 1][j + 1] = max(dp[i + 1][j + 1], dp[i][j]); + dp[i + 1][j + 1] = max(dp[i + 1][j + 1], dp[i][j + 1]); + dp[i + 1][j + 1] = max(dp[i + 1][j + 1], dp[i + 1][j]); + } + + for(int i = 0; i <= n1; i ++){ + for(int j = 0; j <= n2; j ++) + cout << dp[i][j] << " "; + cout << endl; + } + return dp[n1][n2]; + } +}; + + +int main() { + + vector nums11 = {2,1,-2,5}, nums21 = {3,0,-6}; + cout << Solution().maxDotProduct(nums11, nums21) << endl; + // 18 + + vector nums12 = {3, -2}, nums22 = {2, -6, 7}; + cout << Solution().maxDotProduct(nums12, nums22) << endl; + // 21 + + vector nums13 = {-1, -1}, nums23 = {1, 1}; + cout << Solution().maxDotProduct(nums13, nums23) << endl; + // -1 + + vector nums14 = {-5, -1, -2}, nums24 = {3, 3, 5, 5}; + cout << Solution().maxDotProduct(nums14, nums24) << endl; + // -3 + + vector nums15 = {-5, -1, -2}, nums25 = {3, 5}; + cout << Solution().maxDotProduct(nums15, nums25) << endl; + // -3 + + return 0; +} diff --git a/1001-1500/1458-Max-Dot-Product-of-Two-Subsequences/cpp-1458/main3.cpp b/1001-1500/1458-Max-Dot-Product-of-Two-Subsequences/cpp-1458/main3.cpp new file mode 100644 index 00000000..36909e7d --- /dev/null +++ b/1001-1500/1458-Max-Dot-Product-of-Two-Subsequences/cpp-1458/main3.cpp @@ -0,0 +1,61 @@ +/// Source : https://leetcode.com/problems/max-dot-product-of-two-subsequences/ +/// Author : liuyubobobo +/// Time : 2020-05-24 + +#include +#include + +using namespace std; + + +/// Dynamic Programming + Rolling Array +/// Time Complexity: O(n1 * n2) +/// Space Complexity: O(n2) +class Solution { + +public: + int maxDotProduct(vector& nums1, vector& nums2) { + + int n1 = nums1.size(), n2 = nums2.size(); + vector dp(n2 + 1, -1e9); + + for(int i = 0; i < n1; i ++){ + vector tdp(n2 + 1, -1e9); + for(int j = 0; j < n2; j ++){ + tdp[j + 1] = nums1[i] * nums2[j]; + tdp[j + 1] = max(tdp[j + 1], nums1[i] * nums2[j] + dp[j]); + tdp[j + 1] = max(tdp[j + 1], dp[j]); + tdp[j + 1] = max(tdp[j + 1], dp[j + 1]); + tdp[j + 1] = max(tdp[j + 1], tdp[j]); + } + dp = tdp; + } + return dp[n2]; + } +}; + + +int main() { + + vector nums11 = {2,1,-2,5}, nums21 = {3,0,-6}; + cout << Solution().maxDotProduct(nums11, nums21) << endl; + // 18 + + vector nums12 = {3, -2}, nums22 = {2, -6, 7}; + cout << Solution().maxDotProduct(nums12, nums22) << endl; + // 21 + + vector nums13 = {-1, -1}, nums23 = {1, 1}; + cout << Solution().maxDotProduct(nums13, nums23) << endl; + // -1 + + vector nums14 = {-5, -1, -2}, nums24 = {3, 3, 5, 5}; + cout << Solution().maxDotProduct(nums14, nums24) << endl; + // -3 + + vector nums15 = {-5, -1, -2}, nums25 = {3, 5}; + cout << Solution().maxDotProduct(nums15, nums25) << endl; + // -3 + + return 0; +} diff --git a/1001-1500/1460-Make-Two-Arrays-Equal-by-Reversing-Sub-arrays/cpp-1460/CMakeLists.txt b/1001-1500/1460-Make-Two-Arrays-Equal-by-Reversing-Sub-arrays/cpp-1460/CMakeLists.txt new file mode 100644 index 00000000..cb89cda6 --- /dev/null +++ b/1001-1500/1460-Make-Two-Arrays-Equal-by-Reversing-Sub-arrays/cpp-1460/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1001-1500/1460-Make-Two-Arrays-Equal-by-Reversing-Sub-arrays/cpp-1460/main.cpp b/1001-1500/1460-Make-Two-Arrays-Equal-by-Reversing-Sub-arrays/cpp-1460/main.cpp new file mode 100644 index 00000000..00bcb3c7 --- /dev/null +++ b/1001-1500/1460-Make-Two-Arrays-Equal-by-Reversing-Sub-arrays/cpp-1460/main.cpp @@ -0,0 +1,28 @@ +/// Source : https://leetcode.com/problems/make-two-arrays-equal-by-reversing-sub-arrays/ +/// Author : liuyubobobo +/// Time : 2020-05-30 + +#include +#include + +using namespace std; + + +/// Sorting +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + bool canBeEqual(vector& target, vector& arr) { + + sort(target.begin(), target.end()); + sort(arr.begin(), arr.end()); + return target == arr; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1460-Make-Two-Arrays-Equal-by-Reversing-Sub-arrays/cpp-1460/main2.cpp b/1001-1500/1460-Make-Two-Arrays-Equal-by-Reversing-Sub-arrays/cpp-1460/main2.cpp new file mode 100644 index 00000000..0259ab3e --- /dev/null +++ b/1001-1500/1460-Make-Two-Arrays-Equal-by-Reversing-Sub-arrays/cpp-1460/main2.cpp @@ -0,0 +1,30 @@ +/// Source : https://leetcode.com/problems/make-two-arrays-equal-by-reversing-sub-arrays/ +/// Author : liuyubobobo +/// Time : 2020-05-30 + +#include +#include +#include + +using namespace std; + + +/// Using Hash Map +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + bool canBeEqual(vector& target, vector& arr) { + + unordered_map f1, f2; + for(int i = 0; i < target.size(); i ++) + f1[target[i]] ++, f2[arr[i]] ++; + return f1 == f2; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1461-Check-If-a-String-Contains-All-Binary-Codes-of-Size-K/cpp-1461/CMakeLists.txt b/1001-1500/1461-Check-If-a-String-Contains-All-Binary-Codes-of-Size-K/cpp-1461/CMakeLists.txt new file mode 100644 index 00000000..68c42346 --- /dev/null +++ b/1001-1500/1461-Check-If-a-String-Contains-All-Binary-Codes-of-Size-K/cpp-1461/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main3.cpp) \ No newline at end of file diff --git a/1001-1500/1461-Check-If-a-String-Contains-All-Binary-Codes-of-Size-K/cpp-1461/main.cpp b/1001-1500/1461-Check-If-a-String-Contains-All-Binary-Codes-of-Size-K/cpp-1461/main.cpp new file mode 100644 index 00000000..ef0ab1ed --- /dev/null +++ b/1001-1500/1461-Check-If-a-String-Contains-All-Binary-Codes-of-Size-K/cpp-1461/main.cpp @@ -0,0 +1,43 @@ +/// Source : https://leetcode.com/problems/check-if-a-string-contains-all-binary-codes-of-size-k/ +/// Author : liuyubobobo +/// Time : 2020-05-30 + +#include +#include + +using namespace std; + + +/// HashSet. key type: String +/// Time Complexity: O(|s| * k) +/// Space Complexity: O(1 << k) +class Solution { +public: + bool hasAllCodes(string s, int k) { + + unordered_set set; + for(int i = 0; i + k <= s.size(); i ++) set.insert(s.substr(i, k)); + return set.size() == (1 << k); + } +}; + + +int main() { + + cout << Solution().hasAllCodes("00110110", 2) << endl; + // 1 + + cout << Solution().hasAllCodes("00110", 2) << endl; + // 1 + + cout << Solution().hasAllCodes("0110", 1) << endl; + // 1 + + cout << Solution().hasAllCodes("0110", 2) << endl; + // 0 + + cout << Solution().hasAllCodes("0000000001011100", 4) << endl; + // 0 + + return 0; +} diff --git a/1001-1500/1461-Check-If-a-String-Contains-All-Binary-Codes-of-Size-K/cpp-1461/main2.cpp b/1001-1500/1461-Check-If-a-String-Contains-All-Binary-Codes-of-Size-K/cpp-1461/main2.cpp new file mode 100644 index 00000000..44d168bd --- /dev/null +++ b/1001-1500/1461-Check-If-a-String-Contains-All-Binary-Codes-of-Size-K/cpp-1461/main2.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/check-if-a-string-contains-all-binary-codes-of-size-k/ +/// Author : liuyubobobo +/// Time : 2020-05-30 +/// Updated: 2022-05-30 + +#include +#include + +using namespace std; + + +/// HashSet. key type: Integer +/// Time Complexity: O(|s|) +/// Space Complexity: O(1 << k) +class Solution { +public: + bool hasAllCodes(string s, int k) { + + if(k >= s.size()) return false; + + int cur = 0; + for(int i = 0; i < k - 1; i ++) + cur = 2 * cur + (s[i] == '1'); + + unordered_set set; + for(int i = k - 1; i < (int)s.size(); i ++){ + cur = cur * 2 + (s[i] == '1'); + set.insert(cur); + cur &= ~(1 << (k - 1)); + } + return set.size() == (1 << k); + } +}; + + +int main() { + + cout << Solution().hasAllCodes("00110110", 2) << endl; + // 1 + + cout << Solution().hasAllCodes("00110", 2) << endl; + // 1 + + cout << Solution().hasAllCodes("0110", 1) << endl; + // 1 + + cout << Solution().hasAllCodes("0110", 2) << endl; + // 0 + + cout << Solution().hasAllCodes("0000000001011100", 4) << endl; + // 0 + + cout << Solution().hasAllCodes("0", 20) << endl; + // 0 + + return 0; +} diff --git a/1001-1500/1461-Check-If-a-String-Contains-All-Binary-Codes-of-Size-K/cpp-1461/main3.cpp b/1001-1500/1461-Check-If-a-String-Contains-All-Binary-Codes-of-Size-K/cpp-1461/main3.cpp new file mode 100644 index 00000000..270ddf57 --- /dev/null +++ b/1001-1500/1461-Check-If-a-String-Contains-All-Binary-Codes-of-Size-K/cpp-1461/main3.cpp @@ -0,0 +1,56 @@ +/// Source : https://leetcode.com/problems/check-if-a-string-contains-all-binary-codes-of-size-k/ +/// Author : liuyubobobo +/// Time : 2020-05-30 +/// Updated: 2022-05-30 + +#include +#include + +using namespace std; + + +/// HashSet. Using array +/// Time Complexity: O(|s|) +/// Space Complexity: O(1 << k) +class Solution { +public: + bool hasAllCodes(string s, int k) { + + if(k >= s.size()) return false; + + int cur = 0; + for(int i = 0; i < k - 1; i ++) + cur = 2 * cur + (s[i] == '1'); + + vector used(1 << k, false); + for(int i = k - 1; i < s.size(); i ++){ + cur = cur * 2 + (s[i] == '1'); + used[cur] = true; + cur &= ~(1 << (k - 1)); + } + + for(int e: used) if(!e) return false; + return true; + } +}; + + +int main() { + + cout << Solution().hasAllCodes("00110110", 2) << endl; + // 1 + + cout << Solution().hasAllCodes("00110", 2) << endl; + // 1 + + cout << Solution().hasAllCodes("0110", 1) << endl; + // 1 + + cout << Solution().hasAllCodes("0110", 2) << endl; + // 0 + + cout << Solution().hasAllCodes("0000000001011100", 4) << endl; + // 0 + + return 0; +} diff --git a/1001-1500/1462-Course-Schedule-IV/cpp-1462/CMakeLists.txt b/1001-1500/1462-Course-Schedule-IV/cpp-1462/CMakeLists.txt new file mode 100644 index 00000000..56aa84f9 --- /dev/null +++ b/1001-1500/1462-Course-Schedule-IV/cpp-1462/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main3.cpp) \ No newline at end of file diff --git a/1001-1500/1462-Course-Schedule-IV/cpp-1462/main.cpp b/1001-1500/1462-Course-Schedule-IV/cpp-1462/main.cpp new file mode 100644 index 00000000..d5a98ce3 --- /dev/null +++ b/1001-1500/1462-Course-Schedule-IV/cpp-1462/main.cpp @@ -0,0 +1,73 @@ +/// Source : https://leetcode.com/problems/course-schedule-iv/ +/// Author : liuyubobobo +/// Time : 2020-05-30 + +#include +#include +#include + +using namespace std; + + +/// Check every query using DFS, cache to void repeat calculations +/// Time Complexity: O(n^3 + q) +/// Space Complexity: O(n^2) +class Solution { +public: + vector checkIfPrerequisite(int n, vector>& prerequisites, vector>& queries) { + + vector> g(n); + for(const vector& e: prerequisites) g[e[0]].insert(e[1]); + + vector> reach(n, vector(n, -1)); + vector res; + for(const vector& q: queries) + res.push_back(dfs(n, g, q[0], q[1], reach)); + return res; + } + +private: + bool dfs(int n, const vector>& g, + int a, int b, vector>& reach){ + + if(reach[a][b] != -1) return reach[a][b]; + if(a == b) return true; + + for(int next: g[a]){ + reach[a][next] = true; + reach[next][b] = dfs(n, g, next, b, reach); + if(reach[next][b]) return reach[a][b] = true; + } + return false; + } +}; + + +void print_vec(const vector& res){ + for(int e: res) cout << e << " "; cout << endl; +} + +int main() { + + vector> p1 = {{1, 0}}, q1 = {{0, 1}, {1, 0}}; + print_vec(Solution().checkIfPrerequisite(2, p1, q1)); + // 0 1 + + vector> p2 = {}, q2 = {{1, 0}, {0, 1}}; + print_vec(Solution().checkIfPrerequisite(2, p2, q2)); + // 0 0 + + vector> p3 = {{1, 2}, {1, 0}, {2, 0}}, q3 = {{1, 0}, {1, 2}}; + print_vec(Solution().checkIfPrerequisite(3, p3, q3)); + // 1 1 + + vector> p4 = {{1, 0}, {2, 0}}, q4 = {{0, 1}, {2, 0}}; + print_vec(Solution().checkIfPrerequisite(3, p4, q4)); + // 0 1 + + vector> p5 = {{0, 1}, {1, 2}, {2, 3}, {3, 4}}, q5 = {{0, 4}, {4, 0}, {1, 3}, {3, 0}}; + print_vec(Solution().checkIfPrerequisite(5, p5, q5)); + // 1 0 1 0 + + return 0; +} diff --git a/1001-1500/1462-Course-Schedule-IV/cpp-1462/main2.cpp b/1001-1500/1462-Course-Schedule-IV/cpp-1462/main2.cpp new file mode 100644 index 00000000..fa6917e5 --- /dev/null +++ b/1001-1500/1462-Course-Schedule-IV/cpp-1462/main2.cpp @@ -0,0 +1,75 @@ +/// Source : https://leetcode.com/problems/course-schedule-iv/ +/// Author : liuyubobobo +/// Time : 2020-05-30 + +#include +#include +#include + +using namespace std; + + +/// DFS to pre calculate all results +/// Time Complexity: O(n^3 + q) +/// Space Complexity: O(n^2) +class Solution { +public: + vector checkIfPrerequisite(int n, vector>& prerequisites, vector>& queries) { + + vector> g(n); + for(const vector& e: prerequisites) g[e[0]].insert(e[1]); + + vector> reach(n, vector(n, false)); + vector visited(n, false); + for(int i = 0; i < n; i ++) + if(!visited[i]) dfs(n, g, i, visited, reach); + + vector res; + for(const vector& q: queries) + res.push_back(reach[q[0]][q[1]]); + return res; + } + +private: + void dfs(int n, vector>& g, int v, + vector& visited, vector>& reach){ + + visited[v] = true; + for(int next: g[v]){ + if(!visited[next]) dfs(n, g, next, visited, reach); + for(int i = 0; i < n; i ++) + if(reach[next][i]) reach[v][i] = true; + reach[v][next] = true; + } + } +}; + + +void print_vec(const vector& res){ + for(int e: res) cout << e << " "; cout << endl; +} + +int main() { + + vector> p1 = {{1, 0}}, q1 = {{0, 1}, {1, 0}}; + print_vec(Solution().checkIfPrerequisite(2, p1, q1)); + // 0 1 + + vector> p2 = {}, q2 = {{1, 0}, {0, 1}}; + print_vec(Solution().checkIfPrerequisite(2, p2, q2)); + // 0 0 + + vector> p3 = {{1, 2}, {1, 0}, {2, 0}}, q3 = {{1, 0}, {1, 2}}; + print_vec(Solution().checkIfPrerequisite(3, p3, q3)); + // 1 1 + + vector> p4 = {{1, 0}, {2, 0}}, q4 = {{0, 1}, {2, 0}}; + print_vec(Solution().checkIfPrerequisite(3, p4, q4)); + // 0 1 + + vector> p5 = {{0, 1}, {1, 2}, {2, 3}, {3, 4}}, q5 = {{0, 4}, {4, 0}, {1, 3}, {3, 0}}; + print_vec(Solution().checkIfPrerequisite(5, p5, q5)); + // 1 0 1 0 + + return 0; +} diff --git a/1001-1500/1462-Course-Schedule-IV/cpp-1462/main3.cpp b/1001-1500/1462-Course-Schedule-IV/cpp-1462/main3.cpp new file mode 100644 index 00000000..6d2b20bd --- /dev/null +++ b/1001-1500/1462-Course-Schedule-IV/cpp-1462/main3.cpp @@ -0,0 +1,62 @@ +/// Source : https://leetcode.com/problems/course-schedule-iv/ +/// Author : liuyubobobo +/// Time : 2020-05-30 + +#include +#include +#include + +using namespace std; + + +/// Floyd +/// Time Complexity: O(n^3 + q) +/// Space Complexity: O(n^2) +class Solution { +public: + vector checkIfPrerequisite(int n, vector>& prerequisites, vector>& queries) { + + vector> g(n, vector(n, 0)); + for(const vector& e: prerequisites) g[e[0]][e[1]] = true; + + for(int k = 0; k < n; k ++) + for(int i = 0; i < n; i ++) + for(int j = 0; j < n; j ++) + if(!g[i][j] && g[i][k] && g[k][j]) g[i][j] = true; + + vector res; + for(const vector& q: queries) + res.push_back(g[q[0]][q[1]]); + return res; + } +}; + + +void print_vec(const vector& res){ + for(int e: res) cout << e << " "; cout << endl; +} + +int main() { + + vector> p1 = {{1, 0}}, q1 = {{0, 1}, {1, 0}}; + print_vec(Solution().checkIfPrerequisite(2, p1, q1)); + // 0 1 + + vector> p2 = {}, q2 = {{1, 0}, {0, 1}}; + print_vec(Solution().checkIfPrerequisite(2, p2, q2)); + // 0 0 + + vector> p3 = {{1, 2}, {1, 0}, {2, 0}}, q3 = {{1, 0}, {1, 2}}; + print_vec(Solution().checkIfPrerequisite(3, p3, q3)); + // 1 1 + + vector> p4 = {{1, 0}, {2, 0}}, q4 = {{0, 1}, {2, 0}}; + print_vec(Solution().checkIfPrerequisite(3, p4, q4)); + // 0 1 + + vector> p5 = {{0, 1}, {1, 2}, {2, 3}, {3, 4}}, q5 = {{0, 4}, {4, 0}, {1, 3}, {3, 0}}; + print_vec(Solution().checkIfPrerequisite(5, p5, q5)); + // 1 0 1 0 + + return 0; +} diff --git a/1001-1500/1463-Cherry-Pickup-II/cpp-1463/CMakeLists.txt b/1001-1500/1463-Cherry-Pickup-II/cpp-1463/CMakeLists.txt new file mode 100644 index 00000000..a965d66f --- /dev/null +++ b/1001-1500/1463-Cherry-Pickup-II/cpp-1463/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main3.cpp) \ No newline at end of file diff --git a/1001-1500/1463-Cherry-Pickup-II/cpp-1463/main.cpp b/1001-1500/1463-Cherry-Pickup-II/cpp-1463/main.cpp new file mode 100644 index 00000000..067fe424 --- /dev/null +++ b/1001-1500/1463-Cherry-Pickup-II/cpp-1463/main.cpp @@ -0,0 +1,66 @@ +/// Source : https://leetcode.com/problems/cherry-pickup-ii/ +/// Author : liuyubobobo +/// Time : 2020-05-30 + +#include +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(C^2 * R) +/// Space Complexity: O(C^2 * R) +class Solution { + +private: + int R, C; + +public: + int cherryPickup(vector>& grid) { + + R = grid.size(), C = grid[0].size(); + vector>> dp(R, vector>(C, vector(C, -1))); + return dfs(grid, 0, 0, C - 1, dp); + } + +private: + int dfs(const vector>& grid, int r, int a, int b, + vector>>& dp){ + + if(r == R) return 0; + if(dp[r][a][b] != -1) return dp[r][a][b]; + + int cur = a == b ? grid[r][a] : grid[r][a] + grid[r][b]; + int res = 0; + for(int i = -1; i <= 1; i ++) + if(a + i >= 0 && a + i < C) + for(int j = -1; j <= 1; j ++) + if(b + j >= 0 && b + j < C) + res = max(res, cur + dfs(grid, r + 1, a + i, b + j, dp)); + return dp[r][a][b] = res; + } +}; + + +int main() { + + vector> g1 = {{3,1,1},{2,5,1},{1,5,5},{2,1,1}}; + cout << Solution().cherryPickup(g1) << endl; + // 24 + + vector> g2 = {{1,0,0,0,0,0,1},{2,0,0,0,0,3,0},{2,0,9,0,0,0,0},{0,3,0,5,4,0,0},{1,0,2,3,0,0,6}}; + cout << Solution().cherryPickup(g2) << endl; + // 28 + + vector> g3 = {{1,0,0,3},{0,0,0,3},{0,0,3,3},{9,0,3,3}}; + cout << Solution().cherryPickup(g3) << endl; + // 22 + + vector> g4 = {{1,1},{1,1}}; + cout << Solution().cherryPickup(g4) << endl; + // 4 + + return 0; +} diff --git a/1001-1500/1463-Cherry-Pickup-II/cpp-1463/main2.cpp b/1001-1500/1463-Cherry-Pickup-II/cpp-1463/main2.cpp new file mode 100644 index 00000000..495d8d4e --- /dev/null +++ b/1001-1500/1463-Cherry-Pickup-II/cpp-1463/main2.cpp @@ -0,0 +1,66 @@ +/// Source : https://leetcode.com/problems/cherry-pickup-ii/ +/// Author : liuyubobobo +/// Time : 2020-05-30 + +#include +#include +#include + +using namespace std; + + +/// Memory Search with State Compression +/// Time Complexity: O(C^2 * R) +/// Space Complexity: O(C^2 * R) +class Solution { + +private: + int R, C; + +public: + int cherryPickup(vector>& grid) { + + R = grid.size(), C = grid[0].size(); + vector dp(R * 10000 + C * 100 + C, -1); + return dfs(grid, 0, 0, C - 1, dp); + } + +private: + int dfs(const vector>& grid, int r, int a, int b, + vector& dp){ + + if(r == R) return 0; + if(dp[r * 10000 + a * 100 + b] != -1) return dp[r * 10000 + a * 100 + b]; + + int cur = a == b ? grid[r][a] : grid[r][a] + grid[r][b]; + int res = 0; + for(int i = -1; i <= 1; i ++) + if(a + i >= 0 && a + i < C) + for(int j = -1; j <= 1; j ++) + if(b + j >= 0 && b + j < C) + res = max(res, cur + dfs(grid, r + 1, a + i, b + j, dp)); + return dp[r * 10000 + a * 100 + b] = res; + } +}; + + +int main() { + + vector> g1 = {{3,1,1},{2,5,1},{1,5,5},{2,1,1}}; + cout << Solution().cherryPickup(g1) << endl; + // 24 + + vector> g2 = {{1,0,0,0,0,0,1},{2,0,0,0,0,3,0},{2,0,9,0,0,0,0},{0,3,0,5,4,0,0},{1,0,2,3,0,0,6}}; + cout << Solution().cherryPickup(g2) << endl; + // 28 + + vector> g3 = {{1,0,0,3},{0,0,0,3},{0,0,3,3},{9,0,3,3}}; + cout << Solution().cherryPickup(g3) << endl; + // 22 + + vector> g4 = {{1,1},{1,1}}; + cout << Solution().cherryPickup(g4) << endl; + // 4 + + return 0; +} diff --git a/1001-1500/1463-Cherry-Pickup-II/cpp-1463/main3.cpp b/1001-1500/1463-Cherry-Pickup-II/cpp-1463/main3.cpp new file mode 100644 index 00000000..39646613 --- /dev/null +++ b/1001-1500/1463-Cherry-Pickup-II/cpp-1463/main3.cpp @@ -0,0 +1,67 @@ +/// Source : https://leetcode.com/problems/cherry-pickup-ii/ +/// Author : liuyubobobo +/// Time : 2020-05-30 + +#include +#include +#include + +using namespace std; + + +/// Memory Search with State Compression +/// Optimization: the two routes shouldn't cross +/// Time Complexity: O(C^2 * R) +/// Space Complexity: O(C^2 * R) +class Solution { + +private: + int R, C; + +public: + int cherryPickup(vector>& grid) { + + R = grid.size(), C = grid[0].size(); + vector dp(R * 10000 + C * 100 + C, -1); + return dfs(grid, 0, 0, C - 1, dp); + } + +private: + int dfs(const vector>& grid, int r, int a, int b, + vector& dp){ + + if(r == R) return 0; + if(dp[r * 10000 + a * 100 + b] != -1) return dp[r * 10000 + a * 100 + b]; + + int cur = grid[r][a] + grid[r][b]; + int res = 0; + for(int i = -1; i <= 1; i ++) + if(a + i >= 0 && a + i < C) + for(int j = -1; j <= 1; j ++) + if(b + j >= 0 && b + j < C && a + i < b + j) + res = max(res, cur + dfs(grid, r + 1, a + i, b + j, dp)); + return dp[r * 10000 + a * 100 + b] = res; + } +}; + + +int main() { + + vector> g1 = {{3,1,1},{2,5,1},{1,5,5},{2,1,1}}; + cout << Solution().cherryPickup(g1) << endl; + // 24 + + vector> g2 = {{1,0,0,0,0,0,1},{2,0,0,0,0,3,0},{2,0,9,0,0,0,0},{0,3,0,5,4,0,0},{1,0,2,3,0,0,6}}; + cout << Solution().cherryPickup(g2) << endl; + // 28 + + vector> g3 = {{1,0,0,3},{0,0,0,3},{0,0,3,3},{9,0,3,3}}; + cout << Solution().cherryPickup(g3) << endl; + // 22 + + vector> g4 = {{1,1},{1,1}}; + cout << Solution().cherryPickup(g4) << endl; + // 4 + + return 0; +} diff --git a/1001-1500/1463-Cherry-Pickup-II/cpp-1463/main4.cpp b/1001-1500/1463-Cherry-Pickup-II/cpp-1463/main4.cpp new file mode 100644 index 00000000..f3a52bcf --- /dev/null +++ b/1001-1500/1463-Cherry-Pickup-II/cpp-1463/main4.cpp @@ -0,0 +1,64 @@ +/// Source : https://leetcode.com/problems/cherry-pickup-ii/ +/// Author : liuyubobobo +/// Time : 2020-05-30 + +#include +#include +#include + +using namespace std; + + +/// Dynamic Programming with State Compression + Rolling Array + Optimization +/// Time Complexity: O(C^2 * R) +/// Space Complexity: O(C^2) +class Solution { +public: + int cherryPickup(vector>& grid) { + + int R = grid.size(), C = grid[0].size(); + unordered_map dp; + dp[0 * C + C - 1] = grid[0][0] + grid[0][C - 1]; + for(int i = 1; i < R; i ++){ + + unordered_map tdp; + for(const pair& p: dp){ + int a = p.first / C, b = p.first % C; + for(int j1 = -1; j1 <= 1; j1 ++) + if(a + j1 >= 0 && a + j1 < C) + for(int j2 = -1; j2 <= 1; j2 ++) + if(b + j2 >= 0 && b + j2 < C && a + j1 < b + j2){ + int next = (a + j1) * C + b + j2; + tdp[next] = max(tdp[next], p.second + grid[i][a + j1] + grid[i][b + j2]); + } + } + dp = tdp; + } + + int res = 0; + for(const pair& p: dp) res = max(res, p.second); + return res; + } +}; + + +int main() { + + vector> g1 = {{3,1,1},{2,5,1},{1,5,5},{2,1,1}}; + cout << Solution().cherryPickup(g1) << endl; + // 24 + + vector> g2 = {{1,0,0,0,0,0,1},{2,0,0,0,0,3,0},{2,0,9,0,0,0,0},{0,3,0,5,4,0,0},{1,0,2,3,0,0,6}}; + cout << Solution().cherryPickup(g2) << endl; + // 28 + + vector> g3 = {{1,0,0,3},{0,0,0,3},{0,0,3,3},{9,0,3,3}}; + cout << Solution().cherryPickup(g3) << endl; + // 22 + + vector> g4 = {{1,1},{1,1}}; + cout << Solution().cherryPickup(g4) << endl; + // 4 + + return 0; +} diff --git a/1001-1500/1464-Maximum-Product-of-Two-Elements-in-an-Array/cpp-1464/CMakeLists.txt b/1001-1500/1464-Maximum-Product-of-Two-Elements-in-an-Array/cpp-1464/CMakeLists.txt new file mode 100644 index 00000000..446d8265 --- /dev/null +++ b/1001-1500/1464-Maximum-Product-of-Two-Elements-in-an-Array/cpp-1464/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main2.cpp) \ No newline at end of file diff --git a/1001-1500/1464-Maximum-Product-of-Two-Elements-in-an-Array/cpp-1464/main.cpp b/1001-1500/1464-Maximum-Product-of-Two-Elements-in-an-Array/cpp-1464/main.cpp new file mode 100644 index 00000000..5b4d38fe --- /dev/null +++ b/1001-1500/1464-Maximum-Product-of-Two-Elements-in-an-Array/cpp-1464/main.cpp @@ -0,0 +1,30 @@ +/// Source : https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/ +/// Author : liuyubobobo +/// Time : 2020-05-30 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n^2) +/// Space Complexity: O(1) +class Solution { +public: + int maxProduct(vector& nums) { + + int res = 0; + for(int i = 0; i < nums.size(); i ++) + for(int j = i + 1; j < nums.size(); j ++) + res = max(res, (nums[i] - 1) * (nums[j] - 1)); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1464-Maximum-Product-of-Two-Elements-in-an-Array/cpp-1464/main2.cpp b/1001-1500/1464-Maximum-Product-of-Two-Elements-in-an-Array/cpp-1464/main2.cpp new file mode 100644 index 00000000..f1a0ae5f --- /dev/null +++ b/1001-1500/1464-Maximum-Product-of-Two-Elements-in-an-Array/cpp-1464/main2.cpp @@ -0,0 +1,27 @@ +/// Source : https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/ +/// Author : liuyubobobo +/// Time : 2020-06-05 + +#include +#include + +using namespace std; + + +/// Sorting +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + int maxProduct(vector& nums) { + + sort(nums.begin(), nums.end(), greater()); + return (nums[0] - 1) * (nums[1] - 1); + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1464-Maximum-Product-of-Two-Elements-in-an-Array/cpp-1464/main3.cpp b/1001-1500/1464-Maximum-Product-of-Two-Elements-in-an-Array/cpp-1464/main3.cpp new file mode 100644 index 00000000..3888c080 --- /dev/null +++ b/1001-1500/1464-Maximum-Product-of-Two-Elements-in-an-Array/cpp-1464/main3.cpp @@ -0,0 +1,30 @@ +/// Source : https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/ +/// Author : liuyubobobo +/// Time : 2020-06-05 + +#include +#include + +using namespace std; + + +/// Linear Scan to find the largest and the second largest +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int maxProduct(vector& nums) { + + int a = -1, b = -1; + for(int e: nums) + if(e >= a) b = a, a = e; + else if(e > b) b = e; + return (a - 1) * (b - 1); + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1465-Maximum-Area-of-a-Piece-of-Cake-After-Horizontal-and-Vertical-Cuts/cpp-1465/CMakeLists.txt b/1001-1500/1465-Maximum-Area-of-a-Piece-of-Cake-After-Horizontal-and-Vertical-Cuts/cpp-1465/CMakeLists.txt new file mode 100644 index 00000000..545e47b8 --- /dev/null +++ b/1001-1500/1465-Maximum-Area-of-a-Piece-of-Cake-After-Horizontal-and-Vertical-Cuts/cpp-1465/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1001-1500/1465-Maximum-Area-of-a-Piece-of-Cake-After-Horizontal-and-Vertical-Cuts/cpp-1465/main.cpp b/1001-1500/1465-Maximum-Area-of-a-Piece-of-Cake-After-Horizontal-and-Vertical-Cuts/cpp-1465/main.cpp new file mode 100644 index 00000000..12b9c3bb --- /dev/null +++ b/1001-1500/1465-Maximum-Area-of-a-Piece-of-Cake-After-Horizontal-and-Vertical-Cuts/cpp-1465/main.cpp @@ -0,0 +1,43 @@ +/// Source : https://leetcode.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/ +/// Author : liuyubobobo +/// Time : 2020-05-30 + +#include +#include + +using namespace std; + + +/// Sorting and Find the max gap +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { + +private: + const long long MOD = 1e9 + 7; + +public: + int maxArea(int h, int w, vector& horizontalCuts, vector& verticalCuts) { + + horizontalCuts.push_back(h); + verticalCuts.push_back(w); + sort(horizontalCuts.begin(), horizontalCuts.end()); + sort(verticalCuts.begin(), verticalCuts.end()); + + int a = horizontalCuts[0]; + for(int i = 1; i < horizontalCuts.size(); i ++) + a = max(a, horizontalCuts[i] - horizontalCuts[i - 1]); + + int b = verticalCuts[0]; + for(int i = 1; i < verticalCuts.size(); i ++) + b = max(b, verticalCuts[i] - verticalCuts[i - 1]); + + return (long long)a * (long long)b % MOD; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1466-Reorder-Routes-to-Make-All-Paths-Lead-to-the-City-Zero/cpp-1466/CMakeLists.txt b/1001-1500/1466-Reorder-Routes-to-Make-All-Paths-Lead-to-the-City-Zero/cpp-1466/CMakeLists.txt new file mode 100644 index 00000000..26e63018 --- /dev/null +++ b/1001-1500/1466-Reorder-Routes-to-Make-All-Paths-Lead-to-the-City-Zero/cpp-1466/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main2.cpp) \ No newline at end of file diff --git a/1001-1500/1466-Reorder-Routes-to-Make-All-Paths-Lead-to-the-City-Zero/cpp-1466/main.cpp b/1001-1500/1466-Reorder-Routes-to-Make-All-Paths-Lead-to-the-City-Zero/cpp-1466/main.cpp new file mode 100644 index 00000000..261eb730 --- /dev/null +++ b/1001-1500/1466-Reorder-Routes-to-Make-All-Paths-Lead-to-the-City-Zero/cpp-1466/main.cpp @@ -0,0 +1,49 @@ +/// Source : https://leetcode.com/problems/reorder-routes-to-make-all-paths-lead-to-the-city-zero/ +/// Author : liuyubobobo +/// Time : 2020-05-30 + +#include +#include +#include +#include + +using namespace std; + + +/// DFS, Using Map to record edges' directions +/// Time Complexity: O(V + E) +/// Space Complexity: O(E) +class Solution { +public: + int minReorder(int n, vector>& connections) { + + vector> g(n); + map, int> directions; + for(const vector& e: connections){ + g[e[0]].insert(e[1]), g[e[1]].insert(e[0]); + directions[make_pair(e[0], e[1])] = e[0]; + directions[make_pair(e[1], e[0])] = e[0]; + } + + vector visited(n, false); + return dfs(g, 0, -1, directions, visited); + } + +private: + int dfs(const vector>& g, int v, int p, + map, int>& directions, vector& visited){ + + visited[v] = true; + int res = 0; + if(p != -1) res += (directions[make_pair(v, p)] == p); + for(int next: g[v]) + if(!visited[next]) res += dfs(g, next, v, directions, visited); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1466-Reorder-Routes-to-Make-All-Paths-Lead-to-the-City-Zero/cpp-1466/main2.cpp b/1001-1500/1466-Reorder-Routes-to-Make-All-Paths-Lead-to-the-City-Zero/cpp-1466/main2.cpp new file mode 100644 index 00000000..d55fe4b9 --- /dev/null +++ b/1001-1500/1466-Reorder-Routes-to-Make-All-Paths-Lead-to-the-City-Zero/cpp-1466/main2.cpp @@ -0,0 +1,44 @@ +/// Source : https://leetcode.com/problems/reorder-routes-to-make-all-paths-lead-to-the-city-zero/ +/// Author : liuyubobobo +/// Time : 2020-05-30 + +#include +#include +#include +#include + +using namespace std; + + +/// DFS, record edges' direction on adjacent list +/// Time Complexity: O(V + E) +/// Space Complexity: O(V + E) +class Solution { +public: + int minReorder(int n, vector>& connections) { + + vector> g(n); + for(const vector& e: connections) + g[e[0]][e[1]] = true, g[e[1]][e[0]] = false; + + vector visited(n, false); + return dfs(g, 0, visited); + } + +private: + int dfs(const vector>& g, int v, vector& visited){ + + visited[v] = true; + int res = 0; + for(const pair &p: g[v]) + if(!visited[p.first]) + res += p.second + dfs(g, p.first, visited); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1467-Probability-of-a-Two-Boxes-Having-The-Same-Number-of-Distinct-Balls/cpp-1467/CMakeLists.txt b/1001-1500/1467-Probability-of-a-Two-Boxes-Having-The-Same-Number-of-Distinct-Balls/cpp-1467/CMakeLists.txt new file mode 100644 index 00000000..ffce3872 --- /dev/null +++ b/1001-1500/1467-Probability-of-a-Two-Boxes-Having-The-Same-Number-of-Distinct-Balls/cpp-1467/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main2.cpp) \ No newline at end of file diff --git a/1001-1500/1467-Probability-of-a-Two-Boxes-Having-The-Same-Number-of-Distinct-Balls/cpp-1467/main.cpp b/1001-1500/1467-Probability-of-a-Two-Boxes-Having-The-Same-Number-of-Distinct-Balls/cpp-1467/main.cpp new file mode 100644 index 00000000..b20620dd --- /dev/null +++ b/1001-1500/1467-Probability-of-a-Two-Boxes-Having-The-Same-Number-of-Distinct-Balls/cpp-1467/main.cpp @@ -0,0 +1,83 @@ +/// Source : https://leetcode.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/ +/// Author : liuyubobobo +/// Time : 2020-06-05 + +#include +#include +#include + +using namespace std; + + +/// DFS to calculate all possibilities +/// Time Complexity: O(balls[i] * balls[i] ^ balls.length) +/// Space Complexity: O(balls.length + sum) +class Solution { + +private: + int n; + double perm[49]; + +public: + double getProbability(vector& balls) { + + perm[0] = 1.0; + for(int i = 1; i <= 48; i ++) perm[i] = i * perm[i - 1]; + + n = accumulate(balls.begin(), balls.end(), 0); + + double all = perm[n]; + for(int e: balls) all /= perm[e]; +// cout << "all : " << all << endl; + + double valid = dfs(balls, 0, 0, 0, n / 2, n / 2); +// cout << "valid : " << valid << endl; + + return valid / all; + } + +private: + double dfs(vector& balls, int index, int c1, int c2, int cnt1, int cnt2){ + + if(index == balls.size()) + return cnt1 == 0 && cnt2 == 0 && c1 == c2; + + double res = 0.0; + for(int i = 0; i <= balls[index] && i <= cnt1; i ++) + if(balls[index] - i <= cnt2) + res += dfs(balls, index + 1, i ? c1 + 1 : c1, balls[index] - i ? c2 + 1 : c2, cnt1 - i, cnt2 - (balls[index] - i)) + * C(cnt1, i) * C(cnt2, balls[index] - i); + return res; + } + + double C(int a, int k){ +// assert(k >= 0 && k <= a); + return perm[a] / perm[k] / perm[a - k]; + } +}; + + +int main() { + + vector balls1 = {1, 1}; + cout << Solution().getProbability(balls1) << endl; + // 1.0 + + vector balls2 = {2, 1, 1}; + cout << Solution().getProbability(balls2) << endl; + // 0.66667 + + vector balls3 = {1, 2, 1, 2}; + cout << Solution().getProbability(balls3) << endl; + // 0.6 + + vector balls4 = {3, 2, 1}; + cout << Solution().getProbability(balls4) << endl; + // 0.3 + + vector balls5 = {6,6,6,6,6,6}; + cout << Solution().getProbability(balls5) << endl; + // 0.90327 + + return 0; +} diff --git a/1001-1500/1467-Probability-of-a-Two-Boxes-Having-The-Same-Number-of-Distinct-Balls/cpp-1467/main2.cpp b/1001-1500/1467-Probability-of-a-Two-Boxes-Having-The-Same-Number-of-Distinct-Balls/cpp-1467/main2.cpp new file mode 100644 index 00000000..0408d32c --- /dev/null +++ b/1001-1500/1467-Probability-of-a-Two-Boxes-Having-The-Same-Number-of-Distinct-Balls/cpp-1467/main2.cpp @@ -0,0 +1,88 @@ +/// Source : https://leetcode.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/ +/// Author : liuyubobobo +/// Time : 2020-06-05 + +#include +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(balls[i]^3 * balls.length * sum) +/// Space Complexity: O(balls[i]^2 * balls.length * sum) +class Solution { + +private: + int n; + double perm[49]; + +public: + double getProbability(vector& balls) { + + perm[0] = 1.0; + for(int i = 1; i <= 48; i ++) perm[i] = i * perm[i - 1]; + + n = accumulate(balls.begin(), balls.end(), 0); + + double all = perm[n]; + for(int e: balls) all /= perm[e]; +// cout << "all : " << all << endl; + + vector dp(25 * 10 * 10 * 10, -1); + double valid = dfs(balls, 0, 0, 0, n / 2, n / 2, dp); +// cout << "valid : " << valid << endl; + + return valid / all; + } + +private: + double dfs(vector& balls, int index, int c1, int c2, int cnt1, int cnt2, + vector& dp){ + + if(index == balls.size()) + return cnt1 == 0 && cnt2 == 0 && c1 == c2; + + int hashcode = cnt1 * 1000 + c2 * 100 + c1 * 10 + index; + if(dp[hashcode] != -1) return dp[hashcode]; + + double res = 0.0; + for(int i = 0; i <= balls[index] && i <= cnt1; i ++) + if(balls[index] - i <= cnt2) + res += dfs(balls, index + 1, i ? c1 + 1 : c1, balls[index] - i ? c2 + 1 : c2, cnt1 - i, cnt2 - (balls[index] - i), dp) + * C(cnt1, i) * C(cnt2, balls[index] - i); + return dp[hashcode] = res; + } + + double C(int a, int k){ +// assert(k >= 0 && k <= a); + return perm[a] / perm[k] / perm[a - k]; + } +}; + + +int main() { + + vector balls1 = {1, 1}; + cout << Solution().getProbability(balls1) << endl; + // 1.0 + + vector balls2 = {2, 1, 1}; + cout << Solution().getProbability(balls2) << endl; + // 0.66667 + + vector balls3 = {1, 2, 1, 2}; + cout << Solution().getProbability(balls3) << endl; + // 0.6 + + vector balls4 = {3, 2, 1}; + cout << Solution().getProbability(balls4) << endl; + // 0.3 + + vector balls5 = {6,6,6,6,6,6}; + cout << Solution().getProbability(balls5) << endl; + // 0.90327 + + return 0; +} diff --git a/1001-1500/1469-Find-All-the-Lonely-Nodes/cpp-1469/CMakeLists.txt b/1001-1500/1469-Find-All-the-Lonely-Nodes/cpp-1469/CMakeLists.txt new file mode 100644 index 00000000..9e6ef8a8 --- /dev/null +++ b/1001-1500/1469-Find-All-the-Lonely-Nodes/cpp-1469/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(cpp_1469) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1469 main.cpp) \ No newline at end of file diff --git a/1001-1500/1469-Find-All-the-Lonely-Nodes/cpp-1469/main.cpp b/1001-1500/1469-Find-All-the-Lonely-Nodes/cpp-1469/main.cpp new file mode 100644 index 00000000..4a71fd7c --- /dev/null +++ b/1001-1500/1469-Find-All-the-Lonely-Nodes/cpp-1469/main.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/find-all-the-lonely-nodes/ +/// Author : liuyubobobo +/// Time : 2020-06-05 + +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(h) + +/// 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 getLonelyNodes(TreeNode* root) { + + vector res; + dfs(root, res); + return res; + } + +private: + void dfs(TreeNode* node, vector& res){ + + if(!node) return; + + if(node->left && !node->right) + res.push_back(node->left->val); + + if(!node->left && node->right) + res.push_back(node->right->val); + + dfs(node->left, res); + dfs(node->right, res); + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1470-Shuffle-the-Array/cpp-1470/CMakeLists.txt b/1001-1500/1470-Shuffle-the-Array/cpp-1470/CMakeLists.txt new file mode 100644 index 00000000..e490c904 --- /dev/null +++ b/1001-1500/1470-Shuffle-the-Array/cpp-1470/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main3.cpp) \ No newline at end of file diff --git a/1001-1500/1470-Shuffle-the-Array/cpp-1470/main.cpp b/1001-1500/1470-Shuffle-the-Array/cpp-1470/main.cpp new file mode 100644 index 00000000..620015d9 --- /dev/null +++ b/1001-1500/1470-Shuffle-the-Array/cpp-1470/main.cpp @@ -0,0 +1,29 @@ +/// Source : https://leetcode.com/problems/shuffle-the-array/ +/// Author : liuyubobobo +/// Time : 2020-06-06 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector shuffle(vector& nums, int n) { + + vector res(2 * n); + for(int i = 0, j = 0; i < n; i ++) + res[j ++] = nums[i], res[j ++] = nums[n + i]; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1470-Shuffle-the-Array/cpp-1470/main2.cpp b/1001-1500/1470-Shuffle-the-Array/cpp-1470/main2.cpp new file mode 100644 index 00000000..66b72d01 --- /dev/null +++ b/1001-1500/1470-Shuffle-the-Array/cpp-1470/main2.cpp @@ -0,0 +1,31 @@ +/// Source : https://leetcode.com/problems/shuffle-the-array/ +/// Author : liuyubobobo +/// Time : 2020-06-08 + +#include +#include + +using namespace std; + + +/// Using the higher bits to store the numbers +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + vector shuffle(vector& nums, int n) { + + for(int i = 0; i < 2 * n; i ++){ + int j = i < n ? 2 * i : 2 * (i - n) + 1; + nums[j] |= (nums[i] & 1023) << 10; + } + for(int& e: nums) e >>= 10; + return nums; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1470-Shuffle-the-Array/cpp-1470/main3.cpp b/1001-1500/1470-Shuffle-the-Array/cpp-1470/main3.cpp new file mode 100644 index 00000000..19c063b0 --- /dev/null +++ b/1001-1500/1470-Shuffle-the-Array/cpp-1470/main3.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/shuffle-the-array/ +/// Author : liuyubobobo +/// Time : 2020-06-08 + +#include +#include + +using namespace std; + + +/// Using nums[i] as a buffer storage +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + vector shuffle(vector& nums, int n) { + + for(int i = 0; i < 2 * n; i ++) + if(nums[i] > 0){ + int j = i; + while(nums[i] > 0){ + j = j < n ? 2 * j : 2 * (j - n) + 1; + swap(nums[i], nums[j]); + nums[j] = -nums[j]; + } + } + + for(int& e: nums) e = -e; + return nums; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1471-The-k-Strongest-Values-in-an-Array/cpp-1471/CMakeLists.txt b/1001-1500/1471-The-k-Strongest-Values-in-an-Array/cpp-1471/CMakeLists.txt new file mode 100644 index 00000000..e6f5d34c --- /dev/null +++ b/1001-1500/1471-The-k-Strongest-Values-in-an-Array/cpp-1471/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main2.cpp) \ No newline at end of file diff --git a/1001-1500/1471-The-k-Strongest-Values-in-an-Array/cpp-1471/main.cpp b/1001-1500/1471-The-k-Strongest-Values-in-an-Array/cpp-1471/main.cpp new file mode 100644 index 00000000..f4527e1b --- /dev/null +++ b/1001-1500/1471-The-k-Strongest-Values-in-an-Array/cpp-1471/main.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/the-k-strongest-values-in-an-array/ +/// Author : liuyubobobo +/// Time : 2020-06-06 + +#include +#include + +using namespace std; + + +/// Sorting +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + vector getStrongest(vector& arr, int k) { + + sort(arr.begin(), arr.end()); + int mid = arr[(arr.size() - 1) / 2]; + sort(arr.begin(), arr.end(), [mid](int a, int b){ + if(abs(a - mid) != abs(b - mid)) + return abs(a - mid) > abs(b - mid); + return a > b; + }); + return vector(arr.begin(), arr.begin() + k); + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1471-The-k-Strongest-Values-in-an-Array/cpp-1471/main2.cpp b/1001-1500/1471-The-k-Strongest-Values-in-an-Array/cpp-1471/main2.cpp new file mode 100644 index 00000000..7ca1bce5 --- /dev/null +++ b/1001-1500/1471-The-k-Strongest-Values-in-an-Array/cpp-1471/main2.cpp @@ -0,0 +1,43 @@ +/// Source : https://leetcode.com/problems/the-k-strongest-values-in-an-array/ +/// Author : liuyubobobo +/// Time : 2020-06-06 + +#include +#include +#include + +using namespace std; + + +/// Using Priority Queue +/// Time Complexity: O(nlogk) +/// Space Complexity: O(k) +class Solution { +public: + vector getStrongest(vector& arr, int k) { + + sort(arr.begin(), arr.end()); + int mid = arr[(arr.size() - 1) / 2]; + + auto comp = [mid](int a, int b){ + if(abs(a - mid) != abs(b - mid)) + return abs(a - mid) > abs(b - mid); + return a > b; + }; + + priority_queue, decltype(comp)> pq(comp); + for(int e: arr) + if(pq.size() < k) pq.push(e); + else if(comp(e, pq.top())) pq.pop(), pq.push(e); + + vector res; + while(!pq.empty()) res.push_back(pq.top()), pq.pop(); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1472-Design-Browser-History/cpp-1472/CMakeLists.txt b/1001-1500/1472-Design-Browser-History/cpp-1472/CMakeLists.txt new file mode 100644 index 00000000..56aa84f9 --- /dev/null +++ b/1001-1500/1472-Design-Browser-History/cpp-1472/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main3.cpp) \ No newline at end of file diff --git a/1001-1500/1472-Design-Browser-History/cpp-1472/main.cpp b/1001-1500/1472-Design-Browser-History/cpp-1472/main.cpp new file mode 100644 index 00000000..0e44255f --- /dev/null +++ b/1001-1500/1472-Design-Browser-History/cpp-1472/main.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/design-browser-history/ +/// Author : liuyubobobo +/// Time : 2020-06-06 + +#include +#include + +using namespace std; + + +/// Using Array +/// Time Complexity: init: O(1) +/// visit: O(n) +/// back: O(1) +/// forward: O(1) +class BrowserHistory { + +private: + vector history; + int p; + +public: + BrowserHistory(string homepage) : p(0) { + history.push_back(homepage); + } + + void visit(string url) { + while(p + 1 != history.size()) history.pop_back(); + history.push_back(url); + p ++; + } + + string back(int steps) { + + p = max(0, p - steps); + return history[p]; + } + + string forward(int steps) { + + p = min((int)history.size() - 1, p + steps); + return history[p]; + } +}; + +/** + * Your BrowserHistory object will be instantiated and called as such: + * BrowserHistory* obj = new BrowserHistory(homepage); + * obj->visit(url); + * string param_2 = obj->back(steps); + * string param_3 = obj->forward(steps); + */ + +int main() { + + return 0; +} diff --git a/1001-1500/1472-Design-Browser-History/cpp-1472/main2.cpp b/1001-1500/1472-Design-Browser-History/cpp-1472/main2.cpp new file mode 100644 index 00000000..241664e0 --- /dev/null +++ b/1001-1500/1472-Design-Browser-History/cpp-1472/main2.cpp @@ -0,0 +1,70 @@ +/// Source : https://leetcode.com/problems/design-browser-history/ +/// Author : liuyubobobo +/// Time : 2020-06-06 + +#include +#include + +using namespace std; + + +/// Two Stacks +/// Time Complexity: init: O(1) +/// visit: O(1) +/// back: O(step) +/// forward: O(step) +class BrowserHistory { + +private: + stack history, backhistory; + +public: + BrowserHistory(string homepage){ + history.push(homepage); + } + + void visit(string url) { + history.push(url); + backhistory = stack(); + } + + string back(int steps) { + while(steps -- && history.size() > 1) + backhistory.push(history.top()), history.pop(); + return history.top(); + } + + string forward(int steps) { + while(steps -- && backhistory.size()) + history.push(backhistory.top()), backhistory.pop(); + return history.top(); + } +}; + +/** + * Your BrowserHistory object will be instantiated and called as such: + * BrowserHistory* obj = new BrowserHistory(homepage); + * obj->visit(url); + * string param_2 = obj->back(steps); + * string param_3 = obj->forward(steps); + */ + +int main() { + + BrowserHistory bh("leetcode.com"); + bh.visit("google.com"); + bh.visit("facebook.com"); + bh.visit("youtube.com"); + + cout << bh.back(1) << endl; // facebook + cout << bh.back(1) << endl; // google + cout << bh.forward(1) << endl; // facebook + + bh.visit("linkedin.com"); + + cout << bh.forward(2) << endl; // linkedin + cout << bh.back(2) << endl; // google + cout << bh.back(7) << endl; // leetcode + + return 0; +} diff --git a/1001-1500/1472-Design-Browser-History/cpp-1472/main3.cpp b/1001-1500/1472-Design-Browser-History/cpp-1472/main3.cpp new file mode 100644 index 00000000..f421ece5 --- /dev/null +++ b/1001-1500/1472-Design-Browser-History/cpp-1472/main3.cpp @@ -0,0 +1,71 @@ +/// Source : https://leetcode.com/problems/design-browser-history/ +/// Author : liuyubobobo +/// Time : 2020-06-06 + +#include +#include + +using namespace std; + + +/// Using Array +/// make a sz to record the valid length +/// Time Complexity: init: O(1) +/// visit: O(1) +/// back: O(1) +/// forward: O(1) +class BrowserHistory { + +private: + vector history; + int p, sz; + +public: + BrowserHistory(string homepage) : p(0), sz(1) { + history.push_back(homepage); + } + + void visit(string url) { + if(p + 1 < history.size()) history[++p] = url; + else history.push_back(url), p ++; + sz = p + 1; + } + + string back(int steps) { + p = max(0, p - steps); + return history[p]; + } + + string forward(int steps) { + p = min(sz - 1, p + steps); + return history[p]; + } +}; + +/** + * Your BrowserHistory object will be instantiated and called as such: + * BrowserHistory* obj = new BrowserHistory(homepage); + * obj->visit(url); + * string param_2 = obj->back(steps); + * string param_3 = obj->forward(steps); + */ + +int main() { + + BrowserHistory bh("leetcode.com"); + bh.visit("google.com"); + bh.visit("facebook.com"); + bh.visit("youtube.com"); + + cout << bh.back(1) << endl; // facebook + cout << bh.back(1) << endl; // google + cout << bh.forward(1) << endl; // facebook + + bh.visit("linkedin.com"); + + cout << bh.forward(2) << endl; // linkedin + cout << bh.back(2) << endl; // google + cout << bh.back(7) << endl; // leetcode + + return 0; +} diff --git a/1001-1500/1473-Paint-House-III/cpp-1473/CMakeLists.txt b/1001-1500/1473-Paint-House-III/cpp-1473/CMakeLists.txt new file mode 100644 index 00000000..a965d66f --- /dev/null +++ b/1001-1500/1473-Paint-House-III/cpp-1473/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main3.cpp) \ No newline at end of file diff --git a/1001-1500/1473-Paint-House-III/cpp-1473/main.cpp b/1001-1500/1473-Paint-House-III/cpp-1473/main.cpp new file mode 100644 index 00000000..16a02da1 --- /dev/null +++ b/1001-1500/1473-Paint-House-III/cpp-1473/main.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/paint-house-iii/ +/// Author : liuyubobobo +/// Time : 2020-06-06 + +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(m^2 * n^2) +/// Space Complexity: O(m^2 * n) +class Solution { + +private: + int n; + const int INF = 1e7; + +public: + int minCost(vector& houses, vector>& cost, int m, int n, int target) { + + this->n = n; + + vector>> dp(m, vector>(n + 1, vector(m + 1, -1))); + int res = dfs(houses, 0, 0, target, cost, dp); + return res == INF ? -1 : res; + } + +private: + int dfs(const vector& houses, int index, int precolor, int target, + const vector>& cost, vector>>& dp){ + + if(target < 0) return INF; + if(index == houses.size()) return target ? INF : 0; + if(dp[index][precolor][target] != -1) return dp[index][precolor][target]; + + int res = INF; + if(!houses[index]){ + for(int i = 1; i <= n; i ++) + res = min(res, cost[index][i - 1] + dfs(houses, index + 1, i, i == precolor ? target : target - 1, cost, dp)); + } + else + res = dfs(houses, index + 1, houses[index], houses[index] == precolor ? target : target - 1, cost, dp); + + return dp[index][precolor][target] = res; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1473-Paint-House-III/cpp-1473/main2.cpp b/1001-1500/1473-Paint-House-III/cpp-1473/main2.cpp new file mode 100644 index 00000000..e4d07946 --- /dev/null +++ b/1001-1500/1473-Paint-House-III/cpp-1473/main2.cpp @@ -0,0 +1,45 @@ +/// Source : https://leetcode.com/problems/paint-house-iii/ +/// Author : liuyubobobo +/// Time : 2020-06-06 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(m^2 * n^2) +/// Space Complexity: O(m^2 * n) +class Solution { + +private: + const int INF = 1e7; + +public: + int minCost(vector& houses, vector>& cost, int m, int n, int target) { + + vector>> dp(m, vector>(n + 1, vector(m + 1, INF))); + + if(!houses[0]) for(int color = 1; color <= n; color ++) dp[0][color][1] = cost[0][color - 1]; + else dp[0][houses[0]][1] = 0; + + for(int index = 1; index < m; index ++) + for(int color = 1; color <= n; color ++) + if(!houses[index] || houses[index] == color) + for(int precolor = 1; precolor <= n; precolor ++) + for(int k = 1; k <= target; k ++) + dp[index][color][k] = min(dp[index][color][k], + (houses[index] ? 0 : cost[index][color - 1]) + dp[index - 1][precolor][k - (precolor != color)]); + + int res = INF; + for(int color = 1; color <= n; color ++) res = min(res, dp[m - 1][color][target]); + return res == INF ? -1 : res; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1473-Paint-House-III/cpp-1473/main3.cpp b/1001-1500/1473-Paint-House-III/cpp-1473/main3.cpp new file mode 100644 index 00000000..3ac66e50 --- /dev/null +++ b/1001-1500/1473-Paint-House-III/cpp-1473/main3.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/paint-house-iii/ +/// Author : liuyubobobo +/// Time : 2020-06-06 + +#include +#include + +using namespace std; + + +/// Dynamic Programming + Rolling Array +/// Time Complexity: O(m^2 * n^2) +/// Space Complexity: O(m * n) +class Solution { + +private: + const int INF = 1e7; + +public: + int minCost(vector& houses, vector>& cost, int m, int n, int target) { + + vector> dp(n + 1, vector(m + 1, INF)); + + if(!houses[0]) for(int color = 1; color <= n; color ++) dp[color][1] = cost[0][color - 1]; + else dp[houses[0]][1] = 0; + + for(int index = 1; index < m; index ++){ + + vector> tdp(n + 1, vector(m + 1, INF)); + + for(int color = 1; color <= n; color ++) + if(!houses[index] || houses[index] == color) + for(int precolor = 1; precolor <= n; precolor ++) + for(int k = 1; k <= target; k ++) + tdp[color][k] = min(tdp[color][k], + (houses[index] ? 0 : cost[index][color - 1]) + dp[precolor][k - (precolor != color)]); + dp = tdp; + } + + int res = INF; + for(int color = 1; color <= n; color ++) res = min(res, dp[color][target]); + return res == INF ? -1 : res; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1474-Delete-N-Nodes-After-M-Nodes-of-a-Linked-List/cpp-1474/CMakeLists.txt b/1001-1500/1474-Delete-N-Nodes-After-M-Nodes-of-a-Linked-List/cpp-1474/CMakeLists.txt new file mode 100644 index 00000000..853de288 --- /dev/null +++ b/1001-1500/1474-Delete-N-Nodes-After-M-Nodes-of-a-Linked-List/cpp-1474/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(cpp_1474) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1474 main2.cpp) \ No newline at end of file diff --git a/1001-1500/1474-Delete-N-Nodes-After-M-Nodes-of-a-Linked-List/cpp-1474/main.cpp b/1001-1500/1474-Delete-N-Nodes-After-M-Nodes-of-a-Linked-List/cpp-1474/main.cpp new file mode 100644 index 00000000..109cd7ea --- /dev/null +++ b/1001-1500/1474-Delete-N-Nodes-After-M-Nodes-of-a-Linked-List/cpp-1474/main.cpp @@ -0,0 +1,49 @@ +/// Source : https://leetcode.com/problems/delete-n-nodes-after-m-nodes-of-a-linked-list/ +/// Author : liuyubobobo +/// Time : 2020-06-24 + +#include + + +/// Recursion +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode() : val(0), next(nullptr) {} + ListNode(int x) : val(x), next(nullptr) {} + ListNode(int x, ListNode *next) : val(x), next(next) {} +}; + +class Solution { +public: + ListNode* deleteNodes(ListNode* head, int m, int n) { + + if(!head) return head; + + ListNode* prev = head; + for(int i = 1; i < m && prev; i ++) + prev = prev->next; + if(!prev) return head; + + ListNode* prev2 = prev->next; + for(int i = 1; i < n && prev2; i ++) + prev2 = prev2->next; + if(!prev2){ + prev->next = nullptr; + return head; + } + + prev->next = deleteNodes(prev2->next, m, n); + return head; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1474-Delete-N-Nodes-After-M-Nodes-of-a-Linked-List/cpp-1474/main2.cpp b/1001-1500/1474-Delete-N-Nodes-After-M-Nodes-of-a-Linked-List/cpp-1474/main2.cpp new file mode 100644 index 00000000..1b7c1247 --- /dev/null +++ b/1001-1500/1474-Delete-N-Nodes-After-M-Nodes-of-a-Linked-List/cpp-1474/main2.cpp @@ -0,0 +1,49 @@ +/// Source : https://leetcode.com/problems/delete-n-nodes-after-m-nodes-of-a-linked-list/ +/// Author : liuyubobobo +/// Time : 2020-06-24 + +#include + + +/// Non-Recursion +/// Time Complexity: O(n) +/// Space Complexity: O(1) + +/// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode() : val(0), next(nullptr) {} + ListNode(int x) : val(x), next(nullptr) {} + ListNode(int x, ListNode *next) : val(x), next(next) {} +}; + +class Solution { +public: + ListNode* deleteNodes(ListNode* head, int m, int n) { + + ListNode* prev = head; + while(prev){ + for(int i = 1; i < m && prev; i ++) + prev = prev->next; + if(!prev) break; + + ListNode* prev2 = prev->next; + for(int i = 1; i < n && prev2; i ++) + prev2 = prev2->next; + if(!prev2){ + prev->next = nullptr; + break; + } + prev->next = prev2->next; + prev = prev2->next; + } + return head; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1475-Final-Prices-With-a-Special-Discount-in-a-Shop/cpp-1475/CMakeLists.txt b/1001-1500/1475-Final-Prices-With-a-Special-Discount-in-a-Shop/cpp-1475/CMakeLists.txt new file mode 100644 index 00000000..094e05c3 --- /dev/null +++ b/1001-1500/1475-Final-Prices-With-a-Special-Discount-in-a-Shop/cpp-1475/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(cpp_1475) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1475 main2.cpp) \ No newline at end of file diff --git a/1001-1500/1475-Final-Prices-With-a-Special-Discount-in-a-Shop/cpp-1475/main.cpp b/1001-1500/1475-Final-Prices-With-a-Special-Discount-in-a-Shop/cpp-1475/main.cpp new file mode 100644 index 00000000..549a2637 --- /dev/null +++ b/1001-1500/1475-Final-Prices-With-a-Special-Discount-in-a-Shop/cpp-1475/main.cpp @@ -0,0 +1,38 @@ +/// Source : https://leetcode.com/problems/final-prices-with-a-special-discount-in-a-shop/ +/// Author : liuyubobobo +/// Time : 2020-06-13 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n^2) +/// Space Complexity: O(1) +class Solution { +public: + vector finalPrices(vector& prices) { + + int n = prices.size(); + + vector res(n, 0); + res[n - 1] = prices[n - 1]; + for(int i = n - 2; i >= 0; i --){ + res[i] = prices[i]; + for(int j = i + 1; j < n; j ++) + if(prices[j] <= prices[i]){ + res[i] -= prices[j]; + break; + } + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1475-Final-Prices-With-a-Special-Discount-in-a-Shop/cpp-1475/main2.cpp b/1001-1500/1475-Final-Prices-With-a-Special-Discount-in-a-Shop/cpp-1475/main2.cpp new file mode 100644 index 00000000..6e02e5d4 --- /dev/null +++ b/1001-1500/1475-Final-Prices-With-a-Special-Discount-in-a-Shop/cpp-1475/main2.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/final-prices-with-a-special-discount-in-a-shop/ +/// Author : liuyubobobo +/// Time : 2020-06-13 + +#include +#include +#include + +using namespace std; + + +/// Mono Stack +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector finalPrices(vector& prices) { + + int n = prices.size(); + + vector res(n); + stack stack; + for(int i = 0; i < n; i ++){ + while(!stack.empty() && prices[i] <= prices[stack.top()]) + res[stack.top()] = prices[stack.top()] - prices[i], stack.pop(); + stack.push(i); + } + while (!stack.empty()) res[stack.top()] = prices[stack.top()], stack.pop(); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1476-Subrectangle-Queries/cpp-1476/CMakeLists.txt b/1001-1500/1476-Subrectangle-Queries/cpp-1476/CMakeLists.txt new file mode 100644 index 00000000..eeef6d6c --- /dev/null +++ b/1001-1500/1476-Subrectangle-Queries/cpp-1476/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(cpp_1476) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1476 main2.cpp) \ No newline at end of file diff --git a/1001-1500/1476-Subrectangle-Queries/cpp-1476/main.cpp b/1001-1500/1476-Subrectangle-Queries/cpp-1476/main.cpp new file mode 100644 index 00000000..a44312c4 --- /dev/null +++ b/1001-1500/1476-Subrectangle-Queries/cpp-1476/main.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/subrectangle-queries/ +/// Author : liuyubobobo +/// Time : 2020-06-13 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: init: O(n^2) +/// update: (O(n^2)) +/// get: O(1) +/// Space Complexity: O(n^2) +class SubrectangleQueries { + +private: + vector> rec; + +public: + SubrectangleQueries(vector>& rectangle) : rec(rectangle) {} + + void updateSubrectangle(int row1, int col1, int row2, int col2, int newValue) { + + for(int i = row1; i <= row2; i ++) + for(int j = col1; j <= col2; j ++) + rec[i][j] = newValue; + } + + int getValue(int row, int col) { + return rec[row][col]; + } +}; + +/** + * Your SubrectangleQueries object will be instantiated and called as such: + * SubrectangleQueries* obj = new SubrectangleQueries(rectangle); + * obj->updateSubrectangle(row1,col1,row2,col2,newValue); + * int param_2 = obj->getValue(row,col); + */ + + +int main() { + + return 0; +} diff --git a/1001-1500/1476-Subrectangle-Queries/cpp-1476/main2.cpp b/1001-1500/1476-Subrectangle-Queries/cpp-1476/main2.cpp new file mode 100644 index 00000000..03237f84 --- /dev/null +++ b/1001-1500/1476-Subrectangle-Queries/cpp-1476/main2.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/subrectangle-queries/ +/// Author : liuyubobobo +/// Time : 2020-06-13 + +#include +#include + +using namespace std; + + +/// Using History +/// Time Complexity: init: O(n^2) +/// update: (O(1)) +/// get: O(k) +/// Space Complexity: O(n^2) +class SubrectangleQueries { + +private: + vector> rectangle; + vector> history; + +public: + SubrectangleQueries(vector>& rectangle) : rectangle(rectangle) {} + + void updateSubrectangle(int row1, int col1, int row2, int col2, int newValue) { + history.push_back({row1, col1, row2, col2, newValue}); + } + + int getValue(int row, int col) { + + for(int i = history.size() - 1; i >= 0; i --) + if(history[i][0] <= row && row <= history[i][2] && + history[i][1] <= col && col <= history[i][3]) + return history[i][4]; + return rectangle[row][col]; + } +}; + +/** + * Your SubrectangleQueries object will be instantiated and called as such: + * SubrectangleQueries* obj = new SubrectangleQueries(rectangle); + * obj->updateSubrectangle(row1,col1,row2,col2,newValue); + * int param_2 = obj->getValue(row,col); + */ + + +int main() { + + return 0; +} diff --git a/1001-1500/1477-Find-Two-Non-overlapping-Sub-arrays-Each-With-Target-Sum/cpp-1477/CMakeLists.txt b/1001-1500/1477-Find-Two-Non-overlapping-Sub-arrays-Each-With-Target-Sum/cpp-1477/CMakeLists.txt new file mode 100644 index 00000000..26412ea0 --- /dev/null +++ b/1001-1500/1477-Find-Two-Non-overlapping-Sub-arrays-Each-With-Target-Sum/cpp-1477/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(cpp_1477) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1477 main2.cpp) \ No newline at end of file diff --git a/1001-1500/1477-Find-Two-Non-overlapping-Sub-arrays-Each-With-Target-Sum/cpp-1477/main.cpp b/1001-1500/1477-Find-Two-Non-overlapping-Sub-arrays-Each-With-Target-Sum/cpp-1477/main.cpp new file mode 100644 index 00000000..f8c5dbb4 --- /dev/null +++ b/1001-1500/1477-Find-Two-Non-overlapping-Sub-arrays-Each-With-Target-Sum/cpp-1477/main.cpp @@ -0,0 +1,89 @@ +/// Source : https://leetcode.com/problems/maximum-students-taking-exam/ +/// Author : liuyubobobo +/// Time : 2020-06-13 + +#include +#include +#include + +using namespace std; + + +/// Sliding Windows to get intervals and postsum to get the final result +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { + +public: + int minSumOfLengths(vector& arr, int target) { + + vector> sub = get_subarrays(arr, target); +// for(const pair& p: sub) +// cout << "(" << p.first << "," << p.second << ")"; +// cout << endl; + + int n = sub.size(); + if(n <= 1) return -1; + + sort(sub.begin(), sub.end()); + vector dp(n); + dp[n - 1] = sub.back().second - sub.back().first + 1; + for(int i = n - 2; i >= 0; i --) + dp[i] = min(dp[i + 1], sub[i].second - sub[i].first + 1); + + int res = INT_MAX; + for(int i = 0; i < n; i ++){ + vector>::iterator iter = upper_bound(sub.begin(), sub.end(), make_pair(sub[i].second + 1, -1)); + if(iter != sub.end()) res = min(res, sub[i].second - sub[i].first + 1 + dp[iter - sub.begin()]); + } + return res == INT_MAX ? -1 : res; + } + +private: + vector> get_subarrays(const vector& arr, int t){ + + vector> res; + int l = 0, r = -1, sum = 0; + while(l < arr.size()){ + if(sum == t) res.push_back({l, r}); + + if(r + 1 < arr.size() && sum < t) sum += arr[++r]; + else sum -= arr[l ++]; + } + return res; + } +}; + + +int main() { + + vector arr1 = {3,2,2,4,3}; + cout << Solution().minSumOfLengths(arr1, 3) << endl; + // 2 + + vector arr2 = {7,3,4,7}; + cout << Solution().minSumOfLengths(arr2, 7) << endl; + // 2 + + vector arr3 = {4,3,2,6,2,3,4}; + cout << Solution().minSumOfLengths(arr3, 6) << endl; + // -1 + + vector arr4 = {5,5,4,4,5}; + cout << Solution().minSumOfLengths(arr4, 3) << endl; + // -1 + + vector arr5 = {1, 6, 1}; + cout << Solution().minSumOfLengths(arr5, 7) << endl; + // -1 + + vector arr6 = {1,2,2,3,2,6,7,2,1,4,8}; + cout << Solution().minSumOfLengths(arr6, 5) << endl; + // 4 + + vector arr7 = {64,5,20,9,1,39}; + cout << Solution().minSumOfLengths(arr7, 69) << endl; + // 6 + + return 0; +} diff --git a/1001-1500/1477-Find-Two-Non-overlapping-Sub-arrays-Each-With-Target-Sum/cpp-1477/main2.cpp b/1001-1500/1477-Find-Two-Non-overlapping-Sub-arrays-Each-With-Target-Sum/cpp-1477/main2.cpp new file mode 100644 index 00000000..8c684da5 --- /dev/null +++ b/1001-1500/1477-Find-Two-Non-overlapping-Sub-arrays-Each-With-Target-Sum/cpp-1477/main2.cpp @@ -0,0 +1,76 @@ +/// Source : https://leetcode.com/problems/maximum-students-taking-exam/ +/// Author : liuyubobobo +/// Time : 2020-06-13 + +#include +#include +#include + +using namespace std; + + +/// Presum + Dynamic Programming +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +public: + int minSumOfLengths(vector& arr, int target) { + + unordered_map presum; + presum[0] = 0; + + vector dp = {INT_MAX}; + int pre= 0, res = INT_MAX; + for(int i = 0; i < arr.size(); i ++){ + int sum = arr[i] + pre; + pre = sum; + presum[sum] = i + 1; + if(presum.count(sum - target)){ + int index = presum[sum - target]; + if(dp[index] != INT_MAX) res = min(res, i - index + 1 + dp[index]); + dp.push_back(min(dp.back(), i - index + 1)); + } + else dp.push_back(dp.back()); + } + return res == INT_MAX ? -1 : res; + } +}; + + +int main() { + + vector arr1 = {3,2,2,4,3}; + cout << Solution().minSumOfLengths(arr1, 3) << endl; + // 2 + + vector arr2 = {7,3,4,7}; + cout << Solution().minSumOfLengths(arr2, 7) << endl; + // 2 + + vector arr3 = {4,3,2,6,2,3,4}; + cout << Solution().minSumOfLengths(arr3, 6) << endl; + // -1 + + vector arr4 = {5,5,4,4,5}; + cout << Solution().minSumOfLengths(arr4, 3) << endl; + // -1 + + vector arr5 = {1, 6, 1}; + cout << Solution().minSumOfLengths(arr5, 7) << endl; + // -1 + + vector arr6 = {1,2,2,3,2,6,7,2,1,4,8}; + cout << Solution().minSumOfLengths(arr6, 5) << endl; + // 4 + + vector arr7 = {64,5,20,9,1,39}; + cout << Solution().minSumOfLengths(arr7, 69) << endl; + // 6 + + vector arr8 = {47,17,4,8,8,2,1,1,8,35,30,1,11,1,1,1,44,1,3,27,2,8}; + cout << Solution().minSumOfLengths(arr8, 88) << endl; + // 16 + + return 0; +} diff --git a/1001-1500/1478-Allocate-Mailboxes/cpp-1478/CMakeLists.txt b/1001-1500/1478-Allocate-Mailboxes/cpp-1478/CMakeLists.txt new file mode 100644 index 00000000..0b58f595 --- /dev/null +++ b/1001-1500/1478-Allocate-Mailboxes/cpp-1478/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(cpp_1478) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1478 main3.cpp) \ No newline at end of file diff --git a/1001-1500/1478-Allocate-Mailboxes/cpp-1478/main.cpp b/1001-1500/1478-Allocate-Mailboxes/cpp-1478/main.cpp new file mode 100644 index 00000000..9f34a1fd --- /dev/null +++ b/1001-1500/1478-Allocate-Mailboxes/cpp-1478/main.cpp @@ -0,0 +1,79 @@ +/// Source : https://leetcode.com/problems/allocate-mailboxes/ +/// Author : liuyubobobo +/// Time : 2020-06-13 + +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(k*n^2) +/// Space Complexity: O(k*n) +class Solution { + +private: + int n; + +public: + int minDistance(vector& houses, int k) { + + n = houses.size(); + sort(houses.begin(), houses.end()); + + vector> dis(n, vector(n)); + for(int i = 0; i < n; i ++) + for(int j = i; j < n; j ++) + dis[i][j] = getdis(houses, i, j); + + vector> dp(n, vector(k + 1, -1)); + return dfs(houses, 0, k, dis, dp); + } + +private: + int dfs(const vector& houses, int index, int left, + const vector>& dis, vector>& dp){ + + if(left == -1) return INT_MAX; + if(index == n) return left == 0 ? 0 : INT_MAX; + if(dp[index][left] != -1) return dp[index][left]; + + int res = INT_MAX; + for(int i = index; i < n; i ++){ + int tres = dfs(houses, i + 1, left - 1, dis, dp); + if(tres != INT_MAX) res = min(res, dis[index][i] + tres); + } + return dp[index][left] = res; + } + + int getdis(const vector& houses, int start, int end){ + + int mid = (start + end) / 2; + int res = 0; + for(int i = start; i <= end; i ++) res += abs(houses[i] - houses[mid]); + return res; + } +}; + + +int main() { + + vector houses1 = {1,4,8,10,20}; + cout << Solution().minDistance(houses1, 3) << endl; + // 5 + + vector houses2 = {2,3,5,12,18}; + cout << Solution().minDistance(houses2, 2) << endl; + // 9 + + vector houses3 = {7,4,6,1}; + cout << Solution().minDistance(houses3, 1) << endl; + // 8 + + vector houses4 = {3,6,14,10}; + cout << Solution().minDistance(houses4, 4) << endl; + // 0 + + return 0; +} diff --git a/1001-1500/1478-Allocate-Mailboxes/cpp-1478/main2.cpp b/1001-1500/1478-Allocate-Mailboxes/cpp-1478/main2.cpp new file mode 100644 index 00000000..9baa7a6e --- /dev/null +++ b/1001-1500/1478-Allocate-Mailboxes/cpp-1478/main2.cpp @@ -0,0 +1,73 @@ +/// Source : https://leetcode.com/problems/allocate-mailboxes/ +/// Author : liuyubobobo +/// Time : 2020-06-13 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(k*n^2) +/// Space Complexity: O(k*n) +class Solution { + +public: + int minDistance(vector& houses, int k) { + + int n = houses.size(); + sort(houses.begin(), houses.end()); + + vector> dis(n, vector(n)); + for(int i = 0; i < n; i ++) + for(int j = i; j < n; j ++) + dis[i][j] = getdis(houses, i, j); + + vector> dp(k + 1, vector(n, INT_MAX)); + for(int i = 0; i < n; i ++) + dp[1][i] = dis[0][i]; + + for(int cnt = 2; cnt <= k; cnt ++) + for(int end = cnt - 1; end < n; end ++) + for(int start = end; start >= cnt - 1; start --) + if(dp[cnt - 1][start - 1] != INT_MAX) + dp[cnt][end] = min(dp[cnt][end], dis[start][end] + dp[cnt - 1][start - 1]); + return dp[k][n - 1]; + } + +private: + int getdis(const vector& houses, int start, int end){ + + int mid = (start + end) / 2; + int res = 0; + for(int i = start; i <= end; i ++) res += abs(houses[i] - houses[mid]); + return res; + } +}; + + +int main() { + + vector houses1 = {1,4,8,10,20}; + cout << Solution().minDistance(houses1, 3) << endl; + // 5 + + vector houses2 = {2,3,5,12,18}; + cout << Solution().minDistance(houses2, 2) << endl; + // 9 + + vector houses3 = {7,4,6,1}; + cout << Solution().minDistance(houses3, 1) << endl; + // 8 + + vector houses4 = {3,6,14,10}; + cout << Solution().minDistance(houses4, 4) << endl; + // 0 + + vector houses5 = {1,4,8,10,20}; + cout << Solution().minDistance(houses5, 3) << endl; + // 5 + + return 0; +} diff --git a/1001-1500/1478-Allocate-Mailboxes/cpp-1478/main3.cpp b/1001-1500/1478-Allocate-Mailboxes/cpp-1478/main3.cpp new file mode 100644 index 00000000..17d54872 --- /dev/null +++ b/1001-1500/1478-Allocate-Mailboxes/cpp-1478/main3.cpp @@ -0,0 +1,76 @@ +/// Source : https://leetcode.com/problems/allocate-mailboxes/ +/// Author : liuyubobobo +/// Time : 2020-06-13 + +#include +#include + +using namespace std; + + +/// Dynamic Programming + Rolling Array +/// Time Complexity: O(k*n^2) +/// Space Complexity: O(n) +class Solution { + +public: + int minDistance(vector& houses, int k) { + + int n = houses.size(); + sort(houses.begin(), houses.end()); + + vector> dis(n, vector(n)); + for(int i = 0; i < n; i ++) + for(int j = i; j < n; j ++) + dis[i][j] = getdis(houses, i, j); + + vector dp(n); + for(int i = 0; i < n; i ++) + dp[i] = dis[0][i]; + + for(int cnt = 2; cnt <= k; cnt ++){ + vector tdp(n, INT_MAX); + for(int end = cnt - 1; end < n; end ++) + for(int start = end; start >= cnt - 1; start --) + if(dp[start - 1] != INT_MAX) + tdp[end] = min(tdp[end], dis[start][end] + dp[start - 1]); + dp = tdp; + } + return dp[n - 1]; + } + +private: + int getdis(const vector& houses, int start, int end){ + + int mid = (start + end) / 2; + int res = 0; + for(int i = start; i <= end; i ++) res += abs(houses[i] - houses[mid]); + return res; + } +}; + + +int main() { + + vector houses1 = {1,4,8,10,20}; + cout << Solution().minDistance(houses1, 3) << endl; + // 5 + + vector houses2 = {2,3,5,12,18}; + cout << Solution().minDistance(houses2, 2) << endl; + // 9 + + vector houses3 = {7,4,6,1}; + cout << Solution().minDistance(houses3, 1) << endl; + // 8 + + vector houses4 = {3,6,14,10}; + cout << Solution().minDistance(houses4, 4) << endl; + // 0 + + vector houses5 = {1,4,8,10,20}; + cout << Solution().minDistance(houses5, 3) << endl; + // 5 + + return 0; +} diff --git a/1001-1500/1480-Running-Sum-of-1d-Array/cpp-1480/CMakeLists.txt b/1001-1500/1480-Running-Sum-of-1d-Array/cpp-1480/CMakeLists.txt new file mode 100644 index 00000000..446d8265 --- /dev/null +++ b/1001-1500/1480-Running-Sum-of-1d-Array/cpp-1480/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main2.cpp) \ No newline at end of file diff --git a/1001-1500/1480-Running-Sum-of-1d-Array/cpp-1480/main.cpp b/1001-1500/1480-Running-Sum-of-1d-Array/cpp-1480/main.cpp new file mode 100644 index 00000000..169f5b19 --- /dev/null +++ b/1001-1500/1480-Running-Sum-of-1d-Array/cpp-1480/main.cpp @@ -0,0 +1,30 @@ +/// Source : https://leetcode.com/problems/running-sum-of-1d-array/ +/// Author : liuyubobobo +/// Time : 2020-06-13 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector runningSum(vector& nums) { + + vector res(nums.size()); + res[0] = nums[0]; + for(int i = 1; i < nums.size(); i ++) + res[i] = res[i - 1] + nums[i]; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1480-Running-Sum-of-1d-Array/cpp-1480/main2.cpp b/1001-1500/1480-Running-Sum-of-1d-Array/cpp-1480/main2.cpp new file mode 100644 index 00000000..36bb098d --- /dev/null +++ b/1001-1500/1480-Running-Sum-of-1d-Array/cpp-1480/main2.cpp @@ -0,0 +1,28 @@ +/// Source : https://leetcode.com/problems/running-sum-of-1d-array/ +/// Author : liuyubobobo +/// Time : 2020-06-13 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + vector runningSum(vector& nums) { + + for(int i = 1; i < nums.size(); i ++) + nums[i] += nums[i - 1]; + return nums; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1481-Least-Number-of-Unique-Integers-after-K-Removals/cpp-1481/CMakeLists.txt b/1001-1500/1481-Least-Number-of-Unique-Integers-after-K-Removals/cpp-1481/CMakeLists.txt new file mode 100644 index 00000000..545e47b8 --- /dev/null +++ b/1001-1500/1481-Least-Number-of-Unique-Integers-after-K-Removals/cpp-1481/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1001-1500/1481-Least-Number-of-Unique-Integers-after-K-Removals/cpp-1481/main.cpp b/1001-1500/1481-Least-Number-of-Unique-Integers-after-K-Removals/cpp-1481/main.cpp new file mode 100644 index 00000000..7afe7bf8 --- /dev/null +++ b/1001-1500/1481-Least-Number-of-Unique-Integers-after-K-Removals/cpp-1481/main.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/least-number-of-unique-integers-after-k-removals/ +/// Author : liuyubobobo +/// Time : 2020-06-13 + +#include +#include +#include + +using namespace std; + + +/// Using HashMap + Sorting and greedy +/// Time Complexity: O(nlogn) +/// Space Complexity: O(nlogn) +class Solution { +public: + int findLeastNumOfUniqueInts(vector& arr, int k) { + + unordered_map freq; + for(int e: arr) freq[e] ++; + + vector v; + for(const pair& p: freq) v.push_back(p.second); + sort(v.begin(), v.end(), greater()); + + while(v.size() && k >= v.back()) + k -= v.back(), v.pop_back(); + return v.size(); + } +}; + +int main() { + std::cout << "Hello, World!" << std::endl; + return 0; +} diff --git a/1001-1500/1482-Minimum-Number-of-Days-to-Make-m-Bouquets/cpp-1482/CMakeLists.txt b/1001-1500/1482-Minimum-Number-of-Days-to-Make-m-Bouquets/cpp-1482/CMakeLists.txt new file mode 100644 index 00000000..94acd016 --- /dev/null +++ b/1001-1500/1482-Minimum-Number-of-Days-to-Make-m-Bouquets/cpp-1482/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1001-1500/1482-Minimum-Number-of-Days-to-Make-m-Bouquets/cpp-1482/main.cpp b/1001-1500/1482-Minimum-Number-of-Days-to-Make-m-Bouquets/cpp-1482/main.cpp new file mode 100644 index 00000000..a80f1479 --- /dev/null +++ b/1001-1500/1482-Minimum-Number-of-Days-to-Make-m-Bouquets/cpp-1482/main.cpp @@ -0,0 +1,81 @@ +/// Source : https://leetcode.com/problems/minimum-number-of-days-to-make-m-bouquets/ +/// Author : liuyubobobo +/// Time : 2020-06-13 + +#include +#include +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(nlog(max_days)) +/// Space Complexity: O(1) +class Solution { + +public: + int minDays(vector& bloomDay, int m, int k) { + + if(m * k > bloomDay.size()) return -1; + + int maxday = *max_element(bloomDay.begin(), bloomDay.end()); + if(m * k == bloomDay.size()) + return maxday; + + int l = 1, r = maxday; + while(l < r){ + int mid = (l + r) / 2; + if(flowers(bloomDay, k, mid) >= m) r = mid; + else l = mid + 1; + } + return l >= m ? l : -1; + } + +private: + int flowers(const vector& days, int k, int d){ + + int res = 0; + int i = 0; + while(i < days.size()){ + int j; + for(j = i; j < i + k && j < days.size(); j ++) + if(days[j] > d) break; + + if(j == i + k) res ++, i += k; + else i = j + 1; + } + return res; + } +}; + + +int main() { + + vector days0 = {1,10,2}; + cout << Solution().minDays(days0, 2, 1) << endl; + // 2 + + vector days1 = {1,10,3,10,2}; + cout << Solution().minDays(days1, 3, 1) << endl; + // 3 + + vector days2 = {1,10,3,10,2}; + cout << Solution().minDays(days1, 3, 2) << endl; + // -1 + + vector days3 = {7,7,7,7,12,7,7}; + cout << Solution().minDays(days3, 2, 3) << endl; + // 12 + + vector days4 = {1000000000,1000000000}; + cout << Solution().minDays(days4, 1, 1) << endl; + // 1000000000 + + vector days5 = {1,10,2,9,3,8,4,7,5,6}; + cout << Solution().minDays(days5, 4, 2) << endl; + // 9 + + return 0; +} diff --git a/1001-1500/1483-Kth-Ancestor-of-a-Tree-Node/cpp-1483/CMakeLists.txt b/1001-1500/1483-Kth-Ancestor-of-a-Tree-Node/cpp-1483/CMakeLists.txt new file mode 100644 index 00000000..b07a4ffa --- /dev/null +++ b/1001-1500/1483-Kth-Ancestor-of-a-Tree-Node/cpp-1483/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) \ No newline at end of file diff --git a/1001-1500/1483-Kth-Ancestor-of-a-Tree-Node/cpp-1483/main.cpp b/1001-1500/1483-Kth-Ancestor-of-a-Tree-Node/cpp-1483/main.cpp new file mode 100644 index 00000000..66784c1c --- /dev/null +++ b/1001-1500/1483-Kth-Ancestor-of-a-Tree-Node/cpp-1483/main.cpp @@ -0,0 +1,85 @@ +/// Source : https://leetcode.com/problems/kth-ancestor-of-a-tree-node/ +/// Author : liuyubobobo +/// Time : 2020-06-13 + +#include +#include +#include + +using namespace std; + + +/// Binary Lifting +/// Time Complexity: O(nlogn) +/// Space Complexity: O(logk) +class TreeAncestor { + +private: + vector> dp; + +public: + TreeAncestor(int n, vector& parent) : dp(n) { + + for(int i = 0; i < n; i ++) + dp[i].push_back(parent[i]); + + for(int j = 1; ; j ++){ + bool allminus = true; + for(int i = 0; i < n; i ++){ + int t = dp[i][j - 1] != -1 ? dp[dp[i][j - 1]][j - 1] : -1; + dp[i].push_back(t); + if(t != -1) allminus = false; + } + if(allminus) break; + } + } + + // 递归写法 +// int getKthAncestor(int node, int k) { +// +// if(k == 0 || node == -1) return node; +// +// int pos = ffs(k) - 1; // C++ 语言中 ffs(k) 求解出 k 的最右侧第一个 1 的位置(1-based) +// +// return pos < dp[node].size() ? getKthAncestor(dp[node][pos], k - (1 << pos)) : -1; +// } + + // 非递归写法 + int getKthAncestor(int node, int k) { + + int res = node, pos = 0; + while(k && res != -1){ + if(pos >= dp[res].size()) return -1; + if(k & 1) res = dp[res][pos]; + k >>= 1, pos ++; + } + return res; + } +}; + + +int main() { + + vector tree1 = {-1, 0, 0, 1, 1, 2, 2}; + TreeAncestor o1(7, tree1); + cout << o1.getKthAncestor(3, 1) << endl; // 1 + cout << o1.getKthAncestor(5, 2) << endl; // 0 + cout << o1.getKthAncestor(6, 3) << endl; // -1 + + cout << endl; + + vector tree2 = {-1, 0, 0, 1, 2, 0, 1, 3, 6, 1}; + TreeAncestor o2(10, tree2); + cout << o2.getKthAncestor(8, 6) << endl; // -1 + cout << o2.getKthAncestor(9, 7) << endl; // -1 + cout << o2.getKthAncestor(1, 1) << endl; // 0 + cout << o2.getKthAncestor(2, 5) << endl; // -1 + cout << o2.getKthAncestor(4, 2) << endl; // 0 + cout << o2.getKthAncestor(7, 3) << endl; // 0 + cout << o2.getKthAncestor(3, 7) << endl; // -1 + cout << o2.getKthAncestor(9, 6) << endl; // -1 + cout << o2.getKthAncestor(3, 5) << endl; // -1 + cout << o2.getKthAncestor(8, 8) << endl; // -1 + + return 0; +} diff --git a/1001-1500/1485-Clone-Binary-Tree-With-Random-Pointer/cpp-1485/CMakeLists.txt b/1001-1500/1485-Clone-Binary-Tree-With-Random-Pointer/cpp-1485/CMakeLists.txt new file mode 100644 index 00000000..9c612bdf --- /dev/null +++ b/1001-1500/1485-Clone-Binary-Tree-With-Random-Pointer/cpp-1485/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(cpp_1485) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1485 main2.cpp) \ No newline at end of file diff --git a/1001-1500/1485-Clone-Binary-Tree-With-Random-Pointer/cpp-1485/main.cpp b/1001-1500/1485-Clone-Binary-Tree-With-Random-Pointer/cpp-1485/main.cpp new file mode 100644 index 00000000..940dd936 --- /dev/null +++ b/1001-1500/1485-Clone-Binary-Tree-With-Random-Pointer/cpp-1485/main.cpp @@ -0,0 +1,72 @@ +/// Source : https://leetcode.com/problems/clone-binary-tree-with-random-pointer/ +/// Author : liuyubobobo +/// Time : 2020-06-24 + +#include +#include + +using namespace std; + + +/// Two Pass, Using HashMap and DFS +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// Definition for a Node. +struct Node { + int val; + Node *left; + Node *right; + Node *random; + Node() : val(0), left(nullptr), right(nullptr), random(nullptr) {} + Node(int x) : val(x), left(nullptr), right(nullptr), random(nullptr) {} + Node(int x, Node *left, Node *right, Node *random) : val(x), left(left), right(right), random(random) {} +}; + +struct NodeCopy { + int val; + NodeCopy *left; + NodeCopy *right; + NodeCopy *random; + NodeCopy() : val(0), left(nullptr), right(nullptr), random(nullptr) {} + NodeCopy(int x) : val(x), left(nullptr), right(nullptr), random(nullptr) {} + NodeCopy(int x, NodeCopy *left, NodeCopy *right, NodeCopy *random) : val(x), left(left), right(right), random(random) {} +}; + + +class Solution { + +private: + unordered_map map; + +public: + NodeCopy* copyRandomBinaryTree(Node* root) { + + NodeCopy* ret = dfs(root); + set_rand_pointer(root, ret); + return ret; + } + +private: + void set_rand_pointer(Node* node, NodeCopy* nodecopy){ + + if(!node) return; + nodecopy->random = map[node->random]; + set_rand_pointer(node->left, nodecopy->left); + set_rand_pointer(node->right, nodecopy->right); + } + + NodeCopy* dfs(Node* node){ + + if(!node) return nullptr; + NodeCopy* ret = new NodeCopy(node->val, dfs(node->left), dfs(node->right), nullptr); + map[node] = ret; + return ret; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1485-Clone-Binary-Tree-With-Random-Pointer/cpp-1485/main2.cpp b/1001-1500/1485-Clone-Binary-Tree-With-Random-Pointer/cpp-1485/main2.cpp new file mode 100644 index 00000000..05d1256c --- /dev/null +++ b/1001-1500/1485-Clone-Binary-Tree-With-Random-Pointer/cpp-1485/main2.cpp @@ -0,0 +1,67 @@ +/// Source : https://leetcode.com/problems/clone-binary-tree-with-random-pointer/ +/// Author : liuyubobobo +/// Time : 2020-06-24 + +#include +#include + +using namespace std; + + +/// One Pass, Using HashMap and DFS +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// Definition for a Node. +struct Node { + int val; + Node *left; + Node *right; + Node *random; + Node() : val(0), left(nullptr), right(nullptr), random(nullptr) {} + Node(int x) : val(x), left(nullptr), right(nullptr), random(nullptr) {} + Node(int x, Node *left, Node *right, Node *random) : val(x), left(left), right(right), random(random) {} +}; + +struct NodeCopy { + int val; + NodeCopy *left; + NodeCopy *right; + NodeCopy *random; + NodeCopy() : val(0), left(nullptr), right(nullptr), random(nullptr) {} + NodeCopy(int x) : val(x), left(nullptr), right(nullptr), random(nullptr) {} + NodeCopy(int x, NodeCopy *left, NodeCopy *right, NodeCopy *random) : val(x), left(left), right(right), random(random) {} +}; + + +class Solution { + +private: + unordered_map map; + +public: + NodeCopy* copyRandomBinaryTree(Node* root) { + return dfs(root); + } + +private: + NodeCopy* dfs(Node* node){ + + if(!node) return nullptr; + if(map.count(node)) return map[node]; + + NodeCopy* ret = new NodeCopy(node->val); + map[node] = ret; + + ret->left = dfs(node->left); + ret->right = dfs(node->right); + ret->random = dfs(node->random); + return ret; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1486-XOR-Operation-in-an-Array/cpp-1486/CMakeLists.txt b/1001-1500/1486-XOR-Operation-in-an-Array/cpp-1486/CMakeLists.txt new file mode 100644 index 00000000..446d8265 --- /dev/null +++ b/1001-1500/1486-XOR-Operation-in-an-Array/cpp-1486/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main2.cpp) \ No newline at end of file diff --git a/1001-1500/1486-XOR-Operation-in-an-Array/cpp-1486/main.cpp b/1001-1500/1486-XOR-Operation-in-an-Array/cpp-1486/main.cpp new file mode 100644 index 00000000..74c31d65 --- /dev/null +++ b/1001-1500/1486-XOR-Operation-in-an-Array/cpp-1486/main.cpp @@ -0,0 +1,31 @@ +/// Source : https://leetcode.com/problems/xor-operation-in-an-array/ +/// Author : liuyubobobo +/// Time : 2020-06-20 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int xorOperation(int n, int start) { + + int res = 0; + for(int i = 0; i < n; i ++) + res ^= start + 2 * i; + return res; + } +}; + + +int main() { + + cout << Solution().xorOperation(3, 2) << endl; + + return 0; +} diff --git a/1001-1500/1486-XOR-Operation-in-an-Array/cpp-1486/main2.cpp b/1001-1500/1486-XOR-Operation-in-an-Array/cpp-1486/main2.cpp new file mode 100644 index 00000000..0947dfbc --- /dev/null +++ b/1001-1500/1486-XOR-Operation-in-an-Array/cpp-1486/main2.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/xor-operation-in-an-array/ +/// Author : liuyubobobo +/// Time : 2020-06-24 + +#include +#include + +using namespace std; + + +/// Mathematics +/// Time Complexity: O(1) +/// Space Complexity: O(1) +class Solution { +public: + int xorOperation(int n, int start) { + return 2 * f(n, start / 2) + ((start % 2 == 0 || n % 2 == 0) ? 0 : 1); + } + +private: + int f(int n, int start){ + if(start % 2 == 0) + return n % 2 ? ((n / 2) & 1) ^ (start + n - 1) : ((n / 2) & 1); + return f(n + 1, start - 1) ^ (start - 1); + } +}; + + +int main() { + + cout << Solution().xorOperation(3, 2) << endl; + + return 0; +} diff --git a/1001-1500/1487-Making-File-Names-Unique/cpp-1487/CMakeLists.txt b/1001-1500/1487-Making-File-Names-Unique/cpp-1487/CMakeLists.txt new file mode 100644 index 00000000..545e47b8 --- /dev/null +++ b/1001-1500/1487-Making-File-Names-Unique/cpp-1487/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1001-1500/1487-Making-File-Names-Unique/cpp-1487/main.cpp b/1001-1500/1487-Making-File-Names-Unique/cpp-1487/main.cpp new file mode 100644 index 00000000..7be0451f --- /dev/null +++ b/1001-1500/1487-Making-File-Names-Unique/cpp-1487/main.cpp @@ -0,0 +1,70 @@ +/// Source : https://leetcode.com/problems/making-file-names-unique/ +/// Author : liuyubobobo +/// Time : 2020-06-20 + +#include +#include +#include + +using namespace std; + + +/// Using HashMap +/// Time Complexity: O(n?) +/// Space Complexity: O(n) +class Solution { +public: + vector getFolderNames(vector& names) { + + unordered_map table; + vector res(names.size()); + string e, t; + for(int k = 0; k < names.size(); k ++){ + e = names[k]; + if(table.count(e)){ + for(int i = table[e]; ; i ++){ + t = e + "(" + to_string(i) + ")"; + if(!table.count(t)) break; + else table[e] ++; + } + table[t] ++; + res[k] = t; + } + else { + table[e] ++; + res[k] = e; + } + } + return res; + } +}; + + +void print_vec(const vector& v){ + for(const string& e: v) cout << e << " "; cout << endl; +} + +int main() { + + vector names1 = {"pes","fifa","gta","pes(2019)"}; + print_vec(Solution().getFolderNames(names1)); + // "pes","fifa","gta","pes(2019)" + + vector names2 = {"gta","gta(1)","gta","avalon"}; + print_vec(Solution().getFolderNames(names2)); + // "gta","gta(1)","gta(2)","avalon" + + vector names3 = {"onepiece","onepiece(1)","onepiece(2)","onepiece(3)","onepiece"}; + print_vec(Solution().getFolderNames(names3)); + // "onepiece","onepiece(1)","onepiece(2)","onepiece(3)","onepiece(4)" + + vector names4 = {"wano","wano","wano","wano"}; + print_vec(Solution().getFolderNames(names4)); + // "wano","wano(1)","wano(2)","wano(3)" + + vector names5 = {"kaido","kaido(1)","kaido","kaido(1)"}; + print_vec(Solution().getFolderNames(names5)); + // "kaido","kaido(1)","kaido(2)","kaido(1)(1)" + + return 0; +} \ No newline at end of file diff --git a/1001-1500/1488-Avoid-Flood-in-The-City/cpp-1488/CMakeLists.txt b/1001-1500/1488-Avoid-Flood-in-The-City/cpp-1488/CMakeLists.txt new file mode 100644 index 00000000..94acd016 --- /dev/null +++ b/1001-1500/1488-Avoid-Flood-in-The-City/cpp-1488/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1001-1500/1488-Avoid-Flood-in-The-City/cpp-1488/main.cpp b/1001-1500/1488-Avoid-Flood-in-The-City/cpp-1488/main.cpp new file mode 100644 index 00000000..e2879849 --- /dev/null +++ b/1001-1500/1488-Avoid-Flood-in-The-City/cpp-1488/main.cpp @@ -0,0 +1,81 @@ +/// Source : https://leetcode.com/problems/avoid-flood-in-the-city/ +/// Author : liuyubobobo +/// Time : 2020-06-20 + +#include +#include +#include +#include + +using namespace std; + + +/// Using HashMap for full lake and TreeSet for empty indice +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + vector avoidFlood(vector& rains) { + + vector res(rains.size(), INT_MIN); + unordered_map full; + set empty_index; + for(int i = 0; i < rains.size(); i ++){ + if(rains[i] > 0){ + int index = rains[i]; + if(full.count(index)){ + if(empty_index.empty()) return {}; + + int t = full[index]; + set::iterator iter = empty_index.lower_bound(t); + if(iter == empty_index.end()) return {}; + + res[*iter] = index; + empty_index.erase(iter); + } + res[i] = -1; + full[index] = i; + } + else empty_index.insert(i); + } + + for(int& e: res) if(e == INT_MIN) e = 1; + return res; + } +}; + + +void print_vec(const vector& v){ + if(!v.size()) cout << "{}"; + else for(int e: v) cout << e << " "; + cout << endl; +} + +int main() { + + vector rains1 = {1,2,3,4}; + print_vec(Solution().avoidFlood(rains1)); + // -1 -1 -1 -1 + + vector rains2 = {1,2,0,0,2,1}; + print_vec(Solution().avoidFlood(rains2)); + // -1,-1,2,1,-1,-1 + + vector rains3 = {1,2,0,1,2}; + print_vec(Solution().avoidFlood(rains3)); + // {} + + vector rains4 = {69,0,0,0,69}; + print_vec(Solution().avoidFlood(rains4)); + // -1,69,1,1,-1 + + vector rains5 = {10,20,20}; + print_vec(Solution().avoidFlood(rains5)); + // {} + + vector rains6 = {0,1,1}; + print_vec(Solution().avoidFlood(rains6)); + // {} + + return 0; +} diff --git a/1001-1500/1489-Find-Critical-and-Pseudo-Critical-Edges-in-Minimum-Spanning-Tree/cpp-1489/CMakeLists.txt b/1001-1500/1489-Find-Critical-and-Pseudo-Critical-Edges-in-Minimum-Spanning-Tree/cpp-1489/CMakeLists.txt new file mode 100644 index 00000000..b07a4ffa --- /dev/null +++ b/1001-1500/1489-Find-Critical-and-Pseudo-Critical-Edges-in-Minimum-Spanning-Tree/cpp-1489/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) \ No newline at end of file diff --git a/1001-1500/1489-Find-Critical-and-Pseudo-Critical-Edges-in-Minimum-Spanning-Tree/cpp-1489/main.cpp b/1001-1500/1489-Find-Critical-and-Pseudo-Critical-Edges-in-Minimum-Spanning-Tree/cpp-1489/main.cpp new file mode 100644 index 00000000..a75831b1 --- /dev/null +++ b/1001-1500/1489-Find-Critical-and-Pseudo-Critical-Edges-in-Minimum-Spanning-Tree/cpp-1489/main.cpp @@ -0,0 +1,97 @@ +/// Source : https://leetcode.com/problems/find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/ +/// Author : liuyubobobo +/// Time : 2020-06-20 + +#include +#include +#include + +using namespace std; + + +/// MST +/// Time Complexity: O(E * ElogE) +/// Space Complexity: O(E) +class UF{ + +private: + vector parent; + +public: + UF(int n){ + for(int i = 0 ; i < n ; i ++) + parent.push_back(i); + } + + int find(int p){ + if( p != parent[p] ) + parent[p] = find( parent[p] ); + return parent[p]; + } + + bool isConnected(int p , int q){ + return find(p) == find(q); + } + + void unionElements(int p, int q){ + + int pRoot = find(p); + int qRoot = find(q); + + if( pRoot == qRoot ) + return; + + parent[pRoot] = qRoot; + } +}; + +class Solution { +public: + vector> findCriticalAndPseudoCriticalEdges(int n, vector>& edges) { + + unordered_map index_map; + for(int i = 0; i < edges.size(); i ++) + index_map[edges[i][0] * n + edges[i][1]] = i; + + sort(edges.begin(), edges.end(), [](const vector& e1, const vector& e2){ + return e1[2] < e2[2]; + }); + + vector> res(2); + int minW = minimum_tree(edges, n, -1, -1); + for(int i = 0; i < edges.size(); i ++){ + int index = index_map[edges[i][0] * n + edges[i][1]]; + if(minimum_tree(edges, n, i, -1) > minW) + res[0].push_back(index); + else if(minimum_tree(edges, n, -1, i) == minW) + res[1].push_back(index); + } + return res; + } + +private: + int minimum_tree(const vector>& edges, int n, int del_index, int use_index){ + + UF uf(n); + int res = 0, e_num = 0; + + if(use_index != -1) + uf.unionElements(edges[use_index][0], edges[use_index][1]), + e_num ++, + res += edges[use_index][2]; + + for(int i = 0; i < edges.size(); i ++) + if(i != del_index && !uf.isConnected(edges[i][0], edges[i][1])) + uf.unionElements(edges[i][0], edges[i][1]), + e_num ++, + res += edges[i][2]; + + return e_num == n - 1 ? res : INT_MAX; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1490-Clone-N-ary-Tree/cpp-1490/CMakeLists.txt b/1001-1500/1490-Clone-N-ary-Tree/cpp-1490/CMakeLists.txt new file mode 100644 index 00000000..a31eb27e --- /dev/null +++ b/1001-1500/1490-Clone-N-ary-Tree/cpp-1490/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(cpp_1490) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1490 main.cpp) \ No newline at end of file diff --git a/1001-1500/1490-Clone-N-ary-Tree/cpp-1490/main.cpp b/1001-1500/1490-Clone-N-ary-Tree/cpp-1490/main.cpp new file mode 100644 index 00000000..b1c784e8 --- /dev/null +++ b/1001-1500/1490-Clone-N-ary-Tree/cpp-1490/main.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/clone-n-ary-tree/ +/// Author : liuyubobobo +/// Time : 2020-06-24 + +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(h) + +/// Definition for a Node. +class Node { +public: + int val; + vector children; + + Node() {} + + Node(int _val) { + val = _val; + } + + Node(int _val, vector _children) { + val = _val; + children = _children; + } +}; + +class Solution { +public: + Node* cloneTree(Node* root) { + + if(!root) return root; + + Node* ret = new Node(root->val); + for(Node* node: root->children) + ret->children.push_back(cloneTree(node)); + return ret; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1491-Average-Salary-Excluding-the-Minimum-and-Maximum-Salary/cpp-1491/CMakeLists.txt b/1001-1500/1491-Average-Salary-Excluding-the-Minimum-and-Maximum-Salary/cpp-1491/CMakeLists.txt new file mode 100644 index 00000000..eee6afb8 --- /dev/null +++ b/1001-1500/1491-Average-Salary-Excluding-the-Minimum-and-Maximum-Salary/cpp-1491/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(cpp_1491) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1491 main2.cpp) \ No newline at end of file diff --git a/1001-1500/1491-Average-Salary-Excluding-the-Minimum-and-Maximum-Salary/cpp-1491/main.cpp b/1001-1500/1491-Average-Salary-Excluding-the-Minimum-and-Maximum-Salary/cpp-1491/main.cpp new file mode 100644 index 00000000..71429d6b --- /dev/null +++ b/1001-1500/1491-Average-Salary-Excluding-the-Minimum-and-Maximum-Salary/cpp-1491/main.cpp @@ -0,0 +1,28 @@ +/// Source : https://leetcode.com/problems/average-salary-excluding-the-minimum-and-maximum-salary/submissions/ +/// Author : liuyubobobo +/// Time : 2020-06-27 + +#include +#include +#include + +using namespace std; + + +/// Sorting +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + double average(vector& salary) { + + sort(salary.begin(), salary.end()); + return (double)accumulate(salary.begin() + 1, salary.end() - 1, 0) / (salary.size() - 2); + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1491-Average-Salary-Excluding-the-Minimum-and-Maximum-Salary/cpp-1491/main2.cpp b/1001-1500/1491-Average-Salary-Excluding-the-Minimum-and-Maximum-Salary/cpp-1491/main2.cpp new file mode 100644 index 00000000..d09bf281 --- /dev/null +++ b/1001-1500/1491-Average-Salary-Excluding-the-Minimum-and-Maximum-Salary/cpp-1491/main2.cpp @@ -0,0 +1,31 @@ +/// Source : https://leetcode.com/problems/average-salary-excluding-the-minimum-and-maximum-salary/submissions/ +/// Author : liuyubobobo +/// Time : 2020-06-27 + +#include +#include +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + double average(vector& salary) { + + int minv = *min_element(salary.begin(), salary.end()); + int maxv = *max_element(salary.begin(), salary.end()); + + double sum = accumulate(salary.begin(), salary.end(), 0) - minv - maxv; + return sum / (salary.size() - 2); + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1492-The-kth-Factor-of-n/cpp-1492/CMakeLists.txt b/1001-1500/1492-The-kth-Factor-of-n/cpp-1492/CMakeLists.txt new file mode 100644 index 00000000..07e4107c --- /dev/null +++ b/1001-1500/1492-The-kth-Factor-of-n/cpp-1492/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(cpp_1492) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1492 main4.cpp) \ No newline at end of file diff --git a/1001-1500/1492-The-kth-Factor-of-n/cpp-1492/main.cpp b/1001-1500/1492-The-kth-Factor-of-n/cpp-1492/main.cpp new file mode 100644 index 00000000..b841caa3 --- /dev/null +++ b/1001-1500/1492-The-kth-Factor-of-n/cpp-1492/main.cpp @@ -0,0 +1,29 @@ +/// Source : https://leetcode.com/problems/the-kth-factor-of-n/ +/// Author : liuyubobobo +/// Time : 2020-06-27 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int kthFactor(int n, int k) { + + vector factors; + for(int i = 1; i <= n; i ++) + if(n % i == 0) factors.push_back(i); + return k - 1 < factors.size() ? factors[k - 1] : -1; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1492-The-kth-Factor-of-n/cpp-1492/main2.cpp b/1001-1500/1492-The-kth-Factor-of-n/cpp-1492/main2.cpp new file mode 100644 index 00000000..053a7915 --- /dev/null +++ b/1001-1500/1492-The-kth-Factor-of-n/cpp-1492/main2.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/the-kth-factor-of-n/ +/// Author : liuyubobobo +/// Time : 2020-06-27 + +#include +#include + +using namespace std; + + +/// Just calculate all the factors once +/// Time Complexity: O(sqrt(n)) +/// Space Complexity: O(n) +class Solution { +public: + int kthFactor(int n, int k) { + + vector factors; + for(int i = 1; i * i <= n; i ++) // 使用 i * i <= n,避免 sqrt(n) 运算的性能和精度问题 + if(n % i == 0){ + factors.push_back(i); + + // 对于 i * i == n 的情况要进行以下判断, + // 如果 i * i == n,则 i 和 n / i 是一个数字,不能重复添加进 factors + if(i * i != n) + factors.push_back(n / i); + } + sort(factors.begin(), factors.end()); + return k - 1 < factors.size() ? factors[k - 1] : -1; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1492-The-kth-Factor-of-n/cpp-1492/main3.cpp b/1001-1500/1492-The-kth-Factor-of-n/cpp-1492/main3.cpp new file mode 100644 index 00000000..1cd9cead --- /dev/null +++ b/1001-1500/1492-The-kth-Factor-of-n/cpp-1492/main3.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/the-kth-factor-of-n/ +/// Author : liuyubobobo +/// Time : 2020-06-27 + +#include +#include + +using namespace std; + + +/// Just calculate all the factors once +/// Time Complexity: O(sqrt(n)) +/// Space Complexity: O(n) +class Solution { +public: + int kthFactor(int n, int k) { + + vector factors; + for(int i = 1; i * i <= n; i ++) + if(n % i == 0){ + k --; + if(!k) return i; + if(i * i != n) factors.push_back(n / i); + } + return k - 1 < factors.size() ? factors[factors.size() - k] : -1; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1492-The-kth-Factor-of-n/cpp-1492/main4.cpp b/1001-1500/1492-The-kth-Factor-of-n/cpp-1492/main4.cpp new file mode 100644 index 00000000..97a3435e --- /dev/null +++ b/1001-1500/1492-The-kth-Factor-of-n/cpp-1492/main4.cpp @@ -0,0 +1,42 @@ +/// Source : https://leetcode.com/problems/the-kth-factor-of-n/ +/// Author : liuyubobobo +/// Time : 2020-06-27 + +#include +#include + +using namespace std; + + +/// Just calculate all the factors once +/// Time Complexity: O(sqrt(n)) +/// Space Complexity: O(1) +class Solution { +public: + int kthFactor(int n, int k) { + + int i; + for(i = 1; i * i <= n; i ++) + if(n % i == 0){ + k --; + if(!k) return i; + } + + i--; + for(i = (i * i == n ? i - 1 : i); i > 0; i --) + if(n % i == 0){ + k --; + if(!k) return n / i; + } + + return -1; + } +}; + + +int main() { + + cout << Solution().kthFactor(4, 4) << endl; + + return 0; +} diff --git a/1001-1500/1493-Longest-Subarray-of-1s-After-Deleting-One-Element/cpp-1493/CMakeLists.txt b/1001-1500/1493-Longest-Subarray-of-1s-After-Deleting-One-Element/cpp-1493/CMakeLists.txt new file mode 100644 index 00000000..caa411c4 --- /dev/null +++ b/1001-1500/1493-Longest-Subarray-of-1s-After-Deleting-One-Element/cpp-1493/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(cpp_1493) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1493 main2.cpp) \ No newline at end of file diff --git a/1001-1500/1493-Longest-Subarray-of-1s-After-Deleting-One-Element/cpp-1493/main.cpp b/1001-1500/1493-Longest-Subarray-of-1s-After-Deleting-One-Element/cpp-1493/main.cpp new file mode 100644 index 00000000..f7e11163 --- /dev/null +++ b/1001-1500/1493-Longest-Subarray-of-1s-After-Deleting-One-Element/cpp-1493/main.cpp @@ -0,0 +1,43 @@ +/// Source : https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element/ +/// Author : liuyubobobo +/// Time : 2020-06-27 + +#include +#include + +using namespace std; + + +/// Split +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int longestSubarray(vector& nums) { + + vector> ones; + int start = -1, res = 0; + for(int i = 0; i <= nums.size(); i ++) + if(i < nums.size() && nums[i]) + start = start == -1 ? i : start; + else if(start != -1){ + res = max(res, i - start); + ones.push_back({start, i}); + start = -1; + } + + if(ones.size() == 0) return 0; + if(ones.size() == 1 && ones[0].second - ones[0].first == nums.size()) return nums.size() - 1; + + for(int i = 1; i < ones.size(); i ++) + if(ones[i - 1].second + 1 == ones[i].first) + res = max(res, ones[i - 1].second - ones[i - 1].first + ones[i].second - ones[i].first); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1493-Longest-Subarray-of-1s-After-Deleting-One-Element/cpp-1493/main2.cpp b/1001-1500/1493-Longest-Subarray-of-1s-After-Deleting-One-Element/cpp-1493/main2.cpp new file mode 100644 index 00000000..38891729 --- /dev/null +++ b/1001-1500/1493-Longest-Subarray-of-1s-After-Deleting-One-Element/cpp-1493/main2.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element/ +/// Author : liuyubobobo +/// Time : 2020-06-27 + +#include +#include + +using namespace std; + + +/// Sliding Window +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int longestSubarray(vector& nums) { + + int res = 0, l = 0, r = -1, k = 0; + while(l < nums.size()){ + if(k == 2 || r + 1 == nums.size()){ + k -= !nums[l ++]; + } + else{ + if(r + 1 < nums.size()) + k += !nums[++r]; + res = max(res, r - l + 1 - k); + } + } + return res == nums.size() ? res - 1 : res; + } +}; + + +int main() { + + return 0; +} diff --git a/1001-1500/1494-Parallel-Courses-II/cpp-1494/CMakeLists.txt b/1001-1500/1494-Parallel-Courses-II/cpp-1494/CMakeLists.txt new file mode 100644 index 00000000..bf7a2f3d --- /dev/null +++ b/1001-1500/1494-Parallel-Courses-II/cpp-1494/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(cpp_1494) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1494 main2.cpp) \ No newline at end of file diff --git a/1001-1500/1494-Parallel-Courses-II/cpp-1494/main.cpp b/1001-1500/1494-Parallel-Courses-II/cpp-1494/main.cpp new file mode 100644 index 00000000..644c89a9 --- /dev/null +++ b/1001-1500/1494-Parallel-Courses-II/cpp-1494/main.cpp @@ -0,0 +1,66 @@ +/// Source : https://leetcode.com/problems/parallel-courses-ii/ +/// Author : liuyubobobo +/// Time : 2020-10-17 + +#include +#include +#include + +using namespace std; + + +class Solution { +public: + int minNumberOfSemesters(int n, vector>& dependencies, int k) { + + vector> g(n); + vector indegrees(n, 0); + for(const vector& e: dependencies){ + g[e[0] - 1].push_back(e[1] - 1); + indegrees[e[1] - 1] ++; + } + + queue q; + for(int i = 0; i < n; i ++) + if(!indegrees[i]) q.push(i); + + int res = 0; + while(!q.empty()){ + + int sz = min((int)q.size(), k); + res ++; + + while(sz --){ + int cur = q.front(); + q.pop(); + for(int next: g[cur]){ + indegrees[next] --; + if(!indegrees[next]) q.push(next); + } + } + } + return res; + } +}; + + +int main() { + + vector> dep1 = {{2, 1}, {3, 1}, {1, 4}}; + cout << Solution().minNumberOfSemesters(4, dep1, 2) << endl; + // 3 + + vector> dep2 = {{2, 1}, {3, 1}, {4, 1}, {1, 5}}; + cout << Solution().minNumberOfSemesters(5, dep2, 2) << endl; + // 4 + + vector> dep3 = {}; + cout << Solution().minNumberOfSemesters(11, dep3, 2) << endl; + // 6 + + vector> dep4 = {{1,2},{1,3},{7,5},{7,6},{4,8},{8,9},{9,10},{10,11},{11,12}}; + cout << Solution().minNumberOfSemesters(12, dep4, 2) << endl; + // 6 + + return 0; +} diff --git a/1001-1500/1494-Parallel-Courses-II/cpp-1494/main2.cpp b/1001-1500/1494-Parallel-Courses-II/cpp-1494/main2.cpp new file mode 100644 index 00000000..e7937140 --- /dev/null +++ b/1001-1500/1494-Parallel-Courses-II/cpp-1494/main2.cpp @@ -0,0 +1,105 @@ +/// Source : https://leetcode.com/problems/parallel-courses-ii/ +/// Author : liuyubobobo +/// Time : 2020-10-17 + +#include +#include +#include + +using namespace std; + + +/// State Complression and Memory Search +/// Time Complexity: O(4^n) +/// Space Complexity: O(2^n) +class Solution { + +private: + vector> bitsOfStates; + +public: + int minNumberOfSemesters(int n, vector>& dependencies, int k) { + + for(vector& e: dependencies) e[0] --, e[1] --; + + bitsOfStates = vector>(n + 1); + for(int state = 0; state < (1 << n); state ++) { +// cout << num_of_ones(state) << endl; + bitsOfStates[num_of_ones(state)].push_back(state); + } + + vector dp(1 << n, -1); + return dfs(n, dependencies, k, (1 << n) - 1, dp); + } + +private: + int dfs(int n, const vector>& edges, int k, int state, + vector& dp){ + + if(!state) return 0; + if(dp[state] != -1) return dp[state]; + + vector indegrees(n, 0); + for(const vector& e: edges) + if(state & (1 << e[0])) indegrees[e[1]] ++; + + vector options; + for(int i = 0; i < n; i ++) + if((state & (1 << i)) && !indegrees[i]) options.push_back(i); + + int c = min(k, (int)options.size()); + vector option_states; + get_option_states(options, 0, c, 0, option_states); + + int res = INT_MAX; + for(int option_state: option_states) + res = min(res, 1 + dfs(n, edges, k, state - option_state, dp)); +// cout << state << " : " << res << endl; + return dp[state] = res; + } + + void get_option_states(const vector& options, int index, int k, int state, + vector& res){ + + if(k == 0){ + res.push_back(state); + return; + } + if(index == options.size()) return; + + for(int i = index; i < options.size(); i ++) + get_option_states(options, i + 1, k - 1, state | (1 << options[i]), res); + } + + int num_of_ones(int state){ + + int res = 0; + while(state){ + res += (state & 1); + state >>= 1; + } + return res; + } +}; + + +int main() { + + vector> dep1 = {{2, 1}, {3, 1}, {1, 4}}; + cout << Solution().minNumberOfSemesters(4, dep1, 2) << endl; + // 3 + + vector> dep2 = {{2, 1}, {3, 1}, {4, 1}, {1, 5}}; + cout << Solution().minNumberOfSemesters(5, dep2, 2) << endl; + // 4 + + vector> dep3 = {}; + cout << Solution().minNumberOfSemesters(11, dep3, 2) << endl; + // 6 + + vector> dep4 = {{1,2},{1,3},{7,5},{7,6},{4,8},{8,9},{9,10},{10,11},{11,12}}; + cout << Solution().minNumberOfSemesters(12, dep4, 2) << endl; + // 6 + + return 0; +} diff --git a/1001-1500/1496-Path-Crossing/cpp-1496/CMakeLists.txt b/1001-1500/1496-Path-Crossing/cpp-1496/CMakeLists.txt new file mode 100644 index 00000000..cb89cda6 --- /dev/null +++ b/1001-1500/1496-Path-Crossing/cpp-1496/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1001-1500/1496-Path-Crossing/cpp-1496/main.cpp b/1001-1500/1496-Path-Crossing/cpp-1496/main.cpp new file mode 100644 index 00000000..b85453e3 --- /dev/null +++ b/1001-1500/1496-Path-Crossing/cpp-1496/main.cpp @@ -0,0 +1,44 @@ +/// Source : https://leetcode.com/problems/path-crossing/ +/// Author : liuyubobobo +/// Time : 2020-06-27 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + bool isPathCrossing(string path) { + + set> table; + table.insert({0, 0}); + int x = 0, y = 0; + for(char c: path){ + if(c == 'N') y ++; + else if(c == 'E') x ++; + else if(c == 'S') y --; + else x --; + + if(table.count({x, y})) return true; + table.insert({x, y}); + } + return false; + } +}; + + +int main() { + + cout << Solution().isPathCrossing("NES") << endl; + // 0 + + cout << Solution().isPathCrossing("NESWW") << endl; + // 1 + + return 0; +} diff --git a/1001-1500/1497-Check-If-Array-Pairs-Are-Divisible-by-k/cpp-1497/CMakeLists.txt b/1001-1500/1497-Check-If-Array-Pairs-Are-Divisible-by-k/cpp-1497/CMakeLists.txt new file mode 100644 index 00000000..e6f5d34c --- /dev/null +++ b/1001-1500/1497-Check-If-Array-Pairs-Are-Divisible-by-k/cpp-1497/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main2.cpp) \ No newline at end of file diff --git a/1001-1500/1497-Check-If-Array-Pairs-Are-Divisible-by-k/cpp-1497/main.cpp b/1001-1500/1497-Check-If-Array-Pairs-Are-Divisible-by-k/cpp-1497/main.cpp new file mode 100644 index 00000000..76438c9b --- /dev/null +++ b/1001-1500/1497-Check-If-Array-Pairs-Are-Divisible-by-k/cpp-1497/main.cpp @@ -0,0 +1,55 @@ +/// Source : https://leetcode.com/problems/check-if-array-pairs-are-divisible-by-k/ +/// Author : liuyubobobo +/// Time : 2020-06-27 + +#include +#include +#include + +using namespace std; + + +/// Using HashMap +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + bool canArrange(vector& arr, int k) { + + unordered_map freq; + for(int e: arr) freq[((e % k) + k) % k] ++; + + if(freq[0] % 2) return false; + for(int i = 1; i + i < k; i ++) + if(freq[i] != freq[k - i]) return false; + + if(k % 2 == 0 && freq[k / 2] % 2) return false; + return true; + } +}; + + +int main() { + + vector arr1 = {1,2,3,4,5,10,6,7,8,9}; + cout << Solution().canArrange(arr1, 5) << endl; + // 1 + + vector arr2 = {1,2,3,4,5,6}; + cout << Solution().canArrange(arr2, 7) << endl; + // 1 + + vector arr3 = {1,2,3,4,5,6}; + cout << Solution().canArrange(arr3, 10) << endl; + // 0 + + vector arr4 = {-10, 10}; + cout << Solution().canArrange(arr4, 2) << endl; + // 1 + + vector arr5 = {-1,1,-2,2,-3,3,-4,4}; + cout << Solution().canArrange(arr5, 3) << endl; + // 1 + + return 0; +} diff --git a/1001-1500/1497-Check-If-Array-Pairs-Are-Divisible-by-k/cpp-1497/main2.cpp b/1001-1500/1497-Check-If-Array-Pairs-Are-Divisible-by-k/cpp-1497/main2.cpp new file mode 100644 index 00000000..6f2eb0db --- /dev/null +++ b/1001-1500/1497-Check-If-Array-Pairs-Are-Divisible-by-k/cpp-1497/main2.cpp @@ -0,0 +1,59 @@ +/// Source : https://leetcode.com/problems/check-if-array-pairs-are-divisible-by-k/ +/// Author : liuyubobobo +/// Time : 2020-06-28 + +#include +#include +#include + +using namespace std; + + +/// Sorting and Two Pointers +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + bool canArrange(vector& arr, int k) { + + for(int& e: arr) e = (e % k + k) % k; + sort(arr.begin(), arr.end()); + + int l = 0; + for(; l < arr.size() && arr[l] % k == 0; l ++); + if(l % 2) return false; + + int r = arr.size() - 1; + while(l < r){ + if((arr[l] + arr[r]) % k) return false; + l ++, r --; + } + return l > r; + } +}; + + +int main() { + + vector arr1 = {1,2,3,4,5,10,6,7,8,9}; + cout << Solution().canArrange(arr1, 5) << endl; + // 1 + + vector arr2 = {1,2,3,4,5,6}; + cout << Solution().canArrange(arr2, 7) << endl; + // 1 + + vector arr3 = {1,2,3,4,5,6}; + cout << Solution().canArrange(arr3, 10) << endl; + // 0 + + vector arr4 = {-10, 10}; + cout << Solution().canArrange(arr4, 2) << endl; + // 1 + + vector arr5 = {-1,1,-2,2,-3,3,-4,4}; + cout << Solution().canArrange(arr5, 3) << endl; + // 1 + + return 0; +} diff --git a/1001-1500/1498-Number-of-Subsequences-That-Satisfy-the-Given-Sum-Condition/cpp-1498/CMakeLists.txt b/1001-1500/1498-Number-of-Subsequences-That-Satisfy-the-Given-Sum-Condition/cpp-1498/CMakeLists.txt new file mode 100644 index 00000000..94acd016 --- /dev/null +++ b/1001-1500/1498-Number-of-Subsequences-That-Satisfy-the-Given-Sum-Condition/cpp-1498/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1001-1500/1498-Number-of-Subsequences-That-Satisfy-the-Given-Sum-Condition/cpp-1498/main.cpp b/1001-1500/1498-Number-of-Subsequences-That-Satisfy-the-Given-Sum-Condition/cpp-1498/main.cpp new file mode 100644 index 00000000..db6239a7 --- /dev/null +++ b/1001-1500/1498-Number-of-Subsequences-That-Satisfy-the-Given-Sum-Condition/cpp-1498/main.cpp @@ -0,0 +1,65 @@ +/// Source : https://leetcode.com/problems/number-of-subsequences-that-satisfy-the-given-sum-condition/ +/// Author : liuyubobobo +/// Time : 2020-06-27 + +#include +#include + +using namespace std; + + +/// Sorting + Binary Search + Fast Pow +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { + +private: + const long long MOD = 1e9 + 7; + +public: + int numSubseq(vector& nums, int target) { + + sort(nums.begin(), nums.end()); + + long long res = 0; + for(int i = 0; i < nums.size(); i ++){ + vector::iterator iter = upper_bound(nums.begin() + i, nums.end(), target - nums[i]); + int x = iter - (nums.begin() + i) - 1; + if(x >= 0) res = (res + (mypow(2, x))) % MOD; + } + return res; + } + + long long mypow(int a, int b){ + + if(b == 0) return 1ll; + if(b == 1) return a; + + long long x = mypow(a, b / 2); + long long res = x * x % MOD; + if(b % 2) res = res * a % MOD; + return res; + } +}; + + +int main() { + + vector nums1 = {3,5,6,7}; + cout << Solution().numSubseq(nums1, 9) << endl; + // 4 + + vector nums2 = {3,3,6,8}; + cout << Solution().numSubseq(nums2, 10) << endl; + // 6 + + vector nums3 = {2,3,3,4,6,7}; + cout << Solution().numSubseq(nums3, 12) << endl; + // 61 + + vector nums4 = {5,2,4,1,7,6,8}; + cout << Solution().numSubseq(nums4, 16) << endl; + // 127 + + return 0; +} diff --git a/1001-1500/1499-Max-Value-of-Equation/cpp-1499/CMakeLists.txt b/1001-1500/1499-Max-Value-of-Equation/cpp-1499/CMakeLists.txt new file mode 100644 index 00000000..2879627e --- /dev/null +++ b/1001-1500/1499-Max-Value-of-Equation/cpp-1499/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main4.cpp) \ No newline at end of file diff --git a/1001-1500/1499-Max-Value-of-Equation/cpp-1499/main.cpp b/1001-1500/1499-Max-Value-of-Equation/cpp-1499/main.cpp new file mode 100644 index 00000000..e69de29b diff --git a/1001-1500/1499-Max-Value-of-Equation/cpp-1499/main2.cpp b/1001-1500/1499-Max-Value-of-Equation/cpp-1499/main2.cpp new file mode 100644 index 00000000..202bc426 --- /dev/null +++ b/1001-1500/1499-Max-Value-of-Equation/cpp-1499/main2.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/max-value-of-equation/ +/// Author : liuyubobobo +/// Time : 2020-06-28 + +#include +#include +#include +#include + +using namespace std; + + +/// Using Priority Queue +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + int findMaxValueOfEquation(vector>& points, int k) { + + priority_queue> pq; + + // 初始放入第一个点的信息 + pq.push({points[0][1] - points[0][0], points[0][0]}); + + int res = INT_MIN; + for(int i = 1; i < points.size(); i ++){ + // 将优先队列队头不符合条件的点扔掉 + while(!pq.empty() && points[i][0] - pq.top().second > k) pq.pop(); + + // 使用优先队列队首元素信息更新解 + if(!pq.empty()) + res = max(res, points[i][1] + points[i][0] + pq.top().first); + + // 将当前点的信息放入优先队列 + pq.push({points[i][1] - points[i][0], points[i][0]}); + } + return res; + } +}; + + +int main() { + + vector> points1 = {{1,3},{2,0},{5,10},{6,-10}}; + cout << Solution().findMaxValueOfEquation(points1, 1) << endl; + // 4 + + vector> points2 = {{0,0},{3,0},{9,2}}; + cout << Solution().findMaxValueOfEquation(points2, 3) << endl; + // 3 + + return 0; +} diff --git a/1001-1500/1499-Max-Value-of-Equation/cpp-1499/main3.cpp b/1001-1500/1499-Max-Value-of-Equation/cpp-1499/main3.cpp new file mode 100644 index 00000000..8bdada7a --- /dev/null +++ b/1001-1500/1499-Max-Value-of-Equation/cpp-1499/main3.cpp @@ -0,0 +1,56 @@ +/// Source : https://leetcode.com/problems/max-value-of-equation/ +/// Author : liuyubobobo +/// Time : 2020-06-28 + +#include +#include +#include + +using namespace std; + + +/// Using BST +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + int findMaxValueOfEquation(vector>& points, int k) { + + set> tree; + + // 初始放入第一个点的信息 + tree.insert({points[0][1] - points[0][0], points[0][0]}); + + int res = INT_MIN, j = 0; + for(int i = 1; i < points.size(); i ++){ + + // 删除红黑树中不满足条件的数据 + while(j < i && points[i][0] - points[j][0] > k){ + tree.erase({points[j][1] - points[j][0], points[j][0]}); + j ++; + } + + // 使用红黑树最大元素信息更新解 + if(!tree.empty()) + res = max(res, points[i][1] + points[i][0] + tree.rbegin()->first); + + // 将当前点的信息放入红黑树 + tree.insert({points[i][1] - points[i][0], points[i][0]}); + } + return res; + } +}; + + +int main() { + + vector> points1 = {{1,3},{2,0},{5,10},{6,-10}}; + cout << Solution().findMaxValueOfEquation(points1, 1) << endl; + // 4 + + vector> points2 = {{0,0},{3,0},{9,2}}; + cout << Solution().findMaxValueOfEquation(points2, 3) << endl; + // 3 + + return 0; +} diff --git a/1001-1500/1499-Max-Value-of-Equation/cpp-1499/main4.cpp b/1001-1500/1499-Max-Value-of-Equation/cpp-1499/main4.cpp new file mode 100644 index 00000000..b803e52c --- /dev/null +++ b/1001-1500/1499-Max-Value-of-Equation/cpp-1499/main4.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/max-value-of-equation/ +/// Author : liuyubobobo +/// Time : 2020-06-28 + +#include +#include +#include + +using namespace std; + + +/// Using BST 2 +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + int findMaxValueOfEquation(vector>& points, int k) { + + set> tree; + + // 初始放入第一个点的信息 + tree.insert({points[0][1] - points[0][0], points[0][0]}); + + int res = INT_MIN; + for(int i = 1; i < points.size(); i ++){ + + // 取出红黑树中的最大 y - x 值,如果不满足约束,则删除 + while(!tree.empty() && points[i][0] - tree.rbegin()->second > k) + tree.erase(--tree.end()); + + // 使用红黑树最大元素信息更新解 + if(!tree.empty()) + res = max(res, points[i][1] + points[i][0] + tree.rbegin()->first); + + // 将当前点的信息放入红黑树 + tree.insert({points[i][1] - points[i][0], points[i][0]}); + } + return res; + } +}; + + +int main() { + + vector> points1 = {{1,3},{2,0},{5,10},{6,-10}}; + cout << Solution().findMaxValueOfEquation(points1, 1) << endl; + // 4 + + vector> points2 = {{0,0},{3,0},{9,2}}; + cout << Solution().findMaxValueOfEquation(points2, 3) << endl; + // 3 + + return 0; +} diff --git a/1001-1500/1499-Max-Value-of-Equation/cpp-1499/main5.cpp b/1001-1500/1499-Max-Value-of-Equation/cpp-1499/main5.cpp new file mode 100644 index 00000000..12e9da41 --- /dev/null +++ b/1001-1500/1499-Max-Value-of-Equation/cpp-1499/main5.cpp @@ -0,0 +1,58 @@ +/// Source : https://leetcode.com/problems/max-value-of-equation/ +/// Author : liuyubobobo +/// Time : 2020-06-28 + +#include +#include +#include + +using namespace std; + + +/// Using Mono Queue +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int findMaxValueOfEquation(vector>& points, int k) { + + deque> dq; + + // 初始放入第一个点的信息 + dq.push_front({points[0][1] - points[0][0], points[0][0]}); + + int res = INT_MIN; + for(int i = 1; i < points.size(); i ++){ + + // 对队列首不符合约束的点删除 + while(!dq.empty() && points[i][0] - dq.front().second > k) + dq.pop_front(); + + // 根据队首最大元素信息更新解 + if(!dq.empty()) + res = max(res, points[i][1] + points[i][0] + dq.front().first); + + // 把队列尾的比当前 y - x 还小的元素删除 + while(!dq.empty() && dq.back().first <= points[i][1] - points[i][0]) + dq.pop_back(); + + // 将当前点的信息加入队列 + dq.push_back({points[i][1] - points[i][0], points[i][0]}); + } + return res; + } +}; + + +int main() { + + vector> points1 = {{1,3},{2,0},{5,10},{6,-10}}; + cout << Solution().findMaxValueOfEquation(points1, 1) << endl; + // 4 + + vector> points2 = {{0,0},{3,0},{9,2}}; + cout << Solution().findMaxValueOfEquation(points2, 3) << endl; + // 3 + + return 0; +} diff --git a/1501-2000/1506-Find-Root-of-N-Ary-Tree/cpp-1506/CMakeLists.txt b/1501-2000/1506-Find-Root-of-N-Ary-Tree/cpp-1506/CMakeLists.txt new file mode 100644 index 00000000..8c3de935 --- /dev/null +++ b/1501-2000/1506-Find-Root-of-N-Ary-Tree/cpp-1506/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1506) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1506 main2.cpp) \ No newline at end of file diff --git a/1501-2000/1506-Find-Root-of-N-Ary-Tree/cpp-1506/main.cpp b/1501-2000/1506-Find-Root-of-N-Ary-Tree/cpp-1506/main.cpp new file mode 100644 index 00000000..6e6109f2 --- /dev/null +++ b/1501-2000/1506-Find-Root-of-N-Ary-Tree/cpp-1506/main.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/find-root-of-n-ary-tree/ +/// Author : liuyubobobo +/// Time : 2021-01-08 + +#include +#include +#include + +using namespace std; + + +/// Using HashSet +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +// Definition for a Node. +class Node { +public: + int val; + vector children; + + Node() {} + + Node(int _val) { + val = _val; + } + + Node(int _val, vector _children) { + val = _val; + children = _children; + } +}; + +class Solution { +public: + Node* findRoot(vector tree) { + + unordered_set set; + for(Node* node: tree) + for(Node* next: node->children) + set.insert(next); + + for(Node* node: tree) + if(!set.count(node)) return node; + return nullptr; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1506-Find-Root-of-N-Ary-Tree/cpp-1506/main2.cpp b/1501-2000/1506-Find-Root-of-N-Ary-Tree/cpp-1506/main2.cpp new file mode 100644 index 00000000..f8364031 --- /dev/null +++ b/1501-2000/1506-Find-Root-of-N-Ary-Tree/cpp-1506/main2.cpp @@ -0,0 +1,55 @@ +/// Source : https://leetcode.com/problems/find-root-of-n-ary-tree/ +/// Author : liuyubobobo +/// Time : 2021-01-08 + +#include +#include +#include + +using namespace std; + + +/// Using xor +/// Time Complexity: O(n) +/// Space Complexity: O(1) + +// Definition for a Node. +class Node { +public: + int val; + vector children; + + Node() {} + + Node(int _val) { + val = _val; + } + + Node(int _val, vector _children) { + val = _val; + children = _children; + } +}; + +class Solution { +public: + Node* findRoot(vector tree) { + + int x = 0; + for(Node* node: tree){ + x ^= node->val; + for(Node* next: node->children) + x ^= next->val; + } + + for(Node* node: tree) + if(node->val == x) return node; + return nullptr; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1519-Number-of-Nodes-in-the-Sub-Tree-With-the-Same-Label/cpp-1519/CMakeLists.txt b/1501-2000/1519-Number-of-Nodes-in-the-Sub-Tree-With-the-Same-Label/cpp-1519/CMakeLists.txt new file mode 100644 index 00000000..e30161c9 --- /dev/null +++ b/1501-2000/1519-Number-of-Nodes-in-the-Sub-Tree-With-the-Same-Label/cpp-1519/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_1519) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_1519 main.cpp) diff --git a/1501-2000/1519-Number-of-Nodes-in-the-Sub-Tree-With-the-Same-Label/cpp-1519/main.cpp b/1501-2000/1519-Number-of-Nodes-in-the-Sub-Tree-With-the-Same-Label/cpp-1519/main.cpp new file mode 100644 index 00000000..1a7ff35a --- /dev/null +++ b/1501-2000/1519-Number-of-Nodes-in-the-Sub-Tree-With-the-Same-Label/cpp-1519/main.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/number-of-nodes-in-the-sub-tree-with-the-same-label/description/ +/// Author : liuyubobobo +/// Time : 2023-01-12 + +#include +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector countSubTrees(int n, vector>& edges, string labels) { + + vector> tree(n); + for(const vector& e: edges){ + int u = e[0], v = e[1]; + tree[u].push_back(v), tree[v].push_back(u); + } + + vector> table(n, vector(26, 0)); + dfs(tree, 0, -1, labels, table); + + vector res(n); + for(int i = 0; i < n; i ++) + res[i] = table[i][labels[i] - 'a']; + return res; + } + +private: + void dfs(const vector>& tree, int u, int p, + const string& label, vector>& table){ + + table[u][label[u] - 'a'] ++; + for(int v: tree[u]){ + if(v == p) continue; + dfs(tree, v, u, label, table); + for(int i = 0; i < 26; i ++) + table[u][i] += table[v][i]; + } + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1522-Diameter-of-N-Ary-Tree/cpp-1522/CMakeLists.txt b/1501-2000/1522-Diameter-of-N-Ary-Tree/cpp-1522/CMakeLists.txt new file mode 100644 index 00000000..d8f94851 --- /dev/null +++ b/1501-2000/1522-Diameter-of-N-Ary-Tree/cpp-1522/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1522) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1522 main.cpp) \ No newline at end of file diff --git a/1501-2000/1522-Diameter-of-N-Ary-Tree/cpp-1522/main.cpp b/1501-2000/1522-Diameter-of-N-Ary-Tree/cpp-1522/main.cpp new file mode 100644 index 00000000..23952f4c --- /dev/null +++ b/1501-2000/1522-Diameter-of-N-Ary-Tree/cpp-1522/main.cpp @@ -0,0 +1,65 @@ +/// Source : https://leetcode.com/problems/diameter-of-n-ary-tree/ +/// Author : liuyubobobo +/// Time : 2020-10-15 + +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(h) + +// Definition for a Node. +class Node { +public: + int val; + vector children; + + Node() {} + + Node(int _val) { + val = _val; + } + + Node(int _val, vector _children) { + val = _val; + children = _children; + } +}; + + +class Solution { + +private: + int res; + +public: + int diameter(Node* root) { + + res = 0; + dfs(root); + return res; + } + +private: + int dfs(Node* node){ + + int first = 0, second = 0; + for(Node* next: node->children){ + int t = 1 + dfs(next); + if(t >= first) second = first, first = t; + else if(t > second) second = t; + } + res = max(res, first + second); + return first; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1523-Count-Odd-Numbers-in-an-Interval-Range/cpp-1523/CMakeLists.txt b/1501-2000/1523-Count-Odd-Numbers-in-an-Interval-Range/cpp-1523/CMakeLists.txt new file mode 100644 index 00000000..3a994f27 --- /dev/null +++ b/1501-2000/1523-Count-Odd-Numbers-in-an-Interval-Range/cpp-1523/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_1523) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_1523 main.cpp) diff --git a/1501-2000/1523-Count-Odd-Numbers-in-an-Interval-Range/cpp-1523/main.cpp b/1501-2000/1523-Count-Odd-Numbers-in-an-Interval-Range/cpp-1523/main.cpp new file mode 100644 index 00000000..d1b3d2b3 --- /dev/null +++ b/1501-2000/1523-Count-Odd-Numbers-in-an-Interval-Range/cpp-1523/main.cpp @@ -0,0 +1,26 @@ +/// Source : https://leetcode.com/problems/count-odd-numbers-in-an-interval-range/description/ +/// Author : liuyubobobo +/// Time : 2023-02-13 + +#include + +using namespace std; + + +/// Math +/// Time Complexity: O(1) +/// Space Complexity: O(1) +class Solution { +public: + int countOdds(int low, int high) { + + int len = high - low + 1; + return low % 2 == 1 ? (len + 1) / 2 : len / 2; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1531-String-Compression-II/cpp-1531/CMakeLists.txt b/1501-2000/1531-String-Compression-II/cpp-1531/CMakeLists.txt new file mode 100644 index 00000000..3b24f0ff --- /dev/null +++ b/1501-2000/1531-String-Compression-II/cpp-1531/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_1531) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1531 main.cpp) diff --git a/1501-2000/1531-String-Compression-II/cpp-1531/main.cpp b/1501-2000/1531-String-Compression-II/cpp-1531/main.cpp new file mode 100644 index 00000000..2616d50e --- /dev/null +++ b/1501-2000/1531-String-Compression-II/cpp-1531/main.cpp @@ -0,0 +1,80 @@ +/// Source : https://leetcode.com/problems/string-compression-ii/ +/// Author : liuyubobobo +/// Time : 2022-10-16 + +#include +#include +#include + +using namespace std; + + +/// Memoization +/// Time Complexity: O(27 * 11 * |s| * k) +/// Space Complexity: O(27 * 11 * |s| * k) +class Solution { + +public: + int getLengthOfOptimalCompression(string s, int k) { + + if(all_one_char(s)){ + s = s.substr(0, (int)s.size() - k); + return len(s.size()); + } + + // dp[pre_char][pre_cnt][index][k] + vector>>> dp(27, vector>>(11, vector>(s.size(), vector(k + 1, -1)))); + return dfs(s, 26, 0, 0, k, dp); + } + +private: + int dfs(const string& s, int pre_char, int pre_cnt, int index, int k, + vector>>>& dp){ + + int pre_len = len(pre_cnt); + + if(index == s.size()){ + return pre_len; + } + + if(dp[pre_char][pre_cnt][index][k] != -1) + return dp[pre_char][pre_cnt][index][k]; + + int res = INT_MAX; + if(s[index] - 'a' != pre_char) + res = min(res, pre_len + dfs(s, s[index] - 'a', 1, index + 1, k, dp)); + else + res = min(res, dfs(s, pre_char, min(pre_cnt + 1, 10), index + 1, k, dp)); + + if(k) + res = min(res, dfs(s, pre_char, pre_cnt, index + 1, k - 1, dp)); + return dp[pre_char][pre_cnt][index][k] = res; + } + + int len(int cnt){ + if(cnt == 0) return 0; + else if(cnt == 1) return 1; + else return 1 + to_string(cnt).size(); + } + + bool all_one_char(const string& s){ + for(int i = 1; i < s.size(); i ++) + if(s[i] != s[0]) return false; + return true; + } +}; + + +int main() { + + cout << Solution().getLengthOfOptimalCompression("aaabcccd", 2) << '\n'; + // 4 + + cout << Solution().getLengthOfOptimalCompression("aabbaa", 2) << '\n'; + // 2 + + cout << Solution().getLengthOfOptimalCompression("aaaaaaaaaaa", 0) << '\n'; + // 3 + + return 0; +} diff --git a/1501-2000/1533-Find-the-Index-of-the-Large-Integer/cpp-1533/CMakeLists.txt b/1501-2000/1533-Find-the-Index-of-the-Large-Integer/cpp-1533/CMakeLists.txt new file mode 100644 index 00000000..ef8a6543 --- /dev/null +++ b/1501-2000/1533-Find-the-Index-of-the-Large-Integer/cpp-1533/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_1533) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_1533 main.cpp) diff --git a/1501-2000/1533-Find-the-Index-of-the-Large-Integer/cpp-1533/main.cpp b/1501-2000/1533-Find-the-Index-of-the-Large-Integer/cpp-1533/main.cpp new file mode 100644 index 00000000..fa81143c --- /dev/null +++ b/1501-2000/1533-Find-the-Index-of-the-Large-Integer/cpp-1533/main.cpp @@ -0,0 +1,88 @@ +/// Source : https://leetcode.com/problems/find-the-index-of-the-large-integer/ +/// Author : liuyubobobo +/// Time : 2023-01-14 + +#include +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Compelxity: O(logn) +/// Space Compelxity: O(1) + +// This is the ArrayReader's API interface. +// You should not implement it, or speculate about its implementation +class ArrayReader { + +private: + vector data; + vector presum; + +public: + ArrayReader(const vector& arr): data(arr), presum(data.size() + 1, 0){ + + int n = arr.size(); + for(int i = 0; i < n; i ++) presum[i + 1] = presum[i] + data[i]; + } + + // Compares the sum of arr[l..r] with the sum of arr[x..y] + // return 1 if sum(arr[l..r]) > sum(arr[x..y]) + // return 0 if sum(arr[l..r]) == sum(arr[x..y]) + // return -1 if sum(arr[l..r]) < sum(arr[x..y]) + int compareSub(int l, int r, int x, int y){ + int sum1 = presum[r + 1] - presum[l], sum2 = presum[y + 1] - presum[x]; + if(sum1 > sum2) return 1; + return sum1 == sum2 ? 0 : -1; + } + + // Returns the length of the array + int length(){ + return data.size(); + } +}; + +class Solution { +public: + int getIndex(ArrayReader &reader) { + + int n = reader.length(); + return search(reader, 0, n - 1); + } + +private: + int search(ArrayReader &reader, int l, int r){ + + if(l == r) return l; + + int len = (r - l + 1); + if(len & 1){ + int res = search(reader, l, r - 1); + return res == -1 ? r : res; + } + + int mid = (l + r) / 2; + int x = reader.compareSub(l, mid, mid + 1, r); + if(x == 1) return search(reader, l, mid); + else if(x == 0) return -1; + else return search(reader, mid + 1, r); + } +}; + + +int main() { + + vector nums1 = {6, 6, 12}; + ArrayReader reader1(nums1); + cout << Solution().getIndex(reader1) << '\n'; + // 2 + + vector nums2 = {7, 7, 7, 7, 10, 7, 7, 7}; + ArrayReader reader2(nums2); + cout << Solution().getIndex(reader2) << '\n'; + // 4 + + return 0; +} diff --git a/1501-2000/1539-Kth-Missing-Positive-Number/cpp-1539/CMakeLists.txt b/1501-2000/1539-Kth-Missing-Positive-Number/cpp-1539/CMakeLists.txt new file mode 100644 index 00000000..95424ec7 --- /dev/null +++ b/1501-2000/1539-Kth-Missing-Positive-Number/cpp-1539/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1539) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1539 main.cpp) \ No newline at end of file diff --git a/1501-2000/1539-Kth-Missing-Positive-Number/cpp-1539/main.cpp b/1501-2000/1539-Kth-Missing-Positive-Number/cpp-1539/main.cpp new file mode 100644 index 00000000..cbd4f246 --- /dev/null +++ b/1501-2000/1539-Kth-Missing-Positive-Number/cpp-1539/main.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/kth-missing-positive-number/ +/// Author : liuyubobobo +/// Time : 2021-01-06 + +#include +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(n + k) +/// Space Complexity: O(1) +class Solution { +public: + int findKthPositive(vector& arr, int k) { + + int arrp = 0, e = 1; + while(k){ + if(arrp < arr.size() && arr[arrp] == e) arrp ++; + else k --; + e ++; + } + return e - 1; + } +}; + + +int main() { + + vector arr1 = {2, 3, 4, 7, 11}; + cout << Solution().findKthPositive(arr1, 5) << endl; + // 9 + + vector arr2 = {1, 2, 3, 4}; + cout << Solution().findKthPositive(arr2, 2) << endl; + // 6 + + return 0; +} diff --git a/1501-2000/1557-Minimum-Number-of-Vertices-to-Reach-All-Nodes/cpp-1557/CMakeLists.txt b/1501-2000/1557-Minimum-Number-of-Vertices-to-Reach-All-Nodes/cpp-1557/CMakeLists.txt new file mode 100644 index 00000000..290c8ea2 --- /dev/null +++ b/1501-2000/1557-Minimum-Number-of-Vertices-to-Reach-All-Nodes/cpp-1557/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_1557) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_1557 main.cpp) diff --git a/1501-2000/1557-Minimum-Number-of-Vertices-to-Reach-All-Nodes/cpp-1557/main.cpp b/1501-2000/1557-Minimum-Number-of-Vertices-to-Reach-All-Nodes/cpp-1557/main.cpp new file mode 100644 index 00000000..085230b2 --- /dev/null +++ b/1501-2000/1557-Minimum-Number-of-Vertices-to-Reach-All-Nodes/cpp-1557/main.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/minimum-number-of-vertices-to-reach-all-nodes/description/ +/// Author : liuyubobobo +/// Time : 2023-05-17 + +#include +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(m) +/// Space Complexity: O(n) +class Solution { +public: + vector findSmallestSetOfVertices(int n, vector>& edges) { + + vector d(n, 0); + for(const vector& edge: edges) + d[edge[1]]++; + + vector res; + for(int i = 0; i < n; i++) + if(d[i] == 0) + res.push_back(i); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1559-Detect-Cycles-in-2D-Grid/cpp-1559/CMakeLists.txt b/1501-2000/1559-Detect-Cycles-in-2D-Grid/cpp-1559/CMakeLists.txt new file mode 100644 index 00000000..ad222f88 --- /dev/null +++ b/1501-2000/1559-Detect-Cycles-in-2D-Grid/cpp-1559/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_1559) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1559 main.cpp) diff --git a/1501-2000/1559-Detect-Cycles-in-2D-Grid/cpp-1559/main.cpp b/1501-2000/1559-Detect-Cycles-in-2D-Grid/cpp-1559/main.cpp new file mode 100644 index 00000000..b6e1b966 --- /dev/null +++ b/1501-2000/1559-Detect-Cycles-in-2D-Grid/cpp-1559/main.cpp @@ -0,0 +1,61 @@ +/// Source : https://leetcode.com/problems/detect-cycles-in-2d-grid/ +/// Author : liuyubobobo +/// Time : 2022-03-25 + +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(R * C) +/// Space Complexity: O(R * C) +class Solution { + +private: + const int dirs[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; + int R, C; + +public: + bool containsCycle(vector>& grid) { + + R = grid.size(), C = grid[0].size(); + + vector> visited(R, vector(C, -1)); + int tag = 0; + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++) + if(visited[i][j] == -1 && dfs(grid, i, j, -1, -1, tag ++, visited)) + return true; + return false; + } + +private: + bool dfs(const vector>& grid, int cx, int cy, int px, int py, + int tag, vector>& visited){ + + visited[cx][cy] = tag; + + for(int d = 0; d < 4; d ++){ + int nx = cx + dirs[d][0], ny = cy + dirs[d][1]; + if(!in_area(nx, ny)) continue; + if(grid[nx][ny] != grid[cx][cy]) continue; + if(nx == px && ny == py) continue; + + if(visited[nx][ny] == tag) return true; + if(dfs(grid, nx, ny, cx, cy, tag, visited)) return true; + } + return false; + } + + bool in_area(int x, int y){ + return 0 <= x && x < R && 0 <= y && y < C; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1564-Put-Boxes-Into-the-Warehouse-I/cpp-1564/CMakeLists.txt b/1501-2000/1564-Put-Boxes-Into-the-Warehouse-I/cpp-1564/CMakeLists.txt new file mode 100644 index 00000000..eee33e6b --- /dev/null +++ b/1501-2000/1564-Put-Boxes-Into-the-Warehouse-I/cpp-1564/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1564) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1564 main.cpp) \ No newline at end of file diff --git a/1501-2000/1564-Put-Boxes-Into-the-Warehouse-I/cpp-1564/main.cpp b/1501-2000/1564-Put-Boxes-Into-the-Warehouse-I/cpp-1564/main.cpp new file mode 100644 index 00000000..0d743fe2 --- /dev/null +++ b/1501-2000/1564-Put-Boxes-Into-the-Warehouse-I/cpp-1564/main.cpp @@ -0,0 +1,42 @@ +/// Source : https://leetcode.com/problems/put-boxes-into-the-warehouse-i/ +/// Author : liuyubobobo +/// Time : 2020-10-17 + +#include +#include + +using namespace std; + + +/// Sorting and Greedy +/// Time Complexity: O(nlogn + n + m) +/// Space Complexity: O(1) +class Solution { +public: + int maxBoxesInWarehouse(vector& boxes, vector& warehouse) { + + int cur = warehouse[0]; + for(int i = 1; i < warehouse.size(); i ++){ + warehouse[i] = min(warehouse[i], cur); + cur = warehouse[i]; + } + + sort(boxes.begin(), boxes.end()); + int i = 0, j = warehouse.size() - 1, res = 0; + while(i < boxes.size() && j >= 0) + if(boxes[i] <= warehouse[j]) i ++, j --, res ++; + else j --; + + return res; + } +}; + + +int main() { + + vector box1 = {4, 3, 4, 1}, warehouse1 = {5, 3, 3, 4, 1}; + cout << Solution().maxBoxesInWarehouse(box1, warehouse1) << endl; + // 3 + + return 0; +} diff --git a/1501-2000/1570-Dot-Product-of-Two-Sparse-Vectors/cpp-1570/CMakeLists.txt b/1501-2000/1570-Dot-Product-of-Two-Sparse-Vectors/cpp-1570/CMakeLists.txt new file mode 100644 index 00000000..2e73ce54 --- /dev/null +++ b/1501-2000/1570-Dot-Product-of-Two-Sparse-Vectors/cpp-1570/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_1570) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1570 main.cpp) \ No newline at end of file diff --git a/1501-2000/1570-Dot-Product-of-Two-Sparse-Vectors/cpp-1570/main.cpp b/1501-2000/1570-Dot-Product-of-Two-Sparse-Vectors/cpp-1570/main.cpp new file mode 100644 index 00000000..1a36956d --- /dev/null +++ b/1501-2000/1570-Dot-Product-of-Two-Sparse-Vectors/cpp-1570/main.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/dot-product-of-two-sparse-vectors/ +/// Author : liuyubobobo +/// Time : 2021-06-20 + +#include +#include + +using namespace std; + + +/// Using index-value array +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class SparseVector { + +private: + vector> data; // pos->num + +public: + SparseVector(vector &nums) { + + for(int i = 0; i < nums.size(); i ++) + if(nums[i]) data.push_back({i, nums[i]}); + } + + // Return the dotProduct of two sparse vectors + int dotProduct(SparseVector& vec) { + + int res = 0, i = 0, j = 0; + while(i < data.size() && j < vec.data.size()) + if(data[i].first == vec.data[j].first){ + res += data[i].second * vec.data[j].second; + i ++; + j ++; + } + else if(data[i].first < vec.data[j].first) i ++; + else j ++; + return res; + } +}; + + +int main() { + + vector v1 = {1, 0, 0, 2, 3}, v2 = {0, 3, 0, 4, 0}; + SparseVector sp1(v1), sp2(v2); + cout << sp1.dotProduct(sp2) << endl; + + return 0; +} diff --git a/1501-2000/1572-Matrix-Diagonal-Sum/cpp-1572/CMakeLists.txt b/1501-2000/1572-Matrix-Diagonal-Sum/cpp-1572/CMakeLists.txt new file mode 100644 index 00000000..5828bf49 --- /dev/null +++ b/1501-2000/1572-Matrix-Diagonal-Sum/cpp-1572/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_1572) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_1572 main.cpp) diff --git a/1501-2000/1572-Matrix-Diagonal-Sum/cpp-1572/main.cpp b/1501-2000/1572-Matrix-Diagonal-Sum/cpp-1572/main.cpp new file mode 100644 index 00000000..db259d3e --- /dev/null +++ b/1501-2000/1572-Matrix-Diagonal-Sum/cpp-1572/main.cpp @@ -0,0 +1,30 @@ +/// Source : https://leetcode.com/problems/matrix-diagonal-sum/ +/// Author : liuyubobobo +/// Time : 2023-05-07 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int diagonalSum(vector>& mat) { + + int n = mat.size(), sum = 0; + for(int i = 0; i < n; i ++) + sum += mat[i][i] + mat[i][n - 1 - i]; + if(n & 1) sum -= mat[n / 2][n / 2]; + return sum; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1574-Shortest-Subarray-to-be-Removed-to-Make-Array-Sorted/cpp-1574/CMakeLists.txt b/1501-2000/1574-Shortest-Subarray-to-be-Removed-to-Make-Array-Sorted/cpp-1574/CMakeLists.txt new file mode 100644 index 00000000..d27c9c03 --- /dev/null +++ b/1501-2000/1574-Shortest-Subarray-to-be-Removed-to-Make-Array-Sorted/cpp-1574/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_1574) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_1574 main2.cpp) diff --git a/1501-2000/1574-Shortest-Subarray-to-be-Removed-to-Make-Array-Sorted/cpp-1574/main.cpp b/1501-2000/1574-Shortest-Subarray-to-be-Removed-to-Make-Array-Sorted/cpp-1574/main.cpp new file mode 100644 index 00000000..c9ea9f0a --- /dev/null +++ b/1501-2000/1574-Shortest-Subarray-to-be-Removed-to-Make-Array-Sorted/cpp-1574/main.cpp @@ -0,0 +1,74 @@ +/// Source : https://leetcode.com/problems/shortest-subarray-to-be-removed-to-make-array-sorted/description/ +/// Author : liuyubobobo +/// Time : 2023-03-24 + +#include +#include +#include + +using namespace std; + + +/// Using Map +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { + +public: + int findLengthOfShortestSubarray(vector& arr) { + + if(is_sorted(arr.begin(), arr.end())) return 0; + + int n = arr.size(); + + map table; + table[arr[n - 1]] = n - 1; + int res = 1; + for(int i = n - 2; i >= 0 && arr[i] <= arr[i + 1]; i --) + table[arr[i]] = i, res = n - i; + + for(int i = 0; i < n && (i == 0 || arr[i] >= arr[i - 1]); i ++){ + res = max(res, i + 1); + auto iter = table.lower_bound(arr[i]); + if(iter != table.end()){ + int j = iter->second; + res = max(res, i + 1 + (n - j)); + } + } + return n - res; + } +}; + + +int main() { + + vector arr1 = {1, 2, 3, 10, 4, 2, 3, 5}; + cout << Solution().findLengthOfShortestSubarray(arr1) << '\n'; + // 3 + + vector arr2 = {5, 4, 3, 2, 1}; + cout << Solution().findLengthOfShortestSubarray(arr2) << '\n'; + // 4 + + vector arr3 = {2, 2, 2, 1, 1, 1}; + cout << Solution().findLengthOfShortestSubarray(arr3) << '\n'; + // 3 + + vector arr4 = {1, 2, 3}; + cout << Solution().findLengthOfShortestSubarray(arr4) << '\n'; + // 0 + + vector arr5 = {10, 13, 17, 21, 15, 15, 9, 17, 22, 22, 13}; + cout << Solution().findLengthOfShortestSubarray(arr5) << '\n'; + // 7 + + vector arr6 = {16, 10, 0, 3, 22, 1, 14, 7, 1, 12, 15}; + cout << Solution().findLengthOfShortestSubarray(arr6) << '\n'; + // 8 + + vector arr7 = {22, 0, 23, 23, 27, 23, 12, 19, 18, 10, 25, 29, 15, 28, 0}; + cout << Solution().findLengthOfShortestSubarray(arr7) << '\n'; + // 14 + + return 0; +} diff --git a/1501-2000/1574-Shortest-Subarray-to-be-Removed-to-Make-Array-Sorted/cpp-1574/main2.cpp b/1501-2000/1574-Shortest-Subarray-to-be-Removed-to-Make-Array-Sorted/cpp-1574/main2.cpp new file mode 100644 index 00000000..de45855d --- /dev/null +++ b/1501-2000/1574-Shortest-Subarray-to-be-Removed-to-Make-Array-Sorted/cpp-1574/main2.cpp @@ -0,0 +1,67 @@ +/// Source : https://leetcode.com/problems/shortest-subarray-to-be-removed-to-make-array-sorted/description/ +/// Author : liuyubobobo +/// Time : 2023-03-24 + +#include +#include +#include + +using namespace std; + + +/// Two Pointers +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { + +public: + int findLengthOfShortestSubarray(vector& arr) { + + int n = arr.size(); + + int j = n - 1; + while(j - 1 >= 0 && arr[j - 1] <= arr[j]) j --; + + int res = n - j; + for(int i = 0; i < n && (i == 0 || arr[i] >= arr[i - 1]); i ++){ + res = max(res, i + 1); + while(j < n && (i == j || arr[i] > arr[j])) j ++; + if(j < n) res = max(res, i + 1 + (n - j)); + } + return n - res; + } +}; + + +int main() { + + vector arr1 = {1, 2, 3, 10, 4, 2, 3, 5}; + cout << Solution().findLengthOfShortestSubarray(arr1) << '\n'; + // 3 + + vector arr2 = {5, 4, 3, 2, 1}; + cout << Solution().findLengthOfShortestSubarray(arr2) << '\n'; + // 4 + + vector arr3 = {2, 2, 2, 1, 1, 1}; + cout << Solution().findLengthOfShortestSubarray(arr3) << '\n'; + // 3 + + vector arr4 = {1, 2, 3}; + cout << Solution().findLengthOfShortestSubarray(arr4) << '\n'; + // 0 + + vector arr5 = {10, 13, 17, 21, 15, 15, 9, 17, 22, 22, 13}; + cout << Solution().findLengthOfShortestSubarray(arr5) << '\n'; + // 7 + + vector arr6 = {16, 10, 0, 3, 22, 1, 14, 7, 1, 12, 15}; + cout << Solution().findLengthOfShortestSubarray(arr6) << '\n'; + // 8 + + vector arr7 = {22, 0, 23, 23, 27, 23, 12, 19, 18, 10, 25, 29, 15, 28, 0}; + cout << Solution().findLengthOfShortestSubarray(arr7) << '\n'; + // 14 + + return 0; +} diff --git a/1501-2000/1575-Count-All-Possible-Routes/cpp-1575/CMakeLists.txt b/1501-2000/1575-Count-All-Possible-Routes/cpp-1575/CMakeLists.txt new file mode 100644 index 00000000..53ab7b11 --- /dev/null +++ b/1501-2000/1575-Count-All-Possible-Routes/cpp-1575/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_1575) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_1575 main.cpp) diff --git a/1501-2000/1575-Count-All-Possible-Routes/cpp-1575/main.cpp b/1501-2000/1575-Count-All-Possible-Routes/cpp-1575/main.cpp new file mode 100644 index 00000000..ddede98a --- /dev/null +++ b/1501-2000/1575-Count-All-Possible-Routes/cpp-1575/main.cpp @@ -0,0 +1,48 @@ +/// Source : https://leetcode.com/problems/count-all-possible-routes/description/ +/// Author : liuyubobobo +/// Time : 2023-06-25 + +#include +#include + +using namespace std; + + +/// Memoization +/// Time Complexity: O(n^2 * fuel) +/// Space Complexity: O(n * fuel) +class Solution { + +private: + long long MOD = 1e9 + 7; + +public: + int countRoutes(vector& locations, int start, int finish, int fuel) { + + int n = locations.size(); + vector> dp(n, vector(fuel + 1, -1)); + return dfs(n, locations, finish, start, fuel, dp); + } + +private: + long long dfs(int n, const vector& locations, int finish, int cur, int fuel, + vector>& dp){ + + if(fuel < 0) return 0; + if(dp[cur][fuel] != -1) return dp[cur][fuel]; + + long long res = 0; + if(cur == finish) res = 1; + for(int i = 0; i < n; i ++){ + if(i == cur) continue; + res += dfs(n, locations, finish, i, fuel - abs(locations[i] - locations[cur]), dp); + } + return dp[cur][fuel] = res % MOD; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1576-Replace-All-Question-Marks-to-Avoid-Consecutive-Repeating-Characters/cpp-1576/CMakeLists.txt b/1501-2000/1576-Replace-All-Question-Marks-to-Avoid-Consecutive-Repeating-Characters/cpp-1576/CMakeLists.txt new file mode 100644 index 00000000..ba20c1de --- /dev/null +++ b/1501-2000/1576-Replace-All-Question-Marks-to-Avoid-Consecutive-Repeating-Characters/cpp-1576/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/1501-2000/1577-Number-of-Ways-Where-Square-of-Number-Is-Equal-to-Product-of-Two-Numbers/cpp-1577/CMakeLists.txt b/1501-2000/1577-Number-of-Ways-Where-Square-of-Number-Is-Equal-to-Product-of-Two-Numbers/cpp-1577/CMakeLists.txt new file mode 100644 index 00000000..81ad8b42 --- /dev/null +++ b/1501-2000/1577-Number-of-Ways-Where-Square-of-Number-Is-Equal-to-Product-of-Two-Numbers/cpp-1577/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1501-2000/1577-Number-of-Ways-Where-Square-of-Number-Is-Equal-to-Product-of-Two-Numbers/cpp-1577/main.cpp b/1501-2000/1577-Number-of-Ways-Where-Square-of-Number-Is-Equal-to-Product-of-Two-Numbers/cpp-1577/main.cpp new file mode 100644 index 00000000..3f85b3f3 --- /dev/null +++ b/1501-2000/1577-Number-of-Ways-Where-Square-of-Number-Is-Equal-to-Product-of-Two-Numbers/cpp-1577/main.cpp @@ -0,0 +1,61 @@ +/// Source : https://leetcode.com/problems/number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/ +/// Author : liuyubobobo +/// Time : 2020-09-05 + +#include +#include +#include + +using namespace std; + + +/// HashMap +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { +public: + int numTriplets(vector& nums1, vector& nums2) { + + unordered_map p1; + for(int i = 0; i < nums1.size(); i ++) + for(int j = i + 1; j < nums1.size(); j ++) + p1[(long long)nums1[i] * (long long)nums1[j]] ++; + + unordered_map p2; + for(int i = 0; i < nums2.size(); i ++) + for(int j = i + 1; j < nums2.size(); j ++) + p2[(long long)nums2[i] * (long long)nums2[j]] ++; + + int res = 0; + for(int e: nums1) + res += p2[(long long)e * (long long)e]; + + for(int e: nums2) + res += p1[(long long)e * (long long)e]; + + return res; + } +}; + + + +int main() { + + vector nums11 = {7,4}, nums12 = {5,2,8,9}; + cout << Solution().numTriplets(nums11, nums12) << endl; + // 1 + + vector nums21 = {1,1}, nums22 = {1,1,1}; + cout << Solution().numTriplets(nums21, nums22) << endl; + // 9 + + vector nums31 = {7,7,8,3}, nums32 = {1,2,9,7}; + cout << Solution().numTriplets(nums31, nums32) << endl; + // 2 + + vector nums41 = {4,7,9,11,23}, nums42 = {3,5,1024,12,18}; + cout << Solution().numTriplets(nums41, nums42) << endl; + // 0 + + return 0; +} diff --git a/1501-2000/1578-Minimum-Deletion-Cost-to-Avoid-Repeating-Letters/cpp-1578/CMakeLists.txt b/1501-2000/1578-Minimum-Deletion-Cost-to-Avoid-Repeating-Letters/cpp-1578/CMakeLists.txt new file mode 100644 index 00000000..80fb8c61 --- /dev/null +++ b/1501-2000/1578-Minimum-Deletion-Cost-to-Avoid-Repeating-Letters/cpp-1578/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main2.cpp) \ No newline at end of file diff --git a/1501-2000/1578-Minimum-Deletion-Cost-to-Avoid-Repeating-Letters/cpp-1578/main.cpp b/1501-2000/1578-Minimum-Deletion-Cost-to-Avoid-Repeating-Letters/cpp-1578/main.cpp new file mode 100644 index 00000000..a07603a1 --- /dev/null +++ b/1501-2000/1578-Minimum-Deletion-Cost-to-Avoid-Repeating-Letters/cpp-1578/main.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/minimum-deletion-cost-to-avoid-repeating-letters/ +/// Author : liuyubobobo +/// Time : 2020-09-05 + +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int minCost(string s, vector& cost) { + + vector> dp(27, vector(s.size(), -1)); + return dfs(s, cost, 26, 0, dp); + } + +private: + int dfs(const string& s, const vector& cost, int pre, int index, + vector>& dp){ + + if(index == s.size()) return 0; + if(dp[pre][index] != -1) return dp[pre][index]; + + int res = cost[index] + dfs(s, cost, pre, index + 1, dp); + if(pre != s[index] - 'a') + res = min(res, dfs(s, cost, s[index] - 'a', index + 1, dp)); + return dp[pre][index] = res; + } +}; + + +int main() { + + vector cost1 = {1,2,3,4,5}; + cout << Solution().minCost("abaac", cost1) << endl; + // 3 + + vector cost2 = {1,2,3}; + cout << Solution().minCost("abc", cost2) << endl; + // 0 + + vector cost3 = {1,2,3, 4, 1}; + cout << Solution().minCost("aabaa", cost3) << endl; + // 2 + + return 0; +} diff --git a/1501-2000/1578-Minimum-Deletion-Cost-to-Avoid-Repeating-Letters/cpp-1578/main2.cpp b/1501-2000/1578-Minimum-Deletion-Cost-to-Avoid-Repeating-Letters/cpp-1578/main2.cpp new file mode 100644 index 00000000..6b71bdcd --- /dev/null +++ b/1501-2000/1578-Minimum-Deletion-Cost-to-Avoid-Repeating-Letters/cpp-1578/main2.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/minimum-deletion-cost-to-avoid-repeating-letters/ +/// Author : liuyubobobo +/// Time : 2020-10-17 + +#include +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int minCost(string s, vector& cost) { + + int res = 0; + for(int start = 0, i = 1; i <= s.size(); i ++) + if(i == s.size() || s[i] != s[start]){ + res += accumulate(cost.begin() + start, cost.begin() + i, 0) - *max_element(cost.begin() + start, cost.begin() + i); + start = i; + i = start; + } + return res; + } +}; + + +int main() { + + vector cost1 = {1,2,3,4,5}; + cout << Solution().minCost("abaac", cost1) << endl; + // 3 + + vector cost2 = {1,2,3}; + cout << Solution().minCost("abc", cost2) << endl; + // 0 + + vector cost3 = {1,2,3, 4, 1}; + cout << Solution().minCost("aabaa", cost3) << endl; + // 2 + + return 0; +} diff --git a/1501-2000/1579-Remove-Max-Number-of-Edges-to-Keep-Graph-Fully-Traversable/cpp-1579/CMakeLists.txt b/1501-2000/1579-Remove-Max-Number-of-Edges-to-Keep-Graph-Fully-Traversable/cpp-1579/CMakeLists.txt new file mode 100644 index 00000000..74cc3ee6 --- /dev/null +++ b/1501-2000/1579-Remove-Max-Number-of-Edges-to-Keep-Graph-Fully-Traversable/cpp-1579/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) \ No newline at end of file diff --git a/1501-2000/1579-Remove-Max-Number-of-Edges-to-Keep-Graph-Fully-Traversable/cpp-1579/main.cpp b/1501-2000/1579-Remove-Max-Number-of-Edges-to-Keep-Graph-Fully-Traversable/cpp-1579/main.cpp new file mode 100644 index 00000000..bde90b8a --- /dev/null +++ b/1501-2000/1579-Remove-Max-Number-of-Edges-to-Keep-Graph-Fully-Traversable/cpp-1579/main.cpp @@ -0,0 +1,103 @@ +/// Source : https://leetcode.com/problems/remove-max-number-of-edges-to-keep-graph-fully-traversable/ +/// Author : liuyubobobo +/// Time : 2020-09-05 + +#include +#include + +using namespace std; + + +/// Kruskal +/// Time Complexity: O(e) +/// Space Complexity: O(e) +class UF{ + +private: + vector parent; + +public: + UF(int n){ + for(int i = 0 ; i < n ; i ++) + parent.push_back(i); + } + + int find(int p){ + if( p != parent[p] ) + parent[p] = find( parent[p] ); + return parent[p]; + } + + bool isConnected(int p , int q){ + return find(p) == find(q); + } + + void unionElements(int p, int q){ + + int pRoot = find(p); + int qRoot = find(q); + + if( pRoot == qRoot ) + return; + + parent[pRoot] = qRoot; + } +}; + +class Solution { +public: + int maxNumEdgesToRemove(int n, vector>& edges) { + + int del = 0; + + vector> type[3]; + for(const vector& e: edges) + type[e[0] - 1].push_back({e[1] - 1, e[2] - 1}); + + UF uf1(n), uf2(n); + for(const pair& p: type[2]) + if(uf1.isConnected(p.first, p.second)) del ++; + else{ + uf1.unionElements(p.first, p.second); + uf2.unionElements(p.first, p.second); + } + + for(const pair& p: type[0]) + if(uf1.isConnected(p.first, p.second)) del ++; + else uf1.unionElements(p.first, p.second); + + for(const pair& p: type[1]) + if(uf2.isConnected(p.first, p.second)) del ++; + else uf2.unionElements(p.first, p.second); + + for(int i = 1; i < n; i ++) { + if (!uf1.isConnected(i - 1, i)) return -1; + if (!uf2.isConnected(i - 1, i)) return -1; + } + return del; + } +}; + + +int main() { + + vector> edges1 = { + {3,1,2},{3,2,3},{1,1,3},{1,2,4},{1,1,2},{2,3,4} + }; + cout << Solution().maxNumEdgesToRemove(4, edges1) << endl; + // 2 + + vector> edges2 = { + {3,1,2},{3,2,3},{1,1,4},{2,1,4} + }; + cout << Solution().maxNumEdgesToRemove(4, edges2) << endl; + // 0 + + vector> edges3 = { + {3,2,3},{1,1,2},{2,3,4} + }; + cout << Solution().maxNumEdgesToRemove(4, edges3) << endl; + // -1 + + return 0; +} diff --git a/1501-2000/1580-Put-Boxes-Into-the-Warehouse-II/cpp-1580/CMakeLists.txt b/1501-2000/1580-Put-Boxes-Into-the-Warehouse-II/cpp-1580/CMakeLists.txt new file mode 100644 index 00000000..92fc5ea4 --- /dev/null +++ b/1501-2000/1580-Put-Boxes-Into-the-Warehouse-II/cpp-1580/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1580) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1580 main.cpp) \ No newline at end of file diff --git a/1501-2000/1580-Put-Boxes-Into-the-Warehouse-II/cpp-1580/main.cpp b/1501-2000/1580-Put-Boxes-Into-the-Warehouse-II/cpp-1580/main.cpp new file mode 100644 index 00000000..69317fd8 --- /dev/null +++ b/1501-2000/1580-Put-Boxes-Into-the-Warehouse-II/cpp-1580/main.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/put-boxes-into-the-warehouse-ii/ +/// Author : liuyubobobo +/// Time : 2020-10-16 + +#include +#include + +using namespace std; + + +/// Sorting and Greedy and Two Pointers +/// Time Complexity: O(nlogn + mlogm + (n + m)) +/// Space Complexity: O(1) +class Solution { +public: + int maxBoxesInWarehouse(vector& boxes, vector& warehouse) { + + int index = min_element(warehouse.begin(), warehouse.end()) - warehouse.begin(); + + int cur = warehouse[0]; + for(int i = 0; i < index; i ++){ + warehouse[i] = min(warehouse[i], cur); + cur = warehouse[i]; + } + + cur = warehouse.back(); + for(int i = warehouse.size() - 1; i > index; i --){ + warehouse[i] = min(warehouse[i], cur); + cur = warehouse[i]; + } + + sort(warehouse.begin(), warehouse.end()); + sort(boxes.begin(), boxes.end()); + + int i = 0, j = 0, res = 0; + while(i < warehouse.size() && j < boxes.size()) + if(warehouse[i] >= boxes[j]) i ++, j ++, res ++; + else i ++; + return res; + } +}; + + +int main() { + + vector box1 = {1, 2, 2, 3, 4}, warehouse1 = {3, 4, 1, 2}; + cout << Solution().maxBoxesInWarehouse(box1, warehouse1) << endl; + + return 0; +} diff --git a/1501-2000/1582-Special-Positions-in-a-Binary-Matrix/cpp-1582/CMakeLists.txt b/1501-2000/1582-Special-Positions-in-a-Binary-Matrix/cpp-1582/CMakeLists.txt new file mode 100644 index 00000000..ec9e7c4c --- /dev/null +++ b/1501-2000/1582-Special-Positions-in-a-Binary-Matrix/cpp-1582/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main2.cpp) \ No newline at end of file diff --git a/1501-2000/1582-Special-Positions-in-a-Binary-Matrix/cpp-1582/main.cpp b/1501-2000/1582-Special-Positions-in-a-Binary-Matrix/cpp-1582/main.cpp new file mode 100644 index 00000000..77e4977e --- /dev/null +++ b/1501-2000/1582-Special-Positions-in-a-Binary-Matrix/cpp-1582/main.cpp @@ -0,0 +1,62 @@ +/// Source : https://leetcode.com/problems/special-positions-in-a-binary-matrix/ +/// Author : liuyubobobo +/// Time : 2020-09-12 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n^3) +/// Space Complexity: O(1) +class Solution { +public: + int numSpecial(vector>& mat) { + + int R = mat.size(), C = mat[0].size(), res = 0; + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++) + if(mat[i][j] && special(mat, i, j, R, C)) res ++; + return res; + } + +private: + bool special(const vector>& mat, int x, int y, int R, int C){ + + for(int i = 0; i < R; i ++) + if(i != x && mat[i][y] == 1) return false; + + for(int j = 0; j < C; j ++) + if(j != y && mat[x][j] == 1) return false; + + return true; + } +}; + + +int main() { + + vector> mat1 = {{1,0,0}, {0,0,1},{1,0,0}}; + cout << Solution().numSpecial(mat1) << endl; + // 1 + + vector> mat2 = {{1,0,0}, {0,1,0},{0,0,1}}; + cout << Solution().numSpecial(mat2) << endl; + // 3 + + vector> mat3 = {{0,0,0,1}, {1,0,0,0},{0,1,1,0},{0, 0, 0, 0}}; + cout << Solution().numSpecial(mat3) << endl; + // 2 + + vector> mat4 = {{0,0,0,0,0}, {1,0,0,0,0},{0,1,0,0,0},{0, 0, 1,0, 0}, {0,0,0,1,1}}; + cout << Solution().numSpecial(mat4) << endl; + // 3 + + vector> mat5 = {{0,0,1,0}, {0,0,0,0},{0,0,0,0},{0, 1,0, 0}}; + cout << Solution().numSpecial(mat5) << endl; + // 2 + + return 0; +} diff --git a/1501-2000/1582-Special-Positions-in-a-Binary-Matrix/cpp-1582/main2.cpp b/1501-2000/1582-Special-Positions-in-a-Binary-Matrix/cpp-1582/main2.cpp new file mode 100644 index 00000000..b70c5236 --- /dev/null +++ b/1501-2000/1582-Special-Positions-in-a-Binary-Matrix/cpp-1582/main2.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/special-positions-in-a-binary-matrix/ +/// Author : liuyubobobo +/// Time : 2020-10-16 + +#include +#include + +using namespace std; + + +/// Two Passes +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { +public: + int numSpecial(vector>& mat) { + + int R = mat.size(), C = mat[0].size(); + vector row(R, 0), col(C, 0); + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++) + if(mat[i][j]) row[i] ++, col[j] ++; + + int res = 0; + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++) + if(mat[i][j] && row[i] == 1 && col[j] == 1) + res ++; + return res; + } +}; + + +int main() { + + vector> mat1 = {{1,0,0}, {0,0,1},{1,0,0}}; + cout << Solution().numSpecial(mat1) << endl; + // 1 + + vector> mat2 = {{1,0,0}, {0,1,0},{0,0,1}}; + cout << Solution().numSpecial(mat2) << endl; + // 3 + + vector> mat3 = {{0,0,0,1}, {1,0,0,0},{0,1,1,0},{0, 0, 0, 0}}; + cout << Solution().numSpecial(mat3) << endl; + // 2 + + vector> mat4 = {{0,0,0,0,0}, {1,0,0,0,0},{0,1,0,0,0},{0, 0, 1,0, 0}, {0,0,0,1,1}}; + cout << Solution().numSpecial(mat4) << endl; + // 3 + + vector> mat5 = {{0,0,1,0}, {0,0,0,0},{0,0,0,0},{0, 1,0, 0}}; + cout << Solution().numSpecial(mat5) << endl; + // 2 + + return 0; +} diff --git a/1501-2000/1583-Count-Unhappy-Friends/cpp-1583/CMakeLists.txt b/1501-2000/1583-Count-Unhappy-Friends/cpp-1583/CMakeLists.txt new file mode 100644 index 00000000..81ad8b42 --- /dev/null +++ b/1501-2000/1583-Count-Unhappy-Friends/cpp-1583/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1501-2000/1583-Count-Unhappy-Friends/cpp-1583/main.cpp b/1501-2000/1583-Count-Unhappy-Friends/cpp-1583/main.cpp new file mode 100644 index 00000000..17440ee7 --- /dev/null +++ b/1501-2000/1583-Count-Unhappy-Friends/cpp-1583/main.cpp @@ -0,0 +1,73 @@ +/// Source : https://leetcode.com/problems/count-unhappy-friends/ +/// Author : liuyubobobo +/// Time : 2020-09-12 + +#include +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n^2) +/// Space Complexity: O(n^2) +class Solution { +public: + int unhappyFriends(int n, vector>& preferences, vector>& pairs) { + + vector> pref(n, vector(n, -1)); + for(int i = 0; i < n; i ++) + for(int j = 0; j < preferences[i].size(); j ++) + pref[i][preferences[i][j]] = j; + + unordered_set res; + for(int i = 0; i < pairs.size(); i ++) + for(int j = i + 1; j < pairs.size(); j ++){ + + int x = pairs[i][0], y = pairs[i][1], u = pairs[j][0], v = pairs[j][1]; + if(ok(pref, x, y, u, v)) res.insert(x); + if(ok(pref, x, y, v, u)) res.insert(x); + if(ok(pref, y, x, u, v)) res.insert(y); + if(ok(pref, y, x, v, u)) res.insert(y); + if(ok(pref, u, v, x, y)) res.insert(u); + if(ok(pref, u, v, y, x)) res.insert(u); + if(ok(pref, v, u, x, y)) res.insert(v); + if(ok(pref, v, u, y, x)) res.insert(v); + } + + return res.size(); + } + +private: + bool ok(const vector>& pref, int x, int y, int u, int v){ + return pref[x][u] < pref[x][y] && pref[u][x] < pref[u][v]; + } +}; + + +int main() { + + vector> preferences1 = { + {1, 2, 3}, {3, 2, 0}, {3, 1, 0}, {1, 2, 0} + }; + vector> pairs1 = {{0, 1}, {2, 3}}; + cout << Solution().unhappyFriends(4, preferences1, pairs1) << endl; + // 2 + + vector> preferences2 = { + {1}, {0} + }; + vector> pairs2 = {{1, 0}}; + cout << Solution().unhappyFriends(2, preferences2, pairs2) << endl; + // 0 + + vector> preferences3 = { + {1, 3, 2}, {2, 3, 0}, {1, 3, 0}, {0, 2, 1} + }; + vector> pairs3 = {{1, 3}, {0, 2}}; + cout << Solution().unhappyFriends(4, preferences3, pairs3) << endl; + // 4 + + return 0; +} \ No newline at end of file diff --git a/1501-2000/1584-Min-Cost-to-Connect-All-Points/cpp-1584/CMakeLists.txt b/1501-2000/1584-Min-Cost-to-Connect-All-Points/cpp-1584/CMakeLists.txt new file mode 100644 index 00000000..ce73aee9 --- /dev/null +++ b/1501-2000/1584-Min-Cost-to-Connect-All-Points/cpp-1584/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1501-2000/1584-Min-Cost-to-Connect-All-Points/cpp-1584/main.cpp b/1501-2000/1584-Min-Cost-to-Connect-All-Points/cpp-1584/main.cpp new file mode 100644 index 00000000..8ef3a724 --- /dev/null +++ b/1501-2000/1584-Min-Cost-to-Connect-All-Points/cpp-1584/main.cpp @@ -0,0 +1,112 @@ +/// Source : https://leetcode.com/problems/min-cost-to-connect-all-points/ +/// Author : liuyubobobo +/// Time : 2020-09-12 + +#include +#include + +using namespace std; + + +/// Kruskal MST +/// Time Complexity: O(n^2log(n^2)) +/// Space Complexity: O(n) +class UF{ + +private: + vector parent; + +public: + UF(int n){ + for(int i = 0 ; i < n ; i ++) + parent.push_back(i); + } + + int find(int p){ + if( p != parent[p] ) + parent[p] = find( parent[p] ); + return parent[p]; + } + + bool isConnected(int p , int q){ + return find(p) == find(q); + } + + void unionElements(int p, int q){ + + int pRoot = find(p); + int qRoot = find(q); + + if( pRoot == qRoot ) + return; + + parent[pRoot] = qRoot; + } +}; + +class Solution { +public: + int minCostConnectPoints(vector>& points) { + + int n = points.size(); + + vector>> edges; + for(int i = 0; i < n; i ++) + for(int j = i + 1; j < n; j ++) + edges.push_back({dis(points[i], points[j]), {i, j}}); + + sort(edges.begin(), edges.end()); + + int res = 0; + UF uf(n); + for(const pair>& e: edges){ + int w = e.first, a = e.second.first, b = e.second.second; + if(!uf.isConnected(a, b)){ + res += w; + uf.unionElements(a, b); + } + } + return res; + } + +private: + int dis(const vector& p1, const vector& p2){ + return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1]); + } +}; + + +int main() { + + vector> points1 = { + {0,0},{2,2},{3,10},{5,2},{7,0} + }; + cout << Solution().minCostConnectPoints(points1) << endl; + // 20 + + vector> points2 = { + {3,12},{-2,5},{-4,1} + }; + cout << Solution().minCostConnectPoints(points2) << endl; + // 18 + + vector> points3 = { + {0,0},{1,1},{1,0},{-1,1} + }; + cout << Solution().minCostConnectPoints(points3) << endl; + // 4 + + vector> points4 = { + {-1000000,-1000000},{1000000,1000000} + }; + cout << Solution().minCostConnectPoints(points4) << endl; + // 400000 + + vector> points5 = { + {0, 0} + }; + cout << Solution().minCostConnectPoints(points5) << endl; + // 0 + + return 0; +} \ No newline at end of file diff --git a/1501-2000/1585-Check-If-String-Is-Transformable-With-Substring-Sort-Operations/cpp-1585/CMakeLists.txt b/1501-2000/1585-Check-If-String-Is-Transformable-With-Substring-Sort-Operations/cpp-1585/CMakeLists.txt new file mode 100644 index 00000000..a373769d --- /dev/null +++ b/1501-2000/1585-Check-If-String-Is-Transformable-With-Substring-Sort-Operations/cpp-1585/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main2.cpp) \ No newline at end of file diff --git a/1501-2000/1585-Check-If-String-Is-Transformable-With-Substring-Sort-Operations/cpp-1585/main.cpp b/1501-2000/1585-Check-If-String-Is-Transformable-With-Substring-Sort-Operations/cpp-1585/main.cpp new file mode 100644 index 00000000..f0c96097 --- /dev/null +++ b/1501-2000/1585-Check-If-String-Is-Transformable-With-Substring-Sort-Operations/cpp-1585/main.cpp @@ -0,0 +1,56 @@ +/// Source : https://leetcode.com/problems/check-if-string-is-transformable-with-substring-sort-operations/ +/// Author : liuyubobobo +/// Time : 2020-10-16 + +#include +#include +#include + +using namespace std; + + +/// 10 queues +/// see here for reference: https://leetcode.com/problems/check-if-string-is-transformable-with-substring-sort-operations/discuss/843927/Python-O(10*n)-using-queue +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +public: + bool isTransformable(string s, string t) { + + vector> table(10); + for(int i = 0; i < s.size(); i ++) + table[s[i] - '0'].push(i); + + for(int i = 0; i < t.size(); i ++){ + int a = t[i] - '0'; + if(table[a].empty()) return false; + + for(int j = 0; j < a; j ++) + if(!table[j].empty() && table[j].front() < table[a].front()) return false; + table[a].pop(); + } + return true; + } +}; + + +int main() { + + cout << Solution().isTransformable("84532", "34852") << endl; + // 1 + + cout << Solution().isTransformable("34521", "23415") << endl; + // 1 + + cout << Solution().isTransformable("12345", "12435") << endl; + // 0 + + cout << Solution().isTransformable("1", "2") << endl; + // 0 + + cout << Solution().isTransformable("107595414", "150457194") << endl; + // 0 + + return 0; +} \ No newline at end of file diff --git a/1501-2000/1585-Check-If-String-Is-Transformable-With-Substring-Sort-Operations/cpp-1585/main2.cpp b/1501-2000/1585-Check-If-String-Is-Transformable-With-Substring-Sort-Operations/cpp-1585/main2.cpp new file mode 100644 index 00000000..fefdb5ca --- /dev/null +++ b/1501-2000/1585-Check-If-String-Is-Transformable-With-Substring-Sort-Operations/cpp-1585/main2.cpp @@ -0,0 +1,56 @@ +/// Source : https://leetcode.com/problems/check-if-string-is-transformable-with-substring-sort-operations/ +/// Author : liuyubobobo +/// Time : 2020-10-16 + +#include +#include +#include + +using namespace std; + + +/// 10 queues in reverse order +/// see here for reference: https://leetcode.com/problems/check-if-string-is-transformable-with-substring-sort-operations/discuss/843927/Python-O(10*n)-using-queue +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +public: + bool isTransformable(string s, string t) { + + vector> table(10); + for(int i = s.size() - 1; i >= 0; i --) + table[s[i] - '0'].push(i); + + for(int i = t.size() - 1; i >= 0; i --){ + int a = t[i] - '0'; + if(table[a].empty()) return false; + + for(int j = a + 1; j < 10; j ++) + if(!table[j].empty() && table[j].front() > table[a].front()) return false; + table[a].pop(); + } + return true; + } +}; + + +int main() { + + cout << Solution().isTransformable("84532", "34852") << endl; + // 1 + + cout << Solution().isTransformable("34521", "23415") << endl; + // 1 + + cout << Solution().isTransformable("12345", "12435") << endl; + // 0 + + cout << Solution().isTransformable("1", "2") << endl; + // 0 + + cout << Solution().isTransformable("107595414", "150457194") << endl; + // 0 + + return 0; +} \ No newline at end of file diff --git a/1501-2000/1586-Binary-Search-Tree-Iterator-II/cpp-1586/CMakeLists.txt b/1501-2000/1586-Binary-Search-Tree-Iterator-II/cpp-1586/CMakeLists.txt new file mode 100644 index 00000000..691b540f --- /dev/null +++ b/1501-2000/1586-Binary-Search-Tree-Iterator-II/cpp-1586/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1586) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1586 main.cpp) \ No newline at end of file diff --git a/1501-2000/1586-Binary-Search-Tree-Iterator-II/cpp-1586/main.cpp b/1501-2000/1586-Binary-Search-Tree-Iterator-II/cpp-1586/main.cpp new file mode 100644 index 00000000..99a30e1f --- /dev/null +++ b/1501-2000/1586-Binary-Search-Tree-Iterator-II/cpp-1586/main.cpp @@ -0,0 +1,67 @@ +/// Source : https://leetcode.com/problems/build-binary-expression-tree-from-infix-expression/ +/// Author : liuyubobobo +/// Time : 2020-10-15 + +#include +#include + +using namespace std; + + +/// Inoder to store all the elements +/// Time Complexity: init: O(n) +/// others: O(1) +/// Space Complexity: O(n) + +/// 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 BSTIterator { + +private: + vector v; + int p = -1; + +public: + BSTIterator(TreeNode* root): v(), p(-1) { + inorder(root); + } + + bool hasNext() { + return p + 1 < v.size(); + } + + int next() { + return v[++p]; + } + + bool hasPrev() { + return p - 1 >= 0; + } + + int prev() { + return v[--p]; + } + +private: + void inorder(TreeNode* node){ + + if(!node) return; + inorder(node->left); + v.push_back(node->val); + inorder(node->right); + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1588-Sum-of-All-Odd-Length-Subarrays/cpp-1588/CMakeLists.txt b/1501-2000/1588-Sum-of-All-Odd-Length-Subarrays/cpp-1588/CMakeLists.txt new file mode 100644 index 00000000..44b897b5 --- /dev/null +++ b/1501-2000/1588-Sum-of-All-Odd-Length-Subarrays/cpp-1588/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1588) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1588 main3.cpp) \ No newline at end of file diff --git a/1501-2000/1588-Sum-of-All-Odd-Length-Subarrays/cpp-1588/main.cpp b/1501-2000/1588-Sum-of-All-Odd-Length-Subarrays/cpp-1588/main.cpp new file mode 100644 index 00000000..4bff9cf7 --- /dev/null +++ b/1501-2000/1588-Sum-of-All-Odd-Length-Subarrays/cpp-1588/main.cpp @@ -0,0 +1,43 @@ +/// Source : https://leetcode-cn.com/problems/sum-of-all-odd-length-subarrays/ +/// Author : liuyubobobo +/// Time : 2020-09-19 + +#include +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n^3) +/// Space Complexity: O(1) +class Solution { +public: + int sumOddLengthSubarrays(vector& arr) { + + int res = 0; + for(int i = 0; i < arr.size(); i ++) + for(int sz = 1; i + sz - 1 < arr.size(); sz += 2) + res += accumulate(arr.begin() + i, arr.begin() + i + sz, 0); + return res; + } +}; + + +int main() { + + vector arr1 = {1, 4, 2, 5, 3}; + cout << Solution().sumOddLengthSubarrays(arr1) << endl; + // 58 + + vector arr2 = {1, 2}; + cout << Solution().sumOddLengthSubarrays(arr2) << endl; + // 3 + + vector arr3 = {10,11,12}; + cout << Solution().sumOddLengthSubarrays(arr3) << endl; + // 66 + + return 0; +} diff --git a/1501-2000/1588-Sum-of-All-Odd-Length-Subarrays/cpp-1588/main2.cpp b/1501-2000/1588-Sum-of-All-Odd-Length-Subarrays/cpp-1588/main2.cpp new file mode 100644 index 00000000..c6ae4f29 --- /dev/null +++ b/1501-2000/1588-Sum-of-All-Odd-Length-Subarrays/cpp-1588/main2.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode-cn.com/problems/sum-of-all-odd-length-subarrays/ +/// Author : liuyubobobo +/// Time : 2020-09-19 + +#include +#include + +using namespace std; + + +/// Presum +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { +public: + int sumOddLengthSubarrays(vector& arr) { + + vector presum = {0}; + for(int e: arr) presum.push_back(presum.back() + e); + + int res = 0; + for(int i = 0; i < arr.size(); i ++) + for(int sz = 1; i + sz - 1 < arr.size(); sz += 2) + res += presum[i + sz] - presum[i]; + + return res; + } +}; + + +int main() { + + vector arr1 = {1, 4, 2, 5, 3}; + cout << Solution().sumOddLengthSubarrays(arr1) << endl; + // 58 + + vector arr2 = {1, 2}; + cout << Solution().sumOddLengthSubarrays(arr2) << endl; + // 3 + + vector arr3 = {10,11,12}; + cout << Solution().sumOddLengthSubarrays(arr3) << endl; + // 66 + + return 0; +} diff --git a/1501-2000/1588-Sum-of-All-Odd-Length-Subarrays/cpp-1588/main3.cpp b/1501-2000/1588-Sum-of-All-Odd-Length-Subarrays/cpp-1588/main3.cpp new file mode 100644 index 00000000..b2a48828 --- /dev/null +++ b/1501-2000/1588-Sum-of-All-Odd-Length-Subarrays/cpp-1588/main3.cpp @@ -0,0 +1,45 @@ +/// Source : https://leetcode-cn.com/problems/sum-of-all-odd-length-subarrays/ +/// Author : liuyubobobo +/// Time : 2020-09-19 + +#include +#include + +using namespace std; + + +/// Mathematics +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int sumOddLengthSubarrays(vector& arr) { + + int res = 0; + for(int i = 0; i < arr.size(); i ++){ + int left = i + 1, right = arr.size() - i, + left_even = (left + 1) / 2, right_even = (right + 1) / 2, + left_odd = left / 2, right_odd = right / 2; + res += (left_even * right_even + left_odd * right_odd) * arr[i]; + } + return res; + } +}; + + +int main() { + + vector arr1 = {1, 4, 2, 5, 3}; + cout << Solution().sumOddLengthSubarrays(arr1) << endl; + // 58 + + vector arr2 = {1, 2}; + cout << Solution().sumOddLengthSubarrays(arr2) << endl; + // 3 + + vector arr3 = {10,11,12}; + cout << Solution().sumOddLengthSubarrays(arr3) << endl; + // 66 + + return 0; +} diff --git a/1501-2000/1589-Maximum-Sum-Obtained-of-Any-Permutation/cpp-1589/CMakeLists.txt b/1501-2000/1589-Maximum-Sum-Obtained-of-Any-Permutation/cpp-1589/CMakeLists.txt new file mode 100644 index 00000000..95e3760c --- /dev/null +++ b/1501-2000/1589-Maximum-Sum-Obtained-of-Any-Permutation/cpp-1589/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1589) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1589 main2.cpp) \ No newline at end of file diff --git a/1501-2000/1589-Maximum-Sum-Obtained-of-Any-Permutation/cpp-1589/main.cpp b/1501-2000/1589-Maximum-Sum-Obtained-of-Any-Permutation/cpp-1589/main.cpp new file mode 100644 index 00000000..a1592547 --- /dev/null +++ b/1501-2000/1589-Maximum-Sum-Obtained-of-Any-Permutation/cpp-1589/main.cpp @@ -0,0 +1,115 @@ +/// Source : https://leetcode.com/problems/maximum-sum-obtained-of-any-permutation/ +/// Author : liuyubobobo +/// Time : 2020-09-19 + +#include +#include + +using namespace std; + + +/// Segment Tree with lazy propagation +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class SegmentTree{ + +private: + int n; + vector tree, lazy; + +public: + SegmentTree(int n): n(n), tree(4 * n, 0), lazy(4 * n, 0){} + + void add(int uL, int uR){ + update(0, 0, n-1, uL, uR); + } + + int query(int index){ + return query(0, 0, n-1, index); + } + +private: + void update(int treeID, int treeL, int treeR, int uL, int uR){ + + if(lazy[treeID]){ + tree[treeID] += (treeR - treeL + 1) * lazy[treeID]; + if(treeL != treeR){ + lazy[2 * treeID + 1] += lazy[treeID]; + lazy[2 * treeID + 2] += lazy[treeID]; + } + lazy[treeID] = 0; + } + + if (treeL > uR || treeR < uL) return; + + if(uL <= treeL && uR >= treeR){ + tree[treeID] += treeR - treeL + 1; + if(treeL != treeR){ + lazy[2 * treeID + 1] ++; + lazy[2 * treeID + 2] ++; + } + return; + } + + int mid = (treeL + treeR) / 2; + update(2 * treeID + 1, treeL, mid, uL, uR); + update(2 * treeID + 2, mid + 1, treeR, uL, uR); + tree[treeID] = tree[treeID * 2 + 1] + tree[treeID * 2 + 2]; + return; + } + + int query(int treeID, int treeL, int treeR, int index){ + + if(lazy[treeID]){ + tree[treeID] += (treeR - treeL + 1) * lazy[treeID]; + if(treeL != treeR){ + lazy[2 * treeID + 1] += lazy[treeID]; + lazy[2 * treeID + 2] += lazy[treeID]; + } + lazy[treeID] = 0; + } + + if(treeL== treeR) return tree[treeID]; + + int mid = (treeL + treeR) / 2; + if(index <= mid) return query(2 * treeID + 1, treeL, mid, index); + return query(2 * treeID + 2, mid + 1, treeR, index); + } +}; + +class Solution { + +private: + const long long MOD = 1e9 + 7; + +public: + int maxSumRangeQuery(vector& nums, vector>& requests) { + + int n = nums.size(); + SegmentTree tree(n); + for(const vector& v: requests) + tree.add(v[0], v[1]); + + vector freq(n); + for(int i = 0; i < n; i ++) freq[i] = tree.query(i); + + sort(freq.begin(), freq.end()); + sort(nums.begin(), nums.end()); + + long long res = 0; + for(int i = n - 1; i >= 0; i --) + res = (res + (long long)nums[i] * freq[i]) % MOD; + return res; + } +}; + + +int main() { + + vector nums1 = {1, 2, 3, 4, 5}; + vector> request1 = {{1, 3}, {0, 1}}; + cout << Solution().maxSumRangeQuery(nums1, request1) << endl; + // 19 + + return 0; +} diff --git a/1501-2000/1589-Maximum-Sum-Obtained-of-Any-Permutation/cpp-1589/main2.cpp b/1501-2000/1589-Maximum-Sum-Obtained-of-Any-Permutation/cpp-1589/main2.cpp new file mode 100644 index 00000000..fb62bb84 --- /dev/null +++ b/1501-2000/1589-Maximum-Sum-Obtained-of-Any-Permutation/cpp-1589/main2.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/maximum-sum-obtained-of-any-permutation/ +/// Author : liuyubobobo +/// Time : 2020-09-19 + +#include +#include + +using namespace std; + + +/// Sweep Line +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { + +private: + const long long MOD = 1e9 + 7; + +public: + int maxSumRangeQuery(vector& nums, vector>& requests) { + + int n = nums.size(); + + vector freq(n + 1); + for(const vector& v: requests) + freq[v[0]] ++, freq[v[1] + 1] --; + + for(int i = 1; i <= n; i ++) + freq[i] += freq[i - 1]; + + sort(freq.begin(), freq.begin() + n); + sort(nums.begin(), nums.end()); + + long long res = 0; + for(int i = n - 1; i >= 0; i --) + res = (res + (long long)nums[i] * freq[i]) % MOD; + return res; + } +}; + + +int main() { + + vector nums1 = {1, 2, 3, 4, 5}; + vector> request1 = {{1, 3}, {0, 1}}; + cout << Solution().maxSumRangeQuery(nums1, request1) << endl; + // 19 + + return 0; +} diff --git a/1501-2000/1590-Make-Sum-Divisible-by-P/cpp-1590/CMakeLists.txt b/1501-2000/1590-Make-Sum-Divisible-by-P/cpp-1590/CMakeLists.txt new file mode 100644 index 00000000..61730dc1 --- /dev/null +++ b/1501-2000/1590-Make-Sum-Divisible-by-P/cpp-1590/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1590) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1590 main.cpp) \ No newline at end of file diff --git a/1501-2000/1590-Make-Sum-Divisible-by-P/cpp-1590/main.cpp b/1501-2000/1590-Make-Sum-Divisible-by-P/cpp-1590/main.cpp new file mode 100644 index 00000000..842b41ac --- /dev/null +++ b/1501-2000/1590-Make-Sum-Divisible-by-P/cpp-1590/main.cpp @@ -0,0 +1,68 @@ +/// Source : https://leetcode.com/problems/make-sum-divisible-by-p/ +/// Author : liuyubobobo +/// Time : 2020-09-19 + +#include +#include +#include +#include + +using namespace std; + + +/// Hash Map +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int minSubarray(vector& nums, int p) { + + long long sum = 0; + for(int e: nums) sum += (long long)e; + long long mod = sum % (long long)p; + + if(mod == 0ll) return 0; + + int res = nums.size(); + unordered_map table; + table[0ll] = -1; + + sum = 0; + for(int i = 0; i < nums.size(); i ++){ + sum += (long long)nums[i]; + long long curmod = sum % (long long)p; + table[curmod] = i; + + long long targetmod = curmod >= mod ? (curmod - mod) : (curmod - mod + p); + if(table.count(targetmod)) + res = min(res, i - table[targetmod]); + } + return res == nums.size() ? -1 : res; + } +}; + + +int main() { + + vector nums1 = {3, 1, 4, 2}; + cout << Solution().minSubarray(nums1, 6) << endl; + // 1 + + vector nums2 = {6, 3, 5, 2}; + cout << Solution().minSubarray(nums2, 9) << endl; + // 2 + + vector nums3 = {1, 2, 3}; + cout << Solution().minSubarray(nums3, 3) << endl; + // 0 + + vector nums4 = {1, 2, 3}; + cout << Solution().minSubarray(nums4, 7) << endl; + // -1 + + vector nums5 = {1000000000,1000000000,1000000000}; + cout << Solution().minSubarray(nums5, 3) << endl; + // 0 + + return 0; +} diff --git a/1501-2000/1591-Strange-Printer-II/cpp-1591/CMakeLists.txt b/1501-2000/1591-Strange-Printer-II/cpp-1591/CMakeLists.txt new file mode 100644 index 00000000..4e96dc23 --- /dev/null +++ b/1501-2000/1591-Strange-Printer-II/cpp-1591/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1591) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1591 main.cpp) \ No newline at end of file diff --git a/1501-2000/1591-Strange-Printer-II/cpp-1591/main.cpp b/1501-2000/1591-Strange-Printer-II/cpp-1591/main.cpp new file mode 100644 index 00000000..759498fd --- /dev/null +++ b/1501-2000/1591-Strange-Printer-II/cpp-1591/main.cpp @@ -0,0 +1,112 @@ +/// Source : https://leetcode.com/problems/strange-printer-ii/ +/// Author : liuyubobobo +/// Time : 2020-09-20 + +#include +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(num^2 * m * n) +/// Space Complexity: O(m * n + num) +class Solution { + +private: + class Rectangle{ + public: + int color, minx, maxx, miny, maxy, cnt; + + Rectangle(int color): color(color), cnt(0), + minx(INT_MAX), maxx(INT_MIN), miny(INT_MAX), maxy(INT_MIN){} + + int diff() const{ + return (maxx - minx + 1) * (maxy - miny + 1) - cnt; + } + }; + +public: + bool isPrintable(vector>& targetGrid) { + + vector table(61, NULL); + + for(int i = 0; i < targetGrid.size(); i ++) + for(int j = 0; j < targetGrid[i].size(); j ++){ + int color = targetGrid[i][j]; + if(!table[color]) + table[color] = new Rectangle(color); + table[color]->minx = min(table[color]->minx, i); + table[color]->maxx = max(table[color]->maxx, i); + table[color]->miny = min(table[color]->miny, j); + table[color]->maxy = max(table[color]->maxy, j); + table[color]->cnt ++; + } + + vector q; + for(int i = 1; i <= 60; i ++) + if(table[i] && table[i]->diff() == 0){ + q.push_back(table[i]); + table[i] = NULL; + } + + while(!q.empty()){ + + Rectangle* cur = q.back(); + q.pop_back(); + + for(int i = 1; i <= 60; i ++) + if(table[i]){ + Rectangle* rec = table[i]; + for(int i = cur->minx; i <= cur->maxx; i ++) + if(rec->minx <= i && i <= rec->maxx) + for(int j = cur->miny; j <= cur->maxy; j ++) + if(rec->miny <= j && j <= rec->maxy) + rec->cnt += (targetGrid[i][j] != 0); + + if(rec->diff() == 0){ + q.push_back(rec); + table[i] = NULL; + } + } + + for(int i = cur->minx; i <= cur->maxx; i ++) + for(int j = cur->miny; j <= cur->maxy; j ++) + targetGrid[i][j] = 0; + } + + for(int i = 1; i <= 60; i ++) if(table[i]) return false; + return true; + } +}; + + +int main() { + + vector> grid1 = { + {1,1,1,1},{1,2,2,1},{1,2,2,1},{1,1,1,1} + }; + cout << Solution().isPrintable(grid1) << endl; + // 1 + + vector> grid2 = { + {1,1,1,1},{1,1,3,3},{1,1,3,4},{5,5,1,4} + }; + cout << Solution().isPrintable(grid2) << endl; + // 1 + + vector> grid3 = { + {1,2,1},{2,1,2},{1,2,1} + }; + cout << Solution().isPrintable(grid3) << endl; + // 0 + + vector> grid4 = { + {1,1,1},{3,1,3} + }; + cout << Solution().isPrintable(grid4) << endl; + // 0 + + return 0; +} diff --git a/1501-2000/1592-Rearrange-Spaces-Between-Words/cpp-1592/CMakeLists.txt b/1501-2000/1592-Rearrange-Spaces-Between-Words/cpp-1592/CMakeLists.txt new file mode 100644 index 00000000..d5d5e4ff --- /dev/null +++ b/1501-2000/1592-Rearrange-Spaces-Between-Words/cpp-1592/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1501-2000/1592-Rearrange-Spaces-Between-Words/cpp-1592/main.cpp b/1501-2000/1592-Rearrange-Spaces-Between-Words/cpp-1592/main.cpp new file mode 100644 index 00000000..054050c6 --- /dev/null +++ b/1501-2000/1592-Rearrange-Spaces-Between-Words/cpp-1592/main.cpp @@ -0,0 +1,66 @@ +/// Source : https://leetcode.com/problems/rearrange-spaces-between-words/ +/// Author : liuyubobobo +/// Time : 2020-09-19 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + string reorderSpaces(string text) { + + int spacenum = 0; + for(char c: text) spacenum += (c == ' '); + + vector words; + for(int start = nextletter(text, 0), i = start + 1; i <= text.size(); i ++) + if(i == text.size() || text[i] == ' '){ + words.push_back(text.substr(start, i - start)); + start = nextletter(text, i); + i = start; + } + + if(words.size() == 1) return words[0] + string(spacenum, ' '); + + int interval = spacenum / (words.size() - 1); + string res = ""; + for(int i = 0; i + 1 < words.size(); i ++) + res += words[i] + string(interval, ' '); + res += words.back() + string(spacenum % (words.size() - 1), ' '); + return res; + } + +private: + int nextletter(const string& s, int start){ + for(int i = start; i < s.size(); i ++) + if(s[i] != ' ') return i; + return s.size(); + } +}; + + +int main() { + + string text1 = " this is a sentence "; + cout << Solution().reorderSpaces(text1) << endl; + + string text2 = " practice makes perfect"; + cout << Solution().reorderSpaces(text2) << endl; + + string text3 = "hello world"; + cout << Solution().reorderSpaces(text3) << endl; + + string text4 = " walks udp package into bar a"; + cout << Solution().reorderSpaces(text4) << endl; + + string text5 = "a"; + cout << Solution().reorderSpaces(text5) << endl; + + return 0; +} diff --git a/1501-2000/1593-Split-a-String-Into-the-Max-Number-of-Unique-Substrings/cpp-1593/CMakeLists.txt b/1501-2000/1593-Split-a-String-Into-the-Max-Number-of-Unique-Substrings/cpp-1593/CMakeLists.txt new file mode 100644 index 00000000..81ad8b42 --- /dev/null +++ b/1501-2000/1593-Split-a-String-Into-the-Max-Number-of-Unique-Substrings/cpp-1593/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1501-2000/1593-Split-a-String-Into-the-Max-Number-of-Unique-Substrings/cpp-1593/main.cpp b/1501-2000/1593-Split-a-String-Into-the-Max-Number-of-Unique-Substrings/cpp-1593/main.cpp new file mode 100644 index 00000000..4af650d3 --- /dev/null +++ b/1501-2000/1593-Split-a-String-Into-the-Max-Number-of-Unique-Substrings/cpp-1593/main.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/split-a-string-into-the-max-number-of-unique-substrings/ +/// Author : liuyubobobo +/// Time : 2020-09-19 + +#include +#include +#include + +using namespace std; + + +/// Backtracking +/// Time Complexity: O(|s|^|s|) +/// Space Complexity: O(|s|^2) +class Solution { +public: + int maxUniqueSplit(string s) { + + set bag; + return dfs(s, 0, bag); + } + +private: + int dfs(const string& s, int start, set& bag){ + + if(start == s.size()) + return bag.size(); + + int res = 0; + for(int end = start; end <= s.size(); end ++) + if(!bag.count(s.substr(start, end - start + 1))){ + bag.insert(s.substr(start, end - start + 1)); + res = max(res, dfs(s, end + 1, bag)); + bag.erase(s.substr(start, end - start + 1)); + } + return res; + } +}; + + +int main() { + + cout << Solution().maxUniqueSplit("ababccc") << endl; + // 5 + + cout << Solution().maxUniqueSplit("aba") << endl; + // 2 + + cout << Solution().maxUniqueSplit("aa") << endl; + // 1 + + return 0; +} \ No newline at end of file diff --git a/1501-2000/1594-Maximum-Non-Negative-Product-in-a-Matrix/cpp-1594/CMakeLists.txt b/1501-2000/1594-Maximum-Non-Negative-Product-in-a-Matrix/cpp-1594/CMakeLists.txt new file mode 100644 index 00000000..ce73aee9 --- /dev/null +++ b/1501-2000/1594-Maximum-Non-Negative-Product-in-a-Matrix/cpp-1594/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1501-2000/1594-Maximum-Non-Negative-Product-in-a-Matrix/cpp-1594/main.cpp b/1501-2000/1594-Maximum-Non-Negative-Product-in-a-Matrix/cpp-1594/main.cpp new file mode 100644 index 00000000..73b3148d --- /dev/null +++ b/1501-2000/1594-Maximum-Non-Negative-Product-in-a-Matrix/cpp-1594/main.cpp @@ -0,0 +1,81 @@ +/// Source : https://leetcode.com/problems/maximum-non-negative-product-in-a-matrix/ +/// Author : liuyubobobo +/// Time : 2020-09-19 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(m * n) +/// Space Complexity: O(m * n) +class Solution { + +private: + const long long MOD = 1e9 + 7; + +public: + int maxProductPath(vector>& grid) { + + int R = grid.size(), C = grid[0].size(); + + vector> biggest(R, vector(C, 0ll)); + vector> smallest(R, vector(C, 0ll)); + + smallest[0][0] = biggest[0][0] = grid[0][0]; + for(int i = 1; i < R; i ++) + biggest[i][0] = smallest[i][0] = grid[i][0] * smallest[i - 1][0]; + for(int j = 1; j < C; j ++) + biggest[0][j] = smallest[0][j] = grid[0][j] * smallest[0][j - 1]; + + for(int i = 1; i < R; i ++) + for(int j = 1; j < C; j ++){ + smallest[i][j] = min(min(grid[i][j] * smallest[i - 1][j], grid[i][j] * smallest[i][j - 1]), + min(grid[i][j] * biggest[i - 1][j], grid[i][j] * biggest[i][j - 1])); + biggest[i][j] = max(max(grid[i][j] * smallest[i - 1][j], grid[i][j] * smallest[i][j - 1]), + max(grid[i][j] * biggest[i - 1][j], grid[i][j] * biggest[i][j - 1])); + } + + if(biggest[R - 1][C - 1] >= 0) return biggest[R - 1][C - 1] % MOD; + return -1; + } +}; + + +int main() { + + vector> g1 = { + {-1,-2,-3}, + {-2,-3,-3}, + {-3,-3,-2} + }; + cout << Solution().maxProductPath(g1) << endl; + // -1 + + vector> g2 = { + {1,-2,1}, + {1,-2,1}, + {3,-4,1} + }; + cout << Solution().maxProductPath(g2) << endl; + // 8 + + vector> g3 = { + {1,3}, + {0,-4} + }; + cout << Solution().maxProductPath(g3) << endl; + // 0 + + vector> g4 = { + { 1, 4,4,0}, + {-2, 0,0,1}, + {1,-1,1,1} + }; + cout << Solution().maxProductPath(g4) << endl; + // 2 + + return 0; +} \ No newline at end of file diff --git a/1501-2000/1595-Minimum-Cost-to-Connect-Two-Groups-of-Points/cpp-1595/CMakeLists.txt b/1501-2000/1595-Minimum-Cost-to-Connect-Two-Groups-of-Points/cpp-1595/CMakeLists.txt new file mode 100644 index 00000000..74cc3ee6 --- /dev/null +++ b/1501-2000/1595-Minimum-Cost-to-Connect-Two-Groups-of-Points/cpp-1595/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) \ No newline at end of file diff --git a/1501-2000/1595-Minimum-Cost-to-Connect-Two-Groups-of-Points/cpp-1595/main.cpp b/1501-2000/1595-Minimum-Cost-to-Connect-Two-Groups-of-Points/cpp-1595/main.cpp new file mode 100644 index 00000000..5b0de08e --- /dev/null +++ b/1501-2000/1595-Minimum-Cost-to-Connect-Two-Groups-of-Points/cpp-1595/main.cpp @@ -0,0 +1,78 @@ +/// Source : https://leetcode.com/problems/minimum-cost-to-connect-two-groups-of-points/ +/// Author : liuyubobobo +/// Time : 2020-09-20 + +#include +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(max(m, n) * (1 << m) * (1 << n)) +/// Space Complexity: O((1 << m) * (1 << n)) +class Solution { + +private: + int n, m; + +public: + int connectTwoGroups(vector>& cost) { + + n = cost.size(), m = cost[0].size(); + unordered_map dp; + return dfs(cost, 0, 0, 0, dp); + } + +private: + int dfs(const vector>& c, int state1, int state2, int index, + unordered_map& dp){ + + if(index == n + m) + return 0; + + int hash = state1 * 10000 + state2; + if(dp.count(hash)) return dp[hash]; + + int res = INT_MAX; + if(index < n){ + int p = index; + if(state1 & (1 << p)) return dfs(c, state1, state2, index + 1, dp); + for(int i = 0; i < m; i ++) + res = min(res, c[p][i] + dfs(c, state1 | (1 << p), state2 | (1 << i), index + 1, dp)); + } + else{ + int p = index - n; + if(state2 & (1 << p)) return dfs(c, state1, state2, index + 1, dp); + for(int i = 0; i < n; i ++) + res = min(res, c[i][p] + dfs(c, state1 | (1 << i), state2 | (1 << p), index + 1, dp)); + } + + return dp[hash] = res; + } +}; + + +int main() { + + vector> cost1 = { + {15, 96}, {36, 2} + }; + cout << Solution().connectTwoGroups(cost1) << endl; + // 17 + + vector> cost2 = { + {1, 3, 5}, {4, 1, 1}, {1, 5, 3} + }; + cout << Solution().connectTwoGroups(cost2) << endl; + // 4 + + vector> cost3 = { + {2, 5, 1}, {3, 4, 7}, {8, 1, 2}, {6, 2, 4}, {3, 8, 8} + }; + cout << Solution().connectTwoGroups(cost3) << endl; + // 10 + + return 0; +} \ No newline at end of file diff --git a/1501-2000/1597-Build-Binary-Expression-Tree-From-Infix-Expression/cpp-1597/CMakeLists.txt b/1501-2000/1597-Build-Binary-Expression-Tree-From-Infix-Expression/cpp-1597/CMakeLists.txt new file mode 100644 index 00000000..99495057 --- /dev/null +++ b/1501-2000/1597-Build-Binary-Expression-Tree-From-Infix-Expression/cpp-1597/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1597) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1597 main.cpp) \ No newline at end of file diff --git a/1501-2000/1597-Build-Binary-Expression-Tree-From-Infix-Expression/cpp-1597/main.cpp b/1501-2000/1597-Build-Binary-Expression-Tree-From-Infix-Expression/cpp-1597/main.cpp new file mode 100644 index 00000000..5c58acf5 --- /dev/null +++ b/1501-2000/1597-Build-Binary-Expression-Tree-From-Infix-Expression/cpp-1597/main.cpp @@ -0,0 +1,81 @@ +/// Source : https://leetcode.com/problems/build-binary-expression-tree-from-infix-expression/ +/// Author : liuyubobobo +/// Time : 2020-09-27 + +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// Definition for a binary tree node. +struct Node { + char val; + Node *left; + Node *right; + Node() : val(' '), left(nullptr), right(nullptr) {} + Node(char x) : val(x), left(nullptr), right(nullptr) {} + Node(char x, Node *left, Node *right) : val(x), left(left), right(right) {} +}; + +class Solution { +public: + Node* expTree(string s) { + return dfs(s, 0, s.size() - 1); + } + +private: + Node* dfs(const string& s, int l, int r){ + + if(l > r) return nullptr; + if(l == r) return new Node(s[l]); + + if(s[l] != '('){ + if(s[l + 1] == '+' || s[l + 1] == '-') + return new Node(s[l + 1], new Node(s[l]), dfs(s, l + 2, r)); + + int stack = 0, end = -1; + for(int i = l; i <= r; i ++){ + if(s[i] == '(') stack ++; + else if(s[i] == ')') stack --; + else if(s[i] == '+' || s[i] == '-') + if(!stack){end = i - 1; break;} + } + + if(end == -1) return new Node(s[l + 1], new Node(s[l]), dfs(s, l + 2, r)); + return new Node(s[end + 1], dfs(s, l, end), dfs(s, end + 2, r)); + } + else{ + int stack = 0, end = -1; + for(int i = l; i <= r; i ++){ + if(s[i] == '(') stack ++; + if(s[i] == ')') stack --; + if(!stack){end = i; break;} + } + if(end + 1 <= r) + return new Node(s[end + 1], dfs(s, l + 1, end - 1), dfs(s, end + 2, r)); + return dfs(s, l + 1, r - 1); + } + } +}; + + +void inOrder(const Node* node){ + + if(node == nullptr) return; + inOrder(node->left); + cout << node->val; + inOrder(node->right); +} + +int main() { + + Node* t1 = Solution().expTree("2-3/(5*2)+1"); + inOrder(t1); + + return 0; +} diff --git a/1501-2000/1598-Crawler-Log-Folder/cpp-1598/CMakeLists.txt b/1501-2000/1598-Crawler-Log-Folder/cpp-1598/CMakeLists.txt new file mode 100644 index 00000000..d5d5e4ff --- /dev/null +++ b/1501-2000/1598-Crawler-Log-Folder/cpp-1598/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1501-2000/1598-Crawler-Log-Folder/cpp-1598/main.cpp b/1501-2000/1598-Crawler-Log-Folder/cpp-1598/main.cpp new file mode 100644 index 00000000..4fddd4c3 --- /dev/null +++ b/1501-2000/1598-Crawler-Log-Folder/cpp-1598/main.cpp @@ -0,0 +1,45 @@ +/// Source : https://leetcode.com/problems/crawler-log-folder/ +/// Author : liuyubobobo +/// Time : 2020-09-26 + +#include +#include +#include + +using namespace std; + + +/// Using Stack +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int minOperations(vector& logs) { + + int stack = 0; + for(const string& log: logs){ + if(log == "./") continue; + else if(log == "../") stack = max(0, stack - 1); + else stack ++; + } + return stack; + } +}; + + +int main() { + + vector logs1 = {"d1/","d2/","../","d21/","./"}; + cout << Solution().minOperations(logs1) << endl; + // 2 + + vector logs2 = {"d1/","d2/","./","d3/","../","d31/"}; + cout << Solution().minOperations(logs2) << endl; + // 3 + + vector logs3 = {"d1/","../","../","../"}; + cout << Solution().minOperations(logs3) << endl; + // 0 + + return 0; +} diff --git a/1501-2000/1599-Maximum-Profit-of-Operating-a-Centennial-Wheel/cpp1599/CMakeLists.txt b/1501-2000/1599-Maximum-Profit-of-Operating-a-Centennial-Wheel/cpp1599/CMakeLists.txt new file mode 100644 index 00000000..81ad8b42 --- /dev/null +++ b/1501-2000/1599-Maximum-Profit-of-Operating-a-Centennial-Wheel/cpp1599/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1501-2000/1599-Maximum-Profit-of-Operating-a-Centennial-Wheel/cpp1599/main.cpp b/1501-2000/1599-Maximum-Profit-of-Operating-a-Centennial-Wheel/cpp1599/main.cpp new file mode 100644 index 00000000..ee947e67 --- /dev/null +++ b/1501-2000/1599-Maximum-Profit-of-Operating-a-Centennial-Wheel/cpp1599/main.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/maximum-profit-of-operating-a-centennial-wheel/ +/// Author : liuyubobobo +/// Time : 2020-09-26 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(sum(customers)) +/// Space Complexity: O(1) +class Solution { +public: + int minOperationsMaxProfit(vector& customers, int boardingCost, int runningCost) { + + int k = 0, kres = -1, cp = 0, maxres = 0, curres = 0, waiting = 0; + while(cp < customers.size() || waiting){ + if(cp < customers.size()) waiting += customers[cp]; + cp ++; + + int num = min(4, waiting); + curres += boardingCost * num - runningCost; + waiting -= num; + + k ++; + if(curres > maxres){ + maxres = curres; + kres = k; + } + } + return kres; + } +}; + + +int main() { + + vector customers1 = {8, 3}; + cout << Solution().minOperationsMaxProfit(customers1, 5, 6) << endl; + // 3 + + vector customers2 = {10, 9, 6}; + cout << Solution().minOperationsMaxProfit(customers2, 6, 4) << endl; + // 7 + + vector customers3 = {3,4,0,5,1}; + cout << Solution().minOperationsMaxProfit(customers3, 1, 92) << endl; + // -1 + + vector customers4 = {10,10,6,4,7}; + cout << Solution().minOperationsMaxProfit(customers4, 3, 8) << endl; + // 9 + + return 0; +} diff --git a/1501-2000/1600-Throne-Inheritance/cpp-1600/CMakeLists.txt b/1501-2000/1600-Throne-Inheritance/cpp-1600/CMakeLists.txt new file mode 100644 index 00000000..ce73aee9 --- /dev/null +++ b/1501-2000/1600-Throne-Inheritance/cpp-1600/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1501-2000/1600-Throne-Inheritance/cpp-1600/main.cpp b/1501-2000/1600-Throne-Inheritance/cpp-1600/main.cpp new file mode 100644 index 00000000..1ffe77c7 --- /dev/null +++ b/1501-2000/1600-Throne-Inheritance/cpp-1600/main.cpp @@ -0,0 +1,100 @@ +/// Source : https://leetcode.com/problems/throne-inheritance/ +/// Author : liuyubobobo +/// Time : 2020-09-26 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// Tree +/// Time Complexity: init: O(1) +/// birth: O(1) +/// death: O(1) +/// getInheritanceOrder: O(n) +/// Space Complexity: O(n) +class ThroneInheritance { + +private: + unordered_set live; + unordered_map> R; + string king; + +public: + ThroneInheritance(const string& kingName) : king(kingName) { + live.clear(); + live.insert(kingName); + + R.clear(); + } + + void birth(const string& parentName, const string& childName) { + R[parentName].push_back(childName); + live.insert(childName); + } + + void death(const string& name) { + live.erase(name); + } + + vector getInheritanceOrder() { + + vector res; + dfs(king, res); + return res; + } + +private: + void dfs(const string& name, vector& res){ + + if(live.count(name)) res.push_back(name); + + if(R[name].empty()) return; + + for(const string& s: R[name]) dfs(s, res); + } +}; + + +void print_vec(const vector& v){ + for(const string& e: v) cout << e << " "; cout << endl; +} + +int main() { + + ThroneInheritance t("king"); + + t.birth("king", "andy"); + print_vec(t.getInheritanceOrder()); + // king > andy + + t.birth("king", "bob"); + print_vec(t.getInheritanceOrder()); + // king > andy > bob + + t.birth("king", "catherine"); + print_vec(t.getInheritanceOrder()); + // king > andy > bob > catherine + + t.birth("andy", "matthew"); + print_vec(t.getInheritanceOrder()); + // king > andy > matthew > bob > catherine + + t.birth("bob", "alex"); + print_vec(t.getInheritanceOrder()); + // king > andy > matthew > bob > alex > catherine + + t.birth("bob", "asha"); + print_vec(t.getInheritanceOrder()); + // king > andy > matthew > bob > alex > asha > catherine + + t.death("bob"); + print_vec(t.getInheritanceOrder()); + // king > andy > matthew > bob(death) > alex > asha > catherine + + return 0; +} diff --git a/1501-2000/1601-Maximum-Number-of-Achievable-Transfer-Requests/cpp-1601/CMakeLists.txt b/1501-2000/1601-Maximum-Number-of-Achievable-Transfer-Requests/cpp-1601/CMakeLists.txt new file mode 100644 index 00000000..a373769d --- /dev/null +++ b/1501-2000/1601-Maximum-Number-of-Achievable-Transfer-Requests/cpp-1601/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main2.cpp) \ No newline at end of file diff --git a/1501-2000/1601-Maximum-Number-of-Achievable-Transfer-Requests/cpp-1601/main.cpp b/1501-2000/1601-Maximum-Number-of-Achievable-Transfer-Requests/cpp-1601/main.cpp new file mode 100644 index 00000000..59f1ecca --- /dev/null +++ b/1501-2000/1601-Maximum-Number-of-Achievable-Transfer-Requests/cpp-1601/main.cpp @@ -0,0 +1,62 @@ +/// Source : https://leetcode.com/problems/maximum-number-of-achievable-transfer-requests/ +/// Author : liuyubobobo +/// Time : 2020-09-26 + +#include +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O((n + r)* 2^r) +/// Space Complexity: O(1) +class Solution { +public: + int maximumRequests(int n, vector>& requests) { + + int rnum = requests.size(), res = 0; + for(int i = 0; i < (1 << rnum); i ++) + res = max(res, tryRequest(n, requests, i)); + return res; + } + +private: + int tryRequest(int n, const vector>& requests, int state){ + + vector in(n, 0), out(n, 0); + int index = 0; + while(state){ + if(state % 2){ + out[requests[index][0]] ++; + in[requests[index][1]] ++; + } + + state /= 2; + index ++; + } + + for(int i = 0; i < n; i ++) + if(in[i] != out[i]) return -1; + return accumulate(in.begin(), in.end(), 0); + } +}; + + +int main() { + + vector> r1 = {{0,1},{1,0},{0,1},{1,2},{2,0},{3,4}}; + cout << Solution().maximumRequests(5, r1) << endl; + // 5 + + vector> r2 = {{0,0},{1,2},{2,1}}; + cout << Solution().maximumRequests(3, r2) << endl; + // 3 + + vector> r3 = {{0,3},{3,1},{1,2},{2,0}}; + cout << Solution().maximumRequests(4, r3) << endl; + // 4 + + return 0; +} diff --git a/1501-2000/1601-Maximum-Number-of-Achievable-Transfer-Requests/cpp-1601/main2.cpp b/1501-2000/1601-Maximum-Number-of-Achievable-Transfer-Requests/cpp-1601/main2.cpp new file mode 100644 index 00000000..ba7f9b7b --- /dev/null +++ b/1501-2000/1601-Maximum-Number-of-Achievable-Transfer-Requests/cpp-1601/main2.cpp @@ -0,0 +1,84 @@ +/// Source : https://leetcode.com/problems/maximum-number-of-achievable-transfer-requests/ +/// Author : liuyubobobo +/// Time : 2020-09-26 + +#include +#include +#include +#include + +using namespace std; + + +/// Brute Force with Optimization +/// Time Complexity: O((n + r)* 2^r) +/// Space Complexity: O(1) +class Solution { +public: + int maximumRequests(int n, vector>& requests) { + + int res = 0; + vector indegrees(n, 0), outdegrees(n, 0); + for(const vector& e: requests) + if(e[0] != e[1]) outdegrees[e[0]] ++, indegrees[e[1]] ++; + else res ++; + + vector> rv; + for(const vector& request: requests){ + int a = request[0], b = request[1]; + if(a == b || !indegrees[a] || !indegrees[b] || !outdegrees[a] || !outdegrees[b]) + continue; + rv.push_back(request); + } + + int r = rv.size(), t = 0; + for(int i = 0; i < (1 << r); i ++) + t = max(t, tryRequest(n, rv, i)); + return res + t; + } + +private: + int tryRequest(int n, const vector>& requests, int state){ + + vector in(n, 0), out(n, 0); + int index = 0, res = 0; + while(state){ + if(state & 1){ + out[requests[index][0]] ++; + in[requests[index][1]] ++; + res ++; + } + + state >>= 1, index ++; + } + + if(in != out) return -1; + return res; + } +}; + + +int main() { + + vector> r1 = {{0,1},{1,0},{0,1},{1,2},{2,0},{3,4}}; + cout << Solution().maximumRequests(5, r1) << endl; + // 5 + + vector> r2 = {{0,0},{1,2},{2,1}}; + cout << Solution().maximumRequests(3, r2) << endl; + // 3 + + vector> r3 = {{0,3},{3,1},{1,2},{2,0}}; + cout << Solution().maximumRequests(4, r3) << endl; + // 4 + + vector> r4 = {{1,2},{1,2},{2,2},{0,2},{2,1},{1,1},{1,2}}; + cout << Solution().maximumRequests(3, r4) << endl; + // 4 + + vector> r5 ={{0,3},{3,3},{3,1},{0,1},{3,2},{2,2},{2,0},{1,0},{1,0},{1,2},{2,0},{1,3},{3,0}}; + cout << Solution().maximumRequests(4, r5) << endl; + // 10 + + return 0; +} diff --git a/1501-2000/1602-Find-Nearest-Right-Node-in-Binary-Tree/cpp-1602/CMakeLists.txt b/1501-2000/1602-Find-Nearest-Right-Node-in-Binary-Tree/cpp-1602/CMakeLists.txt new file mode 100644 index 00000000..ee047e54 --- /dev/null +++ b/1501-2000/1602-Find-Nearest-Right-Node-in-Binary-Tree/cpp-1602/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1602) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1602 main2.cpp) \ No newline at end of file diff --git a/1501-2000/1602-Find-Nearest-Right-Node-in-Binary-Tree/cpp-1602/main.cpp b/1501-2000/1602-Find-Nearest-Right-Node-in-Binary-Tree/cpp-1602/main.cpp new file mode 100644 index 00000000..8e1bb877 --- /dev/null +++ b/1501-2000/1602-Find-Nearest-Right-Node-in-Binary-Tree/cpp-1602/main.cpp @@ -0,0 +1,51 @@ +/// Source : https://leetcode.com/problems/find-nearest-right-node-in-binary-tree/ +/// Author : liuyubobobo +/// Time : 2020-10-15 + +#include +#include + +using namespace std; + + +/// BFS, two queues +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// 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* findNearestRightNode(TreeNode* root, TreeNode* u) { + + vector q; + q.push_back(root); + while(!q.empty()){ + + for(int i = 0; i < q.size(); i ++) + if(q[i] == u) return i == q.size() - 1 ? nullptr : q[i + 1]; + + vector q2; + for(TreeNode* node: q){ + if(node->left) q2.push_back(node->left); + if(node->right) q2.push_back(node->right); + } + q = q2; + } + return nullptr; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1602-Find-Nearest-Right-Node-in-Binary-Tree/cpp-1602/main2.cpp b/1501-2000/1602-Find-Nearest-Right-Node-in-Binary-Tree/cpp-1602/main2.cpp new file mode 100644 index 00000000..0f4101cc --- /dev/null +++ b/1501-2000/1602-Find-Nearest-Right-Node-in-Binary-Tree/cpp-1602/main2.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/find-nearest-right-node-in-binary-tree/ +/// Author : liuyubobobo +/// Time : 2020-10-15 + +#include +#include + +using namespace std; + + +/// BFS, one queue and using null as sentinel +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// 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* findNearestRightNode(TreeNode* root, TreeNode* u) { + + queue q; + q.push(root); + q.push(nullptr); + while(!q.empty()){ + + TreeNode* cur = q.front(); + q.pop(); + + if(cur == u) return q.front(); + else if(cur == nullptr) q.push(nullptr); + else{ + if(cur->left) q.push(cur->left); + if(cur->right) q.push(cur->right); + } + } + return nullptr; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1603-Design-Parking-System/cpp-1603/CMakeLists.txt b/1501-2000/1603-Design-Parking-System/cpp-1603/CMakeLists.txt new file mode 100644 index 00000000..328adede --- /dev/null +++ b/1501-2000/1603-Design-Parking-System/cpp-1603/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1603) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1603 main.cpp) \ No newline at end of file diff --git a/1501-2000/1603-Design-Parking-System/cpp-1603/main.cpp b/1501-2000/1603-Design-Parking-System/cpp-1603/main.cpp new file mode 100644 index 00000000..53fa9a48 --- /dev/null +++ b/1501-2000/1603-Design-Parking-System/cpp-1603/main.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/design-parking-system/ +/// Author : liuyubobobo +/// Time : 2020-10-03 + +#include +#include +using namespace std; + + +/// Simulation +/// Time Complexity: O(1) +/// Space Complexity: O(1) +class ParkingSystem { + +private: + vector cap, cur; + +public: + ParkingSystem(int big, int medium, int small): cap(4), cur(4, 0){ + cap[1] = big, cap[2] = medium, cap[3] = small; + } + + bool addCar(int carType) { + + if(cur[carType] + 1 <= cap[carType]){ + cur[carType] ++; + return true; + } + return false; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1604-Alert-Using-Same-Key-Card-Three-or-More-Times-in-a-One-Hour-Period/cpp-1604/CMakeLists.txt b/1501-2000/1604-Alert-Using-Same-Key-Card-Three-or-More-Times-in-a-One-Hour-Period/cpp-1604/CMakeLists.txt new file mode 100644 index 00000000..3eaf395f --- /dev/null +++ b/1501-2000/1604-Alert-Using-Same-Key-Card-Three-or-More-Times-in-a-One-Hour-Period/cpp-1604/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1604) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1604 main2.cpp) \ No newline at end of file diff --git a/1501-2000/1604-Alert-Using-Same-Key-Card-Three-or-More-Times-in-a-One-Hour-Period/cpp-1604/main.cpp b/1501-2000/1604-Alert-Using-Same-Key-Card-Three-or-More-Times-in-a-One-Hour-Period/cpp-1604/main.cpp new file mode 100644 index 00000000..75459351 --- /dev/null +++ b/1501-2000/1604-Alert-Using-Same-Key-Card-Three-or-More-Times-in-a-One-Hour-Period/cpp-1604/main.cpp @@ -0,0 +1,58 @@ +/// Source : https://leetcode.com/problems/alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/ +/// Author : liuyubobobo +/// Time : 2020-10-15 + +#include +#include +#include +#include + +using namespace std; + + +/// Sorting and Sliding Window +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + vector alertNames(vector& keyName, vector& keyTime) { + + vector> v; + for(int i = 0; i < keyName.size(); i ++) + v.push_back({time_to_int(keyTime[i]), keyName[i]}); + + sort(v.begin(), v.end()); + + unordered_map f; + set res; + int l = 0, r = -1; + while(l < v.size()){ + if(r + 1 < v.size() && v[r + 1].first - v[l].first <= 60){ + r ++; + f[v[r].second] ++; + if(f[v[r].second] >= 3) res.insert(v[r].second); + } + else f[v[l ++].second] --; + } + return vector(res.begin(), res.end()); + } + +private: + int time_to_int(const string& t){ + return ((t[0] - '0') * 10 + (t[1] - '0')) * 60 + (t[3] - '0') * 10 + (t[4] - '0'); + } +}; + + +void print_vec(const vector& res){ + for(const string& s: res) cout << s << " "; cout << endl; +} + +int main() { + + vector name1 = {"daniel","daniel","daniel","luis","luis","luis","luis"}; + vector time1 = {"10:00","10:40","11:00","09:00","11:00","13:00","15:00"}; + print_vec(Solution().alertNames(name1, time1)); + + return 0; +} diff --git a/1501-2000/1604-Alert-Using-Same-Key-Card-Three-or-More-Times-in-a-One-Hour-Period/cpp-1604/main2.cpp b/1501-2000/1604-Alert-Using-Same-Key-Card-Three-or-More-Times-in-a-One-Hour-Period/cpp-1604/main2.cpp new file mode 100644 index 00000000..ae4228a2 --- /dev/null +++ b/1501-2000/1604-Alert-Using-Same-Key-Card-Three-or-More-Times-in-a-One-Hour-Period/cpp-1604/main2.cpp @@ -0,0 +1,55 @@ +/// Source : https://leetcode.com/problems/alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/ +/// Author : liuyubobobo +/// Time : 2020-10-15 + +#include +#include +#include +#include + +using namespace std; + + +/// Hashing Table +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + vector alertNames(vector& keyName, vector& keyTime) { + + unordered_map> map; + for(int i = 0; i < keyName.size(); i ++) + map[keyName[i]].push_back(time_to_int(keyTime[i])); + + set res; + for(const pair>& p: map){ + vector t = p.second; + sort(t.begin(), t.end()); + for(int i = 0; i + 2 < p.second.size(); i ++) + if(t[i + 2] - t[i] <= 60){ + res.insert(p.first); + break; + } + } + return vector(res.begin(), res.end()); + } + +private: + int time_to_int(const string& t){ + return ((t[0] - '0') * 10 + (t[1] - '0')) * 60 + (t[3] - '0') * 10 + (t[4] - '0'); + } +}; + + +void print_vec(const vector& res){ + for(const string& s: res) cout << s << " "; cout << endl; +} + +int main() { + + vector name1 = {"daniel","daniel","daniel","luis","luis","luis","luis"}; + vector time1 = {"10:00","10:40","11:00","09:00","11:00","13:00","15:00"}; + print_vec(Solution().alertNames(name1, time1)); + + return 0; +} diff --git a/1501-2000/1605-Find-Valid-Matrix-Given-Row-and-Column-Sums/cpp-1605/CMakeLists.txt b/1501-2000/1605-Find-Valid-Matrix-Given-Row-and-Column-Sums/cpp-1605/CMakeLists.txt new file mode 100644 index 00000000..617ceafd --- /dev/null +++ b/1501-2000/1605-Find-Valid-Matrix-Given-Row-and-Column-Sums/cpp-1605/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1605) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1605 main.cpp) \ No newline at end of file diff --git a/1501-2000/1605-Find-Valid-Matrix-Given-Row-and-Column-Sums/cpp-1605/main.cpp b/1501-2000/1605-Find-Valid-Matrix-Given-Row-and-Column-Sums/cpp-1605/main.cpp new file mode 100644 index 00000000..1096e166 --- /dev/null +++ b/1501-2000/1605-Find-Valid-Matrix-Given-Row-and-Column-Sums/cpp-1605/main.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/find-valid-matrix-given-row-and-column-sums/submissions/ +/// Author : liuyubobobo +/// Time : 2020-10-15 + +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(R * C) +/// Space Complexity: O(1) +class Solution { +public: + vector> restoreMatrix(vector& rowSum, vector& colSum) { + + int R = rowSum.size(), C = colSum.size(); + vector> res(R, vector(C, 0)); + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++){ + res[i][j] = min(rowSum[i], colSum[j]); + rowSum[i] -= res[i][j]; + colSum[j] -= res[i][j]; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1606-Find-Servers-That-Handled-Most-Number-of-Requests/cpp-1606/CMakeLists.txt b/1501-2000/1606-Find-Servers-That-Handled-Most-Number-of-Requests/cpp-1606/CMakeLists.txt new file mode 100644 index 00000000..6f5941ec --- /dev/null +++ b/1501-2000/1606-Find-Servers-That-Handled-Most-Number-of-Requests/cpp-1606/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1606) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1606 main.cpp) \ No newline at end of file diff --git a/1501-2000/1606-Find-Servers-That-Handled-Most-Number-of-Requests/cpp-1606/main.cpp b/1501-2000/1606-Find-Servers-That-Handled-Most-Number-of-Requests/cpp-1606/main.cpp new file mode 100644 index 00000000..f567b486 --- /dev/null +++ b/1501-2000/1606-Find-Servers-That-Handled-Most-Number-of-Requests/cpp-1606/main.cpp @@ -0,0 +1,90 @@ +/// Source : https://leetcode.com/problems/find-servers-that-handled-most-number-of-requests/ +/// Author : liuyubobobo +/// Time : 2020-10-15 + +#include +#include +#include +#include + +using namespace std; + + +/// Priority Queue + TreeMap +/// Time Complexity: O(nlogk) +/// Space Complexity: O(k) +class Solution { +public: + vector busiestServers(int k, vector& arrival, vector& load) { + + priority_queue, vector>, greater>> pq; // (idletime, id) + set available; + vector f(k, 0); + + for(int i = 0; i < min(k, (int)arrival.size()); i ++) { + pq.push({arrival[i] + load[i], i}); + f[i] ++; + } + + for(int i = k; i < arrival.size(); i ++){ + + while(!pq.empty() && pq.top().first <= arrival[i]){ + available.insert(pq.top().second); + pq.pop(); + } + + set::iterator iter = available.lower_bound(i % k); + if(iter == available.end()){ + iter = available.lower_bound(0); + } + + if(iter != available.end()){ + int index = *iter; + available.erase(index); + pq.push({arrival[i] + load[i], index}); + f[index] ++; + } + } + + vector res; + int maxf = 0; + for(int i = 0; i < k; i ++) + if(f[i] > maxf) res = {i}, maxf = f[i]; + else if(f[i] == maxf) res.push_back(i); + return res; + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << " "; cout << endl; +} + +int main() { + + vector arr1 = {1, 2, 3, 4, 5}, load1 = {5, 2, 3, 3, 3}; + print_vec(Solution().busiestServers(3, arr1, load1)); + // 1 + + vector arr2 = {1, 2, 3, 4}, load2 = {1, 2, 1, 2}; + print_vec(Solution().busiestServers(3, arr2, load2)); + // 0 + + vector arr3 = {1, 2, 3}, load3 = {10, 12, 11}; + print_vec(Solution().busiestServers(3, arr3, load3)); + // 0 1 2 + + vector arr4 = {1, 2, 3, 4, 8, 9, 10}, load4 = {5, 2, 10, 3, 1, 2, 2}; + print_vec(Solution().busiestServers(3, arr4, load4)); + // 1 + + vector arr5 = {1}, load5 = {1}; + print_vec(Solution().busiestServers(1, arr5, load5)); + // 0 + + vector arr6 = {1}, load6 = {1000000000}; + print_vec(Solution().busiestServers(3, arr6, load6)); + // 0 + + return 0; +} diff --git a/1501-2000/1608-Special-Array-With-X-Elements-Greater-Than-or-Equal-X/cpp-1608/CMakeLists.txt b/1501-2000/1608-Special-Array-With-X-Elements-Greater-Than-or-Equal-X/cpp-1608/CMakeLists.txt new file mode 100644 index 00000000..16d05792 --- /dev/null +++ b/1501-2000/1608-Special-Array-With-X-Elements-Greater-Than-or-Equal-X/cpp-1608/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main3.cpp) \ No newline at end of file diff --git a/1501-2000/1608-Special-Array-With-X-Elements-Greater-Than-or-Equal-X/cpp-1608/main.cpp b/1501-2000/1608-Special-Array-With-X-Elements-Greater-Than-or-Equal-X/cpp-1608/main.cpp new file mode 100644 index 00000000..c3f269bb --- /dev/null +++ b/1501-2000/1608-Special-Array-With-X-Elements-Greater-Than-or-Equal-X/cpp-1608/main.cpp @@ -0,0 +1,31 @@ +/// Source : https://leetcode.com/problems/special-array-with-x-elements-greater-than-or-equal-x/ +/// Author : liuyubobobo +/// Time : 2020-10-03 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n^2) +/// Space Complexity: O(1) +class Solution { +public: + int specialArray(vector& nums) { + + for(int x = 0; x <= nums.size(); x ++){ + int f = 0; + for(int e: nums) if(e >= x) f ++; + if(f == x) return x; + } + return -1; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1608-Special-Array-With-X-Elements-Greater-Than-or-Equal-X/cpp-1608/main2.cpp b/1501-2000/1608-Special-Array-With-X-Elements-Greater-Than-or-Equal-X/cpp-1608/main2.cpp new file mode 100644 index 00000000..a9cf026c --- /dev/null +++ b/1501-2000/1608-Special-Array-With-X-Elements-Greater-Than-or-Equal-X/cpp-1608/main2.cpp @@ -0,0 +1,31 @@ +/// Source : https://leetcode.com/problems/special-array-with-x-elements-greater-than-or-equal-x/ +/// Author : liuyubobobo +/// Time : 2020-10-04 + +#include +#include + +using namespace std; + + +/// Sorting and Binary Search +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + int specialArray(vector& nums) { + + sort(nums.begin(), nums.end()); + for(int x = 0; x <= nums.size(); x ++){ + vector::iterator iter = lower_bound(nums.begin(), nums.end(), x); + if(nums.end() - iter == x) return x; + } + return -1; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1608-Special-Array-With-X-Elements-Greater-Than-or-Equal-X/cpp-1608/main3.cpp b/1501-2000/1608-Special-Array-With-X-Elements-Greater-Than-or-Equal-X/cpp-1608/main3.cpp new file mode 100644 index 00000000..2938d425 --- /dev/null +++ b/1501-2000/1608-Special-Array-With-X-Elements-Greater-Than-or-Equal-X/cpp-1608/main3.cpp @@ -0,0 +1,39 @@ +/// Source : https://leetcode.com/problems/special-array-with-x-elements-greater-than-or-equal-x/ +/// Author : liuyubobobo +/// Time : 2020-10-04 + +#include +#include + +using namespace std; + + +/// Counting Sort and Suffix Sum +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int specialArray(vector& nums) { + + int n = nums.size(); + vector cnt(n + 2, 0); + for(int e: nums) cnt[min(e, n)] ++; + + for(int i = n; i >= 0; i --){ + cnt[i] += cnt[i + 1]; + if(cnt[i] == i) return i; + } + + return -1; + } +}; + + +int main() { + + vector nums = {3, 5}; + cout << Solution().specialArray(nums) << endl; + // 2 + + return 0; +} diff --git a/1501-2000/1609-Even-Odd-Tree/cpp-1609/CMakeLists.txt b/1501-2000/1609-Even-Odd-Tree/cpp-1609/CMakeLists.txt new file mode 100644 index 00000000..b103b001 --- /dev/null +++ b/1501-2000/1609-Even-Odd-Tree/cpp-1609/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main2.cpp) \ No newline at end of file diff --git a/1501-2000/1609-Even-Odd-Tree/cpp-1609/main.cpp b/1501-2000/1609-Even-Odd-Tree/cpp-1609/main.cpp new file mode 100644 index 00000000..14153655 --- /dev/null +++ b/1501-2000/1609-Even-Odd-Tree/cpp-1609/main.cpp @@ -0,0 +1,77 @@ +/// Source : https://leetcode.com/problems/even-odd-tree/ +/// Author : liuyubobobo +/// Time : 2020-10-03 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// 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 isEvenOddTree(TreeNode* root) { + + vector> data; + dfs(root, 0, data); + + for(int l = 0; l < data.size(); l += 2) + if(!okEven(data[l])) return false; + + for(int l = 1; l < data.size(); l += 2) + if(!okOdd(data[l])) return false; + + return true; + } + +private: + bool okOdd(const vector& v){ + + for(int e: v) if(e % 2 == 1) return false; + + for(int i = 1; i < v.size(); i ++) + if(v[i] >= v[i - 1]) return false; + + return true; + } + + bool okEven(const vector& v){ + + for(int e: v) if(e % 2 == 0) return false; + + for(int i = 1; i < v.size(); i ++) + if(v[i] <= v[i - 1]) return false; + + return true; + } + + void dfs(TreeNode* node, int level, vector>& data){ + + if(level >= data.size()) data.push_back(vector()); + + data[level].push_back(node->val); + + if(node->left) dfs(node->left, level + 1, data); + if(node->right) dfs(node->right, level + 1, data); + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1609-Even-Odd-Tree/cpp-1609/main2.cpp b/1501-2000/1609-Even-Odd-Tree/cpp-1609/main2.cpp new file mode 100644 index 00000000..94fd867c --- /dev/null +++ b/1501-2000/1609-Even-Odd-Tree/cpp-1609/main2.cpp @@ -0,0 +1,63 @@ +/// Source : https://leetcode.com/problems/even-odd-tree/ +/// Author : liuyubobobo +/// Time : 2020-10-04 + +#include +#include +#include + +using namespace std; + + +/// Simulation with BFS +/// Can stop early +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// 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 isEvenOddTree(TreeNode* root) { + + if(root->val % 2 == 0) return false; + + vector q = {root}; + int level = 0; + + while(!q.empty()){ + + level ++; + vector q2; + for(TreeNode* node: q){ + if(node->left && !deal(level, q2, node->left)) return false; + if(node->right && !deal(level, q2, node->right)) return false; + } + q = q2; + } + return true; + } + +private: + bool deal(int level, vector& q2, TreeNode* node){ + if(level % 2 == node->val % 2) return false; + if(!q2.empty() && level % 2 && node->val >= q2.back()->val) return false; + if(!q2.empty() && level % 2 == 0 && node->val <= q2.back()->val) return false; + q2.push_back(node); + return true; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1610-Maximum-Number-of-Visible-Points/cpp-1610/CMakeLists.txt b/1501-2000/1610-Maximum-Number-of-Visible-Points/cpp-1610/CMakeLists.txt new file mode 100644 index 00000000..a645af27 --- /dev/null +++ b/1501-2000/1610-Maximum-Number-of-Visible-Points/cpp-1610/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main3.cpp) \ No newline at end of file diff --git a/1501-2000/1610-Maximum-Number-of-Visible-Points/cpp-1610/main.cpp b/1501-2000/1610-Maximum-Number-of-Visible-Points/cpp-1610/main.cpp new file mode 100644 index 00000000..c13d2238 --- /dev/null +++ b/1501-2000/1610-Maximum-Number-of-Visible-Points/cpp-1610/main.cpp @@ -0,0 +1,82 @@ +/// Source : https://leetcode.com/problems/maximum-number-of-visible-points/ +/// Author : liuyubobobo +/// Time : 2020-10-03 +/// Updated: 2021-11-15 + +#include +#include + +using namespace std; + + +/// atan2 to sort and binary search +/// deal with >= 2 * pi range seperately +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { + +private: + double eps = 1e-6; + +public: + int visiblePoints(vector>& points, int angle, vector& location) { + + int n = points.size(); + + vector v; + int base = 0; + for(const vector& p: points) + if(p[0] == location[0] && p[1] == location[1]) + base ++; + else{ + int x = p[0] - location[0], y = p[1] - location[1]; + double ang = atan2(y, x); + if(ang < 0) ang += 2 * M_PI; + v.push_back(ang); + } + + sort(v.begin(), v.end()); +// for(double e: v) cout << e << " "; cout << endl; + + double a = angle * M_PI / (double)180.0; + int res = 0; + for(int i = 0; i < v.size(); i ++){ + vector::iterator iter = upper_bound(v.begin(), v.end(), v[i] + a + 1e-6); + int pos = (iter - v.begin()); + int tres = pos - i; + if(v[i] + a >= 2 * M_PI){ + iter = upper_bound(v.begin(), v.end(), v[i] + a - 2 * M_PI+ 1e-6); + pos = (iter - v.begin()); + tres += pos; + } + res = max(res, tres); + } + return res + base; + } +}; + + +int main() { + + vector> points1 = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {1, 2}, {2, 1}}; + vector loc1 = {1, 1}; + cout << Solution().visiblePoints(points1, 0, loc1) << endl; + // 4 + + vector> points2 = {{1000000000,999999999},{999999999,1000000000}}; + vector loc2 = {0,0}; + cout << Solution().visiblePoints(points2, 90, loc2) << endl; + // 2 + + vector> points3 = {{13779926,599856510},{195766825,597976710},{119515491,575316056},{744777345,796161766},{187192636,870346582},{413112378,430889309},{436399518,387904921},{296153131,221188617},{536914240,985130562},{226391292,83241861}}; + vector loc3 = {451961560,358354259}; + cout << Solution().visiblePoints(points3, 64, loc3) << endl; + // 6 + + vector> points4 = {{1,1},{1,1},{1,1}}; + vector loc4 = {1,1}; + cout << Solution().visiblePoints(points4, 1, loc4) << endl; + // 3 + + return 0; +} diff --git a/1501-2000/1610-Maximum-Number-of-Visible-Points/cpp-1610/main2.cpp b/1501-2000/1610-Maximum-Number-of-Visible-Points/cpp-1610/main2.cpp new file mode 100644 index 00000000..a45b6643 --- /dev/null +++ b/1501-2000/1610-Maximum-Number-of-Visible-Points/cpp-1610/main2.cpp @@ -0,0 +1,79 @@ +/// Source : https://leetcode.com/problems/maximum-number-of-visible-points/ +/// Author : liuyubobobo +/// Time : 2020-10-04 +/// Updated: 2021-11-15 + +#include +#include + +using namespace std; + + +/// atan2 to sort and binary search +/// deal with >= 2 * pi with cat another array +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { + +private: + double eps = 1e-6; + +public: + int visiblePoints(vector>& points, int angle, vector& location) { + + int n = points.size(); + + vector v; + int base = 0; + for(const vector& p: points) + if(p[0] == location[0] && p[1] == location[1]) + base ++; + else{ + int x = p[0] - location[0], y = p[1] - location[1]; + double ang = atan2(y, x); + if(ang < 0) ang += 2 * M_PI; + v.push_back(ang); + } + + sort(v.begin(), v.end()); +// for(double e: v) cout << e << " "; cout << endl; + int m = v.size(); + for(int i = 0; i < m; i ++) + v.push_back(v[i] + 2 * M_PI); + + double a = angle * M_PI / (double)180.0; + int res = 0; + for(int i = 0; i < m; i ++){ + vector::iterator iter = upper_bound(v.begin(), v.end(), v[i] + a + 1e-6); + int pos = (iter - v.begin()); + res = max(res, pos - i); + } + return res + base; + } +}; + + +int main() { + + vector> points1 = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {1, 2}, {2, 1}}; + vector loc1 = {1, 1}; + cout << Solution().visiblePoints(points1, 0, loc1) << endl; + // 4 + + vector> points2 = {{1000000000,999999999},{999999999,1000000000}}; + vector loc2 = {0,0}; + cout << Solution().visiblePoints(points2, 90, loc2) << endl; + // 2 + + vector> points3 = {{13779926,599856510},{195766825,597976710},{119515491,575316056},{744777345,796161766},{187192636,870346582},{413112378,430889309},{436399518,387904921},{296153131,221188617},{536914240,985130562},{226391292,83241861}}; + vector loc3 = {451961560,358354259}; + cout << Solution().visiblePoints(points3, 64, loc3) << endl; + // 6 + + vector> points4 = {{1,1},{1,1},{1,1}}; + vector loc4 = {1,1}; + cout << Solution().visiblePoints(points4, 1, loc4) << endl; + // 3 + + return 0; +} diff --git a/1501-2000/1610-Maximum-Number-of-Visible-Points/cpp-1610/main3.cpp b/1501-2000/1610-Maximum-Number-of-Visible-Points/cpp-1610/main3.cpp new file mode 100644 index 00000000..27daf11a --- /dev/null +++ b/1501-2000/1610-Maximum-Number-of-Visible-Points/cpp-1610/main3.cpp @@ -0,0 +1,82 @@ +/// Source : https://leetcode.com/problems/maximum-number-of-visible-points/ +/// Author : liuyubobobo +/// Time : 2020-10-04 +/// Updated: 2021-11-15 + +#include +#include + +using namespace std; + + +/// atan2 to sort and sliding window +/// deal with >= 2 * pi with cat another array +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { + +private: + double eps = 1e-6; + +public: + int visiblePoints(vector>& points, int angle, vector& location) { + + int n = points.size(); + + vector v; + int base = 0; + for(const vector& p: points) + if(p[0] == location[0] && p[1] == location[1]) + base ++; + else{ + int x = p[0] - location[0], y = p[1] - location[1]; + double ang = atan2(y, x); + if(ang < 0) ang += 2 * M_PI; + v.push_back(ang); + } + + sort(v.begin(), v.end()); +// for(double e: v) cout << e << " "; cout << endl; + + int m = v.size(); + for(int i = 0; i < m; i ++) + v.push_back(v[i] + 2 * M_PI); + + double a = angle * M_PI / (double)180.0 + eps; + int res = 0, l = 0, r = -1; + while(l < m){ + if(r + 1 < v.size() && v[r + 1] - v[l] <= a){ + r ++; + res = max(res, r - l + 1); + } + else l ++; + } + return res + base; + } +}; + + +int main() { + + vector> points1 = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {1, 2}, {2, 1}}; + vector loc1 = {1, 1}; + cout << Solution().visiblePoints(points1, 0, loc1) << endl; + // 4 + + vector> points2 = {{1000000000,999999999},{999999999,1000000000}}; + vector loc2 = {0,0}; + cout << Solution().visiblePoints(points2, 90, loc2) << endl; + // 2 + + vector> points3 = {{13779926,599856510},{195766825,597976710},{119515491,575316056},{744777345,796161766},{187192636,870346582},{413112378,430889309},{436399518,387904921},{296153131,221188617},{536914240,985130562},{226391292,83241861}}; + vector loc3 = {451961560,358354259}; + cout << Solution().visiblePoints(points3, 64, loc3) << endl; + // 6 + + vector> points4 = {{1,1},{1,1},{1,1}}; + vector loc4 = {1,1}; + cout << Solution().visiblePoints(points4, 1, loc4) << endl; + // 3 + + return 0; +} diff --git a/1501-2000/1611-Minimum-One-Bit-Operations-to-Make-Integers-Zero/cpp-1611/CMakeLists.txt b/1501-2000/1611-Minimum-One-Bit-Operations-to-Make-Integers-Zero/cpp-1611/CMakeLists.txt new file mode 100644 index 00000000..a373769d --- /dev/null +++ b/1501-2000/1611-Minimum-One-Bit-Operations-to-Make-Integers-Zero/cpp-1611/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main2.cpp) \ No newline at end of file diff --git a/1501-2000/1611-Minimum-One-Bit-Operations-to-Make-Integers-Zero/cpp-1611/main.cpp b/1501-2000/1611-Minimum-One-Bit-Operations-to-Make-Integers-Zero/cpp-1611/main.cpp new file mode 100644 index 00000000..014b71ba --- /dev/null +++ b/1501-2000/1611-Minimum-One-Bit-Operations-to-Make-Integers-Zero/cpp-1611/main.cpp @@ -0,0 +1,38 @@ +/// Source : https://leetcode.com/problems/minimum-one-bit-operations-to-make-integers-zero/ +/// Author : liuyubobobo +/// Time : 2020-10-04 + +#include + +using namespace std; + + +/// Grey code to Binary code +/// Ref: https://en.wikipedia.org/wiki/Gray_code +/// Time Complexity: O(logn) +/// Space Complexity: O(1) +class Solution { +public: + int minimumOneBitOperations(int n) { + + int mask = n; + while (mask) { + mask >>= 1; + n ^= mask; + } + return n; + } +}; + + +int main() { + + cout << Solution().minimumOneBitOperations(0) << endl; // 0 + cout << Solution().minimumOneBitOperations(3) << endl; // 2 + cout << Solution().minimumOneBitOperations(6) << endl; // 4 + cout << Solution().minimumOneBitOperations(9) << endl; // 14 + cout << Solution().minimumOneBitOperations(333) << endl; // 393 + cout << Solution().minimumOneBitOperations(284848) << endl; // 495839 + + return 0; +} diff --git a/1501-2000/1611-Minimum-One-Bit-Operations-to-Make-Integers-Zero/cpp-1611/main2.cpp b/1501-2000/1611-Minimum-One-Bit-Operations-to-Make-Integers-Zero/cpp-1611/main2.cpp new file mode 100644 index 00000000..ea8b1d6f --- /dev/null +++ b/1501-2000/1611-Minimum-One-Bit-Operations-to-Make-Integers-Zero/cpp-1611/main2.cpp @@ -0,0 +1,38 @@ +/// Source : https://leetcode.com/problems/minimum-one-bit-operations-to-make-integers-zero/ +/// Author : liuyubobobo +/// Time : 2020-10-04 + +#include + +using namespace std; + + +/// Grey code to Binary code +/// Ref: https://en.wikipedia.org/wiki/Gray_code +/// Time Complexity: O(1) +/// Space Complexity: O(1) +class Solution { +public: + int minimumOneBitOperations(int n) { + + n ^= n >> 16; + n ^= n >> 8; + n ^= n >> 4; + n ^= n >> 2; + n ^= n >> 1; + return n; + } +}; + + +int main() { + + cout << Solution().minimumOneBitOperations(0) << endl; // 0 + cout << Solution().minimumOneBitOperations(3) << endl; // 2 + cout << Solution().minimumOneBitOperations(6) << endl; // 4 + cout << Solution().minimumOneBitOperations(9) << endl; // 14 + cout << Solution().minimumOneBitOperations(333) << endl; // 393 + cout << Solution().minimumOneBitOperations(284848) << endl; // 495839 + + return 0; +} diff --git a/1501-2000/1612-Check-If-Two-Expression-Trees-are-Equivalent/cpp-1612/CMakeLists.txt b/1501-2000/1612-Check-If-Two-Expression-Trees-are-Equivalent/cpp-1612/CMakeLists.txt new file mode 100644 index 00000000..dac1fe81 --- /dev/null +++ b/1501-2000/1612-Check-If-Two-Expression-Trees-are-Equivalent/cpp-1612/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1612) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1612 main.cpp) \ No newline at end of file diff --git a/1501-2000/1612-Check-If-Two-Expression-Trees-are-Equivalent/cpp-1612/main.cpp b/1501-2000/1612-Check-If-Two-Expression-Trees-are-Equivalent/cpp-1612/main.cpp new file mode 100644 index 00000000..617783c4 --- /dev/null +++ b/1501-2000/1612-Check-If-Two-Expression-Trees-are-Equivalent/cpp-1612/main.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/check-if-two-expression-trees-are-equivalent/ +/// Author : liuyubobobo +/// Time : 2020-10-15 + +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// Definition for a binary tree node. +struct Node { + char val; + Node *left; + Node *right; + Node() : val(' '), left(nullptr), right(nullptr) {} + Node(char x) : val(x), left(nullptr), right(nullptr) {} + Node(char x, Node *left, Node *right) : val(x), left(left), right(right) {} +}; + +class Solution { +public: + bool checkEquivalence(Node* root1, Node* root2) { + + unordered_map set1, set2; + dfs(root1, set1); dfs(root2, set2); + + for(const pair& p: set1){ + if(!set2.count(p.first) || set2[p.first] != p.second) return false; + set2.erase(p.first); + } + return set2.empty(); + } + +private: + void dfs(Node* node, unordered_map& set){ + + if(!node) return; + if(!node->left && !node->right) set[node->val] ++; + dfs(node->left, set); + dfs(node->right, set); + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1614-Maximum-Nesting-Depth-of-the-Parentheses/cpp-1614/CMakeLists.txt b/1501-2000/1614-Maximum-Nesting-Depth-of-the-Parentheses/cpp-1614/CMakeLists.txt new file mode 100644 index 00000000..d5d5e4ff --- /dev/null +++ b/1501-2000/1614-Maximum-Nesting-Depth-of-the-Parentheses/cpp-1614/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1501-2000/1614-Maximum-Nesting-Depth-of-the-Parentheses/cpp-1614/main.cpp b/1501-2000/1614-Maximum-Nesting-Depth-of-the-Parentheses/cpp-1614/main.cpp new file mode 100644 index 00000000..9408fcea --- /dev/null +++ b/1501-2000/1614-Maximum-Nesting-Depth-of-the-Parentheses/cpp-1614/main.cpp @@ -0,0 +1,32 @@ +/// Source : https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/ +/// Author : liuyubobobo +/// Time : 2020-10-10 + +#include +#include + +using namespace std; + + +/// Stack Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int maxDepth(string s) { + + int res = 0, stack = 0; + for(char c: s){ + if(c == '(') stack ++; + else if(c == ')') stack --; + res = max(res, stack); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1615-Maximal-Network-Rank/cpp-1615/CMakeLists.txt b/1501-2000/1615-Maximal-Network-Rank/cpp-1615/CMakeLists.txt new file mode 100644 index 00000000..b103b001 --- /dev/null +++ b/1501-2000/1615-Maximal-Network-Rank/cpp-1615/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main2.cpp) \ No newline at end of file diff --git a/1501-2000/1615-Maximal-Network-Rank/cpp-1615/main.cpp b/1501-2000/1615-Maximal-Network-Rank/cpp-1615/main.cpp new file mode 100644 index 00000000..03bb4ea8 --- /dev/null +++ b/1501-2000/1615-Maximal-Network-Rank/cpp-1615/main.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/maximal-network-rank/ +/// Author : liuyubobobo +/// Time : 2020-10-10 + +#include +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(V^2) +/// Space Complexity: O(V + E) +class Solution { +public: + int maximalNetworkRank(int n, vector>& roads) { + + vector> g(n); + for(const vector& e: roads) + g[e[0]].insert(e[1]), g[e[1]].insert(e[0]); + + int res = 0; + for(int i = 0; i < n; i ++) + for(int j = i + 1; j < n; j ++){ + int tres = g[i].size() + g[j].size(); + if(g[i].count(j)) tres --; + res = max(res, tres); + } + return res; + } +}; + + +int main() { + + vector> roads1 = {{0,1},{0,3},{1,2},{1,3}}; + cout << Solution().maximalNetworkRank(4, roads1) << endl; + // 4 + + vector> roads2 = {{0,1},{0,3},{1,2},{1,3},{2,3},{2,4}}; + cout << Solution().maximalNetworkRank(5, roads2) << endl; + // 5 + + vector> roads3 = {{0,1},{1,2},{2,3},{2,4},{5,6},{5,7}}; + cout << Solution().maximalNetworkRank(8, roads3) << endl; + // 5 + + return 0; +} diff --git a/1501-2000/1615-Maximal-Network-Rank/cpp-1615/main2.cpp b/1501-2000/1615-Maximal-Network-Rank/cpp-1615/main2.cpp new file mode 100644 index 00000000..c2678e99 --- /dev/null +++ b/1501-2000/1615-Maximal-Network-Rank/cpp-1615/main2.cpp @@ -0,0 +1,82 @@ +/// Source : https://leetcode.com/problems/maximal-network-rank/ +/// Author : liuyubobobo +/// Time : 2020-10-14 + +#include +#include +#include + +using namespace std; + + +/// Greedy +/// See here for reference: https://leetcode-cn.com/problems/maximal-network-rank/solution/onm-mei-ju-fa-by-zerotrac2/ +/// Time Complexity: O(V + E) +/// Space Complexity: O(V) +class Solution { +public: + int maximalNetworkRank(int n, vector>& roads) { + + vector> g(n); + vector degrees(n); + for(const vector& e: roads) + degrees[e[0]] ++, degrees[e[1]] ++, + g[e[0]].insert(e[1]), g[e[1]].insert(e[0]); + + int first_max = max(degrees[0], degrees[1]), + second_max = degrees[0] == degrees[1] ? 0 : min(degrees[0], degrees[1]), + max_cnt = (degrees[0] == degrees[1] ? 2 : 1); + for(int i = 2; i < n; i ++) + if(degrees[i] > first_max) + second_max = first_max, first_max = degrees[i], max_cnt = 1; + else if(degrees[i] == first_max) max_cnt ++; + else if(degrees[i] > second_max) + second_max = degrees[i]; + + if(max_cnt > 1){ + int c = max_cnt * (max_cnt - 1) / 2; + if(c > roads.size()) + return 2 * first_max; + + for(const vector& e: roads) + if(degrees[e[0]] == first_max && degrees[e[1]] == first_max) + c --; + + if(c) return 2 * first_max; + return 2 * first_max - 1; + } + + int city = -1; + for(int i = 0; i < n; i ++) + if(degrees[i] == first_max){ + city = i; break; + } + + for(int i = 0; i < n; i ++) + if(degrees[i] == second_max && !g[city].count(i)) + return first_max + second_max; + return first_max + second_max - 1; + } +}; + + +int main() { + + vector> roads1 = {{0,1},{0,3},{1,2},{1,3}}; + cout << Solution().maximalNetworkRank(4, roads1) << endl; + // 4 + + vector> roads2 = {{0,1},{0,3},{1,2},{1,3},{2,3},{2,4}}; + cout << Solution().maximalNetworkRank(5, roads2) << endl; + // 5 + + vector> roads3 = {{0,1},{1,2},{2,3},{2,4},{5,6},{5,7}}; + cout << Solution().maximalNetworkRank(8, roads3) << endl; + // 5 + + vector> roads4 = {{0,1}}; + cout << Solution().maximalNetworkRank(2, roads4) << endl; + // 1 + + return 0; +} diff --git a/1501-2000/1616-Split-Two-Strings-to-Make-Palindrome/cpp-1616/CMakeLists.txt b/1501-2000/1616-Split-Two-Strings-to-Make-Palindrome/cpp-1616/CMakeLists.txt new file mode 100644 index 00000000..80fb8c61 --- /dev/null +++ b/1501-2000/1616-Split-Two-Strings-to-Make-Palindrome/cpp-1616/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main2.cpp) \ No newline at end of file diff --git a/1501-2000/1616-Split-Two-Strings-to-Make-Palindrome/cpp-1616/main.cpp b/1501-2000/1616-Split-Two-Strings-to-Make-Palindrome/cpp-1616/main.cpp new file mode 100644 index 00000000..9a26e4b9 --- /dev/null +++ b/1501-2000/1616-Split-Two-Strings-to-Make-Palindrome/cpp-1616/main.cpp @@ -0,0 +1,67 @@ +/// Source : https://leetcode.com/problems/split-two-strings-to-make-palindrome/ +/// Author : liuyubobobo +/// Time : 2020-10-10 + +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + bool checkPalindromeFormation(string a, string b) { + + if(is_palindrome(a) || is_palindrome(b)) return true; + + int n = a.size(), i = 0, j = n - 1; + while(i < j) + if(a[i] == b[j]) i ++, j --; + else if(is_palindrome(a.substr(i, j - i + 1)) || is_palindrome(b.substr(i, j - i + 1))) + return true; + else break; + + if(i >= j) return true; + + i = 0, j = n - 1; + while(i < j) + if(b[i] == a[j]) i ++, j --; + else if(is_palindrome(a.substr(i, j - i + 1)) || is_palindrome(b.substr(i, j - i + 1))) + return true; + else break; + return i >= j; + } + +private: + bool is_palindrome(const string& s){ + int i = 0, j = s.size() - 1; + while(i < j) + if(s[i] != s[j]) return false; + else i ++, j --; + return true; + } +}; + + +int main() { + + cout << Solution().checkPalindromeFormation("x", "y") << endl; + // 1 + + cout << Solution().checkPalindromeFormation("abdef", "fecab") << endl; + // 1 + + cout << Solution().checkPalindromeFormation("ulacfd", "jizalu") << endl; + // 1 + + cout << Solution().checkPalindromeFormation("pvhmupgqeltozftlmfjjde", "yjgpzbezspnnpszebzmhvp") << endl; + // 1 + + cout << Solution().checkPalindromeFormation("xbdef", "xecab") << endl; + // 0 + + return 0; +} diff --git a/1501-2000/1616-Split-Two-Strings-to-Make-Palindrome/cpp-1616/main2.cpp b/1501-2000/1616-Split-Two-Strings-to-Make-Palindrome/cpp-1616/main2.cpp new file mode 100644 index 00000000..918398f4 --- /dev/null +++ b/1501-2000/1616-Split-Two-Strings-to-Make-Palindrome/cpp-1616/main2.cpp @@ -0,0 +1,60 @@ +/// Source : https://leetcode.com/problems/split-two-strings-to-make-palindrome/ +/// Author : liuyubobobo +/// Time : 2020-10-14 + +#include +#include + +using namespace std; + + +/// check from middle +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + bool checkPalindromeFormation(string a, string b) { + + return check(a, b) || check(b, a); + } + +private: + bool check(const string& a, const string& b){ + + int i, j; + if(a.size() % 2) i = j = a.size() / 2; + else i = a.size() / 2 - 1, j = a.size() / 2; + + while(i >= 0 && j < a.size() && a[i] == a[j]) i --, j ++; + + int l = i, r = j; + while(i >= 0 && j < a.size() && a[i] == b[j]) i --, j ++; + if(i < 0) return true; + + i = l, j = r; + while(i >= 0 && j < a.size() && b[i] == a[j]) i --, j ++; + + return i < 0; + } +}; + + +int main() { + + cout << Solution().checkPalindromeFormation("x", "y") << endl; + // 1 + + cout << Solution().checkPalindromeFormation("abdef", "fecab") << endl; + // 1 + + cout << Solution().checkPalindromeFormation("ulacfd", "jizalu") << endl; + // 1 + + cout << Solution().checkPalindromeFormation("pvhmupgqeltozftlmfjjde", "yjgpzbezspnnpszebzmhvp") << endl; + // 1 + + cout << Solution().checkPalindromeFormation("xbdef", "xecab") << endl; + // 0 + + return 0; +} diff --git a/1501-2000/1617-Count-Subtrees-With-Max-Distance-Between-Cities/cpp-1617/CMakeLists.txt b/1501-2000/1617-Count-Subtrees-With-Max-Distance-Between-Cities/cpp-1617/CMakeLists.txt new file mode 100644 index 00000000..a373769d --- /dev/null +++ b/1501-2000/1617-Count-Subtrees-With-Max-Distance-Between-Cities/cpp-1617/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main2.cpp) \ No newline at end of file diff --git a/1501-2000/1617-Count-Subtrees-With-Max-Distance-Between-Cities/cpp-1617/main.cpp b/1501-2000/1617-Count-Subtrees-With-Max-Distance-Between-Cities/cpp-1617/main.cpp new file mode 100644 index 00000000..8ae1359b --- /dev/null +++ b/1501-2000/1617-Count-Subtrees-With-Max-Distance-Between-Cities/cpp-1617/main.cpp @@ -0,0 +1,94 @@ +/// Source : https://leetcode.com/problems/count-subtrees-with-max-distance-between-cities/ +/// Author : liuyubobobo +/// Time : 2020-10-15 + +#include +#include +#include + +using namespace std; + + +/// Brute Force all combinations and get tree diameter +/// Time Complexity: O(n * 2^n) +/// Space Complexity: O(n) +class Solution { +public: + vector countSubgraphsForEachDiameter(int n, vector>& edges) { + + vector> g(n); + for(const vector& e: edges) + g[e[0] - 1].insert(e[1] - 1), g[e[1] - 1].insert(e[0] - 1); + + vector res(n - 1); + for(int i = 0; i <= (1 << n) - 1; i ++){ + int d = getd(n, g, i); +// cout << "state " << i << " : " << d << endl; +// assert(d >= 0 && d < n); + if(d) res[d - 1] ++; + } + return res; + } + +private: + int getd(int n, const vector>& g, int state){ + + for(int i = 0; i < n; i ++) + if(state & (1 << i)){ + int visited = 0, res = 0; + dfs(n, g, i, state, visited, res); + return visited == state ? res : 0; + } + return 0; + } + + int dfs(int n, const vector>& g, int v, int state, + int& visited, int& res){ + + visited |= (1 << v); + + int first = 0, second = 0; + for(int next: g[v]) + if((state & (1 << next)) && !(visited & (1 << next))){ + int t = dfs(n, g, next, state, visited, res) + 1; + if(t >= first) second = first, first = t; + else if(t > second) second = t; + } + res = max(res, first + second); + return first; + } +}; + + +void print_v(const vector& v){ + for(int e: v) cout << e << " "; cout << endl; +} + +int main() { + + vector> edges1 = {{1, 2}, {2, 3}, {2, 4}}; + print_v(Solution().countSubgraphsForEachDiameter(4, edges1)); + // 3, 4, 0 + + vector> edges2 = {{1, 2}}; + print_v(Solution().countSubgraphsForEachDiameter(2, edges2)); + // 1 + + vector> edges3 = {{1, 2}, {2, 3}}; + print_v(Solution().countSubgraphsForEachDiameter(3, edges3)); + // 2 1 + + vector> edges4 = {{1, 3}, {1, 4}, {2, 3}}; + print_v(Solution().countSubgraphsForEachDiameter(4, edges4)); + // 3 2 1 + + vector> edges5 = {{1, 4}, {1, 3}, {2, 5}, {2, 6}, {3, 6}, {6, 7}}; + print_v(Solution().countSubgraphsForEachDiameter(7, edges5)); + // 6 7 7 5 2 0 + + vector> edges6 = {{1, 4}, {1, 5}, {1, 6}, {2, 3}, {2, 5}}; + print_v(Solution().countSubgraphsForEachDiameter(6, edges6)); + // 5 6 4 3 0 + + return 0; +} diff --git a/1501-2000/1617-Count-Subtrees-With-Max-Distance-Between-Cities/cpp-1617/main2.cpp b/1501-2000/1617-Count-Subtrees-With-Max-Distance-Between-Cities/cpp-1617/main2.cpp new file mode 100644 index 00000000..c0729b83 --- /dev/null +++ b/1501-2000/1617-Count-Subtrees-With-Max-Distance-Between-Cities/cpp-1617/main2.cpp @@ -0,0 +1,93 @@ +/// Source : https://leetcode.com/problems/count-subtrees-with-max-distance-between-cities/ +/// Author : liuyubobobo +/// Time : 2020-10-15 + +#include +#include + +using namespace std; + + +/// Tree DP +/// Time Complexity: O(n^5) +/// Space Complexity: O(n^3) +class Solution { +public: + vector countSubgraphsForEachDiameter(int n, vector>& edges) { + + vector> g(n); + for(const vector& e: edges) + g[e[0] - 1].push_back(e[1] - 1), g[e[1] - 1].push_back(e[0] - 1); + + vector res(n - 1, 0); + vector>> dp(n, vector>(n, vector(n, 0))); + + dfs(n, g, 0, -1, dp); + for(int i = 0; i < n; i ++){ + for(int depth = 0; depth < n; depth ++) + for(int d = 1; d < n; d ++) + res[d - 1] += dp[i][depth][d]; + } + return res; + } + +private: + void dfs(int n, const vector>& tree, int v, int parent, + vector>>& dp){ + + dp[v][0][0] = 1; + + for(int w: tree[v]) + if(w != parent){ + + dfs(n, tree, w, v, dp); + + vector> t(n, vector(n, 0)); + for(int wdepth = 0; wdepth + 1 < n; wdepth ++) + for(int wd = wdepth; wd < n; wd ++) + if(dp[w][wdepth][wd]) + for(int vdepth = 0; vdepth + wdepth + 1 < n; vdepth ++) + for(int vd = vdepth; vd < n; vd ++) + if(dp[v][vdepth][vd]) + t[max(vdepth, wdepth + 1)][max(max(vd, wd), vdepth + wdepth + 1)] += dp[v][vdepth][vd] * dp[w][wdepth][wd]; + + for(int depth = 0; depth < n; depth ++) + for(int d = 0; d < n; d ++) + dp[v][depth][d] += t[depth][d]; + } + } +}; + + +void print_v(const vector& v){ + for(int e: v) cout << e << " "; cout << endl; +} + +int main() { + + vector> edges1 = {{1, 2}, {2, 3}, {2, 4}}; + print_v(Solution().countSubgraphsForEachDiameter(4, edges1)); + // 3, 4, 0 + + vector> edges2 = {{1, 2}}; + print_v(Solution().countSubgraphsForEachDiameter(2, edges2)); + // 1 + + vector> edges3 = {{1, 2}, {2, 3}}; + print_v(Solution().countSubgraphsForEachDiameter(3, edges3)); + // 2 1 + + vector> edges4 = {{1, 3}, {1, 4}, {2, 3}}; + print_v(Solution().countSubgraphsForEachDiameter(4, edges4)); + // 3 2 1 + + vector> edges5 = {{1, 4}, {1, 3}, {2, 5}, {2, 6}, {3, 6}, {6, 7}}; + print_v(Solution().countSubgraphsForEachDiameter(7, edges5)); + // 6 7 7 5 2 0 + + vector> edges6 = {{1, 4}, {1, 5}, {1, 6}, {2, 3}, {2, 5}}; + print_v(Solution().countSubgraphsForEachDiameter(6, edges6)); + // 5 6 4 3 0 + + return 0; +} diff --git a/1501-2000/1618-Maximum-Font-to-Fit-a-Sentence-in-a-Screen/cpp-1618/CMakeLists.txt b/1501-2000/1618-Maximum-Font-to-Fit-a-Sentence-in-a-Screen/cpp-1618/CMakeLists.txt new file mode 100644 index 00000000..1740bc9b --- /dev/null +++ b/1501-2000/1618-Maximum-Font-to-Fit-a-Sentence-in-a-Screen/cpp-1618/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1618) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1618 main.cpp) \ No newline at end of file diff --git a/1501-2000/1618-Maximum-Font-to-Fit-a-Sentence-in-a-Screen/cpp-1618/main.cpp b/1501-2000/1618-Maximum-Font-to-Fit-a-Sentence-in-a-Screen/cpp-1618/main.cpp new file mode 100644 index 00000000..97b92561 --- /dev/null +++ b/1501-2000/1618-Maximum-Font-to-Fit-a-Sentence-in-a-Screen/cpp-1618/main.cpp @@ -0,0 +1,48 @@ +/// Source : https://leetcode.com/problems/maximum-font-to-fit-a-sentence-in-a-screen/ +/// Author : liuyubobobo +/// Time : 2020-10-15 + +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(|text| * log(|fonts|)) +/// Space Complexity: O(1) + +// This is the FontInfo's API interface. +// You should not implement it, or speculate about its implementation +class FontInfo { + public: + // Return the width of char ch when fontSize is used. + int getWidth(int fontSize, char ch); + + // Return Height of any char when fontSize is used. + int getHeight(int fontSize); +}; + +class Solution { +public: + int maxFont(string text, long long w, int h, vector& fonts, FontInfo fontInfo) { + + int l = -1, r = fonts.size() - 1; + while(l < r){ + + int mid = (l + r + 1) / 2; + int H = fontInfo.getHeight(fonts[mid]); + long long W = 0ll; + for(char c: text) W += fontInfo.getWidth(fonts[mid], c); + if(H <= h && W <= w) l = mid; + else r = mid - 1; + } + return l == -1 ? -1 : fonts[l]; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1619-Mean-of-Array-After-Removing-Some-Elements/cpp-1619/CMakeLists.txt b/1501-2000/1619-Mean-of-Array-After-Removing-Some-Elements/cpp-1619/CMakeLists.txt new file mode 100644 index 00000000..d5d5e4ff --- /dev/null +++ b/1501-2000/1619-Mean-of-Array-After-Removing-Some-Elements/cpp-1619/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1501-2000/1619-Mean-of-Array-After-Removing-Some-Elements/cpp-1619/main.cpp b/1501-2000/1619-Mean-of-Array-After-Removing-Some-Elements/cpp-1619/main.cpp new file mode 100644 index 00000000..4d75d459 --- /dev/null +++ b/1501-2000/1619-Mean-of-Array-After-Removing-Some-Elements/cpp-1619/main.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/mean-of-array-after-removing-some-elements/ +/// Author : liuyubobobo +/// Time : 2020-10-17 + +#include +#include +#include + +using namespace std; + + +/// Sorting +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + double trimMean(vector& arr) { + + sort(arr.begin(), arr.end()); + + int k = arr.size() / 20, i = 0, j = arr.size() - 1, sum = 0; + while(k --){ + sum += arr[i ++]; + sum += arr[j --]; + } + return (accumulate(arr.begin(), arr.end(), 0) - sum) / (arr.size() * 18 / 20.0); + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1620-Coordinate-With-Maximum-Network-Quality/cpp-1620/CMakeLists.txt b/1501-2000/1620-Coordinate-With-Maximum-Network-Quality/cpp-1620/CMakeLists.txt new file mode 100644 index 00000000..81ad8b42 --- /dev/null +++ b/1501-2000/1620-Coordinate-With-Maximum-Network-Quality/cpp-1620/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1501-2000/1620-Coordinate-With-Maximum-Network-Quality/cpp-1620/main.cpp b/1501-2000/1620-Coordinate-With-Maximum-Network-Quality/cpp-1620/main.cpp new file mode 100644 index 00000000..31a4c336 --- /dev/null +++ b/1501-2000/1620-Coordinate-With-Maximum-Network-Quality/cpp-1620/main.cpp @@ -0,0 +1,55 @@ +/// Source : https://leetcode.com/problems/coordinate-with-maximum-network-quality/ +/// Author : liuyubobobo +/// Time : 2020-10-18 +/// Updated: 2022-11-01 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O((maxx - minx) * (maxy - miny) * |towers|) +/// Space Complexity: O(1) +class Solution { +public: + vector bestCoordinate(vector>& towers, int radius) { + + int minx = INT_MAX, miny = INT_MAX, maxx = INT_MIN, maxy = INT_MIN; + for(const vector& tower: towers){ + minx = min(minx, tower[0] - tower[2]); + miny = min(miny, tower[1] - tower[2]); + maxx = max(maxx, tower[0] + tower[2]); + maxy = max(maxy, tower[1] + tower[2]); + } + + vector res; + int maxq = 0; + for(int x = minx; x <= maxx; x ++) + for(int y = miny; y <= maxy; y ++){ + int curq = getq(towers, x, y, radius); + if(curq > maxq) res = {x, y}, maxq = curq; + } + return maxq == 0 ? vector(2, 0) : res; + } + +private: + int getq(const vector>& towers, int x, int y, int r){ + + int res = 0; + for(const vector& e: towers){ + int d2 = (e[0] - x) * (e[0] - x) + (e[1] - y) * (e[1] - y); + if(d2 <= r * r) + res += (int)(e[2] / (1 + sqrt(d2))); + } + return res; + } +}; + + +int main() { + + + return 0; +} diff --git a/1501-2000/1621-Number-of-Sets-of-K-Non-Overlapping-Line-Segments/cpp-1621/CMakeLists.txt b/1501-2000/1621-Number-of-Sets-of-K-Non-Overlapping-Line-Segments/cpp-1621/CMakeLists.txt new file mode 100644 index 00000000..80fb8c61 --- /dev/null +++ b/1501-2000/1621-Number-of-Sets-of-K-Non-Overlapping-Line-Segments/cpp-1621/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main2.cpp) \ No newline at end of file diff --git a/1501-2000/1621-Number-of-Sets-of-K-Non-Overlapping-Line-Segments/cpp-1621/main.cpp b/1501-2000/1621-Number-of-Sets-of-K-Non-Overlapping-Line-Segments/cpp-1621/main.cpp new file mode 100644 index 00000000..91cc57bf --- /dev/null +++ b/1501-2000/1621-Number-of-Sets-of-K-Non-Overlapping-Line-Segments/cpp-1621/main.cpp @@ -0,0 +1,56 @@ +/// Source : https://leetcode.com/problems/number-of-sets-of-k-non-overlapping-line-segments/ +/// Author : liuyubobobo +/// Time : 2020-10-17 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(nk) +/// Space Complexity: O(n) +class Solution { + +private: + const int MOD = 1e9 + 7; + +public: + int numberOfSets(int n, int k) { + + vector dp(n, 1); + vector presum(n + 1, 0); + for(int i = 0; i < n; i ++) + presum[i + 1] = (presum[i] + dp[i]) % MOD; + + for(int i = 0; i < k; i ++){ + dp[n - 1] = 0; + for(int start = n - 2; start >= 0; start --) + dp[start] = ((dp[start + 1] + presum[n]) % MOD - presum[start + 1] + MOD) % MOD; + + presum[0] = 0; + for(int i = 0; i < n; i ++) + presum[i + 1] = (presum[i] + dp[i]) % MOD; + } + return dp[0]; + } +}; + + +int main() { + + cout << Solution().numberOfSets(4, 2) << endl; + // 5 + + cout << Solution().numberOfSets(3, 1) << endl; + // 3 + + cout << Solution().numberOfSets(30, 7) << endl; + // 796297179 + + cout << Solution().numberOfSets(31, 26) << endl; + // 367290 + + return 0; +} diff --git a/1501-2000/1621-Number-of-Sets-of-K-Non-Overlapping-Line-Segments/cpp-1621/main2.cpp b/1501-2000/1621-Number-of-Sets-of-K-Non-Overlapping-Line-Segments/cpp-1621/main2.cpp new file mode 100644 index 00000000..36f70a9e --- /dev/null +++ b/1501-2000/1621-Number-of-Sets-of-K-Non-Overlapping-Line-Segments/cpp-1621/main2.cpp @@ -0,0 +1,64 @@ +/// Source : https://leetcode.com/problems/number-of-sets-of-k-non-overlapping-line-segments/ +/// Author : liuyubobobo +/// Time : 2020-10-18 + +#include +#include + +using namespace std; + + +/// Mathematics: C(n + k - 1, 2k) +/// See here for proof: https://leetcode-cn.com/problems/number-of-sets-of-k-non-overlapping-line-segments/solution/da-xiao-wei-k-de-bu-zhong-die-xian-duan-de-shu-mu-/ +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { + +private: + const long long MOD = 1e9 + 7; + +public: + int numberOfSets(int n, int k) { + + long long a = fac(n + k - 1); + long long b = fac(2 * k) * fac(n - k - 1) % MOD; + return a * mypow(b, MOD - 2) % MOD; + } + +private: + long long mypow(long long a, int n){ + + if(n == 0) return 1ll; + if(n == 1) return a; + long long t = mypow(a, n / 2); + long long res = t * t % MOD; + if(n & 1) res = res * a % MOD; + return res; + } + + long long fac(long long n){ + + long long res = 1ll; + for(long long i = 1; i <= n; i ++) + res = res * i % MOD; + return res; + } +}; + + +int main() { + + cout << Solution().numberOfSets(4, 2) << endl; + // 5 + + cout << Solution().numberOfSets(3, 1) << endl; + // 3 + + cout << Solution().numberOfSets(30, 7) << endl; + // 796297179 + + cout << Solution().numberOfSets(31, 26) << endl; + // 367290 + + return 0; +} diff --git a/1501-2000/1622-Fancy-Sequence/cpp-1622/CMakeLists.txt b/1501-2000/1622-Fancy-Sequence/cpp-1622/CMakeLists.txt new file mode 100644 index 00000000..a373769d --- /dev/null +++ b/1501-2000/1622-Fancy-Sequence/cpp-1622/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main2.cpp) \ No newline at end of file diff --git a/1501-2000/1622-Fancy-Sequence/cpp-1622/main.cpp b/1501-2000/1622-Fancy-Sequence/cpp-1622/main.cpp new file mode 100644 index 00000000..cf8ff956 --- /dev/null +++ b/1501-2000/1622-Fancy-Sequence/cpp-1622/main.cpp @@ -0,0 +1,59 @@ +/// Source : https://leetcode.com/problems/fancy-sequence/ +/// Author : liuyubobobo +/// Time : 2020-10-18 + +#include +#include + +using namespace std; + + +/// Mathematics +/// See here for reference: https://leetcode.com/problems/fancy-sequence/discuss/898861/C%2B%2B-solution-beats-100-Math-Solution +/// Time Complexity: all operations: O(1) +/// Space Complexity: O(|num|) +class Fancy { + +private: + const long long MOD = 1e9 + 7; + vector num; + long long add = 0ll, mul = 1ll; + +public: + Fancy(){} + + void append(int val) { + num.push_back((val - add + MOD) % MOD * mypow(mul, MOD - 2) % MOD); + } + + void addAll(int inc) { + add = (add + inc) % MOD; + } + + void multAll(int m) { + mul = mul * m % MOD; + add = add * m % MOD; + } + + int getIndex(int idx) { + if(idx >= 0 && idx < num.size()) + return (num[idx] * mul % MOD + add) % MOD; + return -1; + } + +private: + long long mypow(long long x, int n){ + if(n == 0) return 1ll; + if(n == 1) return x; + long long t = mypow(x, n / 2); + long long res = t * t % MOD; + if(n & 1) res = res * x % MOD; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1622-Fancy-Sequence/cpp-1622/main2.cpp b/1501-2000/1622-Fancy-Sequence/cpp-1622/main2.cpp new file mode 100644 index 00000000..f5a5e5b7 --- /dev/null +++ b/1501-2000/1622-Fancy-Sequence/cpp-1622/main2.cpp @@ -0,0 +1,138 @@ +/// Source : https://leetcode.com/problems/fancy-sequence/ +/// Author : liuyubobobo +/// Time : 2020-10-18 + +#include +#include + +using namespace std; + + +/// Segment tree +/// Time Complexity: all operations: O(logn) +/// Space Complexity: O(n) +class SegmentTree{ + +private: + int n; + vector tree, lazya, lazym; + const long long MOD = 1e9 + 7; + +public: + SegmentTree(int n): n(n), tree(4 * n, 0ll), lazya(4 * n, 0ll), lazym(4 * n, 1ll){} + + void add(int index, int val){ + update(0, 0, n - 1, index, index, val, 1); + } + + void update_add(int uL, int uR, int inc){ + update(0, 0, n-1, uL, uR, inc, 1); + } + + void update_mul(int uL, int uR, int mul){ + update(0, 0, n-1, uL, uR, 0, mul); + } + + int query(int index){ + return query(0, 0, n-1, index); + } + +private: + void update(int treeID, int treeL, int treeR, int uL, int uR, int inc, int mul){ + + if(lazya[treeID] != 0 || lazym[treeID] != 1){ + tree[treeID] = (tree[treeID] * lazym[treeID] + (treeR - treeL + 1)* lazya[treeID]) % MOD; + if(treeL != treeR){ + lazym[2 * treeID + 1] = lazym[2 * treeID + 1] * lazym[treeID] % MOD; + lazya[2 * treeID + 1] = lazya[2 * treeID + 1] * lazym[treeID] % MOD; + lazya[2 * treeID + 1] = (lazya[2 * treeID + 1] + lazya[treeID]) % MOD; + + lazym[2 * treeID + 2] = lazym[2 * treeID + 2] * lazym[treeID] % MOD; + lazya[2 * treeID + 2] = lazya[2 * treeID + 2] * lazym[treeID] % MOD; + lazya[2 * treeID + 2] = (lazya[2 * treeID + 2] + lazya[treeID]) % MOD; + } + lazya[treeID] = 0; + lazym[treeID] = 1; + } + + if (treeL > uR || treeR < uL) return; + + if(uL <= treeL && uR >= treeR){ + tree[treeID] = (tree[treeID] + tree[treeID] * (mul - 1) + (treeR - treeL + 1) * inc) % MOD; + if(treeL != treeR){ + lazym[2 * treeID + 1] = lazym[2 * treeID + 1] * mul % MOD; + lazya[2 * treeID + 1] = lazya[2 * treeID + 1] * mul % MOD; + lazya[2 * treeID + 1] = (lazya[2 * treeID + 1] + inc) % MOD; + + lazym[2 * treeID + 2] = lazym[2 * treeID + 2] * mul % MOD; + lazya[2 * treeID + 2] = lazya[2 * treeID + 2] * mul % MOD; + lazya[2 * treeID + 2] = (lazya[2 * treeID + 2] + inc) % MOD; + } + return; + } + + int mid = (treeL + treeR) / 2; + update(2 * treeID + 1, treeL, mid, uL, uR, inc, mul); + update(2 * treeID + 2, mid + 1, treeR, uL, uR, inc, mul); + tree[treeID] = (tree[treeID * 2 + 1] + tree[treeID * 2 + 2]) % MOD; + return; + } + + int query(int treeID, int treeL, int treeR, int index){ + + if(lazya[treeID] != 0 || lazym[treeID] != 1){ + tree[treeID] = (tree[treeID] * lazym[treeID] + (treeR - treeL + 1)* lazya[treeID]) % MOD; + if(treeL != treeR){ + lazym[2 * treeID + 1] = lazym[2 * treeID + 1] * lazym[treeID] % MOD; + lazya[2 * treeID + 1] = lazya[2 * treeID + 1] * lazym[treeID] % MOD; + lazya[2 * treeID + 1] = (lazya[2 * treeID + 1] + lazya[treeID]) % MOD; + + lazym[2 * treeID + 2] = lazym[2 * treeID + 2] * lazym[treeID] % MOD; + lazya[2 * treeID + 2] = lazya[2 * treeID + 2] * lazym[treeID] % MOD; + lazya[2 * treeID + 2] = (lazya[2 * treeID + 2] + lazya[treeID]) % MOD; + } + lazya[treeID] = 0; + lazym[treeID] = 1; + } + + if(treeL == treeR) return tree[treeID]; + + int mid = (treeL + treeR) / 2; + if(index <= mid) return query(2 * treeID + 1, treeL, mid, index); + return query(2 * treeID + 2, mid + 1, treeR, index); + } +}; + +class Fancy { + +private: + SegmentTree tree; + int len = 0; + +public: + Fancy() : tree(1e5 + 1){} + + void append(int val) { + tree.add(len ++, val); + } + + void addAll(int inc) { + tree.update_add(0, len - 1, inc); + } + + void multAll(int mul) { + tree.update_mul(0, len - 1, mul); + } + + int getIndex(int idx) { + if(idx >= 0 && idx < len) + return tree.query(idx); + return -1; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1624-Largest-Substring-Between-Two-Equal-Characters/cpp-1624/CMakeLists.txt b/1501-2000/1624-Largest-Substring-Between-Two-Equal-Characters/cpp-1624/CMakeLists.txt new file mode 100644 index 00000000..d5d5e4ff --- /dev/null +++ b/1501-2000/1624-Largest-Substring-Between-Two-Equal-Characters/cpp-1624/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1501-2000/1624-Largest-Substring-Between-Two-Equal-Characters/cpp-1624/main.cpp b/1501-2000/1624-Largest-Substring-Between-Two-Equal-Characters/cpp-1624/main.cpp new file mode 100644 index 00000000..37397a36 --- /dev/null +++ b/1501-2000/1624-Largest-Substring-Between-Two-Equal-Characters/cpp-1624/main.cpp @@ -0,0 +1,45 @@ +/// Source : https://leetcode.com/problems/largest-substring-between-two-equal-characters/ +/// Author : liuyubobobo +/// Time : 2020-10-17 + +#include +#include + +using namespace std; + + +/// Hash +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int maxLengthBetweenEqualCharacters(string s) { + + vector> pos(26); + for(int i = 0; i < s.size(); i ++) + pos[s[i] - 'a'].push_back(i); + + int res = -1; + for(int i = 0; i < 26; i ++) + if(pos[i].size() > 1) res = max(res, pos[i].back() - pos[i][0] - 1); + return res; + } +}; + + +int main() { + + cout << Solution().maxLengthBetweenEqualCharacters("aa") << endl; + // 0 + + cout << Solution().maxLengthBetweenEqualCharacters("abca") << endl; + // 2 + + cout << Solution().maxLengthBetweenEqualCharacters("cbzxy") << endl; + // -1 + + cout << Solution().maxLengthBetweenEqualCharacters("cabbac") << endl; + // 4 + + return 0; +} diff --git a/1501-2000/1625-Lexicographically-Smallest-String-After-Applying-Operations/cpp-1625/CMakeLists.txt b/1501-2000/1625-Lexicographically-Smallest-String-After-Applying-Operations/cpp-1625/CMakeLists.txt new file mode 100644 index 00000000..81ad8b42 --- /dev/null +++ b/1501-2000/1625-Lexicographically-Smallest-String-After-Applying-Operations/cpp-1625/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1501-2000/1625-Lexicographically-Smallest-String-After-Applying-Operations/cpp-1625/main.cpp b/1501-2000/1625-Lexicographically-Smallest-String-After-Applying-Operations/cpp-1625/main.cpp new file mode 100644 index 00000000..4a604c77 --- /dev/null +++ b/1501-2000/1625-Lexicographically-Smallest-String-After-Applying-Operations/cpp-1625/main.cpp @@ -0,0 +1,72 @@ +/// Source : https://leetcode.com/problems/two-sum/description/ +/// Author : liuyubobobo +/// Time : 2020-10-17 + +#include +#include +#include + +using namespace std; + + +/// BFS +/// Time Complexity: O(|s|) +/// Space Complexity: O(|s|) +class Solution { +public: + string findLexSmallestString(string s, int a, int b) { + + unordered_set visited; + queue q; + q.push(s); + visited.insert(s); + string res = s; + while(!q.empty()){ + + string cur = q.front(); + q.pop(); + res = min(res, cur); + + string s1 = op1(cur, a); + if(!visited.count(s1)){ + visited.insert(s1), q.push(s1); + } + + string s2 = op2(cur, b); + if(!visited.count(s2)){ + visited.insert(s2), q.push(s2); + } + } + return res; + } + +private: + string op1(string s, int a){ + + for(int i = 1; i < s.size(); i += 2) + s[i] = '0' + (s[i] - '0' + a) % 10; + return s; + } + + string op2(const string& s, int b){ + return s.substr(s.size() - b) + s.substr(0, s.size() - b); + } +}; + + +int main() { + + cout << Solution().findLexSmallestString("5525", 9, 2) << endl; + // 2050 + + cout << Solution().findLexSmallestString("74", 5, 1) << endl; + // 24 + + cout << Solution().findLexSmallestString("0011", 4, 2) << endl; + // 0011 + + cout << Solution().findLexSmallestString("43987654", 7, 3) << endl; + // 00553311 + + return 0; +} diff --git a/1501-2000/1626-Best-Team-With-No-Conflicts/cpp-1626/CMakeLists.txt b/1501-2000/1626-Best-Team-With-No-Conflicts/cpp-1626/CMakeLists.txt new file mode 100644 index 00000000..ce73aee9 --- /dev/null +++ b/1501-2000/1626-Best-Team-With-No-Conflicts/cpp-1626/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1501-2000/1626-Best-Team-With-No-Conflicts/cpp-1626/main.cpp b/1501-2000/1626-Best-Team-With-No-Conflicts/cpp-1626/main.cpp new file mode 100644 index 00000000..7d18ee3c --- /dev/null +++ b/1501-2000/1626-Best-Team-With-No-Conflicts/cpp-1626/main.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/best-team-with-no-conflicts/ +/// Author : liuyubobobo +/// Time : 2020-10-17 + +#include +#include + +using namespace std; + + +/// LIS +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { + +public: + int bestTeamScore(vector& scores, vector& ages) { + + int n = scores.size(); + vector> v(n); + for(int i = 0; i < n; i ++) v[i].first = ages[i], v[i].second = scores[i]; + sort(v.begin(), v.end()); + + vector dp(n, 0); + dp[0] = v[0].second; + for(int i = 1; i < n; i ++){ + dp[i] = v[i].second; + for(int j = i - 1; j >= 0; j --) + if(v[i].second >= v[j].second) + dp[i] = max(dp[i], v[i].second + dp[j]); + } + return *max_element(dp.begin(), dp.end()); + } +}; + + +int main() { + + vector scores1 = {1, 3, 5, 10, 15}, ages1 = {1, 2, 3, 4, 5}; + cout << Solution().bestTeamScore(scores1, ages1) << endl; + // 34 + + vector scores2 = {4,5,6,5}, ages2 = {2,1,2,1}; + cout << Solution().bestTeamScore(scores2, ages2) << endl; + // 16 + + vector scores3 = {1,2,3,5}, ages3 = {8,9,10,1}; + cout << Solution().bestTeamScore(scores3, ages3) << endl; + // 6 + + return 0; +} diff --git a/1501-2000/1627-Graph-Connectivity-With-Threshold/cpp-1627/CMakeLists.txt b/1501-2000/1627-Graph-Connectivity-With-Threshold/cpp-1627/CMakeLists.txt new file mode 100644 index 00000000..74cc3ee6 --- /dev/null +++ b/1501-2000/1627-Graph-Connectivity-With-Threshold/cpp-1627/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) \ No newline at end of file diff --git a/1501-2000/1627-Graph-Connectivity-With-Threshold/cpp-1627/main.cpp b/1501-2000/1627-Graph-Connectivity-With-Threshold/cpp-1627/main.cpp new file mode 100644 index 00000000..9641615e --- /dev/null +++ b/1501-2000/1627-Graph-Connectivity-With-Threshold/cpp-1627/main.cpp @@ -0,0 +1,84 @@ +/// Source : https://leetcode.com/problems/graph-connectivity-with-threshold/ +/// Author : liuyubobobo +/// Time : 2020-11-17 + +#include +#include + +using namespace std; + + +/// UF +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class UF{ + +private: + vector parent; + +public: + UF(int n){ + for(int i = 0 ; i < n ; i ++) + parent.push_back(i); + } + + int find(int p){ + if( p != parent[p] ) + parent[p] = find( parent[p] ); + return parent[p]; + } + + bool isConnected(int p , int q){ + return find(p) == find(q); + } + + void unionElements(int p, int q){ + + int pRoot = find(p); + int qRoot = find(q); + + if( pRoot == qRoot ) + return; + + parent[pRoot] = qRoot; + } +}; + +class Solution { + +public: + vector areConnected(int n, int threshold, vector>& queries) { + + UF uf(n + 1); + for(int t = threshold + 1; t <= n; t ++) + for(int k = 1; k * t <= n; k ++) + uf.unionElements(t, k * t); + + vector res; + for(const vector& q: queries) + res.push_back(uf.isConnected(q[0], q[1])); + return res; + } +}; + + +void print_vec(const vector& v){ + for(bool e: v) cout << e << " "; cout << endl; +} + +int main() { + + vector> queries1 = {{1, 4}, {2, 5}, {3, 6}}; + print_vec(Solution().areConnected(6, 2, queries1)); + // 0 0 1 + + vector> queries2 = {{4, 5}, {3, 4}, {3, 2}, {2, 6}, {1, 3}}; + print_vec(Solution().areConnected(6, 0, queries2)); + // 1 1 1 1 1 + + vector> queries3 = {{4, 5}, {4, 5}, {3, 2}, {2, 3}, {3, 4}}; + print_vec(Solution().areConnected(5, 1, queries3)); + // 0 0 0 0 0 + + return 0; +} diff --git a/1501-2000/1628-Design-an-Expression-Tree-With-Evaluate-Function/cpp-1628/CMakeLists.txt b/1501-2000/1628-Design-an-Expression-Tree-With-Evaluate-Function/cpp-1628/CMakeLists.txt new file mode 100644 index 00000000..9929c896 --- /dev/null +++ b/1501-2000/1628-Design-an-Expression-Tree-With-Evaluate-Function/cpp-1628/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1628) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1628 main.cpp) \ No newline at end of file diff --git a/1501-2000/1628-Design-an-Expression-Tree-With-Evaluate-Function/cpp-1628/main.cpp b/1501-2000/1628-Design-an-Expression-Tree-With-Evaluate-Function/cpp-1628/main.cpp new file mode 100644 index 00000000..947b684a --- /dev/null +++ b/1501-2000/1628-Design-an-Expression-Tree-With-Evaluate-Function/cpp-1628/main.cpp @@ -0,0 +1,107 @@ +/// Source : https://leetcode.com/problems/design-an-expression-tree-with-evaluate-function/ +/// Author : liuyubobobo +/// Time : 2020-11-01 + +#include +#include +#include + +using namespace std; + + +/// Stack +/// Tiime Complexity: O(n) +/// Space Complexity: O(n) + +/** + * This is the interface for the expression tree Node. + * You should not remove it, and you can define some classes to implement it. + */ +class Node { +public: + virtual ~Node () {}; + virtual int evaluate() const = 0; +protected: + // define your fields here + +}; + +class MyNode: public Node{ + +public: + char op; + int num; + MyNode* left, *right; + + MyNode(string s): left(nullptr), right(nullptr){ + if(isdigit(s[0])) op = ' ', num = atoi(s.c_str()); + else op = s[0]; + } + + int evaluate() const{ + return dfs(this); + } + +private: + int dfs(const MyNode* node) const{ + + if(node->op == ' ') return node->num; + + int a = dfs(node->left), b = dfs(node->right); + if(node->op == '+') return a + b; + if(node->op == '-') return a - b; + if(node->op == '*') return a * b; + return a / b; + } +}; + + +/** + * This is the TreeBuilder class. + * You can treat it as the driver code that takes the postinfix input + * and returns the expression tree represnting it as a Node. + */ +class TreeBuilder { +public: + Node* buildTree(vector& postfix) { + + stack stack; + for(const string& s: postfix){ + MyNode* node = new MyNode(s); + if(node->op == ' ') stack.push(node); + else{ + MyNode* b = stack.top(); stack.pop(); + MyNode* a = stack.top(); stack.pop(); + node->left = a, node->right = b; + stack.push(node); + } + } + return stack.top(); + } +}; + + +int main() { + + vector s1 = {"3","4","+","2","*","7","/"}; + Node* root1 =TreeBuilder().buildTree(s1); + cout << root1->evaluate() << endl; + // 2 + + vector s2 = {"4","5","7","2","+","-","*"}; + Node* root2 =TreeBuilder().buildTree(s2); + cout << root2->evaluate() << endl; + // -16 + + vector s3 = {"4","2","+","3","5","1","-","*","+"}; + Node* root3 =TreeBuilder().buildTree(s3); + cout << root3->evaluate() << endl; + // 18 + + vector s4 = {"100","200","+","2","/","5","*","7","+"}; + Node* root4 =TreeBuilder().buildTree(s4); + cout << root4->evaluate() << endl; + // 757 + + return 0; +} diff --git a/1501-2000/1629-Slowest-Key/cpp-1629/CMakeLists.txt b/1501-2000/1629-Slowest-Key/cpp-1629/CMakeLists.txt new file mode 100644 index 00000000..d5d5e4ff --- /dev/null +++ b/1501-2000/1629-Slowest-Key/cpp-1629/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1501-2000/1629-Slowest-Key/cpp-1629/main.cpp b/1501-2000/1629-Slowest-Key/cpp-1629/main.cpp new file mode 100644 index 00000000..1dc0e70b --- /dev/null +++ b/1501-2000/1629-Slowest-Key/cpp-1629/main.cpp @@ -0,0 +1,42 @@ +/// Source : https://leetcode.com/problems/slowest-key/ +/// Author : liuyubobobo +/// Time : 2020-10-24 + +#include +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + char slowestKey(vector& releaseTimes, string keysPressed) { + + vector t(26, 0); + for(int i = 0; i < keysPressed.size(); i ++) + t[keysPressed[i] - 'a'] = max(t[keysPressed[i] - 'a'], + (i == 0) ? releaseTimes[i] : (releaseTimes[i] - releaseTimes[i - 1])); + + int maxv = t[0], res = 0; + for(int i = 1; i < 26; i ++) + if(t[i] >= maxv) res = i, maxv = t[i]; + return 'a' + res; + } +}; + + +int main() { + + vector releasTime1 = {9,29,49,50}; + cout << Solution().slowestKey(releasTime1, "cbcd") << endl; + // c + + vector releasTime2 = {12,23,36,46,62}; + cout << Solution().slowestKey(releasTime2, "spuda") << endl; + // a + + return 0; +} diff --git a/1501-2000/1630-Arithmetic-Subarrays/cpp-1630/CMakeLists.txt b/1501-2000/1630-Arithmetic-Subarrays/cpp-1630/CMakeLists.txt new file mode 100644 index 00000000..81ad8b42 --- /dev/null +++ b/1501-2000/1630-Arithmetic-Subarrays/cpp-1630/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1501-2000/1630-Arithmetic-Subarrays/cpp-1630/main.cpp b/1501-2000/1630-Arithmetic-Subarrays/cpp-1630/main.cpp new file mode 100644 index 00000000..b7d0370f --- /dev/null +++ b/1501-2000/1630-Arithmetic-Subarrays/cpp-1630/main.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/arithmetic-subarrays/ +/// Author : liuyubobobo +/// Time : 2020-10-24 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(qnlogn) +/// Space Complexity: O(n) +class Solution { +public: + vector checkArithmeticSubarrays(vector& nums, vector& l, vector& r) { + + vector res(l.size()); + for(int i = 0; i < l.size(); i ++) + res[i] = ok(nums, l[i], r[i]); + return res; + } + +private: + bool ok(const vector& nums, int l, int r){ + + vector a(nums.begin() + l, nums.begin() + (r + 1)); + sort(a.begin(), a.end()); + + int d = a[1] - a[0]; + for(int i = 2; i < a.size(); i ++) + if(a[i] - a[i - 1] != d) return false; + return true; + } +}; + + +void print_vec(const vector& v){ + for(bool e: v) cout << e << " "; cout << endl; +} + +int main() { + + vector nums1 = {4,6,5,9,3,7}, l1 = {0, 0, 2}, r1 = {2, 3, 5}; + print_vec(Solution().checkArithmeticSubarrays(nums1, l1, r1)); + // 1 0 1 + + vector nums2 = {-12,-9,-3,-12,-6,15,20,-25,-20,-15,-10}, + l2 = {0,1,6,4,8,7}, r2 = {4,4,9,7,9,10}; + print_vec(Solution().checkArithmeticSubarrays(nums2, l2, r2)); + // 0 1 0 0 1 1 + + return 0; +} diff --git a/1501-2000/1631-Path-With-Minimum-Effort/cpp-1631/CMakeLists.txt b/1501-2000/1631-Path-With-Minimum-Effort/cpp-1631/CMakeLists.txt new file mode 100644 index 00000000..80fb8c61 --- /dev/null +++ b/1501-2000/1631-Path-With-Minimum-Effort/cpp-1631/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main2.cpp) \ No newline at end of file diff --git a/1501-2000/1631-Path-With-Minimum-Effort/cpp-1631/main.cpp b/1501-2000/1631-Path-With-Minimum-Effort/cpp-1631/main.cpp new file mode 100644 index 00000000..69ab1590 --- /dev/null +++ b/1501-2000/1631-Path-With-Minimum-Effort/cpp-1631/main.cpp @@ -0,0 +1,80 @@ +/// Source : https://leetcode.com/problems/path-with-minimum-effort/ +/// Author : liuyubobobo +/// Time : 2020-10-24 + +#include +#include +#include + +using namespace std; + + +/// Dijkstra +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { + +private: + const int dirs[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; + int R, C; + +public: + int minimumEffortPath(vector>& heights) { + + R = heights.size(), C = heights[0].size(); + vector> dp(R, vector(C, -1)); + vector> visited(R, vector(C, false)); + + priority_queue, vector>, greater>> pq; + pq.push({0, 0}); + while(!pq.empty()){ + int curdis = pq.top().first, cur = pq.top().second; + pq.pop(); + + int curx = cur / C, cury = cur % C; + if(visited[curx][cury]) continue; + + visited[curx][cury] = true; + for(int d = 0; d < 4; d ++){ + int nextx = curx + dirs[d][0], nexty = cury + dirs[d][1]; + if(in_area(nextx, nexty) && !visited[nextx][nexty] && + (dp[nextx][nexty] == -1 || max(dp[curx][cury], abs(heights[nextx][nexty] - heights[curx][cury])) < dp[nextx][nexty])){ + dp[nextx][nexty] = max(dp[curx][cury], abs(heights[nextx][nexty] - heights[curx][cury])); + pq.push({dp[nextx][nexty], nextx * C + nexty}); + } + } + } + return dp[R - 1][C - 1] == -1 ? 0 : dp[R - 1][C - 1]; + } + +private: + bool in_area(int x, int y){ + return x >= 0 && x < R && y >= 0 && y < C; + } +}; + + +int main() { + + vector> heights1 = {{1,2,2},{3,8,2},{5,3,5}}; + cout << Solution().minimumEffortPath(heights1) << endl; + // 2 + + vector> heights2 = {{1,2,3},{3,8,4},{5,3,5}}; + cout << Solution().minimumEffortPath(heights2) << endl; + // 1 + + vector> heights3 = {{1,2,1,1,1},{1,2,1,2,1},{1,2,1,2,1},{1,2,1,2,1},{1,1,1,2,1}}; + cout << Solution().minimumEffortPath(heights3) << endl; + // 0 + + vector> heights4 = {{3}}; + cout << Solution().minimumEffortPath(heights4) << endl; + // 0 + + vector> heights5 = {{1, 10, 6, 7, 9, 10, 4, 9}}; + cout << Solution().minimumEffortPath(heights5) << endl; + // 9 + + return 0; +} diff --git a/1501-2000/1631-Path-With-Minimum-Effort/cpp-1631/main2.cpp b/1501-2000/1631-Path-With-Minimum-Effort/cpp-1631/main2.cpp new file mode 100644 index 00000000..beedf6b9 --- /dev/null +++ b/1501-2000/1631-Path-With-Minimum-Effort/cpp-1631/main2.cpp @@ -0,0 +1,96 @@ +/// Source : https://leetcode.com/problems/path-with-minimum-effort/ +/// Author : liuyubobobo +/// Time : 2020-11-01 + +#include +#include +#include + +using namespace std; + + +/// Edge Sorting and UF +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class UF{ + +private: + vector parent; + +public: + UF(int n){ + for(int i = 0 ; i < n ; i ++) + parent.push_back(i); + } + + int find(int p){ + if( p != parent[p] ) + parent[p] = find( parent[p] ); + return parent[p]; + } + + bool isConnected(int p , int q){ + return find(p) == find(q); + } + + void unionElements(int p, int q){ + + int pRoot = find(p); + int qRoot = find(q); + + if( pRoot == qRoot ) + return; + + parent[pRoot] = qRoot; + } +}; + +class Solution { + +public: + int minimumEffortPath(vector>& heights) { + + int R = heights.size(), C = heights[0].size(); + vector> edges; + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++){ + if(i + 1 < R) edges.push_back({abs(heights[i][j] - heights[i + 1][j]), i * C + j, (i + 1) * C + j}); + if(j + 1 < C) edges.push_back({abs(heights[i][j] - heights[i][j + 1]), i * C + j, i * C + j + 1}); + } + + sort(edges.begin(), edges.end()); + + UF uf(R * C); + for(const vector& e: edges){ + uf.unionElements(e[1], e[2]); + if(uf.isConnected(0, R * C - 1)) return e[0]; + } + return 0; + } +}; + + +int main() { + + vector> heights1 = {{1,2,2},{3,8,2},{5,3,5}}; + cout << Solution().minimumEffortPath(heights1) << endl; + // 2 + + vector> heights2 = {{1,2,3},{3,8,4},{5,3,5}}; + cout << Solution().minimumEffortPath(heights2) << endl; + // 1 + + vector> heights3 = {{1,2,1,1,1},{1,2,1,2,1},{1,2,1,2,1},{1,2,1,2,1},{1,1,1,2,1}}; + cout << Solution().minimumEffortPath(heights3) << endl; + // 0 + + vector> heights4 = {{3}}; + cout << Solution().minimumEffortPath(heights4) << endl; + // 0 + + vector> heights5 = {{1, 10, 6, 7, 9, 10, 4, 9}}; + cout << Solution().minimumEffortPath(heights5) << endl; + // 9 + + return 0; +} diff --git a/1501-2000/1632-Rank-Transform-of-a-Matrix/cpp-1632/CMakeLists.txt b/1501-2000/1632-Rank-Transform-of-a-Matrix/cpp-1632/CMakeLists.txt new file mode 100644 index 00000000..74cc3ee6 --- /dev/null +++ b/1501-2000/1632-Rank-Transform-of-a-Matrix/cpp-1632/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) \ No newline at end of file diff --git a/1501-2000/1632-Rank-Transform-of-a-Matrix/cpp-1632/main.cpp b/1501-2000/1632-Rank-Transform-of-a-Matrix/cpp-1632/main.cpp new file mode 100644 index 00000000..8bc3bd7d --- /dev/null +++ b/1501-2000/1632-Rank-Transform-of-a-Matrix/cpp-1632/main.cpp @@ -0,0 +1,151 @@ +/// Source : https://leetcode.com/problems/rank-transform-of-a-matrix/ +/// Author : liuyubobobo +/// Time : 2020-11-01 + +#include +#include +#include +#include + +using namespace std; + + +/// Sorting + UF +/// Time Complexity: O(R * C * log(R * C)) +/// Space Complexity: O(R * C) +class UF{ + +private: + vector parent; + +public: + UF(int n){ + for(int i = 0 ; i < n ; i ++) + parent.push_back(i); + } + + int find(int p){ + if( p != parent[p] ) + parent[p] = find( parent[p] ); + return parent[p]; + } + + bool isConnected(int p , int q){ + return find(p) == find(q); + } + + void unionElements(int p, int q){ + + int pRoot = find(p); + int qRoot = find(q); + + if( pRoot == qRoot ) + return; + + parent[pRoot] = qRoot; + } +}; + +class Solution { + +private: + int R, C; + +public: + vector> matrixRankTransform(vector>& matrix) { + + R = matrix.size(); + C = matrix[0].size(); + + map> data; + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++) + data[matrix[i][j]].push_back(i * C + j); + + vector> res(R, vector(C, 0)); + vector rowmax(R, 0), colmax(C, 0); + UF uf(R * C); + for(const pair>& p: data){ + + unordered_map> groups = get_groups(p.second, uf); + for(const pair>&pgroup: groups){ + + //pgroup.second : one group + int rank = 0; + for(int v: pgroup.second) + rank = max(rank, max(rowmax[v / C], colmax[v % C]) + 1); + + for(int v: pgroup.second){ + res[v / C][v % C] = rank; + rowmax[v / C] = max(rowmax[v / C], rank); + colmax[v % C] = max(colmax[v % C], rank); + } + } + } + return res; + } + +private: + unordered_map> get_groups(const vector& vec, UF& uf){ + + unordered_map> rows, cols; + for(int v: vec) + rows[v / C].push_back(v), cols[v % C].push_back(v); + + for(const pair>& p: rows) + for(int i = 1; i < p.second.size(); i ++) + uf.unionElements(p.second[i], p.second[i - 1]); + + for(const pair>& p: cols) + for(int i = 1; i < p.second.size(); i ++) + uf.unionElements(p.second[i], p.second[i - 1]); + + unordered_map> res; + for(int v: vec) + res[uf.find(v)].push_back(v); + return res; + } +}; + + +void print_matrix(const vector>& matrix){ + for(const vector& row: matrix){ + for(int e: row) cout << e << " "; cout << endl; + } + cout << endl; +} + +int main() { + + vector> matrix1 = {{1, 2}, {3, 4}}; + print_matrix(Solution().matrixRankTransform(matrix1)); + // 1 2 + // 2 3 + + vector> matrix2 = {{7, 7}, {7, 7}}; + print_matrix(Solution().matrixRankTransform(matrix2)); + // 1 1 + // 1 1 + + vector> matrix3 = {{20,-21,14}, {-19,4,19}, {22, -47,24}, {-19, 4, 19}}; + print_matrix(Solution().matrixRankTransform(matrix3)); + // 4 2 3 + // 1 3 4 + // 5 1 6 + // 1 3 4 + + vector> matrix4 = {{7, 3, 6}, {1, 4, 5}, {9, 8, 2}}; + print_matrix(Solution().matrixRankTransform(matrix4)); + // 5 1 4 + // 1 2 3 + // 6 3 1 + + vector> matrix5 = {{-37, -50, -3, 44}, {-37, 46, 13, -32}, {47, -42, -3, -40}, {-17, -22, -39, 24}}; + print_matrix(Solution().matrixRankTransform(matrix5)); + // 2 1 4 6 + // 2 6 5 4 + // 5 2 4 3 + // 4 3 1 5 + + return 0; +} diff --git a/1501-2000/1634-Add-Two-Polynomials-Represented-as-Linked-Lists/cpp-1634/CMakeLists.txt b/1501-2000/1634-Add-Two-Polynomials-Represented-as-Linked-Lists/cpp-1634/CMakeLists.txt new file mode 100644 index 00000000..9566b75c --- /dev/null +++ b/1501-2000/1634-Add-Two-Polynomials-Represented-as-Linked-Lists/cpp-1634/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1634) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1634 main.cpp) \ No newline at end of file diff --git a/1501-2000/1634-Add-Two-Polynomials-Represented-as-Linked-Lists/cpp-1634/main.cpp b/1501-2000/1634-Add-Two-Polynomials-Represented-as-Linked-Lists/cpp-1634/main.cpp new file mode 100644 index 00000000..b8a6fa1c --- /dev/null +++ b/1501-2000/1634-Add-Two-Polynomials-Represented-as-Linked-Lists/cpp-1634/main.cpp @@ -0,0 +1,51 @@ +/// Source : https://leetcode.com/problems/add-two-polynomials-represented-as-linked-lists/ +/// Author : liuyubobobo +/// Time : 2020-11-01 + +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(n + m) +/// Space Complexity: O(1) + +/// Definition for polynomial singly-linked list. +struct PolyNode { + int coefficient, power; + PolyNode *next; + PolyNode(): coefficient(0), power(0), next(nullptr) {}; + PolyNode(int x, int y): coefficient(x), power(y), next(nullptr) {}; + PolyNode(int x, int y, PolyNode* next): coefficient(x), power(y), next(next) {}; +}; + +class Solution { +public: + PolyNode* addPoly(PolyNode* poly1, PolyNode* poly2) { + + PolyNode* dummyHead = new PolyNode(); + PolyNode* cur = dummyHead; + PolyNode* a = poly1, *b = poly2; + while(a || b){ + if(!a) cur->next = new PolyNode(b->coefficient, b->power), cur = cur->next, b = b ->next; + else if(!b) cur->next = new PolyNode(a->coefficient, a->power), cur = cur->next, a = a ->next; + else if(a->power == b->power){ + if(a->coefficient + b->coefficient){ + cur->next = new PolyNode(a->coefficient + b->coefficient, a->power); + cur = cur->next; + } + a = a->next, b = b->next; + } + else if(a->power > b->power) cur->next = new PolyNode(a->coefficient, a->power), cur = cur->next, a = a ->next; + else cur->next = new PolyNode(b->coefficient, b->power), cur = cur->next, b = b ->next; + } + return dummyHead->next; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1636-Sort-Array-by-Increasing-Frequency/cpp-1636/CMakeLists.txt b/1501-2000/1636-Sort-Array-by-Increasing-Frequency/cpp-1636/CMakeLists.txt new file mode 100644 index 00000000..cdbe19bf --- /dev/null +++ b/1501-2000/1636-Sort-Array-by-Increasing-Frequency/cpp-1636/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1636) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1636 main.cpp) \ No newline at end of file diff --git a/1501-2000/1636-Sort-Array-by-Increasing-Frequency/cpp-1636/main.cpp b/1501-2000/1636-Sort-Array-by-Increasing-Frequency/cpp-1636/main.cpp new file mode 100644 index 00000000..bd45af59 --- /dev/null +++ b/1501-2000/1636-Sort-Array-by-Increasing-Frequency/cpp-1636/main.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/sort-array-by-increasing-frequency/ +/// Author : liuyubobobo +/// Time : 2020-10-31 + +#include +#include +#include + +using namespace std; + + +/// Sorting +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + vector frequencySort(vector& nums) { + + unordered_map f; + for(int e: nums) f[e] ++; + + sort(nums.begin(), nums.end(), [&](int a, int b){ + if(f[a] != f[b]) return f[a] < f[b]; + return a > b; + }); + return nums; + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << " "; cout << endl; +} + +int main() { + + vector nums1 = {1, 1, 2, 2, 2, 3}; + print_vec(Solution().frequencySort(nums1)); + // 3 1 1 2 2 2 + + vector nums2 = {2,3,1,3,2}; + print_vec(Solution().frequencySort(nums2)); + // 1,3,3,2,2 + + return 0; +} diff --git a/1501-2000/1637-Widest-Vertical-Area-Between-Two-Points-Containing-No-Points/cpp-1637/CMakeLists.txt b/1501-2000/1637-Widest-Vertical-Area-Between-Two-Points-Containing-No-Points/cpp-1637/CMakeLists.txt new file mode 100644 index 00000000..1b828152 --- /dev/null +++ b/1501-2000/1637-Widest-Vertical-Area-Between-Two-Points-Containing-No-Points/cpp-1637/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1637) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1637 main2.cpp) \ No newline at end of file diff --git a/1501-2000/1637-Widest-Vertical-Area-Between-Two-Points-Containing-No-Points/cpp-1637/main.cpp b/1501-2000/1637-Widest-Vertical-Area-Between-Two-Points-Containing-No-Points/cpp-1637/main.cpp new file mode 100644 index 00000000..0d2d2f60 --- /dev/null +++ b/1501-2000/1637-Widest-Vertical-Area-Between-Two-Points-Containing-No-Points/cpp-1637/main.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/widest-vertical-area-between-two-points-containing-no-points/ +/// Author : liuyubobobo +/// Time : 2020-10-31 + +#include +#include +#include + +using namespace std; + + +/// TreeSet +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + int maxWidthOfVerticalArea(vector>& points) { + + set set; + for(const vector& p: points) set.insert(p[0]); + + if(set.size() <= 1) return 0; + + int last = *set.begin(), res = 0; + for(int e: set){ + res = max(res, e - last); + last = e; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1637-Widest-Vertical-Area-Between-Two-Points-Containing-No-Points/cpp-1637/main2.cpp b/1501-2000/1637-Widest-Vertical-Area-Between-Two-Points-Containing-No-Points/cpp-1637/main2.cpp new file mode 100644 index 00000000..2a676fda --- /dev/null +++ b/1501-2000/1637-Widest-Vertical-Area-Between-Two-Points-Containing-No-Points/cpp-1637/main2.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/widest-vertical-area-between-two-points-containing-no-points/ +/// Author : liuyubobobo +/// Time : 2020-10-31 + +#include +#include +#include + +using namespace std; + + +/// Sorting +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + int maxWidthOfVerticalArea(vector>& points) { + + sort(points.begin(), points.end()); + + int last = points[0][0], res = 0; + for(const vector& p: points){ + res = max(res, p[0] - last); + last = p[0]; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1638-Count-Substrings-That-Differ-by-One-Character/cpp-1638/CMakeLists.txt b/1501-2000/1638-Count-Substrings-That-Differ-by-One-Character/cpp-1638/CMakeLists.txt new file mode 100644 index 00000000..070b2ade --- /dev/null +++ b/1501-2000/1638-Count-Substrings-That-Differ-by-One-Character/cpp-1638/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1638) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1638 main4.cpp) \ No newline at end of file diff --git a/1501-2000/1638-Count-Substrings-That-Differ-by-One-Character/cpp-1638/main.cpp b/1501-2000/1638-Count-Substrings-That-Differ-by-One-Character/cpp-1638/main.cpp new file mode 100644 index 00000000..15252800 --- /dev/null +++ b/1501-2000/1638-Count-Substrings-That-Differ-by-One-Character/cpp-1638/main.cpp @@ -0,0 +1,48 @@ +/// Source : https://leetcode.com/problems/count-substrings-that-differ-by-one-character/ +/// Author : liuyubobobo +/// Time : 2020-10-31 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(|s| * |t| * min(|s|, |t|)) +/// Space Complexity: O(1) +class Solution { +public: + int countSubstrings(string s, string t) { + + int res = 0; + for(int i = 0; i < s.size(); i ++) + for(int j = 0; j < t.size(); j ++){ + int diff = 0; + for(int len = 0; i + len < s.size() && j + len < t.size(); len ++){ + diff += s[i + len] != t[j + len]; + if(diff == 1) res ++; + else if(diff > 1) break; + } + } + return res; + } +}; + + +int main() { + + cout << Solution().countSubstrings("aba", "baba") << endl; + // 6 + + cout << Solution().countSubstrings("ab", "bb") << endl; + // 3 + + cout << Solution().countSubstrings("a", "a") << endl; + // 0 + + cout << Solution().countSubstrings("abe", "bbc") << endl; + // 10 + + return 0; +} diff --git a/1501-2000/1638-Count-Substrings-That-Differ-by-One-Character/cpp-1638/main2.cpp b/1501-2000/1638-Count-Substrings-That-Differ-by-One-Character/cpp-1638/main2.cpp new file mode 100644 index 00000000..9290cb21 --- /dev/null +++ b/1501-2000/1638-Count-Substrings-That-Differ-by-One-Character/cpp-1638/main2.cpp @@ -0,0 +1,64 @@ +/// Source : https://leetcode.com/problems/count-substrings-that-differ-by-one-character/ +/// Author : liuyubobobo +/// Time : 2020-11-01 + +#include +#include +#include + +using namespace std; + + +/// Check middle difference and counting left and right same substring +/// Time Complexity: O(|s| * |t|) +/// Space Complexity: O(|s| * |t|) +class Solution { +public: + int countSubstrings(string s, string t) { + + vector> pre(s.size(), vector(t.size(), 0)); + for(int j = 0; j < t.size(); j ++) pre[0][j] = s[0] == t[j] ? 1 : 0; + for(int i = 0; i < s.size(); i ++) pre[i][0] = s[i] == t[0] ? 1 : 0; + for(int i = 1; i < s.size(); i ++) + for(int j = 1; j < t.size(); j ++) + pre[i][j] = (s[i] == t[j] ? pre[i - 1][j - 1] + 1 : 0); + + vector> post(s.size(), vector(t.size(), 0)); + for(int j = 0; j < t.size(); j ++) post[s.size() - 1][j] = s.back() == t[j] ? 1 : 0; + for(int i = 0; i < s.size(); i ++) post[i][t.size() - 1] = s[i] == t.back() ? 1: 0; + for(int i = (int)s.size() - 2; i >= 0; i --) + for(int j = (int)t.size() - 2; j >= 0; j --) + post[i][j] = (s[i] == t[j] ? post[i + 1][j + 1] + 1 : 0); + + int res = 0; + for(int i = 0; i < s.size(); i ++) + for(int j = 0; j < t.size(); j ++) + if(s[i] != t[j]){ + int a = ((i - 1 >= 0 && j - 1 >= 0) ? pre[i - 1][j - 1] : 0) + 1; + int b = ((i + 1 < s.size() && j + 1 < t.size()) ? post[i + 1][j + 1] : 0) + 1; + res += a * b; + } + return res; + } +}; + + +int main() { + + cout << Solution().countSubstrings("aba", "baba") << endl; + // 6 + + cout << Solution().countSubstrings("ab", "bb") << endl; + // 3 + + cout << Solution().countSubstrings("a", "a") << endl; + // 0 + + cout << Solution().countSubstrings("abe", "bbc") << endl; + // 10 + + cout << Solution().countSubstrings("abbab", "bbbbb") << endl; + // 33 + + return 0; +} diff --git a/1501-2000/1638-Count-Substrings-That-Differ-by-One-Character/cpp-1638/main3.cpp b/1501-2000/1638-Count-Substrings-That-Differ-by-One-Character/cpp-1638/main3.cpp new file mode 100644 index 00000000..4676388c --- /dev/null +++ b/1501-2000/1638-Count-Substrings-That-Differ-by-One-Character/cpp-1638/main3.cpp @@ -0,0 +1,61 @@ +/// Source : https://leetcode.com/problems/count-substrings-that-differ-by-one-character/ +/// Author : liuyubobobo +/// Time : 2020-11-01 + +#include +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(|s| * |t|) +/// Space Complexity: O(|s| * |t|) +class Solution { +public: + int countSubstrings(string s, string t) { + + vector> same(s.size(), vector(t.size(), 0)); + for(int j = 0; j < t.size(); j ++) same[0][j] = s[0] == t[j] ? 1 : 0; + for(int i = 0; i < s.size(); i ++) same[i][0] = s[i] == t[0] ? 1 : 0; + for(int i = 1; i < s.size(); i ++) + for(int j = 1; j < t.size(); j ++) + same[i][j] = (s[i] == t[j] ? same[i - 1][j - 1] + 1 : 0); + + vector> diff1(s.size(), vector(t.size(), 0)); + for(int j = 0; j < t.size(); j ++) diff1[0][j] = s[0] == t[j] ? 0 : 1; + for(int i = 0; i < s.size(); i ++) diff1[i][0] = s[i] == t[0] ? 0 : 1; + for(int i = 1; i < s.size(); i ++) + for(int j = 1; j < t.size(); j ++) + if(s[i] != t[j]) diff1[i][j] = 1 + same[i - 1][j - 1]; + else diff1[i][j] = diff1[i - 1][j - 1]; + + int res = 0; + for(int i = 0; i < s.size(); i ++) + for(int j = 0; j < t.size(); j ++) + res += diff1[i][j]; + return res; + } +}; + + +int main() { + + cout << Solution().countSubstrings("aba", "baba") << endl; + // 6 + + cout << Solution().countSubstrings("ab", "bb") << endl; + // 3 + + cout << Solution().countSubstrings("a", "a") << endl; + // 0 + + cout << Solution().countSubstrings("abe", "bbc") << endl; + // 10 + + cout << Solution().countSubstrings("abbab", "bbbbb") << endl; + // 33 + + return 0; +} diff --git a/1501-2000/1638-Count-Substrings-That-Differ-by-One-Character/cpp-1638/main4.cpp b/1501-2000/1638-Count-Substrings-That-Differ-by-One-Character/cpp-1638/main4.cpp new file mode 100644 index 00000000..8bf3dc72 --- /dev/null +++ b/1501-2000/1638-Count-Substrings-That-Differ-by-One-Character/cpp-1638/main4.cpp @@ -0,0 +1,68 @@ +/// Source : https://leetcode.com/problems/count-substrings-that-differ-by-one-character/ +/// Author : liuyubobobo +/// Time : 2020-11-01 + +#include +#include +#include + +using namespace std; + + +/// Dynamic Programming with Space Optimization +/// Time Complexity: O(|s| * |t|) +/// Space Complexity: O(|s| * |t|) +class Solution { +public: + int countSubstrings(string s, string t) { + + int res = 0, same, diff1; + for(int j = 0; j < t.size(); j ++){ + int curi = 0, curj = j; + same = s[curi] == t[curj] ? 1 : 0; + diff1 = 1 - same; + res += diff1; + while(curi + 1 < s.size() && curj + 1 < t.size()){ + curi ++, curj ++; + diff1 = s[curi] == t[curj] ? diff1 : (same + 1); + same = s[curi] == t[curj] ? same + 1 : 0; + res += diff1; + } + } + + for(int i = 1; i < s.size(); i ++){ + int curi = i, curj = 0; + same = s[curi] == t[curj] ? 1 : 0; + diff1 = 1 - same; + res += diff1; + while(curi + 1 < s.size() && curj + 1 < t.size()){ + curi ++, curj ++; + diff1 = s[curi] == t[curj] ? diff1 : (same + 1); + same = s[curi] == t[curj] ? same + 1 : 0; + res += diff1; + } + } + return res; + } +}; + + +int main() { + + cout << Solution().countSubstrings("aba", "baba") << endl; + // 6 + + cout << Solution().countSubstrings("ab", "bb") << endl; + // 3 + + cout << Solution().countSubstrings("a", "a") << endl; + // 0 + + cout << Solution().countSubstrings("abe", "bbc") << endl; + // 10 + + cout << Solution().countSubstrings("abbab", "bbbbb") << endl; + // 33 + + return 0; +} diff --git a/1501-2000/1639-Number-of-Ways-to-Form-a-Target-String-Given-a-Dictionary/cpp-1639/CMakeLists.txt b/1501-2000/1639-Number-of-Ways-to-Form-a-Target-String-Given-a-Dictionary/cpp-1639/CMakeLists.txt new file mode 100644 index 00000000..e2ecf2ae --- /dev/null +++ b/1501-2000/1639-Number-of-Ways-to-Form-a-Target-String-Given-a-Dictionary/cpp-1639/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1639) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1639 main3.cpp) \ No newline at end of file diff --git a/1501-2000/1639-Number-of-Ways-to-Form-a-Target-String-Given-a-Dictionary/cpp-1639/main.cpp b/1501-2000/1639-Number-of-Ways-to-Form-a-Target-String-Given-a-Dictionary/cpp-1639/main.cpp new file mode 100644 index 00000000..23b20b72 --- /dev/null +++ b/1501-2000/1639-Number-of-Ways-to-Form-a-Target-String-Given-a-Dictionary/cpp-1639/main.cpp @@ -0,0 +1,65 @@ +/// Source : https://leetcode.com/problems/number-of-ways-to-form-a-target-string-given-a-dictionary/ +/// Author : liuyubobobo +/// Time : 2020-10-31 + +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(|words| * len + len * |target|) +/// Space Complexity: O(|words| * len + len * |target|) +class Solution { + +private: + const int MOD = 1e9 + 7; + +public: + int numWays(vector& words, string target) { + + int len = words[0].size(); + vector> data(len, vector(26, 0)); + for(int i = 0; i < words.size(); i ++) + for(int j = 0; j < len; j ++) data[j][words[i][j] - 'a'] ++; + + vector> dp(len, vector(target.size(), -1)); + return dfs(data, target, 0, 0, dp); + } + +private: + int dfs(const vector>& data, const string& target, int di, int ti, + vector>& dp){ + + if(ti == target.size()) return 1; + if(di == data.size()) return 0; + if(dp[di][ti] != -1) return dp[di][ti]; + + int res = (long long)data[di][target[ti] - 'a'] * dfs(data, target, di + 1, ti + 1, dp) % MOD; + res = res + dfs(data, target, di + 1, ti, dp); + return dp[di][ti] = res % MOD; + } +}; + + +int main() { + + vector words1 = {"acca","bbbb","caca"}; + cout << Solution().numWays(words1, "aba") << endl; + // 6 + + vector words2 = {"abba","baab"}; + cout << Solution().numWays(words2, "bab") << endl; + // 4 + + vector words3 = {"abcd"}; + cout << Solution().numWays(words3, "abcd") << endl; + // 1 + + vector words4 = {"abab","baba","abba","baab"}; + cout << Solution().numWays(words4, "abba") << endl; + // 16 + + return 0; +} diff --git a/1501-2000/1639-Number-of-Ways-to-Form-a-Target-String-Given-a-Dictionary/cpp-1639/main2.cpp b/1501-2000/1639-Number-of-Ways-to-Form-a-Target-String-Given-a-Dictionary/cpp-1639/main2.cpp new file mode 100644 index 00000000..2b8d52ca --- /dev/null +++ b/1501-2000/1639-Number-of-Ways-to-Form-a-Target-String-Given-a-Dictionary/cpp-1639/main2.cpp @@ -0,0 +1,61 @@ +/// Source : https://leetcode.com/problems/number-of-ways-to-form-a-target-string-given-a-dictionary/ +/// Author : liuyubobobo +/// Time : 2020-11-01 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(|words| * len + len * |target|) +/// Space Complexity: O(|words| * len + len * |target|) +class Solution { + +private: + const int MOD = 1e9 + 7; + +public: + int numWays(vector& words, string target) { + + int len = words[0].size(); + vector> data(len, vector(26, 0)); + for(int i = 0; i < words.size(); i ++) + for(int j = 0; j < len; j ++) data[j][words[i][j] - 'a'] ++; + + vector> dp(len, vector(target.size(), 0)); + dp[0][0] = data[0][target[0] - 'a']; + + for(int i = 1; i < len; i ++){ + dp[i][0] = (data[i][target[0] - 'a'] + dp[i - 1][0]) % MOD; + for(int j = 1; j < target.size(); j ++){ + dp[i][j] = (long long)data[i][target[j] - 'a'] * dp[i - 1][j - 1] % MOD; + dp[i][j] = (dp[i][j] + dp[i - 1][j]) % MOD; + } + } + return dp[len - 1][target.size() - 1]; + } +}; + + +int main() { + + vector words1 = {"acca","bbbb","caca"}; + cout << Solution().numWays(words1, "aba") << endl; + // 6 + + vector words2 = {"abba","baab"}; + cout << Solution().numWays(words2, "bab") << endl; + // 4 + + vector words3 = {"abcd"}; + cout << Solution().numWays(words3, "abcd") << endl; + // 1 + + vector words4 = {"abab","baba","abba","baab"}; + cout << Solution().numWays(words4, "abba") << endl; + // 16 + + return 0; +} diff --git a/1501-2000/1639-Number-of-Ways-to-Form-a-Target-String-Given-a-Dictionary/cpp-1639/main3.cpp b/1501-2000/1639-Number-of-Ways-to-Form-a-Target-String-Given-a-Dictionary/cpp-1639/main3.cpp new file mode 100644 index 00000000..be0c864b --- /dev/null +++ b/1501-2000/1639-Number-of-Ways-to-Form-a-Target-String-Given-a-Dictionary/cpp-1639/main3.cpp @@ -0,0 +1,59 @@ +/// Source : https://leetcode.com/problems/number-of-ways-to-form-a-target-string-given-a-dictionary/ +/// Author : liuyubobobo +/// Time : 2020-11-01 + +#include +#include + +using namespace std; + + +/// Dynamic Programming with Space Optimization +/// Time Complexity: O(|words| * len + len * |target|) +/// Space Complexity: O(|words| * len + |target|) +class Solution { + +private: + const int MOD = 1e9 + 7; + +public: + int numWays(vector& words, string target) { + + int len = words[0].size(); + vector> data(len, vector(26, 0)); + for(int i = 0; i < words.size(); i ++) + for(int j = 0; j < len; j ++) data[j][words[i][j] - 'a'] ++; + + vector dp(target.size(), 0); + dp[0] = data[0][target[0] - 'a']; + + for(int i = 1; i < len; i ++){ + for(int j = target.size() - 1; j > 0; j --) + dp[j] = (dp[j] + (long long)data[i][target[j] - 'a'] * dp[j - 1] % MOD) % MOD; + dp[0] = (dp[0] + data[i][target[0] - 'a']) % MOD; + } + return dp[target.size() - 1]; + } +}; + + +int main() { + + vector words1 = {"acca","bbbb","caca"}; + cout << Solution().numWays(words1, "aba") << endl; + // 6 + + vector words2 = {"abba","baab"}; + cout << Solution().numWays(words2, "bab") << endl; + // 4 + + vector words3 = {"abcd"}; + cout << Solution().numWays(words3, "abcd") << endl; + // 1 + + vector words4 = {"abab","baba","abba","baab"}; + cout << Solution().numWays(words4, "abba") << endl; + // 16 + + return 0; +} diff --git a/1501-2000/1640-Check-Array-Formation-Through-Concatenation/cpp-1640/CMakeLists.txt b/1501-2000/1640-Check-Array-Formation-Through-Concatenation/cpp-1640/CMakeLists.txt new file mode 100644 index 00000000..d5d5e4ff --- /dev/null +++ b/1501-2000/1640-Check-Array-Formation-Through-Concatenation/cpp-1640/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1501-2000/1640-Check-Array-Formation-Through-Concatenation/cpp-1640/main.cpp b/1501-2000/1640-Check-Array-Formation-Through-Concatenation/cpp-1640/main.cpp new file mode 100644 index 00000000..d4b1cb37 --- /dev/null +++ b/1501-2000/1640-Check-Array-Formation-Through-Concatenation/cpp-1640/main.cpp @@ -0,0 +1,66 @@ +/// Source : https://leetcode.com/problems/check-array-formation-through-concatenation/ +/// Author : liuyubobobo +/// Time : 2020-10-31 + +#include +#include +#include + +using namespace std; + + +/// Using HashpMap +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + bool canFormArray(vector& arr, vector>& pieces) { + + unordered_map> pmap; + for(const vector& row: pieces) + pmap[row[0]] = row; + + int i = 0; + while(i < arr.size()){ + int a = arr[i]; + if(!pmap.count(a)) return false; + + for(int e: pmap[a]){ + if(arr[i] != e) return false; + i ++; + } + } + return i == arr.size(); + } +}; + + +int main() { + + vector arr1 = {85}; + vector> pieces1 = {{85}}; + cout << Solution().canFormArray(arr1, pieces1) << endl; + // 1 + + vector arr2 = {15, 88}; + vector> pieces2 = {{88}, {15}}; + cout << Solution().canFormArray(arr2, pieces2) << endl; + // 1 + + vector arr3 = {49,18,16}; + vector> pieces3 = {{16,18,49}}; + cout << Solution().canFormArray(arr3, pieces3) << endl; + // 0 + + vector arr4 = {91,4,64,78}; + vector> pieces4 = {{78},{4,64},{91}}; + cout << Solution().canFormArray(arr4, pieces4) << endl; + // 1 + + vector arr5 = {1,3,5,7}; + vector> pieces5 = {{2, 4, 6, 8}}; + cout << Solution().canFormArray(arr5, pieces5) << endl; + // 0 + + return 0; +} diff --git a/1501-2000/1641-Count-Sorted-Vowel-Strings/cpp-1641/CMakeLists.txt b/1501-2000/1641-Count-Sorted-Vowel-Strings/cpp-1641/CMakeLists.txt new file mode 100644 index 00000000..aab7d499 --- /dev/null +++ b/1501-2000/1641-Count-Sorted-Vowel-Strings/cpp-1641/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main4.cpp) \ No newline at end of file diff --git a/1501-2000/1641-Count-Sorted-Vowel-Strings/cpp-1641/main.cpp b/1501-2000/1641-Count-Sorted-Vowel-Strings/cpp-1641/main.cpp new file mode 100644 index 00000000..4eaa9a6c --- /dev/null +++ b/1501-2000/1641-Count-Sorted-Vowel-Strings/cpp-1641/main.cpp @@ -0,0 +1,51 @@ +/// Source : https://leetcode.com/problems/count-sorted-vowel-strings/ +/// Author : liuyubobobo +/// Time : 2020-10-31 + +#include +#include + +using namespace std; + + +/// Memory Search +/// Tiime Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int countVowelStrings(int n) { + + vector> dp(n + 1, vector(5, -1)); + return dfs(n, 0, 0, dp); + } + +private: + int dfs(int n, int index, int letter, vector>& dp){ + + if(index == n) return 1; + if(dp[index][letter] != -1) return dp[index][letter]; + + int res = 0; + for(int i = letter; i < 5; i ++) + res += dfs(n, index + 1, i, dp); + return dp[index][letter] = res; + } +}; + + +int main() { + + cout << Solution().countVowelStrings(1) << endl; + // 5 + + cout << Solution().countVowelStrings(2) << endl; + // 15 + + cout << Solution().countVowelStrings(33) << endl; + // 66045 + + cout << Solution().countVowelStrings(50) << endl; + // 316251 + + return 0; +} diff --git a/1501-2000/1641-Count-Sorted-Vowel-Strings/cpp-1641/main2.cpp b/1501-2000/1641-Count-Sorted-Vowel-Strings/cpp-1641/main2.cpp new file mode 100644 index 00000000..b79eb29d --- /dev/null +++ b/1501-2000/1641-Count-Sorted-Vowel-Strings/cpp-1641/main2.cpp @@ -0,0 +1,45 @@ +/// Source : https://leetcode.com/problems/count-sorted-vowel-strings/ +/// Author : liuyubobobo +/// Time : 2020-11-01 + +#include +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Tiime Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int countVowelStrings(int n) { + + vector> dp(n, vector(5, 1)); + for(int i = 1; i < n; i ++) + for(int j = 0; j < 5; j ++){ + dp[i][j] = 0; + for(int k = 0; k <= j; k ++) dp[i][j] += dp[i - 1][k]; + } + return accumulate(dp[n - 1].begin(), dp[n - 1].end(), 0); + } +}; + + +int main() { + + cout << Solution().countVowelStrings(1) << endl; + // 5 + + cout << Solution().countVowelStrings(2) << endl; + // 15 + + cout << Solution().countVowelStrings(33) << endl; + // 66045 + + cout << Solution().countVowelStrings(50) << endl; + // 316251 + + return 0; +} diff --git a/1501-2000/1641-Count-Sorted-Vowel-Strings/cpp-1641/main3.cpp b/1501-2000/1641-Count-Sorted-Vowel-Strings/cpp-1641/main3.cpp new file mode 100644 index 00000000..f150a9c5 --- /dev/null +++ b/1501-2000/1641-Count-Sorted-Vowel-Strings/cpp-1641/main3.cpp @@ -0,0 +1,44 @@ +/// Source : https://leetcode.com/problems/count-sorted-vowel-strings/ +/// Author : liuyubobobo +/// Time : 2020-11-01 + +#include +#include +#include + +using namespace std; + + +/// Dynamic Programming with Space Optimization +/// Tiime Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int countVowelStrings(int n) { + + vector dp(5, 1); + for(int i = 1; i < n; i ++) + for(int j = 4; j >= 0; j --){ + for(int k = 0; k < j; k ++) dp[j] += dp[k]; + } + return accumulate(dp.begin(), dp.end(), 0); + } +}; + + +int main() { + + cout << Solution().countVowelStrings(1) << endl; + // 5 + + cout << Solution().countVowelStrings(2) << endl; + // 15 + + cout << Solution().countVowelStrings(33) << endl; + // 66045 + + cout << Solution().countVowelStrings(50) << endl; + // 316251 + + return 0; +} diff --git a/1501-2000/1641-Count-Sorted-Vowel-Strings/cpp-1641/main4.cpp b/1501-2000/1641-Count-Sorted-Vowel-Strings/cpp-1641/main4.cpp new file mode 100644 index 00000000..8c0eba99 --- /dev/null +++ b/1501-2000/1641-Count-Sorted-Vowel-Strings/cpp-1641/main4.cpp @@ -0,0 +1,38 @@ +/// Source : https://leetcode.com/problems/count-sorted-vowel-strings/ +/// Author : liuyubobobo +/// Time : 2020-11-01 + +#include +#include +#include + +using namespace std; + + +/// Math +/// Tiime Complexity: O(1) +/// Space Complexity: O(1) +class Solution { +public: + int countVowelStrings(int n) { + return (n + 4) * (n + 3) * (n + 2) * (n + 1) / 24; + } +}; + + +int main() { + + cout << Solution().countVowelStrings(1) << endl; + // 5 + + cout << Solution().countVowelStrings(2) << endl; + // 15 + + cout << Solution().countVowelStrings(33) << endl; + // 66045 + + cout << Solution().countVowelStrings(50) << endl; + // 316251 + + return 0; +} diff --git a/1501-2000/1642-Furthest-Building-You-Can-Reach/cpp-1642/CMakeLists.txt b/1501-2000/1642-Furthest-Building-You-Can-Reach/cpp-1642/CMakeLists.txt new file mode 100644 index 00000000..ce73aee9 --- /dev/null +++ b/1501-2000/1642-Furthest-Building-You-Can-Reach/cpp-1642/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1501-2000/1642-Furthest-Building-You-Can-Reach/cpp-1642/main.cpp b/1501-2000/1642-Furthest-Building-You-Can-Reach/cpp-1642/main.cpp new file mode 100644 index 00000000..708d5277 --- /dev/null +++ b/1501-2000/1642-Furthest-Building-You-Can-Reach/cpp-1642/main.cpp @@ -0,0 +1,51 @@ +/// Source : https://leetcode.com/problems/furthest-building-you-can-reach/ +/// Author : liuyubobobo +/// Time : 2020-10-31 + +#include +#include +#include + +using namespace std; + + +/// Priority Queue + Greedy +/// Time Complexity: O(nlogk) +/// Space Complexity: O(k) +class Solution { +public: + int furthestBuilding(vector& heights, int bricks, int ladders) { + + int res = 0; + priority_queue, greater> pq; + for(int i = 1; i < heights.size(); i ++) + if(heights[i] > heights[i - 1]){ + int a = heights[i] - heights[i - 1]; + pq.push(a); + if(pq.size() > ladders){ + int x = pq.top(); pq.pop(); + if(x > bricks) return i - 1; + bricks -= x; + } + } + return heights.size() - 1; + } +}; + + +int main() { + + vector heights1 = {4,2,7,6,9,14,12}; + cout << Solution().furthestBuilding(heights1, 5, 1) << endl; + // 4 + + vector heights2 = {4,12,2,7,3,18,20,3,19}; + cout << Solution().furthestBuilding(heights2, 10, 2) << endl; + // 7 + + vector heights3 = {14,3,19,3}; + cout << Solution().furthestBuilding(heights3, 17, 0) << endl; + // 3 + + return 0; +} diff --git a/1501-2000/1643-Kth-Smallest-Instructions/cpp-1643/CMakeLists.txt b/1501-2000/1643-Kth-Smallest-Instructions/cpp-1643/CMakeLists.txt new file mode 100644 index 00000000..74cc3ee6 --- /dev/null +++ b/1501-2000/1643-Kth-Smallest-Instructions/cpp-1643/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) \ No newline at end of file diff --git a/1501-2000/1643-Kth-Smallest-Instructions/cpp-1643/main.cpp b/1501-2000/1643-Kth-Smallest-Instructions/cpp-1643/main.cpp new file mode 100644 index 00000000..3331be00 --- /dev/null +++ b/1501-2000/1643-Kth-Smallest-Instructions/cpp-1643/main.cpp @@ -0,0 +1,81 @@ +/// Source : https://leetcode.com/problems/kth-smallest-instructions/ +/// Author : liuyubobobo +/// Time : 2020-10-31 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(R * C) +/// Space Complexity: O(R * C) +class Solution { + +private: + int R, C; + +public: + string kthSmallestPath(vector& destination, int k) { + + R = destination[0] + 1, C = destination[1] + 1; + vector> dp(R, vector(C, 1)); + for(int i = R - 2; i >= 0; i --) + for(int j = C - 2; j >= 0; j --) + dp[i][j] = dp[i + 1][j] + dp[i][j + 1]; + +// for(const vector& row: dp){ +// for(int e: row) cout << e << " "; cout << endl; +// } + + string res = ""; + int x = 0, y = 0; + while(!(x == destination[0] && y == destination[1])){ + if(in_area(x, y + 1) && k <= dp[x][y + 1]){ + res += "H"; + y ++; + } + else{ + res += "V"; + if(in_area(x, y + 1)) k -= dp[x][y + 1]; + x ++; + } + } + return res; + } + +private: + bool in_area(int x, int y){ + return x >= 0 && x < R && y >= 0 && y < C; + } +}; + + +int main() { + + vector d1 = {2, 3}; + cout << Solution().kthSmallestPath(d1, 1) << endl; + // HHHVV + + vector d2 = {2, 3}; + cout << Solution().kthSmallestPath(d1, 2) << endl; + // HHVHV + + vector d3 = {2, 3}; + cout << Solution().kthSmallestPath(d1, 3) << endl; + // HHVVH + + vector d4 = {2, 3}; + cout << Solution().kthSmallestPath(d4, 4) << endl; + // HVHHV + + vector d = {2, 3}; + vector ans = {"HHHVV", "HHVHV", "HHVVH", "HVHHV", "HVHVH", "HVVHH", "VHHHV", "VHHVH", "VHVHH", "VVHHH"}; + for(int i = 1; i <= 10; i ++) + if(Solution().kthSmallestPath(d, i) != ans[i - 1]){ + cout << "Error! " << i << endl; + } + + return 0; +} diff --git a/1501-2000/1644-Lowest-Common-Ancestor-of-a-Binary-Tree-II/cpp-1644/CMakeLists.txt b/1501-2000/1644-Lowest-Common-Ancestor-of-a-Binary-Tree-II/cpp-1644/CMakeLists.txt new file mode 100644 index 00000000..ca3d0f50 --- /dev/null +++ b/1501-2000/1644-Lowest-Common-Ancestor-of-a-Binary-Tree-II/cpp-1644/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1644) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1644 main2.cpp) \ No newline at end of file diff --git a/1501-2000/1644-Lowest-Common-Ancestor-of-a-Binary-Tree-II/cpp-1644/main.cpp b/1501-2000/1644-Lowest-Common-Ancestor-of-a-Binary-Tree-II/cpp-1644/main.cpp new file mode 100644 index 00000000..d05d65bc --- /dev/null +++ b/1501-2000/1644-Lowest-Common-Ancestor-of-a-Binary-Tree-II/cpp-1644/main.cpp @@ -0,0 +1,65 @@ +/// Source : https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree-ii/ +/// Author : liuyubobobo +/// Time : 2020-11-08 + +#include +#include + +using namespace std; + + +/// Calculate the two path +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// 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) { + + vector path1, path2; + dfs(root, p, path1); + if(path1.empty()) return NULL; + + dfs(root, q, path2); + if(path2.empty()) return NULL; + + reverse(path1.begin(), path1.end()); + reverse(path2.begin(), path2.end()); + + TreeNode* res = root; + for(int i = 0; i < path1.size() && i < path2.size() && path1[i] == path2[i]; i ++) + res = path1[i]; + return res; + } + +private: + bool dfs(TreeNode* node, TreeNode* target, vector& path){ + + if(node == target){ + path.push_back(node); + return true; + } + + if(!node) return false; + + if(dfs(node->left, target, path) || dfs(node->right, target, path)){ + path.push_back(node); + return true; + } + return false; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1644-Lowest-Common-Ancestor-of-a-Binary-Tree-II/cpp-1644/main2.cpp b/1501-2000/1644-Lowest-Common-Ancestor-of-a-Binary-Tree-II/cpp-1644/main2.cpp new file mode 100644 index 00000000..12131e8d --- /dev/null +++ b/1501-2000/1644-Lowest-Common-Ancestor-of-a-Binary-Tree-II/cpp-1644/main2.cpp @@ -0,0 +1,65 @@ +/// Source : https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree-ii/ +/// Author : liuyubobobo +/// Time : 2020-11-08 + +#include +#include +#include + +using namespace std; + + +/// Using HashSet +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// 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 { + +private: + unordered_set set; + TreeNode* res; + +public: + TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { + + dfs(root, p, 1); + if(set.empty()) return NULL; + + res = NULL; + dfs(root, q, 2); + return res; + } + +private: + bool dfs(TreeNode* node, TreeNode* target, int type){ + + if(node == target){ + if(type == 1) set.insert(node); + else if(!res && set.count(node)) res = node; + return true; + } + + if(!node) return false; + + if(dfs(node->left, target, type) || dfs(node->right, target, type)){ + if(type == 1) set.insert(node); + else if(!res && set.count(node)) res = node; + return true; + } + return false; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1646-Get-Maximum-in-Generated-Array/cpp-1646/CMakeLists.txt b/1501-2000/1646-Get-Maximum-in-Generated-Array/cpp-1646/CMakeLists.txt new file mode 100644 index 00000000..ec9e7c4c --- /dev/null +++ b/1501-2000/1646-Get-Maximum-in-Generated-Array/cpp-1646/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main2.cpp) \ No newline at end of file diff --git a/1501-2000/1646-Get-Maximum-in-Generated-Array/cpp-1646/main.cpp b/1501-2000/1646-Get-Maximum-in-Generated-Array/cpp-1646/main.cpp new file mode 100644 index 00000000..85c925f7 --- /dev/null +++ b/1501-2000/1646-Get-Maximum-in-Generated-Array/cpp-1646/main.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/get-maximum-in-generated-array/ +/// Author : liuyubobobo +/// Time : 2020-11-07 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int getMaximumGenerated(int n) { + + if(n == 0) return 0; + + vector arr(n + 1, 0); + arr[1] = 1; + int res = arr[1]; + for(int i = 2; i <= n; i ++) + if(i % 2 == 0) arr[i] = arr[i / 2]; + else arr[i] = arr[(i - 1) / 2] + arr[(i + 1) / 2], res = max(res, arr[i]); +// for(int e: arr) cout << e << " "; cout << endl; + return res; + } +}; + + +int main() { + + cout << Solution().getMaximumGenerated(7) << endl; + // 3 + + cout << Solution().getMaximumGenerated(2) << endl; + // 1 + + cout << Solution().getMaximumGenerated(3) << endl; + // 2 + + cout << Solution().getMaximumGenerated(0) << endl; + // 0 + + cout << Solution().getMaximumGenerated(1) << endl; + // 1 + + cout << Solution().getMaximumGenerated(4) << endl; + // 2 + + return 0; +} diff --git a/1501-2000/1646-Get-Maximum-in-Generated-Array/cpp-1646/main2.cpp b/1501-2000/1646-Get-Maximum-in-Generated-Array/cpp-1646/main2.cpp new file mode 100644 index 00000000..017265f8 --- /dev/null +++ b/1501-2000/1646-Get-Maximum-in-Generated-Array/cpp-1646/main2.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/get-maximum-in-generated-array/ +/// Author : liuyubobobo +/// Time : 2020-11-07 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n / 2) +/// Space Complexity: O(n) +class Solution { +public: + int getMaximumGenerated(int n) { + + if(n == 0) return 0; + + vector arr(n + 1, 0); + arr[1] = 1; + int res = arr[1]; + for(int i = 1; 2 * i - 1 <= n; i ++){ + arr[2 * i - 1] = arr[i - 1] + arr[i], res = max(res, arr[2 * i - 1]); + if(2 * i <= n) arr[2 * i] = arr[i]; + } +// for(int e: arr) cout << e << " "; cout << endl; + return res; + } +}; + + +int main() { + + cout << Solution().getMaximumGenerated(7) << endl; + // 3 + + cout << Solution().getMaximumGenerated(2) << endl; + // 1 + + cout << Solution().getMaximumGenerated(3) << endl; + // 2 + + cout << Solution().getMaximumGenerated(0) << endl; + // 0 + + cout << Solution().getMaximumGenerated(1) << endl; + // 1 + + cout << Solution().getMaximumGenerated(4) << endl; + // 2 + + return 0; +} diff --git a/1501-2000/1647-Minimum-Deletions-to-Make-Character-Frequencies-Unique/cpp-1647/CMakeLists.txt b/1501-2000/1647-Minimum-Deletions-to-Make-Character-Frequencies-Unique/cpp-1647/CMakeLists.txt new file mode 100644 index 00000000..81ad8b42 --- /dev/null +++ b/1501-2000/1647-Minimum-Deletions-to-Make-Character-Frequencies-Unique/cpp-1647/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1501-2000/1647-Minimum-Deletions-to-Make-Character-Frequencies-Unique/cpp-1647/main.cpp b/1501-2000/1647-Minimum-Deletions-to-Make-Character-Frequencies-Unique/cpp-1647/main.cpp new file mode 100644 index 00000000..d80ac894 --- /dev/null +++ b/1501-2000/1647-Minimum-Deletions-to-Make-Character-Frequencies-Unique/cpp-1647/main.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/minimum-deletions-to-make-character-frequencies-unique/ +/// Author : liuyubobobo +/// Time : 2020-11-07 + +#include +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int minDeletions(string s) { + + vector f(26, 0); + for(char c: s) f[c - 'a'] ++; + + sort(f.begin(), f.end(), greater()); + + int res = 0; + for(int i = 1; i < 26; i ++) + if(f[i] && f[i] >= f[i - 1]){ + int a = max(f[i - 1] - 1, 0); + res += f[i] - a, f[i] = a; + } + return res; + } +}; + + +int main() { + + cout << Solution().minDeletions("aab") << endl; + // 0 + + cout << Solution().minDeletions("aaabbbcc") << endl; + // 2 + + cout << Solution().minDeletions("ceabaacb") << endl; + // 2 + + cout << Solution().minDeletions("bbcebab") << endl; + // 2 + + return 0; +} diff --git a/1501-2000/1648-Sell-Diminishing-Valued-Colored-Balls/cpp-1648/CMakeLists.txt b/1501-2000/1648-Sell-Diminishing-Valued-Colored-Balls/cpp-1648/CMakeLists.txt new file mode 100644 index 00000000..ce73aee9 --- /dev/null +++ b/1501-2000/1648-Sell-Diminishing-Valued-Colored-Balls/cpp-1648/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1501-2000/1648-Sell-Diminishing-Valued-Colored-Balls/cpp-1648/main.cpp b/1501-2000/1648-Sell-Diminishing-Valued-Colored-Balls/cpp-1648/main.cpp new file mode 100644 index 00000000..f1a0c028 --- /dev/null +++ b/1501-2000/1648-Sell-Diminishing-Valued-Colored-Balls/cpp-1648/main.cpp @@ -0,0 +1,72 @@ +/// Source : https://leetcode.com/problems/sell-diminishing-valued-colored-balls/ +/// Author : liuyubobobo +/// Time : 2020-11-07 + +#include +#include + +using namespace std; + + +/// Sortiing + Greedy +/// Time Complexity: O(nlogn + n) +/// Space Complexity: O(1) +class Solution { + +private: + const long long MOD = 1e9 + 7; + +public: + int maxProfit(vector& inventory, int orders) { + + sort(inventory.begin(), inventory.end(), greater()); + inventory.push_back(0); + + int w = 0; + long long res = 0; + while(orders > 0){ + int maxv = inventory[w]; + while(inventory[w] == maxv) w ++; + + int h = maxv - inventory[w]; + if((long long)w * h <= (long long)orders) { + res += (long long)(maxv + inventory[w] + 1) * h / 2 * w; + res %= MOD; + orders -= w * h; + } + else{ + int hh = orders / w, m = orders % w; + res += (long long)(maxv + maxv - hh + 1) * hh / 2 * w; + res %= MOD; + + res += (long long)m * (maxv - hh); + res %= MOD; + + orders = 0; + } + } + return res; + } +}; + + +int main() { + + vector inventory1 = {2,5}; + cout << Solution().maxProfit(inventory1, 4) << endl; + // 14 + + vector inventory2 = {3,5}; + cout << Solution().maxProfit(inventory2, 6) << endl; + // 19 + + vector inventory3 = {2,8,4,10,6}; + cout << Solution().maxProfit(inventory3, 20) << endl; + // 110 + + vector inventory4 = {1000000000}; + cout << Solution().maxProfit(inventory4, 1000000000) << endl; + // 21 + + return 0; +} diff --git a/1501-2000/1649-Create-Sorted-Array-through-Instructions/cpp-1649/CMakeLists.txt b/1501-2000/1649-Create-Sorted-Array-through-Instructions/cpp-1649/CMakeLists.txt new file mode 100644 index 00000000..0dad4edf --- /dev/null +++ b/1501-2000/1649-Create-Sorted-Array-through-Instructions/cpp-1649/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main3.cpp) \ No newline at end of file diff --git a/1501-2000/1649-Create-Sorted-Array-through-Instructions/cpp-1649/main.cpp b/1501-2000/1649-Create-Sorted-Array-through-Instructions/cpp-1649/main.cpp new file mode 100644 index 00000000..25fabb17 --- /dev/null +++ b/1501-2000/1649-Create-Sorted-Array-through-Instructions/cpp-1649/main.cpp @@ -0,0 +1,124 @@ +/// Source : https://leetcode.com/problems/create-sorted-array-through-instructions/ +/// Author : liuyubobobo +/// Time : 2020-11-07 + +#include +#include +#include + +using namespace std; + + +/// Segment Tree +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class SegmentTree{ + +private: + int n; + vector data, tree; + +public: + SegmentTree(const vector& data): n(data.size()), data(data), tree(4 * n, 0){ + buildSegTree(0, 0, n - 1); + } + + SegmentTree(int n): n(n), data(n, 0), tree(4 * n, 0){} + + void update(int index, int value){ + data[index] = value; + update(0, 0, n - 1, index, value); + } + + int query(int index){ + return data[index]; + } + + int query(int l, int r){ + if(l > r) return 0; + return query(0, 0, n - 1, l, r); + } + +private: + void buildSegTree(int treeID, int l, int r){ + + if(l == r){ + tree[treeID] = data[l]; + return; + } + + int mid = (l + r) / 2; + buildSegTree(treeID * 2 + 1, l, mid); + buildSegTree(treeID * 2 + 2, mid + 1, r); + tree[treeID] = tree[treeID * 2 + 1] + tree[treeID * 2 + 2]; + return; + } + + void update(int treeID, int l, int r, int index, int value){ + + if(l == r){ + assert(l == index); + tree[treeID] = value; + return; + } + + int mid = (l + r) / 2; + if(index <= mid) update(treeID * 2 + 1, l, mid, index, value); + else update(treeID * 2 + 2, mid + 1, r, index, value); + + tree[treeID] = tree[treeID * 2 + 1] + tree[treeID * 2 + 2]; + return; + } + + int query(int treeID, int l, int r, int ql, int qr){ + + if(ql == l && qr == r) + return tree[treeID]; + + int mid = (l + r) / 2; + if(qr <= mid) return query(treeID * 2 + 1, l, mid, ql, qr); + else if(ql > mid) return query(treeID * 2 + 2, mid + 1, r, ql, qr); + + int resl = query(treeID * 2 + 1, l, mid, ql, mid); + int resr = query(treeID * 2 + 2, mid + 1, r, mid + 1, qr); + return resl + resr; + } +}; + +class Solution { + +private: + const int MOD = 1e9 + 7; + +public: + int createSortedArray(vector& instructions) { + + SegmentTree tree(1e5 + 1); + int res = 0; + for(int e: instructions){ + tree.update(e, tree.query(e) + 1); + int left = tree.query(0, e - 1), right = tree.query(e + 1, 1e5); + res += min(left, right); + res %= MOD; + } + return res; + } +}; + + +int main() { + + vector ins1 = {1,5,6,2}; + cout << Solution().createSortedArray(ins1) << endl; + // 1 + + vector ins2 = {1,2,3,6,5,4}; + cout << Solution().createSortedArray(ins2) << endl; + // 3 + + vector ins3 = {1,3,3,3,2,4,2,1,2}; + cout << Solution().createSortedArray(ins3) << endl; + // 4 + + return 0; +} diff --git a/1501-2000/1649-Create-Sorted-Array-through-Instructions/cpp-1649/main2.cpp b/1501-2000/1649-Create-Sorted-Array-through-Instructions/cpp-1649/main2.cpp new file mode 100644 index 00000000..c0586b4e --- /dev/null +++ b/1501-2000/1649-Create-Sorted-Array-through-Instructions/cpp-1649/main2.cpp @@ -0,0 +1,228 @@ +/// Source : https://leetcode.com/problems/create-sorted-array-through-instructions/ +/// Author : liuyubobobo +/// Time : 2020-11-17 + +#include +#include +#include + +using namespace std; + + +/// AVL Tree +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class AVLTree{ + +private: + class Node{ + public: + int key, value = 1; + Node *left = nullptr, *right = nullptr; + int height = 1, size = 1; + + Node(int key): key(key){} + }; + + Node* root = nullptr; + +public: + AVLTree(){} + + int size(){ + return size(root); + } + + // 向二分搜索树中添加新的元素(key, value) + void add(int key){ + root = add(root, key); + } + + bool contains(int key){ + return getNode(root, key) != nullptr; + } + + int get(int key){ + Node* node = getNode(root, key); + assert(node); + return node->value; + } + + int rank(int key){ + + Node* node = getNode(root, key); + assert(node); + + return rank(root, key); + } + +private: + int size(Node* node){ + return node ? node->size : 0; + } + + int height(Node* node){ + return node ? node->height : 0; + } + + int getBalanceFactor(Node* node){ + return height(node->left) - height(node->right); + } + + // 对节点y进行向右旋转操作,返回旋转后新的根节点x + // y x + // / \ / \ + // x T4 向右旋转 (y) z y + // / \ - - - - - - - -> / \ / \ + // z T3 T1 T2 T3 T4 + // / \ + // T1 T2 + Node* rightRotate(Node* y) { + Node* x = y->left; + Node* T3 = x->right; + + // 向右旋转过程 + x->right = y; + y->left = T3; + + // 更新 height 和 size + y->height = max(height(y->left), height(y->right)) + 1; + x->height = max(height(x->left), height(x->right)) + 1; + + y->size = size(y->left) + size(y->right) + y->value; + x->size = size(x->left) + size(x->right) + x->value; + + return x; + } + + // 对节点y进行向左旋转操作,返回旋转后新的根节点x + // y x + // / \ / \ + // T1 x 向左旋转 (y) y z + // / \ - - - - - - - -> / \ / \ + // T2 z T1 T2 T3 T4 + // / \ + // T3 T4 + Node* leftRotate(Node* y) { + Node* x = y->right; + Node* T2 = x->left; + + // 向左旋转过程 + x->left = y; + y->right = T2; + + // 更新 height 和 size + y->height = max(height(y->left), height(y->right)) + 1; + x->height = max(height(x->left), height(x->right)) + 1; + + y->size = size(y->left) + size(y->right) + y->value; + x->size = size(x->left) + size(x->right) + x->value; + + return x; + } + + // 向以node为根的二分搜索树中插入元素(key, value),递归算法 + // 返回插入新节点后二分搜索树的根 + Node* add(Node* node, int key){ + + if(node == nullptr){ + return new Node(key); + } + + if(key < node->key) + node->left = add(node->left, key); + else if(key > node->key) + node->right = add(node->right, key); + else // key.compareTo(node.key) == 0 + node->value ++, node->size ++; + + // 更新 height 和 size + node->height = 1 + max(height(node->left), height(node->right)); + node->size = node->value + size(node->left) + size(node->right); + + // 计算平衡因子 + int balanceFactor = getBalanceFactor(node); + + // 平衡维护 + // LL + if (balanceFactor > 1 && getBalanceFactor(node->left) >= 0) + return rightRotate(node); + + // RR + if (balanceFactor < -1 && getBalanceFactor(node->right) <= 0) + return leftRotate(node); + + // LR + if (balanceFactor > 1 && getBalanceFactor(node->left) < 0) { + node->left = leftRotate(node->left); + return rightRotate(node); + } + + // RL + if (balanceFactor < -1 && getBalanceFactor(node->right) > 0) { + node->right = rightRotate(node->right); + return leftRotate(node); + } + + return node; + } + + // 返回以node为根节点的二分搜索树中,key所在的节点 + Node* getNode(Node* node, int key){ + + if(node == nullptr) + return nullptr; + + if(key == node->key) + return node; + else if(key < node->key) + return getNode(node->left, key); + else // if(key.compareTo(node.key) > 0) + return getNode(node->right, key); + } + + int rank(Node* node, int key){ + if(key == node->key) return size(node->left) + 1; + if(key < node->key) return rank(node->left, key); + return size(node->left) + node->value + rank(node->right, key); + } +}; + +class Solution { + +private: + const int MOD = 1e9 + 7; + +public: + int createSortedArray(vector& instructions) { + + AVLTree tree; + int res = 0; + for(int e: instructions){ + tree.add(e); + int left = tree.rank(e) - 1; + int right = tree.size() - left - tree.get(e); + res += min(left, right); + res %= MOD; + } + return res; + } +}; + + +int main() { + + vector ins1 = {1,5,6,2}; + cout << Solution().createSortedArray(ins1) << endl; + // 1 + + vector ins2 = {1,2,3,6,5,4}; + cout << Solution().createSortedArray(ins2) << endl; + // 3 + + vector ins3 = {1,3,3,3,2,4,2,1,2}; + cout << Solution().createSortedArray(ins3) << endl; + // 4 + + return 0; +} diff --git a/1501-2000/1649-Create-Sorted-Array-through-Instructions/cpp-1649/main3.cpp b/1501-2000/1649-Create-Sorted-Array-through-Instructions/cpp-1649/main3.cpp new file mode 100644 index 00000000..76930fe9 --- /dev/null +++ b/1501-2000/1649-Create-Sorted-Array-through-Instructions/cpp-1649/main3.cpp @@ -0,0 +1,85 @@ +/// Source : https://leetcode.com/problems/create-sorted-array-through-instructions/ +/// Author : liuyubobobo +/// Time : 2020-11-17 + +#include +#include +#include + +using namespace std; + + +/// Merge Sort +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { + +private: + const int MOD = 1e9 + 7; + +public: + int createSortedArray(vector& instructions) { + + int n = instructions.size(); + vector aux(n), indice(n), left(n); + for(int i = 0; i < n; i ++) indice[i] = i; + + merge_sort(instructions, indice, 0, n - 1, aux, left); +// cout << "indice : "; for(int e: indice) cout << e << " "; cout << endl; +// cout << "left : "; for(int e: left) cout << e << " "; cout << endl; + int res = 0; + unordered_map f; + for(int i = 0; i < n; i ++){ + f[instructions[i]] ++; + int right = left[i], left = i + 1 - f[instructions[i]] - right; + res += min(left, right); + res %= MOD; + } + return res; + } + +private: + void merge_sort(const vector& nums, vector& indice, int l, int r, + vector& aux, vector& left){ + + if(l >= r) return; + + int mid = (l + r) / 2; + merge_sort(nums, indice, l, mid, aux, left); + merge_sort(nums, indice, mid + 1, r, aux, left); + if(nums[indice[mid]] > nums[indice[mid + 1]]) + merge(nums, indice, l, mid, r, aux, left); + } + + void merge(const vector& nums, vector& indice, int l, int mid, int r, + vector& aux, vector& left){ + + for(int i = l; i <= r; i ++) aux[i] = indice[i]; + + int i = l, j = mid + 1; + for(int k = l; k <= r; k ++){ + if(i > mid) indice[k] = aux[j ++]; + else if(j > r) indice[k] = aux[i ++]; + else if(nums[aux[i]] <= nums[aux[j]]) indice[k] = aux[i ++]; + else indice[k] = aux[j ++], left[indice[k]] += (mid - i + 1); + } + } +}; + + +int main() { + + vector ins1 = {1,5,6,2}; + cout << Solution().createSortedArray(ins1) << endl; + // 1 + + vector ins2 = {1,2,3,6,5,4}; + cout << Solution().createSortedArray(ins2) << endl; + // 3 + + vector ins3 = {1,3,3,3,2,4,2,1,2}; + cout << Solution().createSortedArray(ins3) << endl; + // 4 + + return 0; +} diff --git a/1501-2000/1650-Lowest-Common-Ancestor-of-a-Binary-Tree-III/cpp-1650/CMakeLists.txt b/1501-2000/1650-Lowest-Common-Ancestor-of-a-Binary-Tree-III/cpp-1650/CMakeLists.txt new file mode 100644 index 00000000..c7c6ffbc --- /dev/null +++ b/1501-2000/1650-Lowest-Common-Ancestor-of-a-Binary-Tree-III/cpp-1650/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1650) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1650 main.cpp) \ No newline at end of file diff --git a/1501-2000/1650-Lowest-Common-Ancestor-of-a-Binary-Tree-III/cpp-1650/main.cpp b/1501-2000/1650-Lowest-Common-Ancestor-of-a-Binary-Tree-III/cpp-1650/main.cpp new file mode 100644 index 00000000..a3551b6c --- /dev/null +++ b/1501-2000/1650-Lowest-Common-Ancestor-of-a-Binary-Tree-III/cpp-1650/main.cpp @@ -0,0 +1,43 @@ +/// Source : https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree-iii/ +/// Author : liuyubobobo +/// Time : 2020-11-14 + +#include +#include + +using namespace std; + + +/// Using HashMap +/// Time Complexity: O(h) +/// Space Complexity: O(h) + +// Definition for a Node. +class Node { +public: + int val; + Node* left; + Node* right; + Node* parent; +}; + +class Solution { +public: + Node* lowestCommonAncestor(Node* p, Node * q) { + + unordered_set set; + while(p) set.insert(p), p = p->parent; + + while(q){ + if(set.count(q)) return q; + q = q->parent; + } + return nullptr; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1652-Defuse-the-Bomb/cpp-1652/CMakeLists.txt b/1501-2000/1652-Defuse-the-Bomb/cpp-1652/CMakeLists.txt new file mode 100644 index 00000000..543c714e --- /dev/null +++ b/1501-2000/1652-Defuse-the-Bomb/cpp-1652/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1652) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1652 main.cpp) \ No newline at end of file diff --git a/1501-2000/1652-Defuse-the-Bomb/cpp-1652/main.cpp b/1501-2000/1652-Defuse-the-Bomb/cpp-1652/main.cpp new file mode 100644 index 00000000..5d80c567 --- /dev/null +++ b/1501-2000/1652-Defuse-the-Bomb/cpp-1652/main.cpp @@ -0,0 +1,41 @@ +/// Source : https://leetcode.com/problems/defuse-the-bomb/ +/// Author : liuyubobobo +/// Time : 2020-11-14 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n * k) +/// Space Complexity: O(1) +class Solution { +public: + vector decrypt(vector& code, int k) { + + int n = code.size(); + vector res(n, 0); + + if(k == 0) return res; + + if(k > 0){ + for(int i = 0; i < n; i ++) + for(int j = 1; j <= k; j ++) + res[i] += code[(i + j)% n]; + } + else{ + for(int i = 0; i < n; i ++) + for(int j = 1; j <= -k; j ++) + res[i] += code[(i - j + n) % n]; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1653-Minimum-Deletions-to-Make-String-Balanced/cpp-1653/CMakeLists.txt b/1501-2000/1653-Minimum-Deletions-to-Make-String-Balanced/cpp-1653/CMakeLists.txt new file mode 100644 index 00000000..1fc96cfa --- /dev/null +++ b/1501-2000/1653-Minimum-Deletions-to-Make-String-Balanced/cpp-1653/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1653) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1653 main4.cpp) \ No newline at end of file diff --git a/1501-2000/1653-Minimum-Deletions-to-Make-String-Balanced/cpp-1653/main.cpp b/1501-2000/1653-Minimum-Deletions-to-Make-String-Balanced/cpp-1653/main.cpp new file mode 100644 index 00000000..165d0f4f --- /dev/null +++ b/1501-2000/1653-Minimum-Deletions-to-Make-String-Balanced/cpp-1653/main.cpp @@ -0,0 +1,48 @@ +/// Source : https://leetcode-cn.com/problems/minimum-deletions-to-make-string-balanced/ +/// Author : liuyubobobo +/// Time : 2020-11-14 + +#include +#include + +using namespace std; + + +/// Presum + Postsum +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int minimumDeletions(string s) { + + int n = s.size(); + + vector preb(n + 1, 0); + for(int i = 0; i < n; i ++) + preb[i + 1] = preb[i] + (s[i] == 'b'); + + vector posta(n + 1, 0); + for(int i = n - 1; i >= 0; i --) + posta[i] = posta[i + 1] + (s[i] == 'a'); + + int res = min(preb[n], posta[0]); + for(int i = 0; i < n; i ++) + res = min(res, posta[i] + preb[i]); + return res; + } +}; + + +int main() { + + cout << Solution().minimumDeletions("aababbab") << endl; + // 2 + + cout << Solution().minimumDeletions("a") << endl; + // 0 + + cout << Solution().minimumDeletions("aabbbbaabababbbbaaaaaabbababaaabaabaabbbabbbbabbabbababaabaababbbbaaaaabbabbabaaaabbbabaaaabbaaabbbaabbaaaaabaa") << endl; + // 52 + + return 0; +} diff --git a/1501-2000/1653-Minimum-Deletions-to-Make-String-Balanced/cpp-1653/main2.cpp b/1501-2000/1653-Minimum-Deletions-to-Make-String-Balanced/cpp-1653/main2.cpp new file mode 100644 index 00000000..4cc0e30b --- /dev/null +++ b/1501-2000/1653-Minimum-Deletions-to-Make-String-Balanced/cpp-1653/main2.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode-cn.com/problems/minimum-deletions-to-make-string-balanced/ +/// Author : liuyubobobo +/// Time : 2020-11-14 + +#include +#include + +using namespace std; + + +/// Postsum +/// Space Optimization with Solution1 +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int minimumDeletions(string s) { + + int n = s.size(); + + vector posta(n + 1, 0); + for(int i = n - 1; i >= 0; i --) + posta[i] = posta[i + 1] + (s[i] == 'a'); + + int res = posta[0], b = 0; + for(int i = 0; i < n; i ++){ + b += s[i] == 'b'; + res = min(res, b + posta[i + 1]); + } + return res; + } +}; + + +int main() { + + cout << Solution().minimumDeletions("aababbab") << endl; + // 2 + + cout << Solution().minimumDeletions("a") << endl; + // 0 + + cout << Solution().minimumDeletions("aabbbbaabababbbbaaaaaabbababaaabaabaabbbabbbbabbabbababaabaababbbbaaaaabbabbabaaaabbbabaaaabbaaabbbaabbaaaaabaa") << endl; + // 52 + + return 0; +} diff --git a/1501-2000/1653-Minimum-Deletions-to-Make-String-Balanced/cpp-1653/main3.cpp b/1501-2000/1653-Minimum-Deletions-to-Make-String-Balanced/cpp-1653/main3.cpp new file mode 100644 index 00000000..5731cba6 --- /dev/null +++ b/1501-2000/1653-Minimum-Deletions-to-Make-String-Balanced/cpp-1653/main3.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode-cn.com/problems/minimum-deletions-to-make-string-balanced/ +/// Author : liuyubobobo +/// Time : 2020-11-14 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// dp[0][i]: ending with a, dp[1][i]: ending with b +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int minimumDeletions(string s) { + + int n = s.size(); + + vector> dp(2, vector(n + 1, 0)); + + dp[0][0] = s[0] == 'b', dp[1][0] = s[0] == 'a'; + for(int i = 1; i < n; i ++){ + if(s[i] == 'a') + dp[0][i] = dp[0][i - 1], dp[1][i] = dp[1][i - 1] + 1; + else + dp[0][i] = dp[0][i - 1] + 1, dp[1][i] = min(dp[0][i - 1], dp[1][i - 1]); + } + return min(dp[0][n - 1], dp[1][n - 1]); + } +}; + + +int main() { + + cout << Solution().minimumDeletions("aababbab") << endl; + // 2 + + cout << Solution().minimumDeletions("a") << endl; + // 0 + + cout << Solution().minimumDeletions("aabbbbaabababbbbaaaaaabbababaaabaabaabbbabbbbabbabbababaabaababbbbaaaaabbabbabaaaabbbabaaaabbaaabbbaabbaaaaabaa") << endl; + // 52 + + return 0; +} diff --git a/1501-2000/1653-Minimum-Deletions-to-Make-String-Balanced/cpp-1653/main4.cpp b/1501-2000/1653-Minimum-Deletions-to-Make-String-Balanced/cpp-1653/main4.cpp new file mode 100644 index 00000000..f501a82a --- /dev/null +++ b/1501-2000/1653-Minimum-Deletions-to-Make-String-Balanced/cpp-1653/main4.cpp @@ -0,0 +1,42 @@ +/// Source : https://leetcode-cn.com/problems/minimum-deletions-to-make-string-balanced/ +/// Author : liuyubobobo +/// Time : 2020-11-14 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// a: ending with a, b: ending with b +/// Space Optimization with Solution3 +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int minimumDeletions(string s) { + + int a = 0, b = 0; + for(char c: s){ + if(c == 'a') b ++; + else b = min(a, b), a ++; + } + return min(a, b); + } +}; + + +int main() { + + cout << Solution().minimumDeletions("aababbab") << endl; + // 2 + + cout << Solution().minimumDeletions("a") << endl; + // 0 + + cout << Solution().minimumDeletions("aabbbbaabababbbbaaaaaabbababaaabaabaabbbabbbbabbabbababaabaababbbbaaaaabbabbabaaaabbbabaaaabbaaabbbaabbaaaaabaa") << endl; + // 52 + + return 0; +} diff --git a/1501-2000/1654-Minimum-Jumps-to-Reach-Home/cpp-1654/CMakeLists.txt b/1501-2000/1654-Minimum-Jumps-to-Reach-Home/cpp-1654/CMakeLists.txt new file mode 100644 index 00000000..fceef2ce --- /dev/null +++ b/1501-2000/1654-Minimum-Jumps-to-Reach-Home/cpp-1654/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1654) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1654 main.cpp) \ No newline at end of file diff --git a/1501-2000/1654-Minimum-Jumps-to-Reach-Home/cpp-1654/main.cpp b/1501-2000/1654-Minimum-Jumps-to-Reach-Home/cpp-1654/main.cpp new file mode 100644 index 00000000..65766938 --- /dev/null +++ b/1501-2000/1654-Minimum-Jumps-to-Reach-Home/cpp-1654/main.cpp @@ -0,0 +1,74 @@ +/// Source : https://leetcode.com/problems/minimum-jumps-to-reach-home/ +/// Author : liuyubobobo +/// Time : 2020-11-16 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// BFS +/// Time Complexity: +class Solution { + +public: + int minimumJumps(vector& forbidden, int a, int b, int x) { + + unordered_set no(forbidden.begin(), forbidden.end()); + + queue q; // pos * 2 + canback + unordered_map dis; + + q.push(1); + dis[1] = 0; + + while(!q.empty()){ + + int cur = q.front() / 2, canback = q.front() % 2; + q.pop(); + + if(cur == x) return dis[cur * 2 + canback]; + + if(cur + a <= 6000 && !no.count(cur + a) && !dis.count((cur + a) * 2 + 1)){ + dis[(cur + a) * 2 + 1] = dis[cur * 2 + canback] + 1; + q.push(2 * (cur + a) + 1); + } + + if(cur - b >= 0 && canback && !no.count(cur - b) && !dis.count((cur - b) * 2)){ + dis[(cur - b) * 2] = dis[cur * 2 + canback] + 1; + q.push(2 * (cur - b)); + } + } + return -1; + } +}; + + +int main() { + + vector forbidden1 = {14, 4, 18, 1, 15}; + cout << Solution().minimumJumps(forbidden1, 3, 15, 9) << endl; + // 3 + + vector forbidden2 = {8,3,16,6,12,20}; + cout << Solution().minimumJumps(forbidden2, 15, 13, 11) << endl; + // -1 + + vector forbidden3 = {1,6,2,14,5,17,4}; + cout << Solution().minimumJumps(forbidden3, 16, 9, 7) << endl; + // 2 + + vector forbidden4 = {5,2,10,12,18}; + cout << Solution().minimumJumps(forbidden4, 8, 6, 16) << endl; + // 2 + + vector forbidden5 = {162,118,178,152,167,100,40,74,199,186,26,73,200,127,30,124,193,84,184,36,103,149,153,9,54,154,133,95,45,198,79,157,64,122,59,71,48,177,82,35,14,176,16,108,111,6,168,31,134,164,136,72,98}; + cout << Solution().minimumJumps(forbidden5, 29, 98, 80) << endl; + // 121 + + return 0; +} diff --git a/1501-2000/1655-Distribute-Repeating-Integers/cpp-1655/CMakeLists.txt b/1501-2000/1655-Distribute-Repeating-Integers/cpp-1655/CMakeLists.txt new file mode 100644 index 00000000..2a1f0ae4 --- /dev/null +++ b/1501-2000/1655-Distribute-Repeating-Integers/cpp-1655/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1655) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1655 main.cpp) \ No newline at end of file diff --git a/1501-2000/1655-Distribute-Repeating-Integers/cpp-1655/main.cpp b/1501-2000/1655-Distribute-Repeating-Integers/cpp-1655/main.cpp new file mode 100644 index 00000000..a05b4244 --- /dev/null +++ b/1501-2000/1655-Distribute-Repeating-Integers/cpp-1655/main.cpp @@ -0,0 +1,86 @@ +/// Source : https://leetcode.com/problems/distribute-repeating-integers/ +/// Author : liuyubobobo +/// Time : 2020-11-16 + +#include +#include +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(n * (2^m) * (2^m)) +/// Space Complexity: O(n * (2^m)) +class Solution { +public: + bool canDistribute(vector& nums, vector& quantity) { + + unordered_map f; + for(int e: nums) f[e] ++; + + vector v; + for(const pair& p: f) v.push_back(p.second); + + vector sum(1 << quantity.size()); + for(int state = 0; state < sum.size(); state ++) + sum[state] = get_sum(quantity, state); + + vector> dp(v.size(), vector(1 << quantity.size(), -1)); + return dfs(v, sum, 0, 0, dp); + } + +private: + bool dfs(const vector& v, const vector& sum, int index, int state, + vector>& dp){ + + if(state == sum.size() - 1) return true; + if(index == v.size()) return false; + + if(dp[index][state] != -1) return dp[index][state]; + + for(int i = 0; i < sum.size(); i ++) + if((i & state) == 0 && v[index] >= sum[i] && dfs(v, sum, index + 1, state | i, dp)) + return dp[index][state] = true; + + return dp[index][state] = false; + } + + int get_sum(const vector& q, int state){ + + int res = 0, index = 0; + while(state){ + if(state % 2) res += q[index]; + index ++; + state /= 2; + } + return res; + } +}; + + +int main() { + + vector nums1 = {1, 2, 3, 4}, q1 = {2}; + cout << Solution().canDistribute(nums1, q1) << endl; + // 0 + + vector nums2 = {1, 2, 3, 3}, q2 = {2}; + cout << Solution().canDistribute(nums2, q2) << endl; + // 1 + + vector nums3 = {1, 1, 2, 2}, q3 = {2, 2}; + cout << Solution().canDistribute(nums3, q3) << endl; + // 1 + + vector nums4 = {1, 1, 2, 3}, q4 = {2, 2}; + cout << Solution().canDistribute(nums4, q4) << endl; + // 0 + + vector nums5 = {1, 1, 1, 1, 1}, q5 = {2, 3}; + cout << Solution().canDistribute(nums5, q5) << endl; + // 1 + + return 0; +} diff --git a/1501-2000/1656-Design-an-Ordered-Stream/cpp-1656/CMakeLists.txt b/1501-2000/1656-Design-an-Ordered-Stream/cpp-1656/CMakeLists.txt new file mode 100644 index 00000000..d5d5e4ff --- /dev/null +++ b/1501-2000/1656-Design-an-Ordered-Stream/cpp-1656/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1501-2000/1656-Design-an-Ordered-Stream/cpp-1656/main.cpp b/1501-2000/1656-Design-an-Ordered-Stream/cpp-1656/main.cpp new file mode 100644 index 00000000..e024ec78 --- /dev/null +++ b/1501-2000/1656-Design-an-Ordered-Stream/cpp-1656/main.cpp @@ -0,0 +1,39 @@ +/// Source : https://leetcode.com/problems/design-an-ordered-stream/ +/// Author : liuyubobobo +/// Time : 2020-11-14 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class OrderedStream { + +private: + vector data; + int p; + +public: + OrderedStream(int n) : data(n, ""), p(0) { } + + vector insert(int id, string value) { + + id --; + data[id] = value; + + vector res; + while(p < data.size() && data[p] != "") + res.push_back(data[p ++]); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1657-Determine-if-Two-Strings-Are-Close/cpp-1657/CMakeLists.txt b/1501-2000/1657-Determine-if-Two-Strings-Are-Close/cpp-1657/CMakeLists.txt new file mode 100644 index 00000000..81ad8b42 --- /dev/null +++ b/1501-2000/1657-Determine-if-Two-Strings-Are-Close/cpp-1657/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1501-2000/1657-Determine-if-Two-Strings-Are-Close/cpp-1657/main.cpp b/1501-2000/1657-Determine-if-Two-Strings-Are-Close/cpp-1657/main.cpp new file mode 100644 index 00000000..6a84869f --- /dev/null +++ b/1501-2000/1657-Determine-if-Two-Strings-Are-Close/cpp-1657/main.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/determine-if-two-strings-are-close/ +/// Author : liuyubobobo +/// Time : 2020-11-14 + +#include +#include + +using namespace std; + + +/// Using HashMap +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + bool closeStrings(string word1, string word2) { + + if(word1.size() != word2.size()) return false; + + vector f1(26, 0), f2(26, 0); + for(int i = 0; i < word1.size(); i ++) + f1[word1[i] - 'a'] ++, f2[word2[i] - 'a'] ++; + + for(int i = 0; i < 26; i ++){ + if(f1[i] && !f2[i]) return false; + if(f2[i] && !f1[i]) return false; + } + + sort(f1.begin(), f1.end()); + sort(f2.begin(), f2.end()); + return f1 == f2; + } +}; + + +int main() { + + cout << Solution().closeStrings("abc", "bca") << endl; + // 1 + + cout << Solution().closeStrings("a", "aa") << endl; + // 0 + + cout << Solution().closeStrings("cabbba", "abbccc") << endl; + // 1 + + cout << Solution().closeStrings("cabbba", "aabbss") << endl; + // 0 + + cout << Solution().closeStrings("uau", "ssx") << endl; + // 0 + + return 0; +} diff --git a/1501-2000/1658-Minimum-Operations-to-Reduce-X-to-Zero/cpp-1658/CMakeLists.txt b/1501-2000/1658-Minimum-Operations-to-Reduce-X-to-Zero/cpp-1658/CMakeLists.txt new file mode 100644 index 00000000..a645af27 --- /dev/null +++ b/1501-2000/1658-Minimum-Operations-to-Reduce-X-to-Zero/cpp-1658/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main3.cpp) \ No newline at end of file diff --git a/1501-2000/1658-Minimum-Operations-to-Reduce-X-to-Zero/cpp-1658/main.cpp b/1501-2000/1658-Minimum-Operations-to-Reduce-X-to-Zero/cpp-1658/main.cpp new file mode 100644 index 00000000..a2df931f --- /dev/null +++ b/1501-2000/1658-Minimum-Operations-to-Reduce-X-to-Zero/cpp-1658/main.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/minimum-operations-to-reduce-x-to-zero/ +/// Author : liuyubobobo +/// Time : 2020-11-14 + +#include +#include + +using namespace std; + + +/// Presum and Binary Search +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + int minOperations(vector& nums, int x) { + + int n = nums.size(); + vector presum(n + 1, 0); + + int res = INT_MAX; + for(int i = 0; i < n; i ++) { + presum[i + 1] = presum[i] + nums[i]; + if(presum[i + 1] == x) res = min(res, i + 1); + } + + int cur = 0; + for(int i = n - 1; i >= 0; i --){ + cur += nums[i]; + vector::iterator iter = lower_bound(presum.begin(), presum.begin() + i, x - cur); + if(iter != presum.begin() + i && *iter == x - cur) + res = min(res, n - i + (int)(iter - presum.begin())); + } + return res == INT_MAX ? -1 : res; + } +}; + + +int main() { + + vector nums1 = {1, 1, 4, 2, 3}; + cout << Solution().minOperations(nums1, 5) << endl; + // 2 + + vector nums2 = {5, 6, 7, 8, 9}; + cout << Solution().minOperations(nums2, 4) << endl; + // -1 + + vector nums3 = {3,2,20,1,1,3}; + cout << Solution().minOperations(nums3, 10) << endl; + // 5 + + return 0; +} diff --git a/1501-2000/1658-Minimum-Operations-to-Reduce-X-to-Zero/cpp-1658/main2.cpp b/1501-2000/1658-Minimum-Operations-to-Reduce-X-to-Zero/cpp-1658/main2.cpp new file mode 100644 index 00000000..3ca3d109 --- /dev/null +++ b/1501-2000/1658-Minimum-Operations-to-Reduce-X-to-Zero/cpp-1658/main2.cpp @@ -0,0 +1,56 @@ +/// Source : https://leetcode.com/problems/minimum-operations-to-reduce-x-to-zero/ +/// Author : liuyubobobo +/// Time : 2020-11-15 + +#include +#include +#include +#include + +using namespace std; + + +/// Presum + HashMap +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int minOperations(vector& nums, int x) { + + int n = nums.size(); + int t = accumulate(nums.begin(), nums.end(), 0) - x; + + unordered_map map; + map[0] = -1; + int cur = 0, res = t == 0 ? n : INT_MAX; + for(int i = 0; i < n; i ++){ + cur += nums[i]; + if(map.count(cur - t)) + res = min(res, n - (i - map[cur - t])); + map[cur] = i; + } + return res == INT_MAX ? -1 : res; + } +}; + + +int main() { + + vector nums1 = {1, 1, 4, 2, 3}; + cout << Solution().minOperations(nums1, 5) << endl; + // 2 + + vector nums2 = {5, 6, 7, 8, 9}; + cout << Solution().minOperations(nums2, 4) << endl; + // -1 + + vector nums3 = {3,2,20,1,1,3}; + cout << Solution().minOperations(nums3, 10) << endl; + // 5 + + vector nums4 = {8828,9581,49,9818,9974,9869,9991,10000,10000,10000,9999,9993,9904,8819,1231,6309}; + cout << Solution().minOperations(nums4, 134365) << endl; + // 16 + + return 0; +} diff --git a/1501-2000/1658-Minimum-Operations-to-Reduce-X-to-Zero/cpp-1658/main3.cpp b/1501-2000/1658-Minimum-Operations-to-Reduce-X-to-Zero/cpp-1658/main3.cpp new file mode 100644 index 00000000..e81536be --- /dev/null +++ b/1501-2000/1658-Minimum-Operations-to-Reduce-X-to-Zero/cpp-1658/main3.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/minimum-operations-to-reduce-x-to-zero/ +/// Author : liuyubobobo +/// Time : 2020-11-15 + +#include +#include +#include + +using namespace std; + + +/// Two Pointer +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int minOperations(vector& nums, int x) { + + int n = nums.size(); + int t = accumulate(nums.begin(), nums.end(), 0) - x, res = INT_MAX; + + int l = 0, r = -1, cur = 0; + while(l < n){ + if(r + 1 < n && cur + nums[r + 1] <= t){ + cur += nums[r + 1]; + r ++; + if(cur == t) res = min(res, n - (r - l + 1)); + } + else + cur -= nums[l ++]; + } + return res == INT_MAX ? -1 : res; + } +}; + + +int main() { + + vector nums1 = {1, 1, 4, 2, 3}; + cout << Solution().minOperations(nums1, 5) << endl; + // 2 + + vector nums2 = {5, 6, 7, 8, 9}; + cout << Solution().minOperations(nums2, 4) << endl; + // -1 + + vector nums3 = {3,2,20,1,1,3}; + cout << Solution().minOperations(nums3, 10) << endl; + // 5 + + return 0; +} diff --git a/1501-2000/1659-Maximize-Grid-Happiness/cpp-1659/CMakeLists.txt b/1501-2000/1659-Maximize-Grid-Happiness/cpp-1659/CMakeLists.txt new file mode 100644 index 00000000..a373769d --- /dev/null +++ b/1501-2000/1659-Maximize-Grid-Happiness/cpp-1659/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main2.cpp) \ No newline at end of file diff --git a/1501-2000/1659-Maximize-Grid-Happiness/cpp-1659/main.cpp b/1501-2000/1659-Maximize-Grid-Happiness/cpp-1659/main.cpp new file mode 100644 index 00000000..e4c4055e --- /dev/null +++ b/1501-2000/1659-Maximize-Grid-Happiness/cpp-1659/main.cpp @@ -0,0 +1,126 @@ +/// Source : https://leetcode.com/problems/maximize-grid-happiness/ +/// Author : liuyubobobo +/// Time : 2020-11-14 + +#include +#include +#include + +using namespace std; + + +/// Memory Search +/// Row by row +/// Time Complexity: O(R * in * ex * (1 << C) * (1 << C)) +/// Space Complexity: O(R * in * ex * (1 << C)) +class Solution { + +private: + int statemax; + vector> score, fix; + vector in_cnt, ex_cnt; + +public: + int getMaxGridHappiness(int m, int n, int introvertsCount, int extrovertsCount) { + + statemax = 1; + for(int i = 0; i < n; i ++) statemax *= 3; + + score = vector>(statemax, vector(statemax)); + fix = vector>(statemax, vector(statemax));; + for(int state1 = 0; state1 < statemax; state1 ++){ + vector v1 = get_state_v(state1, n); + for(int state2 = 0; state2 < statemax; state2 ++){ + vector v2 = get_state_v(state2, n); + score[state1][state2] = get_score(v1, v2); + fix[state1][state2] = get_fix(v1, v2); + } + } + + in_cnt = vector(statemax, 0); + ex_cnt = vector(statemax, 0); + for(int state = 0; state < statemax; state ++) + get_in_and_ex(state); + + int dp[6][7][7][729]; + memset(dp, -1, sizeof(dp)); + return dfs(m, introvertsCount, extrovertsCount, 0, dp); + } + +private: + int dfs(int leftrow, int in, int ex, int last, int dp[6][7][7][729]){ + + if(leftrow == 0) return 0; + if(dp[leftrow][in][ex][last] != -1) return dp[leftrow][in][ex][last]; + + int res = 0; + for(int state = 0; state < statemax; state ++) + if(in >= in_cnt[state] && ex >= ex_cnt[state]) + res = max(res, score[state][last] + fix[last][state] + dfs(leftrow - 1, in - in_cnt[state], ex - ex_cnt[state], state, dp)); + return dp[leftrow][in][ex][last] = res; + } + + vector get_state_v(int state, int col){ + + vector res(col, 0); + for(int i = 0; i < col; i ++) + res[i] = state % 3, state /= 3; + return res; + } + + int get_score(const vector& curv, const vector& lastv){ + + vector v(curv.size(), 0); + for(int i = 0; i < v.size(); i ++) + if(curv[i] == 1){ + v[i] = 120; + if(i > 0 && curv[i - 1]) v[i] -= 30; + if(lastv[i]) v[i] -= 30; + if(i + 1 < v.size() && curv[i + 1]) v[i] -= 30; + } + else if(curv[i] == 2){ + v[i] = 40; + if(i > 0 && curv[i - 1]) v[i] += 20; + if(lastv[i]) v[i] += 20; + if(i + 1 < v.size() && curv[i + 1]) v[i] += 20; + } + return accumulate(v.begin(), v.end(), 0); + } + + int get_fix(const vector& curv, const vector& lastv){ + + int res = 0; + for(int i = 0; i < curv.size(); i ++) + if(curv[i] == 1 && lastv[i]) res -= 30; + else if(curv[i] == 2 && lastv[i]) res += 20; + return res; + } + + void get_in_and_ex(int state){ + + int x = state; + while(x){ + if(x % 3 == 1) in_cnt[state] ++; + else if(x % 3 == 2) ex_cnt[state] ++; + x /= 3; + } + } +}; + + +int main() { + + cout << Solution().getMaxGridHappiness(2, 3, 1, 2) << endl; + // 240 + + cout << Solution().getMaxGridHappiness(3, 1, 2, 1) << endl; + // 260 + + cout << Solution().getMaxGridHappiness(2, 2, 4, 0) << endl; + // 240 + + cout << Solution().getMaxGridHappiness(3, 1, 1, 3) << endl; + // 230 + + return 0; +} diff --git a/1501-2000/1659-Maximize-Grid-Happiness/cpp-1659/main2.cpp b/1501-2000/1659-Maximize-Grid-Happiness/cpp-1659/main2.cpp new file mode 100644 index 00000000..591352fc --- /dev/null +++ b/1501-2000/1659-Maximize-Grid-Happiness/cpp-1659/main2.cpp @@ -0,0 +1,87 @@ +/// Source : https://leetcode.com/problems/maximize-grid-happiness/ +/// Author : liuyubobobo +/// Time : 2020-11-14 + +#include +#include +#include + +using namespace std; + + +/// Memory Search +/// One by one +/// Time Complexity: O(R * C * in * ex * (1 << C)) +/// Space Complexity: O(R * C * in * ex * (1 << C)) +class Solution { + +private: + int statemax = 1, mod, R, C; + +public: + int getMaxGridHappiness(int m, int n, int introvertsCount, int extrovertsCount) { + + R = m, C = n; + for(int i = 0; i < n; i ++) statemax *= 3; + mod = statemax / 3; + + int dp[5][5][7][7][729]; + memset(dp, -1, sizeof(dp)); + return dfs(0, 0, introvertsCount, extrovertsCount, 0, dp); + } + +private: + int dfs(int x, int y, int in, int ex, int last, int dp[5][5][7][7][729]){ + + if(x == R) return 0; + if(y == C) return dfs(x + 1, 0, in, ex, last, dp); + if(dp[x][y][in][ex][last] != -1) return dp[x][y][in][ex][last]; + + int res = dfs(x, y + 1, in, ex, last % mod * 3, dp); + + if(in) { + int t1 = 120, up = last / mod, left = last % 3; + if (x - 1 >= 0 && up) { + t1 -= 30; + t1 += up == 1 ? -30 : 20; + } + if (y - 1 >= 0 && left) { + t1 -= 30; + t1 += left == 1 ? -30 : 20; + } + res = max(res, t1 + dfs(x, y + 1, in - 1, ex, last % mod * 3 + 1, dp)); + } + + if(ex) { + int t2 = 40, up = last / mod, left = last % 3;; + if (x - 1 >= 0 && up) { + t2 += 20; + t2 += up == 1 ? -30 : 20; + } + if (y - 1 >= 0 && left) { + t2 += 20; + t2 += left == 1 ? -30 : 20; + } + res = max(res, t2 + dfs(x, y + 1, in, ex - 1, last % mod * 3 + 2, dp)); + } + return dp[x][y][in][ex][last] = res; + } +}; + + +int main() { + + cout << Solution().getMaxGridHappiness(2, 3, 1, 2) << endl; + // 240 + + cout << Solution().getMaxGridHappiness(3, 1, 2, 1) << endl; + // 260 + + cout << Solution().getMaxGridHappiness(2, 2, 4, 0) << endl; + // 240 + + cout << Solution().getMaxGridHappiness(3, 1, 1, 3) << endl; + // 230 + + return 0; +} diff --git a/1501-2000/1659-Maximize-Grid-Happiness/java-1659/src/Solution.java b/1501-2000/1659-Maximize-Grid-Happiness/java-1659/src/Solution.java new file mode 100644 index 00000000..dd442c66 --- /dev/null +++ b/1501-2000/1659-Maximize-Grid-Happiness/java-1659/src/Solution.java @@ -0,0 +1,114 @@ +/// Source : https://leetcode.com/problems/maximize-grid-happiness/ +/// Author : liuyubobobo +/// Time : 2020-11-14 + +/// Memory Search +/// Row by row +/// Time Complexity: O(R * in * ex * (1 << C) * (1 << C)) +/// Space Complexity: O(R * in * ex * (1 << C)) +class Solution { + + private int statemax = 1; + private int[][][][] dp; + private int[][] score, fix; + private int[] inCnt, exCnt; + + public int getMaxGridHappiness(int m, int n, int introvertsCount, int extrovertsCount) { + + for(int i = 0; i < n; i ++) + statemax *= 3; + + // 预处理 score 和 fix + score = new int[statemax][statemax]; + fix = new int[statemax][statemax]; + for(int state1 = 0; state1 < statemax; state1 ++){ + + int[] v1 = getStateArray(state1, n); + for(int state2 = 0; state2 < statemax; state2 ++){ + + int[] v2 = getStateArray(state2, n); + score[state1][state2] = getScore(v1, v2, n); + fix[state1][state2] = getFix(v1, v2, n); + } + } + + // 预处理每个状态的内向人数和外向人数 + inCnt = new int[statemax]; + exCnt = new int[statemax]; + for(int state = 0; state < statemax; state ++) + getInAndEx(state); + + dp = new int[m + 1][introvertsCount + 1][extrovertsCount + 1][statemax]; + return dfs(m, introvertsCount, extrovertsCount, 0); + } + + // 记忆化搜索 + private int dfs(int leftrow, int in, int ex, int last){ + + if(leftrow == 0) return 0; + if(in == 0 && ex == 0) return 0; + + if(dp[leftrow][in][ex][last] != 0) + return dp[leftrow][in][ex][last]; + + int res = 0; + for(int state = 0; state < statemax; state ++){ + // in 和 ex 人数够用,可以安排,则进行状态转移 + if(in >= inCnt[state] && ex >= exCnt[state]) + res = Math.max(res, score[state][last] + fix[last][state] + dfs(leftrow - 1, in - inCnt[state], ex - exCnt[state], state)); + } + return dp[leftrow][in][ex][last] = res; + } + + // 下面都是各种预处理需要的辅助函数 + private int[] getStateArray(int state, int col){ + + int[] res = new int[col]; + for(int i = 0; i < col; i ++){ + res[i] = state % 3; + state /= 3; + } + return res; + } + + private int getScore(int[] curv, int[] lastv, int col){ + + int res = 0, t = 0; + for(int i = 0; i < col; i ++){ + t = 0; + if(curv[i] == 1){ + t = 120; + if(i > 0 && curv[i - 1] != 0) t -= 30; + if(lastv[i] != 0) t -= 30; + if(i + 1 < col && curv[i + 1] != 0) t -= 30; + } + else if(curv[i] == 2){ + t = 40; + if(i > 0 && curv[i - 1] != 0) t += 20; + if(lastv[i] != 0) t += 20; + if(i + 1 < col && curv[i + 1] != 0) t += 20; + } + res += t; + } + return res; + } + + private int getFix(int[] curv, int[] lastv, int col){ + + int res = 0; + for(int i = 0; i < col; i ++) + if(curv[i] == 1 && lastv[i] != 0) res -= 30; + else if(curv[i] == 2 && lastv[i] != 0) res += 20; + return res; + } + + private void getInAndEx(int state){ + + int in = 0, ex = 0, x = state; + while(x != 0){ + if(x % 3 == 1) inCnt[state] ++; + else if(x % 3 == 2) exCnt[state] ++; + x /= 3; + } + } +} \ No newline at end of file diff --git a/1501-2000/1659-Maximize-Grid-Happiness/java-1659/src/Solution2.java b/1501-2000/1659-Maximize-Grid-Happiness/java-1659/src/Solution2.java new file mode 100644 index 00000000..e46b510b --- /dev/null +++ b/1501-2000/1659-Maximize-Grid-Happiness/java-1659/src/Solution2.java @@ -0,0 +1,60 @@ +/// Source : https://leetcode.com/problems/maximize-grid-happiness/ +/// Author : liuyubobobo +/// Time : 2020-11-14 + +/// Memory Search +/// One by one +/// Time Complexity: O(R * C * in * ex * (1 << C)) +/// Space Complexity: O(R * C * in * ex * (1 << C)) +class Solution2 { + + private int statemax = 1, mod = 0, R = 0, C = 0; + private int[][][][][] dp; + + public int getMaxGridHappiness(int m, int n, int introvertsCount, int extrovertsCount) { + + R = m; + C = n; + for(int i = 0; i < n; i ++) statemax *= 3; + mod = statemax / 3; + + dp = new int[m][n][introvertsCount + 1][extrovertsCount + 1][statemax]; + return dfs(0, 0, introvertsCount, extrovertsCount, 0); + } + + private int dfs(int x, int y, int in, int ex, int last){ + + if(x == R) return 0; + if(y == C) return dfs(x + 1, 0, in, ex, last); + if(dp[x][y][in][ex][last] != 0) return dp[x][y][in][ex][last]; + + int res = dfs(x, y + 1, in, ex, last % mod * 3); + + if(in != 0) { + int t1 = 120, up = last / mod, left = last % 3; + if (x - 1 >= 0 && up != 0) { + t1 -= 30; + t1 += up == 1 ? -30 : 20; + } + if (y - 1 >= 0 && left != 0) { + t1 -= 30; + t1 += left == 1 ? -30 : 20; + } + res = Math.max(res, t1 + dfs(x, y + 1, in - 1, ex, last % mod * 3 + 1)); + } + + if(ex != 0) { + int t2 = 40, up = last / mod, left = last % 3;; + if (x - 1 >= 0 && up != 0) { + t2 += 20; + t2 += up == 1 ? -30 : 20; + } + if (y - 1 >= 0 && left != 0) { + t2 += 20; + t2 += left == 1 ? -30 : 20; + } + res = Math.max(res, t2 + dfs(x, y + 1, in, ex - 1, last % mod * 3 + 2)); + } + return dp[x][y][in][ex][last] = res; + } +} \ No newline at end of file diff --git a/1501-2000/1660-Correct-a-Binary-Tree/cpp-1660/CMakeLists.txt b/1501-2000/1660-Correct-a-Binary-Tree/cpp-1660/CMakeLists.txt new file mode 100644 index 00000000..f2ea26e6 --- /dev/null +++ b/1501-2000/1660-Correct-a-Binary-Tree/cpp-1660/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1660) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1660 main.cpp) \ No newline at end of file diff --git a/1501-2000/1660-Correct-a-Binary-Tree/cpp-1660/main.cpp b/1501-2000/1660-Correct-a-Binary-Tree/cpp-1660/main.cpp new file mode 100644 index 00000000..33d6993b --- /dev/null +++ b/1501-2000/1660-Correct-a-Binary-Tree/cpp-1660/main.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/correct-a-binary-tree/ +/// Author : liuyubobobo +/// Time : 2020-11-21 + +#include +#include + +using namespace std; + + +/// Using HashSet and DFS +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// 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 { + +private: + unordered_set set; + +public: + TreeNode* correctBinaryTree(TreeNode* root) { + + set.clear(); + return dfs(root); + } + +private: + TreeNode* dfs(TreeNode* node){ + + set.insert(node); + if(node->right && set.count(node->right)) return nullptr; + + if(node->right) node->right = dfs(node->right); + if(node->left) node->left = dfs(node->left); + return node; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1662-Check-If-Two-String-Arrays-are-Equivalent/cpp-1662/CMakeLists.txt b/1501-2000/1662-Check-If-Two-String-Arrays-are-Equivalent/cpp-1662/CMakeLists.txt new file mode 100644 index 00000000..ec9e7c4c --- /dev/null +++ b/1501-2000/1662-Check-If-Two-String-Arrays-are-Equivalent/cpp-1662/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main2.cpp) \ No newline at end of file diff --git a/1501-2000/1662-Check-If-Two-String-Arrays-are-Equivalent/cpp-1662/main.cpp b/1501-2000/1662-Check-If-Two-String-Arrays-are-Equivalent/cpp-1662/main.cpp new file mode 100644 index 00000000..82881b07 --- /dev/null +++ b/1501-2000/1662-Check-If-Two-String-Arrays-are-Equivalent/cpp-1662/main.cpp @@ -0,0 +1,29 @@ +/// Source : https://leetcode.com/problems/check-if-two-string-arrays-are-equivalent/ +/// Author : liuyubobobo +/// Time : 2020-11-21 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(|word1| + |word2| + |s|) +/// Space Complexity: O(|s|) +class Solution { +public: + bool arrayStringsAreEqual(vector& word1, vector& word2) { + + string a = "", b = ""; + for(const string& s: word1) a += s; + for(const string& s: word2) b += s; + return a == b; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1662-Check-If-Two-String-Arrays-are-Equivalent/cpp-1662/main2.cpp b/1501-2000/1662-Check-If-Two-String-Arrays-are-Equivalent/cpp-1662/main2.cpp new file mode 100644 index 00000000..7ae325e8 --- /dev/null +++ b/1501-2000/1662-Check-If-Two-String-Arrays-are-Equivalent/cpp-1662/main2.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/check-if-two-string-arrays-are-equivalent/ +/// Author : liuyubobobo +/// Time : 2020-11-21 + +#include +#include + +using namespace std; + + +/// Two Pointers +/// Time Complexity: O(|s|) +/// Space Complexity: O(1) +class Solution { +public: + bool arrayStringsAreEqual(vector& word1, vector& word2) { + + int p1 = 0, p2 = 0, i = 0, j = 0; + while(p1 < word1.size() && p2 < word2.size()){ + + if(word1[p1][i] != word2[p2][j]) return false; + + i ++; + if(i == word1[p1].size()) p1 ++, i = 0; + + j ++; + if(j == word2[p2].size()) p2 ++, j = 0; + } + return p1 == word1.size() && p2 == word2.size(); + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1663-Smallest-String-With-A-Given-Numeric-Value/cpp-1663/CMakeLists.txt b/1501-2000/1663-Smallest-String-With-A-Given-Numeric-Value/cpp-1663/CMakeLists.txt new file mode 100644 index 00000000..81ad8b42 --- /dev/null +++ b/1501-2000/1663-Smallest-String-With-A-Given-Numeric-Value/cpp-1663/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1501-2000/1663-Smallest-String-With-A-Given-Numeric-Value/cpp-1663/main.cpp b/1501-2000/1663-Smallest-String-With-A-Given-Numeric-Value/cpp-1663/main.cpp new file mode 100644 index 00000000..3ceca8c9 --- /dev/null +++ b/1501-2000/1663-Smallest-String-With-A-Given-Numeric-Value/cpp-1663/main.cpp @@ -0,0 +1,44 @@ +/// Source : https://leetcode.com/problems/smallest-string-with-a-given-numeric-value/ +/// Author : liuyubobobo +/// Time : 2020-11-21 + +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + string getSmallestString(int n, int k) { + + string res(n, 'a'); + int sum = n; + + int i = n - 1; + while(sum != k){ + if(k - sum >= 25) + res[i] = 'z', sum += 25; + else + res[i] += (k - sum), sum = k; + + i --; + } + return res; + } +}; + + +int main() { + + cout << Solution().getSmallestString(3, 27) << endl; + // aay + + cout << Solution().getSmallestString(5, 73) << endl; + // aaszz + + return 0; +} diff --git a/1501-2000/1664-Ways-to-Make-a-Fair-Array/cpp-1664/CMakeLists.txt b/1501-2000/1664-Ways-to-Make-a-Fair-Array/cpp-1664/CMakeLists.txt new file mode 100644 index 00000000..ce73aee9 --- /dev/null +++ b/1501-2000/1664-Ways-to-Make-a-Fair-Array/cpp-1664/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1501-2000/1664-Ways-to-Make-a-Fair-Array/cpp-1664/main.cpp b/1501-2000/1664-Ways-to-Make-a-Fair-Array/cpp-1664/main.cpp new file mode 100644 index 00000000..b4cb16df --- /dev/null +++ b/1501-2000/1664-Ways-to-Make-a-Fair-Array/cpp-1664/main.cpp @@ -0,0 +1,60 @@ +/// Source : https://leetcode.com/problems/ways-to-make-a-fair-array/ +/// Author : liuyubobobo +/// Time : 2020-11-21 + +#include +#include + +using namespace std; + + +/// Presum +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int waysToMakeFair(vector& nums) { + + int n = nums.size(); + vector evenpresum(n + 1, 0), oddpresum(n + 1, 0); + for(int i = 0; i < n; i ++) + if(i % 2 == 0){ + evenpresum[i + 1] = evenpresum[i] + nums[i]; + oddpresum[i + 1] = oddpresum[i]; + } + else{ + oddpresum[i + 1] = oddpresum[i] + nums[i]; + evenpresum[i + 1] = evenpresum[i]; + } + + int res = 0; + for(int i = 0; i < n; i ++){ + + int evensum = 0, oddsum = 0; + if(i) evensum += evenpresum[i], oddsum += oddpresum[i]; + + evensum += oddpresum[n] - oddpresum[i + 1]; + oddsum += evenpresum[n] - evenpresum[i + 1]; + if(evensum == oddsum) res ++; + } + return res; + } +}; + + +int main() { + + vector nums1 = {2, 1, 6, 4}; + cout << Solution().waysToMakeFair(nums1) << endl; + // 1 + + vector nums2 = {1, 1, 1}; + cout << Solution().waysToMakeFair(nums2) << endl; + // 3 + + vector nums3 = {1, 2, 3}; + cout << Solution().waysToMakeFair(nums3) << endl; + // 0 + + return 0; +} diff --git a/1501-2000/1665-Minimum-Initial-Energy-to-Finish-Tasks/cpp-1665/CMakeLists.txt b/1501-2000/1665-Minimum-Initial-Energy-to-Finish-Tasks/cpp-1665/CMakeLists.txt new file mode 100644 index 00000000..74cc3ee6 --- /dev/null +++ b/1501-2000/1665-Minimum-Initial-Energy-to-Finish-Tasks/cpp-1665/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) \ No newline at end of file diff --git a/1501-2000/1665-Minimum-Initial-Energy-to-Finish-Tasks/cpp-1665/main.cpp b/1501-2000/1665-Minimum-Initial-Energy-to-Finish-Tasks/cpp-1665/main.cpp new file mode 100644 index 00000000..636e18b0 --- /dev/null +++ b/1501-2000/1665-Minimum-Initial-Energy-to-Finish-Tasks/cpp-1665/main.cpp @@ -0,0 +1,67 @@ +/// Source : https://leetcode.com/problems/minimum-initial-energy-to-finish-tasks/ +/// Author : liuyubobobo +/// Time : 2020-11-21 + +#include +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(nlogn + nlog|max_int|) +/// Space Complexity: O(1) +class Solution { +public: + int minimumEffort(vector>& tasks) { + + sort(tasks.begin(), tasks.end(), [](const vector& v1, const vector& v2){ + + if(v1[1] - v1[0] != v2[1] - v2[0]) + return v1[1] - v1[0] > v2[1] - v2[0]; + + return v1[1] > v2[1]; + }); + + int l = 0, r = 2e9; + while(l < r){ + int mid = (l + r) / 2; + if(ok(tasks, mid)) r = mid; + else l = mid + 1; + } + return l; + } + +private: + bool ok(const vector>& v, int k){ + + for(const vector& e: v){ + if(k < e[1]) return false; + k -= e[0]; + } + return true; + } +}; + + +int main() { + + vector> tasks1 = {{1, 2}, {2, 4}, {4, 8}}; + cout << Solution().minimumEffort(tasks1) << endl; + // 8 + + vector> tasks2 = {{1, 3}, {2, 4}, {10, 11}, {10, 12}, {8, 9}}; + cout << Solution().minimumEffort(tasks2) << endl; + // 32 + + vector> tasks3 = {{1, 7}, {2, 8}, {3, 9}, {4, 10}, {5, 11}, {6, 12}}; + cout << Solution().minimumEffort(tasks3) << endl; + // 27 + + vector> tasks4 = {{1, 2}, {1, 7}, {2, 3}, {5, 9}, {2, 2}}; + cout << Solution().minimumEffort(tasks4) << endl; + // 11 + + return 0; +} diff --git a/1501-2000/1666-Change-the-Root-of-a-Binary-Tree/cpp-1666/CMakeLists.txt b/1501-2000/1666-Change-the-Root-of-a-Binary-Tree/cpp-1666/CMakeLists.txt new file mode 100644 index 00000000..b571cb98 --- /dev/null +++ b/1501-2000/1666-Change-the-Root-of-a-Binary-Tree/cpp-1666/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1666) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1666 main.cpp) \ No newline at end of file diff --git a/1501-2000/1666-Change-the-Root-of-a-Binary-Tree/cpp-1666/main.cpp b/1501-2000/1666-Change-the-Root-of-a-Binary-Tree/cpp-1666/main.cpp new file mode 100644 index 00000000..5c7879ef --- /dev/null +++ b/1501-2000/1666-Change-the-Root-of-a-Binary-Tree/cpp-1666/main.cpp @@ -0,0 +1,99 @@ +/// Source : https://leetcode.com/problems/change-the-root-of-a-binary-tree/ +/// Author : liuyubobobo +/// Time : 2020-11-30 + +#include +#include +#include + +using namespace std; + + +/// Recursion +/// Time Complexity: O(n) +/// Space Complexity: O(h) +class Node { +public: + int val; + Node* left; + Node* right; + Node* parent = 0; + + Node(int v, Node* l, Node* r): val(v), left(l), right(r){} + Node(int v): Node(v, 0, 0){} +}; + +class Solution { + +public: + Node* flipBinaryTree(Node* root, Node * leaf) { + Node* res = flip(leaf); + res->parent = nullptr; + return res; + } + +private: + Node* flip(Node* node){ + + if(!node->parent) return node; + + if(node->parent->left == node) + node->parent->left = nullptr; + else + node->parent->right = nullptr; + + if(node->left){ + node->right = node->left; + node->right->parent = node; + } + node->left = flip(node->parent); + node->left->parent = node; + return node; + } +}; + + +int main() { + +// Node* leaf = new Node(7); +// Node* four = new Node(4); +// Node* two = new Node(2, leaf, four); +// +// Node* six = new Node(6); +// Node* five = new Node(5, six, two); +// +// Node* zero = new Node(0); +// Node* eight = new Node(8); +// Node* one = new Node(1, zero, eight); +// +// Node* root = new Node(3, five, one); +// +// leaf->parent = two; four->parent = two; +// two->parent = five; six->parent = five; +// zero->parent = one; eight->parent = one; +// five->parent = root; one->parent = root; +// +// Node* res = Solution().flipBinaryTree(root, leaf); + + Node* seven = new Node(7); + Node* four = new Node(4); + Node* two = new Node(2, seven, four); + + Node* six = new Node(6); + Node* five = new Node(5, six, two); + + Node* zero = new Node(0); + Node* eight = new Node(8); + Node* one = new Node(1, zero, eight); + + Node* three = new Node(3, five, one); + + seven->parent = two, four->parent = two; + six->parent = five, two->parent = five; + zero->parent = one, eight->parent = one; + five->parent = three, one->parent = three; + + Node* res = Solution().flipBinaryTree(three, zero); + + return 0; +} diff --git a/1501-2000/1668-Maximum-Repeating-Substring/cpp-1668/CMakeLists.txt b/1501-2000/1668-Maximum-Repeating-Substring/cpp-1668/CMakeLists.txt new file mode 100644 index 00000000..21786fd8 --- /dev/null +++ b/1501-2000/1668-Maximum-Repeating-Substring/cpp-1668/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1668) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1668 main2.cpp) \ No newline at end of file diff --git a/1501-2000/1668-Maximum-Repeating-Substring/cpp-1668/main.cpp b/1501-2000/1668-Maximum-Repeating-Substring/cpp-1668/main.cpp new file mode 100644 index 00000000..0475f83b --- /dev/null +++ b/1501-2000/1668-Maximum-Repeating-Substring/cpp-1668/main.cpp @@ -0,0 +1,39 @@ +/// Source : https://leetcode.com/problems/maximum-repeating-substring/ +/// Author : liuyubobobo +/// Time : 2020-11-28 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { +public: + int maxRepeating(string sequence, string word) { + + int res = 0; + for(int i = 1; ; i ++){ + string t = ""; + for(int j = 0; j < i; j ++) t += word; + if(sequence.find(t) == string::npos) break; + res ++; + } + return res; + } +}; + + +int main() { + + cout << Solution().maxRepeating("ababc", "ab") << endl; + // 2 + + cout << Solution().maxRepeating("ababc", "ba") << endl; + // 1 + + return 0; +} diff --git a/1501-2000/1668-Maximum-Repeating-Substring/cpp-1668/main2.cpp b/1501-2000/1668-Maximum-Repeating-Substring/cpp-1668/main2.cpp new file mode 100644 index 00000000..3fed2596 --- /dev/null +++ b/1501-2000/1668-Maximum-Repeating-Substring/cpp-1668/main2.cpp @@ -0,0 +1,39 @@ +/// Source : https://leetcode.com/problems/maximum-repeating-substring/ +/// Author : liuyubobobo +/// Time : 2020-11-28 + +#include +#include + +using namespace std; + + +/// Two Pointers +/// Time Complexity: O(n^2) +/// Space Complexity: O(1) +class Solution { +public: + int maxRepeating(string sequence, string word) { + + int res = 0; + for(int i = 0; i < sequence.size(); i ++){ + int j; + for(j = 0; i + j < sequence.size() && sequence[i + j] == word[j % word.size()]; j ++); + res = max(res, j / (int)word.size()); + + } + return res; + } +}; + + +int main() { + + cout << Solution().maxRepeating("ababc", "ab") << endl; + // 2 + + cout << Solution().maxRepeating("ababc", "ba") << endl; + // 1 + + return 0; +} diff --git a/1501-2000/1669-Merge-In-Between-Linked-Lists/cpp-1669/CMakeLists.txt b/1501-2000/1669-Merge-In-Between-Linked-Lists/cpp-1669/CMakeLists.txt new file mode 100644 index 00000000..f081ec1f --- /dev/null +++ b/1501-2000/1669-Merge-In-Between-Linked-Lists/cpp-1669/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1669) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1669 main.cpp) \ No newline at end of file diff --git a/1501-2000/1669-Merge-In-Between-Linked-Lists/cpp-1669/main.cpp b/1501-2000/1669-Merge-In-Between-Linked-Lists/cpp-1669/main.cpp new file mode 100644 index 00000000..9ef06cd6 --- /dev/null +++ b/1501-2000/1669-Merge-In-Between-Linked-Lists/cpp-1669/main.cpp @@ -0,0 +1,49 @@ +/// Source : https://leetcode.com/problems/design-front-middle-back-queue/ +/// Author : liuyubobobo +/// Time : 2020-11-28 + +#include + +using namespace std; + + +/// Linked List Operation +/// Time Complexity: O(b + |list2|) +/// Space Complexity: O(1) + +/// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode() : val(0), next(nullptr) {} + ListNode(int x) : val(x), next(nullptr) {} + ListNode(int x, ListNode *next) : val(x), next(next) {} +}; + +class Solution { +public: + ListNode* mergeInBetween(ListNode* list1, int a, int b, ListNode* list2) { + + ListNode* dummyHead = new ListNode(-1, list1); + + ListNode* apre, *bpre, *cur = dummyHead; + for(int i = 0; i <= b + 1; i ++){ + if(i == a) apre = cur; + if(i == b + 1) bpre = cur; + cur = cur->next; + } + + apre->next = list2; + + cur = list2; + while(cur->next) cur = cur->next; + cur->next = bpre->next; + + return dummyHead->next; + } +}; + +int main() { + + return 0; +} diff --git a/1501-2000/1670-Design-Front-Middle-Back-Queue/cpp-1670/CMakeLists.txt b/1501-2000/1670-Design-Front-Middle-Back-Queue/cpp-1670/CMakeLists.txt new file mode 100644 index 00000000..a8e02739 --- /dev/null +++ b/1501-2000/1670-Design-Front-Middle-Back-Queue/cpp-1670/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1670) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1670 main.cpp) \ No newline at end of file diff --git a/1501-2000/1670-Design-Front-Middle-Back-Queue/cpp-1670/main.cpp b/1501-2000/1670-Design-Front-Middle-Back-Queue/cpp-1670/main.cpp new file mode 100644 index 00000000..b1021757 --- /dev/null +++ b/1501-2000/1670-Design-Front-Middle-Back-Queue/cpp-1670/main.cpp @@ -0,0 +1,127 @@ +/// Source : https://leetcode.com/problems/design-front-middle-back-queue/ +/// Author : liuyubobobo +/// Time : 2020-11-28 + +#include +#include +using namespace std; + + +/// Double Deque +/// Time Complexity: O(1) for every operations +/// Space Complexity: O(n) +class FrontMiddleBackQueue { + +private: + deque first, second; + +public: + FrontMiddleBackQueue(){ } + + void pushFront(int val) { + + first.push_front(val); + if(first.size() == second.size() + 2){ + second.push_front(first.back()); + first.pop_back(); + } + } + + void pushMiddle(int val) { + + if(first.size() > second.size()){ + second.push_front(first.back()); + first.pop_back(); + } + first.push_back(val); + } + + void pushBack(int val) { + + second.push_back(val); + if(second.size() > first.size()){ + first.push_back(second.front()); + second.pop_front(); + } + } + + int popFront() { + + if(first.size() == 0) return -1; + + int ret = first.front(); + first.pop_front(); + if(second.size() > first.size()){ + first.push_back(second.front()); + second.pop_front(); + } + return ret; + } + + int popMiddle() { + + if(first.size() == 0) return -1; + + int ret = first.back(); + first.pop_back(); + if(second.size() > first.size()){ + first.push_back(second.front()); + second.pop_front(); + } + return ret; + } + + int popBack() { + + if(first.size() == 0) return -1; + + if(second.size() == 0){ + int ret = first.back(); + first.pop_back(); + return ret; + } + + int ret = second.back(); + second.pop_back(); + if(first.size() == second.size() + 2){ + second.push_front(first.back()); + first.pop_back(); + } + return ret; + } +}; + + +int main() { + + FrontMiddleBackQueue q1; + q1.pushFront(1); // [1] + q1.pushBack(2); // [1, 2] + q1.pushMiddle(3); // [1, 3, 2] + q1.pushMiddle(4); // [1, 4, 3, 2] + + cout << q1.popFront() << endl; + // 1 -> [4, 3, 2] + + cout << q1.popMiddle() << endl; + // return 3 -> [4, 2] + + cout << q1.popMiddle() << endl; + // return 4 -> [2] + + cout << q1.popBack() << endl; + // return 2 -> [] + + FrontMiddleBackQueue q2; + q2.pushFront(1); // [1] + q2.pushFront(2); // [2, 1] + q2.pushFront(3); // [3, 2, 1] + q2.pushFront(4); // [4, 3, 2, 1] + + cout << q2.popBack() << endl; // 1 + cout << q2.popBack() << endl; // 2 + cout << q2.popBack() << endl; // 3 + cout << q2.popBack() << endl; // 4 + + return 0; +} diff --git a/1501-2000/1671-Minimum-Number-of-Removals-to-Make-Mountain-Array/cpp-1671/CMakeLists.txt b/1501-2000/1671-Minimum-Number-of-Removals-to-Make-Mountain-Array/cpp-1671/CMakeLists.txt new file mode 100644 index 00000000..de0442fb --- /dev/null +++ b/1501-2000/1671-Minimum-Number-of-Removals-to-Make-Mountain-Array/cpp-1671/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1671) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1671 main2.cpp) \ No newline at end of file diff --git a/1501-2000/1671-Minimum-Number-of-Removals-to-Make-Mountain-Array/cpp-1671/main.cpp b/1501-2000/1671-Minimum-Number-of-Removals-to-Make-Mountain-Array/cpp-1671/main.cpp new file mode 100644 index 00000000..e27d1ea3 --- /dev/null +++ b/1501-2000/1671-Minimum-Number-of-Removals-to-Make-Mountain-Array/cpp-1671/main.cpp @@ -0,0 +1,60 @@ +/// Source : https://leetcode.com/problems/minimum-number-of-removals-to-make-mountain-array/ +/// Author : liuyubobobo +/// Time : 2020-11-29 + +#include +#include + +using namespace std; + + +/// Dynamic Programming - LIS +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { +public: + int minimumMountainRemovals(vector& nums) { + + int n = nums.size(); + + vector dp1(n, 1); + for(int i = 1; i < n; i ++){ + for(int j = i - 1; j >= 0; j --) + if(nums[i] > nums[j]) dp1[i] = max(dp1[i], 1 + dp1[j]); + } + + vector dp2(n, 1); + for(int i = n - 2; i >= 0; i --){ + for(int j = i + 1; j < n; j ++) + if(nums[i] > nums[j]) dp2[i] = max(dp2[i], 1 + dp2[j]); + } + + int res = 3; + for(int i = 0; i < n; i ++) + if(dp1[i] > 1 && dp2[i] > 1) + res = max(res, dp1[i] + dp2[i] - 1); + return n - res; + } +}; + + +int main() { + + vector nums1 = {1, 3, 1}; + cout << Solution().minimumMountainRemovals(nums1) << endl; + // 0 + + vector nums2 = {2,1,1,5,6,2,3,1}; + cout << Solution().minimumMountainRemovals(nums2) << endl; + // 3 + + vector nums3 = {4,3,2,1,1,2,3,1}; + cout << Solution().minimumMountainRemovals(nums3) << endl; + // 4 + + vector nums4 = {1,2,3,4,4,3,2,1}; + cout << Solution().minimumMountainRemovals(nums4) << endl; + // 1 + + return 0; +} diff --git a/1501-2000/1671-Minimum-Number-of-Removals-to-Make-Mountain-Array/cpp-1671/main2.cpp b/1501-2000/1671-Minimum-Number-of-Removals-to-Make-Mountain-Array/cpp-1671/main2.cpp new file mode 100644 index 00000000..21aac69b --- /dev/null +++ b/1501-2000/1671-Minimum-Number-of-Removals-to-Make-Mountain-Array/cpp-1671/main2.cpp @@ -0,0 +1,65 @@ +/// Source : https://leetcode.com/problems/minimum-number-of-removals-to-make-mountain-array/ +/// Author : liuyubobobo +/// Time : 2020-11-29 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Using LIS O(nlogn) Solution +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + int minimumMountainRemovals(vector& nums) { + + int n = nums.size(); + + vector dp1 = {nums[0]}, len1(n, 1); + for(int i = 1; i < n; i ++){ + int index = lower_bound(dp1.begin(), dp1.end(), nums[i]) - dp1.begin(); + if(index >= dp1.size()) dp1.push_back(nums[i]); + else dp1[index] = nums[i]; + len1[i] = index + 1; + } + + vector dp2 = {nums.back()}, len2(n, 1); + for(int i = n - 2; i >= 0; i --){ + int index = lower_bound(dp2.begin(), dp2.end(), nums[i]) - dp2.begin(); + if(index >= dp2.size()) dp2.push_back(nums[i]); + else dp2[index] = nums[i]; + len2[i] = index + 1; + } + + int res = 3; + for(int i = 0; i < n; i ++) + if(len1[i] > 1 && len2[i] > 1) + res = max(res, len1[i] + len2[i] - 1); + return n - res; + } +}; + + +int main() { + + vector nums1 = {1, 3, 1}; + cout << Solution().minimumMountainRemovals(nums1) << endl; + // 0 + + vector nums2 = {2,1,1,5,6,2,3,1}; + cout << Solution().minimumMountainRemovals(nums2) << endl; + // 3 + + vector nums3 = {4,3,2,1,1,2,3,1}; + cout << Solution().minimumMountainRemovals(nums3) << endl; + // 4 + + vector nums4 = {1,2,3,4,4,3,2,1}; + cout << Solution().minimumMountainRemovals(nums4) << endl; + // 1 + + return 0; +} diff --git a/1501-2000/1672-Richest-Customer-Wealth/cpp-1672/CMakeLists.txt b/1501-2000/1672-Richest-Customer-Wealth/cpp-1672/CMakeLists.txt new file mode 100644 index 00000000..d5d5e4ff --- /dev/null +++ b/1501-2000/1672-Richest-Customer-Wealth/cpp-1672/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1501-2000/1672-Richest-Customer-Wealth/cpp-1672/main.cpp b/1501-2000/1672-Richest-Customer-Wealth/cpp-1672/main.cpp new file mode 100644 index 00000000..db8af816 --- /dev/null +++ b/1501-2000/1672-Richest-Customer-Wealth/cpp-1672/main.cpp @@ -0,0 +1,30 @@ +/// Source : https://leetcode.com/problems/richest-customer-wealth/ +/// Author : liuyubobobo +/// Time : 2020-11-28 + +#include +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n * m) +/// Space Complexity: O(1) +class Solution { +public: + int maximumWealth(vector>& accounts) { + + int res = 0; + for(const vector& v: accounts) + res = max(res, accumulate(v.begin(), v.end(), 0)); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1673-Find-the-Most-Competitive-Subsequence/cpp-1673/CMakeLists.txt b/1501-2000/1673-Find-the-Most-Competitive-Subsequence/cpp-1673/CMakeLists.txt new file mode 100644 index 00000000..aab7d499 --- /dev/null +++ b/1501-2000/1673-Find-the-Most-Competitive-Subsequence/cpp-1673/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main4.cpp) \ No newline at end of file diff --git a/1501-2000/1673-Find-the-Most-Competitive-Subsequence/cpp-1673/main.cpp b/1501-2000/1673-Find-the-Most-Competitive-Subsequence/cpp-1673/main.cpp new file mode 100644 index 00000000..3cb86e12 --- /dev/null +++ b/1501-2000/1673-Find-the-Most-Competitive-Subsequence/cpp-1673/main.cpp @@ -0,0 +1,96 @@ +/// Source : https://leetcode.com/problems/find-the-most-competitive-subsequence/ +/// Author : liuyubobobo +/// Time : 2020-11-28 + +#include +#include + +using namespace std; + + +/// Segment Tree +/// Time Complexity: O(nlogn + klogn) +/// Space Complexity: O(n) +class SegmentTree{ + +private: + int n; + vector data, tree; + +public: + SegmentTree(const vector& data): n(data.size()), data(data), tree(4 * n, 0){ + buildSegTree(0, 0, n - 1); + } + + int query(int l, int r){ + return query(0, 0, n - 1, l, r); + } + +private: + void buildSegTree(int treeID, int l, int r){ + + if(l == r){ + tree[treeID] = l; + return; + } + + int mid = (l + r) / 2; + buildSegTree(treeID * 2 + 1, l, mid); + buildSegTree(treeID * 2 + 2, mid + 1, r); + + int resl = tree[treeID * 2 + 1], resr = tree[treeID * 2 + 2]; + tree[treeID] = data[resl] <= data[resr] ? resl : resr; + return; + } + + int query(int treeID, int l, int r, int ql, int qr){ + + if(ql == l && qr == r) + return tree[treeID]; + + int mid = (l + r) / 2; + if(qr <= mid) return query(treeID * 2 + 1, l, mid, ql, qr); + else if(ql > mid) return query(treeID * 2 + 2, mid + 1, r, ql, qr); + + int resl = query(treeID * 2 + 1, l, mid, ql, mid); + int resr = query(treeID * 2 + 2, mid + 1, r, mid + 1, qr); + return data[resl] <= data[resr] ? resl : resr; + } +}; + +class Solution { +public: + vector mostCompetitive(vector& nums, int k) { + + SegmentTree segTree(nums); + + int n = nums.size(); + vector res(k); + int l = 0, r = n - k; + for(int i = 0; i < k; i ++){ + int minindex = segTree.query(l, r); + res[i] = nums[minindex]; + l = minindex + 1; + r ++; + } + return res; + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << " "; cout << endl; +} + +int main() { + + vector nums1 = {3, 5, 2, 6}; + print_vec(Solution().mostCompetitive(nums1, 2)); + // 2 6 + + vector nums2 = {2,4,3,3,5,4,9,6}; + print_vec(Solution().mostCompetitive(nums2, 4)); + // 2 3 3 4 + + return 0; +} \ No newline at end of file diff --git a/1501-2000/1673-Find-the-Most-Competitive-Subsequence/cpp-1673/main2.cpp b/1501-2000/1673-Find-the-Most-Competitive-Subsequence/cpp-1673/main2.cpp new file mode 100644 index 00000000..9ef53fe4 --- /dev/null +++ b/1501-2000/1673-Find-the-Most-Competitive-Subsequence/cpp-1673/main2.cpp @@ -0,0 +1,59 @@ +/// Source : https://leetcode.com/problems/find-the-most-competitive-subsequence/ +/// Author : liuyubobobo +/// Time : 2020-11-30 + +#include +#include +#include + +using namespace std; + + +/// Using Priority Queue +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + vector mostCompetitive(vector& nums, int k) { + + priority_queue, vector>, greater>> pq; + + int n = nums.size(); + for(int i = 0; i < n - k; i ++) + pq.push({nums[i], i}); + + vector res(k); + int l = 0, r = n - k; + for(int i = 0; i < k; i ++){ + + pq.push({nums[r], r}); + r ++; + + while(!pq.empty() && pq.top().second < l) pq.pop(); + + assert(!pq.empty()); + res[i] = pq.top().first; + l = pq.top().second + 1; + pq.pop(); + } + return res; + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << " "; cout << endl; +} + +int main() { + + vector nums1 = {3, 5, 2, 6}; + print_vec(Solution().mostCompetitive(nums1, 2)); + // 2 6 + + vector nums2 = {2,4,3,3,5,4,9,6}; + print_vec(Solution().mostCompetitive(nums2, 4)); + // 2 3 3 4 + + return 0; +} \ No newline at end of file diff --git a/1501-2000/1673-Find-the-Most-Competitive-Subsequence/cpp-1673/main3.cpp b/1501-2000/1673-Find-the-Most-Competitive-Subsequence/cpp-1673/main3.cpp new file mode 100644 index 00000000..be33e91b --- /dev/null +++ b/1501-2000/1673-Find-the-Most-Competitive-Subsequence/cpp-1673/main3.cpp @@ -0,0 +1,59 @@ +/// Source : https://leetcode.com/problems/find-the-most-competitive-subsequence/ +/// Author : liuyubobobo +/// Time : 2020-11-30 + +#include +#include +#include + +using namespace std; + + +/// Using TreeSet +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + vector mostCompetitive(vector& nums, int k) { + + set> tree; + + int n = nums.size(); + for(int i = 0; i < n - k; i ++) + tree.insert({nums[i], i}); + + vector res(k); + int l = 0, r = n - k; + for(int i = 0; i < k; i ++){ + + tree.insert({nums[r], r}); + r ++; + + while(!tree.empty() && tree.begin()->second < l) tree.erase(tree.begin()); + + assert(!tree.empty()); + res[i] = tree.begin()->first; + l = tree.begin()->second + 1; + tree.erase(tree.begin()); + } + return res; + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << " "; cout << endl; +} + +int main() { + + vector nums1 = {3, 5, 2, 6}; + print_vec(Solution().mostCompetitive(nums1, 2)); + // 2 6 + + vector nums2 = {2,4,3,3,5,4,9,6}; + print_vec(Solution().mostCompetitive(nums2, 4)); + // 2 3 3 4 + + return 0; +} \ No newline at end of file diff --git a/1501-2000/1673-Find-the-Most-Competitive-Subsequence/cpp-1673/main4.cpp b/1501-2000/1673-Find-the-Most-Competitive-Subsequence/cpp-1673/main4.cpp new file mode 100644 index 00000000..72fa2387 --- /dev/null +++ b/1501-2000/1673-Find-the-Most-Competitive-Subsequence/cpp-1673/main4.cpp @@ -0,0 +1,49 @@ +/// Source : https://leetcode.com/problems/find-the-most-competitive-subsequence/ +/// Author : liuyubobobo +/// Time : 2020-11-30 + +#include +#include + +using namespace std; + + +/// Mono Stack +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector mostCompetitive(vector& nums, int k) { + + vector stack; + int remove = nums.size() - k; + + for(int e: nums){ + while(!stack.empty() && remove && stack.back() > e) + stack.pop_back(), remove --; + + stack.push_back(e); + } + + while(remove) stack.pop_back(), remove --; + return stack; + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << " "; cout << endl; +} + +int main() { + + vector nums1 = {3, 5, 2, 6}; + print_vec(Solution().mostCompetitive(nums1, 2)); + // 2 6 + + vector nums2 = {2,4,3,3,5,4,9,6}; + print_vec(Solution().mostCompetitive(nums2, 4)); + // 2 3 3 4 + + return 0; +} \ No newline at end of file diff --git a/1501-2000/1674-Minimum-Moves-to-Make-Array-Complementary/cpp-1674/CMakeLists.txt b/1501-2000/1674-Minimum-Moves-to-Make-Array-Complementary/cpp-1674/CMakeLists.txt new file mode 100644 index 00000000..a645af27 --- /dev/null +++ b/1501-2000/1674-Minimum-Moves-to-Make-Array-Complementary/cpp-1674/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main3.cpp) \ No newline at end of file diff --git a/1501-2000/1674-Minimum-Moves-to-Make-Array-Complementary/cpp-1674/main.cpp b/1501-2000/1674-Minimum-Moves-to-Make-Array-Complementary/cpp-1674/main.cpp new file mode 100644 index 00000000..d0ea4f04 --- /dev/null +++ b/1501-2000/1674-Minimum-Moves-to-Make-Array-Complementary/cpp-1674/main.cpp @@ -0,0 +1,131 @@ +/// Source : https://leetcode.com/problems/minimum-moves-to-make-array-complementary/ +/// Author : liuyubobobo +/// Time : 2020-11-30 + +#include +#include + +using namespace std; + + +/// Using Segment Tree +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class SegmentTree{ + +private: + int n; + vector tree, lazy; + +public: + SegmentTree(int n): n(n), tree(4 * n, 0ll), lazy(4 * n, 0ll){} + + void add(int index, int val){ + update(0, 0, n - 1, index, index, val); + } + + void add(int uL, int uR, int val){ + update(0, 0, n - 1, uL, uR, val); + } + + int query(int index){ + return query(0, 0, n - 1, index, index); + } + +private: + void update(int treeID, int treeL, int treeR, int uL, int uR, int val){ + + if(lazy[treeID]){ + tree[treeID] += lazy[treeID] * (treeR - treeL + 1); + if(treeL != treeR){ + lazy[2 * treeID + 1] += lazy[treeID]; + lazy[2 * treeID + 2] += lazy[treeID]; + } + lazy[treeID] = 0; + } + + if (treeL > uR || treeR < uL) return; + + if(uL <= treeL && uR >= treeR){ + tree[treeID] += (long long)val * (treeR - treeL + 1); + if(treeL != treeR){ + lazy[2 * treeID + 1] += val; + lazy[2 * treeID + 2] += val; + } + return; + } + + int mid = (treeL + treeR) / 2; + update(2 * treeID + 1, treeL, mid, uL, uR, val); + update(2 * treeID + 2, mid + 1, treeR, uL, uR, val); + tree[treeID] = tree[treeID * 2 + 1] + tree[treeID * 2 + 2]; + return; + } + + int query(int treeID, int treeL, int treeR, int qL, int qR){ + + if(lazy[treeID]){ + tree[treeID] += lazy[treeID] * (treeR - treeL + 1); + if(treeL != treeR){ + lazy[2 * treeID + 1] += lazy[treeID]; + lazy[2 * treeID + 2] += lazy[treeID]; + } + lazy[treeID] = 0; + } + + if(treeL > qR || treeR < qL) return 0; + + if(qL <= treeL && qR >= treeR) + return tree[treeID]; + + int mid = (treeL + treeR) / 2; + int leftRes = query(2 * treeID + 1, treeL, mid, qL, qR); + int rightRes = query(2 * treeID + 2, mid + 1, treeR, qL, qR); + return leftRes + rightRes; + } +}; + +class Solution { +public: + int minMoves(vector& nums, int limit) { + + SegmentTree segTree(limit * 2 + 1); + + int n = nums.size(); + for(int i = 0; i < n / 2; i ++){ + int x = nums[i], y = nums[n - 1 - i]; + segTree.add(2, 2 * limit, 2); + segTree.add(1 + min(x, y), limit + max(x, y), -1); + segTree.add(x + y, -1); + } + + int res = n; + for(int i = 2; i <= 2 * limit; i ++){ +// cout << segTree.query(i); + res = min(res, segTree.query(i)); + } + return res; + } +}; + + +int main() { + + vector nums1 = {1, 2, 4, 3}; + cout << Solution().minMoves(nums1, 4) << endl; + // 1 + + vector nums2 = {1, 2, 2, 1}; + cout << Solution().minMoves(nums2, 2) << endl; + // 2 + + vector nums3 = {1, 2, 1, 2}; + cout << Solution().minMoves(nums3, 2) << endl; + // 0 + + vector nums4 = {3,1,2,1,2,3,3,1,2,3,2,2,1,2,3,3,3,1,1,2,3,2,1,1,2,3,3,3,1,3,3,1,1,2,2,2,2,2,1,3,1,2,2,2}; + cout << Solution().minMoves(nums4, 3) << endl; + // 13 + + return 0; +} \ No newline at end of file diff --git a/1501-2000/1674-Minimum-Moves-to-Make-Array-Complementary/cpp-1674/main2.cpp b/1501-2000/1674-Minimum-Moves-to-Make-Array-Complementary/cpp-1674/main2.cpp new file mode 100644 index 00000000..cc62eb3e --- /dev/null +++ b/1501-2000/1674-Minimum-Moves-to-Make-Array-Complementary/cpp-1674/main2.cpp @@ -0,0 +1,131 @@ +/// Source : https://leetcode.com/problems/minimum-moves-to-make-array-complementary/ +/// Author : liuyubobobo +/// Time : 2020-11-30 + +#include +#include +#include + +using namespace std; + + +/// Segment Tree Optimized +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class SegmentTree{ + +private: + int n; + vector tree, lazy; + +public: + SegmentTree(int n): n(n), tree(4 * n, 0ll), lazy(4 * n, 0ll){} + + void add(int index, int val){ + update(0, 0, n - 1, index, index, val); + } + + void add(int uL, int uR, int val){ + update(0, 0, n - 1, uL, uR, val); + } + + int query(int index){ + return query(0, 0, n - 1, index, index); + } + +private: + void update(int treeID, int treeL, int treeR, int uL, int uR, int val){ + + if(lazy[treeID]){ + tree[treeID] += lazy[treeID] * (treeR - treeL + 1); + if(treeL != treeR){ + lazy[2 * treeID + 1] += lazy[treeID]; + lazy[2 * treeID + 2] += lazy[treeID]; + } + lazy[treeID] = 0; + } + + if (treeL > uR || treeR < uL) return; + + if(uL <= treeL && uR >= treeR){ + tree[treeID] += (long long)val * (treeR - treeL + 1); + if(treeL != treeR){ + lazy[2 * treeID + 1] += val; + lazy[2 * treeID + 2] += val; + } + return; + } + + int mid = (treeL + treeR) / 2; + update(2 * treeID + 1, treeL, mid, uL, uR, val); + update(2 * treeID + 2, mid + 1, treeR, uL, uR, val); + tree[treeID] = tree[treeID * 2 + 1] + tree[treeID * 2 + 2]; + return; + } + + int query(int treeID, int treeL, int treeR, int qL, int qR){ + + if(lazy[treeID]){ + tree[treeID] += lazy[treeID] * (treeR - treeL + 1); + if(treeL != treeR){ + lazy[2 * treeID + 1] += lazy[treeID]; + lazy[2 * treeID + 2] += lazy[treeID]; + } + lazy[treeID] = 0; + } + + if(treeL > qR || treeR < qL) return 0; + + if(qL <= treeL && qR >= treeR) + return tree[treeID]; + + int mid = (treeL + treeR) / 2; + int leftRes = query(2 * treeID + 1, treeL, mid, qL, qR); + int rightRes = query(2 * treeID + 2, mid + 1, treeR, qL, qR); + return leftRes + rightRes; + } +}; + +class Solution { +public: + int minMoves(vector& nums, int limit) { + + SegmentTree segTree(limit * 2 + 1); + + int n = nums.size(); + unordered_map f; + for(int i = 0; i < n / 2; i ++){ + int x = nums[i], y = nums[n - 1 - i]; + segTree.add(1 + min(x, y), limit + max(x, y), 1); + f[x + y] ++; + } + + int res = n; + for(int i = 2; i <= 2 * limit; i ++){ + res = min(res, n - segTree.query(i) - f[i]); + } + return res; + } +}; + + +int main() { + + vector nums1 = {1, 2, 4, 3}; + cout << Solution().minMoves(nums1, 4) << endl; + // 1 + + vector nums2 = {1, 2, 2, 1}; + cout << Solution().minMoves(nums2, 2) << endl; + // 2 + + vector nums3 = {1, 2, 1, 2}; + cout << Solution().minMoves(nums3, 2) << endl; + // 0 + + vector nums4 = {3,1,2,1,2,3,3,1,2,3,2,2,1,2,3,3,3,1,1,2,3,2,1,1,2,3,3,3,1,3,3,1,1,2,2,2,2,2,1,3,1,2,2,2}; + cout << Solution().minMoves(nums4, 3) << endl; + // 13 + + return 0; +} \ No newline at end of file diff --git a/1501-2000/1674-Minimum-Moves-to-Make-Array-Complementary/cpp-1674/main3.cpp b/1501-2000/1674-Minimum-Moves-to-Make-Array-Complementary/cpp-1674/main3.cpp new file mode 100644 index 00000000..f0fedb12 --- /dev/null +++ b/1501-2000/1674-Minimum-Moves-to-Make-Array-Complementary/cpp-1674/main3.cpp @@ -0,0 +1,63 @@ +/// Source : https://leetcode.com/problems/minimum-moves-to-make-array-complementary/ +/// Author : liuyubobobo +/// Time : 2020-11-28 + +#include +#include + +using namespace std; + + +/// Differential Array +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int minMoves(vector& nums, int limit) { + + vector diff(limit * 2 + 2, 0); + + int n = nums.size(); + for(int i = 0; i < n / 2; i ++){ + int A = nums[i], B = nums[n - 1 - i]; + + int l = 2, r = 2 * limit; + diff[l] += 2, diff[r + 1] -= 2; + + l = 1 + min(A, B), r = limit + max(A, B); + diff[l] += -1, diff[r + 1] -= -1; + + l = A + B, r = A + B; + diff[l] += -1, diff[r + 1] -= -1; + } + + int res = n, sum = 0; + for(int i = 2; i <= 2 * limit; i ++){ + sum += diff[i]; + res = min(res, sum); + } + return res; + } +}; + + +int main() { + + vector nums1 = {1, 2, 4, 3}; + cout << Solution().minMoves(nums1, 4) << endl; + // 1 + + vector nums2 = {1, 2, 2, 1}; + cout << Solution().minMoves(nums2, 2) << endl; + // 2 + + vector nums3 = {1, 2, 1, 2}; + cout << Solution().minMoves(nums3, 2) << endl; + // 0 + + vector nums4 = {3,1,2,1,2,3,3,1,2,3,2,2,1,2,3,3,3,1,1,2,3,2,1,1,2,3,3,3,1,3,3,1,1,2,2,2,2,2,1,3,1,2,2,2}; + cout << Solution().minMoves(nums4, 3) << endl; + // 13 + + return 0; +} \ No newline at end of file diff --git a/1501-2000/1675-Minimize-Deviation-in-Array/cpp-1675/CMakeLists.txt b/1501-2000/1675-Minimize-Deviation-in-Array/cpp-1675/CMakeLists.txt new file mode 100644 index 00000000..0dad4edf --- /dev/null +++ b/1501-2000/1675-Minimize-Deviation-in-Array/cpp-1675/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main3.cpp) \ No newline at end of file diff --git a/1501-2000/1675-Minimize-Deviation-in-Array/cpp-1675/main.cpp b/1501-2000/1675-Minimize-Deviation-in-Array/cpp-1675/main.cpp new file mode 100644 index 00000000..da3e536b --- /dev/null +++ b/1501-2000/1675-Minimize-Deviation-in-Array/cpp-1675/main.cpp @@ -0,0 +1,86 @@ +/// Source : https://leetcode.com/problems/minimum-moves-to-make-array-complementary/ +/// Author : liuyubobobo +/// Time : 2020-11-30 + +#include +#include +#include + +using namespace std; + + +/// Min Heap for n Pointers +/// Time Complexity: O(nlog(max_num) * logn) +/// Space Complexity: O(n) +class Solution { +public: + int minimumDeviation(vector& nums) { + + int n = nums.size(); + + vector> possible(n); + for(int i = 0; i < n; i ++){ + if(nums[i] % 2 == 0){ + while (nums[i] % 2 == 0) possible[i].push_back(nums[i]), nums[i] /= 2; + possible[i].push_back(nums[i]); + } + else{ + possible[i].push_back(nums[i]); + possible[i].push_back(nums[i] * 2); + } + + sort(possible[i].begin(), possible[i].end()); + } + + vector next(n, 0); + priority_queue, vector>, greater>> pq; + int curmax = 0; + for(int i = 0; i < n; i ++) + pq.push({possible[i][0], i}), curmax = max(curmax, possible[i][0]); + + int res = INT_MAX; + while(true){ + res = min(res, curmax - pq.top().first); + + int index = pq.top().second; + pq.pop(); + + next[index] ++; + if(next[index] >= possible[index].size()) break; + + pq.push({possible[index][next[index]], index}); + curmax = max(curmax, possible[index][next[index]]); + } + return res; + } +}; + + +int main() { + + vector nums1 = {1, 2, 3, 4}; + cout << Solution().minimumDeviation(nums1) << endl; + // 1 + + vector nums2 = {4,1,5,20,3}; + cout << Solution().minimumDeviation(nums2) << endl; + // 3 + + vector nums3 = {2,20,8}; + cout << Solution().minimumDeviation(nums3) << endl; + // 3 + + vector nums4 = {3,5}; + cout << Solution().minimumDeviation(nums4) << endl; + // 1 + + vector nums5 = {2, 8, 6, 1, 6}; + cout << Solution().minimumDeviation(nums5) << endl; + // 1 + + vector nums6 = {139502287,127662367,182874278,195316256,158258043,128106398,165570519,161630895,197087073,177018029,142241150,189463437,114131106,180827841,140563651,140631914,127439843,117651449,108277946,148148621,198133057,173477124,180664549,119749615,192791912,171503536,146780066,146619923,180198468,132326257,129079222,142091904,115753487,178875891,171861205,165113533,105888611,148201456,114722931,111227228,139403775,192371264,112237013,173895760,188650252,109366482,174511822,108640913,191279346,127663274,180400034,179515445,109423556,191502543,108986309,163189619,168756945,177284541,114642866,136718954,146122849,186435019,108451832,162317887,137725843,138164718,170588551,159632836,139405555,105243015,187461591,156505003,163176045,107100346,124266013,198186644,160653221,157330716,188843428,130131460,136191103,120065496,143836292,194312999,108470642,166356073,192320235,101600108,170925551,197600861,149364536,158492279,166594704,141871659,197119385,187931161,141314732,124536617,102505057,142054441,142144983,139492998,114061225,172915905,186326112,101258267,176016355,117310304,134565576,175774728,115461652,173657901,150872767,127024993,164739980,199913646,140093586,140579776,115345543,115718199,111611931,189004451,117768984,160145942,103569746,150336410,166224862,129187299,147130259,158224131,167485119,115017904,104014213,149432483,102127258,199320902,193569603,157552714,113431868,165365010,162721361,169993800,130956004,123456024,157811076,167771287,103114996,183508477,171322947,103516387,118407455,111055030,161774593,106983428,187953441,186774576,106113788,124972645,140254982,102498490,186169756,112171085,181140323,127509228,139727086,170141845,102263907,125782453,198344152,132630801,135853494,171044990,143562844,128452102,166392273,154488151,125841090,155342972,118665099,183467485,105245785,173770396,182229265,102072773,137044502,148387216,139608067,141567001,150810789,114476348,163267954,164259991,165425337,152560087,193558089,180008386,154925409,153149280,144881521,161927809,103701602,124355592,199332316,164457368,184521526,176380601,132487910,136872491,124394249,178518694,129959078,168807287,165621480,142432287,186679088,142687756,149852668,137400257,130710611,177159816,143972099,179566227,139405172,125527818,138882615,192825874,115915326,176351775,149859250,196724440,188496780,102484169,138858670,135845950,187121403,165486776,143305183,167154441,171152787,178418731,155915678,138488715,176113588,133032247,135266151,150545120,193146386,100587965,105628049,127805067,100092626,119758139,174858873,145984705,192910027,181173340,138042671,122308978,160770301,130394674,166492711,161910843,119184450,109853721,170848534,121342141,100838796,198131866,156427959,176020777,184930698,117558856,113507815,153587163,123588933,120472984,198163856,107901250,182464664,128964739,138765154,197553755,190480953,169538709,105129765,143353678,199607036,144583353,199403460,195738467,124778611,186233414,168628878,101977678,160897452,195801072,186941874,177230274,179583881,133909934,175430770,158050009,141158921,159321118,192978346,153948939,147725900,128959020,152949311,173602535,195643978,120013972,142084051,136108423,121580658,145565683,156257215,199766954,187813699,171156531,162645972,100216855,139697220,182202999,147699018,110023818,176058211,185321487,176811279,100190707,135798617,116045000,140572589,172900728,116145251,140651548,165834418,116121994,186652919,103162165,164716217,117471904,155970321,113282879,105493962,103599601,188489301,155340595,136108503,127347508,194267446}; + cout << Solution().minimumDeviation(nums6) << endl; + // 98683701 + + return 0; +} \ No newline at end of file diff --git a/1501-2000/1675-Minimize-Deviation-in-Array/cpp-1675/main2.cpp b/1501-2000/1675-Minimize-Deviation-in-Array/cpp-1675/main2.cpp new file mode 100644 index 00000000..a977d7e1 --- /dev/null +++ b/1501-2000/1675-Minimize-Deviation-in-Array/cpp-1675/main2.cpp @@ -0,0 +1,71 @@ +/// Source : https://leetcode.com/problems/minimum-moves-to-make-array-complementary/ +/// Author : liuyubobobo +/// Time : 2020-11-30 + +#include +#include +#include + +using namespace std; + + +/// Min Heap for n Pointers +/// directly on numbers +/// Time Complexity: O(nlog(max_num) * logn) +/// Space Complexity: O(n) +class Solution { +public: + int minimumDeviation(vector& nums) { + + for(int& e: nums) if(e % 2) e *= 2; + + priority_queue pq; + int curmin = INT_MAX; + for(int e: nums) + pq.push(e), curmin = min(curmin, e); + + int res = INT_MAX; + while(true){ + res = min(res, pq.top() - curmin); + + int e = pq.top(); + pq.pop(); + + if(e % 2) break; + + pq.push(e / 2); + curmin = min(curmin, e / 2); + } + return res; + } +}; + + +int main() { + + vector nums1 = {1, 2, 3, 4}; + cout << Solution().minimumDeviation(nums1) << endl; + // 1 + + vector nums2 = {4,1,5,20,3}; + cout << Solution().minimumDeviation(nums2) << endl; + // 3 + + vector nums3 = {2,20,8}; + cout << Solution().minimumDeviation(nums3) << endl; + // 3 + + vector nums4 = {3,5}; + cout << Solution().minimumDeviation(nums4) << endl; + // 1 + + vector nums5 = {2, 8, 6, 1, 6}; + cout << Solution().minimumDeviation(nums5) << endl; + // 1 + + vector nums6 = {139502287,127662367,182874278,195316256,158258043,128106398,165570519,161630895,197087073,177018029,142241150,189463437,114131106,180827841,140563651,140631914,127439843,117651449,108277946,148148621,198133057,173477124,180664549,119749615,192791912,171503536,146780066,146619923,180198468,132326257,129079222,142091904,115753487,178875891,171861205,165113533,105888611,148201456,114722931,111227228,139403775,192371264,112237013,173895760,188650252,109366482,174511822,108640913,191279346,127663274,180400034,179515445,109423556,191502543,108986309,163189619,168756945,177284541,114642866,136718954,146122849,186435019,108451832,162317887,137725843,138164718,170588551,159632836,139405555,105243015,187461591,156505003,163176045,107100346,124266013,198186644,160653221,157330716,188843428,130131460,136191103,120065496,143836292,194312999,108470642,166356073,192320235,101600108,170925551,197600861,149364536,158492279,166594704,141871659,197119385,187931161,141314732,124536617,102505057,142054441,142144983,139492998,114061225,172915905,186326112,101258267,176016355,117310304,134565576,175774728,115461652,173657901,150872767,127024993,164739980,199913646,140093586,140579776,115345543,115718199,111611931,189004451,117768984,160145942,103569746,150336410,166224862,129187299,147130259,158224131,167485119,115017904,104014213,149432483,102127258,199320902,193569603,157552714,113431868,165365010,162721361,169993800,130956004,123456024,157811076,167771287,103114996,183508477,171322947,103516387,118407455,111055030,161774593,106983428,187953441,186774576,106113788,124972645,140254982,102498490,186169756,112171085,181140323,127509228,139727086,170141845,102263907,125782453,198344152,132630801,135853494,171044990,143562844,128452102,166392273,154488151,125841090,155342972,118665099,183467485,105245785,173770396,182229265,102072773,137044502,148387216,139608067,141567001,150810789,114476348,163267954,164259991,165425337,152560087,193558089,180008386,154925409,153149280,144881521,161927809,103701602,124355592,199332316,164457368,184521526,176380601,132487910,136872491,124394249,178518694,129959078,168807287,165621480,142432287,186679088,142687756,149852668,137400257,130710611,177159816,143972099,179566227,139405172,125527818,138882615,192825874,115915326,176351775,149859250,196724440,188496780,102484169,138858670,135845950,187121403,165486776,143305183,167154441,171152787,178418731,155915678,138488715,176113588,133032247,135266151,150545120,193146386,100587965,105628049,127805067,100092626,119758139,174858873,145984705,192910027,181173340,138042671,122308978,160770301,130394674,166492711,161910843,119184450,109853721,170848534,121342141,100838796,198131866,156427959,176020777,184930698,117558856,113507815,153587163,123588933,120472984,198163856,107901250,182464664,128964739,138765154,197553755,190480953,169538709,105129765,143353678,199607036,144583353,199403460,195738467,124778611,186233414,168628878,101977678,160897452,195801072,186941874,177230274,179583881,133909934,175430770,158050009,141158921,159321118,192978346,153948939,147725900,128959020,152949311,173602535,195643978,120013972,142084051,136108423,121580658,145565683,156257215,199766954,187813699,171156531,162645972,100216855,139697220,182202999,147699018,110023818,176058211,185321487,176811279,100190707,135798617,116045000,140572589,172900728,116145251,140651548,165834418,116121994,186652919,103162165,164716217,117471904,155970321,113282879,105493962,103599601,188489301,155340595,136108503,127347508,194267446}; + cout << Solution().minimumDeviation(nums6) << endl; + // 98683701 + + return 0; +} \ No newline at end of file diff --git a/1501-2000/1675-Minimize-Deviation-in-Array/cpp-1675/main3.cpp b/1501-2000/1675-Minimize-Deviation-in-Array/cpp-1675/main3.cpp new file mode 100644 index 00000000..3dc2c3c9 --- /dev/null +++ b/1501-2000/1675-Minimize-Deviation-in-Array/cpp-1675/main3.cpp @@ -0,0 +1,81 @@ +/// Source : https://leetcode.com/problems/minimum-moves-to-make-array-complementary/ +/// Author : liuyubobobo +/// Time : 2020-11-30 + +#include +#include +#include + +using namespace std; + + +/// Sliding Window +/// Time Complexity: O(KlogK) where K = nlog(max_num) +/// Space Complexity: O(K) +class Solution { +public: + int minimumDeviation(vector& nums) { + + int n = nums.size(); + + vector> data; + for(int i = 0; i < n; i ++) + if(nums[i] % 2) + data.push_back({nums[i], i}), data.push_back({nums[i] * 2, i}); + else{ + while(nums[i] % 2 == 0) data.push_back({nums[i], i}), nums[i] /= 2; + data.push_back({nums[i], i}); + } + + sort(data.begin(), data.end()); + + vector f(n, 0); + int cnt = 0, l = 0, r = -1, res = INT_MAX; + while(l < data.size()){ + + if(cnt == n){ + res = min(res, data[r].first - data[l].first); + f[data[l].second] --; + if(f[data[l].second] == 0) cnt --; + l ++; + } + else if(r + 1 < data.size()){ + r ++; + if(f[data[r].second] == 0) cnt ++; + f[data[r].second] ++; + } + else break; + } + return res; + } +}; + + +int main() { + + vector nums1 = {1, 2, 3, 4}; + cout << Solution().minimumDeviation(nums1) << endl; + // 1 + + vector nums2 = {4,1,5,20,3}; + cout << Solution().minimumDeviation(nums2) << endl; + // 3 + + vector nums3 = {2,20,8}; + cout << Solution().minimumDeviation(nums3) << endl; + // 3 + + vector nums4 = {3,5}; + cout << Solution().minimumDeviation(nums4) << endl; + // 1 + + vector nums5 = {2, 8, 6, 1, 6}; + cout << Solution().minimumDeviation(nums5) << endl; + // 1 + + vector nums6 = {139502287,127662367,182874278,195316256,158258043,128106398,165570519,161630895,197087073,177018029,142241150,189463437,114131106,180827841,140563651,140631914,127439843,117651449,108277946,148148621,198133057,173477124,180664549,119749615,192791912,171503536,146780066,146619923,180198468,132326257,129079222,142091904,115753487,178875891,171861205,165113533,105888611,148201456,114722931,111227228,139403775,192371264,112237013,173895760,188650252,109366482,174511822,108640913,191279346,127663274,180400034,179515445,109423556,191502543,108986309,163189619,168756945,177284541,114642866,136718954,146122849,186435019,108451832,162317887,137725843,138164718,170588551,159632836,139405555,105243015,187461591,156505003,163176045,107100346,124266013,198186644,160653221,157330716,188843428,130131460,136191103,120065496,143836292,194312999,108470642,166356073,192320235,101600108,170925551,197600861,149364536,158492279,166594704,141871659,197119385,187931161,141314732,124536617,102505057,142054441,142144983,139492998,114061225,172915905,186326112,101258267,176016355,117310304,134565576,175774728,115461652,173657901,150872767,127024993,164739980,199913646,140093586,140579776,115345543,115718199,111611931,189004451,117768984,160145942,103569746,150336410,166224862,129187299,147130259,158224131,167485119,115017904,104014213,149432483,102127258,199320902,193569603,157552714,113431868,165365010,162721361,169993800,130956004,123456024,157811076,167771287,103114996,183508477,171322947,103516387,118407455,111055030,161774593,106983428,187953441,186774576,106113788,124972645,140254982,102498490,186169756,112171085,181140323,127509228,139727086,170141845,102263907,125782453,198344152,132630801,135853494,171044990,143562844,128452102,166392273,154488151,125841090,155342972,118665099,183467485,105245785,173770396,182229265,102072773,137044502,148387216,139608067,141567001,150810789,114476348,163267954,164259991,165425337,152560087,193558089,180008386,154925409,153149280,144881521,161927809,103701602,124355592,199332316,164457368,184521526,176380601,132487910,136872491,124394249,178518694,129959078,168807287,165621480,142432287,186679088,142687756,149852668,137400257,130710611,177159816,143972099,179566227,139405172,125527818,138882615,192825874,115915326,176351775,149859250,196724440,188496780,102484169,138858670,135845950,187121403,165486776,143305183,167154441,171152787,178418731,155915678,138488715,176113588,133032247,135266151,150545120,193146386,100587965,105628049,127805067,100092626,119758139,174858873,145984705,192910027,181173340,138042671,122308978,160770301,130394674,166492711,161910843,119184450,109853721,170848534,121342141,100838796,198131866,156427959,176020777,184930698,117558856,113507815,153587163,123588933,120472984,198163856,107901250,182464664,128964739,138765154,197553755,190480953,169538709,105129765,143353678,199607036,144583353,199403460,195738467,124778611,186233414,168628878,101977678,160897452,195801072,186941874,177230274,179583881,133909934,175430770,158050009,141158921,159321118,192978346,153948939,147725900,128959020,152949311,173602535,195643978,120013972,142084051,136108423,121580658,145565683,156257215,199766954,187813699,171156531,162645972,100216855,139697220,182202999,147699018,110023818,176058211,185321487,176811279,100190707,135798617,116045000,140572589,172900728,116145251,140651548,165834418,116121994,186652919,103162165,164716217,117471904,155970321,113282879,105493962,103599601,188489301,155340595,136108503,127347508,194267446}; + cout << Solution().minimumDeviation(nums6) << endl; + // 98683701 + + return 0; +} \ No newline at end of file diff --git a/1501-2000/1676-Lowest-Common-Ancestor-of-a-Binary-Tree-IV/cpp-1676/CMakeLists.txt b/1501-2000/1676-Lowest-Common-Ancestor-of-a-Binary-Tree-IV/cpp-1676/CMakeLists.txt new file mode 100644 index 00000000..16f7565b --- /dev/null +++ b/1501-2000/1676-Lowest-Common-Ancestor-of-a-Binary-Tree-IV/cpp-1676/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1676) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1676 main.cpp) \ No newline at end of file diff --git a/1501-2000/1676-Lowest-Common-Ancestor-of-a-Binary-Tree-IV/cpp-1676/main.cpp b/1501-2000/1676-Lowest-Common-Ancestor-of-a-Binary-Tree-IV/cpp-1676/main.cpp new file mode 100644 index 00000000..1580e2e5 --- /dev/null +++ b/1501-2000/1676-Lowest-Common-Ancestor-of-a-Binary-Tree-IV/cpp-1676/main.cpp @@ -0,0 +1,58 @@ +/// Source : https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree-iv/ +/// Author : liuyubobobo +/// Time : 2020-12-02 + +#include +#include +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(h + |nodes|) + +/// 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* lowestCommonAncestor(TreeNode* root, vector &nodes) { + + unordered_set target(nodes.begin(), nodes.end()); + + TreeNode* res = NULL; + dfs(root, 0, target, res); + return res; + } + +private: + int dfs(TreeNode* node, int depth, const unordered_set& set, + TreeNode*& res){ + + if(!node) return 0; + + int cnt = set.count(node); + if(node->left) cnt += dfs(node->left, depth + 1, set, res); + if(node->right) cnt += dfs(node->right, depth + 1, set, res); + + if(cnt == set.size() && !res) res = node; + cout << node->val << " " << cnt << endl; + return cnt; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1678-Goal-Parser-Interpretation/cpp-1678/CMakeLists.txt b/1501-2000/1678-Goal-Parser-Interpretation/cpp-1678/CMakeLists.txt new file mode 100644 index 00000000..d5d5e4ff --- /dev/null +++ b/1501-2000/1678-Goal-Parser-Interpretation/cpp-1678/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1501-2000/1678-Goal-Parser-Interpretation/cpp-1678/main.cpp b/1501-2000/1678-Goal-Parser-Interpretation/cpp-1678/main.cpp new file mode 100644 index 00000000..bae70080 --- /dev/null +++ b/1501-2000/1678-Goal-Parser-Interpretation/cpp-1678/main.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/goal-parser-interpretation/ +/// Author : liuyubobobo +/// Time : 2020-12-05 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + string interpret(string command) { + + string res = ""; + for(int i = 0; i < command.size(); i ++) + if(command[i] == 'G') res += 'G'; + else if(command[i + 1] == ')') res += 'o', i ++; + else res += "al", i += 3; + return res; + } +}; + + +int main() { + + cout << Solution().interpret("G()()()()(al)") << endl; + // Gooooal + + cout << Solution().interpret("(al)G(al)()()G") << endl; + // alGalooG + + return 0; +} diff --git a/1501-2000/1679-Max-Number-of-K-Sum-Pairs/cpp-1679/CMakeLists.txt b/1501-2000/1679-Max-Number-of-K-Sum-Pairs/cpp-1679/CMakeLists.txt new file mode 100644 index 00000000..b103b001 --- /dev/null +++ b/1501-2000/1679-Max-Number-of-K-Sum-Pairs/cpp-1679/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main2.cpp) \ No newline at end of file diff --git a/1501-2000/1679-Max-Number-of-K-Sum-Pairs/cpp-1679/main.cpp b/1501-2000/1679-Max-Number-of-K-Sum-Pairs/cpp-1679/main.cpp new file mode 100644 index 00000000..a8705c05 --- /dev/null +++ b/1501-2000/1679-Max-Number-of-K-Sum-Pairs/cpp-1679/main.cpp @@ -0,0 +1,55 @@ +/// Source : https://leetcode.com/problems/max-number-of-k-sum-pairs/ +/// Author : liuyubobobo +/// Time : 2020-12-05 + +#include +#include +#include +#include + +using namespace std; + + +/// Using HashMap - Two Pass +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int maxOperations(vector& nums, int k) { + + unordered_map f; + unordered_set set; + + for(int e: nums){ + f[e] ++; + set.insert(e); + } + + int res = 0; + for(int e: set) + if(f.count(k - e)){ + if(e != k - e){ + res += min(f[e], f[k - e]); + f.erase(e), f.erase(k - e); + } + else{ + res += f[e] / 2; + f.erase(e); + } + } + return res; + } +}; + +int main() { + + vector nums1 = {1, 2, 3, 4}; + cout << Solution().maxOperations(nums1, 5) << endl; + // 2 + + vector nums2 = {3,1,3,4,3}; + cout << Solution().maxOperations(nums2, 6) << endl; + // 1 + + return 0; +} \ No newline at end of file diff --git a/1501-2000/1679-Max-Number-of-K-Sum-Pairs/cpp-1679/main2.cpp b/1501-2000/1679-Max-Number-of-K-Sum-Pairs/cpp-1679/main2.cpp new file mode 100644 index 00000000..51084e05 --- /dev/null +++ b/1501-2000/1679-Max-Number-of-K-Sum-Pairs/cpp-1679/main2.cpp @@ -0,0 +1,45 @@ +/// Source : https://leetcode.com/problems/max-number-of-k-sum-pairs/ +/// Author : liuyubobobo +/// Time : 2020-12-05 + +#include +#include +#include + +using namespace std; + + +/// Using HashMap - Single Pass +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int maxOperations(vector& nums, int k) { + + unordered_map f; + + int res = 0; + for(int e: nums){ + if(f[k - e] > 0){ + res ++; + f[k - e] --; + } + else f[e] ++; + } + return res; + } +}; + + +int main() { + + vector nums1 = {1, 2, 3, 4}; + cout << Solution().maxOperations(nums1, 5) << endl; + // 2 + + vector nums2 = {3,1,3,4,3}; + cout << Solution().maxOperations(nums2, 6) << endl; + // 1 + + return 0; +} \ No newline at end of file diff --git a/1501-2000/1680-Concatenation-of-Consecutive-Binary-Numbers/cpp-1680/CMakeLists.txt b/1501-2000/1680-Concatenation-of-Consecutive-Binary-Numbers/cpp-1680/CMakeLists.txt new file mode 100644 index 00000000..7e530eb8 --- /dev/null +++ b/1501-2000/1680-Concatenation-of-Consecutive-Binary-Numbers/cpp-1680/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main4.cpp) \ No newline at end of file diff --git a/1501-2000/1680-Concatenation-of-Consecutive-Binary-Numbers/cpp-1680/main.cpp b/1501-2000/1680-Concatenation-of-Consecutive-Binary-Numbers/cpp-1680/main.cpp new file mode 100644 index 00000000..9f93ac31 --- /dev/null +++ b/1501-2000/1680-Concatenation-of-Consecutive-Binary-Numbers/cpp-1680/main.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/concatenation-of-consecutive-binary-numbers/ +/// Author : liuyubobobo +/// Time : 2020-12-05 + +#include +#include + +using namespace std; + + +/// Binary Search to get the bit length +/// Time Complexiity: O(nlogn) +/// Space Complexity: O(logn) +class Solution { + +private: + const long long MOD = 1e9 + 7; + +public: + int concatenatedBinary(int n) { + + vector pow2 = {1, 2}; + for(int i = 2; i < 31; i ++) + pow2.push_back(pow2.back() * 2); + + long long cur = 0; + for(int i = 1; i <= n; i ++){ + vector::iterator iter = lower_bound(pow2.begin(), pow2.end(), i); + if(*iter != i) iter --; + int l = iter - pow2.begin() + 1; + cur = (cur * pow2[l] + i) % MOD; + } + return cur; + } +}; + + +int main() { + + cout << Solution().concatenatedBinary(1) << endl; + // 1 + + cout << Solution().concatenatedBinary(3) << endl; + // 27 + + cout << Solution().concatenatedBinary(12) << endl; + // 505379714 + + cout << Solution().concatenatedBinary(26042) << endl; + // 502218269 + + return 0; +} \ No newline at end of file diff --git a/1501-2000/1680-Concatenation-of-Consecutive-Binary-Numbers/cpp-1680/main2.cpp b/1501-2000/1680-Concatenation-of-Consecutive-Binary-Numbers/cpp-1680/main2.cpp new file mode 100644 index 00000000..7477115c --- /dev/null +++ b/1501-2000/1680-Concatenation-of-Consecutive-Binary-Numbers/cpp-1680/main2.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/concatenation-of-consecutive-binary-numbers/ +/// Author : liuyubobobo +/// Time : 2020-12-05 + +#include +#include + +using namespace std; + + +/// Two Pointers to get the bit length +/// Time Complexiity: O(n) +/// Space Complexity: O(logn) +class Solution { + +private: + const long long MOD = 1e9 + 7; + +public: + int concatenatedBinary(int n) { + + vector pow2 = {1, 2}; + for(int i = 2; i < 31; i ++) + pow2.push_back(pow2.back() * 2); + + long long cur = 0; + int p = 0; + for(int i = 1; i <= n; i ++){ + if(i == pow2[p + 1]) p ++; + cur = (cur * pow2[p + 1] + i) % MOD; + } + return cur; + } +}; + + +int main() { + + cout << Solution().concatenatedBinary(1) << endl; + // 1 + + cout << Solution().concatenatedBinary(3) << endl; + // 27 + + cout << Solution().concatenatedBinary(12) << endl; + // 505379714 + + cout << Solution().concatenatedBinary(26042) << endl; + // 502218269 + + return 0; +} \ No newline at end of file diff --git a/1501-2000/1680-Concatenation-of-Consecutive-Binary-Numbers/cpp-1680/main3.cpp b/1501-2000/1680-Concatenation-of-Consecutive-Binary-Numbers/cpp-1680/main3.cpp new file mode 100644 index 00000000..74dae8ef --- /dev/null +++ b/1501-2000/1680-Concatenation-of-Consecutive-Binary-Numbers/cpp-1680/main3.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/concatenation-of-consecutive-binary-numbers/ +/// Author : liuyubobobo +/// Time : 2020-12-05 + +#include +#include + +using namespace std; + + +/// Bitwise-Operatioon to get the bit length +/// Time Complexiity: O(n) +/// Space Complexity: O(logn) +class Solution { + +private: + const long long MOD = 1e9 + 7; + +public: + int concatenatedBinary(int n) { + + vector pow2 = {1, 2}; + for(int i = 2; i < 31; i ++) + pow2.push_back(pow2.back() * 2); + + long long cur = 0; + int l = 0; + for(int i = 1; i <= n; i ++){ + if((i & (i - 1)) == 0) l ++; + cur = (cur * pow2[l] + i) % MOD; + } + return cur; + } +}; + + +int main() { + + cout << Solution().concatenatedBinary(1) << endl; + // 1 + + cout << Solution().concatenatedBinary(3) << endl; + // 27 + + cout << Solution().concatenatedBinary(12) << endl; + // 505379714 + + cout << Solution().concatenatedBinary(26042) << endl; + // 502218269 + + return 0; +} \ No newline at end of file diff --git a/1501-2000/1680-Concatenation-of-Consecutive-Binary-Numbers/cpp-1680/main4.cpp b/1501-2000/1680-Concatenation-of-Consecutive-Binary-Numbers/cpp-1680/main4.cpp new file mode 100644 index 00000000..51c9f79d --- /dev/null +++ b/1501-2000/1680-Concatenation-of-Consecutive-Binary-Numbers/cpp-1680/main4.cpp @@ -0,0 +1,45 @@ +/// Source : https://leetcode.com/problems/concatenation-of-consecutive-binary-numbers/ +/// Author : liuyubobobo +/// Time : 2020-12-05 + +#include +#include +#include + +using namespace std; + + +/// Mathematics +/// Time Complexiity: O(n) +/// Space Complexity: O(1) +class Solution { + +private: + const long long MOD = 1e9 + 7; + +public: + int concatenatedBinary(int n) { + long long cur = 0; + for(int i = 1; i <= n; i ++) + cur = (cur * (int)pow(2, floor(log2(i)) + 1) + i) % MOD; + return cur; + } +}; + + +int main() { + + cout << Solution().concatenatedBinary(1) << endl; + // 1 + + cout << Solution().concatenatedBinary(3) << endl; + // 27 + + cout << Solution().concatenatedBinary(12) << endl; + // 505379714 + + cout << Solution().concatenatedBinary(26042) << endl; + // 502218269 + + return 0; +} \ No newline at end of file diff --git a/1501-2000/1681-Minimum-Incompatibility/cpp-1681/CMakeLists.txt b/1501-2000/1681-Minimum-Incompatibility/cpp-1681/CMakeLists.txt new file mode 100644 index 00000000..a373769d --- /dev/null +++ b/1501-2000/1681-Minimum-Incompatibility/cpp-1681/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main2.cpp) \ No newline at end of file diff --git a/1501-2000/1681-Minimum-Incompatibility/cpp-1681/main.cpp b/1501-2000/1681-Minimum-Incompatibility/cpp-1681/main.cpp new file mode 100644 index 00000000..85b7c73a --- /dev/null +++ b/1501-2000/1681-Minimum-Incompatibility/cpp-1681/main.cpp @@ -0,0 +1,96 @@ +/// Source : https://leetcode.com/problems/minimum-incompatibility/ +/// Author : liuyubobobo +/// Time : 2020-12-05 + +#include +#include +#include + +using namespace std; + + +/// State Compression DP +/// Time Complexity: O(2^n * logn + 2^n * C(n, n / k)) +/// Space Complexity: O(C(n, n / k)) +class Solution { +public: + int minimumIncompatibility(vector& nums, int k) { + + int n = nums.size(); + unordered_map table; + + int sz = n / k; + for(int state = 1; state < (1 << n); state ++) + if(ones(state) == sz){ + deal(table, nums, state); + } + + vector dp(1 << n, -1); + int res = dfs(table, (1 << n) - 1, dp); + return res == INT_MAX ? -1 : res; + } + +private: + int dfs(const unordered_map& table, int state, + vector& dp){ + + if(state == 0) return 0; + if(dp[state] != -1) return dp[state]; + + int res = INT_MAX; + for(const pair& p: table) + if((state & p.first) == p.first) { + int t = dfs(table, state - p.first, dp); + if(t != INT_MAX) res = min(res, p.second + t); + } + return dp[state] = res; + } + + void deal(unordered_map& table, const vector& nums, int state){ + + vector v; + int index = 0, x = state; + while(x){ + if(x & 1) v.push_back(nums[index]); + index ++; + x >>= 1; + } + + sort(v.begin(), v.end()); + for(int i = 1; i < v.size(); i ++) + if(v[i - 1] == v[i]) return; + + table[state] = v.back() - v[0]; + } + + int ones(int x){ + int res = 0; + while(x){ + x = x & (x - 1); + res ++; + } + return res; + } +}; + + +int main() { + + vector nums1 = {1, 2, 1, 4}; + cout << Solution().minimumIncompatibility(nums1, 2) << endl; + // 4 + + vector nums2 = {6,3,8,1,3,1,2,2}; + cout << Solution().minimumIncompatibility(nums2, 4) << endl; + // 6 + + vector nums3 = {5,3,3,6,3,3}; + cout << Solution().minimumIncompatibility(nums3, 3) << endl; + // -1 + + vector nums4 = {1}; + cout << Solution().minimumIncompatibility(nums4, 1) << endl; + // 0 + + return 0; +} \ No newline at end of file diff --git a/1501-2000/1681-Minimum-Incompatibility/cpp-1681/main2.cpp b/1501-2000/1681-Minimum-Incompatibility/cpp-1681/main2.cpp new file mode 100644 index 00000000..e075108f --- /dev/null +++ b/1501-2000/1681-Minimum-Incompatibility/cpp-1681/main2.cpp @@ -0,0 +1,87 @@ +/// Source : https://leetcode.com/problems/minimum-incompatibility/ +/// Author : liuyubobobo +/// Time : 2020-12-05 + +#include +#include +#include + +using namespace std; + + +/// State Compression DP +/// Using __builtin_popcount +/// Time Complexity: O(2^n + 2^n * C(n, n / k)) +/// Space Complexity: O(C(n, n / k)) +class Solution { +public: + int minimumIncompatibility(vector& nums, int k) { + + int n = nums.size(); + unordered_map table; + + int sz = n / k; + for(int state = 1; state < (1 << n); state ++) + if(__builtin_popcount(state) == sz) + deal(table, nums, state); + + vector dp(1 << n, -1); + int res = dfs(table, (1 << n) - 1, dp); + return res == INT_MAX ? -1 : res; + } + +private: + int dfs(const unordered_map& table, int state, + vector& dp){ + + if(state == 0) return 0; + if(dp[state] != -1) return dp[state]; + + int res = INT_MAX; + for(const pair& p: table) + if((state & p.first) == p.first) { + int t = dfs(table, state - p.first, dp); + if(t != INT_MAX) res = min(res, p.second + t); + } + return dp[state] = res; + } + + void deal(unordered_map& table, const vector& nums, int state){ + + vector v; + int index = 0, x = state; + while(x){ + if(x & 1) v.push_back(nums[index]); + index ++; + x >>= 1; + } + + sort(v.begin(), v.end()); + for(int i = 1; i < v.size(); i ++) + if(v[i - 1] == v[i]) return; + + table[state] = v.back() - v[0]; + } +}; + + +int main() { + + vector nums1 = {1, 2, 1, 4}; + cout << Solution().minimumIncompatibility(nums1, 2) << endl; + // 4 + + vector nums2 = {6,3,8,1,3,1,2,2}; + cout << Solution().minimumIncompatibility(nums2, 4) << endl; + // 6 + + vector nums3 = {5,3,3,6,3,3}; + cout << Solution().minimumIncompatibility(nums3, 3) << endl; + // -1 + + vector nums4 = {1}; + cout << Solution().minimumIncompatibility(nums4, 1) << endl; + // 0 + + return 0; +} \ No newline at end of file diff --git a/1501-2000/1682-Longest-Palindromic-Subsequence-II/cpp-1682/CMakeLists.txt b/1501-2000/1682-Longest-Palindromic-Subsequence-II/cpp-1682/CMakeLists.txt new file mode 100644 index 00000000..81b40980 --- /dev/null +++ b/1501-2000/1682-Longest-Palindromic-Subsequence-II/cpp-1682/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1682) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1682 main.cpp) \ No newline at end of file diff --git a/1501-2000/1682-Longest-Palindromic-Subsequence-II/cpp-1682/main.cpp b/1501-2000/1682-Longest-Palindromic-Subsequence-II/cpp-1682/main.cpp new file mode 100644 index 00000000..b07674de --- /dev/null +++ b/1501-2000/1682-Longest-Palindromic-Subsequence-II/cpp-1682/main.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/longest-palindromic-subsequence-ii/ +/// Author : liuyubobobo +/// Time : 2020-12-12 + +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(n^2) +/// Space Coomplexity: O(n^2) +class Solution { +public: + int longestPalindromeSubseq(string s) { + + int n = s.size(); + vector>> dp(n, vector>(n, vector(27, -1))); + + int res = 0; + for(int i = 0; i < n; i ++) + res = max(res, dfs(s, i, n - 1, 0, dp)); + return res; + } + +private: + int dfs(const string& s, int l, int r, int p, + vector>>& dp){ + + if(l >= r) return 0; + if(dp[l][r][p] != -1) return dp[l][r][p]; + + int res = dfs(s, l + 1, r, p, dp); + if(s[l] - 'a' + 1 != p) + for(int i = r; i > l; i --) + if(s[i] == s[l]) res = max(res, 2 + dfs(s, l + 1, i - 1, s[l] - 'a' + 1, dp)); + return dp[l][r][p] = res; + } +}; + + +int main() { + + cout << Solution().longestPalindromeSubseq("bbabab") << endl; + // 4 + + cout << Solution().longestPalindromeSubseq("dcbccacdb") << endl; + // 4 + + return 0; +} diff --git a/1501-2000/1684-Count-the-Number-of-Consistent-Strings/cpp-1684/CMakeLists.txt b/1501-2000/1684-Count-the-Number-of-Consistent-Strings/cpp-1684/CMakeLists.txt new file mode 100644 index 00000000..9b4fc9c9 --- /dev/null +++ b/1501-2000/1684-Count-the-Number-of-Consistent-Strings/cpp-1684/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1684) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1684 main.cpp) \ No newline at end of file diff --git a/1501-2000/1684-Count-the-Number-of-Consistent-Strings/cpp-1684/main.cpp b/1501-2000/1684-Count-the-Number-of-Consistent-Strings/cpp-1684/main.cpp new file mode 100644 index 00000000..9e50402e --- /dev/null +++ b/1501-2000/1684-Count-the-Number-of-Consistent-Strings/cpp-1684/main.cpp @@ -0,0 +1,43 @@ +/// Source : https://leetcode.com/problems/count-the-number-of-consistent-strings/ +/// Author : liuyubobobo +/// Time : 2020-12-12 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n * len) +/// Space Complexity: O(1) +class Solution { +public: + int countConsistentStrings(string allowed, vector& words) { + + vector ok(26, false); + for(char c: allowed) ok[c - 'a'] = true; + + int res = 0; + for(const string& s: words){ + + for(char c: s) + if(!ok[c - 'a']){ + res ++; + break; + } + } + return words.size() - res; + } +}; + + +int main() { + + string allowed1 = "ab"; + vector words1 = {"ad","bd","aaab","baa","badab"}; + cout << Solution().countConsistentStrings(allowed1, words1) << endl; + // 2 + + return 0; +} diff --git a/1501-2000/1685-Sum-of-Absolute-Differences-in-a-Sorted-Array/cpp-1685/CMakeLists.txt b/1501-2000/1685-Sum-of-Absolute-Differences-in-a-Sorted-Array/cpp-1685/CMakeLists.txt new file mode 100644 index 00000000..d3fea2a9 --- /dev/null +++ b/1501-2000/1685-Sum-of-Absolute-Differences-in-a-Sorted-Array/cpp-1685/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1685) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1685 main.cpp) \ No newline at end of file diff --git a/1501-2000/1685-Sum-of-Absolute-Differences-in-a-Sorted-Array/cpp-1685/main.cpp b/1501-2000/1685-Sum-of-Absolute-Differences-in-a-Sorted-Array/cpp-1685/main.cpp new file mode 100644 index 00000000..f29641d1 --- /dev/null +++ b/1501-2000/1685-Sum-of-Absolute-Differences-in-a-Sorted-Array/cpp-1685/main.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/sum-of-absolute-differences-in-a-sorted-array/ +/// Author : liuyubobobo +/// Time : 2020-12-12 + +#include +#include + +using namespace std; + + +/// Mathematics +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + vector getSumAbsoluteDifferences(vector& nums) { + + int n = nums.size(); + + int front = 0, tail = 0; + for(int i = 1; i < n; i ++) tail += nums[i] - nums[0]; + + vector res(n, tail); + for(int i = 1; i < nums.size(); i ++){ + int diff = nums[i] - nums[i - 1]; + tail -= (nums.size() - i) * diff; + front += i * diff; + res[i] = front + tail; + } + return res; + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << " "; cout << endl; +} + +int main() { + + vector nums1 = {2, 3, 5}; + print_vec(Solution().getSumAbsoluteDifferences(nums1)); + // 4 3 5 + + vector nums2 = {1,4,6,8,10}; + print_vec(Solution().getSumAbsoluteDifferences(nums2)); + // 24,15,13,15,21 + + return 0; +} diff --git a/1501-2000/1686-Stone-Game-VI/cpp-1686/CMakeLists.txt b/1501-2000/1686-Stone-Game-VI/cpp-1686/CMakeLists.txt new file mode 100644 index 00000000..335ae2f4 --- /dev/null +++ b/1501-2000/1686-Stone-Game-VI/cpp-1686/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1686) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1686 main.cpp) \ No newline at end of file diff --git a/1501-2000/1686-Stone-Game-VI/cpp-1686/main.cpp b/1501-2000/1686-Stone-Game-VI/cpp-1686/main.cpp new file mode 100644 index 00000000..ddf9e302 --- /dev/null +++ b/1501-2000/1686-Stone-Game-VI/cpp-1686/main.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/stone-game-vi/ +/// Author : liuyubobobo +/// Time : 2020-12-13 + +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + int stoneGameVI(vector& aliceValues, vector& bobValues) { + + int n = aliceValues.size(); + + vector> data(n); + for(int i = 0; i < n; i ++) + data[i] = {aliceValues[i] + bobValues[i], aliceValues[i], bobValues[i]}; + + sort(data.begin(), data.end(), greater>()); + + int ascore = 0, bscore = 0; + for(int i = 0; i < n; i ++) + if(i % 2 == 0) ascore += data[i][1]; + else bscore += data[i][2]; + + return ascore == bscore ? 0 : ascore > bscore ? 1 : -1; + } +}; + + +int main() { + + vector alice1 = {1, 3}, bob1 = {2, 1}; + cout << Solution().stoneGameVI(alice1, bob1) << endl; + // 1 + + vector alice2 = {1, 2}, bob2 = {3, 1}; + cout << Solution().stoneGameVI(alice2, bob2) << endl; + // 0 + + return 0; +} diff --git a/1501-2000/1687-Delivering-Boxes-from-Storage-to-Ports/cpp-1687/CMakeLists.txt b/1501-2000/1687-Delivering-Boxes-from-Storage-to-Ports/cpp-1687/CMakeLists.txt new file mode 100644 index 00000000..eed738d0 --- /dev/null +++ b/1501-2000/1687-Delivering-Boxes-from-Storage-to-Ports/cpp-1687/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1687) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1687 main.cpp) \ No newline at end of file diff --git a/1501-2000/1687-Delivering-Boxes-from-Storage-to-Ports/cpp-1687/main.cpp b/1501-2000/1687-Delivering-Boxes-from-Storage-to-Ports/cpp-1687/main.cpp new file mode 100644 index 00000000..7e836d62 --- /dev/null +++ b/1501-2000/1687-Delivering-Boxes-from-Storage-to-Ports/cpp-1687/main.cpp @@ -0,0 +1,80 @@ +/// Source : https://leetcode.com/problems/delivering-boxes-from-storage-to-ports/ +/// Author : liuyubobobo +/// Time : 2021-02-14 + +#include +#include + +using namespace std; + + +/// Greedy + Memory Search +/// Time Complexity: O(n)? +/// Space Complexity: O(n) +class Solution { + +private: + int maxBoxes, maxWeight; + +public: + int boxDelivering(vector>& boxes, int portsCount, int maxBoxes, int maxWeight) { + + this->maxBoxes = maxBoxes; + this->maxWeight = maxWeight; + + vector dp(boxes.size(), -1); + return dfs(boxes, 0, dp); + } + +private: + int dfs(const vector>& boxes, int index, vector& dp){ + + if(index == boxes.size()) return 0; + if(dp[index] != -1) return dp[index]; + + int curboxes = 0, curweight = 0, tres = 0; + int prevport = -1, previndex = index, prevres = -1, i; + for(i = index; i < boxes.size(); i ++){ + + curboxes += 1; + curweight += boxes[i][1]; + + if(curboxes > maxBoxes || curweight > maxWeight) + break; + + if(boxes[i][0] != prevport){ + prevport = boxes[i][0]; + previndex = i; + prevres = tres; + tres += 1; + } + } + + int res = tres + 1 + dfs(boxes,i, dp); + if(previndex != index) + res = min(res, prevres + 1 + dfs(boxes, previndex, dp)); + return dp[index] = res; + } +}; + + +int main() { + + vector> boxes1 = {{1, 1}, {2, 1}, {1, 1}}; + cout << Solution().boxDelivering(boxes1, 2, 3, 3) << endl; + // 4 + + vector> boxes2 = {{1, 2}, {3, 3}, {3, 1}, {3, 1}, {2, 4}}; + cout << Solution().boxDelivering(boxes2, 3, 3, 6) << endl; + // 6 + + vector> boxes3 = {{1, 4}, {1, 2}, {2, 1}, {2, 1}, {3, 2}, {3, 4}}; + cout << Solution().boxDelivering(boxes3, 3, 6, 7) << endl; + // 6 + + vector> boxes4 = {{2, 4}, {2, 5}, {3, 1}, {3, 2}, {3, 7}, {3, 1}, {4, 4}, {1, 3}, {5, 2}}; + cout << Solution().boxDelivering(boxes4, 5, 5, 7) << endl; + // 14 + + return 0; +} diff --git a/1501-2000/1688-Count-of-Matches-in-Tournament/cpp-1688/CMakeLists.txt b/1501-2000/1688-Count-of-Matches-in-Tournament/cpp-1688/CMakeLists.txt new file mode 100644 index 00000000..ec9e7c4c --- /dev/null +++ b/1501-2000/1688-Count-of-Matches-in-Tournament/cpp-1688/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main2.cpp) \ No newline at end of file diff --git a/1501-2000/1688-Count-of-Matches-in-Tournament/cpp-1688/main.cpp b/1501-2000/1688-Count-of-Matches-in-Tournament/cpp-1688/main.cpp new file mode 100644 index 00000000..7b01f3b5 --- /dev/null +++ b/1501-2000/1688-Count-of-Matches-in-Tournament/cpp-1688/main.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/count-of-matches-in-tournament/ +/// Author : liuyubobobo +/// Time : 2020-12-12 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(logn) +/// Space Complexity: O(1) +class Solution { +public: + int numberOfMatches(int n) { + + int res = 0; + while(n > 1){ + if(n % 2){ + res += (n - 1) / 2; + n = (n - 1) / 2 + 1; + } + else{ + res += n / 2; + n /= 2; + } + } + return res; + } +}; + + +int main() { + + cout << Solution().numberOfMatches(7) << endl; + // 6 + + return 0; +} diff --git a/1501-2000/1688-Count-of-Matches-in-Tournament/cpp-1688/main2.cpp b/1501-2000/1688-Count-of-Matches-in-Tournament/cpp-1688/main2.cpp new file mode 100644 index 00000000..66e503c9 --- /dev/null +++ b/1501-2000/1688-Count-of-Matches-in-Tournament/cpp-1688/main2.cpp @@ -0,0 +1,29 @@ +/// Source : https://leetcode.com/problems/count-of-matches-in-tournament/ +/// Author : liuyubobobo +/// Time : 2020-12-12 + +#include +#include + +using namespace std; + + +/// Mathematics +/// Time Complexity: O(logn) +/// Space Complexity: O(1) +class Solution { +public: + int numberOfMatches(int n) { + + return n - 1; + } +}; + + +int main() { + + cout << Solution().numberOfMatches(7) << endl; + // 6 + + return 0; +} diff --git a/1501-2000/1689-Partitioning-Into-Minimum-Number-Of-Deci-Binary-Numbers/cpp-1689/CMakeLists.txt b/1501-2000/1689-Partitioning-Into-Minimum-Number-Of-Deci-Binary-Numbers/cpp-1689/CMakeLists.txt new file mode 100644 index 00000000..81ad8b42 --- /dev/null +++ b/1501-2000/1689-Partitioning-Into-Minimum-Number-Of-Deci-Binary-Numbers/cpp-1689/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1501-2000/1689-Partitioning-Into-Minimum-Number-Of-Deci-Binary-Numbers/cpp-1689/main.cpp b/1501-2000/1689-Partitioning-Into-Minimum-Number-Of-Deci-Binary-Numbers/cpp-1689/main.cpp new file mode 100644 index 00000000..2b8dc364 --- /dev/null +++ b/1501-2000/1689-Partitioning-Into-Minimum-Number-Of-Deci-Binary-Numbers/cpp-1689/main.cpp @@ -0,0 +1,24 @@ +/// Source : https://leetcode.com/problems/partitioning-into-minimum-number-of-deci-binary-numbers/ +/// Author : liuyubobobo +/// Time : 2020-12-12 + +#include +#include + +using namespace std; + + +/// Mathematics +class Solution { +public: + int minPartitions(string n) { + + return *max_element(n.begin(), n.end()) - '0'; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1690-Stone-Game-VII/cpp-1690/CMakeLists.txt b/1501-2000/1690-Stone-Game-VII/cpp-1690/CMakeLists.txt new file mode 100644 index 00000000..ce73aee9 --- /dev/null +++ b/1501-2000/1690-Stone-Game-VII/cpp-1690/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1501-2000/1690-Stone-Game-VII/cpp-1690/main.cpp b/1501-2000/1690-Stone-Game-VII/cpp-1690/main.cpp new file mode 100644 index 00000000..db2a16a7 --- /dev/null +++ b/1501-2000/1690-Stone-Game-VII/cpp-1690/main.cpp @@ -0,0 +1,51 @@ +/// Source : https://leetcode.com/problems/stone-game-vii/ +/// Author : liuyubobobo +/// Time : 2020-12-12 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(n^2) +/// Space Complexity: O(n^2) +class Solution { + +public: + int stoneGameVII(vector& stones) { + + int n = stones.size(); + vector presum(n + 1, 0); + for(int i = 0; i < n; i ++) + presum[i + 1] = presum[i] + stones[i]; + + vector>> dp(2, vector>(n, vector(n, 0))); + + for(int sz = 2; sz <= n; sz ++) + for(int l = 0; l + sz - 1 < n; l ++){ + + int r = l + sz - 1; + dp[0][l][r] = max(presum[r + 1] - presum[l + 1] + dp[1][l + 1][r], + presum[r] - presum[l] + dp[1][l][r - 1]); + dp[1][l][r] = min(- (presum[r + 1] - presum[l + 1]) + dp[0][l + 1][r], + - (presum[r] - presum[l]) + dp[0][l][r - 1]); + } + return dp[0][0][n - 1]; + } +}; + + +int main() { + + vector stones1 = {5,3,1,4,2}; + cout << Solution().stoneGameVII(stones1) << endl; + // 6 + + vector stones2 = {7,90,5,1,100,10,10,2}; + cout << Solution().stoneGameVII(stones2) << endl; + // 122 + + return 0; +} diff --git a/1501-2000/1691-Maximum-Height-by-Stacking-Cuboids/cpp-1691/CMakeLists.txt b/1501-2000/1691-Maximum-Height-by-Stacking-Cuboids/cpp-1691/CMakeLists.txt new file mode 100644 index 00000000..74cc3ee6 --- /dev/null +++ b/1501-2000/1691-Maximum-Height-by-Stacking-Cuboids/cpp-1691/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) \ No newline at end of file diff --git a/1501-2000/1691-Maximum-Height-by-Stacking-Cuboids/cpp-1691/main.cpp b/1501-2000/1691-Maximum-Height-by-Stacking-Cuboids/cpp-1691/main.cpp new file mode 100644 index 00000000..84c6d25b --- /dev/null +++ b/1501-2000/1691-Maximum-Height-by-Stacking-Cuboids/cpp-1691/main.cpp @@ -0,0 +1,51 @@ +/// Source : https://leetcode.com/problems/maximum-height-by-stacking-cuboids/ +/// Author : liuyubobobo +/// Time : 2020-12-13 + +#include +#include + +using namespace std; + + +/// LIS +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { +public: + int maxHeight(vector>& cuboids) { + + for(vector& cube: cuboids) + sort(cube.begin(), cube.end()); + + sort(cuboids.begin(), cuboids.end()); + + int n = cuboids.size(); + vector dp(n, cuboids[0][2]); + for(int i = 1; i < n; i ++){ + dp[i] = cuboids[i][2]; + for(int j = i - 1; j >= 0; j --) + if(cuboids[i][0] >= cuboids[j][0] && cuboids[i][1] >= cuboids[j][1] && cuboids[i][2] >= cuboids[j][2]) + dp[i] = max(dp[i], dp[j] + cuboids[i][2]); + } + return *max_element(dp.begin(), dp.end()); + } +}; + + +int main() { + + vector> cubes1 = {{50,45,20},{95,37,53},{45,23,12}}; + cout << Solution().maxHeight(cubes1) << endl; + // 190 + + vector> cubes2 = {{38,25,45},{76,35,3}}; + cout << Solution().maxHeight(cubes2) << endl; + // 76 + + vector> cubes3 = {{7,11,17},{7,17,11},{11,7,17},{11,17,7},{17,7,11},{17,11,7}}; + cout << Solution().maxHeight(cubes3) << endl; + // 102 + + return 0; +} diff --git a/1501-2000/1692-Count-Ways-to-Distribute-Candies/cpp-1692/CMakeLists.txt b/1501-2000/1692-Count-Ways-to-Distribute-Candies/cpp-1692/CMakeLists.txt new file mode 100644 index 00000000..091f54f8 --- /dev/null +++ b/1501-2000/1692-Count-Ways-to-Distribute-Candies/cpp-1692/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1692) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1692 main.cpp) \ No newline at end of file diff --git a/1501-2000/1692-Count-Ways-to-Distribute-Candies/cpp-1692/main.cpp b/1501-2000/1692-Count-Ways-to-Distribute-Candies/cpp-1692/main.cpp new file mode 100644 index 00000000..5d7e1e9a --- /dev/null +++ b/1501-2000/1692-Count-Ways-to-Distribute-Candies/cpp-1692/main.cpp @@ -0,0 +1,43 @@ +/// Source : https://leetcode.com/problems/count-ways-to-distribute-candies/ +/// Author : liuyubobobo +/// Time : 2020-12-20 + +#include +#include + +using namespace std; + + +/// Mathematics +/// Time Complexity: O(nk) +/// Space Complexity: O(nk) +class Solution { + +private: + long long MOD = 1e9 + 7; + +public: + int waysToDistribute(int n, int k) { + + vector> dp(k + 1, vector(n + 1, 1ll)); + for(int i = 2; i <= k; i ++) + for(int j = i + 1; j <= n; j ++) + dp[i][j] = (dp[i][j - 1] * i + dp[i - 1][j - 1] ) % MOD; + return dp[k][n]; + } +}; + + +int main() { + + cout << Solution().waysToDistribute(3, 2) << endl; + // 3 + + cout << Solution().waysToDistribute(4, 2) << endl; + // 6 + + cout << Solution().waysToDistribute(20, 5) << endl; + // 206085257 + + return 0; +} diff --git a/1501-2000/1694-Reformat-Phone-Number/cpp-1694/CMakeLists.txt b/1501-2000/1694-Reformat-Phone-Number/cpp-1694/CMakeLists.txt new file mode 100644 index 00000000..d5d5e4ff --- /dev/null +++ b/1501-2000/1694-Reformat-Phone-Number/cpp-1694/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1501-2000/1694-Reformat-Phone-Number/cpp-1694/main.cpp b/1501-2000/1694-Reformat-Phone-Number/cpp-1694/main.cpp new file mode 100644 index 00000000..581eae9a --- /dev/null +++ b/1501-2000/1694-Reformat-Phone-Number/cpp-1694/main.cpp @@ -0,0 +1,44 @@ +/// Source : https://leetcode.com/problems/reformat-phone-number/ +/// Author : liuyubobobo +/// Time : 2020-12-19 + +#include +#include + +using namespace std; + + +/// Split +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + string reformatNumber(string number) { + + string s = ""; + for(char c: number) + if(isdigit(c)) s += c; + + vector v; + while(s.size() > 4){ + v.push_back(s.substr(0, 3)); + s = s.substr(3); + } + if(s.size() == 4) + v.push_back({s.substr(0, 2)}), + v.push_back({s.substr(2)}); + else + v.push_back(s); + + string res = v[0]; + for(int i = 1; i < v.size(); i ++) + res += "-" + v[i]; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1695-Maximum-Erasure-Value/cpp-1695/CMakeLists.txt b/1501-2000/1695-Maximum-Erasure-Value/cpp-1695/CMakeLists.txt new file mode 100644 index 00000000..81ad8b42 --- /dev/null +++ b/1501-2000/1695-Maximum-Erasure-Value/cpp-1695/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1501-2000/1695-Maximum-Erasure-Value/cpp-1695/main.cpp b/1501-2000/1695-Maximum-Erasure-Value/cpp-1695/main.cpp new file mode 100644 index 00000000..08714efe --- /dev/null +++ b/1501-2000/1695-Maximum-Erasure-Value/cpp-1695/main.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/maximum-erasure-value/ +/// Author : liuyubobobo +/// Time : 2020-12-19 + +#include +#include +#include + +using namespace std; + + +/// Sliding Window +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int maximumUniqueSubarray(vector& nums) { + + unordered_set set; + int l = 0, r = -1, res = 0, cur = 0; + while(l < nums.size()){ + if(r + 1 < nums.size() && !set.count(nums[r + 1])){ + r ++; + cur += nums[r]; + set.insert(nums[r]); + } + else{ + cur -= nums[l]; + set.erase(nums[l]); + l ++; + } + res = max(res, cur); + } + return res; + } +}; + + +int main() { + + vector nums1 = {4, 2, 4, 5, 6}; + cout << Solution().maximumUniqueSubarray(nums1) << endl; + // 17 + + vector nums2 = {5,2,1,2,5,2,1,2,5}; + cout << Solution().maximumUniqueSubarray(nums2) << endl; + // 8 + + return 0; +} diff --git a/1501-2000/1696-Jump-Game-VI/cpp-1696/CMakeLists.txt b/1501-2000/1696-Jump-Game-VI/cpp-1696/CMakeLists.txt new file mode 100644 index 00000000..7e530eb8 --- /dev/null +++ b/1501-2000/1696-Jump-Game-VI/cpp-1696/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main4.cpp) \ No newline at end of file diff --git a/1501-2000/1696-Jump-Game-VI/cpp-1696/main.cpp b/1501-2000/1696-Jump-Game-VI/cpp-1696/main.cpp new file mode 100644 index 00000000..8799b2c8 --- /dev/null +++ b/1501-2000/1696-Jump-Game-VI/cpp-1696/main.cpp @@ -0,0 +1,118 @@ +/// Source : https://leetcode.com/problems/jump-game-vi/ +/// Author : liuyubobobo +/// Time : 2020-12-19 + +#include +#include + +using namespace std; + + +/// Segment Tree +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class SegmentTree{ + +private: + int n; + vector data, tree; + +public: + SegmentTree(const vector& data): n(data.size()), data(data), tree(4 * n, 0){ + buildSegTree(0, 0, n - 1); + } + + SegmentTree(int n): n(n), data(n, 0), tree(4 * n, 0){} + + void update(int index, int value){ + data[index] = value; + update(0, 0, n - 1, index, value); + } + + int query(int index){ + return data[index]; + } + + int query(int l, int r){ + return query(0, 0, n - 1, l, r); + } + +private: + void buildSegTree(int treeID, int l, int r){ + + if(l == r){ + tree[treeID] = data[l]; + return; + } + + int mid = (l + r) / 2; + buildSegTree(treeID * 2 + 1, l, mid); + buildSegTree(treeID * 2 + 2, mid + 1, r); + tree[treeID] = max(tree[treeID * 2 + 1], tree[treeID * 2 + 2]); + return; + } + + void update(int treeID, int l, int r, int index, int value){ + + if(l == r){ + assert(l == index); + tree[treeID] = value; + return; + } + + int mid = (l + r) / 2; + if(index <= mid) update(treeID * 2 + 1, l, mid, index, value); + else update(treeID * 2 + 2, mid + 1, r, index, value); + + tree[treeID] = max(tree[treeID * 2 + 1], tree[treeID * 2 + 2]); + return; + } + + int query(int treeID, int l, int r, int ql, int qr){ + + if(ql == l && qr == r) + return tree[treeID]; + + int mid = (l + r) / 2; + if(qr <= mid) return query(treeID * 2 + 1, l, mid, ql, qr); + else if(ql > mid) return query(treeID * 2 + 2, mid + 1, r, ql, qr); + + int resl = query(treeID * 2 + 1, l, mid, ql, mid); + int resr = query(treeID * 2 + 2, mid + 1, r, mid + 1, qr); + return max(resl, resr); + } +}; + +class Solution { +public: + int maxResult(vector& nums, int k) { + + int n = nums.size(); + SegmentTree segTree(n); + segTree.update(0, nums[0]); + + for(int i = 1; i < nums.size(); i ++){ + int l = max(0, i - k), r = i - 1; + segTree.update(i, segTree.query(l, r) + nums[i]); + } + return segTree.query(n - 1); + } +}; + + +int main() { + + vector nums1 = {1,-1,-2,4,-7,3}; + cout << Solution().maxResult(nums1, 2) << endl; + // 7 + + vector nums2 = {10,-5,-2,4,0,3}; + cout << Solution().maxResult(nums2, 3) << endl; + // 17 + + vector nums3 = {1,-5,-20,4,-1,3,-6,-3}; + cout << Solution().maxResult(nums3, 2) << endl; + // 0 + + return 0; +} diff --git a/1501-2000/1696-Jump-Game-VI/cpp-1696/main2.cpp b/1501-2000/1696-Jump-Game-VI/cpp-1696/main2.cpp new file mode 100644 index 00000000..d26937c7 --- /dev/null +++ b/1501-2000/1696-Jump-Game-VI/cpp-1696/main2.cpp @@ -0,0 +1,55 @@ +/// Source : https://leetcode.com/problems/jump-game-vi/ +/// Author : liuyubobobo +/// Time : 2020-12-19 + +#include +#include +#include + +using namespace std; + + +/// Tree Map +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + int maxResult(vector& nums, int k) { + + int n = nums.size(); + vector dp(n, nums[0]); + + map tree; + tree[nums[0]] ++; + + for(int i = 1; i < nums.size(); i ++){ + + dp[i] = nums[i] + tree.rbegin()->first; + tree[dp[i]] ++; + + if(i >= k){ + tree[dp[i - k]] --; + if(tree[dp[i - k]] == 0) tree.erase(dp[i - k]); + } + } + return dp.back(); + } +}; + + +int main() { + + vector nums1 = {1,-1,-2,4,-7,3}; + cout << Solution().maxResult(nums1, 2) << endl; + // 7 + + vector nums2 = {10,-5,-2,4,0,3}; + cout << Solution().maxResult(nums2, 3) << endl; + // 17 + + vector nums3 = {1,-5,-20,4,-1,3,-6,-3}; + cout << Solution().maxResult(nums3, 2) << endl; + // 0 + + return 0; +} diff --git a/1501-2000/1696-Jump-Game-VI/cpp-1696/main3.cpp b/1501-2000/1696-Jump-Game-VI/cpp-1696/main3.cpp new file mode 100644 index 00000000..06f553da --- /dev/null +++ b/1501-2000/1696-Jump-Game-VI/cpp-1696/main3.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/jump-game-vi/ +/// Author : liuyubobobo +/// Time : 2020-12-19 + +#include +#include +#include + +using namespace std; + + +/// Priority Queue +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + int maxResult(vector& nums, int k) { + + int n = nums.size(); + vector dp(n, nums[0]); + + priority_queue> pq; + pq.push({nums[0], 0}); + + for(int i = 1; i < nums.size(); i ++){ + + dp[i] = nums[i] + pq.top().first; + pq.push({dp[i], i}); + + while(!pq.empty() && pq.top().second <= i - k) + pq.pop(); + } + return dp.back(); + } +}; + + +int main() { + + vector nums1 = {1,-1,-2,4,-7,3}; + cout << Solution().maxResult(nums1, 2) << endl; + // 7 + + vector nums2 = {10,-5,-2,4,0,3}; + cout << Solution().maxResult(nums2, 3) << endl; + // 17 + + vector nums3 = {1,-5,-20,4,-1,3,-6,-3}; + cout << Solution().maxResult(nums3, 2) << endl; + // 0 + + return 0; +} diff --git a/1501-2000/1696-Jump-Game-VI/cpp-1696/main4.cpp b/1501-2000/1696-Jump-Game-VI/cpp-1696/main4.cpp new file mode 100644 index 00000000..d0e8c3b9 --- /dev/null +++ b/1501-2000/1696-Jump-Game-VI/cpp-1696/main4.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/jump-game-vi/ +/// Author : liuyubobobo +/// Time : 2020-12-19 + +#include +#include +#include + +using namespace std; + + +/// Mono Queue +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int maxResult(vector& nums, int k) { + + int n = nums.size(); + vector dp(n, nums[0]); + + deque q; + q.push_back(0); + + for(int i = 1; i < nums.size(); i ++){ + + dp[i] = nums[i] + dp[q.front()]; + while(!q.empty() && dp[q.back()] <= dp[i]) q.pop_back(); + q.push_back(i); + + while(!q.empty() && q.front() <= i - k) + q.pop_front(); + } + return dp.back(); + } +}; + + +int main() { + + vector nums1 = {1,-1,-2,4,-7,3}; + cout << Solution().maxResult(nums1, 2) << endl; + // 7 + + vector nums2 = {10,-5,-2,4,0,3}; + cout << Solution().maxResult(nums2, 3) << endl; + // 17 + + vector nums3 = {1,-5,-20,4,-1,3,-6,-3}; + cout << Solution().maxResult(nums3, 2) << endl; + // 0 + + return 0; +} diff --git a/1501-2000/1697-Checking-Existence-of-Edge-Length-Limited-Paths/cpp-1697/CMakeLists.txt b/1501-2000/1697-Checking-Existence-of-Edge-Length-Limited-Paths/cpp-1697/CMakeLists.txt new file mode 100644 index 00000000..74cc3ee6 --- /dev/null +++ b/1501-2000/1697-Checking-Existence-of-Edge-Length-Limited-Paths/cpp-1697/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) \ No newline at end of file diff --git a/1501-2000/1697-Checking-Existence-of-Edge-Length-Limited-Paths/cpp-1697/main.cpp b/1501-2000/1697-Checking-Existence-of-Edge-Length-Limited-Paths/cpp-1697/main.cpp new file mode 100644 index 00000000..5af2fa05 --- /dev/null +++ b/1501-2000/1697-Checking-Existence-of-Edge-Length-Limited-Paths/cpp-1697/main.cpp @@ -0,0 +1,77 @@ +/// Source : https://leetcode.com/problems/checking-existence-of-edge-length-limited-paths/ +/// Author : liuyubobobo +/// Time : 2020-12-19 + +#include +#include + +using namespace std; + + +/// Offline: Sort + UF +/// Time Complexity: O(|e|log|e| + |q|log|q| + |q|) +/// Space Complexity: O(n) +class UF{ + +private: + vector parent; + +public: + UF(int n) : parent(n){ + for(int i = 0 ; i < n ; i ++) + parent[i] = i; + } + + int find(int p){ + if(p != parent[p]) + parent[p] = find(parent[p]); + return parent[p]; + } + + bool isConnected(int p, int q){ + return find(p) == find(q); + } + + void unionElements(int p, int q){ + + int pRoot = find(p), qRoot = find(q); + + if(pRoot == qRoot) return; + + parent[pRoot] = qRoot; + } +}; + +class Solution { +public: + vector distanceLimitedPathsExist(int n, vector>& edgeList, vector>& queries) { + + sort(edgeList.begin(), edgeList.end(), [](const vector& e1, const vector& e2){ + return e1[2] < e2[2]; + }); + + for(int i = 0; i < queries.size(); i ++) + queries[i].push_back(i); + sort(queries.begin(), queries.end(), [](const vector& q1, const vector& q2){ + return q1[2] < q2[2]; + }); + + UF uf(n); + vector res(queries.size()); + int ep = 0; + for(int i = 0; i < queries.size(); i ++){ + + while(ep < edgeList.size() && edgeList[ep][2] < queries[i][2]) + uf.unionElements(edgeList[ep][0], edgeList[ep][1]), ep ++; + + res[queries[i][3]] = uf.isConnected(queries[i][0], queries[i][1]); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1698-Number-of-Distinct-Substrings-in-a-String/cpp-1698/CMakeLists.txt b/1501-2000/1698-Number-of-Distinct-Substrings-in-a-String/cpp-1698/CMakeLists.txt new file mode 100644 index 00000000..de5977e2 --- /dev/null +++ b/1501-2000/1698-Number-of-Distinct-Substrings-in-a-String/cpp-1698/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1698) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1698 main.cpp) \ No newline at end of file diff --git a/1501-2000/1698-Number-of-Distinct-Substrings-in-a-String/cpp-1698/main.cpp b/1501-2000/1698-Number-of-Distinct-Substrings-in-a-String/cpp-1698/main.cpp new file mode 100644 index 00000000..9ef7efe0 --- /dev/null +++ b/1501-2000/1698-Number-of-Distinct-Substrings-in-a-String/cpp-1698/main.cpp @@ -0,0 +1,44 @@ +/// Source : https://leetcode-cn.com/problems/number-of-distinct-substrings-in-a-string/ +/// Author : liuyubobobo +/// Time : 2020-12-26 + +#include +#include +#include + +using namespace std; + + +/// Trie +/// Time Complexity: O(n^2) +/// Space Complexity: O(n^2) +class Solution { + +private: + int trie[125250][26]; + +public: + int countDistinct(string s) { + + memset(trie, -1, sizeof(trie)); + + int sz = 1, res = 0; + for(int i = 0; i < s.size(); i ++){ + int cur = 0; + for(int j = i; j < s.size(); j ++){ + if(trie[cur][s[j] - 'a'] == -1){ + trie[cur][s[j] - 'a'] = sz ++; + res ++; + } + cur = trie[cur][s[j] - 'a']; + } + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1700-Number-of-Students-Unable-to-Eat-Lunch/cpp-1700/CMakeLists.txt b/1501-2000/1700-Number-of-Students-Unable-to-Eat-Lunch/cpp-1700/CMakeLists.txt new file mode 100644 index 00000000..03f81a7a --- /dev/null +++ b/1501-2000/1700-Number-of-Students-Unable-to-Eat-Lunch/cpp-1700/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(1700_Number_of_Students_Unable_to_Eat_Lunch) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(1700_Number_of_Students_Unable_to_Eat_Lunch main2.cpp) \ No newline at end of file diff --git a/1501-2000/1700-Number-of-Students-Unable-to-Eat-Lunch/cpp-1700/main.cpp b/1501-2000/1700-Number-of-Students-Unable-to-Eat-Lunch/cpp-1700/main.cpp new file mode 100644 index 00000000..454ce7c9 --- /dev/null +++ b/1501-2000/1700-Number-of-Students-Unable-to-Eat-Lunch/cpp-1700/main.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/number-of-students-unable-to-eat-lunch/ +/// Author : liuyubobobo +/// Time : 2020-12-26 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n^3) +/// Space Complexity: O(1) +class Solution { + +public: + int countStudents(vector& students, vector& sandwiches) { + + while(!students.empty()){ + if(students[0] != sandwiches[0]){ + if(all_same(students)) + return students.size(); + int a = students[0]; + students.erase(students.begin()); + students.push_back(a); + } + else{ + students.erase(students.begin()); + sandwiches.erase(sandwiches.begin()); + } + } + return 0; + } + +private: + bool all_same(const vector& v){ + for(int i = 1; i < v.size(); i ++) + if(v[0] != v[i]) return false; + return true; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1700-Number-of-Students-Unable-to-Eat-Lunch/cpp-1700/main2.cpp b/1501-2000/1700-Number-of-Students-Unable-to-Eat-Lunch/cpp-1700/main2.cpp new file mode 100644 index 00000000..153d1861 --- /dev/null +++ b/1501-2000/1700-Number-of-Students-Unable-to-Eat-Lunch/cpp-1700/main2.cpp @@ -0,0 +1,51 @@ +/// Source : https://leetcode.com/problems/number-of-students-unable-to-eat-lunch/ +/// Author : liuyubobobo +/// Time : 2020-12-26 + +#include +#include +#include + +using namespace std; + + +/// Using Deque and Stack +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { + +public: + int countStudents(vector& students, vector& sandwiches) { + + deque q; + vector cnt(2, 0); + for(int stu: students){ + q.push_back(stu); + cnt[stu] ++; + } + reverse(sandwiches.begin(), sandwiches.end()); + + while(!q.empty()){ + if(q.front() != sandwiches.back()){ + if(cnt[1 - q.front()] == 0) + return q.size(); + int a = q.front(); + q.pop_front(); + q.push_back(a); + } + else{ + int a = q.front(); + cnt[a] --; + q.pop_front(); + sandwiches.pop_back(); + } + } + return 0; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1701-Average-Waiting-Time/cpp-1701/CMakeLists.txt b/1501-2000/1701-Average-Waiting-Time/cpp-1701/CMakeLists.txt new file mode 100644 index 00000000..87a56c46 --- /dev/null +++ b/1501-2000/1701-Average-Waiting-Time/cpp-1701/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1701) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1701 main.cpp) \ No newline at end of file diff --git a/1501-2000/1701-Average-Waiting-Time/cpp-1701/main.cpp b/1501-2000/1701-Average-Waiting-Time/cpp-1701/main.cpp new file mode 100644 index 00000000..7e1681b7 --- /dev/null +++ b/1501-2000/1701-Average-Waiting-Time/cpp-1701/main.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/average-waiting-time/ +/// Author : liuyubobobo +/// Time : 2020-12-26 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + double averageWaitingTime(vector>& customers) { + + long long cur = (long long)customers[0][0], total = 0ll; + for(const vector& e: customers){ + cur = max((long long)e[0], cur) + e[1]; + total += (cur - e[0]); + } + return (double)total / customers.size(); + } +}; + + +int main() { + + vector> customers1 = {{5,2},{5,4},{10,3},{20,1}}; + cout << Solution().averageWaitingTime(customers1) << endl; + + return 0; +} diff --git a/1501-2000/1702-Maximum-Binary-String-After-Change/cpp-1702/CMakeLists.txt b/1501-2000/1702-Maximum-Binary-String-After-Change/cpp-1702/CMakeLists.txt new file mode 100644 index 00000000..8e85973d --- /dev/null +++ b/1501-2000/1702-Maximum-Binary-String-After-Change/cpp-1702/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1702) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1702 main.cpp) \ No newline at end of file diff --git a/1501-2000/1702-Maximum-Binary-String-After-Change/cpp-1702/main.cpp b/1501-2000/1702-Maximum-Binary-String-After-Change/cpp-1702/main.cpp new file mode 100644 index 00000000..f8a9f924 --- /dev/null +++ b/1501-2000/1702-Maximum-Binary-String-After-Change/cpp-1702/main.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/maximum-binary-string-after-change/ +/// Author : liuyubobobo +/// Time : 2020-12-26 + +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + string maximumBinaryString(string binary) { + + int i; + for(i = 0; i + 1 < binary.size(); i ++) + if(binary[i] == '0' && binary[i + 1] == '0') + binary[i] = '1'; + else break; + + while(i < binary.size() && binary[i] == '1') i ++; + if(i == binary.size()) return binary; + + int zero = 0; + for(int j = i + 1; j < binary.size(); j ++) + zero += binary[j] == '0'; + + return string(i + zero, '1') + "0" + string(binary.size() - (i + zero + 1), '1'); + } +}; + + +int main() { + + string binary1 = "000110"; + cout << Solution().maximumBinaryString(binary1) << endl; + // 111011 + + string binary2 = "01"; + cout << Solution().maximumBinaryString(binary2) << endl; + // 01 + + string binary3 = "11"; + cout << Solution().maximumBinaryString(binary3) << endl; + // 11 + + return 0; +} diff --git a/1501-2000/1703-Minimum-Adjacent-Swaps-for-K-Consecutive-Ones/cpp-1703/CMakeLists.txt b/1501-2000/1703-Minimum-Adjacent-Swaps-for-K-Consecutive-Ones/cpp-1703/CMakeLists.txt new file mode 100644 index 00000000..21290062 --- /dev/null +++ b/1501-2000/1703-Minimum-Adjacent-Swaps-for-K-Consecutive-Ones/cpp-1703/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1703) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1703 main.cpp) \ No newline at end of file diff --git a/1501-2000/1703-Minimum-Adjacent-Swaps-for-K-Consecutive-Ones/cpp-1703/main.cpp b/1501-2000/1703-Minimum-Adjacent-Swaps-for-K-Consecutive-Ones/cpp-1703/main.cpp new file mode 100644 index 00000000..9db2db5d --- /dev/null +++ b/1501-2000/1703-Minimum-Adjacent-Swaps-for-K-Consecutive-Ones/cpp-1703/main.cpp @@ -0,0 +1,46 @@ +#include +#include + +using namespace std; + + +class Solution { +public: + int minMoves(vector& nums, int k) { + + vector pos; + for(int i = 0; i < nums.size(); i ++) + if(nums[i]) pos.push_back(i); + + for(int i = 0; i < pos.size(); i ++) pos[i] -= i; + vector presum(pos.size() + 1, 0); + for(int i = 0; i < pos.size(); i ++) + presum[i + 1] = presum[i] + pos[i]; + + int res = INT_MAX; + for(int l = 0; l + k <= pos.size(); l ++){ + int r = l + k - 1; + int t = presum[r + 1] - presum[r - k/2 + 1] - (presum[l + k/2] - presum[l]); + res = min(res, t); + } + return res; + } +}; + + +int main() { + + vector nums1 = {1, 0, 0, 1, 0, 1}; + cout << Solution().minMoves(nums1, 2) << endl; + // 1 + + vector nums2 = {1,0,0,0,0,0,1,1}; + cout << Solution().minMoves(nums2, 3) << endl; + // 5 + + vector nums3 = {1,1,0,1}; + cout << Solution().minMoves(nums3, 2) << endl; + // 0 + + return 0; +} diff --git a/1501-2000/1704-Determine-if-String-Halves-Are-Alike/cpp-1704/CMakeLists.txt b/1501-2000/1704-Determine-if-String-Halves-Are-Alike/cpp-1704/CMakeLists.txt new file mode 100644 index 00000000..c8847e84 --- /dev/null +++ b/1501-2000/1704-Determine-if-String-Halves-Are-Alike/cpp-1704/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1704) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1704 main.cpp) \ No newline at end of file diff --git a/1501-2000/1704-Determine-if-String-Halves-Are-Alike/cpp-1704/main.cpp b/1501-2000/1704-Determine-if-String-Halves-Are-Alike/cpp-1704/main.cpp new file mode 100644 index 00000000..49ec2c90 --- /dev/null +++ b/1501-2000/1704-Determine-if-String-Halves-Are-Alike/cpp-1704/main.cpp @@ -0,0 +1,31 @@ +/// Source : https://leetcode.com/problems/determine-if-string-halves-are-alike/ +/// Author : liuyubobobo +/// Time : 2020-12-29 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + bool halvesAreAlike(string s) { + + unordered_set set = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}; + + int n = s.size(), l = 0, r = 0; + for(int i = 0; i < n / 2; i ++) l += set.count(s[i]); + for(int i = n / 2; i < n; i ++) r += set.count(s[i]); + return l == r; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1705-Maximum-Number-of-Eaten-Apples/cpp-1705/CMakeLists.txt b/1501-2000/1705-Maximum-Number-of-Eaten-Apples/cpp-1705/CMakeLists.txt new file mode 100644 index 00000000..e536beec --- /dev/null +++ b/1501-2000/1705-Maximum-Number-of-Eaten-Apples/cpp-1705/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1705) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1705 main.cpp) \ No newline at end of file diff --git a/1501-2000/1705-Maximum-Number-of-Eaten-Apples/cpp-1705/main.cpp b/1501-2000/1705-Maximum-Number-of-Eaten-Apples/cpp-1705/main.cpp new file mode 100644 index 00000000..9429a64b --- /dev/null +++ b/1501-2000/1705-Maximum-Number-of-Eaten-Apples/cpp-1705/main.cpp @@ -0,0 +1,58 @@ +/// Source : https://leetcode.com/problems/maximum-number-of-eaten-apples/ +/// Author : liuyubobobo +/// Time : 2020-12-29 + +#include +#include +#include + +using namespace std; + + +/// Using Priority Queue +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + int eatenApples(vector& apples, vector& days) { + + int n = apples.size(); + + priority_queue, vector>, greater>> pq; + + int res = 0, cur_day = 0; + while(cur_day < n || !pq.empty()){ + if(cur_day < n && apples[cur_day]) pq.push({cur_day + days[cur_day], apples[cur_day]}); + while(!pq.empty() && pq.top().first <= cur_day) pq.pop(); + + if(!pq.empty()){ + res ++; + + pair p = pq.top(); + pq.pop(); + p.second --; + if(p.second) pq.push(p); + } + cur_day ++; + } + return res; + } +}; + + +int main() { + + vector apples1 = {1, 2, 3, 5, 2}, days1 = {3, 2, 1, 4, 2}; + cout << Solution().eatenApples(apples1, days1) << endl; + // 7 + + vector apples2 = {3,0,0,0,0,2}, days2 = {3,0,0,0,0,2}; + cout << Solution().eatenApples(apples2, days2) << endl; + // 5 + + vector apples3 = {2, 2, 2}, days3 = {6, 4, 2}; + cout << Solution().eatenApples(apples3, days3) << endl; + // 6 + + return 0; +} diff --git a/1501-2000/1706-Where-Will-the-Ball-Fall/cpp-1706/CMakeLists.txt b/1501-2000/1706-Where-Will-the-Ball-Fall/cpp-1706/CMakeLists.txt new file mode 100644 index 00000000..b0808168 --- /dev/null +++ b/1501-2000/1706-Where-Will-the-Ball-Fall/cpp-1706/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1706) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1706 main.cpp) \ No newline at end of file diff --git a/1501-2000/1706-Where-Will-the-Ball-Fall/cpp-1706/main.cpp b/1501-2000/1706-Where-Will-the-Ball-Fall/cpp-1706/main.cpp new file mode 100644 index 00000000..308deeb4 --- /dev/null +++ b/1501-2000/1706-Where-Will-the-Ball-Fall/cpp-1706/main.cpp @@ -0,0 +1,70 @@ +/// Source : https://leetcode.com/problems/where-will-the-ball-fall/ +/// Author : liuyubobobo +/// Time : 2020-12-29 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(m * n) +/// Space Complexity: O(1) +class Solution { +public: + vector findBall(vector>& grid) { + + int R = grid.size(), C = grid[0].size(); + vector res(C, -1); + for(int j = 0; j < C; j ++){ + int curx = 0, cury = j; + while(curx < R){ + if(grid[curx][cury] == 1){ + if(cury + 1 >= C || grid[curx][cury + 1] == -1) + break; + else{ + assert(grid[curx][cury + 1] == 1); + curx ++, cury ++; + } + } + else{ // grid[curx][cury] == -1 + if(cury - 1 < 0 || grid[curx][cury - 1] == 1) + break; + else{ + assert(grid[curx][cury - 1] == -1); + curx ++, cury --; + } + } + if(curx == R) res[j] = cury; + } + } + return res; + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << " "; cout << endl; +} + +int main() { + + vector> grid1 = { + {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_vec(Solution().findBall(grid1)); + // 1 -1 -1 -1 -1 + + vector> grid2 = { + {-1} + }; + print_vec(Solution().findBall(grid2)); + // -1 + + return 0; +} diff --git a/1501-2000/1707-Maximum-XOR-With-an-Element-From-Array/cpp-1707/CMakeLists.txt b/1501-2000/1707-Maximum-XOR-With-an-Element-From-Array/cpp-1707/CMakeLists.txt new file mode 100644 index 00000000..40a1f914 --- /dev/null +++ b/1501-2000/1707-Maximum-XOR-With-an-Element-From-Array/cpp-1707/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1707) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1707 main.cpp) \ No newline at end of file diff --git a/1501-2000/1707-Maximum-XOR-With-an-Element-From-Array/cpp-1707/main.cpp b/1501-2000/1707-Maximum-XOR-With-an-Element-From-Array/cpp-1707/main.cpp new file mode 100644 index 00000000..e59c9472 --- /dev/null +++ b/1501-2000/1707-Maximum-XOR-With-an-Element-From-Array/cpp-1707/main.cpp @@ -0,0 +1,96 @@ +/// Source : https://leetcode.com/problems/maximum-xor-with-an-element-from-array/ +/// Author : liuyubobobo +/// Time : 2020-12-29 + +#include +#include + +using namespace std; + + +/// Trie +/// Time Complexity: O(n + q) +/// Space Complexity: O(n) +class Solution { + +private: + int trie[2000000][2]; + int sz = 0; + const int D = 30; + +public: + vector maximizeXor(vector& nums, vector>& queries) { + + sort(nums.begin(), nums.end()); + for(int i = 0; i < queries.size(); i ++) + queries[i].push_back(i); + + sort(queries.begin(), queries.end(), [](const vector& q1, const vector& q2){ + return q1[1] < q2[1]; + }); + + memset(trie, -1, sizeof(trie)); + sz = 1; + + int i = 0; + vector res(queries.size()); + for(const vector& q: queries){ + + while(i < nums.size() && nums[i] <= q[1]) + insert(nums[i ++]); + + if(sz == 1) res[q[2]] = -1; + else res[q[2]] = query_xor(q[0]) ^ q[0]; + } + return res; + } + +private: + int query_xor(int num){ + + int cur = 0, res = 0; + for(int i = 0; i < D; i ++){ + int e = !!(num & (1 << (D - i - 1))); + if(trie[cur][1 - e] != -1){ + res = res * 2 + 1 - e; + cur = trie[cur][1 - e]; + } + else{ + res = res * 2 + e; + cur = trie[cur][e]; + } + } + return res; + } + + void insert(int num){ + + int cur = 0; + for(int i = 0; i < D; i ++){ + int e = !!(num & (1 << (D - i - 1))); + if(trie[cur][e] == -1) + trie[cur][e] = sz ++; + cur = trie[cur][e]; + } + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << " "; cout << endl; +} + +int main() { + + vector nums1 = {0, 1, 2, 3, 4}; + vector> query1 = {{3, 1}, {1, 3}, {5, 6}}; + print_vec(Solution().maximizeXor(nums1, query1)); + // 3 3 7 + + vector nums2 = {5, 2, 4, 6, 6, 3}; + vector> query2 = {{12, 4}, {8, 1}, {6, 3}}; + print_vec(Solution().maximizeXor(nums2, query2)); + // 15 -1 5 + + return 0; +} diff --git a/1501-2000/1708-Largest-Subarray-Length-K/cpp-1708/CMakeLists.txt b/1501-2000/1708-Largest-Subarray-Length-K/cpp-1708/CMakeLists.txt new file mode 100644 index 00000000..4d19caff --- /dev/null +++ b/1501-2000/1708-Largest-Subarray-Length-K/cpp-1708/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1708) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1708 main.cpp) \ No newline at end of file diff --git a/1501-2000/1708-Largest-Subarray-Length-K/cpp-1708/main.cpp b/1501-2000/1708-Largest-Subarray-Length-K/cpp-1708/main.cpp new file mode 100644 index 00000000..1d0dcc2c --- /dev/null +++ b/1501-2000/1708-Largest-Subarray-Length-K/cpp-1708/main.cpp @@ -0,0 +1,29 @@ +/// Source : https://leetcode.com/problems/largest-subarray-length-k/ +/// Author : liuyubobobo +/// Time : 2021-01-03 + +#include +#include + +using namespace std; + + +/// Max +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + vector largestSubarray(vector& nums, int k) { + + int maxv = nums[0], start = 0; + for(int i = 1; i + k <= nums.size(); i ++) + if(nums[i] > maxv) maxv = nums[i], start = i; + return vector(nums.begin() + start, nums.begin() + start + k); + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1710-Maximum-Units-on-a-Truck/cpp-1710/CMakeLists.txt b/1501-2000/1710-Maximum-Units-on-a-Truck/cpp-1710/CMakeLists.txt new file mode 100644 index 00000000..d5d5e4ff --- /dev/null +++ b/1501-2000/1710-Maximum-Units-on-a-Truck/cpp-1710/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1501-2000/1710-Maximum-Units-on-a-Truck/cpp-1710/main.cpp b/1501-2000/1710-Maximum-Units-on-a-Truck/cpp-1710/main.cpp new file mode 100644 index 00000000..510dc15f --- /dev/null +++ b/1501-2000/1710-Maximum-Units-on-a-Truck/cpp-1710/main.cpp @@ -0,0 +1,48 @@ +/// Source : https://leetcode.com/problems/maximum-units-on-a-truck/ +/// Author : liuyubobobo +/// Time : 2021-01-02 + +#include +#include + +using namespace std; + + +/// Greedy and Sorting +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + int maximumUnits(vector>& boxTypes, int truckSize) { + + sort(boxTypes.begin(), boxTypes.end(), + [](const vector& a, const vector& b){ + return a[1] > b[1]; + }); + + int res = 0; + for(const vector& box: boxTypes){ + + int num = min(box[0], truckSize); + res += num * box[1]; + truckSize -= num; + + if(truckSize == 0) break; + } + return res; + } +}; + + +int main() { + + vector> data1 = {{1, 3}, {2, 2}, {3, 1}}; + cout << Solution().maximumUnits(data1, 4) << endl; + // 8 + + vector> data2 = {{5, 10}, {2, 5}, {4, 7}, {3, 9}}; + cout << Solution().maximumUnits(data2, 10) << endl; + // 91 + + return 0; +} diff --git a/1501-2000/1711-Count-Good-Meals/cpp-1711/CMakeLists.txt b/1501-2000/1711-Count-Good-Meals/cpp-1711/CMakeLists.txt new file mode 100644 index 00000000..b103b001 --- /dev/null +++ b/1501-2000/1711-Count-Good-Meals/cpp-1711/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main2.cpp) \ No newline at end of file diff --git a/1501-2000/1711-Count-Good-Meals/cpp-1711/main.cpp b/1501-2000/1711-Count-Good-Meals/cpp-1711/main.cpp new file mode 100644 index 00000000..2d218d91 --- /dev/null +++ b/1501-2000/1711-Count-Good-Meals/cpp-1711/main.cpp @@ -0,0 +1,62 @@ +/// Source : https://leetcode.com/problems/count-good-meals/ +/// Author : liuyubobobo +/// Time : 2021-01-02 + +#include +#include +#include + +using namespace std; + + +/// Using HashMap +/// Time Complexity: O(nlogn) +/// Space Complextiy: O(n) +class Solution { + +private: + const long long MOD = 1e9 + 7; + +public: + int countPairs(vector& data) { + + unordered_map f; + for(int e: data) f[e] ++; + sort(data.begin(), data.end()); + + int sum = 2; + long long res = (long long)f[0] * f[1] % MOD; + for(int i = 1; i <= 21; i ++){ + + for(int e: data) + if(e < sum / 2){ + if(f.count(sum - e)) res += f[sum - e], res %= MOD; + } + else break; + + if(f.count(sum / 2)) + res += (long long)f[sum / 2] * (f[sum / 2] - 1) / 2, res %= MOD; + + sum *= 2; + } + return res; + } +}; + + +int main() { + + vector data1 = {1, 3, 5, 7, 9}; + cout << Solution().countPairs(data1) << endl; + // 4 + + vector data2 = {1,1,1,3,3,3,7}; + cout << Solution().countPairs(data2) << endl; + // 15 + + vector data3 = {149,107,1,63,0,1,6867,1325,5611,2581,39,89,46,18,12,20,22,234}; + cout << Solution().countPairs(data3) << endl; + // 12 + + return 0; +} diff --git a/1501-2000/1711-Count-Good-Meals/cpp-1711/main2.cpp b/1501-2000/1711-Count-Good-Meals/cpp-1711/main2.cpp new file mode 100644 index 00000000..f5520e49 --- /dev/null +++ b/1501-2000/1711-Count-Good-Meals/cpp-1711/main2.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/count-good-meals/ +/// Author : liuyubobobo +/// Time : 2021-01-02 + +#include +#include +#include + +using namespace std; + + +/// Two Sum + HashMap +/// Time Complexity: O(n) +/// Space Complextiy: O(n) +class Solution { + +private: + const int MOD = 1e9 + 7; + +public: + int countPairs(vector& data) { + + vector pow2(22, 1); + for(int i = 1; i < pow2.size(); i ++) pow2[i] = pow2[i - 1] * 2; + + unordered_map map; + int res = 0; + for(int e: data){ + for(int sum: pow2) + if(map.count(sum - e)) + res = (res + map[sum - e]) % MOD; + map[e] ++; + } + return res; + } +}; + + +int main() { + + vector data1 = {1, 3, 5, 7, 9}; + cout << Solution().countPairs(data1) << endl; + // 4 + + vector data2 = {1,1,1,3,3,3,7}; + cout << Solution().countPairs(data2) << endl; + // 15 + + vector data3 = {149,107,1,63,0,1,6867,1325,5611,2581,39,89,46,18,12,20,22,234}; + cout << Solution().countPairs(data3) << endl; + // 12 + + return 0; +} diff --git a/1501-2000/1712-Ways-to-Split-Array-Into-Three-Subarrays/cpp-1712/CMakeLists.txt b/1501-2000/1712-Ways-to-Split-Array-Into-Three-Subarrays/cpp-1712/CMakeLists.txt new file mode 100644 index 00000000..a645af27 --- /dev/null +++ b/1501-2000/1712-Ways-to-Split-Array-Into-Three-Subarrays/cpp-1712/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main3.cpp) \ No newline at end of file diff --git a/1501-2000/1712-Ways-to-Split-Array-Into-Three-Subarrays/cpp-1712/main.cpp b/1501-2000/1712-Ways-to-Split-Array-Into-Three-Subarrays/cpp-1712/main.cpp new file mode 100644 index 00000000..6e4a19b0 --- /dev/null +++ b/1501-2000/1712-Ways-to-Split-Array-Into-Three-Subarrays/cpp-1712/main.cpp @@ -0,0 +1,86 @@ +/// Source : https://leetcode.com/problems/ways-to-split-array-into-three-subarrays/ +/// Author : liuyubobobo +/// Time : 2021-01-02 + +#include +#include + +using namespace std; + + +/// Binary Search +/// Using prefix sum and suffix sum +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { + +private: + const int MOD = 1e9 + 7; + +public: + int waysToSplit(vector& nums) { + + int n = nums.size(); + + vector presum(n + 1, 0); + for(int i = 0; i < n; i ++) presum[i + 1] = presum[i] + nums[i]; + + vector sufsum(n + 1, 0); + for(int i = n - 1; i >= 0; i --) sufsum[i] = nums[i] + sufsum[i + 1]; + + int res = 0; + for(int i = 0; i + 2 < n; i ++){ + int lsum1 = presum[i + 1]; + vector::iterator iter1 = lower_bound(presum.begin() + (i + 2), presum.end(), lsum1 + lsum1); + if(iter1 != presum.end()){ + int a = iter1 - presum.begin() - 1; + assert(a > i); + + int sum = presum.back() - lsum1; + int rsum = sum - sum / 2; + + int b = binary_search(sufsum, rsum); + if(b == n) b --; + if(b > a) res += (b - a), res %= MOD; + } + } + return res; + } + + int binary_search(const vector& v, int t){ + + int l = 0, r = v.size() - 1; + while(l < r){ + int mid = (l + r + 1) / 2; + if(v[mid] >= t) l = mid; + else r = mid - 1; + } + return l; + } +}; + + +int main() { + + vector nums1 = {1, 1, 1}; + cout << Solution().waysToSplit(nums1) << endl; + // 1 + + vector nums2 = {1, 2, 2, 2, 5, 0}; + cout << Solution().waysToSplit(nums2) << endl; + // 3 + + vector nums3 = {3, 2, 1}; + cout << Solution().waysToSplit(nums3) << endl; + // 0 + + vector nums4 = {0, 3, 3}; + cout << Solution().waysToSplit(nums4) << endl; + // 1 + + vector nums5(1e5, 0); + cout << Solution().waysToSplit(nums5) << endl; + // 999849973 + + return 0; +} diff --git a/1501-2000/1712-Ways-to-Split-Array-Into-Three-Subarrays/cpp-1712/main2.cpp b/1501-2000/1712-Ways-to-Split-Array-Into-Three-Subarrays/cpp-1712/main2.cpp new file mode 100644 index 00000000..e0fe4ea3 --- /dev/null +++ b/1501-2000/1712-Ways-to-Split-Array-Into-Three-Subarrays/cpp-1712/main2.cpp @@ -0,0 +1,69 @@ +/// Source : https://leetcode.com/problems/ways-to-split-array-into-three-subarrays/ +/// Author : liuyubobobo +/// Time : 2021-01-02 + +#include +#include + +using namespace std; + + +/// Binary Search +/// Only use presum and built-in binary search functions +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { + +private: + const int MOD = 1e9 + 7; + +public: + int waysToSplit(vector& nums) { + + int n = nums.size(); + + vector presum(n + 1, 0); + for(int i = 0; i < n; i ++) presum[i + 1] = presum[i] + nums[i]; + + int res = 0; + for(int i = 0; i + 2 < n; i ++){ + int lsum1 = presum[i + 1]; + vector::iterator iter1 = lower_bound(presum.begin() + (i + 2), presum.end() - 1, lsum1 + lsum1); + int a = iter1 - presum.begin(); + + int sum = presum.back() - lsum1; + int lsum2 = sum / 2; + + vector::iterator iter2 = upper_bound(presum.begin() + a, presum.end() - 1, lsum1 + lsum2); + int b = iter2 - presum.begin(); + res = (res + (b - a)) % MOD; + } + return res; + } +}; + + +int main() { + + vector nums1 = {1, 1, 1}; + cout << Solution().waysToSplit(nums1) << endl; + // 1 + + vector nums2 = {1, 2, 2, 2, 5, 0}; + cout << Solution().waysToSplit(nums2) << endl; + // 3 + + vector nums3 = {3, 2, 1}; + cout << Solution().waysToSplit(nums3) << endl; + // 0 + + vector nums4 = {0, 3, 3}; + cout << Solution().waysToSplit(nums4) << endl; + // 1 + + vector nums5(1e5, 0); + cout << Solution().waysToSplit(nums5) << endl; + // 999849973 + + return 0; +} diff --git a/1501-2000/1712-Ways-to-Split-Array-Into-Three-Subarrays/cpp-1712/main3.cpp b/1501-2000/1712-Ways-to-Split-Array-Into-Three-Subarrays/cpp-1712/main3.cpp new file mode 100644 index 00000000..04178641 --- /dev/null +++ b/1501-2000/1712-Ways-to-Split-Array-Into-Three-Subarrays/cpp-1712/main3.cpp @@ -0,0 +1,103 @@ +/// Source : https://leetcode.com/problems/ways-to-split-array-into-three-subarrays/ +/// Author : liuyubobobo +/// Time : 2021-01-03 + +#include +#include + +using namespace std; + + +/// Binary Search +/// use self-implement binary search +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { + +private: + const int MOD = 1e9 + 7; + +public: + int waysToSplit(vector& nums) { + + int n = nums.size(); + + vector presum(n + 1, 0); + for(int i = 0; i < n; i ++) presum[i + 1] = presum[i] + nums[i]; + + int res = 0; + for(int i = 0; i + 2 < n; i ++){ + int lsum1 = presum[i + 1]; + int a = lower_ceil(presum, lsum1 + lsum1, i + 2, (int)presum.size() - 1); + if(a >= (int)presum.size() - 1) continue; + + int sum = presum.back() - lsum1; + int lsum2 = sum / 2; + + int b = upper_ceil(presum, lsum1 + lsum2, i + 2, (int)presum.size() - 2); + if(b == (int) presum.size() - 1 || presum[b] > lsum1 + lsum2) b --; + if(b >= a) + res = (res + (b - a + 1)) % MOD; + } + return res; + } + +private: + int lower_ceil(const vector& v, int t, int L, int R){ + + if(L > R) return R + 1; + int l = L, r = R + 1; + while(l < r){ + int mid = (l + r) / 2; + if(v[mid] >= t) r = mid; + else l = mid + 1; + } + return l; + } + + int upper(const vector& v, int t, int L, int R){ + + if(L > R) return R + 1; + int l = L, r = R + 1; + while(l < r){ + int mid = (l + r) / 2; + if(v[mid] > t) r = mid; + else l = mid + 1; + } + return l; + } + + int upper_ceil(const vector& v, int t, int L, int R){ + + if(L > R) return R + 1; + int index = upper(v, t, L, R); + if(index - 1 >= L && v[index - 1] == t) return index - 1; + return index; + } +}; + + +int main() { + + vector nums1 = {1, 1, 1}; + cout << Solution().waysToSplit(nums1) << endl; + // 1 + + vector nums2 = {1, 2, 2, 2, 5, 0}; + cout << Solution().waysToSplit(nums2) << endl; + // 3 + + vector nums3 = {3, 2, 1}; + cout << Solution().waysToSplit(nums3) << endl; + // 0 + + vector nums4 = {0, 3, 3}; + cout << Solution().waysToSplit(nums4) << endl; + // 1 + + vector nums5(1e5, 0); + cout << Solution().waysToSplit(nums5) << endl; + // 999849973 + + return 0; +} diff --git a/1501-2000/1713-Minimum-Operations-to-Make-a-Subsequence/cpp-1713/CMakeLists.txt b/1501-2000/1713-Minimum-Operations-to-Make-a-Subsequence/cpp-1713/CMakeLists.txt new file mode 100644 index 00000000..abe6d5ab --- /dev/null +++ b/1501-2000/1713-Minimum-Operations-to-Make-a-Subsequence/cpp-1713/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1713) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1713 main.cpp) \ No newline at end of file diff --git a/1501-2000/1713-Minimum-Operations-to-Make-a-Subsequence/cpp-1713/main.cpp b/1501-2000/1713-Minimum-Operations-to-Make-a-Subsequence/cpp-1713/main.cpp new file mode 100644 index 00000000..68e68685 --- /dev/null +++ b/1501-2000/1713-Minimum-Operations-to-Make-a-Subsequence/cpp-1713/main.cpp @@ -0,0 +1,51 @@ +/// Source : https://leetcode.com/problems/minimum-operations-to-make-a-subsequence/ +/// Author : liuyubobobo +/// Time : 2021-01-02 + +#include +#include +#include + +using namespace std; + + +/// LIS +/// Time Complexity: O(|target| + |arr| * log|arr|) +/// Space Complexity: O(|target| + |arr|) +class Solution { +public: + int minOperations(vector& target, vector& arr) { + + unordered_map map; + for(int i = 0; i < target.size(); i ++) + map[target[i]] = i; + + vector v; + for(int e: arr) + if(map.count(e)) v.push_back(map[e]); + + // LIS + vector dp; + for(int e: v) + if(dp.empty() || e > dp.back()) dp.push_back(e); + else{ + vector::iterator iter = lower_bound(dp.begin(), dp.end(), e); + dp[iter - dp.begin()] = e; + } + return target.size() - dp.size(); + } +}; + + +int main() { + + vector target1 = {5, 1, 3}, arr1 = {9, 4, 2, 3, 4}; + cout << Solution().minOperations(target1, arr1) << endl; + // 2 + + vector target2 = {6,4,8,1,3,2}, arr2 = {4,7,6,2,3,8,6,1}; + cout << Solution().minOperations(target2, arr2) << endl; + // 3 + + return 0; +} diff --git a/1501-2000/1714-Sum-Of-Special-Evenly-Spaced-Elements-In-Array/cpp-1714/CMakeLists.txt b/1501-2000/1714-Sum-Of-Special-Evenly-Spaced-Elements-In-Array/cpp-1714/CMakeLists.txt new file mode 100644 index 00000000..7dc5e304 --- /dev/null +++ b/1501-2000/1714-Sum-Of-Special-Evenly-Spaced-Elements-In-Array/cpp-1714/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1714) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1714 main.cpp) \ No newline at end of file diff --git a/1501-2000/1714-Sum-Of-Special-Evenly-Spaced-Elements-In-Array/cpp-1714/main.cpp b/1501-2000/1714-Sum-Of-Special-Evenly-Spaced-Elements-In-Array/cpp-1714/main.cpp new file mode 100644 index 00000000..091f5e08 --- /dev/null +++ b/1501-2000/1714-Sum-Of-Special-Evenly-Spaced-Elements-In-Array/cpp-1714/main.cpp @@ -0,0 +1,74 @@ +/// Source : https://leetcode.com/problems/sum-of-special-evenly-spaced-elements-in-array/ +/// Author : liuyubobobo +/// Time : 2021-01-08 + +#include +#include + +using namespace std; + + +/// SQRT Decomposition +/// Time Complexity: O(n*sqrt(n)) +/// Space Complexity: O(n*sqrt(n)) +class Solution { + +private: + const int MOD = 1e9 + 7; + +public: + vector solve(vector& nums, vector>& queries) { + + int n = nums.size(); + int B = (int)sqrt(n); + + vector> table(B + 1, vector(n + 1, 0)); + for(int b = 1; b <= B; b ++) { + table[b][1] = nums[0]; + for (int i = 1; i < n; i++) + table[b][i + 1] = ((i - b >= 0 ? table[b][i - b + 1] : 0) + nums[i]) % MOD; + } + + vector res(queries.size()); + for(int i = 0; i < queries.size(); i ++){ + int x = queries[i][0], y = queries[i][1]; + if(y > B){ + int t = 0; + for(int j = x; j < n; j += y) + t = (t + nums[j]) % MOD; + res[i] = t; + } + else{ + int t = (n - 1) / y * y + x % y; + while(t >= n) t -= y; + res[i] = (table[y][t + 1] - table[y][max(0, x - y + 1)] + MOD) % MOD; + } + } + return res; + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << " "; cout << endl; +} + +int main() { + + vector nums1 = {0,1,2,3,4,5,6,7}; + vector> queries1 = {{0, 3}, {5, 1}, {4, 2}, {3, 2}}; + print_vec(Solution().solve(nums1, queries1)); + // 9 18 10 10 + + vector nums2 = {100,200,101,201,102,202,103,203}; + vector> queries2 = {{0, 7}}; + print_vec(Solution().solve(nums2, queries2)); + // 303 + + vector nums3 = {1123,9873123,83745634,78649234,872842342,234239847}; + vector> queries3 = {{0, 1}, {3, 4}, {3, 2}}; + print_vec(Solution().solve(nums3, queries3)); + // 279351296 78649234 312889081 + + return 0; +} diff --git a/1501-2000/1716-Calculate-Money-in-Leetcode-Bank/cpp-1716/CMakeLists.txt b/1501-2000/1716-Calculate-Money-in-Leetcode-Bank/cpp-1716/CMakeLists.txt new file mode 100644 index 00000000..a324fcf5 --- /dev/null +++ b/1501-2000/1716-Calculate-Money-in-Leetcode-Bank/cpp-1716/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1716) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1716 main2.cpp) \ No newline at end of file diff --git a/1501-2000/1716-Calculate-Money-in-Leetcode-Bank/cpp-1716/main.cpp b/1501-2000/1716-Calculate-Money-in-Leetcode-Bank/cpp-1716/main.cpp new file mode 100644 index 00000000..c990fc9c --- /dev/null +++ b/1501-2000/1716-Calculate-Money-in-Leetcode-Bank/cpp-1716/main.cpp @@ -0,0 +1,31 @@ +/// Source : https://leetcode.com/problems/calculate-money-in-leetcode-bank/ +/// Author : liuyubobobo +/// Time : 2021-01-09 + +#include +#include + + +/// Brute Force +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int totalMoney(int n) { + + int res = 0; + for(int start = 0;;start ++){ + for(int i = 0; i < 7; i ++){ + res += start + 1 + i; + if(start * 7 + i + 1 == n) return res; + } + } + return -1; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1716-Calculate-Money-in-Leetcode-Bank/cpp-1716/main2.cpp b/1501-2000/1716-Calculate-Money-in-Leetcode-Bank/cpp-1716/main2.cpp new file mode 100644 index 00000000..120c2323 --- /dev/null +++ b/1501-2000/1716-Calculate-Money-in-Leetcode-Bank/cpp-1716/main2.cpp @@ -0,0 +1,29 @@ +/// Source : https://leetcode.com/problems/calculate-money-in-leetcode-bank/ +/// Author : liuyubobobo +/// Time : 2021-01-09 + +#include +#include + + +/// Brute Force +/// Time Complexity: O(n / 7) +/// Space Complexity: O(1) +class Solution { +public: + int totalMoney(int n) { + + int res = 0; + for(int start = 1; n; start ++){ + if(n >= 7) res += (start + 3) * 7, n -= 7; + else res += (start + start + n - 1) * n / 2, n = 0; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1717-Maximum-Score-From-Removing-Substrings/cpp-1717/CMakeLists.txt b/1501-2000/1717-Maximum-Score-From-Removing-Substrings/cpp-1717/CMakeLists.txt new file mode 100644 index 00000000..5a83d925 --- /dev/null +++ b/1501-2000/1717-Maximum-Score-From-Removing-Substrings/cpp-1717/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1717) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1717 main.cpp) \ No newline at end of file diff --git a/1501-2000/1717-Maximum-Score-From-Removing-Substrings/cpp-1717/main.cpp b/1501-2000/1717-Maximum-Score-From-Removing-Substrings/cpp-1717/main.cpp new file mode 100644 index 00000000..6721598b --- /dev/null +++ b/1501-2000/1717-Maximum-Score-From-Removing-Substrings/cpp-1717/main.cpp @@ -0,0 +1,48 @@ +/// Source : https://leetcode.com/problems/maximum-score-from-removing-substrings/ +/// Author : liuyubobobo +/// Time : 2021-01-09 + +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int maximumGain(string s, int x, int y) { + + string first = "ab", second = "ba"; + if(x < y) swap(first, second), swap(x, y); + + int res = 0; + res += solve(s, first, x); + res += solve(s, second, y); + return res; + } + +private: + int solve(string& s, const string& t, int score){ + + string a = ""; + int res = 0; + for(char c: s) + if(!a.empty() && a.back() == t[0] && c == t[1]) + res += score, a.pop_back(); + else + a += c; + s = a; + return res; + } +}; + + +int main() { + + cout << Solution().maximumGain("cdbcbbaaabab", 4, 5) << endl; + // 19 + + return 0; +} diff --git a/1501-2000/1718-Construct-the-Lexicographically-Largest-Valid-Sequence/cpp-1718/CMakeLists.txt b/1501-2000/1718-Construct-the-Lexicographically-Largest-Valid-Sequence/cpp-1718/CMakeLists.txt new file mode 100644 index 00000000..471c1823 --- /dev/null +++ b/1501-2000/1718-Construct-the-Lexicographically-Largest-Valid-Sequence/cpp-1718/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1718) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1718 main.cpp) \ No newline at end of file diff --git a/1501-2000/1718-Construct-the-Lexicographically-Largest-Valid-Sequence/cpp-1718/main.cpp b/1501-2000/1718-Construct-the-Lexicographically-Largest-Valid-Sequence/cpp-1718/main.cpp new file mode 100644 index 00000000..3a86cdf2 --- /dev/null +++ b/1501-2000/1718-Construct-the-Lexicographically-Largest-Valid-Sequence/cpp-1718/main.cpp @@ -0,0 +1,71 @@ +/// Source : https://leetcode.com/problems/construct-the-lexicographically-largest-valid-sequence/ +/// Author : liuyubobobo +/// Time : 2021-01-10 + +#include +#include + +using namespace std; + + +/// Backtracking +/// Time Complexity: O(n!) +/// Space Complexity: O(n) +class Solution { + +private: + int n; + +public: + vector constructDistancedSequence(int n) { + + this->n = n; + + vector res(2 * n - 1, -1); + vector visited(n + 1, false); + dfs(0, res, 2 * n - 1, visited); + + return res; + } + +private: + bool dfs(int index, vector& res, int len, vector& visited){ + + if(index == len) return true; + if(res[index] != -1) return dfs(index + 1, res, len, visited); + + for(int x = n; x > 1; x --) + if(!visited[x] && index + x < res.size() && res[index + x] == -1){ + res[index] = res[index + x] = x; + visited[x] = true; + if(dfs(index + 1, res, len, visited)) return true; + res[index] = res[index + x] = -1; + visited[x] = false; + } + + if(!visited[1]){ + res[index] = 1; + visited[1] = true; + if(dfs(index + 1, res, len, visited)) return true; + res[index] = -1; + visited[1] = false; + } + return false; + } +}; + + +void print_vec(const vector& v){ + for(int x: v) cout << x << " "; cout << endl; +} + +int main() { + + print_vec(Solution().constructDistancedSequence(3)); + // 3 1 2 3 2 + + print_vec(Solution().constructDistancedSequence(5)); + // 5,3,1,4,3,5,2,4,2 + + return 0; +} diff --git a/1501-2000/1719-Number-Of-Ways-To-Reconstruct-A-Tree/cpp-1719/CMakeLists.txt b/1501-2000/1719-Number-Of-Ways-To-Reconstruct-A-Tree/cpp-1719/CMakeLists.txt new file mode 100644 index 00000000..5a493d19 --- /dev/null +++ b/1501-2000/1719-Number-Of-Ways-To-Reconstruct-A-Tree/cpp-1719/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1719) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1719 main.cpp) \ No newline at end of file diff --git a/1501-2000/1719-Number-Of-Ways-To-Reconstruct-A-Tree/cpp-1719/main.cpp b/1501-2000/1719-Number-Of-Ways-To-Reconstruct-A-Tree/cpp-1719/main.cpp new file mode 100644 index 00000000..4fa1a935 --- /dev/null +++ b/1501-2000/1719-Number-Of-Ways-To-Reconstruct-A-Tree/cpp-1719/main.cpp @@ -0,0 +1,108 @@ +/// Source : https://leetcode.com/problems/number-of-ways-to-reconstruct-a-tree/ +/// Author : liuyubobobo +/// Time : 2021-01-16 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// Greedy and DFS +/// Time Complexity: O(V^2 + E) +/// Space Complexity: O(V + E) +class Solution { + +public: + int checkWays(vector>& pairs) { + + unordered_map> g; + int n = 0; + for(const vector& e: pairs) + g[e[0] - 1].insert(e[1] - 1), + g[e[1] - 1].insert(e[0] - 1), + n = max(n, max(e[0], e[1])); + + vector degree(n, 0); + int maxdegree = 0, maxdegv; + for(const pair>& p: g){ + degree[p.first] = p.second.size(); + if(degree[p.first] > maxdegree) + maxdegree = degree[p.first], maxdegv = p.first; + } + + if(maxdegree != (int)g.size() - 1) return 0; + vector visited(n, false); + int ccnum = 0; + return dfs(g, maxdegv, degree, visited, ccnum); + } + +private: + int dfs(unordered_map>& g, int u, + vector& degree, vector& visited, int& ccnum){ + + visited[u] = true; + + int udegree = degree[u]; + + vector next(g.at(u).begin(), g.at(u).end()); + + int ans = 1; + for(int v: next){ + if(degree[v] == udegree) ans = 2; + g[u].erase(v), g[v].erase(u); + degree[u] --; + degree[v] --; + } + + sort(next.begin(), next.end(), [&](int p, int q){return degree[p] > degree[q];}); + for(int v: next) + if(!visited[v]){ + int tnum = 0; + int tans = dfs(g, v, degree, visited, tnum); + ccnum += tnum; + if(tans == 0) return 0; + ans = max(ans, tans); + } + ccnum += 1; + if(udegree != ccnum - 1) return 0; + return ans; + } +}; + + +int main() { + + vector> pairs1 = {{1, 2}, {2, 3}}; + cout << Solution().checkWays(pairs1) << endl; + // 1 + + vector> pairs2 = {{1, 2}, {2, 3}, {1, 3}}; + cout << Solution().checkWays(pairs2) << endl; + // 2 + + vector> pairs3 = {{1, 2}, {2, 3}, {2, 4}, {1, 5}}; + cout << Solution().checkWays(pairs3) << endl; + // 0 + + vector> pairs4 = {{3, 5}, {4, 5}, {2, 5}, {1, 5}, {1, 4}, {2, 4}}; + cout << Solution().checkWays(pairs4) << endl; + // 1 + + vector> pairs5 = {{5, 7}, {11, 12}, {2, 9}, {8, 10}, {1, 4}, {3, 6}}; + cout << Solution().checkWays(pairs5) << endl; + // 0 + + vector> pairs6 = {{4, 5}, {3, 4}, {2, 4}}; + cout << Solution().checkWays(pairs6) << endl; + // 1 + + vector> pairs7 = {{1, 5}, {1, 3}, {2, 3}, {2, 4}, {3, 5}, {3, 4}}; + cout << Solution().checkWays(pairs7) << endl; + // 2 + + return 0; +} diff --git a/1501-2000/1720-Decode-XORed-Array/cpp-1720/CMakeLists.txt b/1501-2000/1720-Decode-XORed-Array/cpp-1720/CMakeLists.txt new file mode 100644 index 00000000..d5d5e4ff --- /dev/null +++ b/1501-2000/1720-Decode-XORed-Array/cpp-1720/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1501-2000/1720-Decode-XORed-Array/cpp-1720/main.cpp b/1501-2000/1720-Decode-XORed-Array/cpp-1720/main.cpp new file mode 100644 index 00000000..328db587 --- /dev/null +++ b/1501-2000/1720-Decode-XORed-Array/cpp-1720/main.cpp @@ -0,0 +1,29 @@ +/// Source : https://leetcode.com/problems/decode-xored-array/ +/// Author : liuyubobobo +/// Time : 2021-01-09 + +#include +#include + +using namespace std; + + +/// Xor +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + vector decode(vector& encoded, int first) { + + vector res(encoded.size() + 1, first); + for(int i = 1; i < res.size(); i ++) + res[i] = res[i - 1] ^ encoded[i - 1]; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1721-Swapping-Nodes-in-a-Linked-List/cpp-1721/CMakeLists.txt b/1501-2000/1721-Swapping-Nodes-in-a-Linked-List/cpp-1721/CMakeLists.txt new file mode 100644 index 00000000..31c71f2a --- /dev/null +++ b/1501-2000/1721-Swapping-Nodes-in-a-Linked-List/cpp-1721/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main3.cpp) \ No newline at end of file diff --git a/1501-2000/1721-Swapping-Nodes-in-a-Linked-List/cpp-1721/main.cpp b/1501-2000/1721-Swapping-Nodes-in-a-Linked-List/cpp-1721/main.cpp new file mode 100644 index 00000000..28c11a5b --- /dev/null +++ b/1501-2000/1721-Swapping-Nodes-in-a-Linked-List/cpp-1721/main.cpp @@ -0,0 +1,55 @@ +/// Source : https://leetcode.com/problems/swapping-nodes-in-a-linked-list/ +/// Author : liuyubobobo +/// Time : 2021-01-09 + +#include +#include +#include + +using namespace std; + + +/// Using HashMap to record index and Node +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode() : val(0), next(nullptr) {} + ListNode(int x) : val(x), next(nullptr) {} + ListNode(int x, ListNode *next) : val(x), next(next) {} +}; + +class Solution { +public: + ListNode* swapNodes(ListNode* head, int k) { + + int len = 0; + ListNode* cur = head; + unordered_map nodes; + while(cur){ + nodes[len ++] = cur; + cur = cur->next; + } + + int a = k - 1, b = len - k; + swap(nodes[a], nodes[b]); + + ListNode* dummyHead = new ListNode(-1); + cur = dummyHead; + for(int i = 0; i < len; i ++){ + cur->next = nodes[i]; + cur = cur->next; + } + cur->next = nullptr; + return dummyHead->next; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1721-Swapping-Nodes-in-a-Linked-List/cpp-1721/main2.cpp b/1501-2000/1721-Swapping-Nodes-in-a-Linked-List/cpp-1721/main2.cpp new file mode 100644 index 00000000..9992567f --- /dev/null +++ b/1501-2000/1721-Swapping-Nodes-in-a-Linked-List/cpp-1721/main2.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/swapping-nodes-in-a-linked-list/ +/// Author : liuyubobobo +/// Time : 2021-01-09 + +#include +#include +#include + +using namespace std; + + +/// Two Passes and Swap value +/// Time Complexity: O(n) +/// Space Complexity: O(1) + +/// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode() : val(0), next(nullptr) {} + ListNode(int x) : val(x), next(nullptr) {} + ListNode(int x, ListNode *next) : val(x), next(next) {} +}; + +class Solution { +public: + ListNode* swapNodes(ListNode* head, int k) { + + int len = 0; + ListNode* cur = head; + while(cur) + cur = cur->next, len ++; + + int a = k - 1, b = len - k; + + ListNode *anode = nullptr, *bnode = nullptr; + cur = head; + for(int i = 0; i < len; i ++){ + if(i == a) anode = cur; + if(i == b) bnode = cur; + cur = cur->next; + } + swap(anode->val, bnode->val); + return head; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1721-Swapping-Nodes-in-a-Linked-List/cpp-1721/main3.cpp b/1501-2000/1721-Swapping-Nodes-in-a-Linked-List/cpp-1721/main3.cpp new file mode 100644 index 00000000..b7f761ba --- /dev/null +++ b/1501-2000/1721-Swapping-Nodes-in-a-Linked-List/cpp-1721/main3.cpp @@ -0,0 +1,48 @@ +/// Source : https://leetcode.com/problems/swapping-nodes-in-a-linked-list/ +/// Author : liuyubobobo +/// Time : 2021-01-09 + +#include +#include +#include + +using namespace std; + + +/// Single Passes and Swap value +/// Time Complexity: O(n) +/// Space Complexity: O(1) + +/// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode() : val(0), next(nullptr) {} + ListNode(int x) : val(x), next(nullptr) {} + ListNode(int x, ListNode *next) : val(x), next(next) {} +}; + +class Solution { +public: + ListNode* swapNodes(ListNode* head, int k) { + + ListNode* cur = head; + for(int i = 0; i < k - 1; i ++) + cur = cur->next; + ListNode* anode = cur; + + ListNode *bnode = head; + while(cur->next){ + cur = cur->next; + bnode = bnode->next; + } + swap(anode->val, bnode->val); + return head; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1722-Minimize-Hamming-Distance-After-Swap-Operations/cpp-1722/CMakeLists.txt b/1501-2000/1722-Minimize-Hamming-Distance-After-Swap-Operations/cpp-1722/CMakeLists.txt new file mode 100644 index 00000000..80fb8c61 --- /dev/null +++ b/1501-2000/1722-Minimize-Hamming-Distance-After-Swap-Operations/cpp-1722/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main2.cpp) \ No newline at end of file diff --git a/1501-2000/1722-Minimize-Hamming-Distance-After-Swap-Operations/cpp-1722/main.cpp b/1501-2000/1722-Minimize-Hamming-Distance-After-Swap-Operations/cpp-1722/main.cpp new file mode 100644 index 00000000..b1848585 --- /dev/null +++ b/1501-2000/1722-Minimize-Hamming-Distance-After-Swap-Operations/cpp-1722/main.cpp @@ -0,0 +1,79 @@ +/// Source : https://leetcode.com/problems/minimize-hamming-distance-after-swap-operations/ +/// Author : liuyubobobo +/// Time : 2021-01-09 + +#include +#include +#include +#include + +using namespace std; + + +/// Connected Components +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int minimumHammingDistance(vector& source, vector& target, vector>& allowedSwaps) { + + int n = source.size(); + vector> g(n); + for(const vector& e: allowedSwaps) + g[e[0]].insert(e[1]), g[e[1]].insert(e[0]); + + vector cc(n, -1); + int color = 0; + for(int i = 0; i < n; i ++) + if(cc[i] == -1) + dfs(g, i, color ++, cc); + + vector> C(color); + for(int i = 0; i < n; i ++) C[cc[i]].push_back(i); + + int res = 0; + for(int co = 0; co < color; co ++){ + unordered_map f; + for(int index: C[co]) + f[source[index]] ++; + + for(int index: C[co]) + if(f.count(target[index])){ + res ++; + f[target[index]] --; + if(f[target[index]] == 0) f.erase(target[index]); + } + } + return n - res; + } + +private: + void dfs(const vector>& g, int u, int color, vector& cc){ + + cc[u] = color; + for(int v: g[u]) + if(cc[v] == -1) + dfs(g, v, color, cc); + } +}; + + +int main() { + + vector s1 = {1, 2, 3, 4}, t1 = {2, 1, 4, 5}; + vector> as1 = {{0, 1}, {2, 3}}; + cout << Solution().minimumHammingDistance(s1, t1, as1) << endl; + // 1 + + vector s2 = {1, 2, 3, 4}, t2 = {1, 3, 2, 4}; + vector> as2 = {}; + cout << Solution().minimumHammingDistance(s2, t2, as2) << endl; + // 2 + + vector s3 = {5, 1, 2, 4, 3}, t3 = {1, 5, 4, 2, 3}; + vector> as3 = {{0, 4}, {4, 2}, {1, 3}, {1, 4}}; + cout << Solution().minimumHammingDistance(s3, t3, as3) << endl; + // 0 + + return 0; +} diff --git a/1501-2000/1722-Minimize-Hamming-Distance-After-Swap-Operations/cpp-1722/main2.cpp b/1501-2000/1722-Minimize-Hamming-Distance-After-Swap-Operations/cpp-1722/main2.cpp new file mode 100644 index 00000000..dc4438e5 --- /dev/null +++ b/1501-2000/1722-Minimize-Hamming-Distance-After-Swap-Operations/cpp-1722/main2.cpp @@ -0,0 +1,82 @@ +/// Source : https://leetcode.com/problems/minimize-hamming-distance-after-swap-operations/ +/// Author : liuyubobobo +/// Time : 2021-01-09 + +#include +#include +#include +#include + +using namespace std; + + +/// Connected Components +/// Two pointer to deal with each component +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + int minimumHammingDistance(vector& source, vector& target, vector>& allowedSwaps) { + + int n = source.size(); + vector> g(n); + for(const vector& e: allowedSwaps) + g[e[0]].insert(e[1]), g[e[1]].insert(e[0]); + + vector cc(n, -1); + int color = 0; + for(int i = 0; i < n; i ++) + if(cc[i] == -1) + dfs(g, i, color ++, cc); + + vector> C(color); + for(int i = 0; i < n; i ++) C[cc[i]].push_back(i); + + int res = 0; + for(int co = 0; co < color; co ++){ + vector a(C[co].size()), b(C[co].size()); + for(int i = 0; i < C[co].size(); i ++) + a[i] = source[C[co][i]], b[i] = target[C[co][i]]; + + sort(a.begin(), a.end()); + sort(b.begin(), b.end()); + + int i = 0, j = 0; + while(i < a.size() && j < b.size()) + if(a[i] < b[j]) i ++; + else if(a[i] > b[j]) j ++; + else res ++, i ++, j ++; + } + return n - res; + } + +private: + void dfs(const vector>& g, int u, int color, vector& cc){ + + cc[u] = color; + for(int v: g[u]) + if(cc[v] == -1) + dfs(g, v, color, cc); + } +}; + + +int main() { + + vector s1 = {1, 2, 3, 4}, t1 = {2, 1, 4, 5}; + vector> as1 = {{0, 1}, {2, 3}}; + cout << Solution().minimumHammingDistance(s1, t1, as1) << endl; + // 1 + + vector s2 = {1, 2, 3, 4}, t2 = {1, 3, 2, 4}; + vector> as2 = {}; + cout << Solution().minimumHammingDistance(s2, t2, as2) << endl; + // 2 + + vector s3 = {5, 1, 2, 4, 3}, t3 = {1, 5, 4, 2, 3}; + vector> as3 = {{0, 4}, {4, 2}, {1, 3}, {1, 4}}; + cout << Solution().minimumHammingDistance(s3, t3, as3) << endl; + // 0 + + return 0; +} diff --git a/1501-2000/1723-Find-Minimum-Time-to-Finish-All-Jobs/cpp-1723/CMakeLists.txt b/1501-2000/1723-Find-Minimum-Time-to-Finish-All-Jobs/cpp-1723/CMakeLists.txt new file mode 100644 index 00000000..a373769d --- /dev/null +++ b/1501-2000/1723-Find-Minimum-Time-to-Finish-All-Jobs/cpp-1723/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main2.cpp) \ No newline at end of file diff --git a/1501-2000/1723-Find-Minimum-Time-to-Finish-All-Jobs/cpp-1723/main.cpp b/1501-2000/1723-Find-Minimum-Time-to-Finish-All-Jobs/cpp-1723/main.cpp new file mode 100644 index 00000000..b0e2b5fb --- /dev/null +++ b/1501-2000/1723-Find-Minimum-Time-to-Finish-All-Jobs/cpp-1723/main.cpp @@ -0,0 +1,56 @@ +/// Source : https://leetcode.com/problems/find-minimum-time-to-finish-all-jobs/ +/// Author : liuyubobobo +/// Time : 2021-01-09 + +#include +#include + +using namespace std; + + +/// State Compression Memory Search +/// Time Complexity: O(k * 2^n) +/// Space Complexity: O(k * 2^n) +class Solution { +public: + int minimumTimeRequired(vector& jobs, int k) { + + int n = jobs.size(); + vector t(1 << n, 0); + for(int state = 1; state < (1 << n); state ++) + t[state] = jobs[__builtin_ctz(state)] + t[state - (1 << __builtin_ctz(state))]; + + vector> dp(k, vector(1 << n, -1)); + return dfs(n, t, (1 << n) - 1, k - 1, dp); + } + +private: + int dfs(int n, const vector& t, int state, int k, + vector>& dp){ + + if(k == 0) return state == 0 ? INT_MAX : t[state]; + if(state == 0) return INT_MAX; + if(dp[k][state] != -1) return dp[k][state]; + + int res = INT_MAX; + for (int s = state; s; s = (s - 1) & state) + if(s != state){ + res = min(res, max(t[s], dfs(n, t, state - s, k - 1, dp))); + } + return dp[k][state] = res; + } +}; + + +int main() { + + vector jobs1 = {3, 2, 3}; + cout << Solution().minimumTimeRequired(jobs1, 3) << endl; + // 3 + + vector jobs2 = {1, 2, 4, 7, 8}; + cout << Solution().minimumTimeRequired(jobs2, 2) << endl; + // 11 + + return 0; +} diff --git a/1501-2000/1723-Find-Minimum-Time-to-Finish-All-Jobs/cpp-1723/main2.cpp b/1501-2000/1723-Find-Minimum-Time-to-Finish-All-Jobs/cpp-1723/main2.cpp new file mode 100644 index 00000000..dbe5f542 --- /dev/null +++ b/1501-2000/1723-Find-Minimum-Time-to-Finish-All-Jobs/cpp-1723/main2.cpp @@ -0,0 +1,48 @@ +/// Source : https://leetcode.com/problems/find-minimum-time-to-finish-all-jobs/ +/// Author : liuyubobobo +/// Time : 2021-01-09 + +#include +#include + +using namespace std; + + +/// State Compression Memory Search +/// Time Complexity: O(k * 2^n) +/// Space Complexity: O(k * 2^n) +class Solution { +public: + int minimumTimeRequired(vector& jobs, int k) { + + int n = jobs.size(); + vector t(1 << n, 0); + for(int state = 1; state < (1 << n); state ++) + t[state] = jobs[__builtin_ctz(state)] + t[state - (1 << __builtin_ctz(state))]; + + vector> dp(k, vector(1 << n, INT_MAX)); + for(int state = 0; state < (1 << n); state ++) + dp[0][state] = t[state]; + + for(int i = 1; i < k; i ++) + for(int state = 1; state < (1 << n); state ++){ + for (int s = state; s; s = (s - 1) & state) + dp[i][state] = min(dp[i][state], max(t[s], dp[i - 1][state - s])); + } + return dp[k - 1][(1 << n) - 1]; + } +}; + + +int main() { + + vector jobs1 = {3, 2, 3}; + cout << Solution().minimumTimeRequired(jobs1, 3) << endl; + // 3 + + vector jobs2 = {1, 2, 4, 7, 8}; + cout << Solution().minimumTimeRequired(jobs2, 2) << endl; + // 11 + + return 0; +} diff --git a/1501-2000/1724-Checking-Existence-of-Edge-Length-Limited-Paths-II/cpp-1724/CMakeLists.txt b/1501-2000/1724-Checking-Existence-of-Edge-Length-Limited-Paths-II/cpp-1724/CMakeLists.txt new file mode 100644 index 00000000..f8012c67 --- /dev/null +++ b/1501-2000/1724-Checking-Existence-of-Edge-Length-Limited-Paths-II/cpp-1724/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1724) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1724 main2.cpp) \ No newline at end of file diff --git a/1501-2000/1724-Checking-Existence-of-Edge-Length-Limited-Paths-II/cpp-1724/main.cpp b/1501-2000/1724-Checking-Existence-of-Edge-Length-Limited-Paths-II/cpp-1724/main.cpp new file mode 100644 index 00000000..c327309b --- /dev/null +++ b/1501-2000/1724-Checking-Existence-of-Edge-Length-Limited-Paths-II/cpp-1724/main.cpp @@ -0,0 +1,98 @@ +/// Source : https://leetcode.com/problems/checking-existence-of-edge-length-limited-paths-ii/ +/// Author : liuyubobobo +/// Time : 2021-01-14 + +#include +#include +#include + +using namespace std; + + +/// MST and Keep all the UF status +/// Time Complexity: init: O(EVlogE) +/// query: O(log(LIMIT)) +/// Space Comoplexity: O(EV) +class UF{ + +public: + vector parent; + + UF(int n) : parent(n){ + for(int i = 0 ; i < n ; i ++) + parent[i] = i; + } + + int find(int p, vector* data = nullptr){ + + if(data == nullptr) data = &parent; + while(p != (*data)[p]) + p = (*data)[p]; + return p; + } + + bool isConnected(int p, int q, vector* data = nullptr){ + return find(p, data) == find(q, data); + } + + void unionElements(int p, int q){ + + int pRoot = find(p), qRoot = find(q); + + if(pRoot == qRoot) return; + + parent[pRoot] = qRoot; + } +}; + + +class DistanceLimitedPathsExist { + +private: + map> table; + UF uf; + +public: + DistanceLimitedPathsExist(int n, vector>& edges) : uf(n){ + + sort(edges.begin(), edges.end(), [](const vector& e1, const vector& e2){ + return e1[2] < e2[2]; + }); + + for(const vector& e: edges) + if(!uf.isConnected(e[0], e[1])){ + uf.unionElements(e[0], e[1]); + table[e[2]] = uf.parent; + } + } + + bool query(int p, int q, int limit) { + + map>::iterator iter = table.lower_bound(limit); + if(iter == table.begin() && iter->first >= limit) return false; + + iter --; + return uf.isConnected(p, q, &iter->second); + } +}; + + +int main() { + + vector> edges1 = {{0, 2, 4}, {0, 3, 2}, {1, 2, 3}, {2, 3, 1}, {4, 5, 5}}; + DistanceLimitedPathsExist obj1(6, edges1); + cout << obj1.query(2, 3, 2) << endl; // 1 + cout << obj1.query(1, 3, 3) << endl; // 0 + cout << obj1.query(2, 0, 3) << endl; // 1 + cout << obj1.query(0, 5, 6) << endl; // 0 + + cout << endl; + + vector> edges2 = {{1, 0, 3}, {1, 0, 5}, {1, 2, 1}, {1, 0, 2}, {2, 0, 1}, {0, 1, 3}}; + DistanceLimitedPathsExist obj2(3, edges2); + cout << obj2.query(2, 1, 5) << endl; // 1 + cout << obj2.query(1, 0, 5) << endl; // 1 + cout << obj2.query(2, 1, 3) << endl; // 1 + + return 0; +} diff --git a/1501-2000/1724-Checking-Existence-of-Edge-Length-Limited-Paths-II/cpp-1724/main2.cpp b/1501-2000/1724-Checking-Existence-of-Edge-Length-Limited-Paths-II/cpp-1724/main2.cpp new file mode 100644 index 00000000..35bc4f64 --- /dev/null +++ b/1501-2000/1724-Checking-Existence-of-Edge-Length-Limited-Paths-II/cpp-1724/main2.cpp @@ -0,0 +1,166 @@ +/// Source : https://leetcode.com/problems/checking-existence-of-edge-length-limited-paths-ii/ +/// Author : liuyubobobo +/// Time : 2021-01-14 + +#include +#include +#include + +using namespace std; + + +/// LCA +/// Time Complexity: init: O(ElogE + V) +/// query: O(logV) +/// Space Comoplexity: O(V + E) +class UF{ + +private: + vector parent; + +public: + UF(int n) : parent(n){ + for(int i = 0 ; i < n ; i ++) + parent[i] = i; + } + + int find(int p){ + if(p != parent[p]) + parent[p] = find(parent[p]); + return parent[p]; + } + + bool isConnected(int p, int q){ + return find(p) == find(q); + } + + void unionElements(int p, int q){ + + int pRoot = find(p), qRoot = find(q); + + if(pRoot == qRoot) return; + + parent[pRoot] = qRoot; + } +}; + +class DistanceLimitedPathsExist { + +private: + UF uf; + + const int L; + vector> up, limits; + vector> tree; + + vector tin, tout; + int timer = 0; + +public: + DistanceLimitedPathsExist(int n, vector>& edges) : uf(n), + L((int)ceil(log2(n))), tree(n), tin(n, -1), tout(n), + up(n, vector(L + 1)), limits(n, vector(L + 1)){ + + sort(edges.begin(), edges.end(), [](const vector& e1, const vector& e2){ + return e1[2] < e2[2]; + }); + + for(const vector& e: edges) + if(!uf.isConnected(e[0], e[1])){ + uf.unionElements(e[0], e[1]); + + tree[e[0]][e[1]] = e[2]; + tree[e[1]][e[0]] = e[2]; + } + + timer = 0; + for(int u = 0; u < n; u ++) + if(tin[u] < 0) + dfs(u, u); + } + + bool query(int p, int q, int limit) { + + if(!uf.isConnected(p, q)) return false; + + int x = lca(p, q); + + for(int i = L; i >= 0; i --) + if(is_ancestor(x, up[p][i]) ){ + if(limits[p][i] >= limit) return false; + p = up[p][i]; + } + + for(int i = L; i >= 0; i --) + if(is_ancestor(x,up[q][i])){ + if(limits[q][i] >= limit) return false; + q = up[q][i]; + } + + return true; + } + +private: + void dfs(int u, int p){ + + tin[u] = timer ++; + up[u][0] = p; + limits[u][0] = u == p ? 0 : tree[p][u]; + for(int i = 1; i <= L; i ++) + up[u][i] = up[up[u][i - 1]][i - 1], + limits[u][i] = max(limits[u][i - 1], limits[up[u][i - 1]][i - 1]); + + for(const pair& pa: tree[u]){ + int v = pa.first; + if(v != p){ + tree[v].erase(u); + dfs(v, u); + } + } + + tout[u] = timer ++; + } + + bool is_ancestor(int u, int v){ + return tin[u] <= tin[v] && tout[v] <= tout[u]; + } + + int lca(int u, int v){ + + if(is_ancestor(u, v)) return u; + if(is_ancestor(v, u)) return v; + + for(int i = L; i >= 0; i --) + if(!is_ancestor(up[u][i], v)) + u = up[u][i]; + return up[u][0]; + } +}; + + +int main() { + + vector> edges1 = {{0, 2, 4}, {0, 3, 2}, {1, 2, 3}, {2, 3, 1}, {4, 5, 5}}; + DistanceLimitedPathsExist obj1(6, edges1); + cout << obj1.query(2, 3, 2) << endl; // 1 + cout << obj1.query(1, 3, 3) << endl; // 0 + cout << obj1.query(2, 0, 3) << endl; // 1 + cout << obj1.query(0, 5, 6) << endl; // 0 + + cout << endl; + + vector> edges2 = {{1, 0, 3}, {1, 0, 5}, {1, 2, 1}, {1, 0, 2}, {2, 0, 1}, {0, 1, 3}}; + DistanceLimitedPathsExist obj2(3, edges2); + cout << obj2.query(2, 1, 5) << endl; // 1 + cout << obj2.query(1, 0, 5) << endl; // 1 + cout << obj2.query(2, 1, 3) << endl; // 1 + + cout << endl; + + vector> edges3 = {{0, 1, 3}, {0, 1, 3}, {0, 1, 4}, {0, 1, 1}, {1, 0, 5}, {1, 0, 3}}; + DistanceLimitedPathsExist obj3(2, edges3); + cout << obj3.query(1, 0, 4) << endl; // 1 + cout << obj3.query(1, 0, 1) << endl; // 0 + + return 0; +} diff --git a/1501-2000/1725-Number-Of-Rectangles-That-Can-Form-The-Largest-Square/cpp-1725/CMakeLists.txt b/1501-2000/1725-Number-Of-Rectangles-That-Can-Form-The-Largest-Square/cpp-1725/CMakeLists.txt new file mode 100644 index 00000000..3d34d376 --- /dev/null +++ b/1501-2000/1725-Number-Of-Rectangles-That-Can-Form-The-Largest-Square/cpp-1725/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1725) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1725 main.cpp) \ No newline at end of file diff --git a/1501-2000/1725-Number-Of-Rectangles-That-Can-Form-The-Largest-Square/cpp-1725/main.cpp b/1501-2000/1725-Number-Of-Rectangles-That-Can-Form-The-Largest-Square/cpp-1725/main.cpp new file mode 100644 index 00000000..6556e878 --- /dev/null +++ b/1501-2000/1725-Number-Of-Rectangles-That-Can-Form-The-Largest-Square/cpp-1725/main.cpp @@ -0,0 +1,32 @@ +/// Source : https://leetcode.com/problems/number-of-rectangles-that-can-form-the-largest-square/ +/// Author : liuyubobobo +/// Time : 2021-01-17 + +#include +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int countGoodRectangles(vector>& rectangles) { + + int maxLen = 0, res = 0; + for(const vector& rec: rectangles){ + int len = min(rec[0], rec[1]); + if(len > maxLen) maxLen = len, res = 1; + else if(len == maxLen) res ++; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1726-Tuple-with-Same-Product/cpp-1726/CMakeLists.txt b/1501-2000/1726-Tuple-with-Same-Product/cpp-1726/CMakeLists.txt new file mode 100644 index 00000000..d7e11105 --- /dev/null +++ b/1501-2000/1726-Tuple-with-Same-Product/cpp-1726/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1726) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1726 main.cpp) \ No newline at end of file diff --git a/1501-2000/1726-Tuple-with-Same-Product/cpp-1726/main.cpp b/1501-2000/1726-Tuple-with-Same-Product/cpp-1726/main.cpp new file mode 100644 index 00000000..b6c5c509 --- /dev/null +++ b/1501-2000/1726-Tuple-with-Same-Product/cpp-1726/main.cpp @@ -0,0 +1,51 @@ +/// Source : https://leetcode.com/problems/tuple-with-same-product/ +/// Author : liuyubobobo +/// Time : 2021-01-17 + +#include +#include +#include + +using namespace std; + + +/// HashMap +/// Time Complexity: O(n^2) +/// Space Complexity: O(n^2) +class Solution { +public: + int tupleSameProduct(vector& nums) { + + unordered_map f; + for(int i = 0; i < nums.size(); i ++) + for(int j = i + 1; j < nums.size(); j ++) + f[nums[i] * nums[j]] ++; + + int res = 0; + for(const pair& p: f) + res += 4 * p.second * (p.second - 1); + return res; + } +}; + + +int main() { + + vector nums1 = {2, 3, 4, 6}; + cout << Solution().tupleSameProduct(nums1) << endl; + // 8 + + vector nums2 = {1, 2, 4, 5, 10}; + cout << Solution().tupleSameProduct(nums2) << endl; + // 16 + + vector nums3 = {2, 3, 4, 6, 8, 12}; + cout << Solution().tupleSameProduct(nums3) << endl; + // 40 + + vector nums4 = {2, 3, 5, 7}; + cout << Solution().tupleSameProduct(nums4) << endl; + // 0 + + return 0; +} diff --git a/1501-2000/1727-Largest-Submatrix-With-Rearrangements/cpp-1727/CMakeLists.txt b/1501-2000/1727-Largest-Submatrix-With-Rearrangements/cpp-1727/CMakeLists.txt new file mode 100644 index 00000000..7fae60c0 --- /dev/null +++ b/1501-2000/1727-Largest-Submatrix-With-Rearrangements/cpp-1727/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1727) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1727 main.cpp) \ No newline at end of file diff --git a/1501-2000/1727-Largest-Submatrix-With-Rearrangements/cpp-1727/main.cpp b/1501-2000/1727-Largest-Submatrix-With-Rearrangements/cpp-1727/main.cpp new file mode 100644 index 00000000..05064eb3 --- /dev/null +++ b/1501-2000/1727-Largest-Submatrix-With-Rearrangements/cpp-1727/main.cpp @@ -0,0 +1,66 @@ +/// Source : https://leetcode.com/problems/largest-submatrix-with-rearrangements/ +/// Author : liuyubobobo +/// Time : 2021-01-17 + +#include +#include + +using namespace std; + + +/// DP and Sorting +/// Time Complexity: O(R * ClogC) +/// Space Complexity: O(C) +class Solution { +public: + int largestSubmatrix(vector>& matrix) { + + int R = matrix.size(), C = matrix[0].size(); + + int res = 0; + for(int i = 0; i < R; i ++){ + + vector cur = matrix[i]; + sort(cur.begin(), cur.end()); + + for(int j = C - 1; j >= 0; j --) + res = max(res, cur[j] * (C - j)); + + if(i + 1 < R){ + for(int j = 0; j < C; j ++) + matrix[i + 1][j] = matrix[i + 1][j] == 0 ? 0 : (matrix[i][j] + 1); + } + } + return res; + } +}; + + +int main() { + + vector> matrix1 = { + {0, 0, 1}, {1, 1, 1}, {1, 0, 1} + }; + cout << Solution().largestSubmatrix(matrix1) << endl; + // 4 + + vector> matrix2 = { + {1, 0, 1, 0, 1} + }; + cout << Solution().largestSubmatrix(matrix2) << endl; + // 3 + + vector> matrix3 = { + {1, 1, 0},{1, 0, 1} + }; + cout << Solution().largestSubmatrix(matrix3) << endl; + // 2 + + vector> matrix4 = { + {0, 0},{0, 0} + }; + cout << Solution().largestSubmatrix(matrix4) << endl; + // 0 + + return 0; +} diff --git a/1501-2000/1728-Cat-and-Mouse-II/cpp-1728/CMakeLists.txt b/1501-2000/1728-Cat-and-Mouse-II/cpp-1728/CMakeLists.txt new file mode 100644 index 00000000..026454df --- /dev/null +++ b/1501-2000/1728-Cat-and-Mouse-II/cpp-1728/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1728) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1728 main.cpp) \ No newline at end of file diff --git a/1501-2000/1728-Cat-and-Mouse-II/cpp-1728/main.cpp b/1501-2000/1728-Cat-and-Mouse-II/cpp-1728/main.cpp new file mode 100644 index 00000000..0f951ec1 --- /dev/null +++ b/1501-2000/1728-Cat-and-Mouse-II/cpp-1728/main.cpp @@ -0,0 +1,147 @@ +/// Source : https://leetcode.com/problems/cat-and-mouse-ii/ +/// Author : liuyubobobo +/// Time : 2021-01-18 + +#include +#include +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(MAX_TURN * 2 * R * C * (catJump + mouseJump)) +/// Space Complexity: O(MAX_TURN * 2 * R * C) +class Solution { + +private: + const int dirs[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; + const int MAX_TURN = 64; + int R, C, catJump, mouseJump, foodPos; + +public: + bool canMouseWin(vector& grid, int catJump, int mouseJump) { + + R = grid.size(), C = grid[0].size(); + this->catJump = catJump, this->mouseJump = mouseJump; + + int catPos, mousePos; + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++) + if(grid[i][j] == 'C') catPos = i * C + j, grid[i][j] = '.'; + else if(grid[i][j] == 'M') mousePos = i * C + j, grid[i][j] = '.'; + else if(grid[i][j] == 'F') foodPos = i * C + j, grid[i][j] = '.'; + + vector dp(600000, -1); + return mouseGo(grid, get_state(0, 0, mousePos, catPos), dp); + } + +private: + bool mouseGo(const vector& grid, int state, vector& dp){ + + if(dp[state] != -1) return dp[state]; + + int counter, first, mousePos, catPos; + de_state(state, counter, first, mousePos, catPos); +// assert(first == 0); + + if(counter == MAX_TURN) return dp[state] = false; + + int mx = mousePos / C, my = mousePos % C; + if(!catGo(grid, get_state(counter, 1, mousePos, catPos), dp)) + return dp[state] = true; + + for(int d = 0; d < 4; d ++) + for(int step = 1; step <= mouseJump; step ++){ + int x = mx + dirs[d][0] * step, y = my + dirs[d][1] * step; + if(!in_area(x, y) || grid[x][y] == '#') break; + if(x * C + y == foodPos) return dp[state] = true; + if(x * C + y == catPos) continue; + + int next_state = get_state(counter, 1, x * C + y, catPos); + if(!catGo(grid, next_state, dp)) + return dp[state] = true; + } + return dp[state] = false; + } + + bool catGo(const vector& grid, int state, vector& dp){ + + if(dp[state] != -1) return dp[state]; + + int counter, first, mousePos, catPos; + de_state(state, counter, first, mousePos, catPos); +// assert(first == 1); + + int cx = catPos / C, cy = catPos % C; + if(!mouseGo(grid, get_state(counter + 1, 0, mousePos, catPos), dp)) + return dp[state] = true; + + for(int d = 0; d < 4; d ++) + for(int step = 1; step <= catJump; step ++){ + int x = cx + dirs[d][0] * step, y = cy + dirs[d][1] * step; + if(!in_area(x, y) || grid[x][y] == '#') break; + if(x * C + y == foodPos) return dp[state] = true; + if(x * C + y == mousePos) return dp[state] = true; + + int next_state = get_state(counter + 1, 0, mousePos, x * C + y); + if(!mouseGo(grid, next_state, dp)) + return dp[state] = true; + } + return dp[state] = false; + } + + bool in_area(int x, int y){ + return x >= 0 && x < R && y >= 0 && y < C; + } + + int get_state(int counter, int first, int mousePos, int catPos){ + return counter * 2 * 64 * 64 + first * 64 * 64 + mousePos * 64 + catPos; + } + + void de_state(int state, int& counter, int& first, int& mousePos, int& catPos){ + + catPos = state % 64; + state /= 64; + mousePos = state % 64; + + state /= 64; + + first = state % 2; + counter = state / 2; + } +}; + + +int main() { + + vector grid1 = { + "####F", + "#C...", + "M...." + }; + cout << Solution().canMouseWin(grid1, 1, 2) << endl; + // 1 + + vector grid2 = { + "####.##", + ".#C#F#.", + "######.", + "##M.###" + }; + cout << Solution().canMouseWin(grid2, 3, 6) << endl; + // 0 + + vector grid3 = { + ".M...", + "..#..", + "#..#.", + "C#.#.", + "...#F" + }; + cout << Solution().canMouseWin(grid3, 3, 1) << endl; + // 1 + + return 0; +} diff --git a/1501-2000/1730-Shortest-Path-to-Get-Food/cpp-1730/CMakeLists.txt b/1501-2000/1730-Shortest-Path-to-Get-Food/cpp-1730/CMakeLists.txt new file mode 100644 index 00000000..a2032844 --- /dev/null +++ b/1501-2000/1730-Shortest-Path-to-Get-Food/cpp-1730/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1730) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1730 main.cpp) \ No newline at end of file diff --git a/1501-2000/1730-Shortest-Path-to-Get-Food/cpp-1730/main.cpp b/1501-2000/1730-Shortest-Path-to-Get-Food/cpp-1730/main.cpp new file mode 100644 index 00000000..e3ecf319 --- /dev/null +++ b/1501-2000/1730-Shortest-Path-to-Get-Food/cpp-1730/main.cpp @@ -0,0 +1,56 @@ +/// Source : https://leetcode.com/problems/shortest-path-to-get-food/ +/// Author : liuyubobobo +/// Time : 2021-01-22 + +#include +#include +#include + +using namespace std; + + +/// BFS +/// Time Complexity: O(R * C) +/// Space Complexity: O(R * C) +class Solution { + +private: + const int dirs[4][2] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; + +public: + int getFood(vector>& grid) { + + int R = grid.size(), C = grid[0].size(), s; + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++) + if(grid[i][j] == '*') s = i * C + j; + + vector> dis(R, vector(C, -1)); + queue q; + q.push(s); + dis[s / C][s % C] = 0; + while(!q.empty()){ + + int cur = q.front(); q.pop(); + int curx = cur / C, cury = cur % C; + if(grid[curx][cury] == '#') return dis[curx][cury]; + + for(int d = 0; d < 4; d ++){ + int nextx = curx + dirs[d][0], nexty = cury + dirs[d][1]; + if(nextx >= 0 && nextx < R && nexty >= 0 && nexty < C && + grid[nextx][nexty] != 'X' && dis[nextx][nexty] == -1){ + + dis[nextx][nexty] = dis[curx][cury] + 1; + q.push(nextx * C + nexty); + } + } + } + return -1; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1732-Find-the-Highest-Altitude/cpp-1732/CMakeLists.txt b/1501-2000/1732-Find-the-Highest-Altitude/cpp-1732/CMakeLists.txt new file mode 100644 index 00000000..a62da05f --- /dev/null +++ b/1501-2000/1732-Find-the-Highest-Altitude/cpp-1732/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1732) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1732 main.cpp) \ No newline at end of file diff --git a/1501-2000/1732-Find-the-Highest-Altitude/cpp-1732/main.cpp b/1501-2000/1732-Find-the-Highest-Altitude/cpp-1732/main.cpp new file mode 100644 index 00000000..d0373289 --- /dev/null +++ b/1501-2000/1732-Find-the-Highest-Altitude/cpp-1732/main.cpp @@ -0,0 +1,29 @@ +/// Source : https://leetcode.com/problems/find-the-highest-altitude/ +/// Author : liuyubobobo +/// Time : 2021-01-23 + +#include +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int largestAltitude(vector& gain) { + + int cur = 0, res = 0; + for(int e: gain) + cur += e, res = max(res, cur); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1733-Minimum-Number-of-People-to-Teach/cpp-1733/CMakeLists.txt b/1501-2000/1733-Minimum-Number-of-People-to-Teach/cpp-1733/CMakeLists.txt new file mode 100644 index 00000000..bb4717f1 --- /dev/null +++ b/1501-2000/1733-Minimum-Number-of-People-to-Teach/cpp-1733/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1733) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1733 main.cpp) \ No newline at end of file diff --git a/1501-2000/1733-Minimum-Number-of-People-to-Teach/cpp-1733/main.cpp b/1501-2000/1733-Minimum-Number-of-People-to-Teach/cpp-1733/main.cpp new file mode 100644 index 00000000..dbb2e96c --- /dev/null +++ b/1501-2000/1733-Minimum-Number-of-People-to-Teach/cpp-1733/main.cpp @@ -0,0 +1,63 @@ +/// Source : https://leetcode.com/problems/minimum-number-of-people-to-teach/ +/// Author : liuyubobobo +/// Time : 2021-01-23 + +#include +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n * m) +/// Space Complexity: O(n * m) +class Solution { +public: + int minimumTeachings(int n, vector>& languages, vector>& friendships) { + + int m = languages.size(); + + vector> language_set(m); + for(int i = 0; i < m; i ++) + language_set[i] = unordered_set(languages[i].begin(), languages[i].end()); + + vector> need_teach; + for(vector& v: friendships){ + int a = v[0] - 1, b = v[1] - 1; + bool ok = false; + for(int l: language_set[a]) + if(language_set[b].count(l)){ + ok = true; + break; + } + + if(!ok) need_teach.push_back({a, b}); + } + + if(need_teach.empty()) return 0; + + int res = INT_MAX; + for(int i = 1; i <= n; i ++){ + + unordered_set teach; + for(const vector& f: need_teach){ + if(!language_set[f[0]].count(i)) teach.insert(f[0]); + if(!language_set[f[1]].count(i)) teach.insert(f[1]); + } + res = min(res, (int)teach.size()); + } + return res; + } +}; + + +int main() { + + vector> language1 = {{1}, {2}, {1, 2}}; + vector> friendships1 = {{1, 2}, {1, 3}, {2, 3}}; + cout << Solution().minimumTeachings(2, language1, friendships1) << endl; + // 1 + + return 0; +} diff --git a/1501-2000/1734-Decode-XORed-Permutation/cpp-1734/CMakeLists.txt b/1501-2000/1734-Decode-XORed-Permutation/cpp-1734/CMakeLists.txt new file mode 100644 index 00000000..829a6eff --- /dev/null +++ b/1501-2000/1734-Decode-XORed-Permutation/cpp-1734/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1734) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1734 main.cpp) \ No newline at end of file diff --git a/1501-2000/1734-Decode-XORed-Permutation/cpp-1734/main.cpp b/1501-2000/1734-Decode-XORed-Permutation/cpp-1734/main.cpp new file mode 100644 index 00000000..c4a6f695 --- /dev/null +++ b/1501-2000/1734-Decode-XORed-Permutation/cpp-1734/main.cpp @@ -0,0 +1,36 @@ +/// Source : https://leetcode.com/problems/decode-xored-permutation/ +/// Author : liuyubobobo +/// Time : 2021-01-23 + +#include +#include + +using namespace std; + + +/// Xor +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + vector decode(vector& encoded) { + + int n = encoded.size() + 1; + + int start = 0; + for(int i = 1; i <= n; i ++) start ^= i; + for(int i = 1; i < encoded.size(); i += 2) + start ^= encoded[i]; + + vector res = {start}; + for(int code: encoded) + res.push_back(res.back() ^ code); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1735-Count-Ways-to-Make-Array-With-Product/cpp-1735/CMakeLists.txt b/1501-2000/1735-Count-Ways-to-Make-Array-With-Product/cpp-1735/CMakeLists.txt new file mode 100644 index 00000000..9707f591 --- /dev/null +++ b/1501-2000/1735-Count-Ways-to-Make-Array-With-Product/cpp-1735/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1735) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1735 main2.cpp) \ No newline at end of file diff --git a/1501-2000/1735-Count-Ways-to-Make-Array-With-Product/cpp-1735/main.cpp b/1501-2000/1735-Count-Ways-to-Make-Array-With-Product/cpp-1735/main.cpp new file mode 100644 index 00000000..a609921e --- /dev/null +++ b/1501-2000/1735-Count-Ways-to-Make-Array-With-Product/cpp-1735/main.cpp @@ -0,0 +1,99 @@ +/// Source : https://leetcode.com/problems/count-ways-to-make-array-with-product/ +/// Author : liuyubobobo +/// Time : 2021-01-28 + +#include +#include +#include + +using namespace std; + + +/// Shieve Prime Numbers and using factorials to calculate combinations +/// Time Complexity: O(q + maxk + maxn + maxk * log(maxk) + q * logk) +/// Space Complexity: O(maxk + maxn) +class Solution { + +private: + const long long MOD = 1e9 + 7; + +public: + vector waysToFillArray(vector>& queries) { + + int maxk = 0, maxn = 0; + for(int i = 0; i < queries.size(); i ++){ + maxk = max(maxk, queries[i][1]); + maxn = max(maxn, queries[i][0]); + } + + vector first = shieve(maxk); + + vector fac(maxk + maxn, 1ll); + for(int i = 2; i < fac.size(); i ++) + fac[i] = fac[i - 1] * i % MOD; + + vector ret(queries.size()); + for(int i = 0; i < queries.size(); i ++){ + int n = queries[i][0], k = queries[i][1]; + + unordered_map d; + while(k != 1) d[first[k]] ++, k /= first[k]; + + long long res = 1ll; + for(const pair& p: d) + res = res * put(p.second, n, fac) % MOD; + ret[i] = res; + } + return ret; + } + +private: + // n balls in m boxes, boxes can be empty + int put(int n, int m, vector& fac){ + return C(n + m - 1, m - 1, fac); + } + + int C(int n, int k, vector& fac){ + return fac[n] * mypow(fac[n - k], MOD - 2) % MOD * mypow(fac[k], MOD - 2) % MOD; + } + + long long mypow(long long a, int k){ + + if(k == 0) return 1ll; + if(k == 1) return a; + + long long t = mypow(a, k / 2); + long long res = t * t % MOD; + if(k % 2) res = res * a % MOD; + return res; + } + + vector shieve(int n){ + + vector first(n + 1, 0); + for(int i = 2; i <= n; i ++) + if(first[i] == 0){ + for(int k = i; k <= n; k += i) + first[k] = i; + } + return first; + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << " "; cout << endl; +} + +int main() { + + vector> queries1 = {{2, 6}, {5, 1}, {73, 660}}; + print_vec(Solution().waysToFillArray(queries1)); + // 4 1 50734910 + + vector> queries2 = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}}; + print_vec(Solution().waysToFillArray(queries2)); + // 1 2 3 10 5 + + return 0; +} diff --git a/1501-2000/1735-Count-Ways-to-Make-Array-With-Product/cpp-1735/main2.cpp b/1501-2000/1735-Count-Ways-to-Make-Array-With-Product/cpp-1735/main2.cpp new file mode 100644 index 00000000..4903439a --- /dev/null +++ b/1501-2000/1735-Count-Ways-to-Make-Array-With-Product/cpp-1735/main2.cpp @@ -0,0 +1,80 @@ +/// Source : https://leetcode.com/problems/count-ways-to-make-array-with-product/ +/// Author : liuyubobobo +/// Time : 2021-01-28 + +#include +#include +#include + +using namespace std; + + +/// Shieve Prime Numbers and using dp to calculate combinations +/// Time Complexity: O(q + maxk + maxn + maxk * log(maxk) + q * logk) +/// Space Complexity: O(maxk + maxn) +class Solution { + +private: + const long long MOD = 1e9 + 7; + +public: + vector waysToFillArray(vector>& queries) { + + int maxk = 0, maxn = 0; + for(int i = 0; i < queries.size(); i ++){ + maxk = max(maxk, queries[i][1]); + maxn = max(maxn, queries[i][0]); + } + + vector first = shieve(maxk); + + vector> C(maxk + maxn, vector(32, 1)); + for(int i = 2; i < C.size(); i ++) + for(int j = 1; j < min(i, 32); j ++) + C[i][j] = (C[i - 1][j] + C[i - 1][j - 1]) % MOD; + + vector ret(queries.size()); + for(int i = 0; i < queries.size(); i ++){ + int n = queries[i][0], k = queries[i][1]; + + unordered_map d; + while(k != 1) d[first[k]] ++, k /= first[k]; + + long long res = 1ll; + for(const pair& p: d) + res = res * (long long)C[p.second + n - 1][p.second] % MOD; + ret[i] = res; + } + return ret; + } + +private: + vector shieve(int n){ + + vector first(n + 1, 0); + for(int i = 2; i <= n; i ++) + if(first[i] == 0){ + for(int k = i; k <= n; k += i) + first[k] = i; + } + return first; + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << " "; cout << endl; +} + +int main() { + + vector> queries1 = {{2, 6}, {5, 1}, {73, 660}}; + print_vec(Solution().waysToFillArray(queries1)); + // 4 1 50734910 + + vector> queries2 = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}}; + print_vec(Solution().waysToFillArray(queries2)); + // 1 2 3 10 5 + + return 0; +} diff --git a/1501-2000/1736-Latest-Time-by-Replacing-Hidden-Digits/cpp-1736/CMakeLists.txt b/1501-2000/1736-Latest-Time-by-Replacing-Hidden-Digits/cpp-1736/CMakeLists.txt new file mode 100644 index 00000000..d5d5e4ff --- /dev/null +++ b/1501-2000/1736-Latest-Time-by-Replacing-Hidden-Digits/cpp-1736/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1501-2000/1736-Latest-Time-by-Replacing-Hidden-Digits/cpp-1736/main.cpp b/1501-2000/1736-Latest-Time-by-Replacing-Hidden-Digits/cpp-1736/main.cpp new file mode 100644 index 00000000..799833c3 --- /dev/null +++ b/1501-2000/1736-Latest-Time-by-Replacing-Hidden-Digits/cpp-1736/main.cpp @@ -0,0 +1,62 @@ +/// Source : https://leetcode.com/problems/latest-time-by-replacing-hidden-digits/ +/// Author : liuyubobobo +/// Time : 2021-01-23 + +#include +#include + +using namespace std; + + +/// Backtrack +/// Time Complexity: O(10^4) +/// Space Complexity: O(1) +class Solution { +public: + string maximumTime(string time) { + + return dfs(time, 0); + } + +private: + string dfs(string& time, int index){ + + if(index == time.size()){ + return ok(time) ? time : "00:00"; + } + + if(time[index] != '?') return dfs(time, index + 1); + + string res = "00:00"; + for(char c = '0'; c <= '9'; c ++){ + time[index] = c; + res = max(res, dfs(time, index + 1)); + time[index] = '?'; + } + return res; + } + + bool ok(const string& time){ + int h = atoi(time.substr(0, 2).c_str()); + int m = atoi(time.substr(3).c_str()); + return h >= 0 && h <= 23 && m >= 0 && m <= 59; + } +}; + + +int main() { + + string time1 = "2?:?0"; + cout << Solution().maximumTime(time1) << endl; + // 23:50 + + string time2 = "0?:3?"; + cout << Solution().maximumTime(time2) << endl; + // 09:39 + + string time3 = "1?:22"; + cout << Solution().maximumTime(time3) << endl; + // 19:22 + + return 0; +} diff --git a/1501-2000/1736-Latest-Time-by-Replacing-Hidden-Digits/cpp-1736/main2.cpp b/1501-2000/1736-Latest-Time-by-Replacing-Hidden-Digits/cpp-1736/main2.cpp new file mode 100644 index 00000000..793f2b89 --- /dev/null +++ b/1501-2000/1736-Latest-Time-by-Replacing-Hidden-Digits/cpp-1736/main2.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/latest-time-by-replacing-hidden-digits/ +/// Author : liuyubobobo +/// Time : 2021-01-23 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(1) +/// Space Complexity: O(1) +class Solution { +public: + string maximumTime(string time) { + + if(time[0] == '?'){ + if(time[1] == '?' || time[1] <= '3') time[0] = '2'; + else time[0] = '1'; + } + + if(time[1] == '?'){ + time[1] = time[0] == '2' ? '3' : '9'; + } + + if(time[3] == '?') time[3] = '5'; + if(time[4] == '?') time[4] = '9'; + + return time; + } +}; + + +int main() { + + string time1 = "2?:?0"; + cout << Solution().maximumTime(time1) << endl; + // 23:50 + + string time2 = "0?:3?"; + cout << Solution().maximumTime(time2) << endl; + // 09:39 + + string time3 = "1?:22"; + cout << Solution().maximumTime(time3) << endl; + // 19:22 + + return 0; +} diff --git a/1501-2000/1737-Change-Minimum-Characters-to-Satisfy-One-of-Three-Conditions/cpp-1737/CMakeLists.txt b/1501-2000/1737-Change-Minimum-Characters-to-Satisfy-One-of-Three-Conditions/cpp-1737/CMakeLists.txt new file mode 100644 index 00000000..81ad8b42 --- /dev/null +++ b/1501-2000/1737-Change-Minimum-Characters-to-Satisfy-One-of-Three-Conditions/cpp-1737/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1501-2000/1737-Change-Minimum-Characters-to-Satisfy-One-of-Three-Conditions/cpp-1737/main.cpp b/1501-2000/1737-Change-Minimum-Characters-to-Satisfy-One-of-Three-Conditions/cpp-1737/main.cpp new file mode 100644 index 00000000..a56e6b14 --- /dev/null +++ b/1501-2000/1737-Change-Minimum-Characters-to-Satisfy-One-of-Three-Conditions/cpp-1737/main.cpp @@ -0,0 +1,61 @@ +/// Source : https://leetcode.com/problems/change-minimum-characters-to-satisfy-one-of-three-conditions/ +/// Author : liuyubobobo +/// Time : 2021-01-23 + +#include +#include +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(|a| + |b|) +/// Space Complexity: O(1) +class Solution { +public: + int minCharacters(string a, string b) { + + vector fa(26, 0), fb(26, 0); + for(char c: a) fa[c - 'a'] ++; + for(char c: b) fb[c - 'a'] ++; + + int res = solve_same(fa, a.size(), fb, b.size()); + for(int s = 0; s < 26; s ++) + for(int t = s + 1; t < 26; t ++){ + res = min(res, solve_less(fa, s, fb, t)); + res = min(res, solve_less(fb, s, fa, t)); + } + return res; + } + +private: + int solve_less(const vector& fa, int s, const vector& fb, int t){ + + int res = 0; + res += accumulate(fa.begin() + (s + 1), fa.end(), 0); + res += accumulate(fb.begin(), fb.begin() + t, 0); + return res; + } + + int solve_same(const vector& fa, int lena, const vector& fb, int lenb){ + + int res = INT_MAX; + for(int i = 0; i < 26; i ++) + res = min(res, lena - fa[i] + lenb - fb[i]); + return res; + } +}; + + +int main() { + + cout << Solution().minCharacters("aba", "caa") << endl; + // 2 + + cout << Solution().minCharacters("dabadd", "cda") << endl; + // 3 + + return 0; +} diff --git a/1501-2000/1738-Find-Kth-Largest-XOR-Coordinate-Value/cpp-1738/CMakeLists.txt b/1501-2000/1738-Find-Kth-Largest-XOR-Coordinate-Value/cpp-1738/CMakeLists.txt new file mode 100644 index 00000000..80fb8c61 --- /dev/null +++ b/1501-2000/1738-Find-Kth-Largest-XOR-Coordinate-Value/cpp-1738/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main2.cpp) \ No newline at end of file diff --git a/1501-2000/1738-Find-Kth-Largest-XOR-Coordinate-Value/cpp-1738/main.cpp b/1501-2000/1738-Find-Kth-Largest-XOR-Coordinate-Value/cpp-1738/main.cpp new file mode 100644 index 00000000..62fb4397 --- /dev/null +++ b/1501-2000/1738-Find-Kth-Largest-XOR-Coordinate-Value/cpp-1738/main.cpp @@ -0,0 +1,72 @@ +/// Source : https://leetcode.com/problems/find-kth-largest-xor-coordinate-value/ +/// Author : liuyubobobo +/// Time : 2021-01-23 + +#include +#include + +using namespace std; + + +/// 2D presum + sorting +/// Time Complexity: O(R * C + R * C * log(R * C)) +/// Space Complexity: O(R * C) +class Solution { +public: + int kthLargestValue(vector>& matrix, int k) { + + int R = matrix.size(), C = matrix[0].size(); + + vector> dp(R, vector(C, 0)); + dp[0][0] = matrix[0][0]; + + vector v = {dp[0][0]}; + for(int j = 1; j < C; j ++){ + dp[0][j] = dp[0][j - 1] ^ matrix[0][j]; + v.push_back(dp[0][j]); + } + for(int i = 1; i < R; i ++){ + dp[i][0] = dp[i - 1][0] ^ matrix[i][0]; + v.push_back(dp[i][0]); + } + + for(int i = 1; i < R; i ++) + for(int j = 1; j < C; j ++){ + dp[i][j] = matrix[i][j] ^ dp[i - 1][j] ^ dp[i][j - 1] ^ dp[i - 1][j - 1]; + v.push_back(dp[i][j]); + } + + sort(v.begin(), v.end(), greater()); + return v[k - 1]; + } +}; + + +int main() { + + vector> m1 = { + {5, 2}, {1, 6} + }; + cout << Solution().kthLargestValue(m1, 1) << endl; + // 7 + + vector> m2 = { + {5, 2}, {1, 6} + }; + cout << Solution().kthLargestValue(m2, 2) << endl; + // 5 + + vector> m3 = { + {5, 2}, {1, 6} + }; + cout << Solution().kthLargestValue(m3, 3) << endl; + // 4 + + vector> m4 = { + {5, 2}, {1, 6} + }; + cout << Solution().kthLargestValue(m4, 4) << endl; + // 0 + + return 0; +} diff --git a/1501-2000/1738-Find-Kth-Largest-XOR-Coordinate-Value/cpp-1738/main2.cpp b/1501-2000/1738-Find-Kth-Largest-XOR-Coordinate-Value/cpp-1738/main2.cpp new file mode 100644 index 00000000..3241cc97 --- /dev/null +++ b/1501-2000/1738-Find-Kth-Largest-XOR-Coordinate-Value/cpp-1738/main2.cpp @@ -0,0 +1,79 @@ +/// Source : https://leetcode.com/problems/find-kth-largest-xor-coordinate-value/ +/// Author : liuyubobobo +/// Time : 2021-01-23 + +#include +#include +#include + +using namespace std; + + +/// 2D presum + priority queue +/// Time Complexity: O(R * C + R * C * logk) +/// Space Complexity: O(R * C) +class Solution { +public: + int kthLargestValue(vector>& matrix, int k) { + + int R = matrix.size(), C = matrix[0].size(); + + vector> dp(R, vector(C, 0)); + dp[0][0] = matrix[0][0]; + + priority_queue, greater> pq; + pq.push(dp[0][0]); + for(int j = 1; j < C; j ++){ + dp[0][j] = dp[0][j - 1] ^ matrix[0][j]; + if(pq.size() >= k && dp[0][j] > pq.top()) + pq.pop(); + if(pq.size() < k) pq.push(dp[0][j]); + } + for(int i = 1; i < R; i ++){ + dp[i][0] = dp[i - 1][0] ^ matrix[i][0]; + if(pq.size() >= k && dp[i][0] > pq.top()) + pq.pop(); + if(pq.size() < k) pq.push(dp[i][0]); + } + + for(int i = 1; i < R; i ++) + for(int j = 1; j < C; j ++){ + dp[i][j] = matrix[i][j] ^ dp[i - 1][j] ^ dp[i][j - 1] ^ dp[i - 1][j - 1]; + if(pq.size() >= k && dp[i][j] > pq.top()) + pq.pop(); + if(pq.size() < k) pq.push(dp[i][j]); + } + + return pq.top(); + } +}; + + +int main() { + + vector> m1 = { + {5, 2}, {1, 6} + }; + cout << Solution().kthLargestValue(m1, 1) << endl; + // 7 + + vector> m2 = { + {5, 2}, {1, 6} + }; + cout << Solution().kthLargestValue(m2, 2) << endl; + // 5 + + vector> m3 = { + {5, 2}, {1, 6} + }; + cout << Solution().kthLargestValue(m3, 3) << endl; + // 4 + + vector> m4 = { + {5, 2}, {1, 6} + }; + cout << Solution().kthLargestValue(m4, 4) << endl; + // 0 + + return 0; +} diff --git a/1501-2000/1739-Building-Boxes/cpp-1739/CMakeLists.txt b/1501-2000/1739-Building-Boxes/cpp-1739/CMakeLists.txt new file mode 100644 index 00000000..74cc3ee6 --- /dev/null +++ b/1501-2000/1739-Building-Boxes/cpp-1739/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) \ No newline at end of file diff --git a/1501-2000/1739-Building-Boxes/cpp-1739/main.cpp b/1501-2000/1739-Building-Boxes/cpp-1739/main.cpp new file mode 100644 index 00000000..0bba3737 --- /dev/null +++ b/1501-2000/1739-Building-Boxes/cpp-1739/main.cpp @@ -0,0 +1,45 @@ +/// Source : https://leetcode.com/problems/building-boxes/ +/// Author : liuyubobobo +/// Time : 2021-01-23 + +#include + +using namespace std; + + +/// Mathematics +/// Time Complexity: O(sqrt(n)) +/// Space Complexity: O(1) +class Solution { +public: + int minimumBoxes(int n) { + + int total = 0, res = 0; + for(int h = 1; h <= n && total < n; h ++){ + for(int x = 1; x <= h && total < n; x ++) + total += x, res ++; + } + return res; + } +}; + + +int main() { + + cout << Solution().minimumBoxes(3) << endl; + // 3 + + cout << Solution().minimumBoxes(4) << endl; + // 3 + + cout << Solution().minimumBoxes(10) << endl; + // 6 + + cout << Solution().minimumBoxes(11) << endl; + // 7 + + cout << Solution().minimumBoxes(1e9) << endl; + // 1650467 + + return 0; +} diff --git a/1501-2000/1740-Find-Distance-in-a-Binary-Tree/cpp-1740/CMakeLists.txt b/1501-2000/1740-Find-Distance-in-a-Binary-Tree/cpp-1740/CMakeLists.txt new file mode 100644 index 00000000..582f3330 --- /dev/null +++ b/1501-2000/1740-Find-Distance-in-a-Binary-Tree/cpp-1740/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1740) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1740 main.cpp) \ No newline at end of file diff --git a/1501-2000/1740-Find-Distance-in-a-Binary-Tree/cpp-1740/main.cpp b/1501-2000/1740-Find-Distance-in-a-Binary-Tree/cpp-1740/main.cpp new file mode 100644 index 00000000..0a0a6acd --- /dev/null +++ b/1501-2000/1740-Find-Distance-in-a-Binary-Tree/cpp-1740/main.cpp @@ -0,0 +1,63 @@ +/// Source : https://leetcode.com/problems/find-distance-in-a-binary-tree/ +/// Author : liuyubobobo +/// Time : 2021-01-28 + +#include +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(h) + +/// 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: + int findDistance(TreeNode* root, int p, int q) { + + vector pv, qv; + dfs(root, p, pv); + dfs(root, q, qv); + + assert(pv.back() == p && qv.back() == q); + + int i; + for(i = 0; i < pv.size() && i < qv.size(); i ++) + if(pv[i] != qv[i]) break; + + return pv.size() - i + qv.size() - i; + } + +private: + bool dfs(TreeNode* node, int t, vector& v){ + + if(!node) return false; + + v.push_back(node->val); + if(t == node->val) return true; + + if(dfs(node->left, t, v)) return true; + if(dfs(node->right, t, v)) return true; + + v.pop_back(); + return false; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1742-Maximum-Number-of-Balls-in-a-Box/cpp-1742/CMakeLists.txt b/1501-2000/1742-Maximum-Number-of-Balls-in-a-Box/cpp-1742/CMakeLists.txt new file mode 100644 index 00000000..d5d5e4ff --- /dev/null +++ b/1501-2000/1742-Maximum-Number-of-Balls-in-a-Box/cpp-1742/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1501-2000/1742-Maximum-Number-of-Balls-in-a-Box/cpp-1742/main.cpp b/1501-2000/1742-Maximum-Number-of-Balls-in-a-Box/cpp-1742/main.cpp new file mode 100644 index 00000000..01c86aac --- /dev/null +++ b/1501-2000/1742-Maximum-Number-of-Balls-in-a-Box/cpp-1742/main.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/maximum-number-of-balls-in-a-box/ +/// Author : liuyubobobo +/// Time : 2021-01-30 + +#include +#include + +using namespace std; + + +/// Using HashMap +/// Time Complexity: O((h - l) * log(h)) +/// Space Complexity: O(h - l) +class Solution { +public: + int countBalls(int lowLimit, int highLimit) { + + unordered_map f; + int res = 0; + for(int i = lowLimit; i <= highLimit; i ++){ + int k = hash(i); + f[k] ++; + res = max(res, f[k]); + } + return res; + } + +private: + int hash(int x){ + + int sum = 0; + while(x){ + sum += x % 10; + x /= 10; + } + return sum; + } +}; + + +int main() { + + cout << Solution().countBalls(1, 10) << endl; + // 2 + + cout << Solution().countBalls(5, 15) << endl; + // 2 + + cout << Solution().countBalls(19, 28) << endl; + // 2 + + return 0; +} diff --git a/1501-2000/1743-Restore-the-Array-From-Adjacent-Pairs/cpp-1743/CMakeLists.txt b/1501-2000/1743-Restore-the-Array-From-Adjacent-Pairs/cpp-1743/CMakeLists.txt new file mode 100644 index 00000000..81ad8b42 --- /dev/null +++ b/1501-2000/1743-Restore-the-Array-From-Adjacent-Pairs/cpp-1743/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1501-2000/1743-Restore-the-Array-From-Adjacent-Pairs/cpp-1743/main.cpp b/1501-2000/1743-Restore-the-Array-From-Adjacent-Pairs/cpp-1743/main.cpp new file mode 100644 index 00000000..3097f957 --- /dev/null +++ b/1501-2000/1743-Restore-the-Array-From-Adjacent-Pairs/cpp-1743/main.cpp @@ -0,0 +1,62 @@ +/// Source : https://leetcode.com/problems/restore-the-array-from-adjacent-pairs/ +/// Author : liuyubobobo +/// Time : 2021-01-30 + +#include +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector restoreArray(vector>& adjacentPairs) { + + unordered_map> g; + for(const vector& p: adjacentPairs) + g[p[0]].push_back(p[1]), g[p[1]].push_back(p[0]); + + int start = -1; + for(const pair>& p: g) + if(p.second.size() == 1){ + start = p.first; + break; + } + + vector res = {start}; + int cur = g[start][0]; + while(g[cur].size() > 1){ + res.push_back(cur); + cur = g[cur][0] == res[res.size() - 2] ? g[cur][1] : g[cur][0]; + } + res.push_back(cur); + + return res; + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << " "; cout << endl; +} + +int main() { + + vector> pair1 = {{2, 1}, {3, 4}, {3, 2}}; + print_vec(Solution().restoreArray(pair1)); + // 1 2 3 4 + + vector> pair2 = {{4, -2}, {1, 4}, {-3, 1}}; + print_vec(Solution().restoreArray(pair2)); + // -2 4 1 -3 + + vector> pair3 = {{100000, -100000}}; + print_vec(Solution().restoreArray(pair3)); + // 100000, -100000 + + return 0; +} diff --git a/1501-2000/1744-Can-You-Eat-Your-Favorite-Candy-on-Your-Favorite-Day/cpp-1744/CMakeLists.txt b/1501-2000/1744-Can-You-Eat-Your-Favorite-Candy-on-Your-Favorite-Day/cpp-1744/CMakeLists.txt new file mode 100644 index 00000000..ce73aee9 --- /dev/null +++ b/1501-2000/1744-Can-You-Eat-Your-Favorite-Candy-on-Your-Favorite-Day/cpp-1744/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1501-2000/1744-Can-You-Eat-Your-Favorite-Candy-on-Your-Favorite-Day/cpp-1744/main.cpp b/1501-2000/1744-Can-You-Eat-Your-Favorite-Candy-on-Your-Favorite-Day/cpp-1744/main.cpp new file mode 100644 index 00000000..41e0298c --- /dev/null +++ b/1501-2000/1744-Can-You-Eat-Your-Favorite-Candy-on-Your-Favorite-Day/cpp-1744/main.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/can-you-eat-your-favorite-candy-on-your-favorite-day/ +/// Author : liuyubobobo +/// Time : 2021-01-30 + +#include +#include + +using namespace std; + + +/// Presum +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector canEat(vector& candiesCount, vector>& queries) { + + int n = candiesCount.size(); + vector presum(n + 1, 0ll); + for(int i = 0; i < n; i ++) + presum[i + 1] = presum[i] + candiesCount[i]; + + vector res(queries.size()); + for(int i = 0; i < queries.size(); i ++){ + int type = queries[i][0], day = queries[i][1], cap = queries[i][2]; + + if(day >= presum[type + 1]) res[i] = false; + else if((long long)(day + 1) * cap <= presum[type]) res[i] = false; + else res[i] = true; + } + return res; + } +}; + + +void print_vec(const vector& v){ + for(bool e: v) cout << e << " "; cout << endl; +} + +int main() { + + vector candies1 = {7, 4, 5, 3, 8}; + vector> queries1 = {{0, 2, 2}, {4, 2, 4}, {2, 13, 1000000000}}; + print_vec(Solution().canEat(candies1, queries1)); + // 1 0 1 + + vector candies2 = {5,2,6,4,1}; + vector> queries2 = {{3, 1, 2}, {4, 10, 3}, {3, 10, 100}, {4, 100, 30}, {1, 3, 1}}; + print_vec(Solution().canEat(candies2, queries2)); + // 0 1 1 0 0 + + return 0; +} diff --git a/1501-2000/1745-Palindrome-Partitioning-IV/cpp-1745/CMakeLists.txt b/1501-2000/1745-Palindrome-Partitioning-IV/cpp-1745/CMakeLists.txt new file mode 100644 index 00000000..74cc3ee6 --- /dev/null +++ b/1501-2000/1745-Palindrome-Partitioning-IV/cpp-1745/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) \ No newline at end of file diff --git a/1501-2000/1745-Palindrome-Partitioning-IV/cpp-1745/main.cpp b/1501-2000/1745-Palindrome-Partitioning-IV/cpp-1745/main.cpp new file mode 100644 index 00000000..91981401 --- /dev/null +++ b/1501-2000/1745-Palindrome-Partitioning-IV/cpp-1745/main.cpp @@ -0,0 +1,48 @@ +/// Source : https://leetcode.com/problems/palindrome-partitioning-iv/ +/// Author : liuyubobobo +/// Time : 2021-01-30 + +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(|s|^2) +/// Space Complexity: O(|s|^2) +class Solution { +public: + bool checkPartitioning(string s) { + + int n = s.size(); + vector> dp(n + 1, vector()); + + dp[1] = vector(n, true); + for(int i = 0; i + 1 < n; i ++) + dp[2].push_back(s[i] == s[i + 1]); + + for(int sz = 3; sz <= n; sz ++) + for(int i = 0; i + sz <= n; i ++) + dp[sz].push_back((s[i] == s[i + sz - 1]) && dp[sz - 2][i + 1]); + + // [0 .. i - 1] [i .. j - 1] [j ... n - 1] + for(int i = 1; i < n; i ++) + for(int j = i + 1; j < n; j ++) + if(dp[i][0] && dp[j - i][i] && dp[n - j][j]) + return true; + return false; + } +}; + + +int main() { + + cout << Solution().checkPartitioning("abcbdd") << endl; + // 1 + + cout << Solution().checkPartitioning("bcbddxy") << endl; + // 0 + + return 0; +} diff --git a/1501-2000/1746-Maximum-Subarray-Sum-After-One-Operation/cpp-1746/CMakeLists.txt b/1501-2000/1746-Maximum-Subarray-Sum-After-One-Operation/cpp-1746/CMakeLists.txt new file mode 100644 index 00000000..fa77dcab --- /dev/null +++ b/1501-2000/1746-Maximum-Subarray-Sum-After-One-Operation/cpp-1746/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1746) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1746 main2.cpp) \ No newline at end of file diff --git a/1501-2000/1746-Maximum-Subarray-Sum-After-One-Operation/cpp-1746/main.cpp b/1501-2000/1746-Maximum-Subarray-Sum-After-One-Operation/cpp-1746/main.cpp new file mode 100644 index 00000000..921c9f20 --- /dev/null +++ b/1501-2000/1746-Maximum-Subarray-Sum-After-One-Operation/cpp-1746/main.cpp @@ -0,0 +1,95 @@ +/// Source : https://leetcode.com/problems/maximum-subarray-sum-after-one-operation/ +/// Author : liuyubobobo +/// Time : 2021-02-05 + +#include +#include + +using namespace std; + + +/// Presum + Segment Tree +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class MinSegmentTree{ + +private: + int n; + vector data, tree; + +public: + MinSegmentTree(const vector& data): n(data.size()), data(data), tree(4 * n, 0){ + buildSegTree(0, 0, n - 1); + } + + int query(int l, int r){ + return query(0, 0, n - 1, l, r); + } + +private: + void buildSegTree(int treeID, int l, int r){ + + if(l == r){ + tree[treeID] = data[l]; + return; + } + + int mid = (l + r) / 2; + buildSegTree(treeID * 2 + 1, l, mid); + buildSegTree(treeID * 2 + 2, mid + 1, r); + tree[treeID] = min(tree[treeID * 2 + 1], tree[treeID * 2 + 2]); + return; + } + + int query(int treeID, int l, int r, int ql, int qr){ + + if(ql == l && qr == r) + return tree[treeID]; + + int mid = (l + r) / 2; + if(qr <= mid) return query(treeID * 2 + 1, l, mid, ql, qr); + else if(ql > mid) return query(treeID * 2 + 2, mid + 1, r, ql, qr); + + int resl = query(treeID * 2 + 1, l, mid, ql, mid); + int resr = query(treeID * 2 + 2, mid + 1, r, mid + 1, qr); + return min(resl, resr); + } +}; + +class Solution { +public: + int maxSumAfterOperation(vector& nums) { + + int n = nums.size(); + vector presum(n + 1, 0), sufsum(n + 1, 0); + + for(int i = 0; i < n; i ++) + presum[i + 1] = presum[i] + nums[i]; + for(int i = n - 1; i >= 0; i --) + sufsum[i] = sufsum[i + 1] + nums[i]; + + MinSegmentTree pretree(presum), suftree(sufsum); + int res = INT_MIN; + for(int i = 0; i < n; i ++){ + int tres = nums[i] * nums[i]; + tres += presum[i] - pretree.query(0, i); + tres += sufsum[i + 1] - suftree.query(i + 1, n); + res = max(res, tres); + } + return res; + } +}; + + +int main() { + + vector nums1 = {2, -1, -4, -3}; + cout << Solution().maxSumAfterOperation(nums1) << endl; + // 17 + + vector nums2 = {1,-1,1,1,-1,-1,1}; + cout << Solution().maxSumAfterOperation(nums2) << endl; + // 4 + + return 0; +} diff --git a/1501-2000/1746-Maximum-Subarray-Sum-After-One-Operation/cpp-1746/main2.cpp b/1501-2000/1746-Maximum-Subarray-Sum-After-One-Operation/cpp-1746/main2.cpp new file mode 100644 index 00000000..2bc5142b --- /dev/null +++ b/1501-2000/1746-Maximum-Subarray-Sum-After-One-Operation/cpp-1746/main2.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/maximum-subarray-sum-after-one-operation/ +/// Author : liuyubobobo +/// Time : 2021-02-05 + +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int maxSumAfterOperation(vector& nums) { + + int n = nums.size(); + if(n == 1) return nums[0] * nums[0]; + + vector dp1(n, nums[0]); + for(int i = 1; i < n; i ++) + dp1[i] = max(dp1[i - 1] + nums[i], nums[i]); + + vector dp2(n, nums.back()); + for(int i = n - 2; i >= 0; i --) + dp2[i] = max(dp2[i + 1] + nums[i], nums[i]); + + int res = max(nums[0] * nums[0] + dp2[1], nums.back() * nums.back() + dp1[n - 2]); + for(int i = 1; i < n - 1; i ++){ + int tres = nums[i] * nums[i] + max(0, dp1[i - 1]) + max(0, dp2[i + 1]); + res = max(res, tres); + } + return res; + } +}; + + +int main() { + + vector nums1 = {2, -1, -4, -3}; + cout << Solution().maxSumAfterOperation(nums1) << endl; + // 17 + + vector nums2 = {1,-1,1,1,-1,-1,1}; + cout << Solution().maxSumAfterOperation(nums2) << endl; + // 4 + + return 0; +} diff --git a/1501-2000/1748-Sum-of-Unique-Elements/cpp-1748/CMakeLists.txt b/1501-2000/1748-Sum-of-Unique-Elements/cpp-1748/CMakeLists.txt new file mode 100644 index 00000000..f3987a4a --- /dev/null +++ b/1501-2000/1748-Sum-of-Unique-Elements/cpp-1748/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1748) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1748 main.cpp) \ No newline at end of file diff --git a/1501-2000/1748-Sum-of-Unique-Elements/cpp-1748/main.cpp b/1501-2000/1748-Sum-of-Unique-Elements/cpp-1748/main.cpp new file mode 100644 index 00000000..e28f485b --- /dev/null +++ b/1501-2000/1748-Sum-of-Unique-Elements/cpp-1748/main.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/sum-of-unique-elements/ +/// Author : liuyubobobo +/// Time : 2021-02-06 + +#include +#include +#include + +using namespace std; + + +/// HashMap +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int sumOfUnique(vector& nums) { + + unordered_map f; + for(int e: nums) f[e] ++; + + int res = 0; + for(const pair& p: f) + if(p.second == 1) res += p.first; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1749-Maximum-Absolute-Sum-of-Any-Subarray/cpp-1749/CMakeLists.txt b/1501-2000/1749-Maximum-Absolute-Sum-of-Any-Subarray/cpp-1749/CMakeLists.txt new file mode 100644 index 00000000..8b0882e0 --- /dev/null +++ b/1501-2000/1749-Maximum-Absolute-Sum-of-Any-Subarray/cpp-1749/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1749) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1749 main2.cpp) \ No newline at end of file diff --git a/1501-2000/1749-Maximum-Absolute-Sum-of-Any-Subarray/cpp-1749/main.cpp b/1501-2000/1749-Maximum-Absolute-Sum-of-Any-Subarray/cpp-1749/main.cpp new file mode 100644 index 00000000..f13c1b65 --- /dev/null +++ b/1501-2000/1749-Maximum-Absolute-Sum-of-Any-Subarray/cpp-1749/main.cpp @@ -0,0 +1,44 @@ +/// Source : https://leetcode.com/problems/maximum-absolute-sum-of-any-subarray/ +/// Author : liuyubobobo +/// Time : 2021-02-06 + +#include +#include + +using namespace std; + + +/// Presum +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int maxAbsoluteSum(vector& nums) { + + int n = nums.size(); + vector presum(n + 1, 0); + for(int i = 0; i < nums.size(); i ++) presum[i + 1] = presum[i] + nums[i]; + + int res = 0; + + int pmin = 0; + for(int i = 1; i <= n; i ++){ + pmin = min(pmin, presum[i - 1]); + res = max(res, abs(presum[i] - pmin)); + } + + int pmax = 0; + for(int i = 1; i <= n; i ++){ + pmax = max(pmax, presum[i - 1]); + res = max(res, abs(presum[i] - pmax)); + } + + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1749-Maximum-Absolute-Sum-of-Any-Subarray/cpp-1749/main2.cpp b/1501-2000/1749-Maximum-Absolute-Sum-of-Any-Subarray/cpp-1749/main2.cpp new file mode 100644 index 00000000..4f15b889 --- /dev/null +++ b/1501-2000/1749-Maximum-Absolute-Sum-of-Any-Subarray/cpp-1749/main2.cpp @@ -0,0 +1,42 @@ +/// Source : https://leetcode.com/problems/maximum-absolute-sum-of-any-subarray/ +/// Author : liuyubobobo +/// Time : 2021-02-06 + +#include +#include + +using namespace std; + + +/// Presum +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int maxAbsoluteSum(vector& nums) { + + int n = nums.size(), res = 0; + + int pmin = 0, pmax = 0, presum = 0; + for(int i = 0; i < n; i ++){ + pmin = min(pmin, presum); + presum += nums[i]; + res = max(res, abs(presum - pmin)); + } + + presum = 0; + for(int i = 0; i < n; i ++){ + pmax = max(pmax, presum); + presum += nums[i]; + res = max(res, abs(presum - pmax)); + } + + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1750-Minimum-Length-of-String-After-Deleting-Similar-Ends/cpp-1750/CMakeLists.txt b/1501-2000/1750-Minimum-Length-of-String-After-Deleting-Similar-Ends/cpp-1750/CMakeLists.txt new file mode 100644 index 00000000..dd2bed8a --- /dev/null +++ b/1501-2000/1750-Minimum-Length-of-String-After-Deleting-Similar-Ends/cpp-1750/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1750) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1750 main.cpp) \ No newline at end of file diff --git a/1501-2000/1750-Minimum-Length-of-String-After-Deleting-Similar-Ends/cpp-1750/main.cpp b/1501-2000/1750-Minimum-Length-of-String-After-Deleting-Similar-Ends/cpp-1750/main.cpp new file mode 100644 index 00000000..88f328a9 --- /dev/null +++ b/1501-2000/1750-Minimum-Length-of-String-After-Deleting-Similar-Ends/cpp-1750/main.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/minimum-length-of-string-after-deleting-similar-ends/ +/// Author : liuyubobobo +/// Time : 2021-02-06 + +#include + +using namespace std; + + +/// Two Pointers +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int minimumLength(string s) { + + int l = 0, r = s.size() - 1; + while(l < r && s[l] == s[r]){ + char c = s[l]; + while(l < r && s[l] == c) l ++; + while(l <= r && s[r] == c) r --; + } + return r - l + 1; + } +}; + + +int main() { + + cout << Solution().minimumLength("ca") << endl; + // 2 + + cout << Solution().minimumLength("cabaabac") << endl; + // 0 + + cout << Solution().minimumLength("aabccabba") << endl; + // 3 + + return 0; +} diff --git a/1501-2000/1751-Maximum-Number-of-Events-That-Can-Be-Attended-II/cpp-1751/CMakeLists.txt b/1501-2000/1751-Maximum-Number-of-Events-That-Can-Be-Attended-II/cpp-1751/CMakeLists.txt new file mode 100644 index 00000000..11a87969 --- /dev/null +++ b/1501-2000/1751-Maximum-Number-of-Events-That-Can-Be-Attended-II/cpp-1751/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1751) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1751 main.cpp) \ No newline at end of file diff --git a/1501-2000/1751-Maximum-Number-of-Events-That-Can-Be-Attended-II/cpp-1751/main.cpp b/1501-2000/1751-Maximum-Number-of-Events-That-Can-Be-Attended-II/cpp-1751/main.cpp new file mode 100644 index 00000000..501bba9c --- /dev/null +++ b/1501-2000/1751-Maximum-Number-of-Events-That-Can-Be-Attended-II/cpp-1751/main.cpp @@ -0,0 +1,64 @@ +/// Source : https://leetcode.com/problems/maximum-number-of-events-that-can-be-attended-ii/ +/// Author : liuyubobobo +/// Time : 2021-02-06 + +#include +#include + +using namespace std; + + +/// DP + Binary Search +/// Time Complexity: O(nlogn + nklogn) +/// Space Complexity: O(nk) +class Solution { +public: + int maxValue(vector>& events, int k) { + + sort(events.begin(), events.end()); + + int n = events.size(); + vector> dp(n, vector(k)); + + int res = events[n - 1][2]; + dp[n - 1][0] = events[n - 1][2]; + for(int i = n - 2; i >= 0; i --){ + dp[i][0] = max(events[i][2], dp[i + 1][0]); + res = max(res, dp[i][0]); + } + + for(int j = 1; j < k; j ++){ + dp[n - 1][j] = events[n - 1][2]; + for(int i = n - 2; i >= 0; i --){ + dp[i][j] = dp[i + 1][j]; + int x = binary_search(events, i + 1, n - 1, events[i][1] + 1); + if(x < n) + dp[i][j] = max(dp[i][j], events[i][2] + dp[x][j - 1]); + res = max(res, dp[i][j]); + } + } + return res; + } + +private: + int binary_search(const vector>& events, int L, int R, int t){ + + int l = L, r = R + 1; + while(l < r){ + int mid = (l + r) / 2; + if(events[mid][0] < t) l = mid + 1; + else r = mid; + } + return l; + } +}; + + +int main() { + + vector> events1 = {{1, 2, 4}, {2, 3, 10}, {3, 4, 3}}; + cout << Solution().maxValue(events1, 2) << endl; + // 10 + + return 0; +} diff --git a/1501-2000/1752-Check-if-Array-Is-Sorted-and-Rotated/cpp-1752/CMakeLists.txt b/1501-2000/1752-Check-if-Array-Is-Sorted-and-Rotated/cpp-1752/CMakeLists.txt new file mode 100644 index 00000000..ec9e7c4c --- /dev/null +++ b/1501-2000/1752-Check-if-Array-Is-Sorted-and-Rotated/cpp-1752/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main2.cpp) \ No newline at end of file diff --git a/1501-2000/1752-Check-if-Array-Is-Sorted-and-Rotated/cpp-1752/main.cpp b/1501-2000/1752-Check-if-Array-Is-Sorted-and-Rotated/cpp-1752/main.cpp new file mode 100644 index 00000000..382057b0 --- /dev/null +++ b/1501-2000/1752-Check-if-Array-Is-Sorted-and-Rotated/cpp-1752/main.cpp @@ -0,0 +1,41 @@ +/// Source : https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/ +/// Author : liuyubobobo +/// Time : 2021-02-06 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n^2) +/// Space Complexity: O(1) +class Solution { +public: + bool check(vector& nums) { + + for(int i = 0; i < nums.size(); i ++) + if(ok(nums, i)) return true; + return false; + } + +private: + bool ok(const vector& nums, int start){ + + int n = nums.size(); + for(int i = 1; i < n; i ++) + if(nums[(start + i) % n] < nums[(start + i - 1) % n]) return false; + return true; + } +}; + + +int main() { + + vector nums1 = {2, 1, 3, 4}; + cout << Solution().check(nums1) << endl; + // 0 + + return 0; +} diff --git a/1501-2000/1752-Check-if-Array-Is-Sorted-and-Rotated/cpp-1752/main2.cpp b/1501-2000/1752-Check-if-Array-Is-Sorted-and-Rotated/cpp-1752/main2.cpp new file mode 100644 index 00000000..294d9675 --- /dev/null +++ b/1501-2000/1752-Check-if-Array-Is-Sorted-and-Rotated/cpp-1752/main2.cpp @@ -0,0 +1,43 @@ +/// Source : https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/ +/// Author : liuyubobobo +/// Time : 2021-02-06 + +#include +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + bool check(vector& nums) { + + int i; + for(i = 1; i < nums.size(); i ++) + if(nums[i - 1] > nums[i]) + break; + + if(i == nums.size()) return true; + + for(int j = i + 1; j < nums.size(); j ++) + if(nums[j] < nums[j - 1]) return false; + return nums[0] >= nums.back(); + } +}; + + +int main() { + + vector nums1 = {2, 1, 3, 4}; + cout << Solution().check(nums1) << endl; + // 0 + + vector nums2 = {3, 4, 5, 1, 2}; + cout << Solution().check(nums2) << endl; + // 1 + + return 0; +} diff --git a/1501-2000/1753-Maximum-Score-From-Removing-Stones/cpp-1753/CMakeLists.txt b/1501-2000/1753-Maximum-Score-From-Removing-Stones/cpp-1753/CMakeLists.txt new file mode 100644 index 00000000..aab7d499 --- /dev/null +++ b/1501-2000/1753-Maximum-Score-From-Removing-Stones/cpp-1753/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main4.cpp) \ No newline at end of file diff --git a/1501-2000/1753-Maximum-Score-From-Removing-Stones/cpp-1753/main.cpp b/1501-2000/1753-Maximum-Score-From-Removing-Stones/cpp-1753/main.cpp new file mode 100644 index 00000000..d043a570 --- /dev/null +++ b/1501-2000/1753-Maximum-Score-From-Removing-Stones/cpp-1753/main.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/maximum-score-from-removing-stones/ +/// Author : liuyubobobo +/// Time : 2021-02-06 + +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(min(a, b, c)) +/// Space Complexity: O(1) +class Solution { +public: + int maximumScore(int a, int b, int c) { + + vector v = {a, b, c}; + sort(v.begin(), v.end()); + + int limit = min(a, b); + int res = 0; + for(int i = 0; i <= limit; i ++) + res = max(res, i + solve(v[0] - i, v[1] - i, v[2])); + return res; + } + +private: + int solve(int a, int b, int c){ + return min(a + b, c); + } +}; + + +int main() { + + cout << Solution().maximumScore(2, 4, 6) << endl; + // 6 + + cout << Solution().maximumScore(4, 4, 6) << endl; + // 7 + + cout << Solution().maximumScore(1, 8, 8) << endl; + // 8 + + return 0; +} diff --git a/1501-2000/1753-Maximum-Score-From-Removing-Stones/cpp-1753/main2.cpp b/1501-2000/1753-Maximum-Score-From-Removing-Stones/cpp-1753/main2.cpp new file mode 100644 index 00000000..a90ccb90 --- /dev/null +++ b/1501-2000/1753-Maximum-Score-From-Removing-Stones/cpp-1753/main2.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/maximum-score-from-removing-stones/ +/// Author : liuyubobobo +/// Time : 2021-02-06 + +#include +#include +#include + +using namespace std; + + +/// Greedy + Priority Queue +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + int maximumScore(int a, int b, int c) { + + priority_queue pq; + pq.push(a), pq.push(b), pq.push(c); + int res = 0; + while(true){ + int x= pq.top(); pq.pop(); + int y = pq.top(); pq.pop(); + if(y == 0) break; + res += 1; + pq.push(x - 1), pq.push(y - 1); + } + return res; + } +}; + + +int main() { + + cout << Solution().maximumScore(2, 4, 6) << endl; + // 6 + + cout << Solution().maximumScore(4, 4, 6) << endl; + // 7 + + cout << Solution().maximumScore(1, 8, 8) << endl; + // 8 + + return 0; +} diff --git a/1501-2000/1753-Maximum-Score-From-Removing-Stones/cpp-1753/main3.cpp b/1501-2000/1753-Maximum-Score-From-Removing-Stones/cpp-1753/main3.cpp new file mode 100644 index 00000000..4fbec231 --- /dev/null +++ b/1501-2000/1753-Maximum-Score-From-Removing-Stones/cpp-1753/main3.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/maximum-score-from-removing-stones/ +/// Author : liuyubobobo +/// Time : 2021-02-06 + +#include +#include +#include + +using namespace std; + + +/// Greedy + Priority Queue + Optimization +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + int maximumScore(int a, int b, int c) { + + priority_queue pq; + pq.push(a), pq.push(b), pq.push(c); + int res = 0; + while(true){ + int x= pq.top(); pq.pop(); + int y = pq.top(); pq.pop(); + if(y == 0) break; + + int z = pq.top(); + if(z == 0){ + res += min(x, y); + break; + } + + int t = y - (z - 1); + res += t; + pq.push(x - t), pq.push(y - t); + } + return res; + } +}; + + +int main() { + + cout << Solution().maximumScore(2, 4, 6) << endl; + // 6 + + cout << Solution().maximumScore(4, 4, 6) << endl; + // 7 + + cout << Solution().maximumScore(1, 8, 8) << endl; + // 8 + + return 0; +} diff --git a/1501-2000/1753-Maximum-Score-From-Removing-Stones/cpp-1753/main4.cpp b/1501-2000/1753-Maximum-Score-From-Removing-Stones/cpp-1753/main4.cpp new file mode 100644 index 00000000..59eeb256 --- /dev/null +++ b/1501-2000/1753-Maximum-Score-From-Removing-Stones/cpp-1753/main4.cpp @@ -0,0 +1,39 @@ +/// Source : https://leetcode.com/problems/maximum-score-from-removing-stones/ +/// Author : liuyubobobo +/// Time : 2021-02-06 + +#include +#include +#include + +using namespace std; + + +/// Mathematics +/// Time Complexity: O(1) +/// Space Complexity: O(1) +class Solution { +public: + int maximumScore(int a, int b, int c) { + + if(a >= b + c) return b + c; + if(b >= a + c) return a + c; + if(c >= a + b) return a + b; + return (a + b + c) / 2; + } +}; + + +int main() { + + cout << Solution().maximumScore(2, 4, 6) << endl; + // 6 + + cout << Solution().maximumScore(4, 4, 6) << endl; + // 7 + + cout << Solution().maximumScore(1, 8, 8) << endl; + // 8 + + return 0; +} diff --git a/1501-2000/1754-Largest-Merge-Of-Two-Strings/cpp-1754/CMakeLists.txt b/1501-2000/1754-Largest-Merge-Of-Two-Strings/cpp-1754/CMakeLists.txt new file mode 100644 index 00000000..ce73aee9 --- /dev/null +++ b/1501-2000/1754-Largest-Merge-Of-Two-Strings/cpp-1754/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1501-2000/1754-Largest-Merge-Of-Two-Strings/cpp-1754/main.cpp b/1501-2000/1754-Largest-Merge-Of-Two-Strings/cpp-1754/main.cpp new file mode 100644 index 00000000..b803410c --- /dev/null +++ b/1501-2000/1754-Largest-Merge-Of-Two-Strings/cpp-1754/main.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/largest-merge-of-two-strings/ +/// Author : liuyubobobo +/// Time : 2021-02-06 + +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O((m + n) * max(m, n)) +/// Space Complexity: O(max(m, n)) +class Solution { +public: + string largestMerge(string word1, string word2) { + + int n = word1.size(), m = word2.size(); + + string res = ""; + int i = 0, j = 0; + while(i <= n && j <= m){ + if(i == n){ + res += word2.substr(j); + break; + } + else if(j == m){ + res += word1.substr(i); + break; + } + else if(word1[i] > word2[j]) + res += word1[i], i ++; + else if(word1[i] < word2[j]) + res += word2[j], j ++; + else if(word1.substr(i + 1) > word2.substr(j + 1)) + res += word1[i], i ++; + else + res += word2[j], j ++; + } + return res; + } +}; + + +int main() { + + cout << Solution().largestMerge("cabaa", "bcaaa") << endl; + // "cbcabaaaaa" + + cout << Solution().largestMerge("abcabc", "abdcaba") << endl; + // "abdcabcabcaba" + + cout << Solution().largestMerge("abc", "abd") << endl; + // "abdabc" + + return 0; +} diff --git a/1501-2000/1754-Largest-Merge-Of-Two-Strings/cpp-1754/main2.cpp b/1501-2000/1754-Largest-Merge-Of-Two-Strings/cpp-1754/main2.cpp new file mode 100644 index 00000000..16a0050e --- /dev/null +++ b/1501-2000/1754-Largest-Merge-Of-Two-Strings/cpp-1754/main2.cpp @@ -0,0 +1,66 @@ +/// Source : https://leetcode.com/problems/largest-merge-of-two-strings/ +/// Author : liuyubobobo +/// Time : 2021-02-06 + +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O((m + n) * max(m, n)) +/// Space Complexity: O(max(m, n)) +class Solution { +public: + string largestMerge(string word1, string word2) { + + int n = word1.size(), m = word2.size(); + + string res = ""; + int i = 0, j = 0; + while(i <= n && j <= m){ + if(i == n){ + res += word2.substr(j); + break; + } + else if(j == m){ + res += word1.substr(i); + break; + } + else if(word1[i] > word2[j]) + res += word1[i], i ++; + else if(word1[i] < word2[j]) + res += word2[j], j ++; + else if(greater(word1, i + 1, word2, j + 1)) + res += word1[i], i ++; + else + res += word2[j], j ++; + } + return res; + } + +private: + bool greater(const string& s1, int i, const string& s2, int j){ + + while(i < s1.size() && j < s2.size()) + if(s1[i] != s2[j]) return s1[i] > s2[j]; + else i ++, j ++; + return i < s1.size(); + } +}; + + +int main() { + + cout << Solution().largestMerge("cabaa", "bcaaa") << endl; + // "cbcabaaaaa" + + cout << Solution().largestMerge("abcabc", "abdcaba") << endl; + // "abdcabcabcaba" + + cout << Solution().largestMerge("abc", "abd") << endl; + // "abdabc" + + return 0; +} diff --git a/1501-2000/1755-Closest-Subsequence-Sum/cpp-1755/CMakeLists.txt b/1501-2000/1755-Closest-Subsequence-Sum/cpp-1755/CMakeLists.txt new file mode 100644 index 00000000..a373769d --- /dev/null +++ b/1501-2000/1755-Closest-Subsequence-Sum/cpp-1755/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main2.cpp) \ No newline at end of file diff --git a/1501-2000/1755-Closest-Subsequence-Sum/cpp-1755/main.cpp b/1501-2000/1755-Closest-Subsequence-Sum/cpp-1755/main.cpp new file mode 100644 index 00000000..d54d4cca --- /dev/null +++ b/1501-2000/1755-Closest-Subsequence-Sum/cpp-1755/main.cpp @@ -0,0 +1,75 @@ +/// Source : https://leetcode.com/problems/closest-subsequence-sum/ +/// Author : liuyubobobo +/// Time : 2021-02-06 + +#include +#include + +using namespace std; + + +/// Halve and Binary Search +/// Time Comelixity: O(2^(n/2) + nlogn) +/// Space Complexity: O(2^(n/2)) +class Solution { +public: + int minAbsDifference(vector& nums, int goal) { + + if(nums.size() == 1) return min(abs(goal), abs(nums[0] - goal)); + + int n = nums.size(); + vector a, b; + for(int i = 0; i < n / 2; i ++) a.push_back(nums[i]); + for(int i = n / 2; i < n; i ++) b.push_back(nums[i]); + + vector A = get(a), B = get(b); +// for(int e: A) cout << e << " "; cout << endl; +// for(int e: B) cout << e << " "; cout << endl; + sort(B.begin(), B.end()); + + int res = abs(goal); + for(int e: A){ + vector::iterator iter = lower_bound(B.begin(), B.end(), goal - e); + if(iter != B.end()) res = min(res, abs(e + *iter - goal)); + if(iter != B.begin()){ + iter --; + res = min(res, abs(e + *iter - goal)); + } + } + return res; + } + +private: + vector get(const vector& nums){ + + int n = nums.size(), p; + vector res(1 << n, 0); + for(int i = 1; i < (1 << n); i ++){ + p = __builtin_ffs(i) - 1; + res[i] = nums[p] + res[i - (1 << p)]; + } + return res; + } +}; + + +int main() { + + vector nums1 = {5, -7, 3, 5}; + cout << Solution().minAbsDifference(nums1, 6) << endl; + // 0 + + vector nums2 = {7, -9, 15, -2}; + cout << Solution().minAbsDifference(nums2, -5) << endl; + // 1 + + vector nums3 = {1, 2, 3}; + cout << Solution().minAbsDifference(nums3, -7) << endl; + // 7 + + vector nums4 = {1556913,-259675,-7667451,-4380629,-4643857,-1436369,7695949,-4357992,-842512,-118463}; + cout << Solution().minAbsDifference(nums4, -9681425) << endl; + // 10327 + + return 0; +} diff --git a/1501-2000/1755-Closest-Subsequence-Sum/cpp-1755/main2.cpp b/1501-2000/1755-Closest-Subsequence-Sum/cpp-1755/main2.cpp new file mode 100644 index 00000000..11bd4ce0 --- /dev/null +++ b/1501-2000/1755-Closest-Subsequence-Sum/cpp-1755/main2.cpp @@ -0,0 +1,75 @@ +/// Source : https://leetcode.com/problems/closest-subsequence-sum/ +/// Author : liuyubobobo +/// Time : 2021-02-06 + +#include +#include + +using namespace std; + + +/// Halve and Two Pointers +/// Time Comelixity: O(2^(n/2) + nlogn) +/// Space Complexity: O(2^(n/2)) +class Solution { +public: + int minAbsDifference(vector& nums, int goal) { + + if(nums.size() == 1) return min(abs(goal), abs(nums[0] - goal)); + + int n = nums.size(); + vector a, b; + for(int i = 0; i < n / 2; i ++) a.push_back(nums[i]); + for(int i = n / 2; i < n; i ++) b.push_back(nums[i]); + + vector A = get(a), B = get(b); +// for(int e: A) cout << e << " "; cout << endl; +// for(int e: B) cout << e << " "; cout << endl; + sort(A.begin(), A.end()); + sort(B.begin(), B.end()); + + int res = abs(goal); + int l = 0, r = B.size() - 1; + while(l < A.size() && r >= 0){ + int t = A[l] + B[r] - goal; + res = min(res, abs(t)); + if(t <= 0) l ++; + else r --; + } + return res; + } + +private: + vector get(const vector& nums){ + + int n = nums.size(), p; + vector res(1 << n, 0); + for(int i = 1; i < (1 << n); i ++){ + p = __builtin_ffs(i) - 1; + res[i] = nums[p] + res[i - (1 << p)]; + } + return res; + } +}; + + +int main() { + + vector nums1 = {5, -7, 3, 5}; + cout << Solution().minAbsDifference(nums1, 6) << endl; + // 0 + + vector nums2 = {7, -9, 15, -2}; + cout << Solution().minAbsDifference(nums2, -5) << endl; + // 1 + + vector nums3 = {1, 2, 3}; + cout << Solution().minAbsDifference(nums3, -7) << endl; + // 7 + + vector nums4 = {1556913,-259675,-7667451,-4380629,-4643857,-1436369,7695949,-4357992,-842512,-118463}; + cout << Solution().minAbsDifference(nums4, -9681425) << endl; + // 10327 + + return 0; +} diff --git a/1501-2000/1756-Design-Most-Recently-Used-Queue/cpp-1756/CMakeLists.txt b/1501-2000/1756-Design-Most-Recently-Used-Queue/cpp-1756/CMakeLists.txt new file mode 100644 index 00000000..efb51580 --- /dev/null +++ b/1501-2000/1756-Design-Most-Recently-Used-Queue/cpp-1756/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1756) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1756 main2.cpp) \ No newline at end of file diff --git a/1501-2000/1756-Design-Most-Recently-Used-Queue/cpp-1756/main.cpp b/1501-2000/1756-Design-Most-Recently-Used-Queue/cpp-1756/main.cpp new file mode 100644 index 00000000..3bdd2235 --- /dev/null +++ b/1501-2000/1756-Design-Most-Recently-Used-Queue/cpp-1756/main.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/design-most-recently-used-queue/ +/// Author : liuyubobobo +/// Time : 2021-02-10 + +#include +#include + +using namespace std; + + +/// Using Arrays +/// Time Complexity: init: O(n) +/// fetch: O(n) +/// Space Complexity: O(n) +class MRUQueue { + +private: + vector q; + +public: + MRUQueue(int n) : q(n) { + for(int i = 0; i < n; i ++) q[i] = i + 1; + } + + int fetch(int k) { + k --; + int ret = q[k]; + for(int i = k + 1; i < q.size(); i ++) + q[i - 1] = q[i]; + q.back() = ret; +// for(int e: q) cout << e << " "; cout << endl; + return ret; + } +}; + + +int main() { + + MRUQueue q(8); + cout << q.fetch(3) << endl; // 3 + cout << q.fetch(5) << endl; // 6 + cout << q.fetch(2) << endl; // 2 + cout << q.fetch(8) << endl; // 2 + + return 0; +} diff --git a/1501-2000/1756-Design-Most-Recently-Used-Queue/cpp-1756/main2.cpp b/1501-2000/1756-Design-Most-Recently-Used-Queue/cpp-1756/main2.cpp new file mode 100644 index 00000000..175d16df --- /dev/null +++ b/1501-2000/1756-Design-Most-Recently-Used-Queue/cpp-1756/main2.cpp @@ -0,0 +1,329 @@ +/// Source : https://leetcode.com/problems/design-most-recently-used-queue/ +/// Author : liuyubobobo +/// Time : 2021-02-10 + +#include +#include + +using namespace std; + + +/// Using AVL Tree +/// Time Complexity: init: O(nlogn) +/// fetch: O(logn) +/// Space Complexity: O(n) +template +class AVLTree{ + +private: + class Node{ + public: + Key key; + Value value; + Node *left = nullptr, *right = nullptr; + int height = 1, size = 1; + + Node(const Key& key, const Value& value): key(key), value(value){} + }; + + Node* root = nullptr; + +public: + AVLTree(){} + + int size(){ + return size(root); + } + + // 向二分搜索树中添加新的元素(key, value) + void add(const Key& key, const Value& value){ + root = add(root, key, value); + } + + bool contains(const Key& key){ + return getNode(root, key) != nullptr; + } + + Value get(const Key& key){ + Node* node = getNode(root, key); + assert(node); + return node->value; + } + + void set(const Key& key, const Value& newValue){ + Node* node = getNode(root, key); + assert(node); + node->value = newValue; + } + + // 从二分搜索树中删除键为key的节点 + Value remove(const Key& key){ + + Node* node = getNode(root, key); + assert(node); + + root = remove(root, key); + return node->value; + } + + int rank(const Key& key){ + + Node* node = getNode(root, key); + assert(node); + + return rank(root, key); + } + + Key select(int rank){ + return select(root, rank); + } + +private: + int size(Node* node){ + return node ? node->size : 0; + } + + int height(Node* node){ + return node ? node->height : 0; + } + + int getBalanceFactor(Node* node){ + return height(node->left) - height(node->right); + } + + // 对节点y进行向右旋转操作,返回旋转后新的根节点x + // y x + // / \ / \ + // x T4 向右旋转 (y) z y + // / \ - - - - - - - -> / \ / \ + // z T3 T1 T2 T3 T4 + // / \ + // T1 T2 + Node* rightRotate(Node* y) { + Node* x = y->left; + Node* T3 = x->right; + + // 向右旋转过程 + x->right = y; + y->left = T3; + + // 更新 height 和 size + y->height = max(height(y->left), height(y->right)) + 1; + x->height = max(height(x->left), height(x->right)) + 1; + + y->size = size(y->left) + size(y->right) + 1; + x->size = size(x->left) + size(x->right) + 1; + + return x; + } + + // 对节点y进行向左旋转操作,返回旋转后新的根节点x + // y x + // / \ / \ + // T1 x 向左旋转 (y) y z + // / \ - - - - - - - -> / \ / \ + // T2 z T1 T2 T3 T4 + // / \ + // T3 T4 + Node* leftRotate(Node* y) { + Node* x = y->right; + Node* T2 = x->left; + + // 向左旋转过程 + x->left = y; + y->right = T2; + + // 更新 height 和 size + y->height = max(height(y->left), height(y->right)) + 1; + x->height = max(height(x->left), height(x->right)) + 1; + + y->size = size(y->left) + size(y->right) + 1; + x->size = size(x->left) + size(x->right) + 1; + + return x; + } + + // 向以node为根的二分搜索树中插入元素(key, value),递归算法 + // 返回插入新节点后二分搜索树的根 + Node* add(Node* node, const Key& key, const Value& value){ + + if(node == nullptr){ + return new Node(key, value); + } + + if(key < node->key) + node->left = add(node->left, key, value); + else if(key > node->key) + node->right = add(node->right, key, value); + else // key.compareTo(node.key) == 0 + node->value = value; + + // 更新 height 和 size + node->height = 1 + max(height(node->left), height(node->right)); + node->size = 1 + size(node->left) + size(node->right); + + // 计算平衡因子 + int balanceFactor = getBalanceFactor(node); + + // 平衡维护 + // LL + if (balanceFactor > 1 && getBalanceFactor(node->left) >= 0) + return rightRotate(node); + + // RR + if (balanceFactor < -1 && getBalanceFactor(node->right) <= 0) + return leftRotate(node); + + // LR + if (balanceFactor > 1 && getBalanceFactor(node->left) < 0) { + node->left = leftRotate(node->left); + return rightRotate(node); + } + + // RL + if (balanceFactor < -1 && getBalanceFactor(node->right) > 0) { + node->right = rightRotate(node->right); + return leftRotate(node); + } + + return node; + } + + // 返回以node为根节点的二分搜索树中,key所在的节点 + Node* getNode(Node* node, const Key& key){ + + if(node == nullptr) + return nullptr; + + if(key == node->key) + return node; + else if(key < node->key) + return getNode(node->left, key); + else // if(key.compareTo(node.key) > 0) + return getNode(node->right, key); + } + + // 返回以node为根的二分搜索树的最小值所在的节点 + Node* minimum(Node* node){ + if(!node->left) return node; + return minimum(node->left); + } + + Node* remove(Node* node, const Key& key){ + + if(node == nullptr) return nullptr; + + Node* retNode; + if(key < node->key){ + node->left = remove(node->left, key); + retNode = node; + } + else if(key > node->key){ + node->right = remove(node->right, key); + retNode = node; + } + else{ // key == node.key + + if(node->left == nullptr){ // 待删除节点左子树为空的情况 + Node* rightNode = node->right; + node->right = nullptr; + retNode = rightNode; + } + else if(node->right == nullptr){ // 待删除节点右子树为空的情况 + Node* leftNode = node->left; + node->left = nullptr; + retNode = leftNode; + } + else{ // 待删除节点左右子树均不为空的情况 + // 找到比待删除节点大的最小节点, 即待删除节点右子树的最小节点 + // 用这个节点顶替待删除节点的位置 + Node* successor = minimum(node->right); + successor->right = remove(node->right, successor->key); + successor->left = node->left; + + node->left = node->right = nullptr; + + retNode = successor; + } + } + + if(retNode == nullptr) return nullptr; + + // 更新 height 和 size + retNode->height = 1 + max(height(retNode->left), height(retNode->right)); + retNode->size = 1 + size(retNode->left) + size(retNode->right); + + // 计算平衡因子 + int balanceFactor = getBalanceFactor(retNode); + + // 平衡维护 + // LL + if (balanceFactor > 1 && getBalanceFactor(retNode->left) >= 0) + return rightRotate(retNode); + + // RR + if (balanceFactor < -1 && getBalanceFactor(retNode->right) <= 0) + return leftRotate(retNode); + + // LR + if (balanceFactor > 1 && getBalanceFactor(retNode->left) < 0) { + retNode->left = leftRotate(retNode->left); + return rightRotate(retNode); + } + + // RL + if (balanceFactor < -1 && getBalanceFactor(retNode->right) > 0) { + retNode->right = rightRotate(retNode->right); + return leftRotate(retNode); + } + + return retNode; + } + + int rank(Node* node, const Key& key){ + if(key == node->key) return size(node->left) + 1; + if(key < node->key) return rank(node->left, key); + return size(node->left) + 1 + rank(node->right, key); + } + + int select(Node* node, int rank){ + + if(size(node->left) == rank) return node->key; + + if(rank < size(node->left)) return select(node->left, rank); + return select(node->right, rank - size(node->left) - 1); + } +}; + +class MRUQueue { + +private: + int maxid; + AVLTree tree; + +public: + MRUQueue(int n) : maxid(n) { + for(int i = 0; i < n; i ++) + tree.add(i, i + 1); + } + + int fetch(int k) { + k --; + int key = tree.select(k), value = tree.get(key); + tree.remove(key); + tree.add(maxid ++, value); + return value; + } +}; + + +int main() { + + MRUQueue q(8); + cout << q.fetch(3) << endl; // 3 + cout << q.fetch(5) << endl; // 6 + cout << q.fetch(2) << endl; // 2 + cout << q.fetch(8) << endl; // 2 + + return 0; +} diff --git a/1501-2000/1758-Minimum-Changes-To-Make-Alternating-Binary-String/cpp-1758/CMakeLists.txt b/1501-2000/1758-Minimum-Changes-To-Make-Alternating-Binary-String/cpp-1758/CMakeLists.txt new file mode 100644 index 00000000..ec9e7c4c --- /dev/null +++ b/1501-2000/1758-Minimum-Changes-To-Make-Alternating-Binary-String/cpp-1758/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main2.cpp) \ No newline at end of file diff --git a/1501-2000/1758-Minimum-Changes-To-Make-Alternating-Binary-String/cpp-1758/main.cpp b/1501-2000/1758-Minimum-Changes-To-Make-Alternating-Binary-String/cpp-1758/main.cpp new file mode 100644 index 00000000..bc2592a9 --- /dev/null +++ b/1501-2000/1758-Minimum-Changes-To-Make-Alternating-Binary-String/cpp-1758/main.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/minimum-changes-to-make-alternating-binary-string/ +/// Author : liuyubobobo +/// Time : 2021-02-13 + +#include +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int minOperations(string s) { + + int res = INT_MAX; + + string s1(s.size(), '0'); + for(int i = 0; i < s1.size(); i += 2) + s1[i] = '1'; + res = min(res, diff(s, s1)); + + string s2(s.size(), '0'); + for(int i = 1; i < s2.size(); i += 2) + s2[i] = '1'; + res = min(res, diff(s, s2)); + + return res; + } + +private: + int diff(const string& s1, const string& s2){ + + int res = 0; + for(int i = 0; i < s1.size(); i ++) + res += (s1[i] != s2[i]); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1758-Minimum-Changes-To-Make-Alternating-Binary-String/cpp-1758/main2.cpp b/1501-2000/1758-Minimum-Changes-To-Make-Alternating-Binary-String/cpp-1758/main2.cpp new file mode 100644 index 00000000..e38c02c6 --- /dev/null +++ b/1501-2000/1758-Minimum-Changes-To-Make-Alternating-Binary-String/cpp-1758/main2.cpp @@ -0,0 +1,31 @@ +/// Source : https://leetcode.com/problems/minimum-changes-to-make-alternating-binary-string/ +/// Author : liuyubobobo +/// Time : 2021-02-13 + +#include +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int minOperations(string s) { + + int res1 = 0, res2 = 0; + for(int i = 0; i < s.size(); i ++){ + res1 += s[i] != ('0' + i % 2); + res2 += s[i] == ('0' + i % 2); + } + return min(res1, res2); + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1759-Count-Number-of-Homogenous-Substrings/cpp-1759/CMakeLists.txt b/1501-2000/1759-Count-Number-of-Homogenous-Substrings/cpp-1759/CMakeLists.txt new file mode 100644 index 00000000..81ad8b42 --- /dev/null +++ b/1501-2000/1759-Count-Number-of-Homogenous-Substrings/cpp-1759/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1501-2000/1759-Count-Number-of-Homogenous-Substrings/cpp-1759/main.cpp b/1501-2000/1759-Count-Number-of-Homogenous-Substrings/cpp-1759/main.cpp new file mode 100644 index 00000000..8a4cbd96 --- /dev/null +++ b/1501-2000/1759-Count-Number-of-Homogenous-Substrings/cpp-1759/main.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/count-number-of-homogenous-substrings/ +/// Author : liuyubobobo +/// Time : 2021-02-13 + +#include +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int countHomogenous(string s) { + + long long res = 0ll, MOD = 1e9 + 7; + for(int start = 0, i = 1; i <= s.size(); i ++) + if(i == s.size() || s[i] != s[start]){ + + int len = i - start; + res += (1ll + (long long)len) * (long long)len / 2ll; + res %= MOD; + + start = i; + i = start; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1760-Minimum-Limit-of-Balls-in-a-Bag/cpp-1760/CMakeLists.txt b/1501-2000/1760-Minimum-Limit-of-Balls-in-a-Bag/cpp-1760/CMakeLists.txt new file mode 100644 index 00000000..ce73aee9 --- /dev/null +++ b/1501-2000/1760-Minimum-Limit-of-Balls-in-a-Bag/cpp-1760/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1501-2000/1760-Minimum-Limit-of-Balls-in-a-Bag/cpp-1760/main.cpp b/1501-2000/1760-Minimum-Limit-of-Balls-in-a-Bag/cpp-1760/main.cpp new file mode 100644 index 00000000..48d892d0 --- /dev/null +++ b/1501-2000/1760-Minimum-Limit-of-Balls-in-a-Bag/cpp-1760/main.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/minimum-limit-of-balls-in-a-bag/ +/// Author : liuyubobobo +/// Time : 2021-02-13 + +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(nlog(max_num)) +/// Space Complexity: O(1) +class Solution { +public: + int minimumSize(vector& nums, int maxOperations) { + + int l = 1, r = *max_element(nums.begin(), nums.end()), k = nums.size() + maxOperations; + while(l < r){ + int mid = (l + r) / 2; + if(ok(nums, mid, k)) r = mid; + else l = mid + 1; + } + return l; + } + +private: + bool ok(const vector& nums, int k, int n){ + + int sum = 0; + for(int num: nums) + sum += num / k + !!(num % k); + return sum <= n; + } +}; + + +int main() { + + vector nums1 = {9}; + cout << Solution().minimumSize(nums1, 2) << endl; + // 3 + + vector nums2 = {2, 4, 8, 2}; + cout << Solution().minimumSize(nums2, 4) << endl; + // 2 + + vector nums3 = {7, 17}; + cout << Solution().minimumSize(nums3, 2) << endl; + // 7 + + return 0; +} diff --git a/1501-2000/1761-Minimum-Degree-of-a-Connected-Trio-in-a-Graph/cpp-1761/CMakeLists.txt b/1501-2000/1761-Minimum-Degree-of-a-Connected-Trio-in-a-Graph/cpp-1761/CMakeLists.txt new file mode 100644 index 00000000..74cc3ee6 --- /dev/null +++ b/1501-2000/1761-Minimum-Degree-of-a-Connected-Trio-in-a-Graph/cpp-1761/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) \ No newline at end of file diff --git a/1501-2000/1761-Minimum-Degree-of-a-Connected-Trio-in-a-Graph/cpp-1761/main.cpp b/1501-2000/1761-Minimum-Degree-of-a-Connected-Trio-in-a-Graph/cpp-1761/main.cpp new file mode 100644 index 00000000..2b74bde2 --- /dev/null +++ b/1501-2000/1761-Minimum-Degree-of-a-Connected-Trio-in-a-Graph/cpp-1761/main.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/minimum-degree-of-a-connected-trio-in-a-graph/ +/// Author : liuyubobobo +/// Time : 2021-02-13 + +#include +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n^3) +/// Space Complexity: O(n^2) +class Solution { +public: + int minTrioDegree(int n, vector>& edges) { + + vector> table(n, vector(n, false)); + vector degree(n, 0); + for(const vector& e: edges){ + table[e[0] - 1][e[1] - 1] = table[e[1] - 1][e[0] - 1] = 1; + degree[e[0] - 1] ++; + degree[e[1] - 1] ++; + } + + int res = INT_MAX; + for(int u = 0; u < n; u ++) + for(int v = u + 1; v < n; v ++) + if(table[u][v]) + for(int w = v + 1; w < n; w ++) + if(table[u][w] && table[v][w]) + res = min(res, degree[u] + degree[v] + degree[w] - 6); + return res == INT_MAX ? -1 : res; + } +}; + + +int main() { + + vector> edges1 = { + {1,2},{1,3},{3,2},{4,1},{5,2},{3,6} + }; + cout << Solution().minTrioDegree(6, edges1) << endl; + // 3 + + vector> edges2 = { + {1,3},{4,1},{4,3},{2,5},{5,6},{6,7},{7,5},{2,6} + }; + cout << Solution().minTrioDegree(7, edges2) << endl; + // 0 + + return 0; +} diff --git a/1501-2000/1762-Buildings-With-an-Ocean-View/cpp-1762/CMakeLists.txt b/1501-2000/1762-Buildings-With-an-Ocean-View/cpp-1762/CMakeLists.txt new file mode 100644 index 00000000..34456228 --- /dev/null +++ b/1501-2000/1762-Buildings-With-an-Ocean-View/cpp-1762/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1762) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1762 main.cpp) \ No newline at end of file diff --git a/1501-2000/1762-Buildings-With-an-Ocean-View/cpp-1762/main.cpp b/1501-2000/1762-Buildings-With-an-Ocean-View/cpp-1762/main.cpp new file mode 100644 index 00000000..503ee746 --- /dev/null +++ b/1501-2000/1762-Buildings-With-an-Ocean-View/cpp-1762/main.cpp @@ -0,0 +1,31 @@ +/// Source : https://leetcode.com/problems/buildings-with-an-ocean-view/ +/// Author : liuyubobobo +/// Time : 2021-02-18 + +#include +#include + +using namespace std; + + +/// Mono Stack +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + vector findBuildings(vector& heights) { + + vector res = {(int)heights.size() - 1}; + for(int i = heights.size() - 2; i >= 0; i --) + if(heights[i] > heights[res.back()]) res.push_back(i); + + reverse(res.begin(), res.end()); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1763-Longest-Nice-Substring/cpp-1763/CMakeLists.txt b/1501-2000/1763-Longest-Nice-Substring/cpp-1763/CMakeLists.txt new file mode 100644 index 00000000..b10f516b --- /dev/null +++ b/1501-2000/1763-Longest-Nice-Substring/cpp-1763/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1763) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1763 main3.cpp) \ No newline at end of file diff --git a/1501-2000/1763-Longest-Nice-Substring/cpp-1763/main.cpp b/1501-2000/1763-Longest-Nice-Substring/cpp-1763/main.cpp new file mode 100644 index 00000000..c940c216 --- /dev/null +++ b/1501-2000/1763-Longest-Nice-Substring/cpp-1763/main.cpp @@ -0,0 +1,44 @@ +/// Source : https://leetcode.com/problems/longest-nice-substring/ +/// Author : liuyubobobo +/// Time : 2021-02-20 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n^3) +/// Space Complexity: O(1) +class Solution { +public: + string longestNiceSubstring(string s) { + + string res = ""; + for(int i = 0; i < s.size(); i ++) + for(int len = 2; i + len <= s.size(); len ++) + if(ok(s.substr(i, len)) && len > res.size()) + res = s.substr(i, len); + return res; + } + +private: + bool ok(const string& s){ + + vector lower(26, false), upper(26, false); + for(char c: s) + if(islower(c)) lower[c - 'a'] = true; + else upper[c - 'A'] = true; + + for(int i = 0; i < 26; i ++) + if(lower[i] ^ upper[i]) return false; + return true; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1763-Longest-Nice-Substring/cpp-1763/main2.cpp b/1501-2000/1763-Longest-Nice-Substring/cpp-1763/main2.cpp new file mode 100644 index 00000000..d86d4044 --- /dev/null +++ b/1501-2000/1763-Longest-Nice-Substring/cpp-1763/main2.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/longest-nice-substring/ +/// Author : liuyubobobo +/// Time : 2021-02-20 + +#include +#include + +using namespace std; + + +/// Brute Force with Optimization +/// Time Complexity: O(n^2) +/// Space Complexity: O(1) +class Solution { +public: + string longestNiceSubstring(string s) { + + string res = ""; + for(int i = 0; i < s.size(); i ++){ + vector lower(26, false), upper(26, false); + for(int j = i; j < s.size(); j ++){ + if(islower(s[j])) lower[s[j] - 'a'] = true; + else upper[s[j] - 'A'] = true; + + if((lower == upper) && (j - i + 1) > (int)res.size()) + res = s.substr(i, j - i + 1); + } + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1763-Longest-Nice-Substring/cpp-1763/main3.cpp b/1501-2000/1763-Longest-Nice-Substring/cpp-1763/main3.cpp new file mode 100644 index 00000000..5b78161f --- /dev/null +++ b/1501-2000/1763-Longest-Nice-Substring/cpp-1763/main3.cpp @@ -0,0 +1,38 @@ +/// Source : https://leetcode.com/problems/longest-nice-substring/ +/// Author : liuyubobobo +/// Time : 2021-02-20 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Using bitwise operation to record +/// Time Complexity: O(n^2) +/// Space Complexity: O(1) +class Solution { +public: + string longestNiceSubstring(string s) { + + string res = ""; + for(int i = 0; i < s.size(); i ++){ + int lower = 0, upper = 0; + for(int j = i; j < s.size(); j ++){ + if(islower(s[j])) lower |= 1 << (s[j] - 'a'); + else upper |= 1 << (s[j] - 'A'); + + if((lower == upper) && (j - i + 1) > (int)res.size()) + res = s.substr(i, j - i + 1); + } + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1764-Form-Array-by-Concatenating-Subarrays-of-Another-Array/cpp-1764/CMakeLists.txt b/1501-2000/1764-Form-Array-by-Concatenating-Subarrays-of-Another-Array/cpp-1764/CMakeLists.txt new file mode 100644 index 00000000..c4edc05b --- /dev/null +++ b/1501-2000/1764-Form-Array-by-Concatenating-Subarrays-of-Another-Array/cpp-1764/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1764) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1764 main.cpp) \ No newline at end of file diff --git a/1501-2000/1764-Form-Array-by-Concatenating-Subarrays-of-Another-Array/cpp-1764/main.cpp b/1501-2000/1764-Form-Array-by-Concatenating-Subarrays-of-Another-Array/cpp-1764/main.cpp new file mode 100644 index 00000000..1ab53cce --- /dev/null +++ b/1501-2000/1764-Form-Array-by-Concatenating-Subarrays-of-Another-Array/cpp-1764/main.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/form-array-by-concatenating-subarrays-of-another-array/ +/// Author : liuyubobobo +/// Time : 2021-02-20 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(m * n) +/// Space Complexity: O(1) +class Solution { +public: + bool canChoose(vector>& groups, vector& nums) { + + int pos = 0; + for(const vector& group: groups){ + int tres = find(nums, group, pos); + if(tres == -1) return false; + + pos = tres + group.size(); + } + return true; + } + +private: + int find(const vector& nums, const vector& t, int start){ + + for(int i = start; i + (int)t.size() <= nums.size(); i ++){ + int j = 0; + for(; j < t.size(); j ++) + if(nums[i + j] != t[j]) break; + if(j == t.size()) return i; + } + return -1; + } +}; + + +int main() { + + vector> groups1 = {{1, -1, -1}, {3, -2, 0}}; + vector nums1 = {1, -1, 0, 1, -1, -1, 3, -2, 0}; + cout << Solution().canChoose(groups1, nums1) << endl; + // 1 + + return 0; +} diff --git a/1501-2000/1765-Map-of-Highest-Peak/cpp-1765/CMakeLists.txt b/1501-2000/1765-Map-of-Highest-Peak/cpp-1765/CMakeLists.txt new file mode 100644 index 00000000..7c89e1c9 --- /dev/null +++ b/1501-2000/1765-Map-of-Highest-Peak/cpp-1765/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1765) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1765 main.cpp) \ No newline at end of file diff --git a/1501-2000/1765-Map-of-Highest-Peak/cpp-1765/main.cpp b/1501-2000/1765-Map-of-Highest-Peak/cpp-1765/main.cpp new file mode 100644 index 00000000..eba2fee6 --- /dev/null +++ b/1501-2000/1765-Map-of-Highest-Peak/cpp-1765/main.cpp @@ -0,0 +1,64 @@ +/// Source : https://leetcode.com/problems/map-of-highest-peak/ +/// Author : liuyubobobo +/// Time : 2021-02-20 + +#include +#include +#include + +using namespace std; + + +/// BFS +/// Time Complexity: O(R * C) +/// Space Complexity: O(R * C) +class Solution { + +private: + const int dirs[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; + int R, C; + +public: + vector> highestPeak(vector>& isWater) { + + R = isWater.size(), C = isWater[0].size(); + + vector> res(R, vector(C, -1)); + queue> q; + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++) + if(isWater[i][j]){ + q.push({i * C + j, 0}); + res[i][j] = 0; + } + + while(!q.empty()){ + int cur = q.front().first, v = q.front().second; + q.pop(); + + int curx = cur / C, cury = cur % C; + for(int d = 0; d < 4; d ++){ + int nextx = curx + dirs[d][0], nexty = cury + dirs[d][1]; + if(in_area(nextx, nexty) && res[nextx][nexty] == -1){ + res[nextx][nexty] = v + 1; + q.push({nextx * C + nexty, v + 1}); + } + } + } + return res; + } + +private: + bool in_area(int x, int y){ + return x >= 0 && x < R && y >= 0 && y < C; + } +}; + + +int main() { + + vector> isWater = {{0, 1}, {0, 0}}; + vector> res = Solution().highestPeak(isWater); + + return 0; +} diff --git a/1501-2000/1766-Tree-of-Coprimes/cpp-1766/CMakeLists.txt b/1501-2000/1766-Tree-of-Coprimes/cpp-1766/CMakeLists.txt new file mode 100644 index 00000000..7082e196 --- /dev/null +++ b/1501-2000/1766-Tree-of-Coprimes/cpp-1766/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1766) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1766 main.cpp) \ No newline at end of file diff --git a/1501-2000/1766-Tree-of-Coprimes/cpp-1766/main.cpp b/1501-2000/1766-Tree-of-Coprimes/cpp-1766/main.cpp new file mode 100644 index 00000000..ee92f9db --- /dev/null +++ b/1501-2000/1766-Tree-of-Coprimes/cpp-1766/main.cpp @@ -0,0 +1,83 @@ +/// Source : https://leetcode.com/problems/tree-of-coprimes/ +/// Author : liuyubobobo +/// Time : 2021-02-21 + +#include +#include +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +private: + int MAX; + +public: + vector getCoprimes(vector& nums, vector>& edges) { + + int n = nums.size(); + vector> g(n); + for(const vector& e: edges) + g[e[0]].insert(e[1]), g[e[1]].insert(e[0]); + + MAX = *max_element(nums.begin(), nums.end()); + vector>> cur(MAX + 1); + vector res(n, -1); + dfs(g, 0, -1, 0, nums, cur, res); + return res; + } + +private: + void dfs(const vector>& g, int u, int parent, int d, + const vector& nums, vector>>& cur, vector& res){ + + int num = nums[u], cur_res_d = -1; + for(int v = 1; v <= MAX; v ++) + if(!cur[v].empty() && gcd(num, v) == 1){ + if(res[u] == -1 || cur[v].top().second > cur_res_d){ + res[u] = cur[v].top().first; + cur_res_d = cur[v].top().second; + } + } + + cur[num].push({u, d}); + for(int v: g[u]) + if(v != parent) + dfs(g, v, u, d + 1, nums, cur, res); + cur[num].pop(); + } + + int gcd(int x, int y){ + + if(x < y) swap(x, y); + + if(x % y == 0) return y; + return gcd(y, x % y); + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << " "; cout << endl; +} + +int main() { + + vector nums1 = {2, 3, 3, 2}; + vector> edges1 = {{0, 1}, {1, 2}, {1, 3}}; + print_vec(Solution().getCoprimes(nums1, edges1)); + // -1 0 0 1 + + vector nums2 = {5,6,10,2,3,6,15}; + vector> edges2 = {{0, 1}, {0, 2}, {1, 3}, {1, 4}, {2, 5}, {2, 6}}; + print_vec(Solution().getCoprimes(nums2, edges2)); + // -1 0 -1 0 0 0 -1 + + return 0; +} diff --git a/1501-2000/1768-Merge-Strings-Alternately/cpp-1768/CMakeLists.txt b/1501-2000/1768-Merge-Strings-Alternately/cpp-1768/CMakeLists.txt new file mode 100644 index 00000000..d5d5e4ff --- /dev/null +++ b/1501-2000/1768-Merge-Strings-Alternately/cpp-1768/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1501-2000/1768-Merge-Strings-Alternately/cpp-1768/main.cpp b/1501-2000/1768-Merge-Strings-Alternately/cpp-1768/main.cpp new file mode 100644 index 00000000..424a5aa3 --- /dev/null +++ b/1501-2000/1768-Merge-Strings-Alternately/cpp-1768/main.cpp @@ -0,0 +1,32 @@ +/// Source : https://leetcode.com/problems/merge-strings-alternately/ +/// Author : liuyubobobo +/// Time : 2021-02-20 + +#include +#include + +using namespace std; + + +/// Merge +/// Time Complexity: O(|word1| + |word2|) +/// Space Complexity: O(1) +class Solution { +public: + string mergeAlternately(string word1, string word2) { + + int p = 0, q = 0; + string res = ""; + while(p < word1.size() || q < word2.size()){ + if(p < word1.size()) res += word1[p ++]; + if(q < word2.size()) res += word2[q ++]; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1769-Minimum-Number-of-Operations-to-Move-All-Balls-to-Each-Box/cpp-1769/CMakeLists.txt b/1501-2000/1769-Minimum-Number-of-Operations-to-Move-All-Balls-to-Each-Box/cpp-1769/CMakeLists.txt new file mode 100644 index 00000000..b103b001 --- /dev/null +++ b/1501-2000/1769-Minimum-Number-of-Operations-to-Move-All-Balls-to-Each-Box/cpp-1769/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main2.cpp) \ No newline at end of file diff --git a/1501-2000/1769-Minimum-Number-of-Operations-to-Move-All-Balls-to-Each-Box/cpp-1769/main.cpp b/1501-2000/1769-Minimum-Number-of-Operations-to-Move-All-Balls-to-Each-Box/cpp-1769/main.cpp new file mode 100644 index 00000000..1c2bd4f3 --- /dev/null +++ b/1501-2000/1769-Minimum-Number-of-Operations-to-Move-All-Balls-to-Each-Box/cpp-1769/main.cpp @@ -0,0 +1,31 @@ +/// Source : https://leetcode.com/problems/minimum-number-of-operations-to-move-all-balls-to-each-box/ +/// Author : liuyubobobo +/// Time : 2021-02-21 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n^2) +/// Space Complexity: O(1) +class Solution { +public: + vector minOperations(string boxes) { + + int n = boxes.size(); + vector res(n, 0); + for(int i = 0; i < n; i ++) + for(int j = 0; j < n; j ++) + if(boxes[j] == '1') res[i] += abs(i - j); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1769-Minimum-Number-of-Operations-to-Move-All-Balls-to-Each-Box/cpp-1769/main2.cpp b/1501-2000/1769-Minimum-Number-of-Operations-to-Move-All-Balls-to-Each-Box/cpp-1769/main2.cpp new file mode 100644 index 00000000..1691898d --- /dev/null +++ b/1501-2000/1769-Minimum-Number-of-Operations-to-Move-All-Balls-to-Each-Box/cpp-1769/main2.cpp @@ -0,0 +1,38 @@ +/// Source : https://leetcode.com/problems/minimum-number-of-operations-to-move-all-balls-to-each-box/ +/// Author : liuyubobobo +/// Time : 2021-02-21 + +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + vector minOperations(string boxes) { + + int left = 0, left_move = 0, right = 0, right_move = 0; + for(int i = 0; i < boxes.size(); i ++) + if(boxes[i] == '1') right ++, right_move += i; + + vector res(boxes.size(), 0); + for(int i = 0; i < boxes.size(); i ++){ + res[i] = left_move + right_move; + right -= boxes[i] == '1'; + left += boxes[i] == '1'; + right_move -= right; + left_move += left; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1770-Maximum-Score-from-Performing-Multiplication-Operations/cpp-1770/CMakeLists.txt b/1501-2000/1770-Maximum-Score-from-Performing-Multiplication-Operations/cpp-1770/CMakeLists.txt new file mode 100644 index 00000000..80fb8c61 --- /dev/null +++ b/1501-2000/1770-Maximum-Score-from-Performing-Multiplication-Operations/cpp-1770/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main2.cpp) \ No newline at end of file diff --git a/1501-2000/1770-Maximum-Score-from-Performing-Multiplication-Operations/cpp-1770/main.cpp b/1501-2000/1770-Maximum-Score-from-Performing-Multiplication-Operations/cpp-1770/main.cpp new file mode 100644 index 00000000..c73de24c --- /dev/null +++ b/1501-2000/1770-Maximum-Score-from-Performing-Multiplication-Operations/cpp-1770/main.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/maximum-score-from-performing-multiplication-operations/ +/// Author : liuyubobobo +/// Time : 2021-02-20 + +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(m^2) +/// Space Complexity: O(m^2) +class Solution { + +private: + int n, m; + const int INF = 1e9; + +public: + int maximumScore(vector& nums, vector& multipliers) { + + n = nums.size(), m = multipliers.size(); + vector> dp(m, vector(m, -INF)); + return dfs(nums, multipliers, 0, 0, dp); + } + +private: + int dfs(const vector& nums, const vector& mul, int l, int r, + vector>& dp){ + + if(l + r == m) return 0; + if(dp[l][r] != -INF) return dp[l][r]; + + return dp[l][r] = max(nums[l] * mul[l + r] + dfs(nums, mul, l + 1, r, dp), + nums[n - 1 - r] * mul[l + r] + dfs(nums, mul, l, r + 1, dp)); + } +}; + + +int main() { + + vector nums1 = {1,2 , 3}, mul1 = {3, 2, 1}; + cout << Solution().maximumScore(nums1, mul1) << endl; + // 14 + + vector nums2 = {-5,-3,-3,-2,7,1}, mul2 = {-10,-5,3,4,6}; + cout << Solution().maximumScore(nums2, mul2) << endl; + // 102 + + return 0; +} diff --git a/1501-2000/1770-Maximum-Score-from-Performing-Multiplication-Operations/cpp-1770/main2.cpp b/1501-2000/1770-Maximum-Score-from-Performing-Multiplication-Operations/cpp-1770/main2.cpp new file mode 100644 index 00000000..b9549f26 --- /dev/null +++ b/1501-2000/1770-Maximum-Score-from-Performing-Multiplication-Operations/cpp-1770/main2.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/maximum-score-from-performing-multiplication-operations/ +/// Author : liuyubobobo +/// Time : 2021-02-21 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(m^2) +/// Space Complexity: O(m^2) +class Solution { + +public: + int maximumScore(vector& nums, vector& mul) { + + int n = nums.size(), m = mul.size(); + vector> dp(m + 1, vector(m + 1, 0)); + + for(int l = 1; l <= m; l ++) + dp[l][0] = dp[l - 1][0] + mul[l - 1] * nums[l - 1]; + for(int r = 1; r <= m; r ++) + dp[0][r] = dp[0][r - 1] + mul[r - 1] * nums[n - r]; + + for(int l = 1; l < m; l ++) + for(int r = 1; l + r <= m; r ++) + dp[l][r] = max(dp[l - 1][r] + mul[l + r - 1] * nums[l - 1], + dp[l][r - 1] + mul[l + r - 1] * nums[n - r]); + + int res = INT_MIN; + for(int i = 0; i <= m; i ++) res = max(res, dp[i][m - i]); + return res; + } +}; + + +int main() { + + vector nums1 = {1,2 , 3}, mul1 = {3, 2, 1}; + cout << Solution().maximumScore(nums1, mul1) << endl; + // 14 + + vector nums2 = {-5,-3,-3,-2,7,1}, mul2 = {-10,-5,3,4,6}; + cout << Solution().maximumScore(nums2, mul2) << endl; + // 102 + + return 0; +} diff --git a/1501-2000/1771-Maximize-Palindrome-Length-From-Subsequences/cpp-1771/CMakeLists.txt b/1501-2000/1771-Maximize-Palindrome-Length-From-Subsequences/cpp-1771/CMakeLists.txt new file mode 100644 index 00000000..a373769d --- /dev/null +++ b/1501-2000/1771-Maximize-Palindrome-Length-From-Subsequences/cpp-1771/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main2.cpp) \ No newline at end of file diff --git a/1501-2000/1771-Maximize-Palindrome-Length-From-Subsequences/cpp-1771/main.cpp b/1501-2000/1771-Maximize-Palindrome-Length-From-Subsequences/cpp-1771/main.cpp new file mode 100644 index 00000000..245a1cc9 --- /dev/null +++ b/1501-2000/1771-Maximize-Palindrome-Length-From-Subsequences/cpp-1771/main.cpp @@ -0,0 +1,89 @@ +/// Source : https://leetcode.com/problems/maximize-palindrome-length-from-subsequences/ +/// Author : liuyubobobo +/// Time : 2021-02-20 + +#include +#include + +using namespace std; + + +/// Memory Search +/// And pre-calculate max palindrome string length from each string seperately +/// Time Complexity: O(n^2 + m^2 + m * n) +/// Space Complexity: O(n^2 + m^2 + m * n) +class Solution { + +private: + int n, m; + +public: + int longestPalindrome(string word1, string word2) { + + n = word1.size(), m = word2.size(); + + vector> dp1(n, vector(n, -1)); + go(word1, n, dp1); + + vector> dp2(m, vector(m, -1)); + go(word2, m, dp2); + + vector>> dp(2, vector>(n, vector(m, -1))); + return dfs(word1, word2, 0, 0, m - 1, dp, dp1, dp2); + } + +private: + void go(const string& s, int len, vector>& dp){ + + for(int i = 0; i < len; i ++) dp[i][i] = 1; + for(int i = 0; i + 1 < len; i ++) + dp[i][i + 1] = (s[i] == s[i + 1] ? 2 : 1); + + for(int l = 3; l <= len; l ++) + for(int i = 0; i + l <= len; i ++){ + dp[i][i + l - 1] = max(dp[i + 1][i + l - 1], dp[i][i + l - 2]); + if(s[i] == s[i + l - 1]) + dp[i][i + l - 1] = max(dp[i][i + l - 1], 2 + dp[i + 1][i + l - 2]); + } + } + + int dfs(const string& s1, const string& s2, int ok, int l, int r, + vector>>& dp, + vector>& dp1, vector>& dp2){ + + if(l >= s1.size() && r < 0) return 0; + + if(l >= s1.size()) return ok ? dp2[0][r] : 0; + if(r < 0) return ok ? dp1[l][n - 1] : 0; + + if(dp[ok][l][r] != -1) return dp[ok][l][r]; + + int res = dfs(s1, s2, ok, l + 1, r, dp, dp1, dp2); + res = max(res, dfs(s1, s2, ok, l, r - 1, dp, dp1, dp2)); + if(s1[l] == s2[r]) + res = max(res, 2 + dfs(s1, s2, 1, l + 1, r - 1, dp, dp1, dp2)); +// cout << ok << " " << l << " " << r << " : " << res << endl; + return dp[ok][l][r] = res; + } +}; + + +int main() { + + cout << Solution().longestPalindrome("cacb", "cbba") << endl; + // 5 + + cout << Solution().longestPalindrome("ab", "ab") << endl; + // 3 + + cout << Solution().longestPalindrome("aa", "bb") << endl; + // 0 + + cout << Solution().longestPalindrome("aaa", "a") << endl; + // 4 + + cout << Solution().longestPalindrome("aaaada", "ca") << endl; + // 6 + + return 0; +} diff --git a/1501-2000/1771-Maximize-Palindrome-Length-From-Subsequences/cpp-1771/main2.cpp b/1501-2000/1771-Maximize-Palindrome-Length-From-Subsequences/cpp-1771/main2.cpp new file mode 100644 index 00000000..84950804 --- /dev/null +++ b/1501-2000/1771-Maximize-Palindrome-Length-From-Subsequences/cpp-1771/main2.cpp @@ -0,0 +1,68 @@ +/// Source : https://leetcode.com/problems/maximize-palindrome-length-from-subsequences/ +/// Author : liuyubobobo +/// Time : 2021-02-24 + +#include +#include + +using namespace std; + + +/// String Concatenating and DP +/// Time Complexity: O((n + m)^2) +/// Space Complexity: O((n + m)^2) +class Solution { + +public: + int longestPalindrome(string word1, string word2) { + + string s = word1 + word2; + int len = s.size(); + + vector> dp(len, vector(len, -1)); + for(int i = 0; i < len; i ++) dp[i][i] = 1; + + int res = 0; + for(int i = 0; i + 1 < len; i ++){ + dp[i][i + 1] = (s[i] == s[i + 1] ? 2 : 1); + if(s[i] == s[i + 1] && i < word1.size() && i + 1 >= word1.size()) + res = 2; + } + + for(int l = 3; l <= len; l ++) + for(int i = 0; i + l <= len; i ++){ + dp[i][i + l - 1] = max(dp[i + 1][i + l - 1], dp[i][i + l - 2]); + if(s[i] == s[i + l - 1]) + dp[i][i + l - 1] = max(dp[i][i + l - 1], 2 + dp[i + 1][i + l - 2]); + + if(s[i] == s[i + l - 1] && i < word1.size() && i + l - 1 >= word1.size()) + res = max(res, dp[i][i + l - 1]); + } + + return res; + } +}; + + +int main() { + + cout << Solution().longestPalindrome("cacb", "cbba") << endl; + // 5 + + cout << Solution().longestPalindrome("ab", "ab") << endl; + // 3 + + cout << Solution().longestPalindrome("aa", "bb") << endl; + // 0 + + cout << Solution().longestPalindrome("aaa", "a") << endl; + // 4 + + cout << Solution().longestPalindrome("aaaada", "ca") << endl; + // 6 + + cout << Solution().longestPalindrome("aba", "cfc") << endl; + // 0 + + return 0; +} diff --git a/1501-2000/1772-Sort-Features-by-Popularity/cpp-1772/CMakeLists.txt b/1501-2000/1772-Sort-Features-by-Popularity/cpp-1772/CMakeLists.txt new file mode 100644 index 00000000..0f0b924b --- /dev/null +++ b/1501-2000/1772-Sort-Features-by-Popularity/cpp-1772/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1772) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1772 main.cpp) \ No newline at end of file diff --git a/1501-2000/1772-Sort-Features-by-Popularity/cpp-1772/main.cpp b/1501-2000/1772-Sort-Features-by-Popularity/cpp-1772/main.cpp new file mode 100644 index 00000000..8a9ed880 --- /dev/null +++ b/1501-2000/1772-Sort-Features-by-Popularity/cpp-1772/main.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/sort-features-by-popularity/ +/// Author : liuyubobobo +/// Time : 2021-02-26 + +#include +#include +#include +#include + +using namespace std; + + +/// Using HashSet and Stable Sort +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + vector sortFeatures(vector& features, vector& responses) { + + unordered_set features_set(features.begin(), features.end()); + + unordered_map f; + for(const string& s: responses){ + unordered_set set = get_set(s); + for(const string& e: set) + if(features_set.count(e)) f[e] ++; + } + + stable_sort(features.begin(), features.end(), + [&](const string& s1, const string& s2){ + return f[s1] > f[s2]; + }); + return features; + } + +private: + unordered_set get_set(const string& s){ + + unordered_set set; + for(int start = 0, i = 1; i <= s.size(); i ++) + if(i == s.size() || s[i] == ' '){ + set.insert(s.substr(start, i - start)); + start = i + 1; + i = start; + } + return set; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1773-Count-Items-Matching-a-Rule/cpp-1773/CMakeLists.txt b/1501-2000/1773-Count-Items-Matching-a-Rule/cpp-1773/CMakeLists.txt new file mode 100644 index 00000000..d5d5e4ff --- /dev/null +++ b/1501-2000/1773-Count-Items-Matching-a-Rule/cpp-1773/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1501-2000/1773-Count-Items-Matching-a-Rule/cpp-1773/main.cpp b/1501-2000/1773-Count-Items-Matching-a-Rule/cpp-1773/main.cpp new file mode 100644 index 00000000..32508278 --- /dev/null +++ b/1501-2000/1773-Count-Items-Matching-a-Rule/cpp-1773/main.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/count-items-matching-a-rule/ +/// Author : liuyubobobo +/// Time : 2021-02-27 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int countMatches(vector>& items, string ruleKey, string ruleValue) { + + int type = 0; + if(ruleKey == "color") type = 1; + else if(ruleKey == "name") type = 2; + + int res = 0; + for(const vector& v: items) + res += v[type] == ruleValue; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1774-Closest-Dessert-Cost/cpp-1774/CMakeLists.txt b/1501-2000/1774-Closest-Dessert-Cost/cpp-1774/CMakeLists.txt new file mode 100644 index 00000000..b103b001 --- /dev/null +++ b/1501-2000/1774-Closest-Dessert-Cost/cpp-1774/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main2.cpp) \ No newline at end of file diff --git a/1501-2000/1774-Closest-Dessert-Cost/cpp-1774/main.cpp b/1501-2000/1774-Closest-Dessert-Cost/cpp-1774/main.cpp new file mode 100644 index 00000000..bea077b4 --- /dev/null +++ b/1501-2000/1774-Closest-Dessert-Cost/cpp-1774/main.cpp @@ -0,0 +1,80 @@ +/// Source : https://leetcode.com/problems/closest-dessert-cost/ +/// Author : liuyubobobo +/// Time : 2021-02-27 + +#include +#include + +using namespace std; + + +/// DP + Binary Search +/// Time Complexity: O((1 << 2m)log(1 << 2m) + nlog(1 << 2m)) +/// Space Complexity: O(1 << 2m) +class Solution { +public: + int closestCost(vector& baseCosts, vector& toppingCosts, int target) { + + vector v = toppingCosts; + for(int e: toppingCosts) + v.push_back(e); + + int m = v.size(); + vector options(1 << m, 0); + for(int state = 1; state < (1 << m); state ++){ + int pos = __builtin_ffs(state) - 1; + options[state] = options[state - (1 << pos)] + v[pos]; + } + sort(options.begin(), options.end()); + + int best = -1e9; + for(int base: baseCosts){ + + int t = target - base; + vector::iterator iter = lower_bound(options.begin(), options.end(), t); + if(iter != options.end()){ + int price = base + *iter; + if(abs(price - target) < abs(best - target)) + best = price; + else if(abs(price - target) ==abs(best - target) && price < best) + best = price; + } + + if(iter != options.begin()){ + iter --; + int price = base + *iter; + if(abs(price - target) < abs(best - target)) + best = price; + else if(abs(price - target) ==abs(best - target) && price < best) + best = price; + } + } + return best; + } +}; + + +int main() { + + vector baseCosts1 = {1, 7}, toppingCosts1 = {3, 4}; + cout << Solution().closestCost(baseCosts1, toppingCosts1, 10) << endl; + // 10 + + vector baseCosts2 = {2, 3}, toppingCosts2 = {4, 5, 100}; + cout << Solution().closestCost(baseCosts2, toppingCosts2, 18) << endl; + // 17 + + vector baseCosts3 = {3, 10}, toppingCosts3 = {2, 5}; + cout << Solution().closestCost(baseCosts3, toppingCosts3, 9) << endl; + // 8 + + vector baseCosts4 = {10}, toppingCosts4 = {1}; + cout << Solution().closestCost(baseCosts4, toppingCosts4, 1) << endl; + // 10 + + vector baseCosts5 = {5, 9}, toppingCosts5 = {10, 1}; + cout << Solution().closestCost(baseCosts5, toppingCosts5, 7) << endl; + // 7 + + return 0; +} diff --git a/1501-2000/1774-Closest-Dessert-Cost/cpp-1774/main2.cpp b/1501-2000/1774-Closest-Dessert-Cost/cpp-1774/main2.cpp new file mode 100644 index 00000000..60e0082d --- /dev/null +++ b/1501-2000/1774-Closest-Dessert-Cost/cpp-1774/main2.cpp @@ -0,0 +1,70 @@ +/// Source : https://leetcode.com/problems/closest-dessert-cost/ +/// Author : liuyubobobo +/// Time : 2021-03-03 + +#include +#include + +using namespace std; + + +/// Backtracking +/// Time Complexity: O(n * 3^m) +/// Space Complexity: O(m) +class Solution { + +private: + int best; + +public: + int closestCost(vector& baseCosts, vector& toppingCosts, int target) { + + best = -1e9; + for(int base: baseCosts){ + dfs(toppingCosts, 0, base, target); + } + return best; + } + +private: + void dfs(const vector& toppings, int index, int cur, int target){ + + if(index == toppings.size()){ + if(abs(cur - target) < abs(best - target)) + best = cur; + else if(abs(cur - target) == abs(best - target) && cur < best) + best = cur; + return; + } + + for(int i = 0; i <= 2; i ++) + dfs(toppings, index + 1, cur + i * toppings[index], target); + return; + } +}; + + +int main() { + + vector baseCosts1 = {1, 7}, toppingCosts1 = {3, 4}; + cout << Solution().closestCost(baseCosts1, toppingCosts1, 10) << endl; + // 10 + + vector baseCosts2 = {2, 3}, toppingCosts2 = {4, 5, 100}; + cout << Solution().closestCost(baseCosts2, toppingCosts2, 18) << endl; + // 17 + + vector baseCosts3 = {3, 10}, toppingCosts3 = {2, 5}; + cout << Solution().closestCost(baseCosts3, toppingCosts3, 9) << endl; + // 8 + + vector baseCosts4 = {10}, toppingCosts4 = {1}; + cout << Solution().closestCost(baseCosts4, toppingCosts4, 1) << endl; + // 10 + + vector baseCosts5 = {5, 9}, toppingCosts5 = {10, 1}; + cout << Solution().closestCost(baseCosts5, toppingCosts5, 7) << endl; + // 7 + + return 0; +} diff --git a/1501-2000/1775-Equal-Sum-Arrays-With-Minimum-Number-of-Operations/cpp-1775/CMakeLists.txt b/1501-2000/1775-Equal-Sum-Arrays-With-Minimum-Number-of-Operations/cpp-1775/CMakeLists.txt new file mode 100644 index 00000000..80fb8c61 --- /dev/null +++ b/1501-2000/1775-Equal-Sum-Arrays-With-Minimum-Number-of-Operations/cpp-1775/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main2.cpp) \ No newline at end of file diff --git a/1501-2000/1775-Equal-Sum-Arrays-With-Minimum-Number-of-Operations/cpp-1775/main.cpp b/1501-2000/1775-Equal-Sum-Arrays-With-Minimum-Number-of-Operations/cpp-1775/main.cpp new file mode 100644 index 00000000..335aff77 --- /dev/null +++ b/1501-2000/1775-Equal-Sum-Arrays-With-Minimum-Number-of-Operations/cpp-1775/main.cpp @@ -0,0 +1,76 @@ +/// Source : https://leetcode.com/problems/equal-sum-arrays-with-minimum-number-of-operations/ +/// Author : liuyubobobo +/// Time : 2021-02-27 + +#include +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int minOperations(vector& nums1, vector& nums2) { + + int n1 = nums1.size(), n2 = nums2.size(); + if(6 * n1 < n2 || 6 * n2 < n1) return -1; + + int sum1 = accumulate(nums1.begin(), nums1.end(), 0); + int sum2 = accumulate(nums2.begin(), nums2.end(), 0); + if(sum1 == sum2) return 0; + + if(sum1 > sum2){ + swap(n1, n2); + swap(sum1, sum2); + swap(nums1, nums2); + } + + vector f1(7, 0), f2(7, 0); + for(int e: nums1) f1[e] ++; + for(int e: nums2) f2[e] ++; + + int res = 0; + for(int i = 1; i <= 5; i ++){ + + int a = i, b = 7 - i; + for(int i = 0; i < f1[a]; i ++){ + sum1 += (6 - a); + res ++; + if(sum1 >= sum2) return res; + } + + for(int i = 0; i < f2[b]; i ++){ + sum2 -= (b - 1); + res ++; + if(sum1 >= sum2) return res; + } + } + return res; + } +}; + + +int main() { + + vector nums11 = {1,2,3,4,5,6}, nums12 = {1,1,2,2,2,2}; + cout << Solution().minOperations(nums11, nums12) << endl; + // 3 + + vector nums21 = {1,1,1,1,1,1,1}, nums22 = {6}; + cout << Solution().minOperations(nums21, nums22) << endl; + // -1 + + vector nums31 = {6, 6}, nums32 = {1}; + cout << Solution().minOperations(nums31, nums32) << endl; + // 3 + + vector nums41 = {5,6,4,3,1,2}, nums42 = {6,3,3,1,4,5,3,4,1,3,4}; + cout << Solution().minOperations(nums41, nums42) << endl; + // 4 + + return 0; +} diff --git a/1501-2000/1775-Equal-Sum-Arrays-With-Minimum-Number-of-Operations/cpp-1775/main2.cpp b/1501-2000/1775-Equal-Sum-Arrays-With-Minimum-Number-of-Operations/cpp-1775/main2.cpp new file mode 100644 index 00000000..da6d4729 --- /dev/null +++ b/1501-2000/1775-Equal-Sum-Arrays-With-Minimum-Number-of-Operations/cpp-1775/main2.cpp @@ -0,0 +1,75 @@ +/// Source : https://leetcode.com/problems/equal-sum-arrays-with-minimum-number-of-operations/ +/// Author : liuyubobobo +/// Time : 2021-02-27 + +#include +#include +#include + +using namespace std; + + +/// Greedy with Optimization +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int minOperations(vector& nums1, vector& nums2) { + + int n1 = nums1.size(), n2 = nums2.size(); + if(6 * n1 < n2 || 6 * n2 < n1) return -1; + + int sum1 = accumulate(nums1.begin(), nums1.end(), 0); + int sum2 = accumulate(nums2.begin(), nums2.end(), 0); + if(sum1 == sum2) return 0; + + if(sum1 > sum2){ + swap(n1, n2); + swap(sum1, sum2); + swap(nums1, nums2); + } + + vector f1(7, 0), f2(7, 0); + for(int e: nums1) f1[e] ++; + for(int e: nums2) f2[e] ++; + + int res = 0; + for(int i = 1; i <= 5; i ++){ + + int a = i, b = 7 - i; + + int k = min(f1[a], (sum2 - sum1) / (6 - a) + !!((sum2 - sum1) % (6 - a))); + res += k; + sum1 += k * (6 - a); + if(sum1 >= sum2) return res; + + k = min(f2[b], (sum2 - sum1) / (b - 1) + !!((sum2 - sum1) % (b - 1))); + res += k; + sum2 -= k * (b - 1); + if(sum1 >= sum2) return res; + } + return res; + } +}; + + +int main() { + + vector nums11 = {1,2,3,4,5,6}, nums12 = {1,1,2,2,2,2}; + cout << Solution().minOperations(nums11, nums12) << endl; + // 3 + + vector nums21 = {1,1,1,1,1,1,1}, nums22 = {6}; + cout << Solution().minOperations(nums21, nums22) << endl; + // -1 + + vector nums31 = {6, 6}, nums32 = {1}; + cout << Solution().minOperations(nums31, nums32) << endl; + // 3 + + vector nums41 = {5,6,4,3,1,2}, nums42 = {6,3,3,1,4,5,3,4,1,3,4}; + cout << Solution().minOperations(nums41, nums42) << endl; + // 4 + + return 0; +} diff --git a/1501-2000/1776-Car-Fleet-II/cpp-1776/CMakeLists.txt b/1501-2000/1776-Car-Fleet-II/cpp-1776/CMakeLists.txt new file mode 100644 index 00000000..74cc3ee6 --- /dev/null +++ b/1501-2000/1776-Car-Fleet-II/cpp-1776/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) \ No newline at end of file diff --git a/1501-2000/1776-Car-Fleet-II/cpp-1776/main.cpp b/1501-2000/1776-Car-Fleet-II/cpp-1776/main.cpp new file mode 100644 index 00000000..2fbff09d --- /dev/null +++ b/1501-2000/1776-Car-Fleet-II/cpp-1776/main.cpp @@ -0,0 +1,90 @@ +/// Source : https://leetcode.com/problems/car-fleet-ii/ +/// Author : liuyubobobo +/// Time : 2021-03-03 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// Using Priority Queue +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + vector getCollisionTimes(vector>& cars) { + + int n = cars.size(); + + set carset; + for(int i = 0; i < n; i ++) + carset.insert(i); + + priority_queue, vector>, greater>> pq; + for(int i = 0; i + 1 < n; i ++) + if(cars[i][1] > cars[i + 1][1]) + pq.push({(double)(cars[i + 1][0] - cars[i][0]) / (cars[i][1] - cars[i + 1][1]), i}); + + vector res(n, -1.0); + while(!pq.empty()){ + double t = pq.top().first, index = pq.top().second; + pq.pop(); + if(res[index] >= 0.0) continue; + + res[index] = t; + + int next = get_next(carset, index); + if(next == -1) continue; + + int prev = get_prev(carset, index); + if(prev == -1) continue; + + carset.erase(index); + + if(cars[prev][1] > cars[next][1]) + pq.push({(double)(cars[next][0] - cars[prev][0]) / (cars[prev][1] - cars[next][1]), prev}); + } + return res; + } + +private: + int get_prev(set& s, int index){ + + set::iterator iter = s.lower_bound(index); + assert(iter != s.end()); + + if(iter == s.begin()) return -1; + iter --; + return *iter; + } + + int get_next(set& s, int index){ + + set::iterator iter = s.lower_bound(index); + assert(iter != s.end()); + iter ++; + return iter == s.end() ? -1 : *iter; + } +}; + + +void print_vec(const vector& v){ + for(double e: v) cout << e << " "; cout << endl; +} + +int main() { + + vector> cars1 = {{1,2},{2,1},{4,3},{7,2}}; + print_vec(Solution().getCollisionTimes(cars1)); + // 1.00000,-1.00000,3.00000,-1.00000 + + vector> cars2 = {{3,4},{5,4},{6,3},{9,1}}; + print_vec(Solution().getCollisionTimes(cars2)); + // 2.00000,1.00000,1.50000,-1.00000 + + return 0; +} diff --git a/1501-2000/1778-Shortest-Path-in-a-Hidden-Grid/cpp-1778/CMakeLists.txt b/1501-2000/1778-Shortest-Path-in-a-Hidden-Grid/cpp-1778/CMakeLists.txt new file mode 100644 index 00000000..06d3ab21 --- /dev/null +++ b/1501-2000/1778-Shortest-Path-in-a-Hidden-Grid/cpp-1778/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1778) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1778 main.cpp) \ No newline at end of file diff --git a/1501-2000/1778-Shortest-Path-in-a-Hidden-Grid/cpp-1778/main.cpp b/1501-2000/1778-Shortest-Path-in-a-Hidden-Grid/cpp-1778/main.cpp new file mode 100644 index 00000000..4d743b3e --- /dev/null +++ b/1501-2000/1778-Shortest-Path-in-a-Hidden-Grid/cpp-1778/main.cpp @@ -0,0 +1,118 @@ +/// Source : https://leetcode.com/problems/shortest-path-in-a-hidden-grid/ +/// Author : liuyubobobo +/// Time : 2021-03-05 + +#include +#include +#include +#include +#include + +using namespace std; + + +// This is the gridMaster's API interface. +// You should not implement it, or speculate about its implementation +class GridMaster { + +public: + bool canMove(char direction); + void move(char direction); + bool isTarget(); +}; + + +/// DFS and BFS +/// Time Complexity: O(R * C) +/// Space Complexity: O(R * C) +class Solution { + +private: + const map> dirs = { + {'U', {-1, 0}}, + {'D', {1, 0}}, + {'L', {0, -1}}, + {'R', {0, 1}} + }; + const map rd = { + {'U', 'D'}, + {'D', 'U'}, + {'L', 'R'}, + {'R', 'L'} + }; + int startx = 501, starty = 501, endx, endy; + +public: + int findShortestPath(GridMaster& master) { + + startx = 501, starty = 501, endx = -1, endy = -1; + vector> grid(1003, vector(1003, -1)); + dfs(grid, startx, starty, master); + +// cout << "end : " << endx << " " << endy << endl; + + if(endx == -1){ + assert(endy == -1); + return -1; + } + + return bfs(grid, startx, starty, endx, endy); + } + +private: + int bfs(const vector>& grid, int sx, int sy, int tx, int ty){ + + vector> dis(1003, vector(1003, -1)); + dis[sx][sy] = 0; + + queue> q; + q.push({sx, sy}); + + const int dirs[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; + while(!q.empty()){ + int curx = q.front().first, cury = q.front().second; + q.pop(); + + if(curx == tx && cury == ty) return dis[curx][cury]; + + for(int d = 0; d < 4; d ++){ + int nextx = curx + dirs[d][0], nexty = cury + dirs[d][1]; + if(grid[nextx][nexty] == 0 && dis[nextx][nexty] == -1){ + dis[nextx][nexty] = 1 + dis[curx][cury]; + q.push({nextx, nexty}); + } + } + } + assert(false); + return -1; + } + + void dfs(vector>& grid, int x, int y, GridMaster& master){ + + if(master.isTarget()) endx = x, endy = y; + + for(const pair>& p: dirs){ + char d = p.first; + int dx = p.second.first, dy = p.second.second; + int nextx = x + dx, nexty = y + dy; + + if(grid[nextx][nexty] == -1){ + if(master.canMove(d)){ + grid[nextx][nexty] = 0; + master.move(d); + dfs(grid, nextx, nexty, master); + master.move(rd.at(d)); + } + else{ + grid[nextx][nexty] = 1; + } + } + } + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1779-Find-Nearest-Point-That-Has-the-Same-X-or-Y-Coordinate/cpp-1779/CMakeLists.txt b/1501-2000/1779-Find-Nearest-Point-That-Has-the-Same-X-or-Y-Coordinate/cpp-1779/CMakeLists.txt new file mode 100644 index 00000000..8c9aa7c2 --- /dev/null +++ b/1501-2000/1779-Find-Nearest-Point-That-Has-the-Same-X-or-Y-Coordinate/cpp-1779/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1779) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1779 main2.cpp) \ No newline at end of file diff --git a/1501-2000/1779-Find-Nearest-Point-That-Has-the-Same-X-or-Y-Coordinate/cpp-1779/main.cpp b/1501-2000/1779-Find-Nearest-Point-That-Has-the-Same-X-or-Y-Coordinate/cpp-1779/main.cpp new file mode 100644 index 00000000..8afdb205 --- /dev/null +++ b/1501-2000/1779-Find-Nearest-Point-That-Has-the-Same-X-or-Y-Coordinate/cpp-1779/main.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/find-nearest-point-that-has-the-same-x-or-y-coordinate/ +/// Author : liuyubobobo +/// Time : 2021-03-11 + +#include +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int nearestValidPoint(int x, int y, vector>& points) { + + int res = -1, dis = INT_MAX; + for(int i = 0; i < points.size(); i ++){ + if(x == points[i][0] && abs(y - points[i][1]) < dis) + res = i, dis = abs(y - points[i][1]); + if(y == points[i][1] && abs(x - points[i][0]) < dis) + res = i, dis = abs(x - points[i][0]); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1779-Find-Nearest-Point-That-Has-the-Same-X-or-Y-Coordinate/cpp-1779/main2.cpp b/1501-2000/1779-Find-Nearest-Point-That-Has-the-Same-X-or-Y-Coordinate/cpp-1779/main2.cpp new file mode 100644 index 00000000..c4098e21 --- /dev/null +++ b/1501-2000/1779-Find-Nearest-Point-That-Has-the-Same-X-or-Y-Coordinate/cpp-1779/main2.cpp @@ -0,0 +1,31 @@ +/// Source : https://leetcode.com/problems/find-nearest-point-that-has-the-same-x-or-y-coordinate/ +/// Author : liuyubobobo +/// Time : 2021-03-11 + +#include +#include + +using namespace std; + + +/// Linear Scan - a little bit optimization +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int nearestValidPoint(int x, int y, vector>& points) { + + int res = -1, dis = INT_MAX; + for(int i = 0; i < points.size(); i ++){ + if((x == points[i][0] || y == points[i][1]) && abs(x - points[i][0]) + abs(y - points[i][1]) < dis) + res = i, dis = abs(x - points[i][0]) + abs(y - points[i][1]); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1780-Check-if-Number-is-a-Sum-of-Powers-of-Three/cpp-1780/CMakeLists.txt b/1501-2000/1780-Check-if-Number-is-a-Sum-of-Powers-of-Three/cpp-1780/CMakeLists.txt new file mode 100644 index 00000000..ce0c88d1 --- /dev/null +++ b/1501-2000/1780-Check-if-Number-is-a-Sum-of-Powers-of-Three/cpp-1780/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1780) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1780 main2.cpp) \ No newline at end of file diff --git a/1501-2000/1780-Check-if-Number-is-a-Sum-of-Powers-of-Three/cpp-1780/main.cpp b/1501-2000/1780-Check-if-Number-is-a-Sum-of-Powers-of-Three/cpp-1780/main.cpp new file mode 100644 index 00000000..9d57557a --- /dev/null +++ b/1501-2000/1780-Check-if-Number-is-a-Sum-of-Powers-of-Three/cpp-1780/main.cpp @@ -0,0 +1,32 @@ +/// Source : https://leetcode.com/problems/check-if-number-is-a-sum-of-powers-of-three/ +/// Author : liuyubobobo +/// Time : 2021-03-11 + +#include + +using namespace std; + + +/// 3-based number convert +/// Time Complexity: O(logn) +/// Space Complexity: O(1) +class Solution { +public: + bool checkPowersOfThree(int n) { + + int cur = 1; + while(cur * 3 <= n) cur *= 3; + + while(cur){ + if(n >= cur) n -= cur; + cur /= 3; + } + return n == 0; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1780-Check-if-Number-is-a-Sum-of-Powers-of-Three/cpp-1780/main2.cpp b/1501-2000/1780-Check-if-Number-is-a-Sum-of-Powers-of-Three/cpp-1780/main2.cpp new file mode 100644 index 00000000..6ccb67c1 --- /dev/null +++ b/1501-2000/1780-Check-if-Number-is-a-Sum-of-Powers-of-Three/cpp-1780/main2.cpp @@ -0,0 +1,29 @@ +/// Source : https://leetcode.com/problems/check-if-number-is-a-sum-of-powers-of-three/ +/// Author : liuyubobobo +/// Time : 2021-03-11 + +#include + +using namespace std; + + +/// 3-based number convert +/// Time Complexity: O(logn) +/// Space Complexity: O(1) +class Solution { +public: + bool checkPowersOfThree(int n) { + + while(n){ + if(n % 3 == 2) return false; + n /= 3; + } + return true; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1781-Sum-of-Beauty-of-All-Substrings/cpp-1781/CMakeLists.txt b/1501-2000/1781-Sum-of-Beauty-of-All-Substrings/cpp-1781/CMakeLists.txt new file mode 100644 index 00000000..352cd7ef --- /dev/null +++ b/1501-2000/1781-Sum-of-Beauty-of-All-Substrings/cpp-1781/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1781) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1781 main.cpp) \ No newline at end of file diff --git a/1501-2000/1781-Sum-of-Beauty-of-All-Substrings/cpp-1781/main.cpp b/1501-2000/1781-Sum-of-Beauty-of-All-Substrings/cpp-1781/main.cpp new file mode 100644 index 00000000..2257c929 --- /dev/null +++ b/1501-2000/1781-Sum-of-Beauty-of-All-Substrings/cpp-1781/main.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/sum-of-beauty-of-all-substrings/ +/// Author : liuyubobobo +/// Time : 2021-03-11 + +#include +#include + +using namespace std; + + +/// Presum +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { +public: + int beautySum(string s) { + + int n = s.size(); + + vector> presum(26, vector(n + 1, 0)); + for(int c = 0; c < 26; c ++) + for(int i = 0; i < n; i ++) + presum[c][i + 1] = presum[c][i] + (s[i] == ('a' + c)); + + int res = 0; + for(int start = 0; start < n; start ++) + for(int end = start; end < n; end ++){ + int maxf = INT_MIN, minf = INT_MAX; + for(int c = 0; c < 26; c ++){ + int f = presum[c][end + 1] - presum[c][start]; + if(f) + maxf = max(maxf, f), + minf = min(minf, f); + } + + res += (maxf - minf); + } + return res; + } +}; + + +int main() { + + cout << Solution().beautySum("aabcb") << endl; + // 5 + + cout << Solution().beautySum("aabcbaa") << endl; + // 17 + + return 0; +} diff --git a/1501-2000/1782-Count-Pairs-Of-Nodes/cpp-1782/CMakeLists.txt b/1501-2000/1782-Count-Pairs-Of-Nodes/cpp-1782/CMakeLists.txt new file mode 100644 index 00000000..e73f7684 --- /dev/null +++ b/1501-2000/1782-Count-Pairs-Of-Nodes/cpp-1782/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1782) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1782 main.cpp) \ No newline at end of file diff --git a/1501-2000/1782-Count-Pairs-Of-Nodes/cpp-1782/main.cpp b/1501-2000/1782-Count-Pairs-Of-Nodes/cpp-1782/main.cpp new file mode 100644 index 00000000..d2428d2b --- /dev/null +++ b/1501-2000/1782-Count-Pairs-Of-Nodes/cpp-1782/main.cpp @@ -0,0 +1,72 @@ +/// Source : https://leetcode.com/problems/count-pairs-of-nodes/ +/// Author : liuyubobobo +/// Time : 2021-03-15 + +#include +#include +#include + +using namespace std; + + +/// inclusive-exclusive +/// Time Complexity: O(eloge + q * (nlogn + e)) +/// Space Complexity: O(e) +class Solution { +public: + vector countPairs(int n, vector>& edges, vector& queries) { + + vector degrees(n); + map, int> edge_table; + + for(vector& e: edges){ + e[0] --, e[1] --; + edge_table[{min(e[0], e[1]), max(e[0], e[1])}] ++; + degrees[e[0]] ++, degrees[e[1]] ++; + } + + vector sorted_degrees = degrees; + sort(sorted_degrees.begin(), sorted_degrees.end()); + + vector res; + for(int q: queries){ + + int num = greater_pairs(sorted_degrees, q); + for(const pair, int>& p: edge_table){ + int e0 = p.first.first, e1 = p.first.second, f = p.second; + if(degrees[e0] + degrees[e1] > q && degrees[e0] + degrees[e1] - f <= q) + num --; + } + res.push_back(num); + } + return res; + } + +private: + int greater_pairs(const vector& data, int k){ + + int res = 0; + for(int i = 0; i < data.size(); i ++){ + vector::const_iterator iter = upper_bound(data.begin() + (i + 1), data.end(), k - data[i]); + res += (data.end() - iter); + } + return res; + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << " "; cout << endl; +} + +int main() { + + vector> edges1 = { + {1, 5}, {1, 5}, {3, 4}, {2, 5}, {1, 3}, {5, 1}, {2, 3}, {2, 5} + }; + vector queries1 = {1, 2, 3, 4, 5}; + print_vec(Solution().countPairs(5, edges1, queries1)); + // 10 10 9 8 6 + + return 0; +} diff --git a/1501-2000/1784-Check-if-Binary-String-Has-at-Most-One-Segment-of-Ones/cpp-1784/CMakeLists.txt b/1501-2000/1784-Check-if-Binary-String-Has-at-Most-One-Segment-of-Ones/cpp-1784/CMakeLists.txt new file mode 100644 index 00000000..ec9e7c4c --- /dev/null +++ b/1501-2000/1784-Check-if-Binary-String-Has-at-Most-One-Segment-of-Ones/cpp-1784/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main2.cpp) \ No newline at end of file diff --git a/1501-2000/1784-Check-if-Binary-String-Has-at-Most-One-Segment-of-Ones/cpp-1784/main.cpp b/1501-2000/1784-Check-if-Binary-String-Has-at-Most-One-Segment-of-Ones/cpp-1784/main.cpp new file mode 100644 index 00000000..a9818dd9 --- /dev/null +++ b/1501-2000/1784-Check-if-Binary-String-Has-at-Most-One-Segment-of-Ones/cpp-1784/main.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/check-if-binary-string-has-at-most-one-segment-of-ones/ +/// Author : liuyubobobo +/// Time : 2021-03-06 + +#include +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + bool checkOnesSegment(string s) { + + int cnt = 0; + for(int start = next_one(s, 0), i = start + 1; i <= s.size(); i ++) + if(i == s.size() || s[i] == '0'){ + cnt ++; + start = next_one(s, i); + i = start; + } + return cnt == 1; + } + +private: + int next_one(const string& s, int start){ + for(int i = start; i < s.size(); i ++) + if(s[i] == '1') return i; + return s.size(); + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1784-Check-if-Binary-String-Has-at-Most-One-Segment-of-Ones/cpp-1784/main2.cpp b/1501-2000/1784-Check-if-Binary-String-Has-at-Most-One-Segment-of-Ones/cpp-1784/main2.cpp new file mode 100644 index 00000000..d8523c4c --- /dev/null +++ b/1501-2000/1784-Check-if-Binary-String-Has-at-Most-One-Segment-of-Ones/cpp-1784/main2.cpp @@ -0,0 +1,26 @@ +/// Source : https://leetcode.com/problems/check-if-binary-string-has-at-most-one-segment-of-ones/ +/// Author : liuyubobobo +/// Time : 2021-03-06 + +#include +#include + +using namespace std; + + +/// No "01" since there's no leading zeros +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + bool checkOnesSegment(string s) { + + return s.find("01") == string::npos; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1785-Minimum-Elements-to-Add-to-Form-a-Given-Sum/cpp-1785/CMakeLists.txt b/1501-2000/1785-Minimum-Elements-to-Add-to-Form-a-Given-Sum/cpp-1785/CMakeLists.txt new file mode 100644 index 00000000..81ad8b42 --- /dev/null +++ b/1501-2000/1785-Minimum-Elements-to-Add-to-Form-a-Given-Sum/cpp-1785/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1501-2000/1785-Minimum-Elements-to-Add-to-Form-a-Given-Sum/cpp-1785/main.cpp b/1501-2000/1785-Minimum-Elements-to-Add-to-Form-a-Given-Sum/cpp-1785/main.cpp new file mode 100644 index 00000000..84c218a4 --- /dev/null +++ b/1501-2000/1785-Minimum-Elements-to-Add-to-Form-a-Given-Sum/cpp-1785/main.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/minimum-elements-to-add-to-form-a-given-sum/ +/// Author : liuyubobobo +/// Time : 2021-03-06 + +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int minElements(vector& nums, int limit, int goal) { + + long long sum = 0ll; + for(const int num: nums) sum += (long long)num; + + if(sum == (long long)goal) return 0; + return solve(abs(goal - sum), (long long)limit); + } + +private: + long long solve(long long sum, long long limit){ + long long res = sum / limit; + if(sum % limit != 0) + res += 1ll; + return res; + } +}; + + +int main() { + + vector nums1 = {1, -1, 1}; + cout << Solution().minElements(nums1, 3, -4) << endl; + // 2 + + vector nums2 = {1, -10, 9, 1}; + cout << Solution().minElements(nums2, 100, 0) << endl; + // 1 + + return 0; +} diff --git a/1501-2000/1786-Number-of-Restricted-Paths-From-First-to-Last-Node/cpp-1786/CMakeLists.txt b/1501-2000/1786-Number-of-Restricted-Paths-From-First-to-Last-Node/cpp-1786/CMakeLists.txt new file mode 100644 index 00000000..ce73aee9 --- /dev/null +++ b/1501-2000/1786-Number-of-Restricted-Paths-From-First-to-Last-Node/cpp-1786/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1501-2000/1786-Number-of-Restricted-Paths-From-First-to-Last-Node/cpp-1786/main.cpp b/1501-2000/1786-Number-of-Restricted-Paths-From-First-to-Last-Node/cpp-1786/main.cpp new file mode 100644 index 00000000..39d0aa92 --- /dev/null +++ b/1501-2000/1786-Number-of-Restricted-Paths-From-First-to-Last-Node/cpp-1786/main.cpp @@ -0,0 +1,101 @@ +/// Source : https://leetcode.com/problems/number-of-restricted-paths-from-first-to-last-node/ +/// Author : liuyubobobo +/// Time : 2021-03-06 + +#include +#include +#include +#include + +using namespace std; + + +/// Dijkstra + DAG DP +/// Time Complexity: O(eloge) +/// Space Complexity: O(n + e) +class Solution { + +private: + const int INF = 1e9 + 7; + +public: + int countRestrictedPaths(int n, vector>& edges) { + + vector> g(n); + for(const vector& e: edges){ + int u = e[0] - 1, v = e[1] - 1, w = e[2]; + g[u][v] = w; + g[v][u] = w; + } + + vector dis = dij(n, g, n - 1); +// for(int e: dis) cout << e << " "; cout << endl; + + vector dp(n, -1); + return dfs(g, 0, dis, dp); + } + +private: + int dfs(const vector>& g, int u, + const vector& dis, vector& dp){ + + if(dp[u] != -1) return dp[u]; + + int res = 0; + bool ok = false; + for(const pair& p: g[u]){ + int v = p.first; + if(dis[u] > dis[v]){ + res = (res + dfs(g, v, dis, dp)) % INF; + ok = true; + } + } + + return dp[u] = (ok ? res : 1); + } + + vector dij(int n, const vector>& g, int s){ + + vector visited(n, false); + vector dis(n, INF); + + priority_queue, vector>, greater>> pq; + pq.push({0, n - 1}); + while(!pq.empty()){ + int curd = pq.top().first, cur = pq.top().second; + pq.pop(); + + if(visited[cur]) continue; + + visited[cur] = true; + dis[cur] = curd; + + for(const pair& p: g[cur]){ + int next = p.first, w = p.second; + if(!visited[next] && curd + w < dis[next]){ + dis[next] = curd + w; + pq.push({dis[next], next}); + } + } + } + return dis; + } +}; + + +int main() { + + vector> edges1 = { + {1,2,3},{1,3,3},{2,3,1},{1,4,2},{5,2,2},{3,5,1},{5,4,10} + }; + cout << Solution().countRestrictedPaths(5, edges1) << endl; + // 3 + + vector> edges2 = { + {1,3,1},{4,1,2},{7,3,4},{2,5,3},{5,6,1},{6,7,2},{7,5,3},{2,6,4} + }; + cout << Solution().countRestrictedPaths(7, edges2) << endl; + // 1 + + return 0; +} diff --git a/1501-2000/1787-Make-the-XOR-of-All-Segments-Equal-to-Zero/cpp-1787/CMakeLists.txt b/1501-2000/1787-Make-the-XOR-of-All-Segments-Equal-to-Zero/cpp-1787/CMakeLists.txt new file mode 100644 index 00000000..74cc3ee6 --- /dev/null +++ b/1501-2000/1787-Make-the-XOR-of-All-Segments-Equal-to-Zero/cpp-1787/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) \ No newline at end of file diff --git a/1501-2000/1787-Make-the-XOR-of-All-Segments-Equal-to-Zero/cpp-1787/main.cpp b/1501-2000/1787-Make-the-XOR-of-All-Segments-Equal-to-Zero/cpp-1787/main.cpp new file mode 100644 index 00000000..6bcc3643 --- /dev/null +++ b/1501-2000/1787-Make-the-XOR-of-All-Segments-Equal-to-Zero/cpp-1787/main.cpp @@ -0,0 +1,82 @@ +/// Source : https://leetcode.com/problems/make-the-xor-of-all-segments-equal-to-zero/ +/// Author : liuyubobobo +/// Time : 2021-03-11 + +#include +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(LIMIT * k) +/// Space Complexity: O(LIMIT * k) +class Solution { + +public: + int minChanges(vector& nums, int k) { + + vector pow2 = {1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024}; + int LIMIT = *lower_bound(pow2.begin(), pow2.end(), *max_element(nums.begin(), nums.end())) * 2; + + vector> f(k); + vector total(k, 0); + for(int i = 0; i < nums.size(); i ++){ + total[i % k] ++; + f[i % k][nums[i]] ++; + } + + vector> dp(k, vector(LIMIT)); + int premin = INT_MAX; + for(int x = 0; x < LIMIT; x ++){ + dp[k - 1][x] = total[k - 1] - f[k - 1][x]; + premin = min(premin, dp[k - 1][x]); + } + + for(int index = k - 2; index >= 0; index --){ + + int curmin = total[index] + premin; + for(int x = 0; x < LIMIT; x ++){ + dp[index][x] = total[index] + premin; + + for(const pair& p: f[index]){ + dp[index][x] = min(dp[index][x], total[index] - p.second + dp[index + 1][x ^ p.first]); + curmin = min(curmin, dp[index][x]); + } + } + premin = curmin; + } + return dp[0][0]; + } +}; + + +int main() { + + vector nums1 = {1, 2, 0, 3, 0}; + cout << Solution().minChanges(nums1, 1) << endl; + // 3 + + vector nums2 = {3,4,5,2,1,7,3,4,7}; + cout << Solution().minChanges(nums2, 3) << endl; + // 3 + + vector nums3 = {26,19,19,28,13,14,6,25,28,19,0,15,25,11}; + cout << Solution().minChanges(nums3, 3) << endl; + // 11 + + vector nums4 = {4,17,25,30,27,20,14,8,24,21,7,3,13,11,10,3,21,21,30,0,0}; + cout << Solution().minChanges(nums4, 13) << endl; + // 8 + + vector nums5 = {231,167,89,85,224,180,45,58,23,108,157,95,108,64,206,109,147,28,194,17,4,46,74,96,237,109,114,122,161,76,181,251,9,82,44,15,242,7,23,109,210,109,181,12,14,226,61,49,8,74,19,152,4,137,243,27,187,200,168,145,188,203,98,193,253,133,164,198,132,119,148,146,94,43,181,123,212,83,157}; + cout << Solution().minChanges(nums5, 2) << endl; + // 75 + + vector nums6 = {67,101,73,239,200,79,137,0,65,145,0,51,244,234,1,229,198,133,241,178,158,111,39,164,203,145,127,113,103,248,87,199,202,4,36,19,141,141,58,188,31,253,223,151,88,36,174,242,1,113,217,114,233,40,221,212,218,142,135,206,133,216,90,13,169,108,218,89,104,82,162,247,34,222,13,80,183,139,230,182,114,88,95,102,175,148,150,110,189,10,104,23,86,34,95,158,227,159,147,0,249,96,157,224,33,150,61,130,25,229,173,217,35,86,220,63,26,216,148,82,103,206,23,28,17,146,117,158,153,64,230,150,255,208,168,137,7,219,56,7,199,95,61,78,20,122,227,189,109,86,181,24,4,160,244,122,79,57,63,173,49,44,14,145,129,38,163,240,38,252,190,239,180,18,211,23,57,177,206,140,160,171,63,120,191,3,126,139,213,88,39,67,122,67,210,157,119,92,85,152,195,151,167,199,128,132,221,23,11,225,231,159,133,21,152,52,49,46,76,112,146,10,77}; + cout << Solution().minChanges(nums6, 75) << endl; + // 147 + + return 0; +} diff --git a/1501-2000/1788-Maximize-the-Beauty-of-the-Garden/cpp-1788/CMakeLists.txt b/1501-2000/1788-Maximize-the-Beauty-of-the-Garden/cpp-1788/CMakeLists.txt new file mode 100644 index 00000000..1cf66ecc --- /dev/null +++ b/1501-2000/1788-Maximize-the-Beauty-of-the-Garden/cpp-1788/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1788) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1788 main2.cpp) \ No newline at end of file diff --git a/1501-2000/1788-Maximize-the-Beauty-of-the-Garden/cpp-1788/main.cpp b/1501-2000/1788-Maximize-the-Beauty-of-the-Garden/cpp-1788/main.cpp new file mode 100644 index 00000000..a35892da --- /dev/null +++ b/1501-2000/1788-Maximize-the-Beauty-of-the-Garden/cpp-1788/main.cpp @@ -0,0 +1,64 @@ +/// Source : https://leetcode.com/problems/maximize-the-beauty-of-the-garden/ +/// Author : liuyubobobo +/// Time : 2021-03-11 + +#include +#include +#include + +using namespace std; + + +/// Presum + Greedy +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int maximumBeauty(vector& flowers) { + + int n = flowers.size(); + vector presum(n + 1, 0); + for(int i = 0; i < n; i ++) + presum[i + 1] = presum[i] + (flowers[i] > 0 ? flowers[i] : 0); + + map maxindex, minindex; + for(int i = 0; i < flowers.size(); i ++) + if(maxindex.count(flowers[i])){ + maxindex[flowers[i]] = max(maxindex[flowers[i]], i); + minindex[flowers[i]] = min(minindex[flowers[i]], i); + } + else{ + maxindex[flowers[i]] = minindex[flowers[i]] = i; + } + + int res = INT_MIN; + for(const pair& p: maxindex){ + int end = p.first, maxi = p.second, mini = minindex[end]; + if(maxi != mini){ + int tres = 2 * end; + mini ++, maxi --; + if(mini <= maxi) tres += presum[maxi + 1] - presum[mini]; + res = max(res, tres); + } + } + return res; + } +}; + + +int main() { + + vector flowers1 = {1, 2, 3, 1, 2}; + cout << Solution().maximumBeauty(flowers1) << endl; + // 8 + + vector flowers2 = {100, 1, 1, -3, 1}; + cout << Solution().maximumBeauty(flowers2) << endl; + // 3 + + vector flowers3 = {-1, -2, 0, -1}; + cout << Solution().maximumBeauty(flowers3) << endl; + // -2 + + return 0; +} diff --git a/1501-2000/1788-Maximize-the-Beauty-of-the-Garden/cpp-1788/main2.cpp b/1501-2000/1788-Maximize-the-Beauty-of-the-Garden/cpp-1788/main2.cpp new file mode 100644 index 00000000..73da3810 --- /dev/null +++ b/1501-2000/1788-Maximize-the-Beauty-of-the-Garden/cpp-1788/main2.cpp @@ -0,0 +1,60 @@ +/// Source : https://leetcode.com/problems/maximize-the-beauty-of-the-garden/ +/// Author : liuyubobobo +/// Time : 2021-03-11 + +#include +#include +#include + +using namespace std; + + +/// Presum + Greedy +/// A little optimization +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int maximumBeauty(vector& flowers) { + + int n = flowers.size(); + vector presum(n + 1, 0); + for(int i = 0; i < n; i ++) + presum[i + 1] = presum[i] + (flowers[i] > 0 ? flowers[i] : 0); + + map index; + int res = INT_MIN; + for(int i = 0; i < flowers.size(); i ++){ + if(index.count(flowers[i])){ + int end = flowers[i], maxi = i, mini = index[end]; + if(maxi != mini){ + int tres = 2 * end; + mini ++, maxi --; + if(mini <= maxi) tres += presum[maxi + 1] - presum[mini]; + res = max(res, tres); + } + } + else + index[flowers[i]] = i; + } + return res; + } +}; + + +int main() { + + vector flowers1 = {1, 2, 3, 1, 2}; + cout << Solution().maximumBeauty(flowers1) << endl; + // 8 + + vector flowers2 = {100, 1, 1, -3, 1}; + cout << Solution().maximumBeauty(flowers2) << endl; + // 3 + + vector flowers3 = {-1, -2, 0, -1}; + cout << Solution().maximumBeauty(flowers3) << endl; + // -2 + + return 0; +} diff --git a/1501-2000/1790-Check-if-One-String-Swap-Can-Make-Strings-Equal/cpp-1790/CMakeLists.txt b/1501-2000/1790-Check-if-One-String-Swap-Can-Make-Strings-Equal/cpp-1790/CMakeLists.txt new file mode 100644 index 00000000..d5d5e4ff --- /dev/null +++ b/1501-2000/1790-Check-if-One-String-Swap-Can-Make-Strings-Equal/cpp-1790/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1501-2000/1790-Check-if-One-String-Swap-Can-Make-Strings-Equal/cpp-1790/main.cpp b/1501-2000/1790-Check-if-One-String-Swap-Can-Make-Strings-Equal/cpp-1790/main.cpp new file mode 100644 index 00000000..6b071aa7 --- /dev/null +++ b/1501-2000/1790-Check-if-One-String-Swap-Can-Make-Strings-Equal/cpp-1790/main.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/check-if-one-string-swap-can-make-strings-equal/ +/// Author : liuyubobobo +/// Time : 2021-03-13 + +#include +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + bool areAlmostEqual(string s1, string s2) { + + int a = -1, b = -1; + for(int i = 0; i < s1.size(); i ++) + if(s1[i] != s2[i]){ + if(a == -1) a = i; + else if(b == -1) b = i; + else return false; + } + + if(a == -1 && b == -1) return true; + + if(a != -1 && b == -1) return false; + + return s1[a] == s2[b] && s1[b] == s2[a]; + } +}; + + +int main() { + + cout << Solution().areAlmostEqual("bank", "kanb") << endl; + // 1 + + cout << Solution().areAlmostEqual("attack", "defend") << endl; + // 0 + + cout << Solution().areAlmostEqual("kelb", "kelb") << endl; + // 1 + + cout << Solution().areAlmostEqual("abcd", "dcba") << endl; + // 0 + + return 0; +} diff --git a/1501-2000/1791-Find-Center-of-Star-Graph/cpp-1791/CMakeLists.txt b/1501-2000/1791-Find-Center-of-Star-Graph/cpp-1791/CMakeLists.txt new file mode 100644 index 00000000..aab7d499 --- /dev/null +++ b/1501-2000/1791-Find-Center-of-Star-Graph/cpp-1791/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main4.cpp) \ No newline at end of file diff --git a/1501-2000/1791-Find-Center-of-Star-Graph/cpp-1791/main.cpp b/1501-2000/1791-Find-Center-of-Star-Graph/cpp-1791/main.cpp new file mode 100644 index 00000000..84031eca --- /dev/null +++ b/1501-2000/1791-Find-Center-of-Star-Graph/cpp-1791/main.cpp @@ -0,0 +1,75 @@ +/// Source : https://leetcode.com/problems/find-center-of-star-graph/ +/// Author : liuyubobobo +/// Time : 2021-03-13 + +#include +#include +#include +#include + +using namespace std; + + +/// BFS +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int findCenter(vector>& edges) { + + int n = edges.size() + 1; + + vector> g(n); + vector visited(n, false); + vector degree(n, 0); + for(const vector& e: edges){ + int a = e[0] - 1, b = e[1] - 1; + degree[a] ++; + degree[b] ++; + g[a].insert(b); + g[b].insert(a); + } + + queue q; + for(int i = 0; i < n; i ++) + if(degree[i] == 1){ + degree[i] --; + q.push(i); + } + + int res = 0; + while(!q.empty()){ + int cur = q.front(); + q.pop(); + + res = cur; + + visited[cur] = true; + for(int next: g[cur]) + if(!visited[next]){ + degree[next] --; + if(degree[next] == 1 && !visited[next]) + q.push(next); + } + } + return res + 1; + } +}; + + +int main() { + + vector> edges1 = { + {1,2},{2,3},{4,2} + }; + cout << Solution().findCenter(edges1) << endl; + // 2 + + vector> edges2 = { + {1,2},{5,1},{1,3},{1,4} + }; + cout << Solution().findCenter(edges2) << endl; + // 1 + + return 0; +} diff --git a/1501-2000/1791-Find-Center-of-Star-Graph/cpp-1791/main2.cpp b/1501-2000/1791-Find-Center-of-Star-Graph/cpp-1791/main2.cpp new file mode 100644 index 00000000..af8313ec --- /dev/null +++ b/1501-2000/1791-Find-Center-of-Star-Graph/cpp-1791/main2.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/find-center-of-star-graph/ +/// Author : liuyubobobo +/// Time : 2021-03-13 + +#include +#include +#include +#include + +using namespace std; + + +/// Using Degrees +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int findCenter(vector>& edges) { + + int n = edges.size() + 1; + + vector degree(n, 0); + for(const vector& e: edges){ + int a = e[0] - 1, b = e[1] - 1; + degree[a] ++; + degree[b] ++; + } + + int maxd = 0, res = 0; + for(int i = 0; i < n; i ++) + if(degree[i] > maxd) maxd = degree[i], res = i; + return res + 1; + } +}; + + +int main() { + + vector> edges1 = { + {1,2},{2,3},{4,2} + }; + cout << Solution().findCenter(edges1) << endl; + // 2 + + vector> edges2 = { + {1,2},{5,1},{1,3},{1,4} + }; + cout << Solution().findCenter(edges2) << endl; + // 1 + + return 0; +} diff --git a/1501-2000/1791-Find-Center-of-Star-Graph/cpp-1791/main3.cpp b/1501-2000/1791-Find-Center-of-Star-Graph/cpp-1791/main3.cpp new file mode 100644 index 00000000..c7e2e85c --- /dev/null +++ b/1501-2000/1791-Find-Center-of-Star-Graph/cpp-1791/main3.cpp @@ -0,0 +1,55 @@ +/// Source : https://leetcode.com/problems/find-center-of-star-graph/ +/// Author : liuyubobobo +/// Time : 2021-03-13 + +#include +#include +#include +#include + +using namespace std; + + +/// Using Degrees +/// The star's degree must be n - 1 +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int findCenter(vector>& edges) { + + int n = edges.size() + 1; + + vector degree(n, 0); + for(const vector& e: edges){ + int a = e[0] - 1, b = e[1] - 1; + + degree[a] ++; + if(degree[a] == n) return a + 1; + + degree[b] ++; + if(degree[b] == n) return b + 1; + } + + assert(false); + return -1; + } +}; + + +int main() { + + vector> edges1 = { + {1,2},{2,3},{4,2} + }; + cout << Solution().findCenter(edges1) << endl; + // 2 + + vector> edges2 = { + {1,2},{5,1},{1,3},{1,4} + }; + cout << Solution().findCenter(edges2) << endl; + // 1 + + return 0; +} diff --git a/1501-2000/1791-Find-Center-of-Star-Graph/cpp-1791/main4.cpp b/1501-2000/1791-Find-Center-of-Star-Graph/cpp-1791/main4.cpp new file mode 100644 index 00000000..2aa4b514 --- /dev/null +++ b/1501-2000/1791-Find-Center-of-Star-Graph/cpp-1791/main4.cpp @@ -0,0 +1,41 @@ +/// Source : https://leetcode.com/problems/find-center-of-star-graph/ +/// Author : liuyubobobo +/// Time : 2021-03-13 + +#include +#include +#include +#include + +using namespace std; + + +/// The star must occurs in every edge +/// Time Complexity: O(1) +/// Space Complexity: O(1) +class Solution { +public: + int findCenter(vector>& edges) { + + if(edges[0][0] == edges[1][0] || edges[0][0] == edges[1][1]) return edges[0][0]; + return edges[0][1]; + } +}; + + +int main() { + + vector> edges1 = { + {1,2},{2,3},{4,2} + }; + cout << Solution().findCenter(edges1) << endl; + // 2 + + vector> edges2 = { + {1,2},{5,1},{1,3},{1,4} + }; + cout << Solution().findCenter(edges2) << endl; + // 1 + + return 0; +} diff --git a/1501-2000/1792-Maximum-Average-Pass-Ratio/cpp-1792/CMakeLists.txt b/1501-2000/1792-Maximum-Average-Pass-Ratio/cpp-1792/CMakeLists.txt new file mode 100644 index 00000000..ce73aee9 --- /dev/null +++ b/1501-2000/1792-Maximum-Average-Pass-Ratio/cpp-1792/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1501-2000/1792-Maximum-Average-Pass-Ratio/cpp-1792/main.cpp b/1501-2000/1792-Maximum-Average-Pass-Ratio/cpp-1792/main.cpp new file mode 100644 index 00000000..61abb5ce --- /dev/null +++ b/1501-2000/1792-Maximum-Average-Pass-Ratio/cpp-1792/main.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/maximum-average-pass-ratio/submissions/ +/// Author : liuyubobobo +/// Time : 2021-03-13 + +#include +#include +#include + +using namespace std; + + +/// Using Priority Queue +/// Time Complexity: O(n + mlogn) +/// Space Complexity: O(n) +class Solution { +public: + double maxAverageRatio(vector>& classes, int extraStudents) { + + priority_queue> pq; + for(int i = 0; i < classes.size(); i ++) + pq.push({(double)(classes[i][0] + 1) / (classes[i][1] + 1) - (double)classes[i][0] / classes[i][1], i}); + + while(extraStudents){ + int i = pq.top().second; + pq.pop(); + + classes[i][0] ++; + classes[i][1] ++; + pq.push({(double)(classes[i][0] + 1) / (classes[i][1] + 1) - (double)classes[i][0] / classes[i][1], i}); + extraStudents --; + } + + double sum = 0.0; + for(const vector& data: classes) + sum += (double)data[0] / data[1]; + return sum / classes.size(); + } +}; + + +int main() { + + vector> classes1 = {{1, 2}, {3, 5}, {2, 2}}; + cout << Solution().maxAverageRatio(classes1, 2) << endl; + // 0.78333 + + vector> classes2 = {{2, 4}, {3, 9}, {4, 5}, {2, 10}}; + cout << Solution().maxAverageRatio(classes2, 4) << endl; + // 0.53485 + + return 0; +} diff --git a/1501-2000/1793-Maximum-Score-of-a-Good-Subarray/cpp-1793/CMakeLists.txt b/1501-2000/1793-Maximum-Score-of-a-Good-Subarray/cpp-1793/CMakeLists.txt new file mode 100644 index 00000000..a373769d --- /dev/null +++ b/1501-2000/1793-Maximum-Score-of-a-Good-Subarray/cpp-1793/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main2.cpp) \ No newline at end of file diff --git a/1501-2000/1793-Maximum-Score-of-a-Good-Subarray/cpp-1793/main.cpp b/1501-2000/1793-Maximum-Score-of-a-Good-Subarray/cpp-1793/main.cpp new file mode 100644 index 00000000..08251c34 --- /dev/null +++ b/1501-2000/1793-Maximum-Score-of-a-Good-Subarray/cpp-1793/main.cpp @@ -0,0 +1,62 @@ +/// Source : https://leetcode.com/problems/maximum-score-of-a-good-subarray/ +/// Author : liuyubobobo +/// Time : 2021-03-14 + +#include +#include +#include + +using namespace std; + + +/// Mono Stack +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int maximumScore(vector& nums, int k) { + + int n = nums.size(); + + vector right(n); + stack stack; + for(int i = 0; i < n; i ++){ + while(!stack.empty() && nums[i] < nums[stack.top()]) + right[stack.top()] = i - 1, stack.pop(); + stack.push(i); + } + while(!stack.empty()) right[stack.top()] = n - 1, stack.pop(); + + vector left(n); + for(int i = n - 1; i >= 0; i --){ + while(!stack.empty() && nums[i] < nums[stack.top()]) + left[stack.top()] = i + 1, stack.pop(); + stack.push(i); + } + while(!stack.empty()) left[stack.top()] = 0, stack.pop(); + + int res = 0; + for(int i = 0; i < n; i ++) + if(left[i] <= k && k <= right[i]) + res = max(res, nums[i] * (right[i] - left[i] + 1)); + return res; + } +}; + + +int main() { + + vector nums1 = {1, 4, 3, 7, 4, 5}; + cout << Solution().maximumScore(nums1, 3) << endl; + // 15 + + vector nums2 = {5,5,4,5,4,1,1,1}; + cout << Solution().maximumScore(nums2, 0) << endl; + // 20 + + vector nums3 = {6569,9667,3148,7698,1622,2194,793,9041,1670,1872}; + cout << Solution().maximumScore(nums3, 5) << endl; + // 9732 + + return 0; +} diff --git a/1501-2000/1793-Maximum-Score-of-a-Good-Subarray/cpp-1793/main2.cpp b/1501-2000/1793-Maximum-Score-of-a-Good-Subarray/cpp-1793/main2.cpp new file mode 100644 index 00000000..f31b0518 --- /dev/null +++ b/1501-2000/1793-Maximum-Score-of-a-Good-Subarray/cpp-1793/main2.cpp @@ -0,0 +1,59 @@ +/// Source : https://leetcode.com/problems/maximum-score-of-a-good-subarray/ +/// Author : liuyubobobo +/// Time : 2021-03-14 + +#include +#include + +using namespace std; + + +/// Two Pointers and Greedy +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int maximumScore(vector& nums, int k) { + + int l = k - 1, r = k + 1; + int res =nums[k], curmin = nums[k]; + while(l >= 0 || r < nums.size()){ + if(l < 0){ + curmin = min(curmin, nums[r]); + r ++; + } + else if(r >= nums.size()){ + curmin = min(curmin, nums[l]); + l --; + } + else if(nums[l] > nums[r]){ + curmin = min(curmin, nums[l]); + l --; + } + else{ + curmin = min(curmin, nums[r]); + r ++; + } + res = max(res, curmin * (r - l + 1)); + } + return res; + } +}; + + +int main() { + + vector nums1 = {1, 4, 3, 7, 4, 5}; + cout << Solution().maximumScore(nums1, 3) << endl; + // 15 + + vector nums2 = {5,5,4,5,4,1,1,1}; + cout << Solution().maximumScore(nums2, 0) << endl; + // 20 + + vector nums3 = {6569,9667,3148,7698,1622,2194,793,9041,1670,1872}; + cout << Solution().maximumScore(nums3, 5) << endl; + // 9732 + + return 0; +} diff --git a/1501-2000/1794-Count-Pairs-of-Equal-Substrings-With-Minimum-Difference/cpp-1794/CMakeLists.txt b/1501-2000/1794-Count-Pairs-of-Equal-Substrings-With-Minimum-Difference/cpp-1794/CMakeLists.txt new file mode 100644 index 00000000..6bd9d1d2 --- /dev/null +++ b/1501-2000/1794-Count-Pairs-of-Equal-Substrings-With-Minimum-Difference/cpp-1794/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1794) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1794 main.cpp) \ No newline at end of file diff --git a/1501-2000/1794-Count-Pairs-of-Equal-Substrings-With-Minimum-Difference/cpp-1794/main.cpp b/1501-2000/1794-Count-Pairs-of-Equal-Substrings-With-Minimum-Difference/cpp-1794/main.cpp new file mode 100644 index 00000000..9663dae4 --- /dev/null +++ b/1501-2000/1794-Count-Pairs-of-Equal-Substrings-With-Minimum-Difference/cpp-1794/main.cpp @@ -0,0 +1,61 @@ +/// Source : https://leetcode.com/problems/count-pairs-of-equal-substrings-with-minimum-difference/ +/// Author : liuyubobobo +/// Time : 2021-03-21 + +#include +#include + +using namespace std; + + +/// Greedy +/// Time Compleixty: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int countQuadruples(string s1, string s2) { + + vector first(26, -1), last(26, -1); + for(int i = 0; i < s1.size(); i ++) + if(first[s1[i] - 'a'] == -1) + first[s1[i] - 'a'] = i; + + for(int i = s2.size() - 1; i >= 0; i --) + if(last[s2[i] - 'a'] == -1) + last[s2[i] - 'a'] = i; + + int minv = INT_MAX, minc = -1; + for(int i = 0; i < 26; i ++) + if(first[i] != -1 && last[i] != -1){ + if(first[i] - last[i] < minv) + minv = first[i] - last[i], minc = i; + else if(first[i] - last[i] == minv && first[i] < first[minc]) + minc = i; + } + + if(minc == -1) return 0; + + int res = 0, i = first[minc], j = last[minc]; + while(i < s1.size() && j < s2.size() && s1[i] == s2[j]) + res ++, i ++, j ++; + return res; + } +}; + + +int main() { + + cout << Solution().countQuadruples("abcd", "bccda") << endl; + // 1 + + cout << Solution().countQuadruples("ab", "cd") << endl; + // 0 + + cout << Solution().countQuadruples("dwtgmqucavlta", "gupciaqadwtgm") << endl; + // 5 + + cout << Solution().countQuadruples("rzsntggflhavoq", "qshrzsn") << endl; + // 4 + + return 0; +} diff --git a/1501-2000/1796-Second-Largest-Digit-in-a-String/cpp-1796/CMakeLists.txt b/1501-2000/1796-Second-Largest-Digit-in-a-String/cpp-1796/CMakeLists.txt new file mode 100644 index 00000000..c984ffb4 --- /dev/null +++ b/1501-2000/1796-Second-Largest-Digit-in-a-String/cpp-1796/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1796) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1796 main2.cpp) \ No newline at end of file diff --git a/1501-2000/1796-Second-Largest-Digit-in-a-String/cpp-1796/main.cpp b/1501-2000/1796-Second-Largest-Digit-in-a-String/cpp-1796/main.cpp new file mode 100644 index 00000000..2d9eb8c2 --- /dev/null +++ b/1501-2000/1796-Second-Largest-Digit-in-a-String/cpp-1796/main.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/second-largest-digit-in-a-string/ +/// Author : liuyubobobo +/// Time : 2021-03-21 + +#include +#include + +using namespace std; + + +/// Using Set +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int secondHighest(string s) { + + set d; + for(char c: s) + if(isdigit(c)) d.insert(c - '0'); + + if(d.size() <= 1) return -1; + + set::reverse_iterator iter = d.rbegin(); + iter ++; + return *iter; + } +}; + + +int main() { + + cout << Solution().secondHighest("ck077") << endl; + // 0 + + return 0; +} diff --git a/1501-2000/1796-Second-Largest-Digit-in-a-String/cpp-1796/main2.cpp b/1501-2000/1796-Second-Largest-Digit-in-a-String/cpp-1796/main2.cpp new file mode 100644 index 00000000..10e0a8b2 --- /dev/null +++ b/1501-2000/1796-Second-Largest-Digit-in-a-String/cpp-1796/main2.cpp @@ -0,0 +1,36 @@ +/// Source : https://leetcode.com/problems/second-largest-digit-in-a-string/ +/// Author : liuyubobobo +/// Time : 2021-03-21 + +#include +#include + +using namespace std; + + +/// Only the first two largest number recorded +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int secondHighest(string s) { + + int a = -1, b = -1; + for(char c: s) + if(isdigit(c)){ + int t = c - '0'; + if(t > a) b = a, a = t; + else if(t != a && t > b) b = t; + } + return b; + } +}; + + +int main() { + + cout << Solution().secondHighest("ck077") << endl; + // 0 + + return 0; +} diff --git a/1501-2000/1797-Design-Authentication-Manager/cpp-1797/CMakeLists.txt b/1501-2000/1797-Design-Authentication-Manager/cpp-1797/CMakeLists.txt new file mode 100644 index 00000000..f8477bff --- /dev/null +++ b/1501-2000/1797-Design-Authentication-Manager/cpp-1797/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1797) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1797 main.cpp) \ No newline at end of file diff --git a/1501-2000/1797-Design-Authentication-Manager/cpp-1797/main.cpp b/1501-2000/1797-Design-Authentication-Manager/cpp-1797/main.cpp new file mode 100644 index 00000000..ab36ccb6 --- /dev/null +++ b/1501-2000/1797-Design-Authentication-Manager/cpp-1797/main.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/design-authentication-manager/ +/// Author : liuyubobobo +/// Time : 2021-03-21 + +#include +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class AuthenticationManager { + +private: + int t; + unordered_map expire; + +public: + AuthenticationManager(int timeToLive) : t(timeToLive) {} + + void generate(string tokenId, int currentTime) { + expire[tokenId] = currentTime + t; + } + + void renew(string tokenId, int currentTime) { + + if(expire.count(tokenId) && currentTime >= expire[tokenId]) + expire.erase(tokenId); + + if(expire.count(tokenId)) + expire[tokenId] = currentTime + t; + } + + int countUnexpiredTokens(int currentTime) { + + vector del; + for(const pair& p: expire) + if(currentTime >= p.second) del.push_back(p.first); + + for(const string& s: del) + expire.erase(s); + return expire.size(); + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1798-Maximum-Number-of-Consecutive-Values-You-Can-Make/cpp-1798/CMakeLists.txt b/1501-2000/1798-Maximum-Number-of-Consecutive-Values-You-Can-Make/cpp-1798/CMakeLists.txt new file mode 100644 index 00000000..32277ee8 --- /dev/null +++ b/1501-2000/1798-Maximum-Number-of-Consecutive-Values-You-Can-Make/cpp-1798/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1798) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1798 main.cpp) \ No newline at end of file diff --git a/1501-2000/1798-Maximum-Number-of-Consecutive-Values-You-Can-Make/cpp-1798/main.cpp b/1501-2000/1798-Maximum-Number-of-Consecutive-Values-You-Can-Make/cpp-1798/main.cpp new file mode 100644 index 00000000..226ee8e6 --- /dev/null +++ b/1501-2000/1798-Maximum-Number-of-Consecutive-Values-You-Can-Make/cpp-1798/main.cpp @@ -0,0 +1,32 @@ +/// Source : https://leetcode.com/problems/maximum-number-of-consecutive-values-you-can-make/ +/// Author : liuyubobobo +/// Time : 2021-03-21 + +#include +#include + +using namespace std; + + +/// Sorting and Greedy +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + int getMaximumConsecutive(vector& coins) { + + sort(coins.begin(), coins.end()); + + int cur = 0; + for(int e: coins) + if(e <= cur + 1) cur += e; + else break; + return cur + 1; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1799-Maximize-Score-After-N-Operations/cpp-1799/CMakeLists.txt b/1501-2000/1799-Maximize-Score-After-N-Operations/cpp-1799/CMakeLists.txt new file mode 100644 index 00000000..c1d2568e --- /dev/null +++ b/1501-2000/1799-Maximize-Score-After-N-Operations/cpp-1799/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1799) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1799 main.cpp) \ No newline at end of file diff --git a/1501-2000/1799-Maximize-Score-After-N-Operations/cpp-1799/main.cpp b/1501-2000/1799-Maximize-Score-After-N-Operations/cpp-1799/main.cpp new file mode 100644 index 00000000..529d9baf --- /dev/null +++ b/1501-2000/1799-Maximize-Score-After-N-Operations/cpp-1799/main.cpp @@ -0,0 +1,73 @@ +/// Source : https://leetcode.com/problems/maximize-score-after-n-operations/ +/// Author : liuyubobobo +/// Time : 2021-03-21 + +#include +#include + +using namespace std; + + +/// State Compression Memory Search +/// Time Complexity: O(n^3 * (2^n)) +/// Space Complexity: O(n * 2^n) +class Solution { + +private: + int n; + +public: + int maxScore(vector& nums) { + + n = nums.size(); + vector> table(n, vector(n, 0)); + for(int i = 0; i < nums.size(); i ++) + for(int j = i + 1; j < nums.size(); j ++) + table[i][j] = table[j][i] = gcd(nums[i], nums[j]); + + vector> dp(n / 2, vector(1 << n, -1)); + return dfs(nums, 0, 0, dp, table); + } + +private: + int dfs(const vector& nums, int op, int state, vector>& dp, + const vector>& table){ + + if(op == dp.size()) return 0; + if(dp[op][state] != -1) return dp[op][state]; + + int res = 0; + for(int i = 0; i < n; i ++) + if((state & (1 << i)) == 0) + for(int j = i + 1; j < n; j ++) + if((state & (1 << j)) == 0) + res = max(res, table[i][j] * (op + 1) + dfs(nums, op + 1, state + (1 << i) + (1 << j), dp, table)); + return dp[op][state] = res; + } + + int gcd(int x, int y){ + + if(x > y) swap(x, y); + + if(y % x == 0) return x; + return gcd(y % x, x); + } +}; + + +int main() { + + vector nums1 = {1, 2}; + cout << Solution().maxScore(nums1) << endl; + // 1 + + vector nums2 = {3, 4, 6, 8}; + cout << Solution().maxScore(nums2) << endl; + // 11 + + vector nums3 = {1, 2, 3, 4, 5, 6}; + cout << Solution().maxScore(nums3) << endl; + // 14 + + return 0; +} diff --git a/1501-2000/1800-Maximum-Ascending-Subarray-Sum/cpp-1800/CMakeLists.txt b/1501-2000/1800-Maximum-Ascending-Subarray-Sum/cpp-1800/CMakeLists.txt new file mode 100644 index 00000000..ec9e7c4c --- /dev/null +++ b/1501-2000/1800-Maximum-Ascending-Subarray-Sum/cpp-1800/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main2.cpp) \ No newline at end of file diff --git a/1501-2000/1800-Maximum-Ascending-Subarray-Sum/cpp-1800/main.cpp b/1501-2000/1800-Maximum-Ascending-Subarray-Sum/cpp-1800/main.cpp new file mode 100644 index 00000000..8892f94c --- /dev/null +++ b/1501-2000/1800-Maximum-Ascending-Subarray-Sum/cpp-1800/main.cpp @@ -0,0 +1,60 @@ +/// Source : https://leetcode.com/problems/maximum-ascending-subarray-sum/ +/// Author : liuyubobobo +/// Time : 2021-03-20 + +#include +#include + +using namespace std; + + +/// Presum + Brute Force +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { +public: + int maxAscendingSum(vector& nums) { + + int n = nums.size(); + vector presum(n + 1, 0); + for(int i = 0; i < n; i ++) + presum[i + 1] = presum[i] + nums[i]; + + int res = *max_element(nums.begin(), nums.end()); + for(int start = 0; start < n; start ++) + for(int end = start + 1; end < n; end ++) + if(ok(nums, start, end)) + res = max(res, presum[end + 1] - presum[start]); + return res; + } + +private: + bool ok(const vector& nums, int a, int b){ + + for(int i = a + 1; i <= b; i ++) + if(nums[i] <= nums[i - 1]) return false; + return true; + } +}; + + +int main() { + + vector nums1 = {10, 20, 30, 5, 10, 50}; + cout << Solution().maxAscendingSum(nums1) << endl; + // 65 + + vector nums2 = {10, 20, 30, 40, 50}; + cout << Solution().maxAscendingSum(nums2) << endl; + // 150 + + vector nums3 = {12,17,15,13,10,11,12}; + cout << Solution().maxAscendingSum(nums3) << endl; + // 33 + + vector nums4 = {100,10,1}; + cout << Solution().maxAscendingSum(nums4) << endl; + // 100 + + return 0; +} diff --git a/1501-2000/1800-Maximum-Ascending-Subarray-Sum/cpp-1800/main2.cpp b/1501-2000/1800-Maximum-Ascending-Subarray-Sum/cpp-1800/main2.cpp new file mode 100644 index 00000000..b23f9909 --- /dev/null +++ b/1501-2000/1800-Maximum-Ascending-Subarray-Sum/cpp-1800/main2.cpp @@ -0,0 +1,49 @@ +/// Source : https://leetcode.com/problems/maximum-ascending-subarray-sum/ +/// Author : liuyubobobo +/// Time : 2021-03-21 + +#include +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int maxAscendingSum(vector& nums) { + + int cur = nums[0], res = nums[0]; + for(int i = 1; i <= nums.size(); i ++) + if(i == nums.size() || nums[i] <= nums[i - 1]){ + res = max(res, cur); + if(i < nums.size()) cur = nums[i]; + } + else cur += nums[i]; + return res; + } +}; + + +int main() { + + vector nums1 = {10, 20, 30, 5, 10, 50}; + cout << Solution().maxAscendingSum(nums1) << endl; + // 65 + + vector nums2 = {10, 20, 30, 40, 50}; + cout << Solution().maxAscendingSum(nums2) << endl; + // 150 + + vector nums3 = {12,17,15,13,10,11,12}; + cout << Solution().maxAscendingSum(nums3) << endl; + // 33 + + vector nums4 = {100,10,1}; + cout << Solution().maxAscendingSum(nums4) << endl; + // 100 + + return 0; +} diff --git a/1501-2000/1801-Number-of-Orders-in-the-Backlog/cpp-1801/CMakeLists.txt b/1501-2000/1801-Number-of-Orders-in-the-Backlog/cpp-1801/CMakeLists.txt new file mode 100644 index 00000000..81ad8b42 --- /dev/null +++ b/1501-2000/1801-Number-of-Orders-in-the-Backlog/cpp-1801/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1501-2000/1801-Number-of-Orders-in-the-Backlog/cpp-1801/main.cpp b/1501-2000/1801-Number-of-Orders-in-the-Backlog/cpp-1801/main.cpp new file mode 100644 index 00000000..a37ce4a5 --- /dev/null +++ b/1501-2000/1801-Number-of-Orders-in-the-Backlog/cpp-1801/main.cpp @@ -0,0 +1,82 @@ +/// Source : https://leetcode.com/problems/number-of-orders-in-the-backlog/ +/// Author : liuyubobobo +/// Time : 2021-03-20 + +#include +#include +#include + +using namespace std; + + +/// Using Prioriity Queue to simulate +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + int getNumberOfBacklogOrders(vector>& orders) { + + priority_queue> buyq; + priority_queue, vector>, greater>> sellq; + + for(const vector& order: orders){ + int price = order[0], type = order[2]; + long long amount = (long long)order[1]; + + if(type){ // sell + while(amount != 0ll && !buyq.empty() && buyq.top().first >= price){ + long long t = min(amount, buyq.top().second); + + pair top_e = buyq.top(); + buyq.pop(); + top_e.second -= t; + amount -= t; + + if(top_e.second != 0ll) buyq.push(top_e); + } + + if(amount != 0ll) sellq.push({price, amount}); + } + else{ // buy + + while(amount != 0ll && !sellq.empty() && sellq.top().first <= price){ + long long t = min(amount, sellq.top().second); + + pair top_e = sellq.top(); + sellq.pop(); + top_e.second -= t; + amount -= t; + + if(top_e.second != 0ll) sellq.push(top_e); + } + + if(amount != 0ll) buyq.push({price, amount}); + } + } + + long long MOD = 1e9 + 7; + + long long sum = 0ll; + while(!sellq.empty()) sum += sellq.top().second, sellq.pop(); + while(!buyq.empty()) sum += buyq.top().second, buyq.pop(); + return sum % MOD; + } +}; + + +int main() { + + vector> orders1 = { + {10,5,0},{15,2,1},{25,1,1},{30,4,0} + }; + cout << Solution().getNumberOfBacklogOrders(orders1) << endl; + // 6 + + vector> orders2 = { + {7,1000000000,1},{15,3,0},{5,999999995,0},{5,1,1} + }; + cout << Solution().getNumberOfBacklogOrders(orders2) << endl; + // 999999984 + + return 0; +} diff --git a/1501-2000/1802-Maximum-Value-at-a-Given-Index-in-a-Bounded-Array/cpp-1802/CMakeLists.txt b/1501-2000/1802-Maximum-Value-at-a-Given-Index-in-a-Bounded-Array/cpp-1802/CMakeLists.txt new file mode 100644 index 00000000..ce73aee9 --- /dev/null +++ b/1501-2000/1802-Maximum-Value-at-a-Given-Index-in-a-Bounded-Array/cpp-1802/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1501-2000/1802-Maximum-Value-at-a-Given-Index-in-a-Bounded-Array/cpp-1802/main.cpp b/1501-2000/1802-Maximum-Value-at-a-Given-Index-in-a-Bounded-Array/cpp-1802/main.cpp new file mode 100644 index 00000000..5690aae0 --- /dev/null +++ b/1501-2000/1802-Maximum-Value-at-a-Given-Index-in-a-Bounded-Array/cpp-1802/main.cpp @@ -0,0 +1,64 @@ +/// Source : https://leetcode.com/problems/maximum-value-at-a-given-index-in-a-bounded-array/ +/// Author : liuyubobobo +/// Time : 2021-03-20 + +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(log(maxSum)) +/// Space Complexity: O(1) +class Solution { +public: + int maxValue(int n, int index, int maxSum) { + + long long l = 1ll, r = (long long)maxSum; + while(l < r){ + + long long mid = (l + r + 1ll) / 2ll; + if(ok(n, index, maxSum, mid)) l = mid; + else r = mid - 1ll; + } + return l; + } + +private: + bool ok(int n, int index, long long maxSum, long long k){ + + int left = index, right = n - index - 1; + long long sum = 0ll; + if(left) sum += get_sum(k - 1, left); + if(right) sum += get_sum(k - 1, right); + return sum + k <= maxSum; + } + + long long get_sum(long long maxv, int n){ + + if(maxv - (long long)(n - 1) > 0) + return (maxv + maxv - (long long)(n - 1)) * (long long)n / 2ll; + + int n1 = maxv; + long long sum = (maxv + maxv - (long long)(n1 - 1)) * (long long)n1 / 2ll; + return sum + (long long)(n - n1); + } +}; + + +int main() { + + cout << Solution().maxValue(4, 2, 6) << endl; + // 2 + + cout << Solution().maxValue(6, 1, 10) << endl; + // 3 + + cout << Solution().maxValue(3, 2, 18) << endl; + // 7 + + cout << Solution().maxValue(8, 7, 14) << endl; + // 4 + + return 0; +} diff --git a/1501-2000/1803-Count-Pairs-With-XOR-in-a-Range/cpp-1803/CMakeLists.txt b/1501-2000/1803-Count-Pairs-With-XOR-in-a-Range/cpp-1803/CMakeLists.txt new file mode 100644 index 00000000..74cc3ee6 --- /dev/null +++ b/1501-2000/1803-Count-Pairs-With-XOR-in-a-Range/cpp-1803/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) \ No newline at end of file diff --git a/1501-2000/1803-Count-Pairs-With-XOR-in-a-Range/cpp-1803/main.cpp b/1501-2000/1803-Count-Pairs-With-XOR-in-a-Range/cpp-1803/main.cpp new file mode 100644 index 00000000..39fb2a8e --- /dev/null +++ b/1501-2000/1803-Count-Pairs-With-XOR-in-a-Range/cpp-1803/main.cpp @@ -0,0 +1,121 @@ +/// Source : https://leetcode.com/problems/count-pairs-with-xor-in-a-range/ +/// Author : liuyubobobo +/// Time : 2021-03-21 + +#include +#include + +using namespace std; + + +/// Trie +/// Time Complexity: O(nlog(maxnum)) +/// Space Complexity: O(nlog(maxnum)) +class Solution { + +public: + int countPairs(vector& nums, int low, int high) { + + int maxv = *max_element(nums.begin(), nums.end()); + maxv = max(maxv, high); + int B = 0; + while(maxv) B ++, maxv >>= 1; + + vector>> trie(1, {0, {-1, -1}}); + int res = 0; + vector highb = get_binary(high, B), lowb = get_binary(low - 1, B); + for(int num: nums){ + + vector v = get_binary(num, B); + int a = solve(trie, 0, v, 0, highb); + int b = solve(trie, 0, v, 0, lowb); + res += a - b; + + add(trie, 0, v, 0); + } + + return res; + } + +private: + int solve(const vector>>& trie, int root, + const vector& num, int index, const vector& k){ + + if(root >= trie.size()) return 0; + + if(index == k.size()) + return trie[root].first; + + int left = trie[root].second.first, right = trie[root].second.second; + + if(num[index] == 0 && k[index] == 0) + return solve(trie, left, num, index + 1, k); + + if(num[index] == 0 && k[index] == 1) + return (left == - 1 ? 0 : trie[left].first) + solve(trie, right, num, index + 1, k); + + if(num[index] == 1 && k[index] == 0) + return solve(trie, right, num, index + 1, k); + + return (right == -1 ? 0 : trie[right].first) + solve(trie, left, num, index + 1, k); + } + + void add(vector>>& trie, int root, const vector& num, int index){ + + if(index == num.size()){ + trie[root].first += 1; + return; + } + + int left = trie[root].second.first, right = trie[root].second.second; + if(num[index]){ + if(right == -1){ + trie.push_back({0, {-1, -1}}); + right = trie.size() - 1; + trie[root].second.second = right; + } + add(trie, right, num, index + 1); + } + else{ + if(left == -1){ + trie.push_back({0, {-1, -1}}); + left = trie.size() - 1; + trie[root].second.first = left; + } + add(trie, left, num, index + 1); + } + + trie[root].first = (left == -1 ? 0 : trie[left].first) + (right == -1 ? 0 : trie[right].first); + } + + vector get_binary(int num, int B){ + + vector res(B); + for(int i = 0; i < B; i ++) + res[i] = (num & 1), num >>= 1; + reverse(res.begin(), res.end()); + return res; + } +}; + + +int main() { + + vector nums1 = {1, 4, 2, 7}; + cout << Solution().countPairs(nums1, 2, 6) << endl; + // 6 + + vector nums2 = {9,8,4,2,1}; + cout << Solution().countPairs(nums2, 5, 14) << endl; + // 8 + + vector nums3 = {7881,760,709,2937,1245,720,5187,6361,3793,141,7238}; + cout << Solution().countPairs(nums3, 1492, 3832) << endl; + // 16 + + vector nums4 = {3856,3174,2182,7497,6155,4589,3581,4548,3982,2508}; + cout << Solution().countPairs(nums4, 6903, 6946) << endl; + // 0 + + return 0; +} diff --git a/1501-2000/1804-Implement-Trie-II/cpp-1804/CMakeLists.txt b/1501-2000/1804-Implement-Trie-II/cpp-1804/CMakeLists.txt new file mode 100644 index 00000000..7f797e2d --- /dev/null +++ b/1501-2000/1804-Implement-Trie-II/cpp-1804/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1804) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1804 main.cpp) \ No newline at end of file diff --git a/1501-2000/1804-Implement-Trie-II/cpp-1804/main.cpp b/1501-2000/1804-Implement-Trie-II/cpp-1804/main.cpp new file mode 100644 index 00000000..b30a9411 --- /dev/null +++ b/1501-2000/1804-Implement-Trie-II/cpp-1804/main.cpp @@ -0,0 +1,102 @@ +/// Source : https://leetcode.com/problems/implement-trie-ii-prefix-tree/ +/// Author : liuyubobobo +/// Time : 2021-06-18 + +#include +#include +#include + +using namespace std; + + +/// Trie +/// Time Complexity: O(|s|) +/// Space Complexity: O(total_characters) +class Trie { + +private: + class Node{ + + public: + vector next; + int word_cnt, sz; + + Node() : next(26, nullptr), word_cnt(0), sz(0) {}; + }; + + Node* root; + +public: + Trie() : root(new Node()) {} + + void insert(string word) { + + Node* cur = root; + stack stack; + stack.push(root); + for(char c: word){ + if(cur->next[c - 'a'] == nullptr) + cur->next[c - 'a'] = new Node(); + cur = cur->next[c - 'a']; + stack.push(cur); + } + + cur->word_cnt ++; + + while(!stack.empty()){ + Node* node = stack.top(); + stack.pop(); + node->sz ++; + } + } + + int countWordsEqualTo(string word) { + + Node* cur = root; + for(char c: word){ + if(cur->next[c - 'a'] == nullptr) + return 0; + cur = cur->next[c - 'a']; + } + return cur->word_cnt; + } + + int countWordsStartingWith(string prefix) { + + Node* cur = root; + for(char c: prefix){ + if(cur->next[c - 'a'] == nullptr) + return 0; + cur = cur->next[c - 'a']; + } + return cur->sz; + } + + void erase(string word) { + + Node* cur = root; + stack stack; + stack.push(root); + for(char c: word){ + assert(cur->next[c - 'a']); + cur = cur->next[c - 'a']; + stack.push(cur); + } + + assert(cur->word_cnt); + + cur->word_cnt --; + + while(!stack.empty()){ + Node* node = stack.top(); + stack.pop(); + node->sz --; + } + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1805-Number-of-Different-Integers-in-a-String/cpp-1805/CMakeLists.txt b/1501-2000/1805-Number-of-Different-Integers-in-a-String/cpp-1805/CMakeLists.txt new file mode 100644 index 00000000..d5d5e4ff --- /dev/null +++ b/1501-2000/1805-Number-of-Different-Integers-in-a-String/cpp-1805/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1501-2000/1805-Number-of-Different-Integers-in-a-String/cpp-1805/main.cpp b/1501-2000/1805-Number-of-Different-Integers-in-a-String/cpp-1805/main.cpp new file mode 100644 index 00000000..317e33dc --- /dev/null +++ b/1501-2000/1805-Number-of-Different-Integers-in-a-String/cpp-1805/main.cpp @@ -0,0 +1,51 @@ +/// Source : https://leetcode.com/problems/number-of-different-integers-in-a-string/ +/// Author : liuyubobobo +/// Time : 2021-03-27 + +#include +#include + +using namespace std; + + +/// Split and Using HashSet +/// Time Complexity: O(|s|) +/// Space Complexity: O(|s|) +class Solution { +public: + int numDifferentIntegers(string s) { + + unordered_set set; + for(int start = next_digit(s, 0), i = start + 1; i <= s.size(); i ++){ + if(i == s.size() || !isdigit(s[i])){ + + string x = s.substr(start, i - start); + while(x.size() && x[0] == '0') x = x.substr(1); + set.insert(x); + + start = next_digit(s, i); + i = start; + } + } + return set.size(); + } + +private: + int next_digit(const string& s, int start){ + for(int i = start; i < s.size(); i ++) + if(isdigit(s[i])) return i; + return s.size(); + } +}; + + +int main() { + + cout << Solution().numDifferentIntegers("0aoqn2dsforb4pcjcqk4xdkzmqqq7xlixpzpgo7iokycmzpy2z8ya0p5se962r0wseoag9") << endl; + // 8 + + cout << Solution().numDifferentIntegers("uu717761265362523668772526716127260222200144937319826j717761265362523668772526716127260222200144937319826k717761265362523668772526716127260222200144937319826b7177612653625236687725267161272602222001449373198262hgb9utohfvfrxprqva3y5cdfdudf7zuh64mobfr6mhy17") << endl; + // 9 + + return 0; +} diff --git a/1501-2000/1806-Minimum-Number-of-Operations-to-Reinitialize-a-Permutation/cpp-1806/CMakeLists.txt b/1501-2000/1806-Minimum-Number-of-Operations-to-Reinitialize-a-Permutation/cpp-1806/CMakeLists.txt new file mode 100644 index 00000000..81ad8b42 --- /dev/null +++ b/1501-2000/1806-Minimum-Number-of-Operations-to-Reinitialize-a-Permutation/cpp-1806/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1501-2000/1806-Minimum-Number-of-Operations-to-Reinitialize-a-Permutation/cpp-1806/main.cpp b/1501-2000/1806-Minimum-Number-of-Operations-to-Reinitialize-a-Permutation/cpp-1806/main.cpp new file mode 100644 index 00000000..8f1f754b --- /dev/null +++ b/1501-2000/1806-Minimum-Number-of-Operations-to-Reinitialize-a-Permutation/cpp-1806/main.cpp @@ -0,0 +1,66 @@ +/// Source : https://leetcode.com/problems/minimum-number-of-operations-to-reinitialize-a-permutation/ +/// Author : liuyubobobo +/// Time : 2021-03-27 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { +public: + int reinitializePermutation(int n) { + + vector a(n); + for(int i = 0; i < n; i ++) a[i] = i; + + int res = 0; + do{ + res ++; + a = change(a); + }while(!in_order(a)); + return res; + } + +private: + bool in_order(const vector& a){ + + for(int i = 0; i < a.size(); i ++) + if(a[i] != i) return false; + return true; + } + + vector change(const vector& a){ + + vector res(a.size()); + for(int i = 0; i < a.size(); i ++) + if(i % 2 == 0) res[i] = a[i / 2]; + else res[i] = a[a.size() / 2 + (i - 1) / 2]; + return res; + } +}; + + +int main() { + + cout << Solution().reinitializePermutation(2) << endl; + // 1 + + cout << Solution().reinitializePermutation(4) << endl; + // 2 + + cout << Solution().reinitializePermutation(6) << endl; + // 4 + + cout << Solution().reinitializePermutation(8) << endl; + // 3 + + cout << Solution().reinitializePermutation(1000) << endl; + // 36 + + return 0; +} diff --git a/1501-2000/1807-Evaluate-the-Bracket-Pairs-of-a-String/cpp-1807/CMakeLists.txt b/1501-2000/1807-Evaluate-the-Bracket-Pairs-of-a-String/cpp-1807/CMakeLists.txt new file mode 100644 index 00000000..ce73aee9 --- /dev/null +++ b/1501-2000/1807-Evaluate-the-Bracket-Pairs-of-a-String/cpp-1807/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1501-2000/1807-Evaluate-the-Bracket-Pairs-of-a-String/cpp-1807/main.cpp b/1501-2000/1807-Evaluate-the-Bracket-Pairs-of-a-String/cpp-1807/main.cpp new file mode 100644 index 00000000..e09f4e5d --- /dev/null +++ b/1501-2000/1807-Evaluate-the-Bracket-Pairs-of-a-String/cpp-1807/main.cpp @@ -0,0 +1,60 @@ +/// Source : https://leetcode.com/problems/evaluate-the-bracket-pairs-of-a-string/ +/// Author : liuyubobobo +/// Time : 2021-03-27 + +#include +#include +#include + +using namespace std; + + +/// Linear Scan + Using HashMap +/// Time Complexity: O(|s|) +/// Space Complexity: O(|knowledge|) +class Solution { +public: + string evaluate(string s, vector>& knowledge) { + + unordered_map map; + for(const vector& p: knowledge) + map[p[0]] = p[1]; + + string res = "", key = ""; + for(char c: s) + if(c == '(') key += c; + else if(c == ')'){ + key = key.substr(1); +// cout << key << endl; + res += (map.count(key) ? map[key] : "?"); + key = ""; + } + else{ + if(key.empty()) res += c; + else key += c; + } + return res; + } +}; + + +int main() { + + vector> knowledge1 = {{"name","bob"},{"age","two"}}; + cout << Solution().evaluate("(name)is(age)yearsold", knowledge1) << endl; + // bobistwoyearsold + + vector> knowledge2 = {{"a","b"}}; + cout << Solution().evaluate("hi(name)", knowledge2) << endl; + // hi? + + vector> knowledge3 = {{"a","yes"}}; + cout << Solution().evaluate("(a)(a)(a)aaa", knowledge3) << endl; + // yesyesyesaaa + + vector> knowledge4 = {{"a","b"}, {"b", "a"}}; + cout << Solution().evaluate("(a)(b)", knowledge4) << endl; + // ba + + return 0; +} diff --git a/1501-2000/1808-Maximize-Number-of-Nice-Divisors/cpp-1808/CMakeLists.txt b/1501-2000/1808-Maximize-Number-of-Nice-Divisors/cpp-1808/CMakeLists.txt new file mode 100644 index 00000000..74cc3ee6 --- /dev/null +++ b/1501-2000/1808-Maximize-Number-of-Nice-Divisors/cpp-1808/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) \ No newline at end of file diff --git a/1501-2000/1808-Maximize-Number-of-Nice-Divisors/cpp-1808/main.cpp b/1501-2000/1808-Maximize-Number-of-Nice-Divisors/cpp-1808/main.cpp new file mode 100644 index 00000000..7abbbc8a --- /dev/null +++ b/1501-2000/1808-Maximize-Number-of-Nice-Divisors/cpp-1808/main.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/maximize-number-of-nice-divisors/ +/// Author : liuyubobobo +/// Time : 2021-03-27 + +#include + +using namespace std; + + +/// Mathematics +/// Time Complexity: O(log(primeFactors)) +/// Space Complexity: O(log(primeFactors)) +class Solution { + +private: + long long MOD = 1e9 + 7; + +public: + int maxNiceDivisors(int primeFactors) { + + if(primeFactors <= 3) return primeFactors; + + int n3 = primeFactors / 3; + if(primeFactors % 3 == 1) n3 --; + + long long res = mypow(3ll, n3); + if(primeFactors % 3 == 1) res = res * 4ll % MOD; + if(primeFactors % 3 == 2) res = res * 2ll % MOD; + return res; + } + +private: + long long mypow(long long a, int k){ + + if(k == 0) return 1ll; + + long long t = mypow(a, k / 2); + long long res = t * t % MOD; + if(k % 2) res = res * a % MOD; + return res; + } +}; + + +int main() { + + cout << Solution().maxNiceDivisors(5) << endl; + // 6 + + cout << Solution().maxNiceDivisors(8) << endl; + // 18 + + return 0; +} diff --git a/1501-2000/1810-Minimum-Path-Cost-in-a-Hidden-Grid/cpp-1810/CMakeLists.txt b/1501-2000/1810-Minimum-Path-Cost-in-a-Hidden-Grid/cpp-1810/CMakeLists.txt new file mode 100644 index 00000000..9b03b72a --- /dev/null +++ b/1501-2000/1810-Minimum-Path-Cost-in-a-Hidden-Grid/cpp-1810/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_1810) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1810 main.cpp) \ No newline at end of file diff --git a/1501-2000/1810-Minimum-Path-Cost-in-a-Hidden-Grid/cpp-1810/main.cpp b/1501-2000/1810-Minimum-Path-Cost-in-a-Hidden-Grid/cpp-1810/main.cpp new file mode 100644 index 00000000..ae5a6451 --- /dev/null +++ b/1501-2000/1810-Minimum-Path-Cost-in-a-Hidden-Grid/cpp-1810/main.cpp @@ -0,0 +1,102 @@ +/// Source : https://leetcode.com/problems/minimum-path-cost-in-a-hidden-grid/ +/// Author : liuyubobobo +/// Time : 2021-06-18 + +#include +#include +#include +#include + +using namespace std; + + +/// Dijkstra +/// Time Complexity: O((m * n)log(m * n)) +/// Space Complexity: O(m * n) + +// This is the GridMaster's API interface. +// You should not implement it, or speculate about its implementation +class GridMaster { + public: + bool canMove(char direction); + int move(char direction); + bool isTarget(); +}; + +class Solution { + +private: + unordered_map> dirs = { + {'U', {-1, 0}}, + {'R', {0, 1}}, + {'D', {1, 0}}, + {'L', {0, -1}} + }; + +public: + int findShortestPath(GridMaster &master) { + + vector> g(201, vector(201, -1)); + vector target(2, -1); + g[100][100] = 0; + fill(master, g, 100, 100, target); + // cout << "fill completed" << endl; + + unordered_set visited; + priority_queue, vector>, greater>> pq; + pq.push({0, 100 * 201 + 100}); + while(!pq.empty()){ + int w = pq.top().first, pos = pq.top().second; + pq.pop(); + + int y = pos % 201, x = (pos - y) / 201; + if(visited.count(pos)) continue; + visited.insert(pos); + + if(x == target[0] && y == target[1]) return w; + + for(const pair>& p: dirs){ + int dx = p.second.first, dy = p.second.second; + int nx = x + dx, ny = y + dy, npos = nx * 201 + ny; + if(g[nx][ny] != -1 && !visited.count(npos)){ + pq.push({w + g[nx][ny], npos}); + } + } + } + return -1; + } + + void fill(GridMaster& master, vector>& g, int x, int y, + vector& target){ + + // cout << x << " " << y << endl; + if(master.isTarget()) + target[0] = x, target[1] = y; + + for(const pair>& p: dirs){ + char d = p.first; + int dx = p.second.first, dy = p.second.second; + + int nx = x + dx, ny = y + dy; + if(master.canMove(d) && g[nx][ny] == -1){ + g[nx][ny] = master.move(d); + // cout << "go to " << d << " " << nx << " " << ny << endl; + fill(master, g, nx, ny, target); + switch(d){ + case 'U': master.move('D'); break; + case 'D': master.move('U'); break; + case 'L': master.move('R'); break; + case 'R': master.move('L'); break; + default : assert(false); + } + } + } + // cout << "back to " << x << " " << y << endl; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1812-Determine-Color-of-a-Chessboard-Square/cpp-1812/CMakeLists.txt b/1501-2000/1812-Determine-Color-of-a-Chessboard-Square/cpp-1812/CMakeLists.txt new file mode 100644 index 00000000..a10367bb --- /dev/null +++ b/1501-2000/1812-Determine-Color-of-a-Chessboard-Square/cpp-1812/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1812) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1812 main.cpp) \ No newline at end of file diff --git a/1501-2000/1812-Determine-Color-of-a-Chessboard-Square/cpp-1812/main.cpp b/1501-2000/1812-Determine-Color-of-a-Chessboard-Square/cpp-1812/main.cpp new file mode 100644 index 00000000..1fd1df74 --- /dev/null +++ b/1501-2000/1812-Determine-Color-of-a-Chessboard-Square/cpp-1812/main.cpp @@ -0,0 +1,26 @@ +/// Source : https://leetcode.com/problems/determine-color-of-a-chessboard-square/ +/// Author : liuyubobobo +/// Time : 2021-04-04 + +#include + +using namespace std; + + +/// Mathematics +/// Time Complexity: O(1) +/// Space Complexity: O(1) +class Solution { +public: + bool squareIsWhite(string coordinates) { + + int a = coordinates[0] - 'a', b = coordinates[1] - '1'; + return (a + b) % 2; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1813-Sentence-Similarity-III/cpp-1813/CMakeLists.txt b/1501-2000/1813-Sentence-Similarity-III/cpp-1813/CMakeLists.txt new file mode 100644 index 00000000..a62ce3c5 --- /dev/null +++ b/1501-2000/1813-Sentence-Similarity-III/cpp-1813/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1813) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1813 main.cpp) \ No newline at end of file diff --git a/1501-2000/1813-Sentence-Similarity-III/cpp-1813/main.cpp b/1501-2000/1813-Sentence-Similarity-III/cpp-1813/main.cpp new file mode 100644 index 00000000..e454c4c6 --- /dev/null +++ b/1501-2000/1813-Sentence-Similarity-III/cpp-1813/main.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/sentence-similarity-iii/ +/// Author : liuyubobobo +/// Time : 2021-04-04 + +#include +#include + +using namespace std; + + +/// Two Pointers +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + bool areSentencesSimilar(string s1, string s2) { + + if(s1 == s2) return true; + + vector v1 = get_vector(s1), v2 = get_vector(s2); + + if(v1.size() < v2.size()) swap(v1, v2); + + int l1 = 0, r1 = v1.size() - 1, l2 = 0, r2 = v2.size() - 1; + while(l2 < v2.size() && l1 < v1.size() && v1[l1] == v2[l2]) l1 ++, l2 ++; + while(r2 >= 0 && r1 >= 0 && v1[r1] == v2[r2]) r1 --, r2 --; + return l2 > r2; + } + +private: + vector get_vector(const string& s){ + + vector v; + for(int start = 0, i = start + 1; i <= s.size(); i ++) + if(i == s.size() || s[i] == ' '){ + v.push_back(s.substr(start, i - start)); + start = i + 1; + i = start; + } + return v; + } +}; + + +int main() { + + cout << Solution().areSentencesSimilar("CwFfRo regR", "CwFfRo H regR") << endl; + // 1 + + cout << Solution().areSentencesSimilar("Eating right now", "Eating") << endl; + // 1 + + return 0; +} diff --git a/1501-2000/1814-Count-Nice-Pairs-in-an-Array/cpp-1814/CMakeLists.txt b/1501-2000/1814-Count-Nice-Pairs-in-an-Array/cpp-1814/CMakeLists.txt new file mode 100644 index 00000000..a6a74113 --- /dev/null +++ b/1501-2000/1814-Count-Nice-Pairs-in-an-Array/cpp-1814/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1814) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1814 main.cpp) \ No newline at end of file diff --git a/1501-2000/1814-Count-Nice-Pairs-in-an-Array/cpp-1814/main.cpp b/1501-2000/1814-Count-Nice-Pairs-in-an-Array/cpp-1814/main.cpp new file mode 100644 index 00000000..80c73b07 --- /dev/null +++ b/1501-2000/1814-Count-Nice-Pairs-in-an-Array/cpp-1814/main.cpp @@ -0,0 +1,49 @@ +/// Source : https://leetcode.com/problems/count-nice-pairs-in-an-array/ +/// Author : liuyubobobo +/// Time : 2021-04-04 + +#include +#include + +using namespace std; + + +/// Sorting and Mathematics +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + int countNicePairs(vector& nums) { + + for(int i = 0; i < nums.size(); i ++) + nums[i] -= get_rev(nums[i]); + + sort(nums.begin(), nums.end()); + long long res = 0ll; + for(int start = 0, i = start + 1; i <= nums.size(); i ++) + if(i == nums.size() || nums[i] != nums[start]){ + int n = i - start; + res += (long long)n * (n - 1) / 2ll; + start = i; + i = start; + } + return res % (long long)(1e9 + 7); + } + +private: + int get_rev(int x){ + + int res = 0; + while(x){ + res = res * 10 + x % 10; + x /= 10; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1815-Maximum-Number-of-Groups-Getting-Fresh-Donuts/cpp-1815/CMakeLists.txt b/1501-2000/1815-Maximum-Number-of-Groups-Getting-Fresh-Donuts/cpp-1815/CMakeLists.txt new file mode 100644 index 00000000..136be21f --- /dev/null +++ b/1501-2000/1815-Maximum-Number-of-Groups-Getting-Fresh-Donuts/cpp-1815/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_1815) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1815 main.cpp) \ No newline at end of file diff --git a/1501-2000/1815-Maximum-Number-of-Groups-Getting-Fresh-Donuts/cpp-1815/main.cpp b/1501-2000/1815-Maximum-Number-of-Groups-Getting-Fresh-Donuts/cpp-1815/main.cpp new file mode 100644 index 00000000..09c71f3c --- /dev/null +++ b/1501-2000/1815-Maximum-Number-of-Groups-Getting-Fresh-Donuts/cpp-1815/main.cpp @@ -0,0 +1,71 @@ +/// Source : https://leetcode.com/problems/maximum-number-of-groups-getting-fresh-donuts/ +/// Author : liuyubobobo +/// Time : 2020-06-11 +/// Updaetd: 2023-01-21 + +#include +#include +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(2^n) +/// Space Complexity: O(2^n) +class Solution { +public: + int maxHappyGroups(int batchSize, vector& groups) { + + vector f(batchSize); + for(int e: groups) f[e % batchSize] ++; + + int res = f[0]; + f[0] = 0; + + map dp; + res += dfs(f, batchSize, dp); + return res; + } + +private: + int dfs(vector& f, int k, map& dp){ + + long long h = 0; + for(int e: f) h = h * 10ll + e; + + auto iter = dp.find(h); + if(iter != dp.end()) return iter->second; + + int pre = f[0]; + int res = 0; + for(int i = 1; i < f.size(); i ++) + if(f[i]){ + f[i] --; + f[0] = (pre + i) % k; + res = max(res, (pre == 0) + dfs(f, k, dp)); + f[0] = pre; + f[i] ++; + } + return dp[h] = res; + } +}; + + +int main() { + + vector groups1 = {1, 2, 3, 4, 5, 6}; + cout << Solution().maxHappyGroups(3, groups1) << endl; + // 4 + + vector groups2 = {1, 3, 2, 5, 2, 2, 1, 6}; + cout << Solution().maxHappyGroups(4, groups2) << endl; + // 4 + + vector groups3 = {909925048,861425549,820096754,67760437,273878288,126614243,531969375,817077202,482637353,507069465,699642631,407608742,846885254,225437260,100780964,523832097,30437867,959191866,897395949}; + cout << Solution().maxHappyGroups(1, groups3) << endl; + // 19 + + return 0; +} \ No newline at end of file diff --git a/1501-2000/1816-Truncate-Sentence/cpp-1816/CMakeLists.txt b/1501-2000/1816-Truncate-Sentence/cpp-1816/CMakeLists.txt new file mode 100644 index 00000000..d5d5e4ff --- /dev/null +++ b/1501-2000/1816-Truncate-Sentence/cpp-1816/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1501-2000/1816-Truncate-Sentence/cpp-1816/main.cpp b/1501-2000/1816-Truncate-Sentence/cpp-1816/main.cpp new file mode 100644 index 00000000..3b23f818 --- /dev/null +++ b/1501-2000/1816-Truncate-Sentence/cpp-1816/main.cpp @@ -0,0 +1,36 @@ +/// Source : https://leetcode.com/problems/truncate-sentence/ +/// Author : liuyubobobo +/// Time : 2021-04-03 + +#include +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + string truncateSentence(string s, int k) { + + string res = ""; + for(int start = 0, i = start + 1; i <= s.size() && k; i ++) + if(i == s.size() || s[i] == ' '){ + res += s.substr(start, i - start) + " "; + start = i + 1; + i = start; + k --; + } + + res.pop_back(); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1817-Finding-the-Users-Active-Minutes/cpp-1817/CMakeLists.txt b/1501-2000/1817-Finding-the-Users-Active-Minutes/cpp-1817/CMakeLists.txt new file mode 100644 index 00000000..81ad8b42 --- /dev/null +++ b/1501-2000/1817-Finding-the-Users-Active-Minutes/cpp-1817/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1501-2000/1817-Finding-the-Users-Active-Minutes/cpp-1817/main.cpp b/1501-2000/1817-Finding-the-Users-Active-Minutes/cpp-1817/main.cpp new file mode 100644 index 00000000..c907c777 --- /dev/null +++ b/1501-2000/1817-Finding-the-Users-Active-Minutes/cpp-1817/main.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/finding-the-users-active-minutes/ +/// Author : liuyubobobo +/// Time : 2021-04-03 + +#include +#include +#include +#include + +using namespace std; + + +/// Using HashMap +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector findingUsersActiveMinutes(vector>& logs, int k) { + + unordered_map> f; + for(const vector& v: logs) + f[v[0]].insert(v[1]); + + vector res(k, 0); + for(const pair>& p: f){ + if(p.second.size() - 1 < res.size()) + res[p.second.size() - 1] ++; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1818-Minimum-Absolute-Sum-Difference/cpp-1818/CMakeLists.txt b/1501-2000/1818-Minimum-Absolute-Sum-Difference/cpp-1818/CMakeLists.txt new file mode 100644 index 00000000..ce73aee9 --- /dev/null +++ b/1501-2000/1818-Minimum-Absolute-Sum-Difference/cpp-1818/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1501-2000/1818-Minimum-Absolute-Sum-Difference/cpp-1818/main.cpp b/1501-2000/1818-Minimum-Absolute-Sum-Difference/cpp-1818/main.cpp new file mode 100644 index 00000000..9e5b9a31 --- /dev/null +++ b/1501-2000/1818-Minimum-Absolute-Sum-Difference/cpp-1818/main.cpp @@ -0,0 +1,58 @@ +/// Source : https://leetcode.com/problems/minimum-absolute-sum-difference/ +/// Author : liuyubobobo +/// Time : 2021-04-03 + +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + int minAbsoluteSumDiff(vector& nums1, vector& nums2) { + + long long sum = 0ll; + for(int i = 0; i < nums1.size(); i ++) + sum += (long long)abs(nums1[i] - nums2[i]); + + vector v = nums1; + sort(v.begin(), v.end()); + + long long res = sum; + for(int i = 0; i < nums1.size(); i ++){ + + vector::iterator iter = lower_bound(v.begin(), v.end(), nums2[i]); + if(iter != v.end()) + res = min(res, sum - (long long)abs(nums1[i] - nums2[i]) + (long long)abs(*iter - nums2[i])); + + if(iter != v.begin()){ + iter --; + res = min(res, sum - (long long)abs(nums1[i] - nums2[i]) + (long long)abs(*iter - nums2[i])); + } + } + + return res % (long long)(1e9 + 7); + } +}; + + +int main() { + + vector nums11 = {1, 7, 5}, nums12 = {2, 3, 5}; + cout << Solution().minAbsoluteSumDiff(nums11, nums12) << endl; + // 3 + + vector nums21 = {2, 4, 6, 8, 10}, nums22 = {2, 4, 6, 8, 10}; + cout << Solution().minAbsoluteSumDiff(nums21, nums22) << endl; + // 0 + + vector nums31 = {1,10,4,4,2,7}, nums32 = {9,3,5,1,7,4}; + cout << Solution().minAbsoluteSumDiff(nums31, nums32) << endl; + // 20 + + return 0; +} diff --git a/1501-2000/1819-Number-of-Different-Subsequences-GCDs/cpp-1819/CMakeLists.txt b/1501-2000/1819-Number-of-Different-Subsequences-GCDs/cpp-1819/CMakeLists.txt new file mode 100644 index 00000000..74cc3ee6 --- /dev/null +++ b/1501-2000/1819-Number-of-Different-Subsequences-GCDs/cpp-1819/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) \ No newline at end of file diff --git a/1501-2000/1819-Number-of-Different-Subsequences-GCDs/cpp-1819/main.cpp b/1501-2000/1819-Number-of-Different-Subsequences-GCDs/cpp-1819/main.cpp new file mode 100644 index 00000000..e9f2eee8 --- /dev/null +++ b/1501-2000/1819-Number-of-Different-Subsequences-GCDs/cpp-1819/main.cpp @@ -0,0 +1,72 @@ +/// Source : https://leetcode.com/problems/number-of-different-subsequences-gcds/ +/// Author : liuyubobobo +/// Time : 2021-04-04 + +#include +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(n * sqrt(max_num)) +/// Space Complexity: O(max_num) +class Solution { +public: + int countDifferentSubsequenceGCDs(vector& nums) { + + int maxv = *max_element(nums.begin(), nums.end()); + + vector dp(maxv + 1, -1); + for(int num: nums){ + + for(int d = 1; d * d <= num; d ++) + if(num % d == 0){ + process(dp, d, num); + if(d * d != num) process(dp, num / d, num); + } + } + + int res = 0; + for(int i = 0; i < dp.size(); i ++) + res += (dp[i] == i); + return res; + } + +private: + void process(vector& dp, int d, int num){ + + if(dp[d] == -1){ + dp[d] = num; + return; + } + + dp[d] = gcd(dp[d], num); + } + + int gcd(int a, int b) { + if(a < b) swap(a, b); + if (b == 0) + return a; + return gcd(b, a % b); + } +}; + + +int main() { + + vector nums1 = {6, 10, 3}; + cout << Solution().countDifferentSubsequenceGCDs(nums1) << endl; + // 5 + + vector nums2 = {5, 15, 40, 5, 6}; + cout << Solution().countDifferentSubsequenceGCDs(nums2) << endl; + // 7 + + vector nums3 = {5852,6671,170275,141929,2414,99931,179958,56781,110656,190278,7613,138315,58116,114790,129975,144929,61102,90624,60521,177432,57353,199478,120483,75965,5634,109100,145872,168374,26215,48735,164982,189698,77697,31691,194812,87215,189133,186435,131282,110653,133096,175717,49768,79527,74491,154031,130905,132458,103116,154404,9051,125889,63633,194965,105982,108610,174259,45353,96240,143865,184298,176813,193519,98227,22667,115072,174001,133281,28294,42913,136561,103090,97131,128371,192091,7753,123030,11400,80880,184388,161169,155500,151566,103180,169649,44657,44196,131659,59491,3225,52303,141458,143744,60864,106026,134683,90132,151466,92609,120359,70590,172810,143654,159632,191208,1497,100582,194119,134349,33882,135969,147157,53867,111698,14713,126118,95614,149422,145333,52387,132310,108371,127121,93531,108639,90723,416,141159,141587,163445,160551,86806,120101,157249,7334,60190,166559,46455,144378,153213,47392,24013,144449,66924,8509,176453,18469,21820,4376,118751,3817,197695,198073,73715,65421,70423,28702,163789,48395,90289,76097,18224,43902,41845,66904,138250,44079,172139,71543,169923,186540,77200,119198,184190,84411,130153,124197,29935,6196,81791,101334,90006,110342,49294,67744,28512,66443,191406,133724,54812,158768,113156,5458,59081,4684,104154,38395,9261,188439,42003,116830,184709,132726,177780,111848,142791,57829,165354,182204,135424,118187,58510,137337,170003,8048,103521,176922,150955,84213,172969,165400,111752,15411,193319,78278,32948,55610,12437,80318,18541,20040,81360,78088,194994,41474,109098,148096,66155,34182,2224,146989,9940,154819,57041,149496,120810,44963,184556,163306,133399,9811,99083,52536,90946,25959,53940,150309,176726,113496,155035,50888,129067,27375,174577,102253,77614,132149,131020,4509,85288,160466,105468,73755,4743,41148,52653,85916,147677,35427,88892,112523,55845,69871,176805,25273,99414,143558,90139,180122,140072,127009,139598,61510,17124,190177,10591,22199,34870,44485,43661,141089,55829,70258,198998,87094,157342,132616,66924,96498,88828,89204,29862,76341,61654,158331,187462,128135,35481,152033,144487,27336,84077,10260,106588,19188,99676,38622,32773,89365,30066,161268,153986,99101,20094,149627,144252,58646,148365,21429,69921,95655,77478,147967,140063,29968,120002,72662,28241,11994,77526,3246,160872,175745,3814,24035,108406,30174,10492,49263,62819,153825,110367,42473,30293,118203,43879,178492,63287,41667,195037,26958,114060,99164,142325,77077,144235,66430,186545,125046,82434,26249,54425,170932,83209,10387,7147,2755,77477,190444,156388,83952,117925,102569,82125,104479,16506,16828,83192,157666,119501,29193,65553,56412,161955,142322,180405,122925,173496,93278,67918,48031,141978,54484,80563,52224,64588,94494,21331,73607,23440,197470,117415,23722,170921,150565,168681,88837,59619,102362,80422,10762,85785,48972,83031,151784,79380,64448,87644,26463,142666,160273,151778,156229,24129,64251,57713,5341,63901,105323,18961,70272,144496,18591,191148,19695,5640,166562,2600,76238,196800,94160,129306,122903,40418,26460,131447,86008,20214,133503,174391,45415,47073,39208,37104,83830,80118,28018,185946,134836,157783,76937,33109,54196,37141,142998,189433,8326,82856,163455,176213,144953,195608,180774,53854,46703,78362,113414,140901,41392,12730,187387,175055,64828,66215,16886,178803,117099,112767,143988,65594,141919,115186,141050,118833,2849}; + cout << Solution().countDifferentSubsequenceGCDs(nums3) << endl; + // 923 + + return 0; +} diff --git a/1501-2000/1820-Maximum-Number-of-Accepted-Invitations/cpp-1820/CMakeLists.txt b/1501-2000/1820-Maximum-Number-of-Accepted-Invitations/cpp-1820/CMakeLists.txt new file mode 100644 index 00000000..dd745482 --- /dev/null +++ b/1501-2000/1820-Maximum-Number-of-Accepted-Invitations/cpp-1820/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_1820) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1820 main.cpp) \ No newline at end of file diff --git a/1501-2000/1820-Maximum-Number-of-Accepted-Invitations/cpp-1820/main.cpp b/1501-2000/1820-Maximum-Number-of-Accepted-Invitations/cpp-1820/main.cpp new file mode 100644 index 00000000..313a4162 --- /dev/null +++ b/1501-2000/1820-Maximum-Number-of-Accepted-Invitations/cpp-1820/main.cpp @@ -0,0 +1,82 @@ +/// Source : https://leetcode.com/problems/maximum-number-of-accepted-invitations/ +/// Author : liuyubobobo +/// Time : 2021-06-11 + +#include +#include +#include + +using namespace std; + + +/// Hungarian Algorithm +/// Time Complexity: O(m^2 * n) +/// Space Complexity: O(m * n) +class MaxMatching{ + +private: + int m, n; // m - row size, n = column size + vector> g; + vector matching; + +public: + MaxMatching(int m, int n) : m(m), n(n), g(m), matching(n, -1){} + + void add_edge(int u, int v){ + assert(u >= 0 && u < m && v >= 0 && v < n); + g[u].insert(v); + } + + int solve(){ + + int res = 0; + for(int i = 0; i < m; i ++){ + vector visited(n, false); + if(dfs(i, visited)) res ++; + } + return res; + } + +private: + bool dfs(int u, vector& visited){ + + for(int v: g[u]) + if(!visited[v]){ + visited[v] = true; + if(matching[v] == -1 || dfs(matching[v], visited)){ + matching[v] = u; + return true; + } + } + return false; + } +}; + +class Solution { +public: + int maximumInvitations(vector>& grid) { + + int m = grid.size(), n = grid[0].size(); + MaxMatching maxMatching(m, n); + + for(int i = 0; i < m; i ++) + for(int j = 0; j < n; j ++) + if(grid[i][j]) maxMatching.add_edge(i, j); + + return maxMatching.solve(); + } +}; + + +int main() { + + vector> grid1 = { + {1, 1, 1}, + {1, 0, 1}, + {0, 0, 1} + }; + cout << Solution().maximumInvitations(grid1) << endl; + // 3 + + return 0; +} diff --git a/1501-2000/1822-Sign-of-the-Product-of-an-Array/cpp-1822/CMakeLists.txt b/1501-2000/1822-Sign-of-the-Product-of-an-Array/cpp-1822/CMakeLists.txt new file mode 100644 index 00000000..56912ed2 --- /dev/null +++ b/1501-2000/1822-Sign-of-the-Product-of-an-Array/cpp-1822/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1501-2000/1822-Sign-of-the-Product-of-an-Array/cpp-1822/main.cpp b/1501-2000/1822-Sign-of-the-Product-of-an-Array/cpp-1822/main.cpp new file mode 100644 index 00000000..0db991c9 --- /dev/null +++ b/1501-2000/1822-Sign-of-the-Product-of-an-Array/cpp-1822/main.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/sign-of-the-product-of-an-array/ +/// Author : liuyubobobo +/// Time : 2021-04-10 + +#include +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int arraySign(vector& nums) { + + int pos = 0, neg = 0, zero = 0; + for(int num: nums) + if(num > 0) pos ++; + else if(num < 0) neg ++; + else zero ++; + + if(zero) return 0; + return neg % 2 ? -1 : 1; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1823-Find-the-Winner-of-the-Circular-Game/cpp-1823/CMakeLists.txt b/1501-2000/1823-Find-the-Winner-of-the-Circular-Game/cpp-1823/CMakeLists.txt new file mode 100644 index 00000000..358dfef4 --- /dev/null +++ b/1501-2000/1823-Find-the-Winner-of-the-Circular-Game/cpp-1823/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1501-2000/1823-Find-the-Winner-of-the-Circular-Game/cpp-1823/main.cpp b/1501-2000/1823-Find-the-Winner-of-the-Circular-Game/cpp-1823/main.cpp new file mode 100644 index 00000000..dae65ee2 --- /dev/null +++ b/1501-2000/1823-Find-the-Winner-of-the-Circular-Game/cpp-1823/main.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/find-the-winner-of-the-circular-game/ +/// Author : liuyubobobo +/// Time : 2021-04-10 + +#include + +using namespace std; + + +/// Mathematics +/// Joseph Problem +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int findTheWinner(int n, int k) { + + int s = 0; + for (int i = 2; i <= n; i++) + s = (s + k) % i; + return s + 1; + } +}; + + +int main() { + + cout << Solution().findTheWinner(5, 2) << endl; + // 3 + + cout << Solution().findTheWinner(6, 5) << endl; + // 1 + + return 0; +} diff --git a/1501-2000/1824-Minimum-Sideway-Jumps/cpp-1824/CMakeLists.txt b/1501-2000/1824-Minimum-Sideway-Jumps/cpp-1824/CMakeLists.txt new file mode 100644 index 00000000..ad5a4184 --- /dev/null +++ b/1501-2000/1824-Minimum-Sideway-Jumps/cpp-1824/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1501-2000/1824-Minimum-Sideway-Jumps/cpp-1824/main.cpp b/1501-2000/1824-Minimum-Sideway-Jumps/cpp-1824/main.cpp new file mode 100644 index 00000000..eed69f20 --- /dev/null +++ b/1501-2000/1824-Minimum-Sideway-Jumps/cpp-1824/main.cpp @@ -0,0 +1,62 @@ +/// Source : https://leetcode.com/problems/minimum-sideway-jumps/ +/// Author : liuyubobobo +/// Time : 2021-04-10 + +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +private: + int n; + +public: + int minSideJumps(vector& obstacles) { + + n = obstacles.size(); + vector> dp(4, vector(n, -1)); + return dfs(2, 0, obstacles, dp); + } + +private: + int dfs(int index, int pos, const vector& obstacles, vector>& dp){ + + if(pos == n - 1) return 0; + if(dp[index][pos] != -1) return dp[index][pos]; + + int res = INT_MAX; + if(obstacles[pos + 1] != index) + res = min(res, dfs(index, pos + 1, obstacles, dp)); + + for(int next_index = 1; next_index <= 3; next_index ++) + if(next_index != index){ + if(obstacles[pos] != next_index && obstacles[pos + 1] != next_index) + res = min(res, 1 + dfs(next_index, pos + 1, obstacles, dp)); + } + return dp[index][pos] = res; + } +}; + + +int main() { + + vector obstacle1 = {0,1,2,3,0}; + cout << Solution().minSideJumps(obstacle1) << endl; + // 2 + + vector obstacle2 = {0,1,1,3,3,0}; + cout << Solution().minSideJumps(obstacle2) << endl; + // 0 + + vector obstacle3 = {0,2,1,0,3,0}; + cout << Solution().minSideJumps(obstacle3) << endl; + // 2 + + return 0; +} diff --git a/1501-2000/1825-Finding-MK-Average/cpp-1825/CMakeLists.txt b/1501-2000/1825-Finding-MK-Average/cpp-1825/CMakeLists.txt new file mode 100644 index 00000000..b826605a --- /dev/null +++ b/1501-2000/1825-Finding-MK-Average/cpp-1825/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_1825) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1825 main.cpp) \ No newline at end of file diff --git a/1501-2000/1825-Finding-MK-Average/cpp-1825/main.cpp b/1501-2000/1825-Finding-MK-Average/cpp-1825/main.cpp new file mode 100644 index 00000000..2ec518bb --- /dev/null +++ b/1501-2000/1825-Finding-MK-Average/cpp-1825/main.cpp @@ -0,0 +1,139 @@ +/// Source : https://leetcode.com/problems/finding-mk-average/ +/// Author : liuyubobobo +/// Time : 2021-06-10 + +#include +#include +#include + +using namespace std; + + +/// Tree MultiSet +/// make the minTree to be full first, make the middleTree to be full second +/// Time Complexity: O(mlogm) +/// Space Complexity: O(m) +class MKAverage { + +private: + int m, k; + deque q; + multiset minTree, maxTree, middleTree; + long long sum = 0ll; + +public: + MKAverage(int m, int k) : m(m), k(k) {} + + void addElement(int num) { + + if(q.size() == m){ + int front = q.front(); + q.pop_front(); + + remove(front); + } + + add(num); + q.push_back(num); + } + + void remove(int e){ + + multiset::iterator iter = maxTree.find(e); + if(iter != maxTree.end()){ + maxTree.erase(iter); + return; + } + + iter = middleTree.find(e); + if(iter != middleTree.end()){ + middleTree.erase(iter); + sum -= e; + + while(middleTree.size() < m - 2 * k && maxTree.size()){ + int e = *maxTree.begin(); + maxTree.erase(maxTree.begin()); + + middleTree.insert(e); + sum += e; + } + + return; + } + + assert(minTree.count(e)); + minTree.erase(minTree.find(e)); + + while(minTree.size() < k && middleTree.size()){ + int e = *middleTree.begin(); + middleTree.erase(middleTree.begin()); + sum -= e; + + minTree.insert(e); + } + + while(middleTree.size() < m - 2 * k && maxTree.size()){ + int e = *maxTree.begin(); + maxTree.erase(maxTree.begin()); + + middleTree.insert(e); + sum += e; + } + } + + void add(int e){ + + minTree.insert(e); + + while(minTree.size() > k){ + int e = *minTree.rbegin(); + minTree.erase((--minTree.end())); + + middleTree.insert(e); + sum += e; + } + + while(middleTree.size() > m - 2 * k){ + int e = *middleTree.rbegin(); + middleTree.erase((--middleTree.end())); + sum -= e; + + maxTree.insert(e); + } + } + + int calculateMKAverage() { + if(q.size() < m) return -1; + return sum / (m - 2 * k); + } +}; + + +int main() { + +// ["MKAverage","addElement","addElement","calculateMKAverage","addElement","calculateMKAverage","addElement","addElement","addElement","calculateMKAverage"] +// [[3,1],[3],[1],[],[10],[],[5],[5],[5],[]] + MKAverage o1(3, 1); + o1.addElement(3); + o1.addElement(1); + cout << o1.calculateMKAverage() << endl; // -1 + o1.addElement(10); + cout << o1.calculateMKAverage() << endl; // 3 + + cout << endl; + +// ["MKAverage","addElement","addElement","calculateMKAverage","addElement","addElement","calculateMKAverage","addElement","addElement","calculateMKAverage","addElement"] +// [[3,1],[17612],[74607],[],[8272],[33433],[],[15456],[64938],[],[99741]] + MKAverage o2(3, 1); + o2.addElement(17612); + o2.addElement(74607); + cout << o2.calculateMKAverage() << endl; // -1 + o2.addElement(8272); + o2.addElement(33433); + cout << o2.calculateMKAverage() << endl; // 33433 + o2.addElement(15456); + o2.addElement(64938); + cout << o2.calculateMKAverage() << endl; // 33433 + + return 0; +} diff --git a/1501-2000/1826-Faulty-Sensor/cpp-1826/CMakeLists.txt b/1501-2000/1826-Faulty-Sensor/cpp-1826/CMakeLists.txt new file mode 100644 index 00000000..94056950 --- /dev/null +++ b/1501-2000/1826-Faulty-Sensor/cpp-1826/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_1826) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1826 main.cpp) \ No newline at end of file diff --git a/1501-2000/1826-Faulty-Sensor/cpp-1826/main.cpp b/1501-2000/1826-Faulty-Sensor/cpp-1826/main.cpp new file mode 100644 index 00000000..4ea9b3fd --- /dev/null +++ b/1501-2000/1826-Faulty-Sensor/cpp-1826/main.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/faulty-sensor/ +/// Author : liuyubobobo +/// Time : 2021-04-18 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { +public: + int badSensor(vector& sensor1, vector& sensor2) { + + int res = -1; + for(int i = 0; i < sensor1.size(); i ++) + if(ok(sensor1, i, sensor2)){ + res = 2; + } + + for(int i = 0; i < sensor2.size(); i ++) + if(ok(sensor2, i, sensor1)){ + if(res == 2) return -1; + res = 1; + } + + return res; + } + +private: + bool ok(const vector& a, int index, const vector& b){ + + vector x = a; + x.erase(x.begin() + index); + + vector y = b; + y.pop_back(); + + return x == y; + } +}; + + +int main() { + + vector sensor11 = {2, 3, 4, 5}, sensor12 = {2, 1, 3, 4}; + cout << Solution().badSensor(sensor11, sensor12) << endl; + // 1 + + return 0; +} diff --git a/1501-2000/1827-Minimum-Operations-to-Make-the-Array-Increasing/cpp-1827/CMakeLists.txt b/1501-2000/1827-Minimum-Operations-to-Make-the-Array-Increasing/cpp-1827/CMakeLists.txt new file mode 100644 index 00000000..56912ed2 --- /dev/null +++ b/1501-2000/1827-Minimum-Operations-to-Make-the-Array-Increasing/cpp-1827/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1501-2000/1827-Minimum-Operations-to-Make-the-Array-Increasing/cpp-1827/main.cpp b/1501-2000/1827-Minimum-Operations-to-Make-the-Array-Increasing/cpp-1827/main.cpp new file mode 100644 index 00000000..76a6a726 --- /dev/null +++ b/1501-2000/1827-Minimum-Operations-to-Make-the-Array-Increasing/cpp-1827/main.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/minimum-operations-to-make-the-array-increasing/ +/// Author : liuyubobobo +/// Time : 2021-04-17 + +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int minOperations(vector& nums) { + + int res = 0; + for(int i = 1; i < nums.size(); i ++){ + if(nums[i] <= nums[i - 1]){ + res += 1 + nums[i - 1] - nums[i]; + nums[i] = nums[i - 1] + 1; + } + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1828-Queries-on-Number-of-Points-Inside-a-Circle/cpp-1828/CMakeLists.txt b/1501-2000/1828-Queries-on-Number-of-Points-Inside-a-Circle/cpp-1828/CMakeLists.txt new file mode 100644 index 00000000..358dfef4 --- /dev/null +++ b/1501-2000/1828-Queries-on-Number-of-Points-Inside-a-Circle/cpp-1828/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1501-2000/1828-Queries-on-Number-of-Points-Inside-a-Circle/cpp-1828/main.cpp b/1501-2000/1828-Queries-on-Number-of-Points-Inside-a-Circle/cpp-1828/main.cpp new file mode 100644 index 00000000..bfbb81b0 --- /dev/null +++ b/1501-2000/1828-Queries-on-Number-of-Points-Inside-a-Circle/cpp-1828/main.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/queries-on-number-of-points-inside-a-circle/ +/// Author : liuyubobobo +/// Time : 2021-04-17 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(|p| * |q|) +class Solution { +public: + vector countPoints(vector>& points, vector>& queries) { + + vector res; + for(const vector& q: queries) + res.push_back(query(points, q[0], q[1], q[2])); + return res; + } + +private: + int query(const vector>& points, int x, int y, int r){ + + int res = 0; + for(const vector& p: points) + res += (x - p[0]) * (x - p[0]) + (y - p[1]) * (y - p[1]) <= r * r; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1829-Maximum-XOR-for-Each-Query/cpp-1829/CMakeLists.txt b/1501-2000/1829-Maximum-XOR-for-Each-Query/cpp-1829/CMakeLists.txt new file mode 100644 index 00000000..ad5a4184 --- /dev/null +++ b/1501-2000/1829-Maximum-XOR-for-Each-Query/cpp-1829/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1501-2000/1829-Maximum-XOR-for-Each-Query/cpp-1829/main.cpp b/1501-2000/1829-Maximum-XOR-for-Each-Query/cpp-1829/main.cpp new file mode 100644 index 00000000..f797e587 --- /dev/null +++ b/1501-2000/1829-Maximum-XOR-for-Each-Query/cpp-1829/main.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/maximum-xor-for-each-query/ +/// Author : liuyubobobo +/// Time : 2021-04-17 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n * maxBit) +/// Space Complexity: O(1) +class Solution { +public: + vector getMaximumXor(vector& nums, int maximumBit) { + + vector pow2(30, 1); + for(int i = 1; i < 30; i ++) pow2[i] = pow2[i - 1] * 2; + + vector res; + int x = 0; + for(int num: nums){ + x ^= num; + res.push_back(solve(x, maximumBit, pow2)); + } + + reverse(res.begin(), res.end()); + return res; + } + +private: + int solve(int x, int maximumBit, const vector& pow2){ + + int res = 0; + for(int i = 0; i < maximumBit; i ++) + res += (!(x % 2)) * pow2[i], x /= 2; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1830-Minimum-Number-of-Operations-to-Make-String-Sorted/cpp-1830/CMakeLists.txt b/1501-2000/1830-Minimum-Number-of-Operations-to-Make-String-Sorted/cpp-1830/CMakeLists.txt new file mode 100644 index 00000000..873af693 --- /dev/null +++ b/1501-2000/1830-Minimum-Number-of-Operations-to-Make-String-Sorted/cpp-1830/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_1830) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1830 main.cpp) \ No newline at end of file diff --git a/1501-2000/1830-Minimum-Number-of-Operations-to-Make-String-Sorted/cpp-1830/main.cpp b/1501-2000/1830-Minimum-Number-of-Operations-to-Make-String-Sorted/cpp-1830/main.cpp new file mode 100644 index 00000000..e5370c90 --- /dev/null +++ b/1501-2000/1830-Minimum-Number-of-Operations-to-Make-String-Sorted/cpp-1830/main.cpp @@ -0,0 +1,98 @@ +/// Source : https://leetcode.com/problems/minimum-number-of-operations-to-make-string-sorted/ +/// Author : liuyubobobo +/// Time : 2021-05-05 + +#include +#include +#include + +using namespace std; + + +/// Combination +/// Time Complexity: O(|s|*log(MOD)) +/// Space Complexity: O(|s|) +class Solution { + +private: + long long MOD = 1e9 + 7; + +public: + int makeStringSorted(string s) { + + vector perm(s.size() + 1, 1); + for(int i = 1; i <= s.size(); i ++) + perm[i] = perm[i - 1] * (long long)i % MOD; + + vector perminv(s.size() + 1, 1); + for(int i = 1; i <= s.size(); i ++) + perminv[i] = mypow(perm[i], MOD - 2); + + vector f(26, 0); + for(char c: s) f[c - 'a'] ++; + return dfs(s, 0, f, perm, perminv); + } + +private: + long long dfs(const string& s, int index, vector& f, + const vector& perm, const vector& perminv){ + + if(index == s.size()) return 0; + + long long res = 0ll; + for(int i = 0; i < s[index] - 'a'; i ++) + if(f[i]){ + f[i] --; + res += permutation_num(f, perm, perminv); + res %= MOD; + f[i] ++; + } + + f[s[index] - 'a'] --; + res += dfs(s, index + 1, f, perm, perminv); + res %= MOD; + return res; + } + +private: + long long permutation_num(const vector& f, const vector& perm, + const vector& perminv){ + + int sum = accumulate(f.begin(), f.end(), 0); + long long res = perm[sum]; + for(int e: f){ +// assert(f[e] < perm.size()); + res = (long long)res * perminv[e] % MOD; + } + return res; + } + + long long mypow(long long n, int k){ + + if(k == 0) return 1ll; + if(k == 1) return n; + + long long half = mypow(n, k / 2); + long long res = half * half % MOD; + if(k % 2) res = res * n % MOD; + return res; + } +}; + + +int main() { + + cout << Solution().makeStringSorted("cba") << endl; + // 5 + + cout << Solution().makeStringSorted("aabaa") << endl; + // 2 + + cout << Solution().makeStringSorted("cdbea") << endl; + // 63 + + cout << Solution().makeStringSorted("leetcodeleetcodeleetcode") << endl; + // 982157772 + + return 0; +} diff --git a/1501-2000/1832-Check-if-the-Sentence-Is-Pangram/cpp-1832/CMakeLists.txt b/1501-2000/1832-Check-if-the-Sentence-Is-Pangram/cpp-1832/CMakeLists.txt new file mode 100644 index 00000000..56912ed2 --- /dev/null +++ b/1501-2000/1832-Check-if-the-Sentence-Is-Pangram/cpp-1832/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1501-2000/1832-Check-if-the-Sentence-Is-Pangram/cpp-1832/main.cpp b/1501-2000/1832-Check-if-the-Sentence-Is-Pangram/cpp-1832/main.cpp new file mode 100644 index 00000000..ddeac3d4 --- /dev/null +++ b/1501-2000/1832-Check-if-the-Sentence-Is-Pangram/cpp-1832/main.cpp @@ -0,0 +1,32 @@ +/// Source : https://leetcode.com/problems/check-if-the-sentence-is-pangram/ +/// Author : liuyubobobo +/// Time : 2021-04-17 + +#include +#include + +using namespace std; + + +/// Hash Map +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + bool checkIfPangram(string sentence) { + + vector f(26, 0); + for(char c: sentence) + f[c - 'a'] ++; + + for(int e: f) + if(!e) return false; + return true; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1833-Maximum-Ice-Cream-Bars/cpp-1833/CMakeLists.txt b/1501-2000/1833-Maximum-Ice-Cream-Bars/cpp-1833/CMakeLists.txt new file mode 100644 index 00000000..358dfef4 --- /dev/null +++ b/1501-2000/1833-Maximum-Ice-Cream-Bars/cpp-1833/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1501-2000/1833-Maximum-Ice-Cream-Bars/cpp-1833/main.cpp b/1501-2000/1833-Maximum-Ice-Cream-Bars/cpp-1833/main.cpp new file mode 100644 index 00000000..648f4907 --- /dev/null +++ b/1501-2000/1833-Maximum-Ice-Cream-Bars/cpp-1833/main.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/maximum-ice-cream-bars/ +/// Author : liuyubobobo +/// Time : 2021-04-17 + +#include +#include + +using namespace std; + + +/// Sorting and Greedy +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + int maxIceCream(vector& costs, int coins) { + + sort(costs.begin(), costs.end()); + + int res = 0; + for(int e: costs) + if(e <= coins){ + res ++; + coins -= e; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1834-Single-Threaded-CPU/cpp-1834/CMakeLists.txt b/1501-2000/1834-Single-Threaded-CPU/cpp-1834/CMakeLists.txt new file mode 100644 index 00000000..ad5a4184 --- /dev/null +++ b/1501-2000/1834-Single-Threaded-CPU/cpp-1834/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1501-2000/1834-Single-Threaded-CPU/cpp-1834/main.cpp b/1501-2000/1834-Single-Threaded-CPU/cpp-1834/main.cpp new file mode 100644 index 00000000..fb042e87 --- /dev/null +++ b/1501-2000/1834-Single-Threaded-CPU/cpp-1834/main.cpp @@ -0,0 +1,66 @@ +/// Source : https://leetcode.com/problems/single-threaded-cpu/ +/// Author : liuyubobobo +/// Time : 2021-04-17 + +#include +#include +#include + +using namespace std; + + +/// Sorting + Priority Queue +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + vector getOrder(vector>& tasks) { + + for(int i = 0; i < tasks.size(); i ++) + tasks[i].push_back(i); + + sort(tasks.begin(), tasks.end(), [](const vector& t1, const vector& t2){ + if(t1[0] != t2[0]) return t1[0] < t2[0]; + if(t1[2] != t2[2]) return t1[2] < t2[2]; + return t1[1] < t2[1]; + }); + + priority_queue, vector>, greater>> pq; + vector res; + long long curt = 0; + int index = 0; + while(res.size() != tasks.size()){ + if(pq.empty()){ + curt = (long long)tasks[index][0]; + } + else{ + int process_time = pq.top().first, id = pq.top().second; + pq.pop(); + res.push_back(id); + curt += (long long)process_time; + } + + while(index < tasks.size() && tasks[index][0] <= curt) + pq.push({tasks[index][1], tasks[index][2]}), index ++; + } + return res; + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << " "; cout << endl; +} + +int main() { + + vector> task1 = {{1, 2}, {2, 4}, {3, 2}, {4, 1}}; + print_vec(Solution().getOrder(task1)); + // 0 2 3 1 + + vector> task2 = {{7, 10}, {7, 12}, {7, 5}, {7, 4}, {7, 2}}; + print_vec(Solution().getOrder(task2)); + // 4 3 2 0 1 + + return 0; +} diff --git a/1501-2000/1835-Find-XOR-Sum-of-All-Pairs-Bitwise-AND/cpp-1835/CMakeLists.txt b/1501-2000/1835-Find-XOR-Sum-of-All-Pairs-Bitwise-AND/cpp-1835/CMakeLists.txt new file mode 100644 index 00000000..8e6ea4a2 --- /dev/null +++ b/1501-2000/1835-Find-XOR-Sum-of-All-Pairs-Bitwise-AND/cpp-1835/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) \ No newline at end of file diff --git a/1501-2000/1835-Find-XOR-Sum-of-All-Pairs-Bitwise-AND/cpp-1835/main.cpp b/1501-2000/1835-Find-XOR-Sum-of-All-Pairs-Bitwise-AND/cpp-1835/main.cpp new file mode 100644 index 00000000..a1d6c65a --- /dev/null +++ b/1501-2000/1835-Find-XOR-Sum-of-All-Pairs-Bitwise-AND/cpp-1835/main.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/find-xor-sum-of-all-pairs-bitwise-and/ +/// Author : liuyubobobo +/// Time : 2021-04-17 + +#include +#include + +using namespace std; + + +/// Bit to bit process +/// Time Complexity: O(|arr1| + |arr2|) +/// Space Complexity: O(1) +class Solution { +public: + int getXORSum(vector& arr1, vector& arr2) { + + vector f1(31, 0), f2(31, 0); + for(int e: arr1) process(e, f1); + for(int e: arr2) process(e, f2); + + int res = 0; + for(int i = 30; i >= 0; i --){ + long long one = (long long)f1[i] * f2[i]; + int x = one % 2ll; + res = res * 2 + x; + } + return res; + } + +private: + void process(int num, vector& f){ + for(int i = 0; i < 31; i ++) + f[i] += (num & 1), num >>= 1; + } +}; + + +int main() { + + vector arr11 = {1, 2, 3}, arr12 = {6, 5}; + cout << Solution().getXORSum(arr11, arr12) << endl; + // 0 + + vector arr21 = {12}, arr22 = {4}; + cout << Solution().getXORSum(arr21, arr22) << endl; + // 4 + + return 0; +} diff --git a/1501-2000/1836-Remove-Duplicates-From-an-Unsorted-Linked-List/cpp-1836/CMakeLists.txt b/1501-2000/1836-Remove-Duplicates-From-an-Unsorted-Linked-List/cpp-1836/CMakeLists.txt new file mode 100644 index 00000000..e354a483 --- /dev/null +++ b/1501-2000/1836-Remove-Duplicates-From-an-Unsorted-Linked-List/cpp-1836/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_1836) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1836 main.cpp) \ No newline at end of file diff --git a/1501-2000/1836-Remove-Duplicates-From-an-Unsorted-Linked-List/cpp-1836/main.cpp b/1501-2000/1836-Remove-Duplicates-From-an-Unsorted-Linked-List/cpp-1836/main.cpp new file mode 100644 index 00000000..e99e6115 --- /dev/null +++ b/1501-2000/1836-Remove-Duplicates-From-an-Unsorted-Linked-List/cpp-1836/main.cpp @@ -0,0 +1,49 @@ +/// Source : https://leetcode.com/problems/remove-duplicates-from-an-unsorted-linked-list/ +/// Author : liuyubobobo +/// Time : 2021-04-24 + +#include +#include + +using namespace std; + + +/// Using HashMap +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode() : val(0), next(nullptr) {} + ListNode(int x) : val(x), next(nullptr) {} + ListNode(int x, ListNode *next) : val(x), next(next) {} +}; + +class Solution { +public: + ListNode* deleteDuplicatesUnsorted(ListNode* head) { + + ListNode* dummyHead = new ListNode(-1, head); + + unordered_map f; + for(ListNode* cur = head; cur != nullptr; cur = cur->next) + f[cur->val] ++; + + ListNode* prev = dummyHead; + while(prev->next){ + if(f[prev->next->val] > 1) + prev->next = prev->next->next; + else + prev = prev->next; + } + return dummyHead->next; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1837-Sum-of-Digits-in-Base-K/cpp-1837/CMakeLists.txt b/1501-2000/1837-Sum-of-Digits-in-Base-K/cpp-1837/CMakeLists.txt new file mode 100644 index 00000000..56912ed2 --- /dev/null +++ b/1501-2000/1837-Sum-of-Digits-in-Base-K/cpp-1837/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1501-2000/1837-Sum-of-Digits-in-Base-K/cpp-1837/main.cpp b/1501-2000/1837-Sum-of-Digits-in-Base-K/cpp-1837/main.cpp new file mode 100644 index 00000000..4435a3cd --- /dev/null +++ b/1501-2000/1837-Sum-of-Digits-in-Base-K/cpp-1837/main.cpp @@ -0,0 +1,30 @@ +/// Source : https://leetcode.com/problems/sum-of-digits-in-base-k/ +/// Author : liuyubobobo +/// Time : 2021-04-24 + +#include + +using namespace std; + + +/// K-Based Number +/// Time Complexity: O(logn) +/// Space Complexity: O(1) +class Solution { +public: + int sumBase(int n, int k) { + + int res = 0; + while(n){ + res += n % k; + n /= k; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1838-Frequency-of-the-Most-Frequent-Element/cpp-1838/CMakeLists.txt b/1501-2000/1838-Frequency-of-the-Most-Frequent-Element/cpp-1838/CMakeLists.txt new file mode 100644 index 00000000..b875daa2 --- /dev/null +++ b/1501-2000/1838-Frequency-of-the-Most-Frequent-Element/cpp-1838/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main2.cpp) \ No newline at end of file diff --git a/1501-2000/1838-Frequency-of-the-Most-Frequent-Element/cpp-1838/main.cpp b/1501-2000/1838-Frequency-of-the-Most-Frequent-Element/cpp-1838/main.cpp new file mode 100644 index 00000000..29b7abf9 --- /dev/null +++ b/1501-2000/1838-Frequency-of-the-Most-Frequent-Element/cpp-1838/main.cpp @@ -0,0 +1,61 @@ +/// Source : https://leetcode.com/problems/frequency-of-the-most-frequent-element/ +/// Author : liuyubobobo +/// Time : 2021-04-24 + +#include +#include + +using namespace std; + + +/// Presum + Binary Search +/// Time Complexity: O(nlogn) +/// Space Complexity: O(nlogn) +class Solution { +public: + int maxFrequency(vector& nums, int k) { + + sort(nums.begin(), nums.end()); + vector presum(nums.size() + 1, 0ll); + for(int i = 0; i < nums.size(); i ++) + presum[i + 1] = presum[i] + nums[i]; + + int res = 0; + for(int i = 0; i < nums.size(); i ++) + res = max(res, solve(nums, i, k, presum)); + return res; + } + +private: + int solve(const vector& nums, int start, int k, const vector& presum){ + + int l = start, r = nums.size() - 1; + while(l < r){ + + int mid = (l + r + 1) / 2; + if((long long)nums[mid] * (mid - start + 1) - (presum[mid + 1] - presum[start]) <= (long long)k) + l = mid; + else + r = mid - 1; + } + return r - start + 1; + } +}; + + +int main() { + + vector nums1 = {1, 2, 4}; + cout << Solution().maxFrequency(nums1, 5) << endl; + // 3 + + vector nums2 = {1, 4, 8, 13}; + cout << Solution().maxFrequency(nums2, 5) << endl; + // 2 + + vector nums3 = {3, 9, 6}; + cout << Solution().maxFrequency(nums3, 2) << endl; + // 1 + + return 0; +} diff --git a/1501-2000/1838-Frequency-of-the-Most-Frequent-Element/cpp-1838/main2.cpp b/1501-2000/1838-Frequency-of-the-Most-Frequent-Element/cpp-1838/main2.cpp new file mode 100644 index 00000000..d2c82699 --- /dev/null +++ b/1501-2000/1838-Frequency-of-the-Most-Frequent-Element/cpp-1838/main2.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/frequency-of-the-most-frequent-element/ +/// Author : liuyubobobo +/// Time : 2021-04-24 + +#include +#include + +using namespace std; + + +/// Sliding Windows +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + int maxFrequency(vector& nums, int k) { + + sort(nums.begin(), nums.end()); + + int l = 0, r = -1, res = 0; + long long sum = 0ll; + while(l < nums.size()){ + if(r + 1 < nums.size() && (long long)nums[r + 1] * (r - l + 2) - (sum + nums[r + 1]) <= k){ + r ++; + res = max(res, r - l + 1); + sum += nums[r]; + } + else{ + sum -= nums[l]; + l ++; + } + } + return res; + } +}; + + +int main() { + + vector nums1 = {1, 2, 4}; + cout << Solution().maxFrequency(nums1, 5) << endl; + // 3 + + vector nums2 = {1, 4, 8, 13}; + cout << Solution().maxFrequency(nums2, 5) << endl; + // 2 + + vector nums3 = {3, 9, 6}; + cout << Solution().maxFrequency(nums3, 2) << endl; + // 1 + + return 0; +} diff --git a/1501-2000/1839-Longest-Substring-Of-All-Vowels-in-Order/cpp-1839/CMakeLists.txt b/1501-2000/1839-Longest-Substring-Of-All-Vowels-in-Order/cpp-1839/CMakeLists.txt new file mode 100644 index 00000000..ad5a4184 --- /dev/null +++ b/1501-2000/1839-Longest-Substring-Of-All-Vowels-in-Order/cpp-1839/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1501-2000/1839-Longest-Substring-Of-All-Vowels-in-Order/cpp-1839/main.cpp b/1501-2000/1839-Longest-Substring-Of-All-Vowels-in-Order/cpp-1839/main.cpp new file mode 100644 index 00000000..eed0844e --- /dev/null +++ b/1501-2000/1839-Longest-Substring-Of-All-Vowels-in-Order/cpp-1839/main.cpp @@ -0,0 +1,49 @@ +/// Source : https://leetcode.com/problems/longest-substring-of-all-vowels-in-order/ +/// Author : liuyubobobo +/// Time : 2021-04-24 + +#include +#include +#include + +using namespace std; + + +/// Split +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int longestBeautifulSubstring(string word) { + + int res = 0; + for(int start = 0, i = start + 1; i <= word.size(); i ++) + if(i == word.size() || word[i] < word[i - 1]){ + + vector set(26, false); + for(int j = start; j < i; j ++) set[word[j] - 'a'] = true; + if(accumulate(set.begin(), set.end(), 0) == 5) + res = max(res, i - start); + + start = i; + i = start; + } + + return res; + } +}; + + +int main() { + + cout << Solution().longestBeautifulSubstring("aeiaaioaaaaeiiiiouuuooaauuaeiu") << endl; + // 13 + + cout << Solution().longestBeautifulSubstring("aeeeiiiioooauuuaeiou") << endl; + // 5 + + cout << Solution().longestBeautifulSubstring("a") << endl; + // 0 + + return 0; +} diff --git a/1501-2000/1840-Maximum-Building-Height/cpp-1840/CMakeLists.txt b/1501-2000/1840-Maximum-Building-Height/cpp-1840/CMakeLists.txt new file mode 100644 index 00000000..8700daa5 --- /dev/null +++ b/1501-2000/1840-Maximum-Building-Height/cpp-1840/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main2.cpp) \ No newline at end of file diff --git a/1501-2000/1840-Maximum-Building-Height/cpp-1840/main.cpp b/1501-2000/1840-Maximum-Building-Height/cpp-1840/main.cpp new file mode 100644 index 00000000..1cac8593 --- /dev/null +++ b/1501-2000/1840-Maximum-Building-Height/cpp-1840/main.cpp @@ -0,0 +1,86 @@ +/// Source : https://leetcode.com/problems/maximum-building-height/ +/// Author : liuyubobobo +/// Time : 2021-04-24 + +#include +#include +#include + +using namespace std; + + +/// Two Pass +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + int maxBuilding(int n, vector>& restrictions) { + + restrictions.push_back({1, 0}); + sort(restrictions.begin(), restrictions.end()); + if(restrictions.back()[0] != n) + restrictions.push_back({n, (int)2e9}); + + vector> v = {{1, 0}}; + for(int i = 1; i < restrictions.size(); i ++){ + int p = restrictions[i][0], h = restrictions[i][1]; + if(h >= v.back().second) + v.push_back({p, h}); + else{ + pair pre = {-1, -1}; + while(v.back().second > h && v.back().second - h > p - v.back().first) + pre = v.back(), v.pop_back(); + + if(pre.first != -1) + v.push_back({pre.first, h + (p - pre.first)}); + v.push_back({p, h}); + } + } + + int res = 0, pre = 0; + for(int i = 1; i < v.size(); i ++){ + int p1 = v[i - 1].first, h1 = pre; + int p2 = v[i].first, h2 = v[i].second; + + if(h2 >= h1 && h2 - h1 >= p2 - p1){ + res = max(res, h1 + p2 - p1); + pre = h1 + (p2 - p1); + } + else if(h2 < h1 && h1 - h2 >= p2 - p1) + pre = h1 - (p2 - p1); + else{ + int x = ((long long)h2 - h1 + p1 + p2) / 2ll; + res = max(res, h1 + x - p1); + int maxh = h1 + x - p1; + pre = max(maxh - (p2 - x), h2); + } + } + return res; + } +}; + + +int main() { + + vector> r1 = {{2, 1}, {4, 1}}; + cout << Solution().maxBuilding(5, r1) << endl; + // 2 + + vector> r2 = {}; + cout << Solution().maxBuilding(6, r2) << endl; + // 5 + + vector> r3 = {{5, 3}, {2, 5}, {7, 4}, {10, 3}}; + cout << Solution().maxBuilding(10, r3) << endl; + // 5 + + vector> r4 = {{6, 2}, {5, 1}, {2, 4}, {3, 0}, {9, 5}, {7, 0}, {4, 2}, {10, 3}, {8, 0}}; + cout << Solution().maxBuilding(10, r4) << endl; + // 2 + + vector> r5 = {{2, 4}, {3, 3}}; + cout << Solution().maxBuilding(3, r5) << endl; + // 2 + + return 0; +} diff --git a/1501-2000/1840-Maximum-Building-Height/cpp-1840/main2.cpp b/1501-2000/1840-Maximum-Building-Height/cpp-1840/main2.cpp new file mode 100644 index 00000000..1d12d2ff --- /dev/null +++ b/1501-2000/1840-Maximum-Building-Height/cpp-1840/main2.cpp @@ -0,0 +1,66 @@ +/// Source : https://leetcode.com/problems/maximum-building-height/ +/// Author : liuyubobobo +/// Time : 2021-04-26 + +#include +#include +#include + +using namespace std; + + +/// Three Pass +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + int maxBuilding(int n, vector>& r) { + + r.push_back({1, 0}); + sort(r.begin(), r.end()); + if(r.back()[0] != n) + r.push_back({n, (int)2e9}); + + for(int i = 1; i < r.size(); i ++) + r[i][1] = min(r[i][1], r[i - 1][1] + r[i][0] - r[i - 1][0]); + + for(int i = (int)r.size() - 2; i >= 0; i --) + r[i][1] = min(r[i][1], r[i + 1][1] + r[i + 1][0] - r[i][0]); + + int res = 0; + for(int i = 1; i < r.size(); i ++){ + int p1 = r[i - 1][0], h1 = r[i - 1][1]; + int p2 = r[i][0], h2 = r[i][1]; + + int x = ((long long)h2 - h1 + p1 + p2) / 2ll; + res = max(res, h1 + x - p1); + } + return res; + } +}; + + +int main() { + + vector> r1 = {{2, 1}, {4, 1}}; + cout << Solution().maxBuilding(5, r1) << endl; + // 2 + + vector> r2 = {}; + cout << Solution().maxBuilding(6, r2) << endl; + // 5 + + vector> r3 = {{5, 3}, {2, 5}, {7, 4}, {10, 3}}; + cout << Solution().maxBuilding(10, r3) << endl; + // 5 + + vector> r4 = {{6, 2}, {5, 1}, {2, 4}, {3, 0}, {9, 5}, {7, 0}, {4, 2}, {10, 3}, {8, 0}}; + cout << Solution().maxBuilding(10, r4) << endl; + // 2 + + vector> r5 = {{2, 4}, {3, 3}}; + cout << Solution().maxBuilding(3, r5) << endl; + // 2 + + return 0; +} diff --git a/1501-2000/1842-Next-Palindrome-Using-Same-Digits/cpp-1842/CMakeLists.txt b/1501-2000/1842-Next-Palindrome-Using-Same-Digits/cpp-1842/CMakeLists.txt new file mode 100644 index 00000000..543f9d26 --- /dev/null +++ b/1501-2000/1842-Next-Palindrome-Using-Same-Digits/cpp-1842/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_1842) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1842 main.cpp) \ No newline at end of file diff --git a/1501-2000/1842-Next-Palindrome-Using-Same-Digits/cpp-1842/main.cpp b/1501-2000/1842-Next-Palindrome-Using-Same-Digits/cpp-1842/main.cpp new file mode 100644 index 00000000..018b78d5 --- /dev/null +++ b/1501-2000/1842-Next-Palindrome-Using-Same-Digits/cpp-1842/main.cpp @@ -0,0 +1,44 @@ +/// Source : https://leetcode.com/problems/next-palindrome-using-same-digits/ +/// Author : liuyubobobo +/// Time : 2021-05-03 + +#include +#include + +using namespace std; + + +/// next_permutation +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + string nextPalindrome(string num) { + + int sz = num.size(); + string half = num.substr(0, sz / 2); + + if(!next_permutation(half.begin(), half.end())) return ""; + + string post = half; + reverse(post.begin(), post.end()); + return half + (sz % 2 ? (string(1, num[sz / 2])) : "") + post; + } +}; + +int main() { + + cout << Solution().nextPalindrome("1221") << endl; + // 2112 + + cout << Solution().nextPalindrome("32123") << endl; + // "" + + cout << Solution().nextPalindrome("45544554") << endl; + // 54455445 + + cout << Solution().nextPalindrome("23143034132") << endl; + // 23314041332 + + return 0; +} diff --git a/1501-2000/1844-Replace-All-Digits-with-Characters/cpp-1844/CMakeLists.txt b/1501-2000/1844-Replace-All-Digits-with-Characters/cpp-1844/CMakeLists.txt new file mode 100644 index 00000000..97a2aa3e --- /dev/null +++ b/1501-2000/1844-Replace-All-Digits-with-Characters/cpp-1844/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_1844) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1844 main.cpp) \ No newline at end of file diff --git a/1501-2000/1844-Replace-All-Digits-with-Characters/cpp-1844/main.cpp b/1501-2000/1844-Replace-All-Digits-with-Characters/cpp-1844/main.cpp new file mode 100644 index 00000000..d56bebc3 --- /dev/null +++ b/1501-2000/1844-Replace-All-Digits-with-Characters/cpp-1844/main.cpp @@ -0,0 +1,27 @@ +/// Source : https://leetcode.com/problems/replace-all-digits-with-characters/ +/// Author : liuyubobobo +/// Time : 2021-05-01 + +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + string replaceDigits(string s) { + + for(int i = 1; i < s.size(); i += 2) + s[i] = s[i - 1] + (s[i] - '0'); + return s; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1845-Seat-Reservation-Manager/cpp-1845/CMakeLists.txt b/1501-2000/1845-Seat-Reservation-Manager/cpp-1845/CMakeLists.txt new file mode 100644 index 00000000..6c02cf31 --- /dev/null +++ b/1501-2000/1845-Seat-Reservation-Manager/cpp-1845/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_1845) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1845 main.cpp) \ No newline at end of file diff --git a/1501-2000/1845-Seat-Reservation-Manager/cpp-1845/main.cpp b/1501-2000/1845-Seat-Reservation-Manager/cpp-1845/main.cpp new file mode 100644 index 00000000..bb87a05a --- /dev/null +++ b/1501-2000/1845-Seat-Reservation-Manager/cpp-1845/main.cpp @@ -0,0 +1,43 @@ +/// Source : https://leetcode.com/problems/seat-reservation-manager/ +/// Author : liuyubobobo +/// Time : 2021-05-01 + +#include +#include + +using namespace std; + + +/// Using TreeSet +/// Time Complexity: init: O(nlogn) +/// reserve and unreserve: O(logn) +/// Space Complexity: O(n) +class SeatManager { + +private: + set seats; + +public: + SeatManager(int n) { + + for(int i = 1; i <= n; i ++) + seats.insert(i); + } + + int reserve() { + + int seat = *seats.begin(); + seats.erase(seat); + return seat; + } + + void unreserve(int seatNumber) { + seats.insert(seatNumber); + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1846-Maximum-Element-After-Decreasing-and-Rearranging/cpp-1846/CMakeLists.txt b/1501-2000/1846-Maximum-Element-After-Decreasing-and-Rearranging/cpp-1846/CMakeLists.txt new file mode 100644 index 00000000..4a32a4fa --- /dev/null +++ b/1501-2000/1846-Maximum-Element-After-Decreasing-and-Rearranging/cpp-1846/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_1846) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1846 main.cpp) \ No newline at end of file diff --git a/1501-2000/1846-Maximum-Element-After-Decreasing-and-Rearranging/cpp-1846/main.cpp b/1501-2000/1846-Maximum-Element-After-Decreasing-and-Rearranging/cpp-1846/main.cpp new file mode 100644 index 00000000..0a0c91c7 --- /dev/null +++ b/1501-2000/1846-Maximum-Element-After-Decreasing-and-Rearranging/cpp-1846/main.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/maximum-element-after-decreasing-and-rearranging/ +/// Author : liuyubobobo +/// Time : 2021-05-01 + +#include +#include + +using namespace std; + + +/// Sorting and Greedy +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + int maximumElementAfterDecrementingAndRearranging(vector& arr) { + + sort(arr.begin(), arr.end()); + arr[0] = 1; + for(int i = 1; i < arr.size(); i ++) + arr[i] = min(arr[i - 1] + 1, arr[i]); + return arr.back(); + } +}; + + +int main() { + + vector arr1 = {2, 2, 1, 2, 1}; + cout << Solution().maximumElementAfterDecrementingAndRearranging(arr1) << endl; + // 2 + + return 0; +} diff --git a/1501-2000/1847-Closest-Room/cpp-1847/CMakeLists.txt b/1501-2000/1847-Closest-Room/cpp-1847/CMakeLists.txt new file mode 100644 index 00000000..359412a2 --- /dev/null +++ b/1501-2000/1847-Closest-Room/cpp-1847/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_1847) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1847 main.cpp) \ No newline at end of file diff --git a/1501-2000/1847-Closest-Room/cpp-1847/main.cpp b/1501-2000/1847-Closest-Room/cpp-1847/main.cpp new file mode 100644 index 00000000..a274ec38 --- /dev/null +++ b/1501-2000/1847-Closest-Room/cpp-1847/main.cpp @@ -0,0 +1,71 @@ +/// Source : https://leetcode.com/problems/closest-room/ +/// Author : liuyubobobo +/// Time : 2021-05-01 + +#include +#include +#include + +using namespace std; + + +/// Offline Algorithm +/// Time Complexity: O(qlogq + nlogn + qlogn) +/// Space Complexity: O(n) +class Solution { +public: + vector closestRoom(vector>& rooms, vector>& queries) { + + for(int i = 0; i < queries.size(); i ++) + queries[i].push_back(i); + + sort(rooms.begin(), rooms.end(), + [](const vector& a, const vector& b){ + return a[1] > b[1]; + }); + + sort(queries.begin(), queries.end(), + [](const vector& q1, const vector& q2){ + return q1[1] > q2[1]; + }); + + vector res(queries.size(), -1); + set ids; + for(int ri = 0, qi = 0; qi < queries.size(); qi ++){ + while(ri < rooms.size() && rooms[ri][1] >= queries[qi][1]) + ids.insert(rooms[ri ++][0]); + + int pref = queries[qi][0]; + set::iterator iter = ids.lower_bound(pref); + + int minv = INT_MAX, curres = -1; + if(iter != ids.end()) + if(abs(*iter - pref) <= minv) + minv = abs(*iter - pref), curres = *iter; + + if(iter != ids.begin()){ + iter --; + if(abs(*iter - pref) <= minv) + curres = *iter; + } + + res[queries[qi][2]] = curres; + } + return res; + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << " "; cout << endl; +} + +int main() { + + vector> rooms2 = {{1, 4}, {2, 3}, {3, 5}, {4, 1}, {5, 2}}; + vector> queries2 = {{2, 3}, {2, 4}, {2, 5}}; + print_vec(Solution().closestRoom(rooms2, queries2)); + // 2 1 3 + + return 0; +} diff --git a/1501-2000/1848-Minimum-Distance-to-the-Target-Element/cpp-1848/CMakeLists.txt b/1501-2000/1848-Minimum-Distance-to-the-Target-Element/cpp-1848/CMakeLists.txt new file mode 100644 index 00000000..56912ed2 --- /dev/null +++ b/1501-2000/1848-Minimum-Distance-to-the-Target-Element/cpp-1848/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1501-2000/1848-Minimum-Distance-to-the-Target-Element/cpp-1848/main.cpp b/1501-2000/1848-Minimum-Distance-to-the-Target-Element/cpp-1848/main.cpp new file mode 100644 index 00000000..8941a4d4 --- /dev/null +++ b/1501-2000/1848-Minimum-Distance-to-the-Target-Element/cpp-1848/main.cpp @@ -0,0 +1,30 @@ +/// Source : https://leetcode.com/problems/minimum-distance-to-the-target-element/ +/// Author : liuyubobobo +/// Time : 2021-05-01 + +#include +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int getMinDistance(vector& nums, int target, int start) { + + int res = INT_MAX; + for(int i = 0; i < nums.size(); i ++) + if(nums[i] == target) + res = min(res, abs(i - start)); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1849-Splitting-a-String-Into-Descending-Consecutive-Values/cpp-1849/CMakeLists.txt b/1501-2000/1849-Splitting-a-String-Into-Descending-Consecutive-Values/cpp-1849/CMakeLists.txt new file mode 100644 index 00000000..b875daa2 --- /dev/null +++ b/1501-2000/1849-Splitting-a-String-Into-Descending-Consecutive-Values/cpp-1849/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main2.cpp) \ No newline at end of file diff --git a/1501-2000/1849-Splitting-a-String-Into-Descending-Consecutive-Values/cpp-1849/main.cpp b/1501-2000/1849-Splitting-a-String-Into-Descending-Consecutive-Values/cpp-1849/main.cpp new file mode 100644 index 00000000..c2f7c267 --- /dev/null +++ b/1501-2000/1849-Splitting-a-String-Into-Descending-Consecutive-Values/cpp-1849/main.cpp @@ -0,0 +1,80 @@ +/// Source : https://leetcode.com/problems/splitting-a-string-into-descending-consecutive-values/ +/// Author : liuyubobobo +/// Time : 2021-05-01 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(|s| * 2^|s|) +/// Space Complexity: O(|s|) +class Solution { +public: + bool splitString(string s) { + + int n = s.size(); + vector bits(n); + for(int state = 0; state < (1 << n); state ++){ + get_bits(state, bits); + + long long a = -1; + int cnt = 0, start = 0, i = 1; + for(; i <= bits.size(); i ++) + if(i == bits.size() || bits[i] != bits[start]){ + + long long num = get_long(s, start, i); + if(num < 0ll) break; + + if(cnt == 0) a = num; + else if(num != a - cnt) break; + + cnt ++; + start = i; + i = start; + } + if(i == bits.size() + 1 && cnt > 1) return true; + } + return false; + } + +private: + long long get_long(const string& s, int start, int end){ + + long long a = 0ll; + for(int i = start; i < end; i ++){ + if((LONG_LONG_MAX - (s[i] - '0')) / 10ll < a) return -1; + a = a * 10ll + (s[i] - '0'); + } + return a; + } + + void get_bits(int state, vector& res){ + + for(int i = 0; i < res.size(); i ++) + res[i] = state & 1, state >>= 1; + } +}; + + +int main() { + + cout << Solution().splitString("1234") << endl; + // 0 + + cout << Solution().splitString("050043") << endl; + // 1 + + cout << Solution().splitString("9080701") << endl; + // 0 + + cout << Solution().splitString("10009998") << endl; + // 1 + + cout << Solution().splitString("810809808807806805") << endl; + // 1 + + return 0; +} diff --git a/1501-2000/1849-Splitting-a-String-Into-Descending-Consecutive-Values/cpp-1849/main2.cpp b/1501-2000/1849-Splitting-a-String-Into-Descending-Consecutive-Values/cpp-1849/main2.cpp new file mode 100644 index 00000000..6904a2b3 --- /dev/null +++ b/1501-2000/1849-Splitting-a-String-Into-Descending-Consecutive-Values/cpp-1849/main2.cpp @@ -0,0 +1,77 @@ +/// Source : https://leetcode.com/problems/splitting-a-string-into-descending-consecutive-values/ +/// Author : liuyubobobo +/// Time : 2021-05-03 + +#include +#include + +using namespace std; + + +/// Enumerating First String +/// Time Complexity: O(|s|^2) +/// Space Complexity: O(|s|) +class Solution { +public: + bool splitString(string s) { + + for(int end = 0; end + 1 < s.size(); end ++){ + string first = s.substr(0, end + 1); + long long a = get_long(first); + if(a < 0) break; + + if(ok(s, end + 1, a - 1ll)) + return true; + } + return false; + } + +private: + long long get_long(const string& s){ + + long long a = 0ll; + for(int i = 0; i < s.size(); i ++){ + if((LONG_LONG_MAX - (s[i] - '0')) / 10ll < a) return -1; + a = a * 10ll + (s[i] - '0'); + } + return a; + } + + bool ok(const string& s, int start, long long t){ + + if(start >= s.size()) return true; + + long long cur = 0ll; + int i = start; + for(; i < s.size(); i ++){ + cur = cur * 10ll + (s[i] - '0'); + if(cur > t) return false; + if(cur == t && ok(s, i + 1, t - 1ll)) return true; + } + return false; + } +}; + + +int main() { + + cout << Solution().splitString("1234") << endl; + // 0 + + cout << Solution().splitString("050043") << endl; + // 1 + + cout << Solution().splitString("9080701") << endl; + // 0 + + cout << Solution().splitString("10009998") << endl; + // 1 + + cout << Solution().splitString("810809808807806805") << endl; + // 1 + + cout << Solution().splitString("200100") << endl; + // 1 + + return 0; +} diff --git a/1501-2000/1850-Minimum-Adjacent-Swaps-to-Reach-the-Kth-Smallest-Number/cpp-1850/CMakeLists.txt b/1501-2000/1850-Minimum-Adjacent-Swaps-to-Reach-the-Kth-Smallest-Number/cpp-1850/CMakeLists.txt new file mode 100644 index 00000000..ad5a4184 --- /dev/null +++ b/1501-2000/1850-Minimum-Adjacent-Swaps-to-Reach-the-Kth-Smallest-Number/cpp-1850/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1501-2000/1850-Minimum-Adjacent-Swaps-to-Reach-the-Kth-Smallest-Number/cpp-1850/main.cpp b/1501-2000/1850-Minimum-Adjacent-Swaps-to-Reach-the-Kth-Smallest-Number/cpp-1850/main.cpp new file mode 100644 index 00000000..b1c0b4d5 --- /dev/null +++ b/1501-2000/1850-Minimum-Adjacent-Swaps-to-Reach-the-Kth-Smallest-Number/cpp-1850/main.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/minimum-adjacent-swaps-to-reach-the-kth-smallest-number/ +/// Author : liuyubobobo +/// Time : 2021-05-01 + +#include +#include + +using namespace std; + + +/// next_permutation + Greedy +/// Time Complexity: O(k * |num| + |num|^2) +/// Space Complexity: O(|num|) +class Solution { +public: + int getMinSwaps(string num, int k) { + + string onum = num; + for(int i = 0; i < k; i ++) + next_permutation(num.begin(), num.end()); +// cout << num << endl; + return solve(onum, num); + } + +private: + int solve(string& s, const string& t){ + + int res = 0; + for(int i = 0; i < t.size(); i ++){ + + int j = i; + for(; j < s.size(); j ++) + if(s[j] == t[i]) break; + + for(; j > i; j --){ + swap(s[j], s[j - 1]); + res ++; + } + } + return res; + } +}; + + +int main() { + + cout << Solution().getMinSwaps("5489355142", 4) << endl; + // 2 + + cout << Solution().getMinSwaps("11112", 4) << endl; + // 4 + + cout << Solution().getMinSwaps("00123", 1) << endl; + // 1 + + return 0; +} diff --git a/1501-2000/1851-Minimum-Interval-to-Include-Each-Query/cpp-1851/CMakeLists.txt b/1501-2000/1851-Minimum-Interval-to-Include-Each-Query/cpp-1851/CMakeLists.txt new file mode 100644 index 00000000..c12729a4 --- /dev/null +++ b/1501-2000/1851-Minimum-Interval-to-Include-Each-Query/cpp-1851/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main3.cpp) \ No newline at end of file diff --git a/1501-2000/1851-Minimum-Interval-to-Include-Each-Query/cpp-1851/main.cpp b/1501-2000/1851-Minimum-Interval-to-Include-Each-Query/cpp-1851/main.cpp new file mode 100644 index 00000000..82cc1eac --- /dev/null +++ b/1501-2000/1851-Minimum-Interval-to-Include-Each-Query/cpp-1851/main.cpp @@ -0,0 +1,124 @@ +/// Source : https://leetcode.com/problems/minimum-interval-to-include-each-query/ +/// Author : liuyubobobo +/// Time : 2021-05-01 + +#include +#include + +using namespace std; + + +/// Segment Tree +/// Time Complexity: O(nlogn + maxnum*log(maxnum)) +/// Space Complexity: O(maxnum) +class SegmentTree{ + +private: + int n; + vector data, tree; + +public: + SegmentTree(const vector& data): n(data.size()), data(data), tree(4 * n, 0){ + buildSegTree(0, 0, n - 1); + } + + void query(int l, int r, int a, const vector>& indexes, vector& res){ + query(0, 0, n - 1, l, r, a, indexes, res); + } + +private: + void buildSegTree(int treeID, int l, int r){ + + if(l == r){ + tree[treeID] = data[l]; + return; + } + + int mid = (l + r) / 2; + buildSegTree(treeID * 2 + 1, l, mid); + buildSegTree(treeID * 2 + 2, mid + 1, r); + tree[treeID] = tree[treeID * 2 + 1] + tree[treeID * 2 + 2]; + return; + } + + void query(int treeID, int l, int r, int ql, int qr, int a, + const vector>& indexes, vector& res){ + + if(tree[treeID] == 0) return; + if(qr < l || r < ql) return; + + if(l == r){ + for(int index: indexes[l]) + if(res[index] == -1) res[index] = a; + tree[treeID] = 0; + return; + } + + int mid = (l + r) / 2; + if(qr <= mid) query(treeID * 2 + 1, l, mid, ql, qr, a, indexes, res); + else if(ql > mid) query(treeID * 2 + 2, mid + 1, r, ql, qr, a, indexes, res); + else{ + query(treeID * 2 + 1, l, mid, ql, mid, a, indexes, res); + query(treeID * 2 + 2, mid + 1, r, mid + 1, qr, a, indexes, res); + } + + tree[treeID] = tree[treeID * 2 + 1] + tree[treeID * 2 + 2]; + return; + } +}; + +class Solution { +public: + vector minInterval(vector>& intervals, vector& queries) { + + int maxv = *max_element(queries.begin(), queries.end()); + vector data(maxv + 1, 0); + vector> indexes(maxv + 1); + + for(int i = 0; i < queries.size(); i ++) + data[queries[i]] = 1, indexes[queries[i]].push_back(i); + + SegmentTree tree(data); + + sort(intervals.begin(), intervals.end(), + [](const vector& v1, const vector& v2){ + return v1[1] - v1[0] < v2[1] - v2[0]; + }); + + vector res(queries.size(), -1); + for(const vector& interval: intervals){ + tree.query(interval[0], interval[1], interval[1] - interval[0] + 1, indexes, res); + } + return res; + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << " "; cout << endl; +} + +int main() { + + vector> intervals1 = {{1, 4}, {2, 4}, {3, 6}, {4, 4}}; + vector queries1 = {2, 3, 4, 5}; + print_vec(Solution().minInterval(intervals1, queries1)); + // 3 3 1 4 + + vector> intervals2 = {{2, 3}, {2, 5}, {1, 8}, {20, 25}}; + vector queries2 = {2, 19, 5, 22}; + print_vec(Solution().minInterval(intervals2, queries2)); + // 2,-1,4,6 + + vector> intervals3 = {{9, 9}, {9, 10}}; + vector queries3 = {9}; + print_vec(Solution().minInterval(intervals3, queries3)); + // 1 + + vector> intervals4 = {{5, 10}, {7, 7}}; + vector queries4 = {6, 6}; + print_vec(Solution().minInterval(intervals4, queries4)); + // 6 6 + + return 0; +} diff --git a/1501-2000/1851-Minimum-Interval-to-Include-Each-Query/cpp-1851/main2.cpp b/1501-2000/1851-Minimum-Interval-to-Include-Each-Query/cpp-1851/main2.cpp new file mode 100644 index 00000000..b6bdb408 --- /dev/null +++ b/1501-2000/1851-Minimum-Interval-to-Include-Each-Query/cpp-1851/main2.cpp @@ -0,0 +1,74 @@ +/// Source : https://leetcode.com/problems/minimum-interval-to-include-each-query/ +/// Author : liuyubobobo +/// Time : 2021-05-03 + +#include +#include +#include + +using namespace std; + + +/// Offline Algorithm + Priority Queue +/// Time Complexity: O(nlogn + (n + q)logq) +/// Space Complexity: O(n + q) +class Solution { +public: + vector minInterval(vector>& intervals, vector& queries) { + + sort(intervals.begin(), intervals.end()); + + vector> qv; + for(int i = 0; i < queries.size(); i ++) + qv.push_back({queries[i], i}); + sort(qv.begin(), qv.end()); + + priority_queue, vector>, greater>> pq; + // len, end + + int ii = 0; + vector res(qv.size(), -1); + for(const pair& p: qv){ + int q = p.first, index = p.second; + while(ii < intervals.size() && intervals[ii][0] <= q){ + pq.push({intervals[ii][1] - intervals[ii][0] + 1, intervals[ii][1]}); + ii ++; + } + + while(!pq.empty() && pq.top().second < q) pq.pop(); + + if(!pq.empty()) res[index] = pq.top().first; + } + return res; + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << " "; cout << endl; +} + +int main() { + + vector> intervals1 = {{1, 4}, {2, 4}, {3, 6}, {4, 4}}; + vector queries1 = {2, 3, 4, 5}; + print_vec(Solution().minInterval(intervals1, queries1)); + // 3 3 1 4 + + vector> intervals2 = {{2, 3}, {2, 5}, {1, 8}, {20, 25}}; + vector queries2 = {2, 19, 5, 22}; + print_vec(Solution().minInterval(intervals2, queries2)); + // 2,-1,4,6 + + vector> intervals3 = {{9, 9}, {9, 10}}; + vector queries3 = {9}; + print_vec(Solution().minInterval(intervals3, queries3)); + // 1 + + vector> intervals4 = {{5, 10}, {7, 7}}; + vector queries4 = {6, 6}; + print_vec(Solution().minInterval(intervals4, queries4)); + // 6 6 + + return 0; +} diff --git a/1501-2000/1851-Minimum-Interval-to-Include-Each-Query/cpp-1851/main3.cpp b/1501-2000/1851-Minimum-Interval-to-Include-Each-Query/cpp-1851/main3.cpp new file mode 100644 index 00000000..f55ca6c9 --- /dev/null +++ b/1501-2000/1851-Minimum-Interval-to-Include-Each-Query/cpp-1851/main3.cpp @@ -0,0 +1,125 @@ +/// Source : https://leetcode.com/problems/minimum-interval-to-include-each-query/ +/// Author : liuyubobobo +/// Time : 2021-05-03 + +#include +#include +#include + +using namespace std; + + +/// UF to deal with Segment Problem +/// See here: https://leetcode.com/problems/minimum-interval-to-include-each-query/discuss/1186840/Python-union-find +/// Time Complexity: O(nlogn + qlogq + nlogq) +/// Space Complexity: O(q) +class UF{ + +private: + vector parent; + +public: + UF(int n) : parent(n){ + for(int i = 0 ; i < n ; i ++) + parent[i] = i; + } + + int find(int p){ + if(p != parent[p]) + parent[p] = find(parent[p]); + return parent[p]; + } + + bool isConnected(int p, int q){ + return find(p) == find(q); + } + + void unionElements(int p, int q){ + + int pRoot = find(p), qRoot = find(q); + + if(pRoot == qRoot) return; + + parent[pRoot] = qRoot; + } +}; + +class Solution { +public: + vector minInterval(vector>& intervals, vector& queries) { + + sort(intervals.begin(), intervals.end(), + [](const vector& a, const vector& b){ + + if(a[1] - a[0] + 1 != b[1] - b[0] + 1) + return a[1] - a[0] + 1 < b[1] - b[0] + 1; + return a[0] < b[0]; + }); + + vector> qv(queries.size()); + for(int i = 0; i < queries.size(); i ++) + qv[i] = {queries[i], i}; + sort(qv.begin(), qv.end()); + + UF uf(qv.size()); + vector res(queries.size(), -1); + for(const vector& interval: intervals){ + int l = interval[0], r = interval[1]; + + vector>::iterator iter1 = lower_bound(qv.begin(), qv.end(), make_pair(l, INT_MIN)); + if(iter1 == qv.end()) continue; + + vector>::iterator iter2 = upper_bound(qv.begin(), qv.end(), make_pair(r, INT_MAX)); + if(iter2 == qv.begin()) continue; + iter2 --; + + int ql = iter1 - qv.begin(), qr = iter2 - qv.begin(); + if(ql > qr) continue; + + while(true){ + int v = uf.find(ql); + if(qv[v].first > r) break; + + if(res[qv[v].second] == -1) + res[qv[v].second] = r - l + 1; + + if(v + 1 < qv.size()) + uf.unionElements(v, v + 1); + else + break; + } + } + + return res; + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << " "; cout << endl; +} + +int main() { + + vector> intervals1 = {{1, 4}, {2, 4}, {3, 6}, {4, 4}}; + vector queries1 = {2, 3, 4, 5}; + print_vec(Solution().minInterval(intervals1, queries1)); + // 3 3 1 4 + + vector> intervals2 = {{2, 3}, {2, 5}, {1, 8}, {20, 25}}; + vector queries2 = {2, 19, 5, 22}; + print_vec(Solution().minInterval(intervals2, queries2)); + // 2,-1,4,6 + + vector> intervals3 = {{9, 9}, {9, 10}}; + vector queries3 = {9}; + print_vec(Solution().minInterval(intervals3, queries3)); + // 1 + + vector> intervals4 = {{5, 10}, {7, 7}}; + vector queries4 = {6, 6}; + print_vec(Solution().minInterval(intervals4, queries4)); + // 6 6 + + return 0; +} diff --git a/1501-2000/1852-Distinct-Numbers-in-Each-Subarray/cpp-1852/CMakeLists.txt b/1501-2000/1852-Distinct-Numbers-in-Each-Subarray/cpp-1852/CMakeLists.txt new file mode 100644 index 00000000..484a95bc --- /dev/null +++ b/1501-2000/1852-Distinct-Numbers-in-Each-Subarray/cpp-1852/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_1852) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1852 main.cpp) \ No newline at end of file diff --git a/1501-2000/1852-Distinct-Numbers-in-Each-Subarray/cpp-1852/main.cpp b/1501-2000/1852-Distinct-Numbers-in-Each-Subarray/cpp-1852/main.cpp new file mode 100644 index 00000000..618d2d1a --- /dev/null +++ b/1501-2000/1852-Distinct-Numbers-in-Each-Subarray/cpp-1852/main.cpp @@ -0,0 +1,39 @@ +/// Source : https://leetcode.com/problems/distinct-numbers-in-each-subarray/ +/// Author : liuyubobobo +/// Time : 2021-05-06 + +#include +#include +#include + +using namespace std; + + +/// Sliding Window +/// Time Complexity: O(n) +/// Space Complexity: O(k) +class Solution { +public: + vector distinctNumbers(vector& nums, int k) { + + unordered_map f; + vector res; + + for(int i = 0; i < k - 1; i ++) + f[nums[i]] ++; + + for(int i = k - 1; i < nums.size(); i ++){ + f[nums[i]] ++; + res.push_back(f.size()); + f[nums[i - (k - 1)]] --; + if(f[nums[i - (k - 1)]] == 0) f.erase(nums[i - (k - 1)]); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1854-Maximum-Population-Year/cpp-1854/CMakeLists.txt b/1501-2000/1854-Maximum-Population-Year/cpp-1854/CMakeLists.txt new file mode 100644 index 00000000..ce028c8f --- /dev/null +++ b/1501-2000/1854-Maximum-Population-Year/cpp-1854/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main2.cpp) \ No newline at end of file diff --git a/1501-2000/1854-Maximum-Population-Year/cpp-1854/main.cpp b/1501-2000/1854-Maximum-Population-Year/cpp-1854/main.cpp new file mode 100644 index 00000000..0a0755ae --- /dev/null +++ b/1501-2000/1854-Maximum-Population-Year/cpp-1854/main.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/maximum-population-year/ +/// Author : liuyubobobo +/// Time : 2021-05-08 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n * |death - birth|) +/// Space Complexity: O(max(death)) +class Solution { +public: + int maximumPopulation(vector>& logs) { + + vector people(2051, 0); + for(const vector& log: logs) + for(int i = log[0]; i < log[1]; i ++) + people[i] ++; + + int maxpeople = -1, res = 0; + for(int i = 1950; i <= 2050; i ++) + if(people[i] > maxpeople) res = i, maxpeople = people[i]; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1854-Maximum-Population-Year/cpp-1854/main2.cpp b/1501-2000/1854-Maximum-Population-Year/cpp-1854/main2.cpp new file mode 100644 index 00000000..61a73038 --- /dev/null +++ b/1501-2000/1854-Maximum-Population-Year/cpp-1854/main2.cpp @@ -0,0 +1,38 @@ +/// Source : https://leetcode.com/problems/maximum-population-year/ +/// Author : liuyubobobo +/// Time : 2021-05-19 + +#include +#include + +using namespace std; + + +/// Sweepline +/// Time Complexity: O(n) +/// Space Complexity: O(max(death)) +class Solution { +public: + int maximumPopulation(vector>& logs) { + + vector people(2051, 0); + for(const vector& log: logs) + people[log[0]] ++, people[log[1]] --; + + int maxpeople = -1, res = 0, cur = 0; + for(int i = 1950; i <= 2050; i ++){ + cur += people[i]; + if(cur > maxpeople) res = i, maxpeople = cur; + } + return res; + } +}; + + +int main() { + + vector> logs1 = {{1950,1961},{1960,1971},{1970,1981}}; + cout << Solution().maximumPopulation(logs1) << endl; + + return 0; +} diff --git a/1501-2000/1855-Maximum-Distance-Between-a-Pair-of-Values/cpp-1855/CMakeLists.txt b/1501-2000/1855-Maximum-Distance-Between-a-Pair-of-Values/cpp-1855/CMakeLists.txt new file mode 100644 index 00000000..305c6939 --- /dev/null +++ b/1501-2000/1855-Maximum-Distance-Between-a-Pair-of-Values/cpp-1855/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main3.cpp) \ No newline at end of file diff --git a/1501-2000/1855-Maximum-Distance-Between-a-Pair-of-Values/cpp-1855/main.cpp b/1501-2000/1855-Maximum-Distance-Between-a-Pair-of-Values/cpp-1855/main.cpp new file mode 100644 index 00000000..777894a5 --- /dev/null +++ b/1501-2000/1855-Maximum-Distance-Between-a-Pair-of-Values/cpp-1855/main.cpp @@ -0,0 +1,69 @@ +/// Source : https://leetcode.com/problems/maximum-distance-between-a-pair-of-values/ +/// Author : liuyubobobo +/// Time : 2021-05-08 + +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + int maxDistance(vector& nums1, vector& nums2) { + + vector data = nums2; + reverse(data.begin(), data.end()); + + int res = 0; + for(int i = 0; i < nums1.size(); i ++){ + + int j = binary_search(data, 0, (int)nums2.size() - i - 1, nums1[i]); +// cout << j << endl; + if(j != -1) + res = max(res, j - i); + } + return res; + } + +private: + int binary_search(const vector& v, int L, int R, int t){ + + if(L > R) return -1; + + int l = L, r = R + 1; + while(l < r){ + int mid = (l + r) / 2; + if(v[mid] >= t) r = mid; + else l = mid + 1; + } + + if(l > R) return -1; + return (int)v.size() - 1 - l; + } +}; + + +int main() { + + vector nums11 = {55, 30, 5, 4, 2}, nums12 = {100, 20, 10, 10, 5}; + cout << Solution().maxDistance(nums11, nums12) << endl; + // 2 + + vector nums21 = {2, 2, 2}, nums22 = {10, 10, 1}; + cout << Solution().maxDistance(nums21, nums22) << endl; + // 1 + + vector nums31 = {30, 29, 19, 5}, nums32 = {25, 25, 25, 25, 25}; + cout << Solution().maxDistance(nums31, nums32) << endl; + // 2 + + vector nums41 = {5, 4}, nums42 = {3, 2}; + cout << Solution().maxDistance(nums41, nums42) << endl; + // 0 + + return 0; +} diff --git a/1501-2000/1855-Maximum-Distance-Between-a-Pair-of-Values/cpp-1855/main2.cpp b/1501-2000/1855-Maximum-Distance-Between-a-Pair-of-Values/cpp-1855/main2.cpp new file mode 100644 index 00000000..f2a383f6 --- /dev/null +++ b/1501-2000/1855-Maximum-Distance-Between-a-Pair-of-Values/cpp-1855/main2.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/maximum-distance-between-a-pair-of-values/ +/// Author : liuyubobobo +/// Time : 2021-05-19 + +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + int maxDistance(vector& nums1, vector& nums2) { + + int res = 0; + for(int i = 0; i < nums1.size(); i ++){ + + vector::reverse_iterator riter = lower_bound(nums2.rbegin(), nums2.rend(), nums1[i]); + if(riter != nums2.rend()){ + int j = riter - nums2.rbegin(); + j = nums2.size() - 1 - j; + res = max(res, max(0, j - i)); + } + } + return res; + } +}; + + +int main() { + + vector nums11 = {55, 30, 5, 4, 2}, nums12 = {100, 20, 10, 10, 5}; + cout << Solution().maxDistance(nums11, nums12) << endl; + // 2 + + vector nums21 = {2, 2, 2}, nums22 = {10, 10, 1}; + cout << Solution().maxDistance(nums21, nums22) << endl; + // 1 + + vector nums31 = {30, 29, 19, 5}, nums32 = {25, 25, 25, 25, 25}; + cout << Solution().maxDistance(nums31, nums32) << endl; + // 2 + + vector nums41 = {5, 4}, nums42 = {3, 2}; + cout << Solution().maxDistance(nums41, nums42) << endl; + // 0 + + return 0; +} diff --git a/1501-2000/1855-Maximum-Distance-Between-a-Pair-of-Values/cpp-1855/main3.cpp b/1501-2000/1855-Maximum-Distance-Between-a-Pair-of-Values/cpp-1855/main3.cpp new file mode 100644 index 00000000..b4c760c7 --- /dev/null +++ b/1501-2000/1855-Maximum-Distance-Between-a-Pair-of-Values/cpp-1855/main3.cpp @@ -0,0 +1,48 @@ +/// Source : https://leetcode.com/problems/maximum-distance-between-a-pair-of-values/ +/// Author : liuyubobobo +/// Time : 2021-05-19 + +#include +#include + +using namespace std; + + +/// Two Pointers +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int maxDistance(vector& nums1, vector& nums2) { + + int res = 0; + for(int i = 0, j = 0; i < nums1.size(); i ++){ + + while(j + 1 < nums2.size() && nums2[j + 1] >= nums1[i]) j ++; + res = max(res, max(0, j - i)); + } + return res; + } +}; + + +int main() { + + vector nums11 = {55, 30, 5, 4, 2}, nums12 = {100, 20, 10, 10, 5}; + cout << Solution().maxDistance(nums11, nums12) << endl; + // 2 + + vector nums21 = {2, 2, 2}, nums22 = {10, 10, 1}; + cout << Solution().maxDistance(nums21, nums22) << endl; + // 1 + + vector nums31 = {30, 29, 19, 5}, nums32 = {25, 25, 25, 25, 25}; + cout << Solution().maxDistance(nums31, nums32) << endl; + // 2 + + vector nums41 = {5, 4}, nums42 = {3, 2}; + cout << Solution().maxDistance(nums41, nums42) << endl; + // 0 + + return 0; +} diff --git a/1501-2000/1856-Maximum-Subarray-Min-Product/cpp-1856/CMakeLists.txt b/1501-2000/1856-Maximum-Subarray-Min-Product/cpp-1856/CMakeLists.txt new file mode 100644 index 00000000..ad5a4184 --- /dev/null +++ b/1501-2000/1856-Maximum-Subarray-Min-Product/cpp-1856/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1501-2000/1856-Maximum-Subarray-Min-Product/cpp-1856/main.cpp b/1501-2000/1856-Maximum-Subarray-Min-Product/cpp-1856/main.cpp new file mode 100644 index 00000000..649aa0ae --- /dev/null +++ b/1501-2000/1856-Maximum-Subarray-Min-Product/cpp-1856/main.cpp @@ -0,0 +1,75 @@ +/// Source : https://leetcode.com/problems/maximum-subarray-min-product/ +/// Author : liuyubobobo +/// Time : 2021-05-08 + +#include +#include +#include + +using namespace std; + + +/// Mono Stack +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +private: + long long MOD = 1e9 + 7; + +public: + int maxSumMinProduct(vector& nums) { + + vector right(nums.size(), nums.size()); + stack stack; + for(int i = 0; i < nums.size(); i ++){ + while(!stack.empty() && nums[i] < nums[stack.top()]) + right[stack.top()] = i, stack.pop(); + stack.push(i); + } + +// cout << "right : "; +// for(int e: right) cout << e << " "; cout << endl; + + vector left(nums.size(), -1); + while(!stack.empty()) stack.pop(); + for(int i = nums.size() - 1; i >= 0; i --){ + while(!stack.empty() && nums[i] < nums[stack.top()]) + left[stack.top()] = i, stack.pop(); + stack.push(i); + } + +// cout << "left : "; +// for(int e: left) cout << e << " "; cout << endl; + + vector presum(nums.size() + 1, 0ll); + for(int i = 0; i < nums.size(); i ++) + presum[i + 1] = presum[i] + nums[i]; + + long long res = -1ll; + for(int i = 0; i < nums.size(); i ++){ + int l = left[i] + 1, r = right[i] - 1; + res = max(res, (presum[r + 1] - presum[l]) * nums[i]); + } + + return res % MOD; + } +}; + + +int main() { + + vector nums1 = {1, 2, 3, 2}; + cout << Solution().maxSumMinProduct(nums1) << endl; + // 14 + + vector nums2 = {2, 3, 3, 1, 2}; + cout << Solution().maxSumMinProduct(nums2) << endl; + // 18 + + vector nums3 = {3, 1, 5, 6, 4, 2}; + cout << Solution().maxSumMinProduct(nums3) << endl; + // 60 + + return 0; +} diff --git a/1501-2000/1857-Largest-Color-Value-in-a-Directed-Graph/cpp-1857/CMakeLists.txt b/1501-2000/1857-Largest-Color-Value-in-a-Directed-Graph/cpp-1857/CMakeLists.txt new file mode 100644 index 00000000..8700daa5 --- /dev/null +++ b/1501-2000/1857-Largest-Color-Value-in-a-Directed-Graph/cpp-1857/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main2.cpp) \ No newline at end of file diff --git a/1501-2000/1857-Largest-Color-Value-in-a-Directed-Graph/cpp-1857/main.cpp b/1501-2000/1857-Largest-Color-Value-in-a-Directed-Graph/cpp-1857/main.cpp new file mode 100644 index 00000000..c70767dc --- /dev/null +++ b/1501-2000/1857-Largest-Color-Value-in-a-Directed-Graph/cpp-1857/main.cpp @@ -0,0 +1,81 @@ +/// Source : https://leetcode.com/problems/largest-color-value-in-a-directed-graph/ +/// Author : liuyubobobo +/// Time : 2021-05-08 + +#include +#include +#include +#include + +using namespace std; + + +/// DAG DP +/// Time Complexity: O(V + E) +/// Space Complexity: O(V + E) +class Solution { +public: + int largestPathValue(string colors, vector>& edges) { + + int n = colors.size(); + vector> g(n); + for(const vector& e: edges) + g[e[0]].insert(e[1]); + + vector degrees(n, 0); + for(int u = 0; u < n; u ++) + for(int v: g[u]) degrees[v] ++; + + int res = -1; + for(char color = 'a'; color <= 'z'; color ++){ + int tres = solve(n, g, degrees, color, colors); + if(tres == -1) return -1; + res = max(res, tres); + } + return res; + } + +private: + int solve(int n, const vector>& g, vector degrees, char color, const string& colors){ + + queue q; + vector dp(n, 0); + int cnt = n; + for(int u = 0; u < n; u ++) + if(degrees[u] == 0){ + q.push(u); + cnt --; + if(colors[u] == color) + dp[u] = 1; + } + + while(!q.empty()){ + int u = q.front(); + q.pop(); + + for(int v: g[u]){ + dp[v] = max(dp[v], dp[u] + (colors[v] == color)); + degrees[v] --; + if(degrees[v] == 0) + cnt --, q.push(v); + } + } + + if(cnt) return -1; + return *max_element(dp.begin(), dp.end()); + } +}; + + +int main() { + + vector> edges1 = {{0, 1}, {0, 2}, {2, 3}, {3, 4}}; + cout << Solution().largestPathValue("abaca", edges1) << endl; + // 3 + + vector> edges2 = {{0, 0}}; + cout << Solution().largestPathValue("a", edges2) << endl; + // -1 + + return 0; +} diff --git a/1501-2000/1857-Largest-Color-Value-in-a-Directed-Graph/cpp-1857/main2.cpp b/1501-2000/1857-Largest-Color-Value-in-a-Directed-Graph/cpp-1857/main2.cpp new file mode 100644 index 00000000..ca955632 --- /dev/null +++ b/1501-2000/1857-Largest-Color-Value-in-a-Directed-Graph/cpp-1857/main2.cpp @@ -0,0 +1,74 @@ +/// Source : https://leetcode.com/problems/largest-color-value-in-a-directed-graph/ +/// Author : liuyubobobo +/// Time : 2021-05-20 + +#include +#include +#include +#include + +using namespace std; + + +/// DAG DP +/// Another implementation +/// Time Complexity: O(V + E) +/// Space Complexity: O(V + E) +class Solution { +public: + int largestPathValue(string colors, vector>& edges) { + + int n = colors.size(); + vector> g(n); + for(const vector& e: edges) + g[e[0]].insert(e[1]); + + vector degrees(n, 0); + for(int u = 0; u < n; u ++) + for(int v: g[u]) degrees[v] ++; + + vector> dp(n, vector(26, 0)); + queue q; + int cnt = n; + for(int u = 0; u < n; u ++) + if(degrees[u] == 0){ + q.push(u); + cnt --; + dp[u][colors[u] - 'a'] = 1; + } + + while(!q.empty()){ + int u = q.front(); + q.pop(); + + for(int v: g[u]){ + for(int color = 0; color < 26; color ++) + dp[v][color] = max(dp[v][color], dp[u][color] + (colors[v] == 'a' + color)); + degrees[v] --; + if(degrees[v] == 0) + cnt --, q.push(v); + } + } + + if(cnt) return -1; + + int res = 0; + for(int i = 0; i < n; i ++) + res = max(res, *max_element(dp[i].begin(), dp[i].end())); + return res; + } +}; + + +int main() { + + vector> edges1 = {{0, 1}, {0, 2}, {2, 3}, {3, 4}}; + cout << Solution().largestPathValue("abaca", edges1) << endl; + // 3 + + vector> edges2 = {{0, 0}}; + cout << Solution().largestPathValue("a", edges2) << endl; + // -1 + + return 0; +} diff --git a/1501-2000/1858-Longest-Word-With-All-Prefixes/cpp-1858/CMakeLists.txt b/1501-2000/1858-Longest-Word-With-All-Prefixes/cpp-1858/CMakeLists.txt new file mode 100644 index 00000000..03a6e4c5 --- /dev/null +++ b/1501-2000/1858-Longest-Word-With-All-Prefixes/cpp-1858/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_1858) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1858 main.cpp) \ No newline at end of file diff --git a/1501-2000/1858-Longest-Word-With-All-Prefixes/cpp-1858/main.cpp b/1501-2000/1858-Longest-Word-With-All-Prefixes/cpp-1858/main.cpp new file mode 100644 index 00000000..f51ec661 --- /dev/null +++ b/1501-2000/1858-Longest-Word-With-All-Prefixes/cpp-1858/main.cpp @@ -0,0 +1,83 @@ +/// Source : https://leetcode.com/problems/longest-word-with-all-prefixes/ +/// Author : liuyubobobo +/// Time : 2021-05-16 + +#include +#include + +using namespace std; + + +/// Trie +/// Time Complexity: O(all_letters) +/// Space Complexity: O(all_letters) +class Trie{ + +private: + class Node{ + public: + vector next; + bool is_end; + Node() : next(26, nullptr), is_end(false){} + }; + + Node* root; + +public: + Trie(){ + root = new Node(); +// root->is_end = true; + } + + void add(const string& s){ + + Node* pre = root; + for(char c: s){ + if(!pre->next[c - 'a']) + pre->next[c - 'a'] = new Node(); + pre = pre->next[c - 'a']; + } + pre->is_end = true; + } + + string query(){ + + string res = ""; + dfs(root, "", res); + return res; + } + +private: + void dfs(const Node* node, const string& cur, string& res){ + + if(cur.size() > res.size()) res = cur; + else if(cur.size() == res.size()) res = min(res, cur); + + for(int i = 0; i < 26; i ++) + if(node->next[i] && node->next[i]->is_end) + dfs(node->next[i], cur + string(1, 'a' + i), res); + } +}; + +class Solution { + +public: + string longestWord(vector& words) { + + Trie trie; + for(const string& word: words) + trie.add(word); + + return trie.query(); + } +}; + + +int main() { + + vector words1 = {"k","ki","kir","kira", "kiran"}; + cout << Solution().longestWord(words1) << endl; + // kiran + + return 0; +} diff --git a/1501-2000/1859-Sorting-the-Sentence/cpp-1859/CMakeLists.txt b/1501-2000/1859-Sorting-the-Sentence/cpp-1859/CMakeLists.txt new file mode 100644 index 00000000..2fc50eea --- /dev/null +++ b/1501-2000/1859-Sorting-the-Sentence/cpp-1859/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_1859) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1859 main.cpp) \ No newline at end of file diff --git a/1501-2000/1859-Sorting-the-Sentence/cpp-1859/main.cpp b/1501-2000/1859-Sorting-the-Sentence/cpp-1859/main.cpp new file mode 100644 index 00000000..5c8da8fc --- /dev/null +++ b/1501-2000/1859-Sorting-the-Sentence/cpp-1859/main.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/sorting-the-sentence/ +/// Author : liuyubobobo +/// Time : 2021-05-15 + +#include +#include + +using namespace std; + + +/// Sorting +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + string sortSentence(string s) { + + vector v; + for(int start = 0, i = 1; i <= s.size(); i ++) + if(i == s.size() || s[i] == ' '){ + v.push_back(s.substr(start, i - start)); + + start = i + 1; + i = start; + } + + sort(v.begin(), v.end(), [](const string& a, const string& b){ + return a.back() < b.back(); + }); + + string res = ""; + for(const string& e: v){ + res += e; + res.pop_back(); + res += " "; + } + res.pop_back(); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1860-Incremental-Memory-Leak/cpp-1860/CMakeLists.txt b/1501-2000/1860-Incremental-Memory-Leak/cpp-1860/CMakeLists.txt new file mode 100644 index 00000000..50865b2c --- /dev/null +++ b/1501-2000/1860-Incremental-Memory-Leak/cpp-1860/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_1860) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1860 main.cpp) \ No newline at end of file diff --git a/1501-2000/1860-Incremental-Memory-Leak/cpp-1860/main.cpp b/1501-2000/1860-Incremental-Memory-Leak/cpp-1860/main.cpp new file mode 100644 index 00000000..2314fa38 --- /dev/null +++ b/1501-2000/1860-Incremental-Memory-Leak/cpp-1860/main.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/incremental-memory-leak/ +/// Author : liuyubobobo +/// Time : 2021-05-15 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(sqrt(memory1 + memory2)) +/// Space Complexity: O(1) +class Solution { +public: + vector memLeak(int memory1, int memory2) { + + for(int i = 1;;i ++){ + if(i > memory1 && i > memory2) + return {i, memory1, memory2}; + else if(memory1 >= memory2) + memory1 -= i; + else memory2 -= i; + } + return {}; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1861-Rotating-the-Box/cpp-1861/CMakeLists.txt b/1501-2000/1861-Rotating-the-Box/cpp-1861/CMakeLists.txt new file mode 100644 index 00000000..97c14162 --- /dev/null +++ b/1501-2000/1861-Rotating-the-Box/cpp-1861/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_1861) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1861 main.cpp) \ No newline at end of file diff --git a/1501-2000/1861-Rotating-the-Box/cpp-1861/main.cpp b/1501-2000/1861-Rotating-the-Box/cpp-1861/main.cpp new file mode 100644 index 00000000..162b0ec3 --- /dev/null +++ b/1501-2000/1861-Rotating-the-Box/cpp-1861/main.cpp @@ -0,0 +1,71 @@ +/// Source : https://leetcode.com/problems/rotating-the-box/ +/// Author : liuyubobobo +/// Time : 2021-05-15 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(R * C) +/// Space Complexity: O(R * C) +class Solution { +public: + vector> rotateTheBox(vector>& box) { + + int R = box.size(), C = box[0].size(); + vector> res(C, vector(R)); + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++) + res[j][R - 1 - i] = box[i][j]; + + fall(res); + return res; + } + +private: + void fall(vector>& box){ + + int R = box.size(), C = box[0].size(); + for(int j = 0; j < C; j ++){ + int k = R - 1, i = R - 1; + for(; i >= 0; i --) + if(box[i][j] == '#') + box[i][j] = '.', + box[k][j] = '#', + k --; + else if(box[i][j] == '*') + k = i - 1; + } + } +}; + + +void print(const vector>& box){ + + for(const vector& line: box){ + for(char c: line) cout << c << " "; + cout << endl; + } +} + +int main() { + + vector> box1 = {{'#', '.', '#'}}; + print(Solution().rotateTheBox(box1)); + // . + // # + // # + + vector> box2 = {{'#', '.', '*', '.'}, + {'#', '#', '*', '.'}}; + print(Solution().rotateTheBox(box2)); + // # . + // # # + // * * + // . . + + return 0; +} diff --git a/1501-2000/1862-Sum-of-Floored-Pairs/cpp-1862/CMakeLists.txt b/1501-2000/1862-Sum-of-Floored-Pairs/cpp-1862/CMakeLists.txt new file mode 100644 index 00000000..5916b1a5 --- /dev/null +++ b/1501-2000/1862-Sum-of-Floored-Pairs/cpp-1862/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_1862) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1862 main.cpp) \ No newline at end of file diff --git a/1501-2000/1862-Sum-of-Floored-Pairs/cpp-1862/main.cpp b/1501-2000/1862-Sum-of-Floored-Pairs/cpp-1862/main.cpp new file mode 100644 index 00000000..b517bec1 --- /dev/null +++ b/1501-2000/1862-Sum-of-Floored-Pairs/cpp-1862/main.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/sum-of-floored-pairs/ +/// Author : liuyubobobo +/// Time : 2021-05-17 + +#include +#include +#include + +using namespace std; + + +/// Presum +/// Time Complexity: O(n + maxv * log(maxv)) +/// Space Complexity: O(maxv) +class Solution { + +private: + long long MOD = 1e9 + 7; + +public: + int sumOfFlooredPairs(vector& nums) { + + int maxv = *max_element(nums.begin(), nums.end()); + vector presum(maxv + 1, 0); + for(int e: nums) presum[e] ++; + for(int i = 1; i <= maxv; i ++) presum[i] += presum[i - 1]; + + long long res = 0ll; + for(int e = 1; e <= maxv; e ++) + if(presum[e] - presum[e - 1]){ + + for(int k = 1; k * e <= maxv; k ++) + // [k * e, (k + 1) * e - 1] + res += (long long)(presum[e] - presum[e - 1]) * k * + (((k + 1) * e - 1 <= maxv ? presum[(k + 1) * e - 1] : presum.back()) - presum[k * e - 1]); + } + + return res % MOD; + } +}; + + +int main() { + + vector nums1 = {2, 5, 9}; + cout << Solution().sumOfFlooredPairs(nums1) << endl; + // 10 + + vector nums2 = {7, 7, 7, 7, 7, 7, 7}; + cout << Solution().sumOfFlooredPairs(nums2) << endl; + // 49 + + return 0; +} diff --git a/1501-2000/1863-Sum-of-All-Subset-XOR-Totals/cpp-1863/CMakeLists.txt b/1501-2000/1863-Sum-of-All-Subset-XOR-Totals/cpp-1863/CMakeLists.txt new file mode 100644 index 00000000..56912ed2 --- /dev/null +++ b/1501-2000/1863-Sum-of-All-Subset-XOR-Totals/cpp-1863/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1501-2000/1863-Sum-of-All-Subset-XOR-Totals/cpp-1863/main.cpp b/1501-2000/1863-Sum-of-All-Subset-XOR-Totals/cpp-1863/main.cpp new file mode 100644 index 00000000..e4d04ad4 --- /dev/null +++ b/1501-2000/1863-Sum-of-All-Subset-XOR-Totals/cpp-1863/main.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/sum-of-all-subset-xor-totals/ +/// Author : liuyubobobo +/// Time : 2021-05-15 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n * 2^n) +/// Space Complexity: O(1) +class Solution { +public: + int subsetXORSum(vector& nums) { + + int n = nums.size(), res = 0; + for(int state = 1; state < (1 << n); state ++){ + + int t = 0; + for(int k = 0; k < n; k ++) + if(state & (1 << k)) t ^= nums[k]; + res += t; + } + return res; + } +}; + +int main() { + + return 0; +} diff --git a/1501-2000/1864-Minimum-Number-of-Swaps-to-Make-the-Binary-String-Alternating/cpp-1864/CMakeLists.txt b/1501-2000/1864-Minimum-Number-of-Swaps-to-Make-the-Binary-String-Alternating/cpp-1864/CMakeLists.txt new file mode 100644 index 00000000..358dfef4 --- /dev/null +++ b/1501-2000/1864-Minimum-Number-of-Swaps-to-Make-the-Binary-String-Alternating/cpp-1864/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1501-2000/1864-Minimum-Number-of-Swaps-to-Make-the-Binary-String-Alternating/cpp-1864/main.cpp b/1501-2000/1864-Minimum-Number-of-Swaps-to-Make-the-Binary-String-Alternating/cpp-1864/main.cpp new file mode 100644 index 00000000..41e55bbe --- /dev/null +++ b/1501-2000/1864-Minimum-Number-of-Swaps-to-Make-the-Binary-String-Alternating/cpp-1864/main.cpp @@ -0,0 +1,61 @@ +/// Source : https://leetcode.com/problems/minimum-number-of-swaps-to-make-the-binary-string-alternating/ +/// Author : liuyubobobo +/// Time : 2021-05-15 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Compelxity: O(|s|) +/// Space Complexity: O(|s|) +class Solution { +public: + int minSwaps(string s) { + + int n = s.size(); + + string a = ""; + for(int i = 0; i < n; i ++) + a += ('0' + (i % 2)); + int ares = solve(s, a); + + string b = ""; + for(int i = 0; i < n; i ++) + b += ('0' + (1 - i % 2)); + int bres = solve(s, b); + + int res = min(ares, bres); + return res == INT_MAX ? -1 : res; + } + +private: + int solve(const string& s, const string& t){ + + int one = 0, zero = 0; + for(int i = 0; i < s.size(); i ++) + if(s[i] != t[i]){ + if(s[i] == '1') one ++; + else zero ++; + } + + return one == zero ? one : INT_MAX; + } +}; + + +int main() { + + cout << Solution().minSwaps("111000") << endl; + // 1 + + cout << Solution().minSwaps("010") << endl; + // 0 + + cout << Solution().minSwaps("1110") << endl; + // -1 + + return 0; +} diff --git a/1501-2000/1865-Finding-Pairs-With-a-Certain-Sum/cpp-1865/CMakeLists.txt b/1501-2000/1865-Finding-Pairs-With-a-Certain-Sum/cpp-1865/CMakeLists.txt new file mode 100644 index 00000000..ad5a4184 --- /dev/null +++ b/1501-2000/1865-Finding-Pairs-With-a-Certain-Sum/cpp-1865/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1501-2000/1865-Finding-Pairs-With-a-Certain-Sum/cpp-1865/main.cpp b/1501-2000/1865-Finding-Pairs-With-a-Certain-Sum/cpp-1865/main.cpp new file mode 100644 index 00000000..11ba17af --- /dev/null +++ b/1501-2000/1865-Finding-Pairs-With-a-Certain-Sum/cpp-1865/main.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/finding-pairs-with-a-certain-sum/ +/// Author : liuyubobobo +/// Time : 2021-05-15 + +#include +#include +#include + +using namespace std; + + +/// Using HashMap +/// Time Complexity: init: O(|nums1| + |nums2|) +/// add: O(1) +/// count: O(|nums1|) +/// Space Complexity: O(|nums1| + |nums2|) +class FindSumPairs { + +private: + vector nums1, nums2; + unordered_map f; + +public: + FindSumPairs(vector& nums1, vector& nums2) : nums1(nums1), nums2(nums2) { + for(int e: nums2) f[e] ++; + } + + void add(int index, int val) { + + int a = nums2[index]; + f[a] --; + if(f[a] == 0) f.erase(a); + f[a + val] ++; + nums2[index] += val; + } + + int count(int tot) { + + int res = 0; + for(int e: nums1) + if(f.find(tot - e) != f.end()) res += f[tot - e]; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1866-Number-of-Ways-to-Rearrange-Sticks-With-K-Sticks-Visible/cpp-1866/CMakeLists.txt b/1501-2000/1866-Number-of-Ways-to-Rearrange-Sticks-With-K-Sticks-Visible/cpp-1866/CMakeLists.txt new file mode 100644 index 00000000..c12729a4 --- /dev/null +++ b/1501-2000/1866-Number-of-Ways-to-Rearrange-Sticks-With-K-Sticks-Visible/cpp-1866/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main3.cpp) \ No newline at end of file diff --git a/1501-2000/1866-Number-of-Ways-to-Rearrange-Sticks-With-K-Sticks-Visible/cpp-1866/main.cpp b/1501-2000/1866-Number-of-Ways-to-Rearrange-Sticks-With-K-Sticks-Visible/cpp-1866/main.cpp new file mode 100644 index 00000000..4cb75fae --- /dev/null +++ b/1501-2000/1866-Number-of-Ways-to-Rearrange-Sticks-With-K-Sticks-Visible/cpp-1866/main.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/number-of-ways-to-rearrange-sticks-with-k-sticks-visible/ +/// Author : liuyubobobo +/// Time : 2021-05-18 + +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(nk) +/// Space Complexity: O(nk) +class Solution { + +private: + long long MOD = 1e9 + 7; + +public: + long long rearrangeSticks(int n, int k) { + + vector> dp(n + 1, vector(k + 1, -1ll)); + return dfs(n, k, dp); + } + +private: + long long dfs(int n, int k, vector>& dp){ + + if(k > n) return 0; + if(k == 0) return 0; + if(n == 1) return 1; + if(dp[n][k] != -1ll) return dp[n][k]; + return dp[n][k] = (dfs(n - 1, k - 1, dp) + (n - 1) * dfs(n - 1, k, dp)) % MOD; + } +}; + + +int main() { + + cout << Solution().rearrangeSticks(3, 2) << endl; + // 3 + + cout << Solution().rearrangeSticks(5, 5) << endl; + // 1 + + cout << Solution().rearrangeSticks(20, 11) << endl; + // 647427950 + + return 0; +} diff --git a/1501-2000/1866-Number-of-Ways-to-Rearrange-Sticks-With-K-Sticks-Visible/cpp-1866/main2.cpp b/1501-2000/1866-Number-of-Ways-to-Rearrange-Sticks-With-K-Sticks-Visible/cpp-1866/main2.cpp new file mode 100644 index 00000000..082e4672 --- /dev/null +++ b/1501-2000/1866-Number-of-Ways-to-Rearrange-Sticks-With-K-Sticks-Visible/cpp-1866/main2.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/number-of-ways-to-rearrange-sticks-with-k-sticks-visible/ +/// Author : liuyubobobo +/// Time : 2021-05-18 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(nk) +/// Space Complexity: O(nk) +class Solution { + +private: + long long MOD = 1e9 + 7; + +public: + long long rearrangeSticks(int n, int k) { + + vector> dp(n + 1, vector(k + 1, 0ll)); + dp[1][1] = 1ll; + for(int i = 2; i <= n; i ++){ + for(int j = 1; j <= min(i, k); j ++) + dp[i][j] = (dp[i - 1][j - 1] + (i - 1) * dp[i - 1][j]) % MOD; + } + + return dp[n][k]; + } +}; + + +int main() { + + cout << Solution().rearrangeSticks(3, 2) << endl; + // 3 + + cout << Solution().rearrangeSticks(5, 5) << endl; + // 1 + + cout << Solution().rearrangeSticks(20, 11) << endl; + // 647427950 + + return 0; +} diff --git a/1501-2000/1866-Number-of-Ways-to-Rearrange-Sticks-With-K-Sticks-Visible/cpp-1866/main3.cpp b/1501-2000/1866-Number-of-Ways-to-Rearrange-Sticks-With-K-Sticks-Visible/cpp-1866/main3.cpp new file mode 100644 index 00000000..53ffe56f --- /dev/null +++ b/1501-2000/1866-Number-of-Ways-to-Rearrange-Sticks-With-K-Sticks-Visible/cpp-1866/main3.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/number-of-ways-to-rearrange-sticks-with-k-sticks-visible/ +/// Author : liuyubobobo +/// Time : 2021-05-18 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(nk) +/// Space Complexity: O(nk) +class Solution { + +private: + long long MOD = 1e9 + 7; + +public: + long long rearrangeSticks(int n, int k) { + + vector dp(k + 1, 0ll); + dp[1] = 1ll; + for(int i = 2; i <= n; i ++){ + for(int j = min(i, k); j >= 1; j --) + dp[j] = (dp[j - 1] + (i - 1) * dp[j]) % MOD; + } + + return dp[k]; + } +}; + + +int main() { + + cout << Solution().rearrangeSticks(3, 2) << endl; + // 3 + + cout << Solution().rearrangeSticks(5, 5) << endl; + // 1 + + cout << Solution().rearrangeSticks(20, 11) << endl; + // 647427950 + + return 0; +} diff --git a/1501-2000/1868-Product-of-Two-Run-Length-Encoded-Arrays/cpp-1868/CMakeLists.txt b/1501-2000/1868-Product-of-Two-Run-Length-Encoded-Arrays/cpp-1868/CMakeLists.txt new file mode 100644 index 00000000..8acc408f --- /dev/null +++ b/1501-2000/1868-Product-of-Two-Run-Length-Encoded-Arrays/cpp-1868/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_1868) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1868 main.cpp) \ No newline at end of file diff --git a/1501-2000/1868-Product-of-Two-Run-Length-Encoded-Arrays/cpp-1868/main.cpp b/1501-2000/1868-Product-of-Two-Run-Length-Encoded-Arrays/cpp-1868/main.cpp new file mode 100644 index 00000000..66c0a6a9 --- /dev/null +++ b/1501-2000/1868-Product-of-Two-Run-Length-Encoded-Arrays/cpp-1868/main.cpp @@ -0,0 +1,41 @@ +/// Source : https://leetcode.com/problems/product-of-two-run-length-encoded-arrays/ +/// Author : liuyubobobo +/// Time : 2021-05-20 + +#include +#include + +using namespace std; + + +/// Two Pointers +/// Time Complexity: O(|endcode1| + |encode2|) +/// Space Compelxity: O(1) +class Solution { +public: + vector> findRLEArray(vector>& encoded1, vector>& encoded2) { + + vector> res; + int i = 0, j = 0; + while(i < encoded1.size() && j < encoded2.size()){ + + int f = min(encoded1[i][1], encoded2[j][1]); + int v = encoded1[i][0] * encoded2[j][0]; + if(!res.empty() && res.back()[0] == v) res.back()[1] += f; + else res.push_back({v, f}); + + encoded1[i][1] -= f; + if(encoded1[i][1] == 0) i ++; + + encoded2[j][1] -= f; + if(encoded2[j][1] == 0) j ++; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1869-Longer-Contiguous-Segments-of-Ones-than-Zeros/cpp-1869/CMakeLists.txt b/1501-2000/1869-Longer-Contiguous-Segments-of-Ones-than-Zeros/cpp-1869/CMakeLists.txt new file mode 100644 index 00000000..56912ed2 --- /dev/null +++ b/1501-2000/1869-Longer-Contiguous-Segments-of-Ones-than-Zeros/cpp-1869/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1501-2000/1869-Longer-Contiguous-Segments-of-Ones-than-Zeros/cpp-1869/main.cpp b/1501-2000/1869-Longer-Contiguous-Segments-of-Ones-than-Zeros/cpp-1869/main.cpp new file mode 100644 index 00000000..c760ee8e --- /dev/null +++ b/1501-2000/1869-Longer-Contiguous-Segments-of-Ones-than-Zeros/cpp-1869/main.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/longer-contiguous-segments-of-ones-than-zeros/ +/// Author : liuyubobobo +/// Time : 2021-05-22 + +#include + +using namespace std; + + +/// Split String +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + bool checkZeroOnes(string s) { + + int zero = 0, one = 0; + for(int start = 0, i = 1; i <= s.size(); i ++) + if(i == s.size() || s[i] != s[start]){ + + if(s[start] == '0') zero = max(zero, i - start); + else one = max(one, i - start); + + start = i; + i = start; + } + return one > zero; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1870-Minimum-Speed-to-Arrive-on-Time/cpp-1870/CMakeLists.txt b/1501-2000/1870-Minimum-Speed-to-Arrive-on-Time/cpp-1870/CMakeLists.txt new file mode 100644 index 00000000..358dfef4 --- /dev/null +++ b/1501-2000/1870-Minimum-Speed-to-Arrive-on-Time/cpp-1870/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1501-2000/1870-Minimum-Speed-to-Arrive-on-Time/cpp-1870/main.cpp b/1501-2000/1870-Minimum-Speed-to-Arrive-on-Time/cpp-1870/main.cpp new file mode 100644 index 00000000..94940854 --- /dev/null +++ b/1501-2000/1870-Minimum-Speed-to-Arrive-on-Time/cpp-1870/main.cpp @@ -0,0 +1,58 @@ +/// Source : https://leetcode.com/problems/minimum-speed-to-arrive-on-time/ +/// Author : liuyubobobo +/// Time : 2021-05-22 + +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(n * log(MAX_INT)) +/// Space Complexity: O(1) +class Solution { +public: + int minSpeedOnTime(vector& dist, double hour) { + + int l = 1, r = 1e7 + 1; + while(l < r){ + int mid = l + (r - l) / 2; + if(get_time(dist, mid) <= hour) r = mid; + else l = mid + 1; + } + return l == 1e7 + 1 ? -1 : l; + } + +private: + double get_time(const vector& dist, int speed){ + + double h = 0; + for(int i = 0; i < dist.size(); i ++) + if(i != dist.size() - 1) h += dist[i] / speed + !!(dist[i] % speed); + else h += (double)dist[i] / speed; + return h; + } +}; + + +int main() { + + vector dist1 = {1, 3, 2}; + cout << Solution().minSpeedOnTime(dist1, 6) << endl; + // 1 + + vector dist2 = {1, 3, 2}; + cout << Solution().minSpeedOnTime(dist2, 2.7) << endl; + // 3 + + vector dist3 = {1, 3, 2}; + cout << Solution().minSpeedOnTime(dist3, 1.9) << endl; + // -1 + + vector dist4 = {1, 1, 100000}; + cout << Solution().minSpeedOnTime(dist4, 2.01) << endl; + // 10000000 + + return 0; +} diff --git a/1501-2000/1871-Jump-Game-VII/cpp-1871/CMakeLists.txt b/1501-2000/1871-Jump-Game-VII/cpp-1871/CMakeLists.txt new file mode 100644 index 00000000..53575fde --- /dev/null +++ b/1501-2000/1871-Jump-Game-VII/cpp-1871/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main2.cpp) \ No newline at end of file diff --git a/1501-2000/1871-Jump-Game-VII/cpp-1871/main.cpp b/1501-2000/1871-Jump-Game-VII/cpp-1871/main.cpp new file mode 100644 index 00000000..99c3ae3f --- /dev/null +++ b/1501-2000/1871-Jump-Game-VII/cpp-1871/main.cpp @@ -0,0 +1,60 @@ +/// Source : https://leetcode.com/problems/jump-game-vii/ +/// Author : liuyubobobo +/// Time : 2021-05-22 + +#include +#include + +using namespace std; + + +/// Presum +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + bool canReach(string s, int minJump, int maxJump) { + + s = string(maxJump, '0') + s; // deal with bounding problem + int n = s.size(); + vector data(n, 0), presum(n + 1, 0); + + data[maxJump] = 1, presum[maxJump + 1] = 1; + for(int i = maxJump + 1; i < n; i ++){ + presum[i + 1] = presum[i]; + if(s[i] == '0'){ + int l = i - maxJump, r = i - minJump; + if(presum[r + 1] - presum[l]) + data[i] = 1, presum[i + 1] ++; + } + } + return data.back(); + } +}; + + +int main() { + + cout << Solution().canReach("011010", 2, 3) << endl; + // 1 + + cout << Solution().canReach("01101110", 2, 3) << endl; + // 0 + + cout << Solution().canReach("00", 1000, 1000) << endl; + // 1 + + cout << Solution().canReach("01", 1000, 1000) << endl; + // 0 + + cout << Solution().canReach("010", 1, 1) << endl; + // 0 + + cout << Solution().canReach("0" + string(1e5-2, '1') + "0", 1, 1e5 - 2) << endl; + // 0 + + cout << Solution().canReach("01010", 5, 5) << endl; + // 0 + + return 0; +} diff --git a/1501-2000/1871-Jump-Game-VII/cpp-1871/main2.cpp b/1501-2000/1871-Jump-Game-VII/cpp-1871/main2.cpp new file mode 100644 index 00000000..cef399e9 --- /dev/null +++ b/1501-2000/1871-Jump-Game-VII/cpp-1871/main2.cpp @@ -0,0 +1,61 @@ +/// Source : https://leetcode.com/problems/jump-game-vii/ +/// Author : liuyubobobo +/// Time : 2021-05-23 + +#include +#include + +using namespace std; + + +/// Another Presum Implementation +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + bool canReach(string s, int minJump, int maxJump) { + + int n = s.size(); + vector data(n, 0), presum(n + 1, 0); + + data[0] = 1, presum[1] = 1; + for(int i = 1; i < minJump; i ++) presum[i + 1] = 1; // deal with bounding problem + + for(int i = minJump; i < n; i ++){ + presum[i + 1] = presum[i]; + if(s[i] == '0'){ + int l = max(0, i - maxJump), r = i - minJump; + if(presum[r + 1] - presum[l]) + data[i] = 1, presum[i + 1] ++; + } + } + return data.back(); + } +}; + + +int main() { + + cout << Solution().canReach("011010", 2, 3) << endl; + // 1 + + cout << Solution().canReach("01101110", 2, 3) << endl; + // 0 + + cout << Solution().canReach("00", 1000, 1000) << endl; + // 1 + + cout << Solution().canReach("01", 1000, 1000) << endl; + // 0 + + cout << Solution().canReach("010", 1, 1) << endl; + // 0 + + cout << Solution().canReach("0" + string(1e5-2, '1') + "0", 1, 1e5 - 2) << endl; + // 0 + + cout << Solution().canReach("01010", 5, 5) << endl; + // 0 + + return 0; +} diff --git a/1501-2000/1872-Stone-Game-VIII/cpp-1872/CMakeLists.txt b/1501-2000/1872-Stone-Game-VIII/cpp-1872/CMakeLists.txt new file mode 100644 index 00000000..8700daa5 --- /dev/null +++ b/1501-2000/1872-Stone-Game-VIII/cpp-1872/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main2.cpp) \ No newline at end of file diff --git a/1501-2000/1872-Stone-Game-VIII/cpp-1872/main.cpp b/1501-2000/1872-Stone-Game-VIII/cpp-1872/main.cpp new file mode 100644 index 00000000..9395e732 --- /dev/null +++ b/1501-2000/1872-Stone-Game-VIII/cpp-1872/main.cpp @@ -0,0 +1,55 @@ +/// Source : https://leetcode.com/problems/stone-game-viii/ +/// Author : liuyubobobo +/// Time : 2021-05-23 + +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int stoneGameVIII(vector& stones) { + + int n = stones.size(); + vector sum(n, stones[0]); + for(int i = 1; i < n; i ++) + sum[i] = sum[i - 1] + stones[i]; + + vector dp(n, INT_MIN); + return dfs(n, sum, 0, dp); + } + +private: + int dfs(int n, const vector& sum, int start, vector& dp){ + + if(start >= n - 1) return 0; + if(start == n - 2) return sum[start + 1]; + if(dp[start] != INT_MIN) return dp[start]; + + int res = max(sum[start + 1] - dfs(n, sum, start + 1, dp), dfs(n, sum, start + 1, dp)); + return dp[start] = res; + } +}; + + +int main() { + + vector stones1 = {-1, 2, -3, 4, -5}; + cout << Solution().stoneGameVIII(stones1) << endl; + // 5 + + vector stones2 = {7, -6, 5, 10, 5, -2, -6}; + cout << Solution().stoneGameVIII(stones2) << endl; + // 13 + + vector stones3 = {-10, -12}; + cout << Solution().stoneGameVIII(stones3) << endl; + // -22 + + return 0; +} diff --git a/1501-2000/1872-Stone-Game-VIII/cpp-1872/main2.cpp b/1501-2000/1872-Stone-Game-VIII/cpp-1872/main2.cpp new file mode 100644 index 00000000..3a498ddb --- /dev/null +++ b/1501-2000/1872-Stone-Game-VIII/cpp-1872/main2.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/stone-game-viii/ +/// Author : liuyubobobo +/// Time : 2021-05-23 + +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int stoneGameVIII(vector& stones) { + + int n = stones.size(); + vector sum(n, stones[0]); + for(int i = 1; i < n; i ++) + sum[i] = sum[i - 1] + stones[i]; + + vector dp(n, INT_MIN); + dp[n - 2] = sum[n - 1]; + for(int i = n - 3; i >= 0; i --) + dp[i] = max(sum[i + 1] - dp[i + 1], dp[i + 1]); + return dp[0]; + } +}; + + +int main() { + + vector stones1 = {-1, 2, -3, 4, -5}; + cout << Solution().stoneGameVIII(stones1) << endl; + // 5 + + vector stones2 = {7, -6, 5, 10, 5, -2, -6}; + cout << Solution().stoneGameVIII(stones2) << endl; + // 13 + + vector stones3 = {-10, -12}; + cout << Solution().stoneGameVIII(stones3) << endl; + // -22 + + return 0; +} diff --git a/1501-2000/1874-Minimize-Product-Sum-of-Two-Arrays/cpp-1874/CMakeLists.txt b/1501-2000/1874-Minimize-Product-Sum-of-Two-Arrays/cpp-1874/CMakeLists.txt new file mode 100644 index 00000000..82e01aee --- /dev/null +++ b/1501-2000/1874-Minimize-Product-Sum-of-Two-Arrays/cpp-1874/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_1874) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1874 main.cpp) \ No newline at end of file diff --git a/1501-2000/1874-Minimize-Product-Sum-of-Two-Arrays/cpp-1874/main.cpp b/1501-2000/1874-Minimize-Product-Sum-of-Two-Arrays/cpp-1874/main.cpp new file mode 100644 index 00000000..50b54a54 --- /dev/null +++ b/1501-2000/1874-Minimize-Product-Sum-of-Two-Arrays/cpp-1874/main.cpp @@ -0,0 +1,32 @@ +/// Source : https://leetcode.com/problems/minimize-product-sum-of-two-arrays/ +/// Author : liuyubobobo +/// Time : 2021-05-27 + +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + int minProductSum(vector& nums1, vector& nums2) { + + sort(nums1.begin(), nums1.end()); + sort(nums2.rbegin(), nums2.rend()); + + int res = 0; + for(int i = 0; i < nums1.size(); i ++) + res += nums1[i] * nums2[i]; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1876-Substrings-of-Size-Three-with-Distinct-Characters/cpp-1876/CMakeLists.txt b/1501-2000/1876-Substrings-of-Size-Three-with-Distinct-Characters/cpp-1876/CMakeLists.txt new file mode 100644 index 00000000..f0a47a85 --- /dev/null +++ b/1501-2000/1876-Substrings-of-Size-Three-with-Distinct-Characters/cpp-1876/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_1876) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1876 main.cpp) \ No newline at end of file diff --git a/1501-2000/1876-Substrings-of-Size-Three-with-Distinct-Characters/cpp-1876/main.cpp b/1501-2000/1876-Substrings-of-Size-Three-with-Distinct-Characters/cpp-1876/main.cpp new file mode 100644 index 00000000..bb102044 --- /dev/null +++ b/1501-2000/1876-Substrings-of-Size-Three-with-Distinct-Characters/cpp-1876/main.cpp @@ -0,0 +1,28 @@ +/// Source : https://leetcode.com/problems/substrings-of-size-three-with-distinct-characters/ +/// Author : liuyubobobo +/// Time : 2021-05-28 + +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int countGoodSubstrings(string s) { + + int res = 0; + for(int i = 2; i < s.size(); i ++) + res += ((s[i-2]!=s[i-1]) && (s[i-1]!=s[i]) && (s[i]!=s[i-2])); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1877-Minimize-Maximum-Pair-Sum-in-Array/cpp-1877/CMakeLists.txt b/1501-2000/1877-Minimize-Maximum-Pair-Sum-in-Array/cpp-1877/CMakeLists.txt new file mode 100644 index 00000000..7ad7b7e9 --- /dev/null +++ b/1501-2000/1877-Minimize-Maximum-Pair-Sum-in-Array/cpp-1877/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_1877) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1877 main.cpp) \ No newline at end of file diff --git a/1501-2000/1877-Minimize-Maximum-Pair-Sum-in-Array/cpp-1877/main.cpp b/1501-2000/1877-Minimize-Maximum-Pair-Sum-in-Array/cpp-1877/main.cpp new file mode 100644 index 00000000..7463e370 --- /dev/null +++ b/1501-2000/1877-Minimize-Maximum-Pair-Sum-in-Array/cpp-1877/main.cpp @@ -0,0 +1,32 @@ +/// Source : https://leetcode.com/problems/minimize-maximum-pair-sum-in-array/ +/// Author : liuyubobobo +/// Time : 2021-05-28 + +#include +#include + +using namespace std; + + +/// Sorting and Greedy +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + int minPairSum(vector& nums) { + + sort(nums.begin(), nums.end()); + + int n = nums.size(); + int res = nums[0] + nums.back(); + for(int i = 1; i < (n >> 1); i ++) + res = max(res, nums[i] + nums[n - 1 - i]); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1878-Get-Biggest-Three-Rhombus-Sums-in-a-Grid/cpp-1878/CMakeLists.txt b/1501-2000/1878-Get-Biggest-Three-Rhombus-Sums-in-a-Grid/cpp-1878/CMakeLists.txt new file mode 100644 index 00000000..253fafe2 --- /dev/null +++ b/1501-2000/1878-Get-Biggest-Three-Rhombus-Sums-in-a-Grid/cpp-1878/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_1878) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1878 main.cpp) \ No newline at end of file diff --git a/1501-2000/1878-Get-Biggest-Three-Rhombus-Sums-in-a-Grid/cpp-1878/main.cpp b/1501-2000/1878-Get-Biggest-Three-Rhombus-Sums-in-a-Grid/cpp-1878/main.cpp new file mode 100644 index 00000000..9834100d --- /dev/null +++ b/1501-2000/1878-Get-Biggest-Three-Rhombus-Sums-in-a-Grid/cpp-1878/main.cpp @@ -0,0 +1,117 @@ +/// Source : https://leetcode.com/problems/get-biggest-three-rhombus-sums-in-a-grid/ +/// Author : liuyubobobo +/// Time : 2021-06-10 + +#include +#include +#include + +using namespace std; + + +/// PreSum +/// Time Complexity: O(m * n) +/// Space Complexity: O(m * n) +class Solution { + +private: + int m, n; + +public: + vector getBiggestThree(vector>& grid) { + + m = grid.size(), n = grid[0].size(); + vector> A(m + 2, vector(n + 2, 0)), B = A; + + for(int i = 0; i < m; i ++) + for(int j = 0; j < n; j ++) { + A[i + 1][j + 1] = grid[i][j] + A[i][j]; + B[i + 1][j + 1] = grid[i][j] + B[i][j + 2]; + } + +// cout << "grid : " << endl; +// for(const vector& r: grid){ +// for(int e: r) cout << e << "\t"; cout << endl; +// } +// +// cout << "A : " << endl; +// for(const vector& r: A){ +// for(int e: r) cout << e << "\t"; cout << endl; +// } +// +// cout << "B : " << endl; +// for(const vector& r: B){ +// for(int e: r) cout << e << "\t"; cout << endl; +// } + + set set; + for(int i = 0; i < m; i ++) + for(int j = 0; j < n; j ++){ + set.insert(grid[i][j]); + + for(int sz = 1; in_area(i-sz,j+sz) && in_area(i+sz,j+sz) && in_area(i,j+2*sz);sz++){ + int res = A[i + sz + 1][j + sz + 1] - A[i][j]; + res += A[i + 1][j + 2 * sz + 1] - A[i - sz][j + sz]; + res += B[i - 1 + 1][j + 1 + 1] - B[i - sz + 1][j + sz + 1]; + res += B[i + sz - 1 + 1][j + sz + 1 + 1] - B[i + 1][j + 2 * sz + 1]; +// res -= grid[i][j] + grid[i - sz][j + sz] + grid[i][j + 2 * sz] + grid[i + sz][j + sz]; + set.insert(res); +// cout << i << "," << j << "," << sz << " : " << res << endl; + } + } + + vector res; + while(!set.empty() && res.size() < 3){ + res.push_back(*set.rbegin()); + set.erase(res.back()); + } + return res; + } + +private: + bool in_area(int x, int y){ + return x >= 0 && x < m && y >= 0 && y < n; + } +}; + + +void print_vector(const vector& v){ + for(int e: v) cout << e << " "; cout << endl; +} + +int main() { + + vector> grid1 = { + {1, 2, 3}, + {4, 5, 6}, + {7, 8, 9} + }; + print_vector(Solution().getBiggestThree(grid1)); + // 20, 9, 8 + + vector> grid2 = { + {3,4,5,1,3}, + {3,3,4,2,3}, + {20,30,200,40,10}, + {1,5,5,4,1}, + {4,3,2,2,5} + }; + print_vector(Solution().getBiggestThree(grid2)); + // 228, 216, 211 + + vector> grid3 = {{7, 7, 7}}; + print_vector(Solution().getBiggestThree(grid3)); + // 7 + + vector> grid4 ={ + {20,17,9,13,5,2,9,1,5}, + {14,9,9,9,16,18,3,4,12}, + {18,15,10,20,19,20,15,12,11}, + {19,16,19,18,8,13,15,14,11}, + {4,19,5,2,19,17,7,2,2} + }; + print_vector(Solution().getBiggestThree(grid4)); + // 107, 103, 102 + + return 0; +} diff --git a/1501-2000/1879-Minimum-XOR-Sum-of-Two-Arrays/cpp-1879/CMakeLists.txt b/1501-2000/1879-Minimum-XOR-Sum-of-Two-Arrays/cpp-1879/CMakeLists.txt new file mode 100644 index 00000000..63c67279 --- /dev/null +++ b/1501-2000/1879-Minimum-XOR-Sum-of-Two-Arrays/cpp-1879/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_1879) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1879 main.cpp) \ No newline at end of file diff --git a/1501-2000/1879-Minimum-XOR-Sum-of-Two-Arrays/cpp-1879/main.cpp b/1501-2000/1879-Minimum-XOR-Sum-of-Two-Arrays/cpp-1879/main.cpp new file mode 100644 index 00000000..abd47145 --- /dev/null +++ b/1501-2000/1879-Minimum-XOR-Sum-of-Two-Arrays/cpp-1879/main.cpp @@ -0,0 +1,61 @@ +/// Source : https://leetcode.com/problems/minimum-xor-sum-of-two-arrays/ +/// Author : liuyubobobo +/// Time : 2021-06-10 + +#include +#include + +using namespace std; + + +/// State Compression Memory Search +/// Time Complexity: O(n * 2^n) +/// Space Complexity: O(2^n) +class Solution { + +private: + int n; + +public: + int minimumXORSum(vector& nums1, vector& nums2) { + + n = nums1.size(); + + vector dp(1 << n, -1); + return dfs(nums1, nums2, 0, dp); + } + +private: + int dfs(const vector& nums1, const vector& nums2, int state, + vector& dp){ + + int index = __builtin_popcount(state); + + if(index == n) return 0; + if(dp[state] != -1) return dp[state]; + + int res = INT_MAX; + for(int i = 0; i < n; i ++) + if(!(state & (1 << i))) + res = min(res, (nums1[index]^nums2[i]) + dfs(nums1, nums2, state | (1 << i), dp)); + return dp[state] = res; + } +}; + + +int main() { + + vector nums11 = {1, 2, 3}, nums12 = {3, 2, 1}; + cout << Solution().minimumXORSum(nums11, nums12) << endl; + // 0 + + vector nums21 = {1, 0, 3}, nums22 = {5, 3, 4}; + cout << Solution().minimumXORSum(nums21, nums22) << endl; + // 8 + + vector nums31 = {72, 97, 8, 32, 15}, nums32 = {63, 97, 57, 60, 83}; + cout << Solution().minimumXORSum(nums31, nums32) << endl; + // 152 + + return 0; +} diff --git a/1501-2000/1880-Check-if-Word-Equals-Summation-of-Two-Words/cpp-1880/CMakeLists.txt b/1501-2000/1880-Check-if-Word-Equals-Summation-of-Two-Words/cpp-1880/CMakeLists.txt new file mode 100644 index 00000000..56912ed2 --- /dev/null +++ b/1501-2000/1880-Check-if-Word-Equals-Summation-of-Two-Words/cpp-1880/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1501-2000/1880-Check-if-Word-Equals-Summation-of-Two-Words/cpp-1880/main.cpp b/1501-2000/1880-Check-if-Word-Equals-Summation-of-Two-Words/cpp-1880/main.cpp new file mode 100644 index 00000000..f08ae993 --- /dev/null +++ b/1501-2000/1880-Check-if-Word-Equals-Summation-of-Two-Words/cpp-1880/main.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/check-if-word-equals-summation-of-two-words/ +/// Author : liuyubobobo +/// Time : 2021-05-29 + +#include + +using namespace std; + + +/// string to int +/// Time Complexity: (|a| + |b| + |c|) +/// Space Complexity: O(1) +class Solution { +public: + bool isSumEqual(string& firstWord, string& secondWord, string& targetWord) { + + int a = parse(firstWord), b = parse(secondWord), c = parse(targetWord); + return a + b == c; + } + +private: + int parse(const string& s){ + int res = 0; + for(char c: s) + res = res * 10 + (c - 'a'); + return res; + } +}; + +int main() { + + return 0; +} diff --git a/1501-2000/1881-Maximum-Value-after-Insertion/cpp-1881/CMakeLists.txt b/1501-2000/1881-Maximum-Value-after-Insertion/cpp-1881/CMakeLists.txt new file mode 100644 index 00000000..358dfef4 --- /dev/null +++ b/1501-2000/1881-Maximum-Value-after-Insertion/cpp-1881/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1501-2000/1881-Maximum-Value-after-Insertion/cpp-1881/main.cpp b/1501-2000/1881-Maximum-Value-after-Insertion/cpp-1881/main.cpp new file mode 100644 index 00000000..10177d0a --- /dev/null +++ b/1501-2000/1881-Maximum-Value-after-Insertion/cpp-1881/main.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/maximum-value-after-insertion/ +/// Author : liuyubobobo +/// Time : 2021-05-29 + +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(|n|) +/// Space Complexity: O(1) +class Solution { +public: + string maxValue(string n, int x) { + + int i; + if(n[0] != '-'){ + for(i = 0; i < n.size(); i ++) + if(n[i] < '0' + x) break; + return n.substr(0, i) + string(1, '0' + x) + n.substr(i); + } + + for(i = 1; i < n.size(); i ++) + if(n[i] > '0' + x) break; + return n.substr(0, i) + string(1, '0' + x) + n.substr(i); + } +}; + + +int main() { + + cout << Solution().maxValue("99", 9) << endl; + // 999 + + cout << Solution().maxValue("514", 2) << endl; + // 5214 + + cout << Solution().maxValue("-13", 2) << endl; + // -123 + + cout << Solution().maxValue("-33", 2) << endl; + // -233 + + cout << Solution().maxValue("-11", 2) << endl; + // -112 + + cout << Solution().maxValue("-6484681536456", 5) << endl; + // -5648468153646 + + return 0; +} diff --git a/1501-2000/1882-Process-Tasks-Using-Servers/cpp-1882/CMakeLists.txt b/1501-2000/1882-Process-Tasks-Using-Servers/cpp-1882/CMakeLists.txt new file mode 100644 index 00000000..ad5a4184 --- /dev/null +++ b/1501-2000/1882-Process-Tasks-Using-Servers/cpp-1882/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1501-2000/1882-Process-Tasks-Using-Servers/cpp-1882/main.cpp b/1501-2000/1882-Process-Tasks-Using-Servers/cpp-1882/main.cpp new file mode 100644 index 00000000..b5ddff54 --- /dev/null +++ b/1501-2000/1882-Process-Tasks-Using-Servers/cpp-1882/main.cpp @@ -0,0 +1,78 @@ +/// Source : https://leetcode.com/problems/process-tasks-using-servers/ +/// Author : liuyubobobo +/// Time : 2021-05-29 + +#include +#include + +using namespace std; + + +/// Priority Queue +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + vector assignTasks(vector& servers, vector& tasks) { + + // waiting_servers {weight, index} + priority_queue, vector>, greater>> waiting_servers; + for(int i = 0; i < servers.size(); i ++) + waiting_servers.push({servers[i], i}); + + // busy_servers {end_tine, index} + priority_queue, vector>, greater>> busy_servers; + vector res(tasks.size()); + int curt = 0, i = 0; + while(i < tasks.size()){ + + if(waiting_servers.empty() && busy_servers.top().first > curt) + curt = busy_servers.top().first; + + while(!busy_servers.empty() && busy_servers.top().first == curt){ + int no = busy_servers.top().second; + waiting_servers.push({servers[no], no}); + busy_servers.pop(); + } + + while(!waiting_servers.empty() && i < tasks.size() && curt >= i){ +// cout << i << " " << curt << endl; + res[i] = waiting_servers.top().second; + int no = waiting_servers.top().second; + busy_servers.push({curt + tasks[i], no}); + waiting_servers.pop(); + i ++; + } + curt ++; + } + return res; + } +}; + + +void print_vector(const vector& v){ + for(int e: v) cout << e << " "; cout << endl; +} + +int main() { + + vector servers1 = {3, 3, 2}, task1 = {1, 2, 3, 2, 1, 2}; + print_vector(Solution().assignTasks(servers1, task1)); + // 2 2 0 2 1 2 + + vector servers2 = {5,1,4,3,2}, task2 = {2,1,2,4,5,2,1}; + print_vector(Solution().assignTasks(servers2, task2)); + // 1,4,1,4,1,3,2 + + vector servers3 = {10,63,95,16,85,57,83,95,6,29,71}, task3 = {70,31,83,15,32,67,98,65,56,48,38,90,5}; + print_vector(Solution().assignTasks(servers3, task3)); + // [8,0,3,9,5,1,10,6,4,2,7,9,0] + + vector servers4 = {338,890,301,532,284,930,426,616,919,267,571,140,716,859,980,469,628,490,195,664,925,652,503,301,917,563,82,947,910,451,366,190,253,516,503,721,889,964,506,914,986,718,520,328,341,765,922,139,911,578,86,435,824,321,942,215,147,985,619,865}; + vector tasks4 = {773,537,46,317,233,34,712,625,336,221,145,227,194,693,981,861,317,308,400,2,391,12,626,265,710,792,620,416,267,611,875,361,494,128,133,157,638,632,2,158,428,284,847,431,94,782,888,44,117,489,222,932,494,948,405,44,185,587,738,164,356,783,276,547,605,609,930,847,39,579,768,59,976,790,612,196,865,149,975,28,653,417,539,131,220,325,252,160,761,226,629,317,185,42,713,142,130,695,944,40,700,122,992,33,30,136,773,124,203,384,910,214,536,767,859,478,96,172,398,146,713,80,235,176,876,983,363,646,166,928,232,699,504,612,918,406,42,931,647,795,139,933,746,51,63,359,303,752,799,836,50,854,161,87,346,507,468,651,32,717,279,139,851,178,934,233,876,797,701,505,878,731,468,884,87,921,782,788,803,994,67,905,309,2,85,200,368,672,995,128,734,157,157,814,327,31,556,394,47,53,755,721,159,843}; + vector res = Solution().assignTasks(servers4, tasks4); + vector correct = {26,50,47,11,56,31,18,55,32,9,4,2,23,53,43,0,44,30,6,51,29,51,15,17,22,34,38,33,42,3,25,10,49,51,7,58,16,21,19,31,19,12,41,35,45,52,13,59,47,36,1,28,48,39,24,8,46,20,5,54,27,37,14,57,40,59,8,45,4,51,47,7,58,4,31,23,54,7,9,56,2,46,56,1,17,42,11,30,12,44,14,32,7,10,23,1,29,27,6,10,33,24,19,10,35,30,35,10,17,49,50,36,29,1,48,44,7,11,24,57,42,30,10,55,3,20,38,15,7,46,32,21,40,16,59,30,53,17,18,22,51,11,53,36,57,26,5,36,56,55,31,34,57,7,52,37,31,10,0,51,41,2,32,25,0,7,49,47,13,14,24,57,28,4,45,43,39,38,8,2,44,45,29,25,25,12,54,5,44,30,27,23,26,7,33,58,41,25,52,40,58,9,52,40}; + for(int i = 0; i < res.size(); i ++) + if(res[i] != correct[i]){cout << i << endl;} + return 0; +} diff --git a/1501-2000/1883-Minimum-Skips-to-Arrive-at-Meeting-On-Time/cpp-1883/CMakeLists.txt b/1501-2000/1883-Minimum-Skips-to-Arrive-at-Meeting-On-Time/cpp-1883/CMakeLists.txt new file mode 100644 index 00000000..8e6ea4a2 --- /dev/null +++ b/1501-2000/1883-Minimum-Skips-to-Arrive-at-Meeting-On-Time/cpp-1883/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) \ No newline at end of file diff --git a/1501-2000/1883-Minimum-Skips-to-Arrive-at-Meeting-On-Time/cpp-1883/main.cpp b/1501-2000/1883-Minimum-Skips-to-Arrive-at-Meeting-On-Time/cpp-1883/main.cpp new file mode 100644 index 00000000..0953b70e --- /dev/null +++ b/1501-2000/1883-Minimum-Skips-to-Arrive-at-Meeting-On-Time/cpp-1883/main.cpp @@ -0,0 +1,83 @@ +/// Source : https://leetcode.com/problems/minimum-skips-to-arrive-at-meeting-on-time/ +/// Author : liuyubobobo +/// Time : 2021-05-29 + +#include +#include + +using namespace std; + + +/// Binary Search + Memory Search +/// Time Complexity: O(n^2 * logn) +/// Space Complexity: O(n^2) +class Solution { + +private: + double speed, hoursBefore; + vector> dp; + +public: + int minSkips(vector& dist, int speed, int hoursBefore) { + + this->speed = speed; + this->hoursBefore = hoursBefore; + + double t = 0; + for(int d: dist) + t += d / this->speed; + + if(t > this->hoursBefore) return -1; + + int n = dist.size(); + dp = vector>(n, vector(n + 1, -1.0)); + + int l = 0, r = n - 1; + while(l < r){ + int mid = (l + r) / 2; + if(ok(dist, mid)) r = mid; + else l = mid + 1; + } + return l; + } + +private: + bool ok(const vector& dist, int k){ + + int n = dist.size(); + return dfs(dist, n - 1, k) <= hoursBefore; + } + + double dfs(const vector& dist, int i, int k){ + + if(i == 0) return dist[i] / speed; + if(dp[i][k] >= 0.0) return dp[i][k]; + + double res = ceil(dfs(dist, i - 1, k) - 1e-8) + dist[i] / speed; + if(k) + res = min(res, dfs(dist, i - 1, k - 1) + dist[i] / speed); + return dp[i][k] = res; + } +}; + + +int main() { + + vector dist1 = {1, 3, 2}; + cout << Solution().minSkips(dist1, 4, 2) << endl; + // 1 + + vector dist2 = {7, 3, 5, 5}; + cout << Solution().minSkips(dist2, 2, 10) << endl; + // 2 + + vector dist3 = {7, 3, 5, 5}; + cout << Solution().minSkips(dist3, 1, 10) << endl; + // -1 + + vector dist4 = {35,57,85,55,63,78,57,54,35,28,97,66,15,45,56,15,37,87,87,76,63,68,86,40,6,29,51,77,8,1,27,39,28,99,18,98,33,38,42,16,1,64,96,56,23,17,49,69,91,30,65,72,86,46,10,51,95,6,56,3,59,10,41,74,55,74,52,91,82,54,38,15,52,3,42,22,80,59,89,47,12,56,14,32,56,76,52,68,11,51,40,96,44,29,43,100,22,10,66,82,15,68,66,25,100,45,45,94,83,19,31,14,19,33,26,23,78,20,98,98,84,10,23,99,81,64,60,97,73,98,75,58,88,73,83,82,80,42,81,41,20}; + cout << Solution().minSkips(dist4, 59, 128) << endl; + // 101 + + return 0; +} diff --git a/1501-2000/1884-Egg-Drop-With-2-Eggs-and-N-Floors/cpp-1884/CMakeLists.txt b/1501-2000/1884-Egg-Drop-With-2-Eggs-and-N-Floors/cpp-1884/CMakeLists.txt new file mode 100644 index 00000000..f268934f --- /dev/null +++ b/1501-2000/1884-Egg-Drop-With-2-Eggs-and-N-Floors/cpp-1884/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_1884) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1884 main.cpp) \ No newline at end of file diff --git a/1501-2000/1884-Egg-Drop-With-2-Eggs-and-N-Floors/cpp-1884/main.cpp b/1501-2000/1884-Egg-Drop-With-2-Eggs-and-N-Floors/cpp-1884/main.cpp new file mode 100644 index 00000000..0ee54ecb --- /dev/null +++ b/1501-2000/1884-Egg-Drop-With-2-Eggs-and-N-Floors/cpp-1884/main.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/egg-drop-with-2-eggs-and-n-floors/ +/// Author : liuyubobobo +/// Time : 2021-06-09 + +#include +#include + +using namespace std; + + +/// Mathematics +/// Time Complexity: O(n^2) +/// Space Complexity: O(1) +class Solution { +public: + int twoEggDrop(int n) { + + for(int i = 1; i <= n; i ++){ + + int sum = 0; + for(int j = i; j >= 1; j --) + sum += j; + if(sum >= n) return i; + } + return -1; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1885-Count-Pairs-in-Two-Arrays/cpp-1885/CMakeLists.txt b/1501-2000/1885-Count-Pairs-in-Two-Arrays/cpp-1885/CMakeLists.txt new file mode 100644 index 00000000..9ffa9169 --- /dev/null +++ b/1501-2000/1885-Count-Pairs-in-Two-Arrays/cpp-1885/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_1885) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1885 main3.cpp) \ No newline at end of file diff --git a/1501-2000/1885-Count-Pairs-in-Two-Arrays/cpp-1885/main.cpp b/1501-2000/1885-Count-Pairs-in-Two-Arrays/cpp-1885/main.cpp new file mode 100644 index 00000000..60260d54 --- /dev/null +++ b/1501-2000/1885-Count-Pairs-in-Two-Arrays/cpp-1885/main.cpp @@ -0,0 +1,105 @@ +/// Source : https://leetcode.com/problems/count-pairs-in-two-arrays/ +/// Author : liuyubobobo +/// Time : 2021-06-07 + +#include +#include +#include + +using namespace std; + + +/// Segment Tree +/// Time Complexity: O(nlog(max_range)) +/// Space Complexity: O(max_range) +class SegmentTree{ + +private: + int n; + vector data, tree; + +public: + SegmentTree(int n): n(n), data(n, 0), tree(4 * n, 0){} + + void update(int index, int value){ + data[index] = value; + update(0, 0, n - 1, index, value); + } + + int query(int index){ + return data[index]; + } + + int query(int l, int r){ + if(l > r) return 0; + return query(0, 0, n - 1, l, r); + } + +private: + void update(int treeID, int l, int r, int index, int value){ + + if(l == r){ + assert(l == index); + tree[treeID] = value; + return; + } + + int mid = (l + r) / 2; + if(index <= mid) update(treeID * 2 + 1, l, mid, index, value); + else update(treeID * 2 + 2, mid + 1, r, index, value); + + tree[treeID] = tree[treeID * 2 + 1] + tree[treeID * 2 + 2]; + return; + } + + int query(int treeID, int l, int r, int ql, int qr){ + + if(ql == l && qr == r) + return tree[treeID]; + + int mid = (l + r) / 2; + if(qr <= mid) return query(treeID * 2 + 1, l, mid, ql, qr); + else if(ql > mid) return query(treeID * 2 + 2, mid + 1, r, ql, qr); + + int resl = query(treeID * 2 + 1, l, mid, ql, mid); + int resr = query(treeID * 2 + 2, mid + 1, r, mid + 1, qr); + return resl + resr; + } +}; + +class Solution { +public: + long long countPairs(vector& nums1, vector& nums2) { + + int n = nums1.size(); + assert(n == nums2.size()); + for(int i = 0; i < n; i ++) nums1[i] -= nums2[i]; +// for(int e: nums1) cout << e << " "; cout << endl; + + int minv = *min_element(nums1.begin(), nums1.end()); + int maxv = *max_element(nums1.begin(), nums1.end()); + SegmentTree segTree(maxv - minv + 1); + + long long res = 0ll; + for(int e: nums1){ + res += segTree.query(max(0, -e + 1 - minv), maxv - minv); + segTree.update(e - minv, segTree.query(e - minv) + 1); + } + + return res; + } +}; + + +int main() { + + vector nums11 = {2,1,2,1}, nums12 = {1,2,1,2}; + cout << Solution().countPairs(nums11, nums12) << endl; + // 1 + + vector nums21 = {1,10,6,2}, nums22 = {1,4,1,5}; + cout << Solution().countPairs(nums21, nums22) << endl; + // 1 + + return 0; +} diff --git a/1501-2000/1885-Count-Pairs-in-Two-Arrays/cpp-1885/main2.cpp b/1501-2000/1885-Count-Pairs-in-Two-Arrays/cpp-1885/main2.cpp new file mode 100644 index 00000000..5b4c3f97 --- /dev/null +++ b/1501-2000/1885-Count-Pairs-in-Two-Arrays/cpp-1885/main2.cpp @@ -0,0 +1,222 @@ +/// Source : https://leetcode.com/problems/count-pairs-in-two-arrays/ +/// Author : liuyubobobo +/// Time : 2021-06-07 + +#include +#include +#include + +using namespace std; + + +/// AVL +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class AVLTree{ + +private: + class Node{ + public: + int key, value = 1; + Node *left = nullptr, *right = nullptr; + int height = 1, size = 1; + + Node(int key): key(key){} + }; + + Node* root = nullptr; + +public: + AVLTree(){} + + int size(){ + return size(root); + } + + // 向二分搜索树中添加新的元素(key, value) + void add(int key){ + root = add(root, key); + } + + bool contains(int key){ + return getNode(root, key) != nullptr; + } + + int get(int key){ + Node* node = getNode(root, key); + assert(node); + return node->value; + } + + // 1-based rank + int rank(int key){ + + Node* node = getNode(root, key); + assert(node); + + return size_less_than(key) + 1; + } + + int size_less_than(int key){ + return size_less_than(root, key); + } + + int size_larger_than(int key){ + return size_larger_than(root, key); + } + +private: + int size(Node* node){ + return node ? node->size : 0; + } + + int height(Node* node){ + return node ? node->height : 0; + } + + int getBalanceFactor(Node* node){ + return height(node->left) - height(node->right); + } + + Node* rightRotate(Node* y) { + Node* x = y->left; + Node* T3 = x->right; + + // 向右旋转过程 + x->right = y; + y->left = T3; + + // 更新 height 和 size + y->height = max(height(y->left), height(y->right)) + 1; + x->height = max(height(x->left), height(x->right)) + 1; + + y->size = size(y->left) + size(y->right) + y->value; + x->size = size(x->left) + size(x->right) + x->value; + + return x; + } + + Node* leftRotate(Node* y) { + Node* x = y->right; + Node* T2 = x->left; + + // 向左旋转过程 + x->left = y; + y->right = T2; + + // 更新 height 和 size + y->height = max(height(y->left), height(y->right)) + 1; + x->height = max(height(x->left), height(x->right)) + 1; + + y->size = size(y->left) + size(y->right) + y->value; + x->size = size(x->left) + size(x->right) + x->value; + + return x; + } + + // 向以node为根的二分搜索树中插入元素(key, value),递归算法 + // 返回插入新节点后二分搜索树的根 + Node* add(Node* node, int key){ + + if(node == nullptr){ + return new Node(key); + } + + if(key < node->key) + node->left = add(node->left, key); + else if(key > node->key) + node->right = add(node->right, key); + else // key.compareTo(node.key) == 0 + node->value ++, node->size ++; + + // 更新 height 和 size + node->height = 1 + max(height(node->left), height(node->right)); + node->size = node->value + size(node->left) + size(node->right); + + // 计算平衡因子 + int balanceFactor = getBalanceFactor(node); + + // 平衡维护 + // LL + if (balanceFactor > 1 && getBalanceFactor(node->left) >= 0) + return rightRotate(node); + + // RR + if (balanceFactor < -1 && getBalanceFactor(node->right) <= 0) + return leftRotate(node); + + // LR + if (balanceFactor > 1 && getBalanceFactor(node->left) < 0) { + node->left = leftRotate(node->left); + return rightRotate(node); + } + + // RL + if (balanceFactor < -1 && getBalanceFactor(node->right) > 0) { + node->right = rightRotate(node->right); + return leftRotate(node); + } + + return node; + } + + // 返回以node为根节点的二分搜索树中,key所在的节点 + Node* getNode(Node* node, int key){ + + if(node == nullptr) + return nullptr; + + if(key == node->key) + return node; + else if(key < node->key) + return getNode(node->left, key); + else // if(key.compareTo(node.key) > 0) + return getNode(node->right, key); + } + + int size_less_than(Node* node, int key){ + if(!node) return 0; + if(key <= node->key) return size_less_than(node->left, key); + return size(node->left) + node->value + size_less_than(node->right, key); + } + + int size_larger_than(Node* node, int key){ + if(!node) return 0; + if(key >= node->key) return size_larger_than(node->right, key); + return size(node->right) + node->value + size_larger_than(node->left, key); + } +}; + +class Solution { +public: + long long countPairs(vector& nums1, vector& nums2) { + + int n = nums1.size(); + assert(n == nums2.size()); + for(int i = 0; i < n; i ++) nums1[i] -= nums2[i]; +// for(int e: nums1) cout << e << " "; cout << endl; + + AVLTree tree; + + long long res = 0ll; + for(int e: nums1){ + res += tree.size_larger_than(-e); + tree.add(e); + } + return res; + } +}; + + +int main() { + + vector nums11 = {2,1,2,1}, nums12 = {1,2,1,2}; + cout << Solution().countPairs(nums11, nums12) << endl; + // 1 + + vector nums21 = {1,10,6,2}, nums22 = {1,4,1,5}; + cout << Solution().countPairs(nums21, nums22) << endl; + // 5 + + return 0; +} diff --git a/1501-2000/1885-Count-Pairs-in-Two-Arrays/cpp-1885/main3.cpp b/1501-2000/1885-Count-Pairs-in-Two-Arrays/cpp-1885/main3.cpp new file mode 100644 index 00000000..3f2be705 --- /dev/null +++ b/1501-2000/1885-Count-Pairs-in-Two-Arrays/cpp-1885/main3.cpp @@ -0,0 +1,42 @@ +/// Source : https://leetcode.com/problems/count-pairs-in-two-arrays/ +/// Author : liuyubobobo +/// Time : 2021-06-07 + +#include +#include +#include + +using namespace std; + + +/// Sorting and Binary Search +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + long long countPairs(vector& nums1, vector& nums2) { + + int n = nums1.size(); + assert(n == nums2.size()); + for(int i = 0; i < n; i ++) nums1[i] -= nums2[i]; +// for(int e: nums1) cout << e << " "; cout << endl; + + sort(nums1.begin(), nums1.end()); + long long res = 0ll; + for(int i = 1; i < n; i ++){ + vector::iterator iter = upper_bound(nums1.begin(), nums1.begin() + i, - nums1[i]); + res += (i - (iter - nums1.begin())); + } + return res; + } +}; + + +int main() { + + vector nums1 = {2,1,2,1}, nums2 = {1,2,1,2}; + cout << Solution().countPairs(nums1, nums2) << endl; + // 1 + + return 0; +} diff --git a/1501-2000/1885-Count-Pairs-in-Two-Arrays/cpp-1885/main4.cpp b/1501-2000/1885-Count-Pairs-in-Two-Arrays/cpp-1885/main4.cpp new file mode 100644 index 00000000..60d4357d --- /dev/null +++ b/1501-2000/1885-Count-Pairs-in-Two-Arrays/cpp-1885/main4.cpp @@ -0,0 +1,42 @@ +/// Source : https://leetcode.com/problems/count-pairs-in-two-arrays/ +/// Author : liuyubobobo +/// Time : 2021-06-07 + +#include +#include +#include + +using namespace std; + + +/// Sorting and Two Pointers +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + long long countPairs(vector& nums1, vector& nums2) { + + int n = nums1.size(); + assert(n == nums2.size()); + for(int i = 0; i < n; i ++) nums1[i] -= nums2[i]; +// for(int e: nums1) cout << e << " "; cout << endl; + + sort(nums1.begin(), nums1.end()); + long long res = 0ll; + for(int i = 0, j = n - 1; i < n; i ++){ + while(j > i && nums1[i] + nums1[j] > 0) j --; + res += (long long)(n - max(j + 1, i + 1)); + } + return res; + } +}; + + +int main() { + + vector nums1 = {2,1,2,1}, nums2 = {1,2,1,2}; + cout << Solution().countPairs(nums1, nums2) << endl; + // 1 + + return 0; +} diff --git a/1501-2000/1886-Determine-Whether-Matrix-Can-Be-Obtained-By-Rotation/cpp-1886/CMakeLists.txt b/1501-2000/1886-Determine-Whether-Matrix-Can-Be-Obtained-By-Rotation/cpp-1886/CMakeLists.txt new file mode 100644 index 00000000..56912ed2 --- /dev/null +++ b/1501-2000/1886-Determine-Whether-Matrix-Can-Be-Obtained-By-Rotation/cpp-1886/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1501-2000/1886-Determine-Whether-Matrix-Can-Be-Obtained-By-Rotation/cpp-1886/main.cpp b/1501-2000/1886-Determine-Whether-Matrix-Can-Be-Obtained-By-Rotation/cpp-1886/main.cpp new file mode 100644 index 00000000..ffa6fe67 --- /dev/null +++ b/1501-2000/1886-Determine-Whether-Matrix-Can-Be-Obtained-By-Rotation/cpp-1886/main.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/determine-whether-matrix-can-be-obtained-by-rotation/ +/// Author : liuyubobobo +/// Time : 2021-06-05 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n^2) +/// Space Complexity: O(n^2) +class Solution { +public: + bool findRotation(vector>& mat, vector>& target) { + + for(int i = 0; i < 4; i ++){ + mat = rotate(mat); +// for(const vector& row: mat){ +// for(int e: row) cout << e << " "; +// cout << endl; +// } +// cout << endl; + + if(mat == target) return true; + } + return false; + } + +private: + vector> rotate(const vector>& M){ + + int n = M.size(); + vector> res(n, vector(n)); + + for(int i = 0; i < n; i ++) + for(int j = 0; j < n; j ++) + res[j][n - 1 - i] = M[i][j]; + return res; + } +}; + + +int main() { + + vector> mat3 = {{0,0,0},{0,1,0},{1,1,1}}; + vector> target3 = {{1, 1, 1}, {0, 1, 0}, {0, 0, 0}}; + cout << Solution().findRotation(mat3, target3) << endl; + // 1 + + return 0; +} diff --git a/1501-2000/1887-Reduction-Operations-to-Make-the-Array-Elements-Equal/cpp-1887/CMakeLists.txt b/1501-2000/1887-Reduction-Operations-to-Make-the-Array-Elements-Equal/cpp-1887/CMakeLists.txt new file mode 100644 index 00000000..358dfef4 --- /dev/null +++ b/1501-2000/1887-Reduction-Operations-to-Make-the-Array-Elements-Equal/cpp-1887/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1501-2000/1887-Reduction-Operations-to-Make-the-Array-Elements-Equal/cpp-1887/main.cpp b/1501-2000/1887-Reduction-Operations-to-Make-the-Array-Elements-Equal/cpp-1887/main.cpp new file mode 100644 index 00000000..ade766d3 --- /dev/null +++ b/1501-2000/1887-Reduction-Operations-to-Make-the-Array-Elements-Equal/cpp-1887/main.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/reduction-operations-to-make-the-array-elements-equal/ +/// Author : liuyubobobo +/// Time : 2021-06-05 + +#include +#include +#include + +using namespace std; + + +/// Sorting + Presum +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + int reductionOperations(vector& nums) { + + unordered_map f; + for(int e: nums) f[e] ++; + + vector> data; + for(const pair& p: f) data.push_back(p); + + sort(data.rbegin(), data.rend()); + + int res = 0, prev = 0; + for(int i = 0; i + 1 < data.size(); i ++){ + prev += data[i].second; + res += prev; + } + return res; + } +}; + + +int main() { + + vector nums1 = {5, 1, 3}; + cout << Solution().reductionOperations(nums1) << endl; + // 3 + + vector nums2 = {1, 1, 1}; + cout << Solution().reductionOperations(nums2) << endl; + // 0 + + vector nums3 = {1, 1, 2, 2, 3}; + cout << Solution().reductionOperations(nums3) << endl; + // 4 + + return 0; +} diff --git a/1501-2000/1888-Minimum-Number-of-Flips-to-Make-the-Binary-String-Alternating/cpp-1888/CMakeLists.txt b/1501-2000/1888-Minimum-Number-of-Flips-to-Make-the-Binary-String-Alternating/cpp-1888/CMakeLists.txt new file mode 100644 index 00000000..ad5a4184 --- /dev/null +++ b/1501-2000/1888-Minimum-Number-of-Flips-to-Make-the-Binary-String-Alternating/cpp-1888/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1501-2000/1888-Minimum-Number-of-Flips-to-Make-the-Binary-String-Alternating/cpp-1888/main.cpp b/1501-2000/1888-Minimum-Number-of-Flips-to-Make-the-Binary-String-Alternating/cpp-1888/main.cpp new file mode 100644 index 00000000..0be070cd --- /dev/null +++ b/1501-2000/1888-Minimum-Number-of-Flips-to-Make-the-Binary-String-Alternating/cpp-1888/main.cpp @@ -0,0 +1,81 @@ +/// Source : https://leetcode.com/problems/minimum-number-of-flips-to-make-the-binary-string-alternating/ +/// Author : liuyubobobo +/// Time : 2021-06-05 + +#include +#include + +using namespace std; + + +/// Presum +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int minFlips(string s) { + + int n = s.size(); + + vector zerof(n); + zerof[0] = (s[0] != '0'); + int t = 0; + for(int i = 1; i < n; i ++){ + t = 1 - t; + zerof[i] = zerof[i - 1] + (s[i] != '0' + t); + } +// for(int e: zerof) cout << e << " "; cout << endl; + + vector onef(n); + onef[0] = (s[0] != '1'); + t = 1; + for(int i = 1; i < n; i ++){ + t = 1 - t; + onef[i] = onef[i - 1] + (s[i] != '0' + t); + } +// for(int e: onef) cout << e << " "; cout << endl; + + vector zerob(n); + zerob[n - 1] = (s[n - 1] != '0'); + t = 0; + for(int i = n - 2; i >= 0; i --){ + t = 1 - t; + zerob[i] = zerob[i + 1] + (s[i] != '0' + t); + } +// for(int e: zerob) cout << e << " "; cout << endl; + + vector oneb(n); + oneb[n - 1] = (s[n - 1] != '1'); + t = 1; + for(int i = n - 2; i >= 0; i --){ + t = 1 - t; + oneb[i] = oneb[i + 1] + (s[i] != '0' + t); + } +// for(int e: oneb) cout << e << " "; cout << endl; + + int res = min(zerof[n - 1], onef[n - 1]); + for(int i = 1; i < n; i ++){ + res = min(res, zerob[i] + onef[i - 1]); + res = min(res, oneb[i] + zerof[i - 1]); + } + return res; + } +}; + + +int main() { + + cout << Solution().minFlips("111000") << endl; + // 2 + + cout << Solution().minFlips("010") << endl; + // 0 + + cout << Solution().minFlips("1110") << endl; + // 1 + + cout << Solution().minFlips("01001001101") << endl; + // 2 + + return 0; +} diff --git a/1501-2000/1889-Minimum-Space-Wasted-From-Packaging/cpp-1889/CMakeLists.txt b/1501-2000/1889-Minimum-Space-Wasted-From-Packaging/cpp-1889/CMakeLists.txt new file mode 100644 index 00000000..8e6ea4a2 --- /dev/null +++ b/1501-2000/1889-Minimum-Space-Wasted-From-Packaging/cpp-1889/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) \ No newline at end of file diff --git a/1501-2000/1889-Minimum-Space-Wasted-From-Packaging/cpp-1889/main.cpp b/1501-2000/1889-Minimum-Space-Wasted-From-Packaging/cpp-1889/main.cpp new file mode 100644 index 00000000..838deefe --- /dev/null +++ b/1501-2000/1889-Minimum-Space-Wasted-From-Packaging/cpp-1889/main.cpp @@ -0,0 +1,71 @@ +/// Source : https://leetcode.com/problems/minimum-space-wasted-from-packaging/ +/// Author : liuyubobobo +/// Time : 2021-06-05 + +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(nlogn + mlogm + mlogn) +/// Space Complexity: O(n) +class Solution { +public: + int minWastedSpace(vector& packages, vector>& boxes) { + + sort(packages.begin(), packages.end()); + + int n = packages.size(); + vector presum(n + 1, 0ll); + for(int i = 0; i < n; i ++) + presum[i + 1] = presum[i] + packages[i]; + + long long res = LONG_LONG_MAX; + for(vector& box: boxes){ + + sort(box.begin(), box.end()); + if(box.back() >= packages.back()) + res = min(res, solve(packages, presum, box)); + } + return res == LONG_LONG_MAX ? -1 : res % (long long)(1e9 + 7); + } + +private: + long long solve(const vector& packages, const vector& presum, + const vector& box){ + + int cur = 0; + long long res = 0ll; + for(int b: box){ + vector::const_iterator iter = upper_bound(packages.begin(), packages.end(), b); + int index = iter - packages.begin(); + int num = index - cur; + res += (long long)b * num - (presum[index] - presum[cur]); + cur = index; + } + return res; + } +}; + + +int main() { + + vector packages1 = {2, 3, 5}; + vector> boxes1 = {{4, 8}, {2, 8}}; + cout << Solution().minWastedSpace(packages1, boxes1) << endl; + // 6 + + vector packages2 = {2, 3, 5}; + vector> boxes2 = {{1, 4}, {2, 3}, {3, 4}}; + cout << Solution().minWastedSpace(packages2, boxes2) << endl; + // -1 + + vector packages3 = {3, 5, 8, 10, 11, 12}; + vector> boxes3 = {{12}, {11, 9}, {10, 5, 14}}; + cout << Solution().minWastedSpace(packages3, boxes3) << endl; + // 9 + + return 0; +} diff --git a/1501-2000/1891-Cutting-Ribbons/cpp-1891/CMakeLists.txt b/1501-2000/1891-Cutting-Ribbons/cpp-1891/CMakeLists.txt new file mode 100644 index 00000000..82345848 --- /dev/null +++ b/1501-2000/1891-Cutting-Ribbons/cpp-1891/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_1891) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1891 main.cpp) \ No newline at end of file diff --git a/1501-2000/1891-Cutting-Ribbons/cpp-1891/main.cpp b/1501-2000/1891-Cutting-Ribbons/cpp-1891/main.cpp new file mode 100644 index 00000000..54f25dc0 --- /dev/null +++ b/1501-2000/1891-Cutting-Ribbons/cpp-1891/main.cpp @@ -0,0 +1,43 @@ +/// Source : https://leetcode.com/problems/cutting-ribbons/ +/// Author : liuyubobobo +/// Time : 2021-06-10 + +#include +#include + +using namespace std; + + +/// binary Search +/// Time Complexity: O(nlog(max_ribbons)) +/// Space Complexity: O(1) +class Solution { +public: + int maxLength(vector& ribbons, int k) { + + int l = 0, r = *max_element(ribbons.begin(), ribbons.end()); + while(l < r){ + + int mid = (l + r + 1) / 2; + + if(ok(ribbons, mid, k)) l = mid; + else r = mid - 1; + } + return l; + } + +private: + bool ok(const vector& ribbons, int len, int k){ + + int cnt = 0; + for(int r: ribbons) + cnt += r / len; + return cnt >= k; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1893-Check-if-All-the-Integers-in-a-Range-Are-Covered/cpp-1893/CMakeLists.txt b/1501-2000/1893-Check-if-All-the-Integers-in-a-Range-Are-Covered/cpp-1893/CMakeLists.txt new file mode 100644 index 00000000..0cebaa4d --- /dev/null +++ b/1501-2000/1893-Check-if-All-the-Integers-in-a-Range-Are-Covered/cpp-1893/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_1893) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1893 main.cpp) \ No newline at end of file diff --git a/1501-2000/1893-Check-if-All-the-Integers-in-a-Range-Are-Covered/cpp-1893/main.cpp b/1501-2000/1893-Check-if-All-the-Integers-in-a-Range-Are-Covered/cpp-1893/main.cpp new file mode 100644 index 00000000..d44eb5ed --- /dev/null +++ b/1501-2000/1893-Check-if-All-the-Integers-in-a-Range-Are-Covered/cpp-1893/main.cpp @@ -0,0 +1,38 @@ +/// Source : https://leetcode.com/problems/check-if-all-the-integers-in-a-range-are-covered/ +/// Author : liuyubobobo +/// Time : 2021-06-12 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n * range) +/// Space Complexity: O(range) +class Solution { +public: + bool isCovered(vector>& ranges, int left, int right) { + + vector visited(right + 1, false); + for(const vector& r: ranges){ + for(int i = max(left, r[0]); i <= min(right, r[1]); i ++) + visited[i] = true; + } + + for(int i = left; i <= right; i ++) + if(!visited[i]) return false; + return true; + } +}; + + +int main() { + + vector> ranges1 = {{13,43},{19,20},{32,38},{26,33},{3,38},{16,31},{26,48},{27,43},{12,24}}; + cout << Solution().isCovered(ranges1, 36, 45) << endl; + // true + + return 0; +} diff --git a/1501-2000/1893-Check-if-All-the-Integers-in-a-Range-Are-Covered/cpp-1893/main2.cpp b/1501-2000/1893-Check-if-All-the-Integers-in-a-Range-Are-Covered/cpp-1893/main2.cpp new file mode 100644 index 00000000..a0cde22a --- /dev/null +++ b/1501-2000/1893-Check-if-All-the-Integers-in-a-Range-Are-Covered/cpp-1893/main2.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/check-if-all-the-integers-in-a-range-are-covered/ +/// Author : liuyubobobo +/// Time : 2021-06-12 + +#include +#include + +using namespace std; + + +/// Sorting +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + bool isCovered(vector>& ranges, int left, int right) { + + sort(ranges.begin(), ranges.end()); + for(const vector& r: ranges) + if(r[0] > left) return false; + else{ + left = max(left, r[1] + 1); + if(left > right) return true; + } + return false; + } +}; + + +int main() { + + vector> ranges1 = {{13,43},{19,20},{32,38},{26,33},{3,38},{16,31},{26,48},{27,43},{12,24}}; + cout << Solution().isCovered(ranges1, 36, 45) << endl; + // true + + return 0; +} diff --git a/1501-2000/1894-Find-the-Student-that-Will-Replace-the-Chalk/cpp-1894/CMakeLists.txt b/1501-2000/1894-Find-the-Student-that-Will-Replace-the-Chalk/cpp-1894/CMakeLists.txt new file mode 100644 index 00000000..569587ae --- /dev/null +++ b/1501-2000/1894-Find-the-Student-that-Will-Replace-the-Chalk/cpp-1894/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_1894) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1894 main.cpp) \ No newline at end of file diff --git a/1501-2000/1894-Find-the-Student-that-Will-Replace-the-Chalk/cpp-1894/main.cpp b/1501-2000/1894-Find-the-Student-that-Will-Replace-the-Chalk/cpp-1894/main.cpp new file mode 100644 index 00000000..62304207 --- /dev/null +++ b/1501-2000/1894-Find-the-Student-that-Will-Replace-the-Chalk/cpp-1894/main.cpp @@ -0,0 +1,36 @@ +/// Source : https://leetcode.com/problems/find-the-student-that-will-replace-the-chalk/ +/// Author : liuyubobobo +/// Time : 2021-06-12 + +#include +#include + +using namespace std; + + +/// Presum + Binary Search +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int chalkReplacer(vector& chalk, int k) { + + int n = chalk.size(); + vector presum(n + 1, 0ll); + for(int i = 0; i < n; i ++) + presum[i + 1] = presum[i] + chalk[i]; + + k %= presum.back(); + return upper_bound(presum.begin() + 1, presum.end(), k) - presum.begin() - 1; + } +}; + + +int main() { + + vector chalk1 = {3, 4, 1, 2}; + cout << Solution().chalkReplacer(chalk1, 25) << endl; + // 1 + + return 0; +} diff --git a/1501-2000/1895-Largest-Magic-Square/cpp-1895/CMakeLists.txt b/1501-2000/1895-Largest-Magic-Square/cpp-1895/CMakeLists.txt new file mode 100644 index 00000000..276c728f --- /dev/null +++ b/1501-2000/1895-Largest-Magic-Square/cpp-1895/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_1895) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1895 main.cpp) \ No newline at end of file diff --git a/1501-2000/1895-Largest-Magic-Square/cpp-1895/main.cpp b/1501-2000/1895-Largest-Magic-Square/cpp-1895/main.cpp new file mode 100644 index 00000000..05ed0ad8 --- /dev/null +++ b/1501-2000/1895-Largest-Magic-Square/cpp-1895/main.cpp @@ -0,0 +1,69 @@ +/// Source : https://leetcode.com/problems/largest-magic-square/ +/// Author : liuyubobobo +/// Time : 2021-06-12 + +#include +#include + +using namespace std; + + +/// Presum + Brute Force +/// Time Complexity: O(m * n * min(m, n)) +/// Space Complexity: O(m * n) +class Solution { +public: + int largestMagicSquare(vector>& grid) { + + int m = grid.size(), n = grid[0].size(); + + vector> presum_row(m + 2, vector(n + 2, 0)); + vector> presum_col(m + 2, vector(n + 2, 0)); + vector> presum_dia1(m + 2, vector(n + 2, 0)); + vector> presum_dia2(m + 2, vector(n + 2, 0)); + for(int i = 0; i < m; i ++) + for(int j = 0; j < n; j ++){ + presum_row[i + 1][j + 1] = presum_row[i + 1][j] + grid[i][j]; + presum_col[i + 1][j + 1] = presum_col[i][j + 1] + grid[i][j]; + presum_dia1[i + 1][j + 1] = presum_dia1[i][j] + grid[i][j]; + presum_dia2[i + 1][j + 1] = presum_dia2[i][j + 2] + grid[i][j]; + } + + for(int k = max(m, n); k >= 2; k --) + for(int i = 0; i < m && i + k <= m; i ++) + for(int j = 0; j < n && j + k <= n; j ++){ + if(ok(grid, i, j, k, presum_row, presum_col, presum_dia1, presum_dia2)) + return k; + } + return 1; + } + +private: + bool ok(const vector>& grid, int x, int y, int sz, + const vector>& presum_row, const vector>& presum_col, + const vector>& presum_dia1, const vector>& presum_dia2){ + + int sum = presum_row[x + 1][y + sz] - presum_row[x + 1][y]; + for(int i = x; i < x + sz; i ++) + if(presum_row[i + 1][y + sz] - presum_row[i + 1][y] != sum) + return false; + + for(int j = y; j < y + sz; j ++) + if(presum_col[x + sz][j + 1] - presum_col[x][j + 1] != sum) + return false; + + if(presum_dia1[x + sz][y + sz] - presum_dia1[x][y] != sum) + return false; + + if(presum_dia2[x + sz][y + 1] - presum_dia2[x][y + sz + 1] != sum) + return false; + + return true; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1896-Minimum-Cost-to-Change-the-Final-Value-of-Expression/cpp-1896/CMakeLists.txt b/1501-2000/1896-Minimum-Cost-to-Change-the-Final-Value-of-Expression/cpp-1896/CMakeLists.txt new file mode 100644 index 00000000..ac840fc0 --- /dev/null +++ b/1501-2000/1896-Minimum-Cost-to-Change-the-Final-Value-of-Expression/cpp-1896/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_1896) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1896 main.cpp) \ No newline at end of file diff --git a/1501-2000/1896-Minimum-Cost-to-Change-the-Final-Value-of-Expression/cpp-1896/main.cpp b/1501-2000/1896-Minimum-Cost-to-Change-the-Final-Value-of-Expression/cpp-1896/main.cpp new file mode 100644 index 00000000..7017f166 --- /dev/null +++ b/1501-2000/1896-Minimum-Cost-to-Change-the-Final-Value-of-Expression/cpp-1896/main.cpp @@ -0,0 +1,141 @@ +/// Source : https://leetcode.com/problems/minimum-cost-to-change-the-final-value-of-expression/ +/// Author : liuyubobobo +/// Time : 2021-06-12 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// Build Expression Tree + Memory Search +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +private: + class Node{ + public: + char op; + int val; + Node *left, *right; + + Node(char op, int val, Node* left, Node* right) : op(op), val(val), left(left), right(right){} + Node(char op, int val) : Node(op, val, nullptr, nullptr){} + Node(char op) : Node(op, -1, nullptr, nullptr){} + }; + +public: + int minOperationsToFlip(string expression) { + + int n = expression.size(); + stack stack; + vector match(n, -1); + for(int i = 0; i < n; i ++) + if(expression[i] == '(') + stack.push(i); + else if(expression[i] == ')'){ + assert(!stack.empty()); + match[i] = stack.top(); + match[stack.top()] = i; + stack.pop(); + } + assert(stack.empty()); + + Node* root = build(expression, 0, n - 1, match); + + vector> dp(2); + return dfs(root, 1 - root->val, dp); + } + +private: + int dfs(Node* node, int changeto, vector>& dp){ + + if(node->op == 'v') return node->val != changeto; + if(dp[changeto].count(node)) return dp[changeto][node]; + + if(node->val == changeto) return 0; + + int res = INT_MAX; + if(changeto == 0){ + // 0 | 0 + res = min(res, (node->op != '|') + dfs(node->left, 0, dp) + dfs(node->right, 0, dp)); + + // 0 & 0 + res = min(res, (node->op != '&') + dfs(node->left, 0, dp) + dfs(node->right, 0, dp)); + + // 0 & 1 + res = min(res, (node->op != '&') + dfs(node->left, 0, dp) + dfs(node->right, 1, dp)); + + // 1 & 0 + res = min(res, (node->op != '&') + dfs(node->left, 1, dp) + dfs(node->right, 0, dp)); + } + else{ // changeto == 1 + // 0 | 1 + res = min(res, (node->op != '|') + dfs(node->left, 0, dp) + dfs(node->right, 1, dp)); + + // 1 | 0 + res = min(res, (node->op != '|') + dfs(node->left, 1, dp) + dfs(node->right, 0, dp)); + + // 1 | 1 + res = min(res, (node->op != '|') + dfs(node->left, 1, dp) + dfs(node->right, 1, dp)); + + // 1 & 1 + res = min(res, (node->op != '&') + dfs(node->left, 1, dp) + dfs(node->right, 1, dp)); + } + return dp[changeto][node] = res; + } + + Node* build(const string& exp, int l, int r, const vector& match){ + + if(l == r){ +// assert(isdigit(exp[l])); + return new Node('v', exp[l] - '0'); + } + + if(exp[r] == ')'){ + if(match[r] == l) return build(exp, l + 1, r - 1, match); + + Node* right = build(exp, match[r], r, match); +// assert(exp[match[r] - 1] == '|' || exp[match[r] - 1] == '&'); +// assert(l <= exp[match[r] - 2]); + Node* left = build(exp, l, match[r] - 2, match); + return new Node(exp[match[r] - 1], + exp[match[r] - 1] == '|' ? (left->val | right->val) : (left->val & right->val), + left, right); + } + +// assert(isdigit(exp[r])); +// assert(exp[r - 1] == '&' || exp[r - 1] == '|'); +// assert(l <= r - 2); + Node* right = new Node('v', exp[r] - '0'); + Node* left = build(exp, l, r - 2, match); + return new Node(exp[r - 1], + exp[r - 1] == '|' ? (left->val | right->val) : (left->val & right->val), + left, right); + } +}; + + +int main() { + + cout << Solution().minOperationsToFlip("1&(0|1)") << endl; + // 1 + + cout << Solution().minOperationsToFlip("(0&0)&(0&0&0)") << endl; + // 3 + + cout << Solution().minOperationsToFlip("(0|(1|0&1))") << endl; + // 1 + + cout << Solution().minOperationsToFlip("1|1|(0&0)&1") << endl; + // 1 + + cout << Solution().minOperationsToFlip("1&0|(0&0)&0|0&(1&(1))") << endl; + // 1 + + return 0; +} diff --git a/1501-2000/1897-Redistribute-Characters-to-Make-All-Strings-Equal/cpp-1897/CMakeLists.txt b/1501-2000/1897-Redistribute-Characters-to-Make-All-Strings-Equal/cpp-1897/CMakeLists.txt new file mode 100644 index 00000000..56912ed2 --- /dev/null +++ b/1501-2000/1897-Redistribute-Characters-to-Make-All-Strings-Equal/cpp-1897/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1501-2000/1897-Redistribute-Characters-to-Make-All-Strings-Equal/cpp-1897/main.cpp b/1501-2000/1897-Redistribute-Characters-to-Make-All-Strings-Equal/cpp-1897/main.cpp new file mode 100644 index 00000000..388e58fd --- /dev/null +++ b/1501-2000/1897-Redistribute-Characters-to-Make-All-Strings-Equal/cpp-1897/main.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/redistribute-characters-to-make-all-strings-equal/ +/// Author : liuyubobobo +/// Time : 2021-06-12 + +#include +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(nums_of_characters) +/// Space Complexity: O(1) +class Solution { +public: + bool makeEqual(vector& words) { + + vector f(26, 0); + for(const string& word: words) + for(char c: word) + f[c - 'a'] ++; + + int n = words.size(); + for(int e: f) + if(e % n) return false; + return true; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1898-Maximum-Number-of-Removable-Characters/cpp-1898/CMakeLists.txt b/1501-2000/1898-Maximum-Number-of-Removable-Characters/cpp-1898/CMakeLists.txt new file mode 100644 index 00000000..358dfef4 --- /dev/null +++ b/1501-2000/1898-Maximum-Number-of-Removable-Characters/cpp-1898/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1501-2000/1898-Maximum-Number-of-Removable-Characters/cpp-1898/main.cpp b/1501-2000/1898-Maximum-Number-of-Removable-Characters/cpp-1898/main.cpp new file mode 100644 index 00000000..db976b47 --- /dev/null +++ b/1501-2000/1898-Maximum-Number-of-Removable-Characters/cpp-1898/main.cpp @@ -0,0 +1,56 @@ +/// Source : https://leetcode.com/problems/maximum-number-of-removable-characters/ +/// Author : liuyubobobo +/// Time : 2021-06-12 + +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(|s| * log|removable|) +/// Space Complexity: O(|s|) +class Solution { +public: + int maximumRemovals(string s, string p, vector& removable) { + + int l = 0, r = removable.size(); + while(l < r){ + int mid = (l + r + 1) / 2; + if(ok(s, p, removable, mid)) l = mid; + else r = mid - 1; + } + return l; + } + +private: + bool ok(string s, const string& p, const vector& removable, int k){ + + for(int i = 0; i < k; i ++) + s[removable[i]] = ' '; + + int j = 0; + for(int i = 0; i < s.size() && j < p.size(); i ++) + if(s[i] == p[j]) j ++; + return j == p.size(); + } +}; + + +int main() { + + vector removable1 = {3, 1, 0}; + cout << Solution().maximumRemovals("abcacb", "ab", removable1) << endl; + // 2 + + vector removable2 = {3, 2, 1, 4, 5, 6}; + cout << Solution().maximumRemovals("abcbddddd", "abcd", removable2) << endl; + // 1 + + vector removable3 = {0, 1, 2, 3, 4}; + cout << Solution().maximumRemovals("abcab", "abc", removable3) << endl; + // 0 + + return 0; +} diff --git a/1501-2000/1899-Merge-Triplets-to-Form-Target-Triplet/cpp-1899/CMakeLists.txt b/1501-2000/1899-Merge-Triplets-to-Form-Target-Triplet/cpp-1899/CMakeLists.txt new file mode 100644 index 00000000..ad5a4184 --- /dev/null +++ b/1501-2000/1899-Merge-Triplets-to-Form-Target-Triplet/cpp-1899/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1501-2000/1899-Merge-Triplets-to-Form-Target-Triplet/cpp-1899/main.cpp b/1501-2000/1899-Merge-Triplets-to-Form-Target-Triplet/cpp-1899/main.cpp new file mode 100644 index 00000000..2e1104bc --- /dev/null +++ b/1501-2000/1899-Merge-Triplets-to-Form-Target-Triplet/cpp-1899/main.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/merge-triplets-to-form-target-triplet/ +/// Author : liuyubobobo +/// Time : 2021-06-12 + +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + bool mergeTriplets(vector>& triplets, vector& target) { + + vector res(3, 0); + for(const vector& e: triplets) + if(e[0] <= target[0] && e[1] <= target[1] && e[2] <= target[2]) + res[0] = max(res[0], e[0]), res[1] = max(res[1], e[1]), res[2] = max(res[2], e[2]); + return res == target; + } +}; + + +int main() { + + vector> triplets1 = {{2, 5, 3}, {1, 8, 4}, {1, 7, 5}}; + vector target1 = {2, 7, 5}; + cout << Solution().mergeTriplets(triplets1, target1) << endl; + // 1 + + vector> triplets2 = {{1, 3, 4}, {2, 5, 8}}; + vector target2 = {2, 5, 8}; + cout << Solution().mergeTriplets(triplets2, target2) << endl; + // 1 + + vector> triplets3 = {{2, 5, 3}, {2, 3, 4}, {1, 2, 5}, {5, 2, 3}}; + vector target3 = {5, 5, 5}; + cout << Solution().mergeTriplets(triplets3, target3) << endl; + // 1 + + vector> triplets4 = {{3, 4, 5}, {4, 5, 6}}; + vector target4 = {3, 2, 5}; + cout << Solution().mergeTriplets(triplets4, target4) << endl; + // 0 + + return 0; +} diff --git a/1501-2000/1900-The-Earliest-and-Latest-Rounds-Where-Players-Compete/cpp-1900/CMakeLists.txt b/1501-2000/1900-The-Earliest-and-Latest-Rounds-Where-Players-Compete/cpp-1900/CMakeLists.txt new file mode 100644 index 00000000..8700daa5 --- /dev/null +++ b/1501-2000/1900-The-Earliest-and-Latest-Rounds-Where-Players-Compete/cpp-1900/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main2.cpp) \ No newline at end of file diff --git a/1501-2000/1900-The-Earliest-and-Latest-Rounds-Where-Players-Compete/cpp-1900/main.cpp b/1501-2000/1900-The-Earliest-and-Latest-Rounds-Where-Players-Compete/cpp-1900/main.cpp new file mode 100644 index 00000000..f5fc058a --- /dev/null +++ b/1501-2000/1900-The-Earliest-and-Latest-Rounds-Where-Players-Compete/cpp-1900/main.cpp @@ -0,0 +1,123 @@ +/// Source : https://leetcode.com/problems/the-earliest-and-latest-rounds-where-players-compete/ +/// Author : liuyubobobo +/// Time : 2021-06-12 + +#include +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(n^3*2^n) +/// Space Complexity: O(n^3*2^n) +class Solution { + +public: + vector earliestAndLatest(int n, int firstPlayer, int secondPlayer) { + + vector>> dp1(n + 1, vector>(n + 1, vector(n + 1, -1))); + int minv = dfs(firstPlayer - 1, secondPlayer - firstPlayer - 1, n - secondPlayer, dp1, "min"); + + vector>> dp2(n + 1, vector>(n + 1, vector(n + 1, -1))); + int maxv = dfs(firstPlayer - 1, secondPlayer - firstPlayer - 1, n - secondPlayer, dp2, "max"); + + return {minv + 1, maxv + 1}; + } + +private: + int dfs(int pre1, int pre2, int post, vector>>& dp, const string& op){ + + if(dp[pre1][pre2][post] != -1) return dp[pre1][pre2][post]; + + int n = pre1 + 1 + pre2 + 1 + post; + int player1 = pre1; + int player2 = pre1 + 1 + pre2; + + set> result_set; + vector result(n, false); + if(n % 2 == 1) result[n / 2] = true; + bool ok = play(0, player1, player2, result, result_set); + + if(ok) return dp[pre1][pre2][post] = 0; + + int res = (op == "min") ? INT_MAX : INT_MIN; + for(const vector& state: result_set) + if(op == "min") + res = min(res, 1 + dfs(state[0], state[1], state[2], dp, op)); + else + res = max(res, 1 + dfs(state[0], state[1], state[2], dp, op)); + + return dp[pre1][pre2][post] = res; + } + + bool play(int index, int player1, int player2, + vector& result, set>& result_set){ + + if(index >= (result.size() / 2)){ + int a = 0, b = 0, c = 0; + for(int i = 0; i < result.size(); i ++) + if(result[i]){ + if(i < player1) a ++; + else if(i > player1 && i < player2) b ++; + else if(i > player2) c ++; + } + result_set.insert({a, b, c}); +// if(a + b + c + 2 != (result.size() + 1) / 2){ +// cout << "player1 : " << player1 << " palyer2 : " << player2 << endl; +// for(int e: result) cout << e << " "; cout << endl; +// cout << a << " " << b << " " << c << endl; +// assert(false); +// } + return false; + } + + int x = index, y = result.size() - 1 - index; + if(x == player1 && y == player2) return true; + + if(x == player1 || x == player2){ + result[x] = true; + result[y] = false; + if(play(index + 1, player1, player2, result, result_set)) + return true; + return false; + } + + if(y == player1 || y == player2){ + result[x] = false; + result[y] = true; + if(play(index + 1, player1, player2, result, result_set)) + return true; + return false; + } + + result[x] = true; + result[y] = false; + if(play( index + 1, player1, player2, result, result_set)) + return true; + + result[x] = false; + result[y] = true; + if(play( index + 1, player1, player2, result, result_set)) + return true; + + return false; + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << " "; cout << endl; +} + +int main() { + + print_vec(Solution().earliestAndLatest(11, 2, 4)); + // {3, 4} + + print_vec(Solution().earliestAndLatest(5, 1, 5)); + // {1, 1} + + return 0; +} diff --git a/1501-2000/1900-The-Earliest-and-Latest-Rounds-Where-Players-Compete/cpp-1900/main2.cpp b/1501-2000/1900-The-Earliest-and-Latest-Rounds-Where-Players-Compete/cpp-1900/main2.cpp new file mode 100644 index 00000000..daba4921 --- /dev/null +++ b/1501-2000/1900-The-Earliest-and-Latest-Rounds-Where-Players-Compete/cpp-1900/main2.cpp @@ -0,0 +1,73 @@ +/// Source : https://leetcode.com/problems/the-earliest-and-latest-rounds-where-players-compete/ +/// Author : liuyubobobo +/// Time : 2021-06-12 + +#include +#include +#include + +using namespace std; + + +/// Monte Carlo +/// Time Complexity: O(T*nlogn) +/// Space Complexity: O(n) +class Solution { + +public: + vector earliestAndLatest(int n, int firstPlayer, int secondPlayer) { + + srand(time(NULL)); + + int N = 3000, minv = INT_MAX, maxv = INT_MIN; + while(N --){ + int res = play(n, firstPlayer - 1, secondPlayer - 1); + minv = min(minv, res); + maxv = max(maxv, res); + } + + return {minv, maxv}; + } + +private: + int play(int n, int player1, int player2){ + + vector players(n); + for(int i = 0; i < n; i ++) + players[i] = i; + + for(int t = 1;;t ++){ + vector temp; + for(int i = 0; i <= (players.size() - 1) / 2; i ++){ + int x = players[i], y = players[players.size() - 1 - i]; + if(x == player1 && y == player2) return t; + + if(x == player1 || x == player2) + temp.push_back(x); + else if(y == player1 || y == player2) + temp.push_back(y); + else + temp.push_back(rand() % 2 ? x : y); + } + sort(temp.begin(), temp.end()); + players = temp; + } + return -1; + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << " "; cout << endl; +} + +int main() { + + print_vec(Solution().earliestAndLatest(11, 2, 4)); + // {3, 4} + + print_vec(Solution().earliestAndLatest(5, 1, 5)); + // {1, 1} + + return 0; +} diff --git a/1501-2000/1901-Find-a-Peak-Element-II/cpp-1901/CMakeLists.txt b/1501-2000/1901-Find-a-Peak-Element-II/cpp-1901/CMakeLists.txt new file mode 100644 index 00000000..ab01d1a0 --- /dev/null +++ b/1501-2000/1901-Find-a-Peak-Element-II/cpp-1901/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_1901) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1901 main.cpp) \ No newline at end of file diff --git a/1501-2000/1901-Find-a-Peak-Element-II/cpp-1901/main.cpp b/1501-2000/1901-Find-a-Peak-Element-II/cpp-1901/main.cpp new file mode 100644 index 00000000..82fed405 --- /dev/null +++ b/1501-2000/1901-Find-a-Peak-Element-II/cpp-1901/main.cpp @@ -0,0 +1,45 @@ +/// Source : https://leetcode.com/problems/find-a-peak-element-ii/ +/// Author : liuyubobobo +/// Time : 2021-06-15 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(m*n) +/// Space Complexity: O(1) +class Solution { + +private: + const int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + int m, n; + +public: + vector findPeakGrid(vector>& mat) { + + m = mat.size(), n = mat[0].size(); + for(int i = 0; i < m; i ++) + for(int j = 0; j < n; j ++){ + int d = 0; + for(; d < 4; d ++) + if(in_area(i + dirs[d][0], j + dirs[d][1]) && mat[i + dirs[d][0]][j + dirs[d][1]] >= mat[i][j]) + break; + if(d == 4) return {i, j}; + } + return {-1, -1}; + } + +private: + bool in_area(int x, int y){ + return x >= 0 && x < m && y >= 0 && y < n; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1902-Depth-of-BST-Given-Insertion-Order/cpp-1902/CMakeLists.txt b/1501-2000/1902-Depth-of-BST-Given-Insertion-Order/cpp-1902/CMakeLists.txt new file mode 100644 index 00000000..778a1a50 --- /dev/null +++ b/1501-2000/1902-Depth-of-BST-Given-Insertion-Order/cpp-1902/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_1902) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1902 main.cpp) \ No newline at end of file diff --git a/1501-2000/1902-Depth-of-BST-Given-Insertion-Order/cpp-1902/main.cpp b/1501-2000/1902-Depth-of-BST-Given-Insertion-Order/cpp-1902/main.cpp new file mode 100644 index 00000000..33dddd8a --- /dev/null +++ b/1501-2000/1902-Depth-of-BST-Given-Insertion-Order/cpp-1902/main.cpp @@ -0,0 +1,51 @@ +/// Source : https://leetcode.com/problems/depth-of-bst-given-insertion-order/ +/// Author : liuyubobobo +/// Time : 2021-06-18 + +#include +#include +#include + +using namespace std; + + +/// Using TreeMap +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + int maxDepthBST(vector& order) { + + map tree; // e -> depth + int res = 1; + tree[order[0]] = 1; + + for(int i = 1; i < order.size(); i ++){ + int d = 1; + + map::iterator iter = tree.lower_bound(order[i]); + if(iter != tree.end()) { + d = max(d, iter->second + 1); + } + + if(iter != tree.begin()){ + iter --; + d = max(d, iter->second + 1); + } + + tree[order[i]] = d; + res = max(res, d); + } + return res; + } +}; + + +int main() { + + vector order1 = {2, 1, 4, 3}; + cout << Solution().maxDepthBST(order1) << endl; + // 3 + + return 0; +} diff --git a/1501-2000/1903-Largest-Odd-Number-in-String/cpp-1903/CMakeLists.txt b/1501-2000/1903-Largest-Odd-Number-in-String/cpp-1903/CMakeLists.txt new file mode 100644 index 00000000..56912ed2 --- /dev/null +++ b/1501-2000/1903-Largest-Odd-Number-in-String/cpp-1903/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1501-2000/1903-Largest-Odd-Number-in-String/cpp-1903/main.cpp b/1501-2000/1903-Largest-Odd-Number-in-String/cpp-1903/main.cpp new file mode 100644 index 00000000..f3b8d764 --- /dev/null +++ b/1501-2000/1903-Largest-Odd-Number-in-String/cpp-1903/main.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/largest-odd-number-in-string/ +/// Author : liuyubobobo +/// Time : 2021-06-20 + +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + string largestOddNumber(string num) { + + int i; + for(i = num.size() - 1; i >= 0; i --) + if((num[i] - '0') % 2) + break; + + return num.substr(0, i + 1); + } +}; + + +int main() { + + cout << Solution().largestOddNumber("52") << endl; + // 5 + + cout << Solution().largestOddNumber("4206") << endl; + // "" + + cout << Solution().largestOddNumber("35427") << endl; + // 35427 + + return 0; +} diff --git a/1501-2000/1904-The-Number-of-Full-Rounds-You-Have-Played/cpp-1904/CMakeLists.txt b/1501-2000/1904-The-Number-of-Full-Rounds-You-Have-Played/cpp-1904/CMakeLists.txt new file mode 100644 index 00000000..b875daa2 --- /dev/null +++ b/1501-2000/1904-The-Number-of-Full-Rounds-You-Have-Played/cpp-1904/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main2.cpp) \ No newline at end of file diff --git a/1501-2000/1904-The-Number-of-Full-Rounds-You-Have-Played/cpp-1904/main.cpp b/1501-2000/1904-The-Number-of-Full-Rounds-You-Have-Played/cpp-1904/main.cpp new file mode 100644 index 00000000..a2a8a34d --- /dev/null +++ b/1501-2000/1904-The-Number-of-Full-Rounds-You-Have-Played/cpp-1904/main.cpp @@ -0,0 +1,73 @@ +/// Source : https://leetcode.com/problems/the-number-of-full-rounds-you-have-played/ +/// Author : liuyubobobo +/// Time : 2021-06-19 +/// Updated: 2021-06-23 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(1) +/// Space Complexity: O(1) +class Solution { +public: + int numberOfRounds(string startTime, string finishTime) { + + int h1, m1, h2, m2; + get_time(startTime, h1, m1); + get_time(finishTime, h2, m2); + + if(startTime > finishTime) h2 += 24; + + if(m1 > 0 && m1 < 15) m1 = 15; + else if(m1 > 15 && m1 < 30) m1 = 30; + else if(m1 > 30 && m1 < 45) m1 = 45; + else if(m1 > 45){h1 += 1, m1 = 0;} + + if(m2 > 0 && m2 < 15) m2 = 0; + else if(m2 > 15 && m2 < 30) m2 = 15; + else if(m2 > 30 && m2 < 45) m2 = 30; + else if(m2 > 45) m2 = 45; + + int res = 0; + pair p2 = {h2, m2}; + while(true){ + pair p1 = {h1, m1}; + if(p1 > p2) break; + + res ++; + + m1 += 15; + if(m1 == 60) h1 ++, m1 = 0; + } + return max(res - 1, 0); + } + +private: + void get_time(const string& s, int& h, int& m){ + + h = atoi(s.substr(0, 2).c_str()); + m = atoi(s.substr(3).c_str()); + } +}; + + +int main() { + + cout << Solution().numberOfRounds("12:01", "12:44") << endl; + // 1 + + cout << Solution().numberOfRounds("20:00", "06:00") << endl; + // 40 + + cout << Solution().numberOfRounds("00:00", "23:59") << endl; + // 95 + + cout << Solution().numberOfRounds("23:95", "00:00") << endl; + // 0 + + return 0; +} diff --git a/1501-2000/1904-The-Number-of-Full-Rounds-You-Have-Played/cpp-1904/main2.cpp b/1501-2000/1904-The-Number-of-Full-Rounds-You-Have-Played/cpp-1904/main2.cpp new file mode 100644 index 00000000..810ff3ac --- /dev/null +++ b/1501-2000/1904-The-Number-of-Full-Rounds-You-Have-Played/cpp-1904/main2.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/the-number-of-full-rounds-you-have-played/ +/// Author : liuyubobobo +/// Time : 2021-06-20 +/// Updated: 2021-06-23 + +#include +#include + +using namespace std; + + +/// Mathematics +/// Time Complexity: O(1) +/// Space Complexity: O(1) +class Solution { +public: + int numberOfRounds(string startTime, string finishTime) { + + int h1, m1, h2, m2; + get_time(startTime, h1, m1); + get_time(finishTime, h2, m2); + + if(startTime > finishTime) h2 += 24; + + int a = h1 * 4 + m1 / 15 + !!(m1 % 15); + int b = h2 * 4 + m2 / 15; + return max(b - a, 0); + } + +private: + void get_time(const string& s, int& h, int& m){ + + h = atoi(s.substr(0, 2).c_str()); + m = atoi(s.substr(3).c_str()); + } +}; + + +int main() { + + cout << Solution().numberOfRounds("12:01", "12:44") << endl; + // 1 + + cout << Solution().numberOfRounds("20:00", "06:00") << endl; + // 40 + + cout << Solution().numberOfRounds("00:00", "23:59") << endl; + // 95 + + cout << Solution().numberOfRounds("23:55", "00:00") << endl; + // 0 + + cout << Solution().numberOfRounds("00:47", "00:57") << endl; + // 0 + + return 0; +} diff --git a/1501-2000/1905-Count-Sub-Islands/cpp-1905/CMakeLists.txt b/1501-2000/1905-Count-Sub-Islands/cpp-1905/CMakeLists.txt new file mode 100644 index 00000000..53575fde --- /dev/null +++ b/1501-2000/1905-Count-Sub-Islands/cpp-1905/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main2.cpp) \ No newline at end of file diff --git a/1501-2000/1905-Count-Sub-Islands/cpp-1905/main.cpp b/1501-2000/1905-Count-Sub-Islands/cpp-1905/main.cpp new file mode 100644 index 00000000..a4b9bdd9 --- /dev/null +++ b/1501-2000/1905-Count-Sub-Islands/cpp-1905/main.cpp @@ -0,0 +1,106 @@ +/// Source : https://leetcode.com/problems/count-sub-islands/ +/// Author : liuyubobobo +/// Time : 2021-06-19 + +#include +#include +#include + +using namespace std; + + +/// DFS and set compare +/// Time Complexity: O((R * C)^2) +/// Space Complexity: O(R * C) +class Solution { + +private: + int R, C; + const int dirs[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; + +public: + int countSubIslands(vector>& grid1, vector>& grid2) { + + R = grid1.size(), C = grid1[0].size(); + + vector> cc1(R, vector(C, -1)); + vector> islands1; + get_island(grid1, cc1, islands1); + + vector> cc2(R, vector(C, -1)); + vector> islands2; + get_island(grid2, cc2, islands2); + + int res = 0; + unordered_set visited; + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++){ + if(grid2[i][j] == 0 || grid1[i][j] == 0) continue; + + int cc_index = cc2[i][j]; + if(visited.count(cc_index)) continue; + + if(contains(islands1[cc1[i][j]], islands2[cc_index])){ + res ++; +// cout << "check " << i << " " << j << endl; + } + visited.insert(cc_index); + } + return res; + } + +private: + bool contains(const unordered_set& S, const unordered_set& s){ + + for(int e: s) + if(!S.count(e)) return false; + return true; + } + + void get_island(const vector>& g, + vector>& cc, vector>& islands){ + + int cc_index = 0; + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++) + if(cc[i][j] == -1 && g[i][j] == 1){ + dfs(g, i, j, cc, cc_index ++); + islands.push_back(unordered_set()); + } + + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++) + if(cc[i][j] != -1) + islands[cc[i][j]].insert(i * C + j); + } + + void dfs(const vector>& g, int x, int y, + vector>& cc, int cc_index){ + + cc[x][y] = cc_index; + + for(int d = 0; d < 4; d ++){ + int nx = x + dirs[d][0], ny = y + dirs[d][1]; + if(in_area(nx, ny) && g[nx][ny] == 1 && cc[nx][ny] == -1) + dfs(g, nx, ny, cc, cc_index); + } + } + + bool in_area(int x, int y){ + return x >= 0 && x < R && y >= 0 && y < C; + } +}; + +int main() { + + vector> g11 = { + {1,1,1,0,0},{0,1,1,1,1},{0,0,0,0,0},{1,0,0,0,0},{1,1,0,1,1} + }; + vector> g12 = { + {1,1,1,0,0},{0,0,1,1,1},{0,1,0,0,0},{1,0,1,1,0},{0,1,0,1,0} + }; + cout << Solution().countSubIslands(g11, g12) << endl; + // 3 + + return 0; +} diff --git a/1501-2000/1905-Count-Sub-Islands/cpp-1905/main2.cpp b/1501-2000/1905-Count-Sub-Islands/cpp-1905/main2.cpp new file mode 100644 index 00000000..af7cdfd9 --- /dev/null +++ b/1501-2000/1905-Count-Sub-Islands/cpp-1905/main2.cpp @@ -0,0 +1,85 @@ +/// Source : https://leetcode.com/problems/count-sub-islands/ +/// Author : liuyubobobo +/// Time : 2021-06-20 + +#include +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(R * C) +/// Space Complexity: O(R * C) +class Solution { + +private: + int R, C; + const int dirs[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; + +public: + int countSubIslands(vector>& grid1, vector>& grid2) { + + R = grid1.size(), C = grid1[0].size(); + + vector> visited(R, vector(C, false)); + int res = 0; + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++) + if(grid2[i][j] && !visited[i][j]){ + bool ok = true; + dfs(grid2, i, j, visited, ok, grid1); + res += ok; + } + return res; + } + +private: + void dfs(const vector>& g, int x, int y, + vector>& visited, bool& ok, + const vector>& g2){ + + visited[x][y] = true; + + if(g2[x][y] == 0) ok = false; + + for(int d = 0; d < 4; d ++){ + int nx = x + dirs[d][0], ny = y + dirs[d][1]; + if(in_area(nx, ny) && g[nx][ny] == 1 && !visited[nx][ny]) + dfs(g, nx, ny, visited, ok, g2); + } + } + + bool in_area(int x, int y){ + return x >= 0 && x < R && y >= 0 && y < C; + } +}; + + +int main() { + + vector> g11 = { + {1,1,1,0,0},{0,1,1,1,1},{0,0,0,0,0},{1,0,0,0,0},{1,1,0,1,1} + }; + vector> g12 = { + {1,1,1,0,0},{0,0,1,1,1},{0,1,0,0,0},{1,0,1,1,0},{0,1,0,1,0} + }; + cout << Solution().countSubIslands(g11, g12) << endl; + // 3 + + vector> g21 = { + {1,0,1,0,1}, + {1,1,1,1,1}, + {0,0,0,0,0}, + {1,1,1,1,1}, + {1,0,1,0,1} + }; + vector> g22 = { + {0,0,0,0,0},{1,1,1,1,1},{0,1,0,1,0}, {0,1,0,1,0},{1,0,0,0,1} + }; + cout << Solution().countSubIslands(g21, g22) << endl; + // 2 + + return 0; +} diff --git a/1501-2000/1906-Minimum-Absolute-Difference-Queries/cpp-1906/CMakeLists.txt b/1501-2000/1906-Minimum-Absolute-Difference-Queries/cpp-1906/CMakeLists.txt new file mode 100644 index 00000000..8e6ea4a2 --- /dev/null +++ b/1501-2000/1906-Minimum-Absolute-Difference-Queries/cpp-1906/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) \ No newline at end of file diff --git a/1501-2000/1906-Minimum-Absolute-Difference-Queries/cpp-1906/main.cpp b/1501-2000/1906-Minimum-Absolute-Difference-Queries/cpp-1906/main.cpp new file mode 100644 index 00000000..b2b360a1 --- /dev/null +++ b/1501-2000/1906-Minimum-Absolute-Difference-Queries/cpp-1906/main.cpp @@ -0,0 +1,62 @@ +/// Source : https://leetcode.com/problems/minimum-absolute-difference-queries/ +/// Author : liuyubobobo +/// Time : 2021-06-19 + +#include +#include + +using namespace std; + + +/// Presum +/// Time Complexity: O(max(nums) * (n + q)) +/// Space Complexity: O(max(nums) * n) +class Solution { +public: + vector minDifference(vector& nums, vector>& queries) { + + int n = nums.size(); + + int maxv = *max_element(nums.begin(), nums.end()); + vector> presum(maxv + 1, vector(n + 1, 0)); + + for(int v = 1; v <= maxv; v ++){ + for(int i = 0; i < nums.size(); i ++) + presum[v][i + 1] = presum[v][i] + (nums[i] == v); + } + + vector res(queries.size(), -1); + for(int i = 0; i < queries.size(); i ++){ + int l = queries[i][0], r = queries[i][1]; + + int pre = -1, tres = INT_MAX; + for(int v = 1; v <= maxv; v ++) + if(presum[v][r + 1] - presum[v][l]){ + if(pre != -1) tres = min(tres, v - pre); + pre = v; + } + res[i] = tres == INT_MAX ? -1 : tres; + } + return res; + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << " "; cout << endl; +} + +int main() { + + vector nums1 = {1, 3, 4, 8}; + vector> queries1 = {{0, 1}, {1, 2}, {2, 3}, {0, 3}}; + print_vec(Solution().minDifference(nums1, queries1)); + // 2 1 4 1 + + vector nums2 = {4,5,2,2,7,10}; + vector> queries2 = {{2, 3}, {0, 2}, {0, 5}, {3, 5}}; + print_vec(Solution().minDifference(nums2, queries2)); + // -1 1 1 3 + + return 0; +} diff --git a/1501-2000/1908-Game-of-Nim/cpp-1908/CMakeLists.txt b/1501-2000/1908-Game-of-Nim/cpp-1908/CMakeLists.txt new file mode 100644 index 00000000..6076718d --- /dev/null +++ b/1501-2000/1908-Game-of-Nim/cpp-1908/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_1908) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1908 main.cpp) \ No newline at end of file diff --git a/1501-2000/1908-Game-of-Nim/cpp-1908/main.cpp b/1501-2000/1908-Game-of-Nim/cpp-1908/main.cpp new file mode 100644 index 00000000..2f912f85 --- /dev/null +++ b/1501-2000/1908-Game-of-Nim/cpp-1908/main.cpp @@ -0,0 +1,28 @@ +/// Source : https://leetcode.com/problems/game-of-nim/ +/// Author : liuyubobobo +/// Time : 2021-06-26 + +#include +#include + +using namespace std; + + +/// Nim +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + bool nimGame(vector& piles) { + + int x = 0; + for(int e: piles) x ^= e; + return x != 0; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1909-Remove-One-Element-to-Make-the-Array-Strictly-Increasing/cpp-1919/CMakeLists.txt b/1501-2000/1909-Remove-One-Element-to-Make-the-Array-Strictly-Increasing/cpp-1919/CMakeLists.txt new file mode 100644 index 00000000..6de5a8a2 --- /dev/null +++ b/1501-2000/1909-Remove-One-Element-to-Make-the-Array-Strictly-Increasing/cpp-1919/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_1919) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1919 main.cpp) \ No newline at end of file diff --git a/1501-2000/1909-Remove-One-Element-to-Make-the-Array-Strictly-Increasing/cpp-1919/main.cpp b/1501-2000/1909-Remove-One-Element-to-Make-the-Array-Strictly-Increasing/cpp-1919/main.cpp new file mode 100644 index 00000000..6b446ea8 --- /dev/null +++ b/1501-2000/1909-Remove-One-Element-to-Make-the-Array-Strictly-Increasing/cpp-1919/main.cpp @@ -0,0 +1,42 @@ +/// Source : https://leetcode.com/problems/remove-one-element-to-make-the-array-strictly-increasing/ +/// Author : liuyubobobo +/// Time : 2021-06-26 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { +public: + bool canBeIncreasing(vector& nums) { + + for(int i = 0; i < nums.size(); i ++) + if(is_sort(nums, i)) return true; + + return false; + } + +private: + bool is_sort(const vector& nums, int del){ + + vector data; + for(int i = 0; i < nums.size(); i ++) + if(i != del) + data.push_back(nums[i]); + + for(int i = 1; i < data.size(); i ++) + if(data[i] <= data[i - 1]) return false; + return true; + } +}; + + +int main() { + std::cout << "Hello, World!" << std::endl; + return 0; +} diff --git a/1501-2000/1910-Remove-All-Occurrences-of-a-Substring/cpp-1910/CMakeLists.txt b/1501-2000/1910-Remove-All-Occurrences-of-a-Substring/cpp-1910/CMakeLists.txt new file mode 100644 index 00000000..e553de6d --- /dev/null +++ b/1501-2000/1910-Remove-All-Occurrences-of-a-Substring/cpp-1910/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_1910) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1910 main.cpp) \ No newline at end of file diff --git a/1501-2000/1910-Remove-All-Occurrences-of-a-Substring/cpp-1910/main.cpp b/1501-2000/1910-Remove-All-Occurrences-of-a-Substring/cpp-1910/main.cpp new file mode 100644 index 00000000..2537663c --- /dev/null +++ b/1501-2000/1910-Remove-All-Occurrences-of-a-Substring/cpp-1910/main.cpp @@ -0,0 +1,31 @@ +/// Source : https://leetcode.com/problems/remove-all-occurrences-of-a-substring/ +/// Author : liuyubobobo +/// Time : 2021-06-26 + +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(|s| * |part|) +/// Space Complexity: O(|part|) +class Solution { +public: + string removeOccurrences(string s, string part) { + + while(true){ + int pos = s.find(part); + if(pos == string::npos) break; + + s = s.substr(0, pos) + s.substr(pos + part.size()); + } + return s; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1911-Maximum-Alternating-Subsequence-Sum/cpp-1911/CMakeLists.txt b/1501-2000/1911-Maximum-Alternating-Subsequence-Sum/cpp-1911/CMakeLists.txt new file mode 100644 index 00000000..e9734763 --- /dev/null +++ b/1501-2000/1911-Maximum-Alternating-Subsequence-Sum/cpp-1911/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_1911) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1911 main.cpp) \ No newline at end of file diff --git a/1501-2000/1911-Maximum-Alternating-Subsequence-Sum/cpp-1911/main.cpp b/1501-2000/1911-Maximum-Alternating-Subsequence-Sum/cpp-1911/main.cpp new file mode 100644 index 00000000..5b4e1cf7 --- /dev/null +++ b/1501-2000/1911-Maximum-Alternating-Subsequence-Sum/cpp-1911/main.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/maximum-alternating-subsequence-sum/ +/// Author : liuyubobobo +/// Time : 2021-06-2 + +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +private: + int n; + +public: + long long maxAlternatingSum(vector& nums) { + + n = nums.size(); + vector> dp(2, vector(n, LONG_LONG_MIN)); + return solve(nums, 0, 0, dp); + } + +private: + long long solve(const vector& nums, int index, int odd, + vector>& dp){ + + if(index == n) return 0; + if(dp[odd][index] != LONG_LONG_MIN) return dp[odd][index]; + + long long res = solve(nums, index + 1, odd, dp); + if(odd) + res = max(res, -nums[index] + solve(nums, index + 1, !odd, dp)); + else + res = max(res, nums[index] + solve(nums, index + 1, !odd, dp)); + return dp[odd][index] = res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1912-Design-Movie-Rental-System/cpp-1912/CMakeLists.txt b/1501-2000/1912-Design-Movie-Rental-System/cpp-1912/CMakeLists.txt new file mode 100644 index 00000000..0619fcc4 --- /dev/null +++ b/1501-2000/1912-Design-Movie-Rental-System/cpp-1912/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_1912) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1912 main.cpp) \ No newline at end of file diff --git a/1501-2000/1912-Design-Movie-Rental-System/cpp-1912/main.cpp b/1501-2000/1912-Design-Movie-Rental-System/cpp-1912/main.cpp new file mode 100644 index 00000000..7041d1e2 --- /dev/null +++ b/1501-2000/1912-Design-Movie-Rental-System/cpp-1912/main.cpp @@ -0,0 +1,89 @@ +/// Source : https://leetcode.com/problems/design-movie-rental-system/ +/// Author : liuyubobobo +/// Time : 2021-06-27 + +#include +#include +#include +#include + +using namespace std; + + +/// Using TreeMap and TreeSet +/// Time Complexity: init: O(nlogn) +/// search, drop: O(1) +/// rent, drop: O(logn) +/// Space Complexity: O(n) +class MovieRentingSystem { + +private: + map, int> prices; + + vector>> movies; // movie_id -> price, shop_id + map>> rented; // price -> shop -> movie + +public: + MovieRentingSystem(int n, vector>& entries) : movies(10001) { + + for(const vector& e: entries){ + movies[e[1]].insert({e[2], e[0]}); + prices[{e[0], e[1]}] = e[2]; + } + + } + + vector search(int movieid) { + + set>::iterator iter = movies[movieid].begin(); + int k = 0; + vector res; + while(k < 5 && iter != movies[movieid].end()){ + res.push_back(iter->second); + k ++; + iter ++; + } + return res; + } + + void rent(int shopid, int movieid) { + + int price = prices[{shopid,movieid}]; + movies[movieid].erase({price, shopid}); + + rented[price][shopid].insert(movieid); + } + + void drop(int shopid, int movieid) { + + int price = prices[{shopid,movieid}]; + + movies[movieid].insert({price, shopid}); + + rented[price][shopid].erase(movieid); + if(rented[price][shopid].empty()) rented[price].erase(shopid); + if(rented[price].empty()) rented.erase(price); + } + + vector> report() { + + vector> res; + for(const pair>>& p1: rented){ + int price = p1.first; + for(const pair>& p2: p1.second){ + int shopid = p2.first; + for(int movieid: p2.second){ + res.push_back({shopid, movieid}); + if(res.size() == 5) return res; + } + } + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1913-Maximum-Product-Difference-Between-Two-Pairs/cpp-1913/CMakeLists.txt b/1501-2000/1913-Maximum-Product-Difference-Between-Two-Pairs/cpp-1913/CMakeLists.txt new file mode 100644 index 00000000..56912ed2 --- /dev/null +++ b/1501-2000/1913-Maximum-Product-Difference-Between-Two-Pairs/cpp-1913/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1501-2000/1913-Maximum-Product-Difference-Between-Two-Pairs/cpp-1913/main.cpp b/1501-2000/1913-Maximum-Product-Difference-Between-Two-Pairs/cpp-1913/main.cpp new file mode 100644 index 00000000..85d18bba --- /dev/null +++ b/1501-2000/1913-Maximum-Product-Difference-Between-Two-Pairs/cpp-1913/main.cpp @@ -0,0 +1,28 @@ +/// Source : https://leetcode.com/problems/maximum-product-difference-between-two-pairs/submissions/ +/// Author : liuyubobobo +/// Time : 2021-06-26 + +#include +#include + +using namespace std; + + +/// Sorting +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + int maxProductDifference(vector& nums) { + + int n = nums.size(); + sort(nums.begin(), nums.end()); + return nums[n - 1] * nums[n - 2] - nums[0] * nums[1]; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1914-Cyclically-Rotating-a-Grid/cpp-1914/CMakeLists.txt b/1501-2000/1914-Cyclically-Rotating-a-Grid/cpp-1914/CMakeLists.txt new file mode 100644 index 00000000..358dfef4 --- /dev/null +++ b/1501-2000/1914-Cyclically-Rotating-a-Grid/cpp-1914/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1501-2000/1914-Cyclically-Rotating-a-Grid/cpp-1914/main.cpp b/1501-2000/1914-Cyclically-Rotating-a-Grid/cpp-1914/main.cpp new file mode 100644 index 00000000..4c7a20e6 --- /dev/null +++ b/1501-2000/1914-Cyclically-Rotating-a-Grid/cpp-1914/main.cpp @@ -0,0 +1,107 @@ +/// Source : https://leetcode.com/problems/cyclically-rotating-a-grid/ +/// Author : liuyubobobo +/// Time : 2021-06-26 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(min(R * C) * R * C) +/// Space Complexity: O(R + C) +class Solution { + +private: + int R, C; + +public: + vector> rotateGrid(vector>& grid, int k) { + + R = grid.size(), C = grid[0].size(); + for(int index = 0; index < min(R, C) / 2; index ++){ + vector data; + get_data(grid, index, data); + +// cout << "o data:"; +// for(int e: data) cout << e << " "; cout << endl; + + int kk = k % data.size(); + vector new_data(data.size()); + for(int i = 0; i < data.size(); i ++) + new_data[i] = data[(i + kk) % data.size()]; + +// cout << "new data:"; +// for(int e: new_data) cout << e << " "; cout << endl; + + set_data(grid, index, new_data); + } + + return grid; + } + +private: + void set_data(vector>& g, int k, const vector& data){ + + int index = 0; + for(int j = k; j < C - k; j ++) + g[k][j] = data[index ++]; + + for(int i = k + 1; i < R - k; i ++) + g[i][C - 1 - k] = data[index ++]; + + for(int j = C - 1 - k - 1; j >= k; j --) + g[R - k - 1][j] = data[index ++]; + + for(int i = R - 1 - k - 1; i > k; i --) + g[i][k] = data[index ++]; + } + + void get_data(const vector>& g, int k, vector& data){ + + for(int j = k; j < C - k; j ++) + data.push_back(g[k][j]); + + for(int i = k + 1; i < R - k; i ++) + data.push_back(g[i][C - 1 - k]); + + for(int j = C - 1 - k - 1; j >= k; j --) + data.push_back(g[R - k - 1][j]); + + for(int i = R - 1 - k - 1; i > k; i --) + data.push_back(g[i][k]); + } +}; + + +void print_g(const vector>& g){ + + for(const vector& row: g){ + for(int e: row) cout << e << " "; + cout << endl; + } +} + +int main() { + + vector> grid1 = { + {1,2,3,4}, + {5,6,7,8}, + {9,10,11,12}, + {13,14,15,16} + }; + print_g(Solution().rotateGrid(grid1, 2)); + + vector> grid2 = { + {1,2,3,4}, + {16,1,2,5}, + {15,8,3,6}, + {14,7,4,7}, + {13,6,5,8}, + {12,11,10,9} + }; + print_g(Solution().rotateGrid(grid2, 1)); + + return 0; +} diff --git a/1501-2000/1915-Number-of-Wonderful-Substrings/cpp-1915/CMakeLists.txt b/1501-2000/1915-Number-of-Wonderful-Substrings/cpp-1915/CMakeLists.txt new file mode 100644 index 00000000..ad5a4184 --- /dev/null +++ b/1501-2000/1915-Number-of-Wonderful-Substrings/cpp-1915/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1501-2000/1915-Number-of-Wonderful-Substrings/cpp-1915/main.cpp b/1501-2000/1915-Number-of-Wonderful-Substrings/cpp-1915/main.cpp new file mode 100644 index 00000000..0b7ba87b --- /dev/null +++ b/1501-2000/1915-Number-of-Wonderful-Substrings/cpp-1915/main.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/number-of-wonderful-substrings/ +/// Author : liuyubobobo +/// Time : 2021-06-26 + +#include +#include + +using namespace std; + + +/// State Compression + Using HashMap +/// Time Complexity: O(n) +/// Space Complexity: O(2^10) +class Solution { + +private: + const int W = 10; + +public: + long long wonderfulSubstrings(string word) { + + int n = word.size(); + + vector table(1 << 10, 0); + table[0] = 1; + + int state = 0; + long long res = 0ll; + for(int i = 0; i < n; i ++){ + int w = word[i] - 'a'; + state ^= (1 << w); + + res += table[state]; + + for(int k = 0; k < W; k ++) + res += table[state ^ (1 << k)]; + + table[state] ++; + } + return res; + } +}; + + +int main() { + + cout << Solution().wonderfulSubstrings("aba") << endl; + // 4 + + cout << Solution().wonderfulSubstrings("aabb") << endl; + // 9 + + cout << Solution().wonderfulSubstrings("he") << endl; + // 2 + + return 0; +} diff --git a/1501-2000/1916-Count-Ways-to-Build-Rooms-in-an-Ant-Colony/cpp-1916/CMakeLists.txt b/1501-2000/1916-Count-Ways-to-Build-Rooms-in-an-Ant-Colony/cpp-1916/CMakeLists.txt new file mode 100644 index 00000000..8700daa5 --- /dev/null +++ b/1501-2000/1916-Count-Ways-to-Build-Rooms-in-an-Ant-Colony/cpp-1916/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main2.cpp) \ No newline at end of file diff --git a/1501-2000/1916-Count-Ways-to-Build-Rooms-in-an-Ant-Colony/cpp-1916/main.cpp b/1501-2000/1916-Count-Ways-to-Build-Rooms-in-an-Ant-Colony/cpp-1916/main.cpp new file mode 100644 index 00000000..0247052c --- /dev/null +++ b/1501-2000/1916-Count-Ways-to-Build-Rooms-in-an-Ant-Colony/cpp-1916/main.cpp @@ -0,0 +1,93 @@ +/// Source : https://leetcode.com/problems/count-ways-to-build-rooms-in-an-ant-colony/ +/// Author : liuyubobobo +/// Time : 2021-06-26 + +#include +#include + +using namespace std; + + +/// Tree DP +/// See here for details: https://codeforces.com/blog/entry/75627 +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +private: + const long long MOD = 1e9 + 7; + vector fac; + +public: + int waysToBuildRooms(vector& prevRoom) { + + int n = prevRoom.size(); + + fac.clear(); + fac.push_back(1ll); + for(int i = 1; i <= n; i ++) + fac.push_back(fac[i - 1] * i % MOD); + + vector> tree(n); + for(int i = 1; i < n; i ++) + tree[prevRoom[i]].push_back(i); + + vector sz(n, 0); + get_sz(tree, 0, -1, sz); + + vector dp(n, -1ll); + dfs(tree, 0, -1, sz, dp); + return dp[0]; + } + +private: + long long dfs(const vector>& tree, int u, int p, const vector& sz, + vector& dp){ + + for(int v: tree[u]) + if(v != p) dfs(tree, v, u, sz, dp); + + long long a = fac[sz[u] - 1], b = 1ll; + for(int v: tree[u]){ + a = a * dp[v] % MOD; + b = b * fac[sz[v]] % MOD; + } + + return dp[u] = a * mypow(b, MOD - 2) % MOD; + + } + + void get_sz(const vector>& tree, int u, int p, vector& sz){ + + sz[u] = 1; + for(int v: tree[u]) + if(v != p){ + get_sz(tree, v, u, sz); + sz[u] += sz[v]; + } + } + + long long mypow(long long a, int k){ + + if(k == 0) return 1ll; + long long res = mypow(a, k / 2); + res = res * res % MOD; + if(k % 2) res = res * a % MOD; + return res; + } +}; + + +int main() { + + vector prevRoom1 = {-1, 0, 1}; + cout << Solution().waysToBuildRooms(prevRoom1) << endl; + // 1 + + vector prevRoom2 = {-1, 0, 0, 1, 2}; + cout << Solution().waysToBuildRooms(prevRoom2) << endl; + // 6 + + + return 0; +} diff --git a/1501-2000/1916-Count-Ways-to-Build-Rooms-in-an-Ant-Colony/cpp-1916/main2.cpp b/1501-2000/1916-Count-Ways-to-Build-Rooms-in-an-Ant-Colony/cpp-1916/main2.cpp new file mode 100644 index 00000000..3aacb3ed --- /dev/null +++ b/1501-2000/1916-Count-Ways-to-Build-Rooms-in-an-Ant-Colony/cpp-1916/main2.cpp @@ -0,0 +1,78 @@ +/// Source : https://leetcode.com/problems/count-ways-to-build-rooms-in-an-ant-colony/ +/// Author : liuyubobobo +/// Time : 2021-06-26 + +#include +#include + +using namespace std; + + +/// Mathematics +/// See here for details: https://codeforces.com/blog/entry/75627 +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +private: + const long long MOD = 1e9 + 7; + vector fac; + +public: + int waysToBuildRooms(vector& prevRoom) { + + int n = prevRoom.size(); + + fac.clear(); + fac.push_back(1ll); + for(int i = 1; i <= n; i ++) + fac.push_back(fac[i - 1] * i % MOD); + + vector> tree(n); + for(int i = 1; i < n; i ++) + tree[prevRoom[i]].push_back(i); + + vector sz(n, 0); + get_sz(tree, 0, -1, sz); + + long long res = fac[n]; + for(int i = 0; i < n; i ++) + res = res * mypow(sz[i], MOD - 2) % MOD; + return res; + } + +private: + void get_sz(const vector>& tree, int u, int p, vector& sz){ + + sz[u] = 1; + for(int v: tree[u]) + if(v != p){ + get_sz(tree, v, u, sz); + sz[u] += sz[v]; + } + } + + long long mypow(long long a, int k){ + + if(k == 0) return 1ll; + long long res = mypow(a, k / 2); + res = res * res % MOD; + if(k % 2) res = res * a % MOD; + return res; + } +}; + + +int main() { + + vector prevRoom1 = {-1, 0, 1}; + cout << Solution().waysToBuildRooms(prevRoom1) << endl; + // 1 + + vector prevRoom2 = {-1, 0, 0, 1, 2}; + cout << Solution().waysToBuildRooms(prevRoom2) << endl; + // 6 + + + return 0; +} diff --git a/1501-2000/1918-Kth-Smallest-Subarray-Sum/cpp-1918/CMakeLists.txt b/1501-2000/1918-Kth-Smallest-Subarray-Sum/cpp-1918/CMakeLists.txt new file mode 100644 index 00000000..855bc847 --- /dev/null +++ b/1501-2000/1918-Kth-Smallest-Subarray-Sum/cpp-1918/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_1918) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1918 main.cpp) \ No newline at end of file diff --git a/1501-2000/1918-Kth-Smallest-Subarray-Sum/cpp-1918/main.cpp b/1501-2000/1918-Kth-Smallest-Subarray-Sum/cpp-1918/main.cpp new file mode 100644 index 00000000..0707c567 --- /dev/null +++ b/1501-2000/1918-Kth-Smallest-Subarray-Sum/cpp-1918/main.cpp @@ -0,0 +1,67 @@ +/// Source : https://leetcode.com/problems/kth-smallest-subarray-sum/ +/// Author : liuyubobobo +/// Time : 2021-07-01 + +#include +#include +#include + +using namespace std; + + +/// Binary Search + Two Pointers +/// Time Complexity: O(n * log(sum)) +/// Space Complexity: O(1) +class Solution { +public: + int kthSmallestSubarraySum(vector& nums, int k) { + + int n = nums.size(); + + int l = *min_element(nums.begin(), nums.end()), r = accumulate(nums.begin(), nums.end(), 0); + while(l < r){ + int mid = l + (r - l) / 2; + if(subarr_num(nums, mid) < k) l = mid + 1; + else r = mid; + } + return l; + } + +private: + int subarr_num(const vector& nums, int t){ + + int l = 0, r = -1, sum = 0, res = 0; + while(l < nums.size()){ + if(r + 1 < nums.size() && sum + nums[r + 1] <= t) { + sum += nums[++r]; + if(l <= r) res += (r - l + 1); + } + else{ + sum -= nums[l ++]; + } + } + return res; + } +}; + + +int main() { + + vector nums1 = {2, 1, 3}; + cout << Solution().kthSmallestSubarraySum(nums1, 4) << endl; + // 3 + + vector nums2 = {3, 3, 5, 5}; + cout << Solution().kthSmallestSubarraySum(nums2, 7) << endl; + // 10 + + vector nums3 = {2, 1, 5, 4, 4}; + cout << Solution().kthSmallestSubarraySum(nums3, 3) << endl; + // 3 + + vector nums4 = {1, 2, 4, 4, 9}; + cout << Solution().kthSmallestSubarraySum(nums4, 10) << endl; + // 10 + + return 0; +} diff --git a/1501-2000/1920-Build-Array-from-Permutation/cpp-1920/CMakeLists.txt b/1501-2000/1920-Build-Array-from-Permutation/cpp-1920/CMakeLists.txt new file mode 100644 index 00000000..56912ed2 --- /dev/null +++ b/1501-2000/1920-Build-Array-from-Permutation/cpp-1920/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1501-2000/1920-Build-Array-from-Permutation/cpp-1920/main.cpp b/1501-2000/1920-Build-Array-from-Permutation/cpp-1920/main.cpp new file mode 100644 index 00000000..81b62183 --- /dev/null +++ b/1501-2000/1920-Build-Array-from-Permutation/cpp-1920/main.cpp @@ -0,0 +1,30 @@ +/// Source : https://leetcode.com/problems/build-array-from-permutation/ +/// Author : liuyubobobo +/// Time : 2021-07-03 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + vector buildArray(vector& nums) { + + int n = nums.size(); + vector res(n); + for(int i = 0; i < n; i ++) + res[i] = nums[nums[i]]; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1921-Eliminate-Maximum-Number-of-Monsters/B/CMakeLists.txt b/1501-2000/1921-Eliminate-Maximum-Number-of-Monsters/B/CMakeLists.txt new file mode 100644 index 00000000..358dfef4 --- /dev/null +++ b/1501-2000/1921-Eliminate-Maximum-Number-of-Monsters/B/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1501-2000/1921-Eliminate-Maximum-Number-of-Monsters/B/main.cpp b/1501-2000/1921-Eliminate-Maximum-Number-of-Monsters/B/main.cpp new file mode 100644 index 00000000..9fe8cb52 --- /dev/null +++ b/1501-2000/1921-Eliminate-Maximum-Number-of-Monsters/B/main.cpp @@ -0,0 +1,48 @@ +/// Source : https://leetcode.com/problems/4sum-ii/ +/// Author : liuyubobobo +/// Time : 2021-07-03 + +#include +#include + +using namespace std; + + +/// Sorting +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + int eliminateMaximum(vector& dist, vector& speed) { + + int n = dist.size(); + vector t(n); + for(int i = 0; i < n; i ++) + t[i] = dist[i] / speed[i] + !!(dist[i] % speed[i]); + + sort(t.begin(), t.end()); + + int cur = 0; + for(int i = 0; i < n; i ++, cur ++) + if(cur >= t[i]) return i; + return n; + } +}; + + +int main() { + + vector dist1 = {1, 3, 4}, speed1 = {1, 1, 1}; + cout << Solution().eliminateMaximum(dist1, speed1) << endl; + // 3 + + vector dist2 = {1, 1, 2, 3}, speed2 = {1, 1, 1, 1}; + cout << Solution().eliminateMaximum(dist2, speed2) << endl; + // 1 + + vector dist3 = {3, 2, 4}, speed3 = {5, 3, 2}; + cout << Solution().eliminateMaximum(dist3, speed3) << endl; + // 1 + + return 0; +} diff --git a/1501-2000/1922-Count-Good-Numbers/cpp-1922/CMakeLists.txt b/1501-2000/1922-Count-Good-Numbers/cpp-1922/CMakeLists.txt new file mode 100644 index 00000000..ad5a4184 --- /dev/null +++ b/1501-2000/1922-Count-Good-Numbers/cpp-1922/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1501-2000/1922-Count-Good-Numbers/cpp-1922/main.cpp b/1501-2000/1922-Count-Good-Numbers/cpp-1922/main.cpp new file mode 100644 index 00000000..835b1e97 --- /dev/null +++ b/1501-2000/1922-Count-Good-Numbers/cpp-1922/main.cpp @@ -0,0 +1,55 @@ +/// Source : https://leetcode.com/problems/count-good-numbers/ +/// Author : liuyubobobo +/// Time : 2021-07-03 + +#include +#include + +using namespace std; + + +/// Fast Power +/// Time Complexity: O(logn) +/// Space Complexity: O(logn) +class Solution { + +private: + long long MOD = 1e9 + 7; + +public: + int countGoodNumbers(long long n) { + + long long evenpos = (n + 1ll) / 2ll, oddpos = n - evenpos; + + return mypow(5, evenpos) * mypow(4, oddpos) % MOD; + } + +private: + long long mypow(long long a, long long k){ + + if(k == 0ll) return 1ll; + + long long tres = mypow(a, k / 2ll); + long long res = tres * tres % MOD; + if(k % 2ll == 1ll) res = res * a % MOD; + return res; + } +}; + + +int main() { + + cout << Solution().countGoodNumbers(1ll) << endl; + // 5 + + cout << Solution().countGoodNumbers(4ll) << endl; + // 400 + + cout << Solution().countGoodNumbers(50ll) << endl; + // 564908303 + + cout << Solution().countGoodNumbers(2ll) << endl; + // 20 + + return 0; +} diff --git a/1501-2000/1923-Longest-Common-Subpath/cpp-1923/CMakeLists.txt b/1501-2000/1923-Longest-Common-Subpath/cpp-1923/CMakeLists.txt new file mode 100644 index 00000000..8e6ea4a2 --- /dev/null +++ b/1501-2000/1923-Longest-Common-Subpath/cpp-1923/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) \ No newline at end of file diff --git a/1501-2000/1923-Longest-Common-Subpath/cpp-1923/main.cpp b/1501-2000/1923-Longest-Common-Subpath/cpp-1923/main.cpp new file mode 100644 index 00000000..3af632c1 --- /dev/null +++ b/1501-2000/1923-Longest-Common-Subpath/cpp-1923/main.cpp @@ -0,0 +1,155 @@ +/// Source : https://leetcode.com/problems/longest-common-subpath/ +/// Author : liuyubobobo +/// Time : 2021-08-02 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// RK +/// Time Complexity: O(O(all_path_city * log(min_len))) +/// Space Complexity: O(n) +class StringHash{ + +private: + int n; + unsigned long long B, MOD; + vector h, p; + +public: + StringHash(const vector& s, unsigned long long B = 128, unsigned long long MOD = 1e9+ 7) : + n(s.size()), h(n + 1, 0), p(n + 1, 1ll), B(B), MOD(MOD){ + + for(int i = 0; i < n; i ++){ + h[i + 1] = (h[i] * B + s[i]) % MOD; + p[i + 1] = p[i] * B % MOD; + } + } + + unsigned long long get_hash(int l, int r){ + // assert(l >= 0 && l < n); + // assert(r >= 0 && r < n); + return (h[r + 1] - h[l] * p[r - l + 1] % MOD + MOD) % MOD; + } +}; + +class StringHashU{ + +private: + int n; + unsigned long long B; + vector h, p; + +public: + StringHashU(const vector& s, unsigned long long B = 128) : + n(s.size()), h(n + 1, 0), p(n + 1, 1ll), B(B){ + + for(int i = 0; i < n; i ++){ + h[i + 1] = h[i] * B + s[i]; + p[i + 1] = p[i] * B; + } + } + + unsigned long long get_hash(int l, int r){ + // assert(l >= 0 && l < n); + // assert(r >= 0 && r < n); + return h[r + 1] - h[l] * p[r - l + 1]; + } +}; + +class Solution { + +private: + vector hash1/*, hash2*/; + vector hash3; + +public: + int longestCommonSubpath(int n, vector>& paths) { + + int min_len = INT_MAX, maxv = 0; + for(const vector& path: paths){ + min_len = min(min_len, (int)path.size()); + maxv = max(maxv, *max_element(path.begin(), path.end())); + } + + hash1.clear(), /*hash2.clear(),*/ hash3.clear(); + for(int i = 0; i < paths.size(); i ++){ + hash1.push_back(StringHash(paths[i], 911382323, 972663749)); + // hash2.push_back(StringHash(paths[i], 1e9 + 5e8 + 7, 3e9 + 19)); + hash3.push_back(StringHashU(paths[i], maxv + 7)); + } + + int l = 0, r = min_len; + while(l < r){ + int mid = (l + r + 1) / 2; + if(ok(paths, mid)) l = mid; + else r = mid - 1; + } + return l; + } + +private: + bool ok(const vector>& paths, int len){ + + unordered_set hash1_set, hash2_set, hash3_set; + for(int i = 0; i + len <= paths[0].size(); i ++){ + hash1_set.insert(hash1[0].get_hash(i, i + len - 1)); + // hash2_set.insert(hash2[0].get_hash(i, i + len - 1)); + hash3_set.insert(hash3[0].get_hash(i, i + len - 1)); + } + + for(int i = 1; i < paths.size(); i ++){ + + unordered_set t_hash_set1, /*t_hash_set2, */t_hash_set3; + for(int j = 0; j + len <= paths[i].size(); j ++){ + t_hash_set1.insert(hash1[i].get_hash(j, j + len - 1)); + // t_hash_set2.insert(hash2[i].get_hash(j, j + len - 1)); + t_hash_set3.insert(hash3[i].get_hash(j, j + len - 1)); + } + + hash1_set = intersection(hash1_set, t_hash_set1); + // hash2_set = intersection(hash2_set, t_hash_set2); + hash3_set = intersection(hash3_set, t_hash_set3); + + if(hash1_set.empty() || /*hash2_set.empty() ||*/ hash3_set.empty()) + return false; + } + return true; + } + + unordered_set intersection(unordered_set& a, + unordered_set& b){ + + unordered_set res; + for(long long e: a) + if(b.count(e)) res.insert(e); + return res; + } +}; + + +int main() { + + vector> paths1 = {{0,1,2,3,4},{2,3,4},{4,0,1,2,3}}; + cout << Solution().longestCommonSubpath(5, paths1) << endl; + // 2 + + vector> paths2 = {{0},{1},{2}}; + cout << Solution().longestCommonSubpath(3, paths2) << endl; + // 0 + + vector> paths3 = {{0,1,2,3,4},{4,3,2,1,0}}; + cout << Solution().longestCommonSubpath(5, paths3) << endl; + // 1 + + vector> paths4 = {{0,1,0,1,0,1,0,1,0},{0,1,3,0,1,4,0,1,0}}; + cout << Solution().longestCommonSubpath(5, paths4) << endl; + // 3 + + return 0; +} diff --git a/1501-2000/1924-Erect-the-Fence-II/cpp-1924/CMakeLists.txt b/1501-2000/1924-Erect-the-Fence-II/cpp-1924/CMakeLists.txt new file mode 100644 index 00000000..667fc29e --- /dev/null +++ b/1501-2000/1924-Erect-the-Fence-II/cpp-1924/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_1924) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1924 main.cpp) \ No newline at end of file diff --git a/1501-2000/1924-Erect-the-Fence-II/cpp-1924/main.cpp b/1501-2000/1924-Erect-the-Fence-II/cpp-1924/main.cpp new file mode 100644 index 00000000..c0da9862 --- /dev/null +++ b/1501-2000/1924-Erect-the-Fence-II/cpp-1924/main.cpp @@ -0,0 +1,241 @@ +/// Source : https://leetcode.com/problems/erect-the-fence-ii/ +/// Author : liuyubobobo +/// Time : 2021-07-11 + +#include +#include + +using namespace std; + + +/// Welzl’s Algorithm +/// See here for detail: https://www.geeksforgeeks.org/minimum-enclosing-circle-set-2-welzls-algorithm/ +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +// T 选择 long double 或者 double +template +class LinearSystem{ + +private: + const T eps = 1e-9; + int R, C; + vector> A, original; + +public: + LinearSystem(vector>& matrix, T eps): A(matrix), original(matrix), eps(eps){ + + R = matrix.size(); + assert(R); + + C = matrix[0].size(); + assert(C == R + 1); + } + + vector solve(){ + + T k; + for(int r = 0; r < R; r ++){ + + int max_index = r; + T maxv = abs(A[r][r]); + for(int i = r + 1; i < R; i ++) + if(abs(A[i][r]) > maxv) + max_index = i, maxv = abs(A[i][r]); + + if(max_index != r) swap(A[r], A[max_index]); + + k = A[r][r]; + if(abs(k) < eps){ + for(const vector& v: original){ + for(T e: v) cout << e << ' '; cout << '\n'; + } + return {}; + } + + if(abs(k - 1) > eps) + for(int j = r; j < C; j ++) + A[r][j] /= k; + + for(int i = r + 1; i < R; i ++){ + k = A[i][r]; + if(abs(k) > eps) + for(int j = r; j < C; j ++) + A[i][j] -= k * A[r][j]; + } + } + + for(int j = R - 1; j >= 1; j --){ + for(int i = j - 1; i >= 0; i --){ + k = A[i][j]; + A[i][j] = 0; + A[i][C - 1] -= k * A[j][C - 1]; + } + } + + vector res(R); + for(int i = 0; i < R; i ++) res[i] = A[i].back(); + // assert(validate(res)); + return res; + } + +private: + bool validate(const vector& res){ + + for(int i = 0; i < R; i ++){ + T y = 0.0; + for(int j = 0; j < C - 1; j ++) y += res[j] * original[i][j]; + if(abs(y - original[i].back()) > eps) return false; + } + return true; + } +}; + +// T 选择 long double 或者 double +template +class Welzls{ + +private: + const T eps; + +public: + Welzls(T eps) : eps(eps){} + + vector solve(vector>& points){ + + assert(points.size() > 0); + assert(points[0].size() == 2); + + srand(time(nullptr)); + + vector> supports; + return solve(points, points.size(), supports); + }; + +private: + vector solve(vector>& points, int n, vector> supports){ + + assert(supports.size() <= 3); + if(supports.size() == 3){ + return get_circle(supports[0][0], supports[0][1], + supports[1][0], supports[1][1], + supports[2][0], supports[2][1]); + } + + if(n == 0){ + if(supports.size() == 2) + return get_circle(supports[0][0], supports[0][1], + supports[1][0], supports[1][1]); + else if(supports.size() == 1) + return {supports[0][0], supports[0][1], 0.0}; + + assert(supports.size() == 0); + return {0.0, 0.0, 0.0}; + } + + int index = rand() % n; + swap(points[index], points[n - 1]); + + vector circle = solve(points, n - 1, supports); + if(in_circle(circle, points[n - 1])) + return circle; + + supports.push_back(points[n - 1]); + return solve(points, n - 1, supports); + } + + // 给定三个点,求圆 + // x0 = ret[0], y0 = ret[1], r = ret[2]; + vector get_circle(T x1, T y1, T x2, T y2, T x3, T y3){ + + // 尝试是否可以用两点构成圆? + vector circle = get_circle(x1, y1, x2, y2); + if(in_circle(circle, {x3, y3})) return circle; + + circle = get_circle(x1, y1, x3, y3); + if(in_circle(circle, {x2, y2})) return circle; + + circle = get_circle(x2, y2, x3, y3); + if(in_circle(circle, {x1, y1})) return circle; + + // 用三个不同点构成圆 + vector> A = { + {x1, y1, 1.0, - x1 * x1 - y1 * y1}, + {x2, y2, 1.0, - x2 * x2 - y2 * y2}, + {x3, y3, 1.0, - x3 * x3 - y3 * y3} + }; + + LinearSystem ls(A, eps); + vector res = ls.solve(); + assert(!res.empty()); + circle = {- res[0] / 2.0, - res[1] / 2.0, sqrt((res[0] * res[0] + res[1] * res[1] - 4.0 * res[2])) / 2.0}; + + // assert(on_circle(circle, {x1, y1}) && on_circle(circle, {x2, y2}) && on_circle(circle, {x3, y3})); + return circle; + } + + // 给定两个不同的点,求圆 + // x0 = ret[0], y0 = ret[1], r = ret[2]; + vector get_circle(T x1, T y1, T x2, T y2){ + return {(x1 + x2) / 2.0, (y1 + y2) / 2.0, dis(x1, y1, x2, y2) / 2.0}; + } + + // 计算 (x1, y1) 和 (x2, y2) 的距离 + T dis(T x1, T y1, T x2, T y2){ + return sqrt(dis_square(x1, y1, x2, y2)); + } + + // 计算 (x1, y1) 和 (x2, y2) 的距离的平方 + T dis_square(T x1, T y1, T x2, T y2){ + return (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2); + } + + // 判断 p 是否在 circle 中 + // x0 = circle[0], y0 = circle[1], r = circle[2]; + bool in_circle(const vector& circle, const vector& p){ + return dis_square(circle[0], circle[1], p[0], p[1]) <= circle[2] * circle[2] + eps; + } + + // 判断 p 是否在 circle 上 + // x0 = circle[0], y0 = circle[1], r = circle[2]; + bool on_circle(const vector& circle, const vector& p){ + return abs(dis_square(circle[0], circle[1], p[0], p[1]) - circle[2] * circle[2]) <= eps; + } +}; + + +class Solution { +public: + vector outerTrees(vector>& trees) { + + int n = trees.size(); + vector> points(n, vector(2)); + for(int i = 0; i < n; i ++) + points[i][0] = trees[i][0], points[i][1] = trees[i][1]; + + return Welzls(1e-7).solve(points); + } +}; + + +void print_vec(const vector& v){ + for(double e: v) cout << e << ' '; cout << endl; +} + +int main() { + + vector> trees1 = { + {1, 1}, {2, 2}, {2, 0}, {2, 4}, {3, 3}, {4, 2} + }; + print_vec(Solution().outerTrees(trees1)); + // 2 2 2 + + vector> trees2 = { + {55, 7},{36, 30},{1, 64},{83, 97},{8, 90},{16, 7}, + {18, 23},{98, 77},{57, 33},{98, 54},{73, 7} + }; + print_vec(Solution().outerTrees(trees2)); + // 49.36388,52.10134,56.10061 + + return 0; +} diff --git a/1501-2000/1925-Count-Square-Sum-Triples/cpp-1925/CMakeLists.txt b/1501-2000/1925-Count-Square-Sum-Triples/cpp-1925/CMakeLists.txt new file mode 100644 index 00000000..d32c53c0 --- /dev/null +++ b/1501-2000/1925-Count-Square-Sum-Triples/cpp-1925/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_1925) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1925 main.cpp) \ No newline at end of file diff --git a/1501-2000/1925-Count-Square-Sum-Triples/cpp-1925/main.cpp b/1501-2000/1925-Count-Square-Sum-Triples/cpp-1925/main.cpp new file mode 100644 index 00000000..9f57d0f8 --- /dev/null +++ b/1501-2000/1925-Count-Square-Sum-Triples/cpp-1925/main.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/count-square-sum-triples/ +/// Author : liuyubobobo +/// Time : 2021-07-11 + +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n^2) +/// Space Complexity: O(1) +class Solution { +public: + int countTriples(int n) { + + int res = 0; + for(int i = 1; i <= n; i ++) + for(int j = i; j <= n; j ++){ + int c = i * i + j * j; + int cc = sqrt((double)c); + if(cc * cc == c && 1 <= cc && cc <= n) + res += (i == j ? 1 : 2); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1926-Nearest-Exit-from-Entrance-in-Maze/cpp-1926/CMakeLists.txt b/1501-2000/1926-Nearest-Exit-from-Entrance-in-Maze/cpp-1926/CMakeLists.txt new file mode 100644 index 00000000..819e047b --- /dev/null +++ b/1501-2000/1926-Nearest-Exit-from-Entrance-in-Maze/cpp-1926/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_1926) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1926 main.cpp) \ No newline at end of file diff --git a/1501-2000/1926-Nearest-Exit-from-Entrance-in-Maze/cpp-1926/main.cpp b/1501-2000/1926-Nearest-Exit-from-Entrance-in-Maze/cpp-1926/main.cpp new file mode 100644 index 00000000..c21600f1 --- /dev/null +++ b/1501-2000/1926-Nearest-Exit-from-Entrance-in-Maze/cpp-1926/main.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/ +/// Author : liuyubobobo +/// Time : 2021-07-11 + +#include +#include +#include + +using namespace std; + + +/// BFS +/// Time Complexity: O(R * C) +/// Space Complexity: O(R * C) +class Solution { + +private: + const int dirs[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; + int R, C; + +public: + int nearestExit(vector>& maze, vector& entrance) { + + R = maze.size(), C = maze[0].size(); + vector> dis(R, vector(C, -1)); + + queue q; + q.push(entrance[0] * C + entrance[1]); + dis[entrance[0]][entrance[1]] = 0; + while(!q.empty()){ + int x = q.front() / C, y = q.front() % C; + q.pop(); + + for(int d = 0; d < 4; d ++){ + int nx = x + dirs[d][0], ny = y + dirs[d][1]; + if(in_area(nx, ny) && dis[nx][ny] == -1 && maze[nx][ny] == '.'){ + dis[nx][ny] = dis[x][y] + 1; + if(nx == 0 || nx == R - 1 || ny == 0 || ny == C - 1) + return dis[nx][ny]; + q.push(nx * C + ny); + } + } + } + return -1; + } + +private: + bool in_area(int x, int y){ + return x >= 0 && x < R && y >= 0 && y < C; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1927-Sum-Game/cpp-1927/CMakeLists.txt b/1501-2000/1927-Sum-Game/cpp-1927/CMakeLists.txt new file mode 100644 index 00000000..f5d99dbc --- /dev/null +++ b/1501-2000/1927-Sum-Game/cpp-1927/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_1927) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1927 main.cpp) \ No newline at end of file diff --git a/1501-2000/1927-Sum-Game/cpp-1927/main.cpp b/1501-2000/1927-Sum-Game/cpp-1927/main.cpp new file mode 100644 index 00000000..e16b2ae4 --- /dev/null +++ b/1501-2000/1927-Sum-Game/cpp-1927/main.cpp @@ -0,0 +1,58 @@ +/// Source : https://leetcode.com/problems/sum-game/ +/// Author : liuyubobobo +/// Time : 2021-07-11 + +#include +#include + +using namespace std; + + +/// Ad-Hoc - Mathematics +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + bool sumGame(string num) { + + int n = num.size(); + + int leftsum = 0, left = 0; + for(int i = 0; i < n / 2; i ++) + if(num[i] == '?') left ++; + else leftsum += (num[i] - '0'); + + int rightsum = 0, right = 0; + for(int i = n / 2; i < n; i ++) + if(num[i] == '?') right ++; + else rightsum += (num[i] - '0'); + +// cout << left << " " << leftsum << " " << right << " " << rightsum << endl; + + if(leftsum >= rightsum) + return solve(leftsum - rightsum, left, right); + return solve(rightsum - leftsum, right, left); + } + +private: + // sum + a? = b? + bool solve(int sum, int a, int b){ + +// cout << sum << " " << a << " " << b << endl; + + if((a + b) % 2) return true; + + if(a > b) return true; + + return (b - a) / 2 * 9 != sum; + } +}; + + +int main() { + + cout << Solution().sumGame("?3295???") << endl; + // 0 + + return 0; +} diff --git a/1501-2000/1928-Minimum-Cost-to-Reach-Destination-in-Time/cpp-1928/CMakeLists.txt b/1501-2000/1928-Minimum-Cost-to-Reach-Destination-in-Time/cpp-1928/CMakeLists.txt new file mode 100644 index 00000000..fda2b761 --- /dev/null +++ b/1501-2000/1928-Minimum-Cost-to-Reach-Destination-in-Time/cpp-1928/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_1928) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1928 main2.cpp) \ No newline at end of file diff --git a/1501-2000/1928-Minimum-Cost-to-Reach-Destination-in-Time/cpp-1928/main.cpp b/1501-2000/1928-Minimum-Cost-to-Reach-Destination-in-Time/cpp-1928/main.cpp new file mode 100644 index 00000000..3a2ee700 --- /dev/null +++ b/1501-2000/1928-Minimum-Cost-to-Reach-Destination-in-Time/cpp-1928/main.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/minimum-cost-to-reach-destination-in-time/ +/// Author : liuyubobobo +/// Time : 2021-07-10 + +#include +#include +#include + +using namespace std; + + +/// Memoization +/// Time Complexity: O(maxTime * (V + E)) +/// Space Complexity: O(V * maxTime) +class Solution { + +private: + const int INF = 1e9; + +public: + int minCost(int maxTime, vector>& edges, vector& passingFees) { + + int n = passingFees.size(); + vector> g(n); + for(const vector& e: edges){ + int a = e[0], b = e[1], w = e[2]; + if(!g[a].count(b) || g[a][b] > w) + g[a][b] = g[b][a] = w; + } + + vector> dp(n, vector(maxTime + 1, -1)); + int res = dfs(n, g, passingFees, 0, 0, maxTime, dp); + return res >= INF ? -1 : res; + } + +private: + int dfs(int n, const vector>& g, const vector& fees, + int u, int t, const int maxTime, vector>& dp){ + + if(u == n - 1) return fees[n - 1]; + if(dp[u][t] != -1) return dp[u][t]; + + int res = INF; + for(const pair& p: g[u]){ + int v = p.first, w = p.second; + if(t + w <= maxTime) + res = min(res, fees[u] + dfs(n, g, fees, v, t + w, maxTime, dp)); + } + return dp[u][t] = res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1928-Minimum-Cost-to-Reach-Destination-in-Time/cpp-1928/main2.cpp b/1501-2000/1928-Minimum-Cost-to-Reach-Destination-in-Time/cpp-1928/main2.cpp new file mode 100644 index 00000000..464c8df3 --- /dev/null +++ b/1501-2000/1928-Minimum-Cost-to-Reach-Destination-in-Time/cpp-1928/main2.cpp @@ -0,0 +1,51 @@ +/// Source : https://leetcode.com/problems/minimum-cost-to-reach-destination-in-time/ +/// Author : liuyubobobo +/// Time : 2021-07-10 + +#include +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(maxTime * (V + E)) +/// Space Complexity: O(V * maxTime) +class Solution { + +private: + const int INF = 1e9; + +public: + int minCost(int maxTime, vector>& edges, vector& passingFees) { + + int n = passingFees.size(); + vector> g(n); + for(const vector& e: edges){ + int a = e[0], b = e[1], w = e[2]; + if(!g[a].count(b) || g[a][b] > w) + g[a][b] = g[b][a] = w; + } + + vector> dp(maxTime + 1, vector(n, INF)); + dp[maxTime][n - 1] = passingFees[n - 1]; + + for(int t = maxTime - 1; t >= 0; t --){ + dp[t][n - 1] = passingFees[n - 1]; + for(int u = 0; u < n - 1; u ++) + for(const pair& p: g[u]){ + int v = p.first, w = p.second; + if(t + w <= maxTime) + dp[t][u] = min(dp[t][u], passingFees[u] + dp[t + w][v]); + } + } + return dp[0][0] >= INF ? -1 : dp[0][0]; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1929-Concatenation-of-Array/cpp-1929/CMakeLists.txt b/1501-2000/1929-Concatenation-of-Array/cpp-1929/CMakeLists.txt new file mode 100644 index 00000000..56912ed2 --- /dev/null +++ b/1501-2000/1929-Concatenation-of-Array/cpp-1929/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1501-2000/1929-Concatenation-of-Array/cpp-1929/main.cpp b/1501-2000/1929-Concatenation-of-Array/cpp-1929/main.cpp new file mode 100644 index 00000000..a87ffd85 --- /dev/null +++ b/1501-2000/1929-Concatenation-of-Array/cpp-1929/main.cpp @@ -0,0 +1,30 @@ +/// Source : https://leetcode.com/problems/concatenation-of-array/ +/// Author : liuyubobobo +/// Time : 2021-07-10 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + vector getConcatenation(vector& nums) { + + int n = nums.size(); + vector res(2 * n); + for(int i = 0; i < n; i ++) + res[i] = res[i + n] = nums[i]; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1930-Unique-Length-3-Palindromic-Subsequences/cpp-1930/CMakeLists.txt b/1501-2000/1930-Unique-Length-3-Palindromic-Subsequences/cpp-1930/CMakeLists.txt new file mode 100644 index 00000000..b875daa2 --- /dev/null +++ b/1501-2000/1930-Unique-Length-3-Palindromic-Subsequences/cpp-1930/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main2.cpp) \ No newline at end of file diff --git a/1501-2000/1930-Unique-Length-3-Palindromic-Subsequences/cpp-1930/main.cpp b/1501-2000/1930-Unique-Length-3-Palindromic-Subsequences/cpp-1930/main.cpp new file mode 100644 index 00000000..4a37231d --- /dev/null +++ b/1501-2000/1930-Unique-Length-3-Palindromic-Subsequences/cpp-1930/main.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/unique-length-3-palindromic-subsequences/ +/// Author : liuyubobobo +/// Time : 2021-07-10 + +#include +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int countPalindromicSubsequence(string s) { + + int res = 0; + for(char c = 'a'; c <= 'z'; c ++){ + int i = 0; + for(; i < s.size(); i ++) + if(s[i] == c) break; + + if(i == s.size()) continue; + + int j = s.size() - 1; + for(; j >= 0; j --) + if(s[j] == c) break; + + if(i == j || i + 1 == j) continue; + + vector v(26, 0); + for(int k = i + 1; k < j; k ++) + v[s[k] - 'a'] = 1; + + res += accumulate(v.begin(), v.end(), 0); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1930-Unique-Length-3-Palindromic-Subsequences/cpp-1930/main2.cpp b/1501-2000/1930-Unique-Length-3-Palindromic-Subsequences/cpp-1930/main2.cpp new file mode 100644 index 00000000..5a691fc4 --- /dev/null +++ b/1501-2000/1930-Unique-Length-3-Palindromic-Subsequences/cpp-1930/main2.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/unique-length-3-palindromic-subsequences/ +/// Author : liuyubobobo +/// Time : 2021-07-10 + +#include +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Using presum and binary search +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int countPalindromicSubsequence(string s) { + + int n = s.size(); + vector> presum(26, vector(n + 1, 0)); + for(int i = 0; i < n; i ++) + for(char c = 'a'; c <= 'z'; c ++) + presum[c - 'a'][i + 1] = presum[c - 'a'][i] + (s[i] == c); + + int res = 0; + for(int c = 0; c < 26; c ++){ + + vector::iterator iter = lower_bound(presum[c].begin(), presum[c].end(), 1); + + if(iter == presum[c].end()) continue; + int i = (iter - presum[c].begin()) - 1; + + iter = lower_bound(presum[c].begin(), presum[c].end(), presum[c].back()); + int j = (iter - presum[c].begin()) - 1; + + if(i == j || i + 1 == j) continue; + + for(int cc = 0; cc < 26; cc ++) + res += !!(presum[cc][j] - presum[cc][i + 1]); + } + return res; + } +}; + + +int main() { + + cout << Solution().countPalindromicSubsequence("bbcbaba") << endl; + // 4 + + return 0; +} diff --git a/1501-2000/1931-Painting-a-Grid-With-Three-Different-Colors/cpp-1931/CMakeLists.txt b/1501-2000/1931-Painting-a-Grid-With-Three-Different-Colors/cpp-1931/CMakeLists.txt new file mode 100644 index 00000000..53575fde --- /dev/null +++ b/1501-2000/1931-Painting-a-Grid-With-Three-Different-Colors/cpp-1931/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main2.cpp) \ No newline at end of file diff --git a/1501-2000/1931-Painting-a-Grid-With-Three-Different-Colors/cpp-1931/main.cpp b/1501-2000/1931-Painting-a-Grid-With-Three-Different-Colors/cpp-1931/main.cpp new file mode 100644 index 00000000..c4f5210c --- /dev/null +++ b/1501-2000/1931-Painting-a-Grid-With-Three-Different-Colors/cpp-1931/main.cpp @@ -0,0 +1,101 @@ +/// Source : https://leetcode.com/problems/painting-a-grid-with-three-different-colors/ +/// Author : liuyubobobo +/// Time : 2021-07-10 + +#include +#include +#include + +using namespace std; + + +/// Memoization +/// Time Complexity: O((3^m)^2 * n) +/// Space Complexity: O(3^m * n) +class Solution { + +private: + const int MOD = 1e9 + 7; + +public: + int colorTheGrid(int m, int n) { + + int L = 1; + for(int i = 0; i < m; i ++) L *= 3; + + set okstate; + for(int state = 0; state < L; state ++) + if(ok(state, m)) + okstate.insert(state); + + vector> next(L, vector()); + for(int state: okstate) + get_next(m, state, 0, 0, next[state]); + + vector> dp(L, vector(n, -1)); + int res = 0; + for(int state: okstate) + res = (res + dfs(next, state, 1, n, dp)) % MOD; + return res; + } + +private: + int dfs(const vector>& next, int pstate, int index, int n, + vector>& dp){ + + if(index == n) return 1; + if(dp[pstate][index] != -1) return dp[pstate][index]; + + int res = 0; + for(int state: next[pstate]) + res = (res + dfs(next, state, index + 1, n, dp)) % MOD; + return dp[pstate][index] = res; + } + + void get_next(int m, int state, int index, int next_state, + vector& next){ + + if(index == m){ + next.push_back(next_state); + return; + } + + for(int color = 0; color < 3; color ++) + if(color != state % 3){ + if(index > 0 && color == next_state % 3) + continue; + get_next(m, state / 3, index + 1, next_state * 3 + color, next); + } + } + + bool ok(int x, int len){ + + vector v(len); + for(int i = 0; i < len; i ++){ + v[i] = x % 3, x /= 3; + if(i && v[i] == v[i - 1]) return false; + } + return true; + } +}; + + +int main() { + + cout << Solution().colorTheGrid(1, 1) << endl; + // 3 + + cout << Solution().colorTheGrid(1, 2) << endl; + // 6 + + cout << Solution().colorTheGrid(5, 5) << endl; + // 580986 + + cout << Solution().colorTheGrid(2, 37) << endl; + // 478020091 + + cout << Solution().colorTheGrid(5, 1000) << endl; + // 408208448 + + return 0; +} diff --git a/1501-2000/1931-Painting-a-Grid-With-Three-Different-Colors/cpp-1931/main2.cpp b/1501-2000/1931-Painting-a-Grid-With-Three-Different-Colors/cpp-1931/main2.cpp new file mode 100644 index 00000000..5cb7fb02 --- /dev/null +++ b/1501-2000/1931-Painting-a-Grid-With-Three-Different-Colors/cpp-1931/main2.cpp @@ -0,0 +1,97 @@ +/// Source : https://leetcode.com/problems/painting-a-grid-with-three-different-colors/ +/// Author : liuyubobobo +/// Time : 2021-07-10 + +#include +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O((3^m)^2 * n) +/// Space Complexity: O(3^m) +class Solution { + +private: + const int MOD = 1e9 + 7; + +public: + int colorTheGrid(int m, int n) { + + int L = 1; + for(int i = 0; i < m; i ++) L *= 3; + + set okstate; + for(int state = 0; state < L; state ++) + if(ok(state, m)) + okstate.insert(state); + + vector> next(L, vector()); + for(int state: okstate) + get_next(m, state, 0, 0, next[state]); + + vector dp(L, 0); + for(int state: okstate) dp[state] = 1; + for(int i = n - 2; i >= 0; i --){ + vector tdp(L, 0); + for(int state: okstate) + for(int nextstate: next[state]) + tdp[state] = (tdp[state] + dp[nextstate]) % MOD; + dp = tdp; + } + + int res = 0; + for(int e: dp) res = (res + e) % MOD; + return res; + } + +private: + void get_next(int m, int state, int index, int next_state, + vector& next){ + + if(index == m){ + next.push_back(next_state); + return; + } + + for(int color = 0; color < 3; color ++) + if(color != state % 3){ + if(index > 0 && color == next_state % 3) + continue; + get_next(m, state / 3, index + 1, next_state * 3 + color, next); + } + } + + bool ok(int x, int len){ + + vector v(len); + for(int i = 0; i < len; i ++){ + v[i] = x % 3, x /= 3; + if(i && v[i] == v[i - 1]) return false; + } + return true; + } +}; + + +int main() { + + cout << Solution().colorTheGrid(1, 1) << endl; + // 3 + + cout << Solution().colorTheGrid(1, 2) << endl; + // 6 + + cout << Solution().colorTheGrid(5, 5) << endl; + // 580986 + + cout << Solution().colorTheGrid(2, 37) << endl; + // 478020091 + + cout << Solution().colorTheGrid(5, 1000) << endl; + // 408208448 + + return 0; +} diff --git a/1501-2000/1932-Merge-BSTs-to-Create-Single-BST/cpp-1932/CMakeLists.txt b/1501-2000/1932-Merge-BSTs-to-Create-Single-BST/cpp-1932/CMakeLists.txt new file mode 100644 index 00000000..c8ff52a0 --- /dev/null +++ b/1501-2000/1932-Merge-BSTs-to-Create-Single-BST/cpp-1932/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_1932) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1932 main2.cpp) \ No newline at end of file diff --git a/1501-2000/1932-Merge-BSTs-to-Create-Single-BST/cpp-1932/main.cpp b/1501-2000/1932-Merge-BSTs-to-Create-Single-BST/cpp-1932/main.cpp new file mode 100644 index 00000000..71fe57be --- /dev/null +++ b/1501-2000/1932-Merge-BSTs-to-Create-Single-BST/cpp-1932/main.cpp @@ -0,0 +1,126 @@ +/// Source : https://leetcode.com/problems/merge-bsts-to-create-single-bst/ +/// Author : liuyubobobo +/// Time : 2021-07-11 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// 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* canMerge(vector& trees) { + + unordered_map> f; + unordered_set roots; + unordered_map to_root; + for(TreeNode* node: trees){ + dfs(node, f, to_root, node); + roots.insert(node); + } + + int cnt = 0; + for(const pair>& p: f){ + if(p.second.size() > 2) return nullptr; + else if(p.second.size() == 2) cnt ++; + } + + if(cnt + 1 != trees.size()) return nullptr; + + TreeNode* root = build(roots, f, to_root); + + if(!root) return nullptr; + return is_bst(root, INT_MIN, INT_MAX) ? root : nullptr; + } + +private: + TreeNode* build(unordered_set& roots, + unordered_map>& f, + unordered_map& to_root){ + + for(const pair>& p: f) + if(p.second.size() == 2){ + + TreeNode *a = p.second[0], *b = p.second[1]; + + TreeNode *root, *leaf; + if(roots.count(a) && is_leaf(b)) root = a, leaf = b; + else if(roots.count(b) && is_leaf(a)) root = b, leaf = a; + else return nullptr; + + if(to_root[root] == to_root[leaf]) return nullptr; + + leaf->left = root->left; + leaf->right = root->right; + + if(leaf->left) to_root[leaf->left] = to_root[leaf]; + if(leaf->right) to_root[leaf->right] = to_root[leaf]; + roots.erase(root); + } +// else assert(p.second.size() == 1); + + return roots.size() == 1 ? *roots.begin() : nullptr; + } + + bool is_bst(TreeNode* node, int a, int b){ + + if(!node) return true; + + if(!(a <= node->val && node->val <= b)) return false; + + return is_bst(node->left, a, node->val - 1) && is_bst(node->right, node->val + 1, b); + } + + void dfs(TreeNode* node, unordered_map>& f, + unordered_map& to_root, TreeNode* root){ + + if(!node) return; + + f[node->val].push_back(node); + to_root[node] = root; + + dfs(node->left, f, to_root, root); + dfs(node->right, f, to_root, root); + } + + bool is_leaf(TreeNode* node){ + return !node->left && !node->right; + } +}; + + +int main() { + + vector trees1 = {new TreeNode(1, nullptr, new TreeNode(3)), + new TreeNode(3, new TreeNode(1), nullptr), + new TreeNode(4, new TreeNode(2), nullptr)}; + cout << Solution().canMerge(trees1) << endl; + // null + + vector trees2 = {new TreeNode(5, new TreeNode(1), nullptr), + new TreeNode(1, nullptr, new TreeNode(4)), + new TreeNode(4, new TreeNode(2), nullptr), + new TreeNode(2, nullptr, new TreeNode(3))}; + cout << Solution().canMerge(trees2) << endl; + // 5 + + return 0; +} diff --git a/1501-2000/1932-Merge-BSTs-to-Create-Single-BST/cpp-1932/main2.cpp b/1501-2000/1932-Merge-BSTs-to-Create-Single-BST/cpp-1932/main2.cpp new file mode 100644 index 00000000..9f3009ac --- /dev/null +++ b/1501-2000/1932-Merge-BSTs-to-Create-Single-BST/cpp-1932/main2.cpp @@ -0,0 +1,135 @@ +/// Source : https://leetcode.com/problems/merge-bsts-to-create-single-bst/ +/// Author : liuyubobobo +/// Time : 2021-07-11 + +#include +#include +#include +#include +#include +#include + +using namespace std; + + +/// BFS +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// 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* canMerge(vector& trees) { + + unordered_map f; + unordered_map roots; + for(TreeNode* node: trees){ + dfs(node, f); + roots[node->val] = node; + } + + int cnt = 0; + for(const pair& p: f){ + if(p.second > 2) return nullptr; + else if(p.second == 2) cnt ++; + } + + if(cnt + 1 != trees.size()) return nullptr; + + TreeNode* root = nullptr; + for(TreeNode* node: trees) + if(f[node->val] == 1){ + if(root) return nullptr; + root = node; + } + + root = build(roots, root); + + if(!root) return nullptr; + return is_bst(root, INT_MIN, INT_MAX) ? root : nullptr; + } + +private: + TreeNode* build(unordered_map& roots, TreeNode* root){ + + queue q; + if(is_leaf(root)) q.push(root); + else{ + if(root->left) q.push(root->left); + if(root->right) q.push(root->right); + } + roots.erase(root->val); + + while(!q.empty()){ + TreeNode* cur = q.front(); + q.pop(); + + if(roots.count(cur->val)){ + TreeNode* node = roots[cur->val]; + cur->left = node->left; + cur->right = node->right; + + if(cur->left) q.push(cur->left); + if(cur->right) q.push(cur->right); + + roots.erase(cur->val); + } + } + return roots.empty() ? root : nullptr; + } + + bool is_bst(TreeNode* node, int a, int b){ + + if(!node) return true; + + if(!(a <= node->val && node->val <= b)) return false; + + return is_bst(node->left, a, node->val - 1) && is_bst(node->right, node->val + 1, b); + } + + void dfs(TreeNode* node, unordered_map& f){ + + if(!node) return; + + f[node->val] ++; + + dfs(node->left, f); + dfs(node->right, f); + } + + bool is_leaf(TreeNode* node){ + return !node->left && !node->right; + } +}; + + +int main() { + + vector trees0 = {new TreeNode(7)}; + cout << Solution().canMerge(trees0) << endl; + // 7 + + vector trees1 = {new TreeNode(1, nullptr, new TreeNode(3)), + new TreeNode(3, new TreeNode(1), nullptr), + new TreeNode(4, new TreeNode(2), nullptr)}; + cout << Solution().canMerge(trees1) << endl; + // null + + vector trees2 = {new TreeNode(5, new TreeNode(1), nullptr), + new TreeNode(1, nullptr, new TreeNode(4)), + new TreeNode(4, new TreeNode(2), nullptr), + new TreeNode(2, nullptr, new TreeNode(3))}; + cout << Solution().canMerge(trees2) << endl; + // 5 + + return 0; +} diff --git a/1501-2000/1933-Check-If-a-String-is-Decomposble-to-Value-Equal-Substrings/cpp-1933/CMakeLists.txt b/1501-2000/1933-Check-If-a-String-is-Decomposble-to-Value-Equal-Substrings/cpp-1933/CMakeLists.txt new file mode 100644 index 00000000..5005561c --- /dev/null +++ b/1501-2000/1933-Check-If-a-String-is-Decomposble-to-Value-Equal-Substrings/cpp-1933/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_5817) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_5817 main.cpp) \ No newline at end of file diff --git a/1501-2000/1933-Check-If-a-String-is-Decomposble-to-Value-Equal-Substrings/cpp-1933/main.cpp b/1501-2000/1933-Check-If-a-String-is-Decomposble-to-Value-Equal-Substrings/cpp-1933/main.cpp new file mode 100644 index 00000000..2ab920fa --- /dev/null +++ b/1501-2000/1933-Check-If-a-String-is-Decomposble-to-Value-Equal-Substrings/cpp-1933/main.cpp @@ -0,0 +1,36 @@ +/// Source : https://leetcode.com/problems/check-if-a-string-is-decomposble-to-value-equal-substrings/ +/// Author : liuyubobobo +/// Time : 2021-07-02 + +#include + +using namespace std; + + +/// Split +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + bool isDecomposable(string s) { + + int two = 0; + for(int start = 0, i = 1; i <= s.size(); i ++) + if(i == s.size() || s[i] != s[start]){ + int len = i - start; + if(len % 3 == 1) return false; + if(len % 3 == 2) two ++; + if(two > 1) return false; + + start = i; + i = start; + } + return two == 1; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1935-Maximum-Number-of-Words-You-Can-Type/cpp-1935/CMakeLists.txt b/1501-2000/1935-Maximum-Number-of-Words-You-Can-Type/cpp-1935/CMakeLists.txt new file mode 100644 index 00000000..56912ed2 --- /dev/null +++ b/1501-2000/1935-Maximum-Number-of-Words-You-Can-Type/cpp-1935/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1501-2000/1935-Maximum-Number-of-Words-You-Can-Type/cpp-1935/main.cpp b/1501-2000/1935-Maximum-Number-of-Words-You-Can-Type/cpp-1935/main.cpp new file mode 100644 index 00000000..ce45d58b --- /dev/null +++ b/1501-2000/1935-Maximum-Number-of-Words-You-Can-Type/cpp-1935/main.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/maximum-number-of-words-you-can-type/ +/// Author : liuyubobobo +/// Time : 2021-07-17 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(|text| + |broken|) +/// Space Complexity: O(1) +class Solution { +public: + int canBeTypedWords(string text, string brokenLetters) { + + vector broken(26, false); + for(char c: brokenLetters) broken[c - 'a'] = true; + + int res = 0; + for(int start = 0, i = 1; i <= text.size(); i ++) + if(i == text.size() || text[i] == ' '){ + string word = text.substr(start, i - start); + if(ok(word, broken)) res ++; + + start = i + 1; + i = start; + } + return res; + } + +private: + bool ok(const string& word, const vector& broken){ + + for(char c: word) + if(broken[c - 'a']) + return false; + return true; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1936-Add-Minimum-Number-of-Rungs/cpp-1936/CMakeLists.txt b/1501-2000/1936-Add-Minimum-Number-of-Rungs/cpp-1936/CMakeLists.txt new file mode 100644 index 00000000..358dfef4 --- /dev/null +++ b/1501-2000/1936-Add-Minimum-Number-of-Rungs/cpp-1936/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1501-2000/1936-Add-Minimum-Number-of-Rungs/cpp-1936/main.cpp b/1501-2000/1936-Add-Minimum-Number-of-Rungs/cpp-1936/main.cpp new file mode 100644 index 00000000..f3d5688d --- /dev/null +++ b/1501-2000/1936-Add-Minimum-Number-of-Rungs/cpp-1936/main.cpp @@ -0,0 +1,49 @@ +/// Source : https://leetcode.com/problems/add-minimum-number-of-rungs/ +/// Author : liuyubobobo +/// Time : 2021-07-17 + +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int addRungs(vector& rungs, int dist) { + + + int res = 0; + for(int i = 0; i < rungs.size(); i ++){ + int d = rungs[i] - (i == 0 ? 0 : rungs[i - 1]); + if(d <= dist) continue; + res += (d / dist + !!(d % dist)) - 1; + } + return res; + } +}; + + +int main() { + + vector a1 = {1, 3, 5, 10}; + cout << Solution().addRungs(a1, 2) << endl; + // 2 + + vector a2 = {3, 6, 8, 10}; + cout << Solution().addRungs(a2, 3) << endl; + // 0 + + vector a3 = {3, 4, 6, 7}; + cout << Solution().addRungs(a3, 2) << endl; + // 1 + + vector a4 = {5}; + cout << Solution().addRungs(a4, 10) << endl; + // 0 + + return 0; +} diff --git a/1501-2000/1937-Maximum-Number-of-Points-with-Cost/cpp-1937/CMakeLists.txt b/1501-2000/1937-Maximum-Number-of-Points-with-Cost/cpp-1937/CMakeLists.txt new file mode 100644 index 00000000..ad5a4184 --- /dev/null +++ b/1501-2000/1937-Maximum-Number-of-Points-with-Cost/cpp-1937/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1501-2000/1937-Maximum-Number-of-Points-with-Cost/cpp-1937/main.cpp b/1501-2000/1937-Maximum-Number-of-Points-with-Cost/cpp-1937/main.cpp new file mode 100644 index 00000000..afd1740e --- /dev/null +++ b/1501-2000/1937-Maximum-Number-of-Points-with-Cost/cpp-1937/main.cpp @@ -0,0 +1,71 @@ +/// Source : https://leetcode.com/problems/maximum-number-of-points-with-cost/ +/// Author : liuyubobobo +/// Time : 2021-07-17 + +#include +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(R * C) +/// Space Complexity: O(C) +class Solution { + +public: + long long maxPoints(vector>& points) { + + int R = points.size(), C = points[0].size(); + + vector dp(C, 0); + for(int j = 0; j < C; j ++) dp[j] = points[0][j]; + + vector left(C), right(C); + for(int r = 1; r < R; r ++){ + + for(int j = 0; j < C; j ++) + left[j] = dp[j] + j, right[j] = dp[j] - j; + for(int j = 1; j < C; j ++) + left[j] = max(left[j], left[j - 1]); + for(int j = C - 2; j >= 0; j --) + right[j] = max(right[j], right[j + 1]); + + for(int j = 0; j < C; j ++) + dp[j] = (long long)points[r][j] + max(left[j] - j, right[j] + j); + } + + return *max_element(dp.begin(), dp.end()); + } +}; + + +int main() { + + vector> points1 = { + {1, 2, 3}, + {1, 5, 1}, + {3, 1, 1} + }; + cout << Solution().maxPoints(points1) << endl; + // 9 + + vector> points2 = { + {1, 5}, + {2, 3}, + {4, 2} + }; + cout << Solution().maxPoints(points2) << endl; + // 11 + + vector> points3 = { + {1}, + {2}, + {4} + }; + cout << Solution().maxPoints(points3) << endl; + // 7 + + return 0; +} diff --git a/1501-2000/1938-Maximum-Genetic-Difference-Query/cpp-1938/CMakeLists.txt b/1501-2000/1938-Maximum-Genetic-Difference-Query/cpp-1938/CMakeLists.txt new file mode 100644 index 00000000..8e6ea4a2 --- /dev/null +++ b/1501-2000/1938-Maximum-Genetic-Difference-Query/cpp-1938/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) \ No newline at end of file diff --git a/1501-2000/1938-Maximum-Genetic-Difference-Query/cpp-1938/main.cpp b/1501-2000/1938-Maximum-Genetic-Difference-Query/cpp-1938/main.cpp new file mode 100644 index 00000000..5c1d1f70 --- /dev/null +++ b/1501-2000/1938-Maximum-Genetic-Difference-Query/cpp-1938/main.cpp @@ -0,0 +1,157 @@ +/// Source : https://leetcode.com/problems/maximum-genetic-difference-query/ +/// Author : liuyubobobo +/// Time : 2021-07-17 + +#include +#include +#include +#include + +using namespace std; + + +/// Offline Query + Trie +/// Time Complexity: O(nlog(maxv)) +/// Space Complexity: O(nlog(maxv)) +class Trie { + +private: + class Node{ + + public: + vector next; + int sz; + + Node() : next(2, nullptr), sz(0) {}; + }; + + int L; + Node* root; + +public: + Trie() : root(new Node()){} + + void setL(int L){ + this->L = L; + } + + void insert(int x) { + + Node* cur = root; + cur->sz ++; + for(int i = 0; i < L; i ++){ + int e = !!(x & (1 << (L - i - 1))); + if(cur->next[e] == nullptr) + cur->next[e] = new Node(); + cur = cur->next[e]; + cur->sz ++; + } + } + + void erase(int x) { + + Node* cur = root; + cur->sz --; + for(int i = 0; i < L; i ++){ + int e = !!(x & (1 << (L - i - 1))); + cur = cur->next[e]; + cur->sz --; + } + } + + int query(int x){ + + Node* cur = root; + int res = 0; + for(int i = 0; i < L; i ++){ + int e = !!(x & (1 << (L - i - 1))); + if(cur->next[1 - e] && cur->next[1 - e]->sz){ + res = res * 2 + 1; + cur = cur->next[1 - e]; + } + else{ + res = res * 2; + cur = cur->next[e]; + } + } + return res; + } +}; + +class Solution { + +private: + Trie trie; + +public: + vector maxGeneticDifference(vector& parents, vector>& queries) { + + int n = parents.size(); + + vector> g(n); + int root = -1; + for(int i = 0; i < n; i ++){ + if(parents[i] == -1) + root = i; + else + g[parents[i]].push_back(i); + } + assert(root != -1); + + int maxv = n; + vector>> queries_map(n); // node -> {val, index} + for(int i = 0; i < queries.size(); i ++) { + queries_map[queries[i][0]].push_back({queries[i][1], i}); + maxv = max(maxv, queries[i][1]); + } + + int L = 0; + while(maxv) maxv >>= 1, L ++; + trie.setL(L); + + vector res(queries.size()); + dfs(n, g, root, queries_map, res); + return res; + } + +private: + void dfs(int n, const vector>& g, int u, + const vector>>& queries_map, vector& res){ + + trie.insert(u); + for(const pair& p: queries_map[u]){ + int val = p.first, index = p.second; + res[index] = trie.query(val); + } + + for(int v: g[u]) + dfs(n, g, v, queries_map, res); + + trie.erase(u); + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << ' '; cout << endl; +} + +int main() { + + vector parents1 = {-1, 0, 1, 1}; + vector> queris1 = {{0, 2}, {3, 2}, {2, 5}}; + print_vec(Solution().maxGeneticDifference(parents1, queris1)); + // 2 3 7 + + vector parents2 = {3,7,-1,2,0,7,0,2}; + vector> queris2 = {{4, 6}, {1, 15}, {0, 5}}; + print_vec(Solution().maxGeneticDifference(parents2, queris2)); + // 6 14 7 + + vector parents3 = {-1,0,0,0,3}; + vector> queris3 = {{4, 6}, {0, 0}, {0, 3}, {1, 8}, {4, 0}}; + print_vec(Solution().maxGeneticDifference(parents3, queris3)); + // 6 0 3 9 4 + + return 0; +} diff --git a/1501-2000/1940-Longest-Common-Subsequence-Between-Sorted-Arrays/cpp-1940/CMakeLists.txt b/1501-2000/1940-Longest-Common-Subsequence-Between-Sorted-Arrays/cpp-1940/CMakeLists.txt new file mode 100644 index 00000000..a81ddc5e --- /dev/null +++ b/1501-2000/1940-Longest-Common-Subsequence-Between-Sorted-Arrays/cpp-1940/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_5818) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_5818 main.cpp) \ No newline at end of file diff --git a/1501-2000/1940-Longest-Common-Subsequence-Between-Sorted-Arrays/cpp-1940/main.cpp b/1501-2000/1940-Longest-Common-Subsequence-Between-Sorted-Arrays/cpp-1940/main.cpp new file mode 100644 index 00000000..d647e9c9 --- /dev/null +++ b/1501-2000/1940-Longest-Common-Subsequence-Between-Sorted-Arrays/cpp-1940/main.cpp @@ -0,0 +1,41 @@ +/// Source : https://leetcode.com/problems/longest-common-subsequence-between-sorted-arrays/ +/// Author : liuyubobobo +/// Time : 2021-07-02 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n * m) +/// Space Complexity: O(m) +class Solution { +public: + vector longestCommomSubsequence(vector>& arrays) { + + vector res = arrays[0]; + for(int i = 1; i < arrays.size(); i ++) + res = get_lcs(res, arrays[i]); + return res; + } + +private: + vector get_lcs(const vector& a, const vector& b){ + + vector res; + int i = 0, j = 0; + while(i < a.size() && j < b.size()) + if(a[i] == b[j]) res.push_back(a[i]), i ++, j ++; + else if(a[i] < b[j]) i ++; + else j ++; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1941-Check-if-All-Characters-Have-Equal-Number-of-Occurrences/cpp-1941/CMakeLists.txt b/1501-2000/1941-Check-if-All-Characters-Have-Equal-Number-of-Occurrences/cpp-1941/CMakeLists.txt new file mode 100644 index 00000000..4056cb73 --- /dev/null +++ b/1501-2000/1941-Check-if-All-Characters-Have-Equal-Number-of-Occurrences/cpp-1941/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_1941) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1941 main.cpp) \ No newline at end of file diff --git a/1501-2000/1941-Check-if-All-Characters-Have-Equal-Number-of-Occurrences/cpp-1941/main.cpp b/1501-2000/1941-Check-if-All-Characters-Have-Equal-Number-of-Occurrences/cpp-1941/main.cpp new file mode 100644 index 00000000..58d23dbf --- /dev/null +++ b/1501-2000/1941-Check-if-All-Characters-Have-Equal-Number-of-Occurrences/cpp-1941/main.cpp @@ -0,0 +1,24 @@ +#include +#include +#include + +using namespace std; + + +class Solution { +public: + bool areOccurrencesEqual(string s) { + + vector f(26, 0); + for(char c: s) f[c - 'a'] ++; + + set set; + for(int e: f) if(e) set.insert(e); + return set.size() == 1; + } +}; + +int main() { + + return 0; +} diff --git a/1501-2000/1942-The-Number-of-the-Smallest-Unoccupied-Chair/cpp-1942/CMakeLists.txt b/1501-2000/1942-The-Number-of-the-Smallest-Unoccupied-Chair/cpp-1942/CMakeLists.txt new file mode 100644 index 00000000..d43e46be --- /dev/null +++ b/1501-2000/1942-The-Number-of-the-Smallest-Unoccupied-Chair/cpp-1942/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_1942) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1942 main.cpp) \ No newline at end of file diff --git a/1501-2000/1942-The-Number-of-the-Smallest-Unoccupied-Chair/cpp-1942/main.cpp b/1501-2000/1942-The-Number-of-the-Smallest-Unoccupied-Chair/cpp-1942/main.cpp new file mode 100644 index 00000000..78e85dd1 --- /dev/null +++ b/1501-2000/1942-The-Number-of-the-Smallest-Unoccupied-Chair/cpp-1942/main.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/the-number-of-the-smallest-unoccupied-chair/ +/// Author : liuyubobobo +/// Time : 2021-07-24 + +#include +#include +#include + +using namespace std; + + +/// Sweep lines +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + int smallestChair(vector>& times, int targetFriend) { + + int n = times.size(); + vector> v; // (time, (-1 leave or 1 enter)), index + for(int i = 0; i < n; i ++) + v.push_back({times[i][0], 1, i}), + v.push_back({times[i][1], -1, i}); + + sort(v.begin(), v.end()); + + vector chairs(n, -1); + set available; + for(int i = 0; i < n; i ++) available.insert(i); + for(const vector& p: v){ + int t = p[0], action = p[1], index = p[2]; + if(action == -1){ + assert(chairs[index] != -1 && !available.count(chairs[index])); + available.insert(chairs[index]); + } + else{ + chairs[index] = *available.begin(); + available.erase(available.begin()); + } + } + + return chairs[targetFriend]; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1943-Describe-the-Painting/cpp-1943/CMakeLists.txt b/1501-2000/1943-Describe-the-Painting/cpp-1943/CMakeLists.txt new file mode 100644 index 00000000..0ea66415 --- /dev/null +++ b/1501-2000/1943-Describe-the-Painting/cpp-1943/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_1943) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1943 main.cpp) \ No newline at end of file diff --git a/1501-2000/1943-Describe-the-Painting/cpp-1943/main.cpp b/1501-2000/1943-Describe-the-Painting/cpp-1943/main.cpp new file mode 100644 index 00000000..e33ea2ab --- /dev/null +++ b/1501-2000/1943-Describe-the-Painting/cpp-1943/main.cpp @@ -0,0 +1,81 @@ +/// Source : https://leetcode.com/problems/describe-the-painting/ +/// Author : liuyubobobo +/// Time : 2021-07-24 + +#include +#include +#include + +using namespace std; + + +/// Diff Array +/// Time Compelxity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + vector> splitPainting(vector>& segments) { + + int n = 0; + for(const vector& seg: segments) + n = max(n, seg[1] - 1); + n ++; + + set boundaries; + vector diff(n + 1, 0ll); + for(const vector& seg: segments){ + int a = seg[0] - 1, b = seg[1] - 1; + diff[a] += seg[2], diff[b] -= seg[2]; + boundaries.insert(a); + boundaries.insert(b); + } + + vector res(n - 1, diff[0]); + long long sum = diff[0]; + for(int i = 1; i + 1 < n; i ++){ + sum += diff[i]; + res[i] = sum; + } + + vector bv(boundaries.begin(), boundaries.end()); +// for(int b: bv) cout << b << ' '; cout << endl; + + vector> ret; + for(int i = 1; i < boundaries.size(); i ++) + if(res[bv[i - 1]]) + ret.push_back({bv[i - 1] + 1, bv[i] + 1, res[bv[i - 1]]}); + + return ret; + } +}; + + +void print_vec(const vector>& res){ + for(const vector& row: res){ + cout << '{'; + for(long long e: row) cout << e << ' '; + cout << "} "; + } + cout << endl; +} + +int main() { + + vector> segments1 = {{1, 4, 5}, {4, 7, 7}, {1, 7, 9}}; + print_vec(Solution().splitPainting(segments1)); + // {1, 4, 14}, {4, 7, 16} + + vector> segments2 = {{1, 7, 9}, {6, 8, 15}, {8, 10, 7}}; + print_vec(Solution().splitPainting(segments2)); + // {1, 6, 9}, {6, 7, 24}, {7, 8, 15}, {8, 10, 7} + + vector> segments3 = {{1, 4, 5}, {1, 4, 7}, {4, 7, 1}, {4, 7, 11}}; + print_vec(Solution().splitPainting(segments3)); + // {1, 4, 12}, {4, 7, 12} + + vector> segments4 = {{4,16,12},{9,10,15},{18,19,13},{3,13,20},{12,16,3},{2,10,10},{3,11,4},{13,16,6}}; + print_vec(Solution().splitPainting(segments4)); + // {1, 4, 12}, {4, 7, 12} + + return 0; +} diff --git a/1501-2000/1944-Number-of-Visible-People-in-a-Queue/cpp-1944/CMakeLists.txt b/1501-2000/1944-Number-of-Visible-People-in-a-Queue/cpp-1944/CMakeLists.txt new file mode 100644 index 00000000..7f0437f9 --- /dev/null +++ b/1501-2000/1944-Number-of-Visible-People-in-a-Queue/cpp-1944/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_1944) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1944 main.cpp) \ No newline at end of file diff --git a/1501-2000/1944-Number-of-Visible-People-in-a-Queue/cpp-1944/main.cpp b/1501-2000/1944-Number-of-Visible-People-in-a-Queue/cpp-1944/main.cpp new file mode 100644 index 00000000..25be1c60 --- /dev/null +++ b/1501-2000/1944-Number-of-Visible-People-in-a-Queue/cpp-1944/main.cpp @@ -0,0 +1,84 @@ +/// Source : https://leetcode.com/problems/number-of-visible-people-in-a-queue/ +/// Author : liuyubobobo +/// Time : 2021-07-24 + +#include +#include +#include + +using namespace std; + + +/// Mono Stack + Bknary Search +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + vector canSeePersonsCount(vector& heights) { + + int n = heights.size(); + + vector stack; + vector res(n, 0); + if(n == 1) return res; + + stack.push_back(heights.back()); + for(int i = n - 2; i >= 0; i --){ +// int x = upper(stack, heights[i]); +// if(x == -1) res[i] = stack.size(); +// else res[i] = stack.size() - x; + + if(!stack.empty() && heights[i] > stack[0]) + res[i] = stack.size(); + else + res[i] = stack.size() - upper(stack, heights[i]); + + while(!stack.empty() && stack.back() < heights[i]) + stack.pop_back(); + stack.push_back(heights[i]); + } + return res; + } + +private: + int upper(const vector& v, int t){ + +// for(int e: v) cout << e << ' '; cout << '\n'; + auto iter = upper_bound(v.rbegin(), v.rend(), t); + if(iter == v.rend()){ +// cout << "no solution" << endl; + return -1; + } + +// cout << "find " << t << " get " << *iter << endl; +// cout << "index = " << (iter - v.rbegin()) << endl; + int index = iter - v.rbegin(); + return v.size() - 1 - index; + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << ' '; cout << endl; +} + +int main() { + + vector heights1 = {10, 6, 8, 5, 11, 9}; + print_vec(Solution().canSeePersonsCount(heights1)); + // 3 1 2 1 1 0 + + vector heights2 = {5, 1, 2, 3, 10}; + print_vec(Solution().canSeePersonsCount(heights2)); + // 4 1 1 1 0 + + vector heights3 = {3, 1, 5, 8, 6}; + print_vec(Solution().canSeePersonsCount(heights3)); + // 2 1 1 1 0 + + vector heights4 = {2, 10, 3, 4, 8}; + print_vec(Solution().canSeePersonsCount(heights4)); + // 1 3 1 1 0 + + return 0; +} diff --git a/1501-2000/1945-Sum-of-Digits-of-String-After-Convert/cpp-1945/CMakeLists.txt b/1501-2000/1945-Sum-of-Digits-of-String-After-Convert/cpp-1945/CMakeLists.txt new file mode 100644 index 00000000..56912ed2 --- /dev/null +++ b/1501-2000/1945-Sum-of-Digits-of-String-After-Convert/cpp-1945/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/1501-2000/1945-Sum-of-Digits-of-String-After-Convert/cpp-1945/main.cpp b/1501-2000/1945-Sum-of-Digits-of-String-After-Convert/cpp-1945/main.cpp new file mode 100644 index 00000000..7e708908 --- /dev/null +++ b/1501-2000/1945-Sum-of-Digits-of-String-After-Convert/cpp-1945/main.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/sum-of-digits-of-string-after-convert/ +/// Author : liuyubobobo +/// Time : 2021-07-24 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(k * |s|) +/// Space Complexity: O(|s|) +class Solution { +public: + int getLucky(string s, int k) { + + string t = ""; + for(char c: s) + t += to_string(c - 'a' + 1); +// cout << res << endl; + + int sum = 0; + while(k --){ + sum = 0; + for(char c: t) sum += (c - '0'); + t = to_string(sum); + } + return sum; + } +}; + + +int main() { + + cout << Solution().getLucky("iiii", 1) << endl; + // 36 + + cout << Solution().getLucky("leetcode", 2) << endl; + // 6 + + cout << Solution().getLucky("zbax", 2) << endl; + // 8 + + return 0; +} diff --git a/1501-2000/1946-Largest-Number-After-Mutating-Substring/cpp-1946/CMakeLists.txt b/1501-2000/1946-Largest-Number-After-Mutating-Substring/cpp-1946/CMakeLists.txt new file mode 100644 index 00000000..358dfef4 --- /dev/null +++ b/1501-2000/1946-Largest-Number-After-Mutating-Substring/cpp-1946/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/1501-2000/1946-Largest-Number-After-Mutating-Substring/cpp-1946/main.cpp b/1501-2000/1946-Largest-Number-After-Mutating-Substring/cpp-1946/main.cpp new file mode 100644 index 00000000..9360adbf --- /dev/null +++ b/1501-2000/1946-Largest-Number-After-Mutating-Substring/cpp-1946/main.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/largest-number-after-mutating-substring/ +/// Author : liuyubobobo +/// Time : 2021-07-24 + +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + string maximumNumber(string num, vector& change) { + + bool start = false; + for(char& c: num) + if(change[c - '0'] > c - '0'){ + start = true; + c = (char)('0' + change[c - '0']); + } + else if(change[c - '0'] == c - '0') continue; + else if(start) break; + return num; + } +}; + + +int main() { + + vector change1 = {9,8,5,0,3,6,4,2,6,8}; + cout << Solution().maximumNumber("132", change1) << endl; + // 832 + + vector change2 = {9,4,3,5,7,2,1,9,0,6}; + cout << Solution().maximumNumber("021", change2) << endl; + // 934 + + vector change3 = {1,4,7,5,3,2,5,6,9,4}; + cout << Solution().maximumNumber("5", change3) << endl; + // 5 + + vector change4 = {0,9,2,3,3,2,5,5,5,5}; + cout << Solution().maximumNumber("334111", change4) << endl; + // 334999 + + return 0; +} diff --git a/1501-2000/1947-Maximum-Compatibility-Score-Sum/cpp-1947/CMakeLists.txt b/1501-2000/1947-Maximum-Compatibility-Score-Sum/cpp-1947/CMakeLists.txt new file mode 100644 index 00000000..ad5a4184 --- /dev/null +++ b/1501-2000/1947-Maximum-Compatibility-Score-Sum/cpp-1947/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1501-2000/1947-Maximum-Compatibility-Score-Sum/cpp-1947/main.cpp b/1501-2000/1947-Maximum-Compatibility-Score-Sum/cpp-1947/main.cpp new file mode 100644 index 00000000..cf9161ab --- /dev/null +++ b/1501-2000/1947-Maximum-Compatibility-Score-Sum/cpp-1947/main.cpp @@ -0,0 +1,61 @@ +/// Source : https://leetcode.com/problems/maximum-compatibility-score-sum/ +/// Author : liuyubobobo +/// Time : 2021-07-24 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(m^2 + m! * n) +/// Space Complexity: O(m^2) +class Solution { +public: + int maxCompatibilitySum(vector>& students, vector>& mentors) { + + int n = students[0].size(), m = students.size(); + + vector> scores(m, vector(m)); + for(int i = 0; i < m; i ++) + for(int j = 0; j < m; j ++) + scores[i][j] = get_score(students[i], mentors[j]); + + vector p(m, 0); + for(int i = 1; i < m; i ++) p[i] = i; + + int max_res = 0; + do{ + int tres = 0; + for(int i = 0; i < m; i ++) + tres += scores[p[i]][i]; + max_res = max(max_res, tres); + }while(next_permutation(p.begin(), p.end())); + return max_res; + } + +private: + int get_score(const vector& a, const vector& b){ + int res = 0; + for(int i = 0; i < a.size(); i ++) + res += (a[i] == b[i]); + return res; + } +}; + + +int main() { + + vector> students1 = {{1,1,0},{1,0,1},{0,0,1}}; + vector> mentors1 = {{1,0,0},{0,0,1},{1,1,0}}; + cout << Solution().maxCompatibilitySum(students1, mentors1) << endl; + // 8 + + vector> students2 = {{0,0},{0,0},{0,0}}; + vector> mentors2 = {{1,1},{1,1},{1,1}}; + cout << Solution().maxCompatibilitySum(students2, mentors2) << endl; + // 0 + + return 0; +} diff --git a/1501-2000/1948-Delete-Duplicate-Folders-in-System/cpp-1948/CMakeLists.txt b/1501-2000/1948-Delete-Duplicate-Folders-in-System/cpp-1948/CMakeLists.txt new file mode 100644 index 00000000..8700daa5 --- /dev/null +++ b/1501-2000/1948-Delete-Duplicate-Folders-in-System/cpp-1948/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main2.cpp) \ No newline at end of file diff --git a/1501-2000/1948-Delete-Duplicate-Folders-in-System/cpp-1948/main.cpp b/1501-2000/1948-Delete-Duplicate-Folders-in-System/cpp-1948/main.cpp new file mode 100644 index 00000000..37f115e5 --- /dev/null +++ b/1501-2000/1948-Delete-Duplicate-Folders-in-System/cpp-1948/main.cpp @@ -0,0 +1,185 @@ +/// Source : https://leetcode.com/problems/delete-duplicate-folders-in-system/ +/// Author : liuyubobobo +/// Time : 2021-07-24 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// Tree Encoding +/// Delete in String and construct the new tree based on string +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +private: + class Node{ + + public: + string desc; + map next; + + Node(const string& desc) : desc(desc){}; + }; + + Node* root; + +public: + vector> deleteDuplicateFolder(vector>& paths) { + + root = new Node("/"); + for(const vector& path: paths) + add(root, path); + + map> sub_structure; + string tree_s = dfs(root, sub_structure); + + vector del_vec; + for(const pair>& p: sub_structure) + if(p.second.size() > 1){ + for(const string& del: p.second) del_vec.push_back(del); + } + + sort(del_vec.begin(), del_vec.end(), [](const string& a, const string& b){ + if(a.size() != b.size()) return a.size() > b.size(); + return a < b; + }); + + for(const string& del: del_vec) del_folder(tree_s, del); + del_folder(tree_s, "()"); + +// cout << tree_s << endl; + vector right(tree_s.size(), -1); + stack stack; + for(int i = 0; i < tree_s.size(); i ++) + if(tree_s[i] == '(') stack.push(i); + else if(tree_s[i] == ')') right[stack.top()] = i, stack.pop(); +// for(int e: right) cout << e << ' '; cout << endl; + + Node* new_root = build_tree(tree_s, 0, tree_s.size() - 1, right); + + vector> res; + for(const pair& p: new_root->next){ + vector path; + dfs_res(p.second, path, res); + } + return res; + } + +private: + void dfs_res(Node* node, vector& path, vector>& res){ + + path.push_back(node->desc); + res.push_back(path); + + for(const pair& p: node->next) + dfs_res(p.second, path, res); + path.pop_back(); + } + + Node* build_tree(const string& s, int l, int r, const vector& right){ + + if(l > r) return nullptr; + + assert(s[l] != '('); + + int i = l; + for(; i <= r; i ++) + if(s[i] == '(') break; + + Node* ret = new Node(s.substr(l, i - l)); + + while(i <= r){ + assert(s[i] == '('); + int j = right[i]; + Node* node = build_tree(s, i + 1, j - 1, right); + ret->next[node->desc] = node; + + i = j + 1; + } + return ret; + } + + void del_folder(string& s, const string& t){ + + while(true){ + int pos = s.find(t); + if(pos == string::npos) return; + s = s.substr(0, pos) + s.substr(pos + t.size()); + } + } + + string dfs(Node* node, map>& sub_structure){ + + if(node->next.size() == 0){ + return node->desc; + } + + string ret = ""; + for(const pair& p: node->next){ + string s = p.first; + Node* nextnode = p.second; + ret += "(" + dfs(nextnode, sub_structure) + ")"; + } + +// cout << "folder structure : " << node->desc << " : "; +// cout << ret << endl; + string the_folder_s = node->desc + ret; + + sub_structure[ret].insert(the_folder_s); + + return the_folder_s; + } + + void add(Node* root, const vector& path){ + + Node* cur = root; + for(const string& s: path){ + if(!cur->next.count(s)) + cur->next[s] = new Node(s); + cur = cur->next[s]; + } + } +}; + + +void print_res(const vector>& v){ + if(v.empty()) cout << "empty" << endl; + for(const vector& e: v){ + for(const string& s: e) cout << s << ' '; cout << endl; + } +} + +int main() { + +// vector> paths1 = {{"a"},{"c"},{"d"}, {"a","b"},{"c","b"},{"d","a"}}; +// print_res(Solution().deleteDuplicateFolder(paths1)); +// +// cout << endl; +// +// vector> paths2 = {{"a"},{"c"},{"a","b"},{"c","b"},{"a","b","x"},{"a","b","x","y"},{"w"},{"w","y"}}; +// print_res(Solution().deleteDuplicateFolder(paths2)); +// +// cout << endl; +// +// vector> paths3 = {{"a","b"},{"c","d"},{"c"},{"a"}}; +// print_res(Solution().deleteDuplicateFolder(paths3)); +// +// cout << endl; +// +// vector> paths4 = {{"a"}, {"a","x"},{"a","x", "y"},{"a", "z"},{"b"}, {"b", "x"}, {"b","x", "y"}, {"b", "z"}}; +// print_res(Solution().deleteDuplicateFolder(paths4)); +// +// cout << endl; + + vector> paths5 = {{"a"}, {"a","x"},{"a","x", "y"},{"a", "z"},{"b"}, {"b", "x"}, {"b","x", "y"}, {"b", "z"}, {"b", "w"}}; + print_res(Solution().deleteDuplicateFolder(paths5)); + + cout << endl; + return 0; +} diff --git a/1501-2000/1948-Delete-Duplicate-Folders-in-System/cpp-1948/main2.cpp b/1501-2000/1948-Delete-Duplicate-Folders-in-System/cpp-1948/main2.cpp new file mode 100644 index 00000000..bbe9b5af --- /dev/null +++ b/1501-2000/1948-Delete-Duplicate-Folders-in-System/cpp-1948/main2.cpp @@ -0,0 +1,135 @@ +/// Source : https://leetcode.com/problems/delete-duplicate-folders-in-system/ +/// Author : liuyubobobo +/// Time : 2021-07-24 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// Tree Encoding +/// No need to delete in string +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +private: + class Node{ + + public: + string desc, sub_folder; + map next; + + Node(const string& desc) : desc(desc), sub_folder(""){}; + }; + + Node* root; + +public: + vector> deleteDuplicateFolder(vector>& paths) { + + root = new Node("/"); + for(const vector& path: paths) + add(root, path); + + map sub_structure; + string tree_s = dfs(root, sub_structure); + + vector> res; + for(const pair& p: root->next){ + vector path; + dfs_res(p.second, path, res, sub_structure); + } + return res; + } + +private: + void dfs_res(Node* node, vector& path, vector>& res, + map& sub_structure){ + + if(sub_structure[node->sub_folder] >= 2) return; + + path.push_back(node->desc); + res.push_back(path); + + for(const pair& p: node->next) + dfs_res(p.second, path, res, sub_structure); + path.pop_back(); + } + + string dfs(Node* node, map& sub_structure){ + + if(node->next.size() == 0){ + return node->desc; + } + + string ret = ""; + for(const pair& p: node->next){ + string s = p.first; + Node* nextnode = p.second; + ret += "(" + dfs(nextnode, sub_structure) + ")"; + } + +// cout << "folder structure : " << node->desc << " : "; +// cout << ret << endl; + + string the_folder_s = node->desc + ret; + + sub_structure[ret] ++; + + node->sub_folder = ret; + + return the_folder_s; + } + + void add(Node* root, const vector& path){ + + Node* cur = root; + for(const string& s: path){ + if(!cur->next.count(s)) + cur->next[s] = new Node(s); + cur = cur->next[s]; + } + } +}; + + +void print_res(const vector>& v){ + if(v.empty()) cout << "empty" << endl; + for(const vector& e: v){ + for(const string& s: e) cout << s << ' '; cout << endl; + } +} + +int main() { + +// vector> paths1 = {{"a"},{"c"},{"d"}, {"a","b"},{"c","b"},{"d","a"}}; +// print_res(Solution().deleteDuplicateFolder(paths1)); +// +// cout << endl; +// +// vector> paths2 = {{"a"},{"c"},{"a","b"},{"c","b"},{"a","b","x"},{"a","b","x","y"},{"w"},{"w","y"}}; +// print_res(Solution().deleteDuplicateFolder(paths2)); +// +// cout << endl; +// +// vector> paths3 = {{"a","b"},{"c","d"},{"c"},{"a"}}; +// print_res(Solution().deleteDuplicateFolder(paths3)); +// +// cout << endl; +// +// vector> paths4 = {{"a"}, {"a","x"},{"a","x", "y"},{"a", "z"},{"b"}, {"b", "x"}, {"b","x", "y"}, {"b", "z"}}; +// print_res(Solution().deleteDuplicateFolder(paths4)); +// +// cout << endl; + + vector> paths5 = {{"a"}, {"a","x"},{"a","x", "y"},{"a", "z"},{"b"}, {"b", "x"}, {"b","x", "y"}, {"b", "z"}, {"b", "w"}}; + print_res(Solution().deleteDuplicateFolder(paths5)); + + cout << endl; + return 0; +} diff --git a/1501-2000/1950-Maximum-of-Minimum-Values-in-All-Subarrays/cpp-1950/CMakeLists.txt b/1501-2000/1950-Maximum-of-Minimum-Values-in-All-Subarrays/cpp-1950/CMakeLists.txt new file mode 100644 index 00000000..cf1a3949 --- /dev/null +++ b/1501-2000/1950-Maximum-of-Minimum-Values-in-All-Subarrays/cpp-1950/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_5819) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_5819 main.cpp) \ No newline at end of file diff --git a/1501-2000/1950-Maximum-of-Minimum-Values-in-All-Subarrays/cpp-1950/main.cpp b/1501-2000/1950-Maximum-of-Minimum-Values-in-All-Subarrays/cpp-1950/main.cpp new file mode 100644 index 00000000..ad1ea0ec --- /dev/null +++ b/1501-2000/1950-Maximum-of-Minimum-Values-in-All-Subarrays/cpp-1950/main.cpp @@ -0,0 +1,88 @@ +/// Source : https://leetcode.com/problems/maximum-of-minimum-values-in-all-subarrays/ +/// Author : liuyubobobo +/// Time : 2021-07-02 + +#include +#include +#include + +using namespace std; + + +/// Mono Stack +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector findMaximums(vector& nums) { + + int n = nums.size(); + + stack stack; + vector left(n, -1); + stack.push(0); + for(int i = 1; i < n; i ++){ + while(!stack.empty() && nums[stack.top()] >= nums[i]) + stack.pop(); + left[i] = stack.empty() ? -1: stack.top(); + stack.push(i); + } +// for(int e: left) cout << e << ' '; cout << endl; + + while(!stack.empty()) stack.pop(); + + vector right(n, n); + stack.push(n - 1); + for(int i = n - 2; i >= 0; i --){ + while(!stack.empty() && nums[stack.top()] >= nums[i]) + stack.pop(); + right[i] = stack.empty() ? n: stack.top(); + stack.push(i); + } +// for(int e: right) cout << e << ' '; cout << endl; + + vector res(n, *min_element(nums.begin(), nums.end())); + for(int i = 0; i < n; i ++){ + int v = nums[i], d = right[i] - left[i] - 1; + res[d - 1] = max(res[d - 1], v); + } + + for(int i = n - 2; i >= 0; i --) + res[i] = max(res[i], res[i + 1]); + return res; + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << " "; cout << endl; +} + +int main() { + + vector nums1 = {0, 1, 2, 4}; + print_vec(Solution().findMaximums(nums1)); + // 4 2 1 0 + + vector nums2 = {10, 20, 50, 10}; + print_vec(Solution().findMaximums(nums2)); + // 50 20 10 10 + + vector nums3 = {10, 20, 10, 50, 10}; + print_vec(Solution().findMaximums(nums3)); + // 50 10 10 10 10 + + vector nums4 = {10, 2, 8, 3, 2, 7, 6, 4, 10, 8}; + print_vec(Solution().findMaximums(nums4)); + // 10,8,4,4,4,2,2,2,2,2 + + vector nums5 = {0, 9, 5, 7, 0, 1, 5, 4, 3}; + print_vec(Solution().findMaximums(nums5)); + // 9,5,5,1,0,0,0,0,0 + + vector nums6 = {1, 5, 5, 1}; + print_vec(Solution().findMaximums(nums6)); + // 5, 5, 1, 1 + + return 0; +} diff --git a/1501-2000/1952-Three-Divisors/cpp-1952/CMakeLists.txt b/1501-2000/1952-Three-Divisors/cpp-1952/CMakeLists.txt new file mode 100644 index 00000000..2ae8397c --- /dev/null +++ b/1501-2000/1952-Three-Divisors/cpp-1952/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/1501-2000/1952-Three-Divisors/cpp-1952/main.cpp b/1501-2000/1952-Three-Divisors/cpp-1952/main.cpp new file mode 100644 index 00000000..c3f8b66a --- /dev/null +++ b/1501-2000/1952-Three-Divisors/cpp-1952/main.cpp @@ -0,0 +1,32 @@ +/// Source : https://leetcode.com/problems/three-divisors/ +/// Author : liuyubobobo +/// Time : 2021-07-31 + +#include +#include + +using namespace std; + + +/// Divisor Number +/// Time Complexity: O(sqrt(n)) +/// Space Complexity: O(1) +class Solution { +public: + bool isThree(int n) { + + int cnt = 2; + for(int i = 2; i * i <= n; i ++) + if(n % i == 0){ + cnt ++; + cnt += i * i < n; + } + return cnt == 3; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1953-Maximum-Number-of-Weeks-for-Which-You-Can-Work/cpp-1953/CMakeLists.txt b/1501-2000/1953-Maximum-Number-of-Weeks-for-Which-You-Can-Work/cpp-1953/CMakeLists.txt new file mode 100644 index 00000000..3f98647f --- /dev/null +++ b/1501-2000/1953-Maximum-Number-of-Weeks-for-Which-You-Can-Work/cpp-1953/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/1501-2000/1953-Maximum-Number-of-Weeks-for-Which-You-Can-Work/cpp-1953/main.cpp b/1501-2000/1953-Maximum-Number-of-Weeks-for-Which-You-Can-Work/cpp-1953/main.cpp new file mode 100644 index 00000000..f4edc28f --- /dev/null +++ b/1501-2000/1953-Maximum-Number-of-Weeks-for-Which-You-Can-Work/cpp-1953/main.cpp @@ -0,0 +1,41 @@ +/// Source : https://leetcode.com/problems/maximum-number-of-weeks-for-which-you-can-work/ +/// Author : liuyubobobo +/// Time : 2021-07-31 + +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + long long numberOfWeeks(vector& milestones) { + + long long sum = 0ll, maxv = 0ll; + for(int e: milestones) + sum += e, maxv = max(maxv, (long long)e); + + sum -= maxv; + + if(sum >= maxv) return sum + maxv; + else return sum * 2ll + 1ll; + } +}; + + +int main() { + + vector milestones1 = {1, 2, 3}; + cout << Solution().numberOfWeeks(milestones1) << endl; + // 6 + + vector milestones2 = {5, 2, 1}; + cout << Solution().numberOfWeeks(milestones2) << endl; + // 7 + + return 0; +} diff --git a/1501-2000/1954-Minimum-Garden-Perimeter-to-Collect-Enough-Apples/cpp-1954/CMakeLists.txt b/1501-2000/1954-Minimum-Garden-Perimeter-to-Collect-Enough-Apples/cpp-1954/CMakeLists.txt new file mode 100644 index 00000000..cad75f71 --- /dev/null +++ b/1501-2000/1954-Minimum-Garden-Perimeter-to-Collect-Enough-Apples/cpp-1954/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/1501-2000/1954-Minimum-Garden-Perimeter-to-Collect-Enough-Apples/cpp-1954/main.cpp b/1501-2000/1954-Minimum-Garden-Perimeter-to-Collect-Enough-Apples/cpp-1954/main.cpp new file mode 100644 index 00000000..59c3fd9b --- /dev/null +++ b/1501-2000/1954-Minimum-Garden-Perimeter-to-Collect-Enough-Apples/cpp-1954/main.cpp @@ -0,0 +1,44 @@ +/// Source : https://leetcode.com/problems/minimum-garden-perimeter-to-collect-enough-apples/ +/// Author : liuyubobobo +/// Time : 2021-07-31 + +#include + +using namespace std; + + +/// Mathematics + Binary Search +/// Time Complexity: O(log(sqrt(n))) +/// Space Complexity: O(1) +class Solution { +public: + long long minimumPerimeter(long long neededApples) { + + long long l = 0, r = 100000; + while(l < r){ + long long mid = (l + r) / 2ll; + if(2ll * mid * (mid + 1ll) * (2ll * mid + 1) >= neededApples) + r = mid; + else + l = mid + 1ll; + } + return l * 8ll; + } +}; + + +int main() { + + cout << Solution().minimumPerimeter(1) << endl; + // 8 + + cout << Solution().minimumPerimeter(13) << endl; + // 16 + + cout << Solution().minimumPerimeter(1e9) << endl; + // 5040 + + cout << Solution().minimumPerimeter(1e15) << endl; + + return 0; +} diff --git a/1501-2000/1955-Count-Number-of-Special-Subsequences/cpp-1955/CMakeLists.txt b/1501-2000/1955-Count-Number-of-Special-Subsequences/cpp-1955/CMakeLists.txt new file mode 100644 index 00000000..a0d16fe6 --- /dev/null +++ b/1501-2000/1955-Count-Number-of-Special-Subsequences/cpp-1955/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) diff --git a/1501-2000/1955-Count-Number-of-Special-Subsequences/cpp-1955/main.cpp b/1501-2000/1955-Count-Number-of-Special-Subsequences/cpp-1955/main.cpp new file mode 100644 index 00000000..33d10097 --- /dev/null +++ b/1501-2000/1955-Count-Number-of-Special-Subsequences/cpp-1955/main.cpp @@ -0,0 +1,59 @@ +/// Source : https://leetcode.com/problems/count-number-of-special-subsequences/ +/// Author : liuyubobobo +/// Time : 2021-07-31 + +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +private: + long long MOD = 1e9 + 7; + +public: + int countSpecialSubsequences(vector& nums) { + + int n = nums.size(); + + vector> dp(3, vector(n, 0ll)); + dp[0][0] = nums[0] == 0; + for(int i = 1; i < n; i ++){ + dp[0][i] = dp[0][i - 1]; + if(nums[i] == 0) + dp[0][i] = (1ll + dp[0][i - 1] * 2ll) % MOD; + } + + for(int v = 1; v <= 2; v ++) + for(int i = 1; i < n; i ++){ + dp[v][i] = dp[v][i - 1]; + if(nums[i] == v) + dp[v][i] = (dp[v - 1][i - 1] + dp[v][i - 1] * 2ll) % MOD; + } + + return dp[2][n - 1]; + } +}; + + +int main() { + + vector nums1 = {0, 1, 2, 2}; + cout << Solution().countSpecialSubsequences(nums1) << endl; + // 3 + + vector nums2 = {2, 2, 0, 0}; + cout << Solution().countSpecialSubsequences(nums2) << endl; + // 0 + + vector nums3 = {0, 1, 2, 0, 1, 2}; + cout << Solution().countSpecialSubsequences(nums3) << endl; + // 7 + + return 0; +} diff --git a/1501-2000/1956-Minimum-Time-For-K-Viruses-to-Spread/cpp-1956/CMakeLists.txt b/1501-2000/1956-Minimum-Time-For-K-Viruses-to-Spread/cpp-1956/CMakeLists.txt new file mode 100644 index 00000000..611f2efb --- /dev/null +++ b/1501-2000/1956-Minimum-Time-For-K-Viruses-to-Spread/cpp-1956/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_5820) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_5820 main.cpp) \ No newline at end of file diff --git a/1501-2000/1956-Minimum-Time-For-K-Viruses-to-Spread/cpp-1956/main.cpp b/1501-2000/1956-Minimum-Time-For-K-Viruses-to-Spread/cpp-1956/main.cpp new file mode 100644 index 00000000..2bea1200 --- /dev/null +++ b/1501-2000/1956-Minimum-Time-For-K-Viruses-to-Spread/cpp-1956/main.cpp @@ -0,0 +1,49 @@ +/// Source : https://leetcode.com/problems/minimum-time-for-k-viruses-to-spread/ +/// Author : liuyubobobo +/// Time : 2021-07-02 + +#include +#include + +using namespace std; + + +/// State Compression + Brute Force +/// Time Complexity: O(n^2 + 2^n * k^2) +/// Space Complexity: O(n^2) +class Solution { +public: + int minDayskVariants(vector>& points, int k) { + + int n = points.size(); + vector> A(n, vector(n, 0)); + for(int i = 0; i < n; i ++) + for(int j = i + 1; j < n; j ++){ + int d = abs(points[i][0] - points[j][0]) + abs(points[i][1] - points[j][1]); + A[i][j] = A[j][i] = (d + 1) / 2; + } + + int res = INT_MAX; + for(int state = 1; state <= (1 << n); state ++) + if(__builtin_popcount(state) == k){ + + vector v(k); + int index = 0; + for(int j = 0; j < n; j ++) + if(state & (1 << j)) v[index ++] = j; + + int tres = INT_MIN; + for(int i = 0; i < k; i ++) + for(int j = i + 1; j < k; j ++) + tres = max(tres, A[v[i]][v[j]]); + res = min(res, tres); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1957-Delete-Characters-to-Make-Fancy-String/cpp-1957/CMakeLists.txt b/1501-2000/1957-Delete-Characters-to-Make-Fancy-String/cpp-1957/CMakeLists.txt new file mode 100644 index 00000000..27cf915f --- /dev/null +++ b/1501-2000/1957-Delete-Characters-to-Make-Fancy-String/cpp-1957/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_1957) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1957 main.cpp) diff --git a/1501-2000/1957-Delete-Characters-to-Make-Fancy-String/cpp-1957/main.cpp b/1501-2000/1957-Delete-Characters-to-Make-Fancy-String/cpp-1957/main.cpp new file mode 100644 index 00000000..ce7a0f08 --- /dev/null +++ b/1501-2000/1957-Delete-Characters-to-Make-Fancy-String/cpp-1957/main.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/delete-characters-to-make-fancy-string/ +/// Author : liuyubobobo +/// Time : 2021-08-07 + +#include + +using namespace std; + + +/// String Split +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + string makeFancyString(string s) { + + string res = ""; + for(int start = 0, i = 1; i <= s.size(); i ++) + if(i == s.size() || s[i] != s[start]){ + int len = i - start; + len = min(len, 2); + res += string(len, s[start]); + + start = i; + i = start; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1958-Check-if-Move-is-Legal/cpp-1958/CMakeLists.txt b/1501-2000/1958-Check-if-Move-is-Legal/cpp-1958/CMakeLists.txt new file mode 100644 index 00000000..583af741 --- /dev/null +++ b/1501-2000/1958-Check-if-Move-is-Legal/cpp-1958/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_1958) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1958 main.cpp) diff --git a/1501-2000/1958-Check-if-Move-is-Legal/cpp-1958/main.cpp b/1501-2000/1958-Check-if-Move-is-Legal/cpp-1958/main.cpp new file mode 100644 index 00000000..89b76548 --- /dev/null +++ b/1501-2000/1958-Check-if-Move-is-Legal/cpp-1958/main.cpp @@ -0,0 +1,65 @@ +/// Source : https://leetcode.com/problems/check-if-move-is-legal/ +/// Author : liuyubobobo +/// Time : 2021-08-07 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(R * C) +/// Space Complexity: O(max(R, C)) +class Solution { + +private: + const int dirs[8][2] = { + {1, 0}, {0, 1}, {-1, 0}, {0, -1}, {1, 1}, {1, -1}, {-1, 1}, {-1, -1} + }; + int R, C; + +public: + bool checkMove(vector>& board, int r, int c, char color) { + + R = board.size(), C = board[0].size(); + + board[r][c] = color; + for(int d = 0; d < 8; d ++){ + vector v; + for(int k = 0;;k++){ + int x = r + k * dirs[d][0], y = c + k * dirs[d][1]; + if(!in_area(x, y) || board[x][y] == '.') break; + v.push_back(board[x][y]); + } + if(ok(v)) return true; + } + return false; + } + +private: + bool ok(const vector& v){ + + if(v.size() < 3) return false; + if(v[1] == v[0]) return false; + + vector seg; + for(int start = 0, i = 1; i <= v.size(); i ++) + if(i == v.size() || v[i] != v[start]){ + seg.push_back(i - start); + start = i; + i = start; + } + + return seg.size() >= 3; + } + bool in_area(int x, int y){ + return x >= 0 && x < R && y >= 0 && y < C; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1959-Minimum-Total-Space-Wasted-With-K-Resizing-Operations/cpp-1959/CMakeLists.txt b/1501-2000/1959-Minimum-Total-Space-Wasted-With-K-Resizing-Operations/cpp-1959/CMakeLists.txt new file mode 100644 index 00000000..1c317810 --- /dev/null +++ b/1501-2000/1959-Minimum-Total-Space-Wasted-With-K-Resizing-Operations/cpp-1959/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_1959) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1959 main.cpp) diff --git a/1501-2000/1959-Minimum-Total-Space-Wasted-With-K-Resizing-Operations/cpp-1959/main.cpp b/1501-2000/1959-Minimum-Total-Space-Wasted-With-K-Resizing-Operations/cpp-1959/main.cpp new file mode 100644 index 00000000..b4c8ced7 --- /dev/null +++ b/1501-2000/1959-Minimum-Total-Space-Wasted-With-K-Resizing-Operations/cpp-1959/main.cpp @@ -0,0 +1,61 @@ +/// Source : https://leetcode.com/problems/minimum-total-space-wasted-with-k-resizing-operations/ +/// Author : liuyubobobo +/// Time : 2021-08-07 + +#include +#include + +using namespace std; + + +/// Memoization +/// Time Complexity: O(n * n * k) +/// Space Complexity: O(n * k) +class Solution { + +private: + const int INF = 1e9; + +public: + int minSpaceWastedKResizing(vector& nums, int k) { + + int n = nums.size(); + + vector> dp(k + 1, vector(n, -1)); + return dfs(nums, k, 0, dp); + } + +private: + int dfs(const vector& nums, int k, int index, vector>& dp){ + + if(index == nums.size()) return 0; + if(k < 0) return INF; + if(dp[k][index] != -1) return dp[k][index]; + + int maxv = 0, sum = 0, res = INF; + for(int i = index; i < nums.size(); i ++){ + maxv = max(maxv, nums[i]); + sum += nums[i]; + res = min(res, maxv * (i - index + 1) - sum + dfs(nums, k - 1, i + 1, dp)); + } + return dp[k][index] = res; + } +}; + + +int main() { + + vector nums1 = {10, 20}; + cout << Solution().minSpaceWastedKResizing(nums1, 0) << endl; + // 10 + + vector nums2 = {10, 20, 30}; + cout << Solution().minSpaceWastedKResizing(nums2, 1) << endl; + // 10 + + vector nums3 = {10, 20, 15, 30, 20}; + cout << Solution().minSpaceWastedKResizing(nums3, 2) << endl; + // 15 + + return 0; +} diff --git a/1501-2000/1960-Maximum-Product-of-the-Length-of-Two-Palindromic-Substrings/cpp-1960/CMakeLists.txt b/1501-2000/1960-Maximum-Product-of-the-Length-of-Two-Palindromic-Substrings/cpp-1960/CMakeLists.txt new file mode 100644 index 00000000..087e33ef --- /dev/null +++ b/1501-2000/1960-Maximum-Product-of-the-Length-of-Two-Palindromic-Substrings/cpp-1960/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_1960) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1960 main2.cpp) diff --git a/1501-2000/1960-Maximum-Product-of-the-Length-of-Two-Palindromic-Substrings/cpp-1960/main.cpp b/1501-2000/1960-Maximum-Product-of-the-Length-of-Two-Palindromic-Substrings/cpp-1960/main.cpp new file mode 100644 index 00000000..577f02f0 --- /dev/null +++ b/1501-2000/1960-Maximum-Product-of-the-Length-of-Two-Palindromic-Substrings/cpp-1960/main.cpp @@ -0,0 +1,109 @@ +/// Source : https://leetcode.com/problems/maximum-product-of-the-length-of-two-palindromic-substrings/ +/// Author : liuyubobobo +/// Time : 2021-08-08 + +#include +#include + +using namespace std; + + +/// RK to find max length palindrome +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +template +class StringHash{ + +private: + int n; + T B, MOD; + vector h, p; + +public: + StringHash(const string& s, T B = 128, T MOD = 1e9+ 7) : + n(s.size()), h(n + 1, 0), p(n + 1, 1), B(B), MOD(MOD){ + + for(int i = 0; i < n; i ++){ + h[i + 1] = (h[i] * B + s[i]) % MOD; + p[i + 1] = p[i] * B % MOD; + } + } + + T get_hash(int l, int r){ + // assert(l >= 0 && l < n); + // assert(r >= 0 && r < n); + T res = (h[r + 1] - h[l] * p[r - l + 1]) % MOD; + return res < 0 ? res + MOD : res; + } +}; + + +class Solution { +public: + long long maxProduct(string s) { + + string rs = s; + reverse(rs.begin(), rs.end()); + + StringHash hash(s), rhash(rs); + + int n = s.size(); + vector dp(n, 0); + for(int i = 1; i + 1 < n; i ++){ + int lenl = 0, lenr = min(i, n - i - 1); + while(lenl < lenr){ + int mid = (lenl + lenr + 1) / 2; + if(hash.get_hash(i - mid, i - 1) == rhash.get_hash(n - 1 - (i + mid), n - 1 - (i + 1))) + lenl = mid; + else + lenr = mid - 1; + } + + dp[i] = lenl; + } +// for(int e: dp) cout << e << ' '; cout << endl; + + vector left(n, 0); + for(int i = 0; i < n; i ++) + left[i - dp[i]] = max(left[i - dp[i]], 2 * dp[i] + 1); + for(int i = 1; i < n; i ++) + left[i] = max(left[i], left[i - 1] - 2); +// for(int e: left) cout << e << ' '; cout << endl; + + for(int i = n - 2; i >= 0; i --) + left[i] = max(left[i + 1], left[i]); +// for(int e: left) cout << e << ' '; cout << endl; + + vector right(n, 0); + for(int i = 0; i < n; i ++) + right[i + dp[i]] = max(right[i + dp[i]], 2 * dp[i] + 1); + for(int i = n - 2; i >= 0; i --) + right[i] = max(right[i], right[i + 1] - 2); +// for(int e: right) cout << e << ' '; cout << endl; + + for(int i = 1; i < n; i ++) + right[i] = max(right[i], right[i - 1]); +// for(int e: right) cout << e << ' '; cout << endl; + + long long res = 0ll; + for(int i = 1; i < n; i ++) + res = max(res, (long long)right[i - 1] * left[i]); + + return res; + } +}; + + +int main() { + + cout << Solution().maxProduct("ababbb") << endl; + // 9 + + cout << Solution().maxProduct("zaaaxbbby") << endl; + // 9 + + cout << Solution().maxProduct("ggbswiymmlevedhkbdhntnhdbkhdevelmmyiwsbgg") << endl; + // 45 + + return 0; +} diff --git a/1501-2000/1960-Maximum-Product-of-the-Length-of-Two-Palindromic-Substrings/cpp-1960/main2.cpp b/1501-2000/1960-Maximum-Product-of-the-Length-of-Two-Palindromic-Substrings/cpp-1960/main2.cpp new file mode 100644 index 00000000..c259118b --- /dev/null +++ b/1501-2000/1960-Maximum-Product-of-the-Length-of-Two-Palindromic-Substrings/cpp-1960/main2.cpp @@ -0,0 +1,73 @@ +/// Source : https://leetcode.com/problems/maximum-product-of-the-length-of-two-palindromic-substrings/ +/// Author : liuyubobobo +/// Time : 2021-08-08 + +#include +#include + +using namespace std; + + +/// Manacher +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + long long maxProduct(string s) { + + int n = s.size(); + + vector d1(n); + for (int i = 0, l = 0, r = -1; i < n; i++) { + int k = (i > r) ? 1 : min(d1[l + r - i], r - i + 1); + while (0 <= i - k && i + k < n && s[i - k] == s[i + k]) + k++; + + d1[i] = --k; + if (i + k > r) l = i - k, r = i + k; + } + + vector left(n, 0); + for(int i = 0; i < n; i ++) + left[i - d1[i]] = max(left[i - d1[i]], 2 * d1[i] + 1); + for(int i = 1; i < n; i ++) + left[i] = max(left[i], left[i - 1] - 2); + // for(int e: left) cout << e << ' '; cout << endl; + + for(int i = n - 2; i >= 0; i --) + left[i] = max(left[i + 1], left[i]); + // for(int e: left) cout << e << ' '; cout << endl; + + vector right(n, 0); + for(int i = 0; i < n; i ++) + right[i + d1[i]] = max(right[i + d1[i]], 2 * d1[i] + 1); + for(int i = n - 2; i >= 0; i --) + right[i] = max(right[i], right[i + 1] - 2); + // for(int e: right) cout << e << ' '; cout << endl; + + for(int i = 1; i < n; i ++) + right[i] = max(right[i], right[i - 1]); + // for(int e: right) cout << e << ' '; cout << endl; + + long long res = 0ll; + for(int i = 1; i < n; i ++) + res = max(res, (long long)right[i - 1] * left[i]); + + return res; + } +}; + + +int main() { + + cout << Solution().maxProduct("ababbb") << endl; + // 9 + + cout << Solution().maxProduct("zaaaxbbby") << endl; + // 9 + + cout << Solution().maxProduct("ggbswiymmlevedhkbdhntnhdbkhdevelmmyiwsbgg") << endl; + // 45 + + return 0; +} diff --git a/1501-2000/1961-Check-If-String-Is-a-Prefix-of-Array/cpp-1961/CMakeLists.txt b/1501-2000/1961-Check-If-String-Is-a-Prefix-of-Array/cpp-1961/CMakeLists.txt new file mode 100644 index 00000000..2ae8397c --- /dev/null +++ b/1501-2000/1961-Check-If-String-Is-a-Prefix-of-Array/cpp-1961/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/1501-2000/1961-Check-If-String-Is-a-Prefix-of-Array/cpp-1961/main.cpp b/1501-2000/1961-Check-If-String-Is-a-Prefix-of-Array/cpp-1961/main.cpp new file mode 100644 index 00000000..541ca365 --- /dev/null +++ b/1501-2000/1961-Check-If-String-Is-a-Prefix-of-Array/cpp-1961/main.cpp @@ -0,0 +1,31 @@ +/// Source : https://leetcode.com/problems/check-if-string-is-a-prefix-of-array/ +/// Author : liuyubobobo +/// Time : 2021-08-09 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + bool isPrefixString(string s, vector& words) { + + string cur = ""; + for(const string& e: words){ + cur += e; + if(s == cur) return true; + } + return false; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1962-Remove-Stones-to-Minimize-the-Total/cpp-1962/CMakeLists.txt b/1501-2000/1962-Remove-Stones-to-Minimize-the-Total/cpp-1962/CMakeLists.txt new file mode 100644 index 00000000..3f98647f --- /dev/null +++ b/1501-2000/1962-Remove-Stones-to-Minimize-the-Total/cpp-1962/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/1501-2000/1962-Remove-Stones-to-Minimize-the-Total/cpp-1962/main.cpp b/1501-2000/1962-Remove-Stones-to-Minimize-the-Total/cpp-1962/main.cpp new file mode 100644 index 00000000..ac73a28a --- /dev/null +++ b/1501-2000/1962-Remove-Stones-to-Minimize-the-Total/cpp-1962/main.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/remove-stones-to-minimize-the-total/ +/// Author : liuyubobobo +/// Time : 2021-08-09 + +#include +#include +#include + +using namespace std; + + +/// Priority Queue +/// Time Complexity: O(k * logn) +/// Space Complexity: O(n) +class Solution { +public: + int minStoneSum(vector& piles, int k) { + + priority_queue pq; + for(int pile: piles) pq.push(pile); + + for(int i = 0; i < k && !pq.empty(); i ++){ + int e = pq.top(); pq.pop(); + pq.push(e - e / 2); + } + + int res = 0; + while(!pq.empty()){ + res += pq.top(); pq.pop(); + } + return res; + } +}; + +int main() { + + vector piles1 = {5, 4, 9}; + cout << Solution().minStoneSum(piles1, 2) << endl; + // 12 + + vector piles2 = {4, 3, 6, 7}; + cout << Solution().minStoneSum(piles2, 3) << endl; + // 12 + + return 0; +} diff --git a/1501-2000/1963-Minimum-Number-of-Swaps-to-Make-the-String-Balanced/cpp-1963/CMakeLists.txt b/1501-2000/1963-Minimum-Number-of-Swaps-to-Make-the-String-Balanced/cpp-1963/CMakeLists.txt new file mode 100644 index 00000000..cad75f71 --- /dev/null +++ b/1501-2000/1963-Minimum-Number-of-Swaps-to-Make-the-String-Balanced/cpp-1963/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/1501-2000/1963-Minimum-Number-of-Swaps-to-Make-the-String-Balanced/cpp-1963/main.cpp b/1501-2000/1963-Minimum-Number-of-Swaps-to-Make-the-String-Balanced/cpp-1963/main.cpp new file mode 100644 index 00000000..f598ad11 --- /dev/null +++ b/1501-2000/1963-Minimum-Number-of-Swaps-to-Make-the-String-Balanced/cpp-1963/main.cpp @@ -0,0 +1,58 @@ +/// Source : https://leetcode.com/problems/minimum-number-of-swaps-to-make-the-string-balanced/ +/// Author : liuyubobobo +/// Time : 2021-08-09 + +#include +#include + +using namespace std; + + +/// Two Pointers +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int minSwaps(string s) { + + int n = s.size(), l = 0, r = n - 1; + int stack1 = 0, stack2 = 0, res = 0; + while(l <= r){ + for(; l <= r; l ++){ + if(s[l] == '[') stack1 ++; + else stack1 --; + if(stack1 < 0) break; + } + + for(; r >= l; r --){ + if(s[r] == ']') stack2 ++; + else stack2 --; + if(stack2 < 0) break; + } + + if(l <= r){ + swap(s[l], s[r]); + l ++, r --; + res ++; + stack1 += 2, stack2 += 2; + } + else break; + } + return res; + } +}; + + +int main() { + + cout << Solution().minSwaps("][][") << endl; + // 1 + + cout << Solution().minSwaps("]]][[[") << endl; + // 2 + + cout << Solution().minSwaps("[]") << endl; + // 0 + + return 0; +} diff --git a/1501-2000/1964-Find-the-Longest-Valid-Obstacle-Course-at-Each-Position/cpp-1964/CMakeLists.txt b/1501-2000/1964-Find-the-Longest-Valid-Obstacle-Course-at-Each-Position/cpp-1964/CMakeLists.txt new file mode 100644 index 00000000..2a7f1f76 --- /dev/null +++ b/1501-2000/1964-Find-the-Longest-Valid-Obstacle-Course-at-Each-Position/cpp-1964/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main2.cpp) diff --git a/1501-2000/1964-Find-the-Longest-Valid-Obstacle-Course-at-Each-Position/cpp-1964/main.cpp b/1501-2000/1964-Find-the-Longest-Valid-Obstacle-Course-at-Each-Position/cpp-1964/main.cpp new file mode 100644 index 00000000..2d4cf5f0 --- /dev/null +++ b/1501-2000/1964-Find-the-Longest-Valid-Obstacle-Course-at-Each-Position/cpp-1964/main.cpp @@ -0,0 +1,136 @@ +/// Source : https://leetcode.com/problems/find-the-longest-valid-obstacle-course-at-each-position/ +/// Author : liuyubobobo +/// Time : 2021-08-09 + +#include +#include + +using namespace std; + + +/// Segment Tree +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +template +class SegmentTree{ + +private: + int n; + vector data, tree; + T (*combine)(T a, T b); + +public: + SegmentTree(const vector& data, T (*combine)(T a, T b)): n(data.size()), data(data), tree(4 * n, 0){ + this->combine = combine; + buildSegTree(0, 0, n - 1); + } + + SegmentTree(int n, T (*combine)(T a, T b)): n(n), data(n, 0), tree(4 * n, 0){ + this->combine = combine; + } + + void update(int index, T value){ + data[index] = value; + update(0, 0, n - 1, index, value); + } + + T query(int index){ + assert(0 <= index && index < n); + return data[index]; + } + + T query(int l, int r){ + assert(l <= r); + assert(0 <= l && l < n); + assert(0 <= r && r < n); + return query(0, 0, n - 1, l, r); + } + +private: + void buildSegTree(int treeID, int l, int r){ + + if(l == r){ + tree[treeID] = data[l]; + return; + } + + int mid = (l + r) / 2; + buildSegTree(treeID * 2 + 1, l, mid); + buildSegTree(treeID * 2 + 2, mid + 1, r); + tree[treeID] = combine(tree[treeID * 2 + 1], tree[treeID * 2 + 2]); + return; + } + + void update(int treeID, int l, int r, int index, int value){ + + if(l == r){ + assert(l == index); + tree[treeID] = value; + return; + } + + int mid = (l + r) / 2; + if(index <= mid) update(treeID * 2 + 1, l, mid, index, value); + else update(treeID * 2 + 2, mid + 1, r, index, value); + + tree[treeID] = combine(tree[treeID * 2 + 1], tree[treeID * 2 + 2]); + return; + } + + T query(int treeID, int l, int r, int ql, int qr){ + + if(ql == l && qr == r) + return tree[treeID]; + + int mid = (l + r) / 2; + if(qr <= mid) return query(treeID * 2 + 1, l, mid, ql, qr); + else if(ql > mid) return query(treeID * 2 + 2, mid + 1, r, ql, qr); + + T resl = query(treeID * 2 + 1, l, mid, ql, mid); + T resr = query(treeID * 2 + 2, mid + 1, r, mid + 1, qr); + return combine(resl, resr); + } +}; + +class Solution { +public: + vector longestObstacleCourseAtEachPosition(vector& obstacles) { + + int maxv = *max_element(obstacles.begin(), obstacles.end()); + + auto combine = [](int a, int b){return max(a, b);}; + SegmentTree seg_tree(maxv + 1, combine); + + int n = obstacles.size(); + vector res(n, 1); + seg_tree.update(obstacles[0], 1); + for(int i = 1; i < n; i ++){ + int x = seg_tree.query(0, obstacles[i]); + res[i] = x + 1; + seg_tree.update(obstacles[i], max(seg_tree.query(obstacles[i]), res[i])); + } + return res; + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << ' '; cout << endl; +} + +int main() { + + vector nums1 = {1,2,3,2}; + print_vec(Solution().longestObstacleCourseAtEachPosition(nums1)); + // 1 2 3 3 + + vector nums2 = {2,2,1}; + print_vec(Solution().longestObstacleCourseAtEachPosition(nums2)); + // 1 2 1 + + vector nums3 = {3,1,5,6,4,2}; + print_vec(Solution().longestObstacleCourseAtEachPosition(nums3)); + // 1 2 1 + + return 0; +} diff --git a/1501-2000/1964-Find-the-Longest-Valid-Obstacle-Course-at-Each-Position/cpp-1964/main2.cpp b/1501-2000/1964-Find-the-Longest-Valid-Obstacle-Course-at-Each-Position/cpp-1964/main2.cpp new file mode 100644 index 00000000..994905fe --- /dev/null +++ b/1501-2000/1964-Find-the-Longest-Valid-Obstacle-Course-at-Each-Position/cpp-1964/main2.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/find-the-longest-valid-obstacle-course-at-each-position/ +/// Author : liuyubobobo +/// Time : 2021-08-09 + +#include +#include + +using namespace std; + + +/// LIS +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + vector longestObstacleCourseAtEachPosition(vector& obstacles) { + + vector lis = {obstacles[0]}; + vector res = {1}; + for(int i = 1; i < obstacles.size(); i ++){ + vector::iterator iter = upper_bound(lis.begin(), lis.end(), obstacles[i]); + int k = iter - lis.begin(); + if(iter == lis.end()) + lis.push_back(obstacles[i]); + else + lis[k] = obstacles[i]; + res.push_back(k + 1); + } + return res; + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << ' '; cout << endl; +} + +int main() { + + vector nums1 = {1,2,3,2}; + print_vec(Solution().longestObstacleCourseAtEachPosition(nums1)); + // 1 2 3 3 + + vector nums2 = {2,2,1}; + print_vec(Solution().longestObstacleCourseAtEachPosition(nums2)); + // 1 2 1 + + vector nums3 = {3,1,5,6,4,2}; + print_vec(Solution().longestObstacleCourseAtEachPosition(nums3)); + // 1,1,2,3,2,2 + + return 0; +} diff --git a/1501-2000/1966-Binary-Searchable-Numbers-in-an-Unsorted-Array/cpp-1966/CMakeLists.txt b/1501-2000/1966-Binary-Searchable-Numbers-in-an-Unsorted-Array/cpp-1966/CMakeLists.txt new file mode 100644 index 00000000..22f0b1ea --- /dev/null +++ b/1501-2000/1966-Binary-Searchable-Numbers-in-an-Unsorted-Array/cpp-1966/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_1966) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1966 main.cpp) diff --git a/1501-2000/1966-Binary-Searchable-Numbers-in-an-Unsorted-Array/cpp-1966/main.cpp b/1501-2000/1966-Binary-Searchable-Numbers-in-an-Unsorted-Array/cpp-1966/main.cpp new file mode 100644 index 00000000..d77fb42d --- /dev/null +++ b/1501-2000/1966-Binary-Searchable-Numbers-in-an-Unsorted-Array/cpp-1966/main.cpp @@ -0,0 +1,44 @@ +/// Source : https://leetcode.com/problems/binary-searchable-numbers-in-an-unsorted-array/ +/// Author : liuyubobobo +/// Time : 2021-08-14 + +#include +#include + +using namespace std; + + +/// Range max and min +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int binarySearchableNumbers(vector& nums) { + + int n = nums.size(); + vector left(n, true); + + int maxv = nums[0]; + for(int i = 1; i < n; i ++){ + left[i] = maxv < nums[i]; + maxv = max(maxv, nums[i]); + } + + vector right(n, true); + int minv = nums[n - 1]; + for(int i = n - 2; i >= 0; i --){ + right[i] = minv > nums[i]; + minv = min(minv, nums[i]); + } + + int res = 0; + for(int i = 0; i < n; i ++) res += (left[i] && right[i]); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1967-Number-of-Strings-That-Appear-as-Substrings-in-Word/cpp-1967/CMakeLists.txt b/1501-2000/1967-Number-of-Strings-That-Appear-as-Substrings-in-Word/cpp-1967/CMakeLists.txt new file mode 100644 index 00000000..2ae8397c --- /dev/null +++ b/1501-2000/1967-Number-of-Strings-That-Appear-as-Substrings-in-Word/cpp-1967/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/1501-2000/1967-Number-of-Strings-That-Appear-as-Substrings-in-Word/cpp-1967/main.cpp b/1501-2000/1967-Number-of-Strings-That-Appear-as-Substrings-in-Word/cpp-1967/main.cpp new file mode 100644 index 00000000..a44da3d0 --- /dev/null +++ b/1501-2000/1967-Number-of-Strings-That-Appear-as-Substrings-in-Word/cpp-1967/main.cpp @@ -0,0 +1,29 @@ +/// Source : https://leetcode.com/problems/number-of-strings-that-appear-as-substrings-in-word/ +/// Author : liuyubobobo +/// Time : 2021-08-14 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int numOfStrings(vector& patterns, string word) { + + int res = 0; + for(const string& e: patterns) + res += word.find(e) != string::npos; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1968-Array-With-Elements-Not-Equal-to-Average-of-Neighbors/cpp-1968/CMakeLists.txt b/1501-2000/1968-Array-With-Elements-Not-Equal-to-Average-of-Neighbors/cpp-1968/CMakeLists.txt new file mode 100644 index 00000000..084dd354 --- /dev/null +++ b/1501-2000/1968-Array-With-Elements-Not-Equal-to-Average-of-Neighbors/cpp-1968/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main2.cpp) diff --git a/1501-2000/1968-Array-With-Elements-Not-Equal-to-Average-of-Neighbors/cpp-1968/main.cpp b/1501-2000/1968-Array-With-Elements-Not-Equal-to-Average-of-Neighbors/cpp-1968/main.cpp new file mode 100644 index 00000000..79ad23d4 --- /dev/null +++ b/1501-2000/1968-Array-With-Elements-Not-Equal-to-Average-of-Neighbors/cpp-1968/main.cpp @@ -0,0 +1,29 @@ +/// Source : https://leetcode.com/problems/array-with-elements-not-equal-to-average-of-neighbors/ +/// Author : liuyubobobo +/// Time : 2021-08-14 + +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + vector rearrangeArray(vector& nums) { + + sort(nums.begin(), nums.end()); + for(int i = 1; i + 1 < nums.size(); i += 2) + swap(nums[i], nums[i + 1]); + return nums; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1968-Array-With-Elements-Not-Equal-to-Average-of-Neighbors/cpp-1968/main2.cpp b/1501-2000/1968-Array-With-Elements-Not-Equal-to-Average-of-Neighbors/cpp-1968/main2.cpp new file mode 100644 index 00000000..f1a4295d --- /dev/null +++ b/1501-2000/1968-Array-With-Elements-Not-Equal-to-Average-of-Neighbors/cpp-1968/main2.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/array-with-elements-not-equal-to-average-of-neighbors/ +/// Author : liuyubobobo +/// Time : 2021-08-14 + +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + vector rearrangeArray(vector& nums) { + + sort(nums.begin(), nums.end()); + + int n = nums.size(); + vector res(n); + int j = 0; + for(int i = 0; i < n; i += 2) + res[i] = nums[j ++]; + for(int i = 1; i < n; i += 2) + res[i] = nums[j ++]; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1969-Minimum-Non-Zero-Product-of-the-Array-Elements/cpp-1969/CMakeLists.txt b/1501-2000/1969-Minimum-Non-Zero-Product-of-the-Array-Elements/cpp-1969/CMakeLists.txt new file mode 100644 index 00000000..cad75f71 --- /dev/null +++ b/1501-2000/1969-Minimum-Non-Zero-Product-of-the-Array-Elements/cpp-1969/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/1501-2000/1969-Minimum-Non-Zero-Product-of-the-Array-Elements/cpp-1969/main.cpp b/1501-2000/1969-Minimum-Non-Zero-Product-of-the-Array-Elements/cpp-1969/main.cpp new file mode 100644 index 00000000..5117802e --- /dev/null +++ b/1501-2000/1969-Minimum-Non-Zero-Product-of-the-Array-Elements/cpp-1969/main.cpp @@ -0,0 +1,59 @@ +/// Source : https://leetcode.com/problems/minimum-non-zero-product-of-the-array-elements/ +/// Author : liuyubobobo +/// Time : 2021-08-14 + +#include + +using namespace std; + + +/// Quick Power +/// Time Complexity: O(p) +/// Space Complexity: O(p) +class Solution { +public: + int minNonZeroProduct(int p) { + + if(p == 1) return 1; + + const long long MOD = 1e9 + 7; + + long long res = ((((long long)1) << p) - 1ll) % MOD; + + long long a = ((((long long)1) << p) - 2ll) % MOD; + long long power = (((long long)1) << (p - 1)) - 1ll; + res *= quick_pow(a, power, MOD); + res %= MOD; + + return res; + } + +private: + long long quick_pow(long long a, long long k, long long MOD) { + long long res = 1ll; + while (k > 0) { + if (k & 1) res = (res * a) % MOD; + a = (a * a) % MOD; + k >>= 1; + } + return res; + } +}; + + +int main() { + + cout << Solution().minNonZeroProduct(1) << endl; + // 1 + + cout << Solution().minNonZeroProduct(2) << endl; + // 6 + + cout << Solution().minNonZeroProduct(3) << endl; + // 1512 + + cout << Solution().minNonZeroProduct(35) << endl; + // 1512 + + return 0; +} diff --git a/1501-2000/1970-Last-Day-Where-You-Can-Still-Cross/cpp-1970/CMakeLists.txt b/1501-2000/1970-Last-Day-Where-You-Can-Still-Cross/cpp-1970/CMakeLists.txt new file mode 100644 index 00000000..a0d16fe6 --- /dev/null +++ b/1501-2000/1970-Last-Day-Where-You-Can-Still-Cross/cpp-1970/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) diff --git a/1501-2000/1970-Last-Day-Where-You-Can-Still-Cross/cpp-1970/main.cpp b/1501-2000/1970-Last-Day-Where-You-Can-Still-Cross/cpp-1970/main.cpp new file mode 100644 index 00000000..84585bb6 --- /dev/null +++ b/1501-2000/1970-Last-Day-Where-You-Can-Still-Cross/cpp-1970/main.cpp @@ -0,0 +1,109 @@ +/// Source : https://leetcode.com/problems/last-day-where-you-can-still-cross/ +/// Author : liuyubobobo +/// Time : 2021-08-14 + +#include +#include + +using namespace std; + + +/// UF +/// Time Complexity: O(row * col + |cells|) +/// Space Complexity: O(row * col) +class UF{ + +private: + vector parent; + +public: + UF(int n) : parent(n){ + for(int i = 0 ; i < n ; i ++) + parent[i] = i; + } + + int find(int p){ + if(p != parent[p]) + parent[p] = find(parent[p]); + return parent[p]; + } + + bool is_connected(int p, int q){ + return find(p) == find(q); + } + + void union_elements(int p, int q){ + + int p_root = find(p), q_root = find(q); + + if(p_root == q_root) return; + + parent[p_root] = q_root; + } +}; + +class Solution { + +private: + const int dirs[4][2] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; + +public: + int latestDayToCross(int row, int col, vector>& cells) { + + vector> g(row, vector(col, 1)); + for(vector& p: cells){ + p[0] --, p[1] --; + g[p[0]][p[1]] = 0; + } + + int s = row * col, t = row * col + 1; + UF uf(row * col + 2); + for(int i = 0; i < row; i ++) + for(int j = 0; j < col; j ++) + if(g[i][j]){ + for(int d = 0; d < 4; d ++){ + int nexti = i + dirs[d][0], nextj = j + dirs[d][1]; + if(0 <= nexti && nexti < row && 0 <= nextj && nextj < col && g[nexti][nextj]) + uf.union_elements(i * col + j, nexti * col + nextj); + } + } + + for(int j = 0; j < col; j ++){ + if(g[0][j]) uf.union_elements(s, j); + if(g[row - 1][j]) uf.union_elements((row - 1) * col + j, t); + } + + for(int i = cells.size() - 1; i >= 0; i --){ + if(uf.is_connected(s, t)) return i + 1; + + int x = cells[i][0], y = cells[i][1]; + g[x][y] = 1; + for(int d = 0; d < 4; d ++){ + int nextx = x + dirs[d][0], nexty = y + dirs[d][1]; + if(0 <= nextx && nextx < row && 0 <= nexty && nexty < col && g[nextx][nexty]) + uf.union_elements(x * col + y, nextx * col + nexty); + } + if(x == 0) uf.union_elements(s, x * col + y); + if(x == row - 1) uf.union_elements(x * col + y, t); + } + return -1; + } +}; + + +int main() { + + vector> cells1 = {{1, 1}, {2, 1}, {1, 2}, {2, 2}}; + cout << Solution().latestDayToCross(2, 2, cells1) << endl; + // 2 + + vector> cells2 = {{1, 1}, {1, 2}, {2, 1}, {2, 2}}; + cout << Solution().latestDayToCross(2, 2, cells2) << endl; + // 1 + + vector> cells3 = {{1, 2}, {2, 1}, {3, 3}, {2, 2}, {1, 1}}; + cout << Solution().latestDayToCross(3, 3, cells3) << endl; + // 3 + + return 0; +} diff --git a/1501-2000/1971-Find-if-Path-Exists-in-Graph/cpp-1971/CMakeLists.txt b/1501-2000/1971-Find-if-Path-Exists-in-Graph/cpp-1971/CMakeLists.txt new file mode 100644 index 00000000..938e33ee --- /dev/null +++ b/1501-2000/1971-Find-if-Path-Exists-in-Graph/cpp-1971/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_1971) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1971 main.cpp) diff --git a/1501-2000/1971-Find-if-Path-Exists-in-Graph/cpp-1971/main.cpp b/1501-2000/1971-Find-if-Path-Exists-in-Graph/cpp-1971/main.cpp new file mode 100644 index 00000000..7c25ea54 --- /dev/null +++ b/1501-2000/1971-Find-if-Path-Exists-in-Graph/cpp-1971/main.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/find-if-path-exists-in-graph/ +/// Author : liuyubobobo +/// Time : 2021-08-20 + +#include +#include + +using namespace std; + + +/// DFS +/// Time Compelxity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + bool validPath(int n, vector>& edges, int start, int end) { + + vector> g(n); + for(const vector& e: edges) + g[e[0]].push_back(e[1]), g[e[1]].push_back(e[0]); + + vector visited(n, false); + return dfs(g, start, end, visited); + } + +private: + bool dfs(const vector>& g, int u, int end, vector& visited){ + visited[u] = true; + if(u == end) return true; + for(int v: g[u]) + if(!visited[v] && dfs(g, v, end, visited)) return true; + return false; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1973-Count-Nodes-Equal-to-Sum-of-Descendants/cpp-1973/CMakeLists.txt b/1501-2000/1973-Count-Nodes-Equal-to-Sum-of-Descendants/cpp-1973/CMakeLists.txt new file mode 100644 index 00000000..202fc946 --- /dev/null +++ b/1501-2000/1973-Count-Nodes-Equal-to-Sum-of-Descendants/cpp-1973/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_1973) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1973 main.cpp) diff --git a/1501-2000/1973-Count-Nodes-Equal-to-Sum-of-Descendants/cpp-1973/main.cpp b/1501-2000/1973-Count-Nodes-Equal-to-Sum-of-Descendants/cpp-1973/main.cpp new file mode 100644 index 00000000..79929884 --- /dev/null +++ b/1501-2000/1973-Count-Nodes-Equal-to-Sum-of-Descendants/cpp-1973/main.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/count-nodes-equal-to-sum-of-descendants/ +/// Author : liuyubobobo +/// Time : 2021-08-20 + +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// 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 { + +private: + int res = 0; + +public: + int equalToDescendants(TreeNode* root) { + + res = 0; + dfs(root); + return res; + } + +private: + long long dfs(TreeNode* node){ + + if(!node) return 0; + + long long a = dfs(node->left), b = dfs(node->right); + res += ((long long)node->val == a + b); + return a + b + node->val; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1974-Minimum-Time-to-Type-Word-Using-Special-Typewriter/cpp-1974/CMakeLists.txt b/1501-2000/1974-Minimum-Time-to-Type-Word-Using-Special-Typewriter/cpp-1974/CMakeLists.txt new file mode 100644 index 00000000..fb2bd142 --- /dev/null +++ b/1501-2000/1974-Minimum-Time-to-Type-Word-Using-Special-Typewriter/cpp-1974/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_1974) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1974 main.cpp) diff --git a/1501-2000/1974-Minimum-Time-to-Type-Word-Using-Special-Typewriter/cpp-1974/main.cpp b/1501-2000/1974-Minimum-Time-to-Type-Word-Using-Special-Typewriter/cpp-1974/main.cpp new file mode 100644 index 00000000..f8c82c1a --- /dev/null +++ b/1501-2000/1974-Minimum-Time-to-Type-Word-Using-Special-Typewriter/cpp-1974/main.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/minimum-time-to-type-word-using-special-typewriter/ +/// Author : liuyubobobo +/// Time : 2021-08-21 + +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int minTimeToType(string word) { + + int res = 0; + + char prev = 'a'; + for(char c: word){ + int a = prev - 'a', b = c - 'a'; + int maxv = max(a, b), minv = min(a, b); + res += min(maxv - minv, minv - maxv + 26); + prev = c; + } + res += word.size(); + return res; + } +}; + +int main() { + + cout << Solution().minTimeToType("abc") << endl; + // 5 + + return 0; +} diff --git a/1501-2000/1975-Maximum-Matrix-Sum/cpp-1975/CMakeLists.txt b/1501-2000/1975-Maximum-Matrix-Sum/cpp-1975/CMakeLists.txt new file mode 100644 index 00000000..db9b9fb8 --- /dev/null +++ b/1501-2000/1975-Maximum-Matrix-Sum/cpp-1975/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_1975) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1975 main.cpp) diff --git a/1501-2000/1975-Maximum-Matrix-Sum/cpp-1975/main.cpp b/1501-2000/1975-Maximum-Matrix-Sum/cpp-1975/main.cpp new file mode 100644 index 00000000..339728ea --- /dev/null +++ b/1501-2000/1975-Maximum-Matrix-Sum/cpp-1975/main.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/maximum-matrix-sum/ +/// Author : liuyubobobo +/// Time : 2021-08-21 + +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(n^2 * log(n^2)) +/// Space Complexity: O(n^2) +class Solution { +public: + long long maxMatrixSum(vector>& matrix) { + + int neg = 0; + vector v; + for(const vector& row: matrix){ + for(int e: row){ + neg += (e < 0); + v.push_back(abs(e)); + } + } + + sort(v.begin(), v.end()); + if(neg & 1) v[0] = -v[0]; + + long long res = 0ll; + for(long long e: v) res += e; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1976-Number-of-Ways-to-Arrive-at-Destination/cpp-1976/CMakeLists.txt b/1501-2000/1976-Number-of-Ways-to-Arrive-at-Destination/cpp-1976/CMakeLists.txt new file mode 100644 index 00000000..786f7abb --- /dev/null +++ b/1501-2000/1976-Number-of-Ways-to-Arrive-at-Destination/cpp-1976/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_1976) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1976 main.cpp) diff --git a/1501-2000/1976-Number-of-Ways-to-Arrive-at-Destination/cpp-1976/main.cpp b/1501-2000/1976-Number-of-Ways-to-Arrive-at-Destination/cpp-1976/main.cpp new file mode 100644 index 00000000..547b2ecf --- /dev/null +++ b/1501-2000/1976-Number-of-Ways-to-Arrive-at-Destination/cpp-1976/main.cpp @@ -0,0 +1,74 @@ +/// Source : https://leetcode.com/problems/number-of-ways-to-arrive-at-destination/ +/// Author : liuyubobobo +/// Time : 2021-08-21 + +#include +#include +#include + +using namespace std; + + +/// Dijkstra +/// Time Complexity: O(ElogE) +/// Space Complexity: O(V + E) +class Solution { + +private: + const int MOD = 1e9 + 7; + +public: + int countPaths(int n, vector>& roads) { + + vector>> g(n); + for(const vector& e: roads){ + int a = e[0], b = e[1], w = e[2]; + g[a].push_back({b, w}); + g[b].push_back({a, w}); + } + + vector dis(n, LONG_LONG_MAX / 2); + vector dp(n, 0); + vector visited(n, false); + priority_queue, vector>, greater>> pq; + pq.push({0ll, 0}); + dp[0] = 1; + while(!pq.empty()){ + long long d = pq.top().first; + int u = pq.top().second; + pq.pop(); + + if(visited[u]) continue; + visited[u] = true; + + for(const pair& p: g[u]){ + int v = p.first; + long long w = p.second; + if(!visited[v]){ + if(d + w < dis[v]){ + dis[v] = d + w; + dp[v] = dp[u]; + pq.push({dis[v], v}); + } + else if(d + w == dis[v]) + dp[v] = (dp[v] + dp[u]) % MOD; + } + } + } +// cout << dis.back() << endl; + return dp.back(); + } +}; + + +int main() { + + vector> roads = { + {0,6,7},{0,1,2},{1,2,3},{1,3,3},{6,3,3}, + {3,5,1},{6,5,1},{2,5,1},{0,4,5},{4,6,2} + }; + cout << Solution().countPaths(7, roads) << endl; + // 4 + + return 0; +} diff --git a/1501-2000/1977-Number-of-Ways-to-Separate-Numbers/cpp-1977/CMakeLists.txt b/1501-2000/1977-Number-of-Ways-to-Separate-Numbers/cpp-1977/CMakeLists.txt new file mode 100644 index 00000000..4d2888f7 --- /dev/null +++ b/1501-2000/1977-Number-of-Ways-to-Separate-Numbers/cpp-1977/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_1977) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1977 main2.cpp) diff --git a/1501-2000/1977-Number-of-Ways-to-Separate-Numbers/cpp-1977/main.cpp b/1501-2000/1977-Number-of-Ways-to-Separate-Numbers/cpp-1977/main.cpp new file mode 100644 index 00000000..bffae398 --- /dev/null +++ b/1501-2000/1977-Number-of-Ways-to-Separate-Numbers/cpp-1977/main.cpp @@ -0,0 +1,109 @@ +/// Source : https://leetcode.com/problems/number-of-ways-to-separate-numbers/ +/// Author : liuyubobobo +/// Time : 2021-08-23 + +#include +#include + +using namespace std; + + +/// RK + DP +/// Time Complexity: O(n^2) +/// Space Complexity: O(n^2) +template +class StringHash{ + +private: + int n; + T B, MOD; + vector h, p; + +public: + StringHash(const string& s, T B = 128, T MOD = 1e9+ 7) : + n(s.size()), h(n + 1, 0), p(n + 1, 1), B(B), MOD(MOD){ + + for(int i = 0; i < n; i ++){ + h[i + 1] = (h[i] * B + s[i]) % MOD; + p[i + 1] = p[i] * B % MOD; + } + } + + T get_hash(int l, int r){ + // assert(l >= 0 && l < n); + // assert(r >= 0 && r < n); + // return (h[r + 1] - h[l] * p[r - l + 1] % MOD + MOD) % MOD; + + // 对于有符号类型,以下代码更快 + T res = (h[r + 1] - h[l] * p[r - l + 1]) % MOD; + return res < 0 ? res + MOD : res; + } +}; + +class Solution { + +private: + const int MOD = 1e9 + 7; + StringHash *hash; + +public: + int numberOfCombinations(string num) { + + int n = num.size(); + hash = new StringHash(num); + vector> dp(n + 1, vector(n, 0)); // (len, start) + vector> presum(n + 1, vector(n, 0)); + + dp[n][0] = num[0] != '0'; + presum[n][0] = dp[n][0]; + for(int len = n - 1; len >= 1; len --){ + dp[len][n - len] = num[n - len] != '0'; + for(int start = n - len - 1; start >= 0; start --){ + if(num[start] == '0') continue; + dp[len][start] = presum[len + 1][start + len]; + if(start + len + len <= n && less_or_equal(num, start, start + len, len)) + dp[len][start] += dp[len][start + len]; + dp[len][start] %= MOD; + } + + for(int i = 0; i < n; i ++) + presum[len][i] = (dp[len][i] + presum[len + 1][i]) % MOD; + } + + return presum[1][0]; + } + +private: + bool less_or_equal(const string& num, int start1, int start2, int len){ + if(hash->get_hash(start1, start1 + len - 1) == hash->get_hash(start2, start2 + len - 1)) + return true; + + for(int k = 0; k < len; k ++){ + if(num[start1 + k] < num[start2 + k]) return true; + else if(num[start1 + k] > num[start2 + k]) return false; + } + + return true; + } +}; + + +int main() { + + cout << Solution().numberOfCombinations("327") << endl; + // 2 + + cout << Solution().numberOfCombinations("094") << endl; + // 0 + + cout << Solution().numberOfCombinations("0") << endl; + // 0 + + cout << Solution().numberOfCombinations("9999999999999") << endl; + // 101 + + cout << Solution().numberOfCombinations("11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111") << endl; + // 755568658 + + return 0; +} diff --git a/1501-2000/1977-Number-of-Ways-to-Separate-Numbers/cpp-1977/main2.cpp b/1501-2000/1977-Number-of-Ways-to-Separate-Numbers/cpp-1977/main2.cpp new file mode 100644 index 00000000..77e4aa55 --- /dev/null +++ b/1501-2000/1977-Number-of-Ways-to-Separate-Numbers/cpp-1977/main2.cpp @@ -0,0 +1,105 @@ +/// Source : https://leetcode.com/problems/number-of-ways-to-separate-numbers/ +/// Author : liuyubobobo +/// Time : 2021-08-23 + +#include +#include + +using namespace std; + + +/// RK + DP + Space Optimizaed +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +template +class StringHash{ + +private: + int n; + T B, MOD; + vector h, p; + +public: + StringHash(const string& s, T B = 128, T MOD = 1e9+ 7) : + n(s.size()), h(n + 1, 0), p(n + 1, 1), B(B), MOD(MOD){ + + for(int i = 0; i < n; i ++){ + h[i + 1] = (h[i] * B + s[i]) % MOD; + p[i + 1] = p[i] * B % MOD; + } + } + + T get_hash(int l, int r){ + T res = (h[r + 1] - h[l] * p[r - l + 1]) % MOD; + return res < 0 ? res + MOD : res; + } +}; + +class Solution { + +private: + const int MOD = 1e9 + 7; + StringHash *hash; + +public: + int numberOfCombinations(string num) { + + int n = num.size(); + hash = new StringHash(num); + vector dp(n, 0); // (len, start) + vector presum(n, 0); + + dp[0] = num[0] != '0'; + presum[0] = dp[0]; + for(int len = n - 1; len >= 1; len --){ + dp.assign(n, 0); + dp[n - len] = num[n - len] != '0'; + for(int start = n - len - 1; start >= 0; start --){ + if(num[start] == '0') continue; + dp[start] = presum[start + len]; + if(start + len + len <= n && less_or_equal(num, start, start + len, len)) + dp[start] += dp[start + len]; + dp[start] %= MOD; + } + + for(int i = 0; i < n; i ++) + presum[i] = (presum[i] + dp[i]) % MOD; + } + + return presum[0]; + } + +private: + bool less_or_equal(const string& num, int start1, int start2, int len){ + if(hash->get_hash(start1, start1 + len - 1) == hash->get_hash(start2, start2 + len - 1)) + return true; + + for(int k = 0; k < len; k ++){ + if(num[start1 + k] < num[start2 + k]) return true; + else if(num[start1 + k] > num[start2 + k]) return false; + } + + return true; + } +}; + + +int main() { + + cout << Solution().numberOfCombinations("327") << endl; + // 2 + + cout << Solution().numberOfCombinations("094") << endl; + // 0 + + cout << Solution().numberOfCombinations("0") << endl; + // 0 + + cout << Solution().numberOfCombinations("9999999999999") << endl; + // 101 + + cout << Solution().numberOfCombinations("11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111") << endl; + // 755568658 + + return 0; +} diff --git a/1501-2000/1979-Find-Greatest-Common-Divisor-of-Array/cpp-1979/CMakeLists.txt b/1501-2000/1979-Find-Greatest-Common-Divisor-of-Array/cpp-1979/CMakeLists.txt new file mode 100644 index 00000000..2ae8397c --- /dev/null +++ b/1501-2000/1979-Find-Greatest-Common-Divisor-of-Array/cpp-1979/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/1501-2000/1979-Find-Greatest-Common-Divisor-of-Array/cpp-1979/main.cpp b/1501-2000/1979-Find-Greatest-Common-Divisor-of-Array/cpp-1979/main.cpp new file mode 100644 index 00000000..7352cd37 --- /dev/null +++ b/1501-2000/1979-Find-Greatest-Common-Divisor-of-Array/cpp-1979/main.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/find-greatest-common-divisor-of-array/ +/// Author : liuyubobobo +/// Time : 2021-08-21 + +#include +#include + +using namespace std; + + +/// GCD +/// Time Complexity: O(nlogn) +/// Space Complexity: O(logn) +class Solution { +public: + int findGCD(vector& nums) { + + sort(nums.begin(), nums.end()); + return gcd(nums[0], nums.back()); + } + +private: + int gcd(int a, int b) + { + if (a == 0) return b; + return gcd(b % a, a); + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1980-Find-Unique-Binary-String/cpp-1980/CMakeLists.txt b/1501-2000/1980-Find-Unique-Binary-String/cpp-1980/CMakeLists.txt new file mode 100644 index 00000000..084dd354 --- /dev/null +++ b/1501-2000/1980-Find-Unique-Binary-String/cpp-1980/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main2.cpp) diff --git a/1501-2000/1980-Find-Unique-Binary-String/cpp-1980/main.cpp b/1501-2000/1980-Find-Unique-Binary-String/cpp-1980/main.cpp new file mode 100644 index 00000000..17c1c622 --- /dev/null +++ b/1501-2000/1980-Find-Unique-Binary-String/cpp-1980/main.cpp @@ -0,0 +1,61 @@ +/// Source : https://leetcode.com/problems/find-unique-binary-string/ +/// Author : liuyubobobo +/// Time : 2021-08-21 + +#include +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { +public: + string findDifferentBinaryString(vector& nums) { + + set set; + for(const string& s: nums) set.insert(to_int(s)); + + for(int i = 0; ; i ++) + if(!set.count(i)) + return to_binary_string(i, nums.size()); + return ""; + } + +private: + string to_binary_string(int x, int len){ + + string s(len, ' '); + for(int i = 0; i < len; i ++) + s[len - 1 - i] = ('0' + x % 2), x /= 2; + return s; + } + + int to_int(const string& s){ + int res = 0; + for(char c: s) + res = res * 2 + (c - '0'); + return res; + } +}; + + +int main() { + + vector nums1 = {"01", "10"}; + cout << Solution().findDifferentBinaryString(nums1) << endl; + // 11 + + vector nums2 = {"00", "01"}; + cout << Solution().findDifferentBinaryString(nums2) << endl; + // 11 + + vector nums3 = {"111", "011", "001"}; + cout << Solution().findDifferentBinaryString(nums3) << endl; + // 101 + + return 0; +} diff --git a/1501-2000/1980-Find-Unique-Binary-String/cpp-1980/main2.cpp b/1501-2000/1980-Find-Unique-Binary-String/cpp-1980/main2.cpp new file mode 100644 index 00000000..f712a720 --- /dev/null +++ b/1501-2000/1980-Find-Unique-Binary-String/cpp-1980/main2.cpp @@ -0,0 +1,44 @@ +/// Source : https://leetcode.com/problems/find-unique-binary-string/ +/// Author : liuyubobobo +/// Time : 2021-08-23 + +#include +#include +#include + +using namespace std; + + +/// Cantor's Diagonalization +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + string findDifferentBinaryString(vector& nums) { + + int n = nums.size(); + + string res = ""; + for(int i = 0; i < n; i ++) + res += nums[i][i] == '0' ? "1" : "0"; + return res; + } +}; + + +int main() { + + vector nums1 = {"01", "10"}; + cout << Solution().findDifferentBinaryString(nums1) << endl; + // 11 + + vector nums2 = {"00", "01"}; + cout << Solution().findDifferentBinaryString(nums2) << endl; + // 11 + + vector nums3 = {"111", "011", "001"}; + cout << Solution().findDifferentBinaryString(nums3) << endl; + // 101 + + return 0; +} diff --git a/1501-2000/1981-Minimize-the-Difference-Between-Target-and-Chosen-Elements/cpp-1981/CMakeLists.txt b/1501-2000/1981-Minimize-the-Difference-Between-Target-and-Chosen-Elements/cpp-1981/CMakeLists.txt new file mode 100644 index 00000000..cad75f71 --- /dev/null +++ b/1501-2000/1981-Minimize-the-Difference-Between-Target-and-Chosen-Elements/cpp-1981/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/1501-2000/1981-Minimize-the-Difference-Between-Target-and-Chosen-Elements/cpp-1981/main.cpp b/1501-2000/1981-Minimize-the-Difference-Between-Target-and-Chosen-Elements/cpp-1981/main.cpp new file mode 100644 index 00000000..00c13361 --- /dev/null +++ b/1501-2000/1981-Minimize-the-Difference-Between-Target-and-Chosen-Elements/cpp-1981/main.cpp @@ -0,0 +1,73 @@ +/// Source : https://leetcode.com/problems/minimize-the-difference-between-target-and-chosen-elements/ +/// Author : liuyubobobo +/// Time : 2021-08-21 + +#include +#include + +using namespace std; + + +/// Memoization +/// Time Complexity: O(R * C * target) +/// Space Complexity: O(R * target) +class Solution { + +private: + int R, C; + +public: + int minimizeTheDifference(vector>& mat, int target) { + + for(vector& row: mat) sort(row.begin(), row.end()); + + R = mat.size(), C = mat[0].size(); + vector> dp(R, vector(target + 1, -1)); + return dfs(mat, 0, target, dp); + } + +private: + int dfs(const vector>& mat, int r, int t, + vector>& dp){ + + if(r == R) return t; + if(dp[r][t] != -1) return dp[r][t]; + + int res = INT_MAX; + for(int j = 0; j < C; j ++){ + if(t >= mat[r][j]) + res = min(res, dfs(mat, r + 1, t - mat[r][j], dp)); + else{ + int tres = t - mat[r][j]; + for(int i = r + 1; i < R; i ++) + tres -= mat[i][0]; + res = min(res, -tres); + } + } + return dp[r][t] = res; + } +}; + + +int main() { + + vector> mat1 = { + {1,2,3},{4,5,6},{7,8,9} + }; + cout << Solution().minimizeTheDifference(mat1, 13) << endl; + // 0 + + vector> mat2 = { + {1},{2},{3} + }; + cout << Solution().minimizeTheDifference(mat2, 100) << endl; + // 94 + + vector> mat3 = { + {1,2,9,8,7} + }; + cout << Solution().minimizeTheDifference(mat3, 6) << endl; + // 1 + + return 0; +} diff --git a/1501-2000/1982-Find-Array-Given-Subset-Sums/cpp-1982/CMakeLists.txt b/1501-2000/1982-Find-Array-Given-Subset-Sums/cpp-1982/CMakeLists.txt new file mode 100644 index 00000000..a0d16fe6 --- /dev/null +++ b/1501-2000/1982-Find-Array-Given-Subset-Sums/cpp-1982/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) diff --git a/1501-2000/1982-Find-Array-Given-Subset-Sums/cpp-1982/main.cpp b/1501-2000/1982-Find-Array-Given-Subset-Sums/cpp-1982/main.cpp new file mode 100644 index 00000000..53c1aeaf --- /dev/null +++ b/1501-2000/1982-Find-Array-Given-Subset-Sums/cpp-1982/main.cpp @@ -0,0 +1,128 @@ +/// Source : https://leetcode.com/problems/find-array-given-subset-sums/ +/// Author : liuyubobobo +/// Time : 2021-08-23 + +#include +#include +#include + +using namespace std; + + +/// Recursive +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + vector recoverArray(int n, vector& sums) { + + sort(sums.begin(), sums.end()); + + vector res; + assert(dfs(sums, res)); + return res; + } + +private: + bool dfs(const vector& sums, vector& res){ + + if(sums.size() == 2){ + res.push_back(sums[0] == 0 ? sums[1] : sums[0]); + return true; + } + + int d = sums[1] - sums[0]; + + vector half; + if(can_split(sums, d, half)){ + res.push_back(d); + if(dfs(half, res)) return true; + res.pop_back(); + } + + half.clear(); + if(can_split(sums, -d, half)){ + res.push_back(-d); + assert(dfs(half, res)); + return true; + } + + return false; + } + + bool can_split(const vector& sums, int p, vector& left){ + + multiset set; + for(int e: sums) set.insert(e); + if(!set.count(p) || !set.count(0)) return false; + + set.erase(set.find(0)); + set.erase(set.find(p)); + left.push_back(0); + + multiset::iterator iter; + + if(p <= 0){ + while(!set.empty()){ + int cur = *set.begin(); + set.erase(set.find(cur)); + + iter = set.find(cur - p); + if(iter == set.end()) return false; + set.erase(iter); + + left.push_back(cur - p); + } + } + else{ + while(!set.empty()){ + int cur = *set.rbegin(); + set.erase(set.find(cur)); + + iter = set.find(cur - p); + if(iter == set.end()) return false; + set.erase(iter); + + left.push_back(cur - p); + } + } + + assert(left.size() * 2 == sums.size()); + sort(left.begin(), left.end()); + return true; + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << ' '; cout << '\n'; +} + +int main() { + + vector sums1 = {-3, -2, -1, 0, 0, 1, 2, 3}; + print_vec(Solution().recoverArray(3, sums1)); + // 1 2 -3 + + vector sums2 = {0, 0, 0, 0}; + print_vec(Solution().recoverArray(2, sums2)); + // 0 0 + + vector sums3 = {0,0,5,5,4,-1,4,9,9,-1,4,3,4,8,3,8}; + print_vec(Solution().recoverArray(4, sums3)); + // -1 0 4 5 + + vector sums4 = {-1654,-771,-883,0}; + print_vec(Solution().recoverArray(2, sums4)); + // -771, -883 + + vector sums5 = {-574,-394,0,180,-180,-574,-754,0}; + print_vec(Solution().recoverArray(3, sums5)); + // 180 -180 -574 + + vector sums6 = {-607,0,-720,105,-502,893,286,-539,-434,998,68,-1327,-1432,391,173,-825}; + print_vec(Solution().recoverArray(4, sums6)); + // 105 -607 -825 893 + + return 0; +} diff --git a/1501-2000/1983-Widest-Pair-of-Indices-With-Equal-Range-Sum/cpp-1983/CMakeLists.txt b/1501-2000/1983-Widest-Pair-of-Indices-With-Equal-Range-Sum/cpp-1983/CMakeLists.txt new file mode 100644 index 00000000..be8c0327 --- /dev/null +++ b/1501-2000/1983-Widest-Pair-of-Indices-With-Equal-Range-Sum/cpp-1983/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_1983) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1983 main.cpp) diff --git a/1501-2000/1983-Widest-Pair-of-Indices-With-Equal-Range-Sum/cpp-1983/main.cpp b/1501-2000/1983-Widest-Pair-of-Indices-With-Equal-Range-Sum/cpp-1983/main.cpp new file mode 100644 index 00000000..175a2eaf --- /dev/null +++ b/1501-2000/1983-Widest-Pair-of-Indices-With-Equal-Range-Sum/cpp-1983/main.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/widest-pair-of-indices-with-equal-range-sum/ +/// Author : liuyubobobo +/// Time : 2021-08-27 + +#include +#include +#include + +using namespace std; + + +/// Hash Table +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int widestPairOfIndices(vector& nums1, vector& nums2) { + + int n = nums1.size(); + vector data(n); + for(int i = 0; i < n; i ++) + data[i] = nums1[i] - nums2[i]; + + unordered_map map; + map[0] = -1; + int res = 0, cur = 0; + for(int i = 0; i < n; i ++){ + cur += data[i]; + if(map.count(cur)) + res = max(res, i - map[cur]); + else + map[cur] = i; + } + return res; + } +}; + + +int main() { + + vector nums11 = {1, 1, 0, 1}, nums12 = {0, 1, 1, 0}; + cout << Solution().widestPairOfIndices(nums11, nums12) << endl; + // 3 + + vector nums21 = {0, 1, 1}, nums22 = {1, 0, 1}; + cout << Solution().widestPairOfIndices(nums21, nums22) << endl; + // 3 + + return 0; +} diff --git a/1501-2000/1984-Minimum-Difference-Between-Highest-and-Lowest-of-K Scores/cpp-1984/CMakeLists.txt b/1501-2000/1984-Minimum-Difference-Between-Highest-and-Lowest-of-K Scores/cpp-1984/CMakeLists.txt new file mode 100644 index 00000000..2ae8397c --- /dev/null +++ b/1501-2000/1984-Minimum-Difference-Between-Highest-and-Lowest-of-K Scores/cpp-1984/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/1501-2000/1984-Minimum-Difference-Between-Highest-and-Lowest-of-K Scores/cpp-1984/main.cpp b/1501-2000/1984-Minimum-Difference-Between-Highest-and-Lowest-of-K Scores/cpp-1984/main.cpp new file mode 100644 index 00000000..045f64ed --- /dev/null +++ b/1501-2000/1984-Minimum-Difference-Between-Highest-and-Lowest-of-K Scores/cpp-1984/main.cpp @@ -0,0 +1,32 @@ +/// Source : https://leetcode.com/problems/minimum-difference-between-highest-and-lowest-of-k-scores/ +/// Author : liuyubobobo +/// Time : 2021-08-28 + +#include +#include + +using namespace std; + + +/// Linear Scan +/// Time Compleixty: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int minimumDifference(vector& nums, int k) { + + if(k == 1) return 0; + sort(nums.begin(), nums.end()); + + int res = INT_MAX; + for(int i = k - 1; i < nums.size(); i ++) + res = min(res, nums[i] - nums[i - (k - 1)]); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1985-Find-the-Kth-Largest-Integer-in-the-Array/cpp-1985/CMakeLists.txt b/1501-2000/1985-Find-the-Kth-Largest-Integer-in-the-Array/cpp-1985/CMakeLists.txt new file mode 100644 index 00000000..3f98647f --- /dev/null +++ b/1501-2000/1985-Find-the-Kth-Largest-Integer-in-the-Array/cpp-1985/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/1501-2000/1985-Find-the-Kth-Largest-Integer-in-the-Array/cpp-1985/main.cpp b/1501-2000/1985-Find-the-Kth-Largest-Integer-in-the-Array/cpp-1985/main.cpp new file mode 100644 index 00000000..2def3001 --- /dev/null +++ b/1501-2000/1985-Find-the-Kth-Largest-Integer-in-the-Array/cpp-1985/main.cpp @@ -0,0 +1,51 @@ +/// Source : https://leetcode.com/problems/find-the-kth-largest-integer-in-the-array/ +/// Author : liuyubobobo +/// Time : 2021-08-28 + +#include +#include + +using namespace std; + + +/// Adding leading 0 and sort +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + string kthLargestNumber(vector& nums, int k) { + + int maxlen = 0; + for(const string& num: nums) maxlen = max(maxlen, (int)num.size()); + + for(string& num: nums) num = string(maxlen - num.size(), '0') + num; + + sort(nums.begin(), nums.end(), greater()); + + string res = nums[k - 1]; + while(res.size() > 1 && res[0] == '0') res = res.substr(1); + return res; + } +}; + + +int main() { + + vector nums1 = {"3","6","7","10"}; + cout << Solution().kthLargestNumber(nums1, 4) << endl; + // 3 + + vector nums2 = {"2","21","12","1"}; + cout << Solution().kthLargestNumber(nums2, 3) << endl; + // 2 + + vector nums3 = {"0","0"}; + cout << Solution().kthLargestNumber(nums3, 2) << endl; + // 0 + + vector nums4 = {"623986800","3","887298","695","794","6888794705","269409","59930972","723091307","726368","8028385786","378585"}; + cout << Solution().kthLargestNumber(nums4, 11) << endl; + // 695 + + return 0; +} diff --git a/1501-2000/1986-Minimum-Number-of-Work-Sessions-to-Finish-the-Tasks/cpp-1986/CMakeLists.txt b/1501-2000/1986-Minimum-Number-of-Work-Sessions-to-Finish-the-Tasks/cpp-1986/CMakeLists.txt new file mode 100644 index 00000000..cad75f71 --- /dev/null +++ b/1501-2000/1986-Minimum-Number-of-Work-Sessions-to-Finish-the-Tasks/cpp-1986/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/1501-2000/1986-Minimum-Number-of-Work-Sessions-to-Finish-the-Tasks/cpp-1986/main.cpp b/1501-2000/1986-Minimum-Number-of-Work-Sessions-to-Finish-the-Tasks/cpp-1986/main.cpp new file mode 100644 index 00000000..13201365 --- /dev/null +++ b/1501-2000/1986-Minimum-Number-of-Work-Sessions-to-Finish-the-Tasks/cpp-1986/main.cpp @@ -0,0 +1,59 @@ +/// Source : https://leetcode.com/problems/minimum-number-of-work-sessions-to-finish-the-tasks/ +/// Author : liuyubobobo +/// Time : 2021-08-28 + +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(n^2 * 2^n) +/// Space Complexity: O(n * 2^n) +class Solution { +public: + int minSessions(vector& tasks, int sessionTime) { + + int n = tasks.size(); + vector> dp(sessionTime + 1, vector(1 << n, -1)); + + return 1 + dfs(n, tasks, sessionTime, sessionTime, (1 << n) - 1, dp); + } + +private: + int dfs(int n, vector& tasks, int sessionTime, + int left, int state, vector>& dp){ + + if(state == 0) return 0; + if(dp[left][state] != -1) return dp[left][state]; + + int res = INT_MAX; + for(int i = 0; i < n; i ++) + if((1 << i) & state){ + if(left >= tasks[i]) + res = min(res, dfs(n, tasks, sessionTime, left - tasks[i], state - (1 << i), dp)); + else + res = min(res, 1 + dfs(n, tasks, sessionTime, sessionTime - tasks[i], state - (1 << i), dp)); + } + return dp[left][state] = res; + } +}; + + +int main() { + + vector task1 = {1, 2, 3}; + cout << Solution().minSessions(task1, 3) << endl; + // 2 + + vector task2 = {3, 1, 3, 1, 1}; + cout << Solution().minSessions(task2, 8) << endl; + // 2 + + vector task3 = {1, 2, 3, 4, 5}; + cout << Solution().minSessions(task3, 15) << endl; + // 1 + + return 0; +} diff --git a/1501-2000/1987-Number-of-Unique-Good-Subsequences/cpp-1987/CMakeLists.txt b/1501-2000/1987-Number-of-Unique-Good-Subsequences/cpp-1987/CMakeLists.txt new file mode 100644 index 00000000..a0d16fe6 --- /dev/null +++ b/1501-2000/1987-Number-of-Unique-Good-Subsequences/cpp-1987/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) diff --git a/1501-2000/1987-Number-of-Unique-Good-Subsequences/cpp-1987/main.cpp b/1501-2000/1987-Number-of-Unique-Good-Subsequences/cpp-1987/main.cpp new file mode 100644 index 00000000..0aa2901e --- /dev/null +++ b/1501-2000/1987-Number-of-Unique-Good-Subsequences/cpp-1987/main.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/number-of-unique-good-subsequences/ +/// Author : liuyubobobo +/// Time : 2021-08-31 + +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { + +private: + const int MOD = 1e9 + 7; + +public: + int numberOfUniqueGoodSubsequences(string binary) { + + int end0 = 0, end1 = 0; + for(char c: binary){ + if(c == '0') end0 = (end0 + end1) % MOD; + else end1 = (end0 + end1 + 1) % MOD; + } + return (end0 + end1 + (binary.find('0') != string::npos)) % MOD; + } +}; + + +int main() { + + cout << Solution().numberOfUniqueGoodSubsequences("001") << endl; + // 2 + + cout << Solution().numberOfUniqueGoodSubsequences("11") << endl; + // 2 + + cout << Solution().numberOfUniqueGoodSubsequences("101") << endl; + // 5 + + cout << Solution().numberOfUniqueGoodSubsequences("1110001") << endl; + // 23 + + return 0; +} diff --git a/1501-2000/1989-Maximum-Number-of-People-That-Can-Be-Caught-in-Tag/cpp-1989/CMakeLists.txt b/1501-2000/1989-Maximum-Number-of-People-That-Can-Be-Caught-in-Tag/cpp-1989/CMakeLists.txt new file mode 100644 index 00000000..0c1ef8fe --- /dev/null +++ b/1501-2000/1989-Maximum-Number-of-People-That-Can-Be-Caught-in-Tag/cpp-1989/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_1989) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1989 main.cpp) diff --git a/1501-2000/1989-Maximum-Number-of-People-That-Can-Be-Caught-in-Tag/cpp-1989/main.cpp b/1501-2000/1989-Maximum-Number-of-People-That-Can-Be-Caught-in-Tag/cpp-1989/main.cpp new file mode 100644 index 00000000..113b1e89 --- /dev/null +++ b/1501-2000/1989-Maximum-Number-of-People-That-Can-Be-Caught-in-Tag/cpp-1989/main.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/maximum-number-of-people-that-can-be-caught-in-tag/ +/// Author : liuyubobobo +/// Time : 2021-09-05 + +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int catchMaximumAmountofPeople(vector& team, int dist) { + + int n = team.size(); + + int res = 0, l = 0; + for(int i = 0; i < n; i ++) + if(team[i]){ + l = max(l, i - dist); + while(l <= min(i + dist, n - 1)) + if(team[l] == 0){ + res ++; + l ++; + break; + } + else l ++; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1991-Find-the-Middle-Index-in-Array/cpp-1991/CMakeLists.txt b/1501-2000/1991-Find-the-Middle-Index-in-Array/cpp-1991/CMakeLists.txt new file mode 100644 index 00000000..3a8dd26c --- /dev/null +++ b/1501-2000/1991-Find-the-Middle-Index-in-Array/cpp-1991/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_1991) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1991 main.cpp) diff --git a/1501-2000/1991-Find-the-Middle-Index-in-Array/cpp-1991/main.cpp b/1501-2000/1991-Find-the-Middle-Index-in-Array/cpp-1991/main.cpp new file mode 100644 index 00000000..920d0c0b --- /dev/null +++ b/1501-2000/1991-Find-the-Middle-Index-in-Array/cpp-1991/main.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/find-the-middle-index-in-array/ +/// Author : liuyubobobo +/// Time : 2021-09-05 + +#include +#include + +using namespace std; + + +/// Presum +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int findMiddleIndex(vector& nums) { + + int n = nums.size(); + vector presum(n + 1, 0); + for(int i = 0; i < nums.size(); i ++) + presum[i + 1] = presum[i] + nums[i]; + + for(int i = 0; i < n; i ++) + if(presum[i] == presum[n] - presum[i + 1]) return i; + return -1; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1992-Find-All-Groups-of-Farmland/cpp-1992/CMakeLists.txt b/1501-2000/1992-Find-All-Groups-of-Farmland/cpp-1992/CMakeLists.txt new file mode 100644 index 00000000..f339bc1d --- /dev/null +++ b/1501-2000/1992-Find-All-Groups-of-Farmland/cpp-1992/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_1992) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1992 main.cpp) diff --git a/1501-2000/1992-Find-All-Groups-of-Farmland/cpp-1992/main.cpp b/1501-2000/1992-Find-All-Groups-of-Farmland/cpp-1992/main.cpp new file mode 100644 index 00000000..e4e9f0a4 --- /dev/null +++ b/1501-2000/1992-Find-All-Groups-of-Farmland/cpp-1992/main.cpp @@ -0,0 +1,60 @@ +/// Source : https://leetcode.com/problems/find-all-groups-of-farmland/ +/// Author : liuyubobobo +/// Time : 2021-09-05 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(m * n) +/// Space Complexity: O(m * n) +class Solution { + +private: + int R, C; + +public: + vector> findFarmland(vector>& land) { + + R = land.size(), C = land[0].size(); + vector> res; + vector> visited(R, vector(C, false)); + + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++) + if(land[i][j] == 1 && !visited[i][j]){ + res.push_back(find_rec(land, i, j, visited)); + } + return res; + } + +private: + vector find_rec(const vector>& land, int sx, int sy, + vector>& visited){ + + vector res = {sx, sy}; + int i, j; + for(i = sx; i < R; i ++) + if(land[i][sy] == 0) break; + + for(j = sy; j < C; j ++) + if(land[sx][j] == 0) break; + + res.push_back(i - 1); + res.push_back(j - 1); + + for(int i = sx; i <= res[2]; i ++) + for(int j = sy; j <= res[3]; j ++) + visited[i][j] = true; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1993-Operations-on-Tree/cpp-1993/CMakeLists.txt b/1501-2000/1993-Operations-on-Tree/cpp-1993/CMakeLists.txt new file mode 100644 index 00000000..f2169263 --- /dev/null +++ b/1501-2000/1993-Operations-on-Tree/cpp-1993/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_1993) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1993 main.cpp) diff --git a/1501-2000/1993-Operations-on-Tree/cpp-1993/main.cpp b/1501-2000/1993-Operations-on-Tree/cpp-1993/main.cpp new file mode 100644 index 00000000..8db4fbf9 --- /dev/null +++ b/1501-2000/1993-Operations-on-Tree/cpp-1993/main.cpp @@ -0,0 +1,95 @@ +/// Source : https://leetcode.com/problems/operations-on-tree/ +/// Author : liuyubobobo +/// Time : 2021-09-05 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: init: O(n) +/// lock: O(1) +/// unlock: O(1) +/// upgrade: O(n) +/// Space Complexity: O(n) +class LockingTree { + +private: + int n; + vector parent; + vector> tree; + vector locked; + +public: + LockingTree(vector& parent) : n(parent.size()), parent(parent), tree(n), locked(n, 0) { + + for(int i = 1; i < n; i ++) + tree[parent[i]].push_back(i); + } + + bool lock(int num, int user) { + + if(locked[num]) return false; + + locked[num] = user; + return true; + } + + bool unlock(int num, int user) { + + if(locked[num] != user) return false; + + locked[num] = 0; + return true; + } + + bool upgrade(int num, int user) { + + if(locked[num]) return false; + + int locked_descendants = get_locked_descendants(num, parent[num]); + if(locked_descendants == 0) return false; + + int locked_ancestors = get_locked_ancestors(num); + if(locked_ancestors) return false; + + unlock_descendants(num, parent[num]); + locked[num] = user; + return true; + } + +private: + void unlock_descendants(int u, int p){ + + if(locked[u]) locked[u] = 0; + for(int v: tree[u]) + if(v != p) unlock_descendants(v, u); + } + + int get_locked_descendants(int u, int p){ + + int res = 0; + if(locked[u]) res ++; + for(int v: tree[u]) + if(v != p) res += get_locked_descendants(v, u); + return res; + } + + int get_locked_ancestors(int u){ + + int res = 0; + while(u != -1){ + res += !!locked[u]; + u = parent[u]; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/1501-2000/1994-The-Number-of-Good-Subsets/cpp-1994/CMakeLists.txt b/1501-2000/1994-The-Number-of-Good-Subsets/cpp-1994/CMakeLists.txt new file mode 100644 index 00000000..532c940b --- /dev/null +++ b/1501-2000/1994-The-Number-of-Good-Subsets/cpp-1994/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_1994) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1994 main.cpp) diff --git a/1501-2000/1994-The-Number-of-Good-Subsets/cpp-1994/main.cpp b/1501-2000/1994-The-Number-of-Good-Subsets/cpp-1994/main.cpp new file mode 100644 index 00000000..fc3ad97b --- /dev/null +++ b/1501-2000/1994-The-Number-of-Good-Subsets/cpp-1994/main.cpp @@ -0,0 +1,98 @@ +/// Source : https://leetcode.com/problems/the-number-of-good-subsets/ +/// Author : liuyubobobo +/// Time : 2021-09-05 + +#include +#include +#include + +using namespace std; + + +/// Memoization +/// Time Complexity: O(19 * 2^11) +/// Space Complexity: O(19 * 2^11) +class Solution { + +private: + vector primes = {1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29}; + const long long MOD = 1e9 + 7; + +public: + int numberOfGoodSubsets(vector& nums) { + + int maxv = *max_element(nums.begin(), nums.end()); + vector num2state(31, 0); + num2state[1] = 1; + for(int i = 2; i <= maxv; i ++) + num2state[i] = get_num_state(i); + + map map; + for(int num: nums) + if(num2state[num] != -1) map[num] ++; + + vector> f; + for(const pair& p: map) f.push_back(p); + + vector> dp(f.size(), vector(1 << 11, -1ll)); + return dfs(0, 0, num2state, f, dp); + } + +private: + long long dfs(int index, int state, + const vector& num2state, const vector>& f, + vector>& dp){ + + if(index == f.size()) return 0; + if(dp[index][state] != -1ll) return dp[index][state]; + + long long res = dfs(index + 1, state, num2state, f, dp); + + if((state & num2state[f[index].first]) == 0){ + long long a = f[index].second, b = dfs(index + 1, state | num2state[f[index].first], num2state, f, dp); + + if(f[index].first != 1) res += a * (b + 1); + else res += (quick_pow(2ll, a, MOD) - 1 + MOD) % MOD * b; + res %= MOD; + } + + return dp[index][state] = res; + } + + int get_num_state(int num){ + + int res = 0; + for(int i = 1; i < primes.size() && num >= primes[i]; i ++){ + if(num % primes[i] == 0){ + res += (1 << i); + num /= primes[i]; + if(num % primes[i] == 0) return -1; + } + } + return res; + } + + long long quick_pow(long long a, long long k, long long MOD) { + long long res = 1ll; + while (k > 0) { + if (k & 1) res = (res * a) % MOD; + a = (a * a) % MOD; + k >>= 1; + } + return res; + } +}; + + +int main() { + + vector nums1 = {1, 2, 3, 4}; + cout << Solution().numberOfGoodSubsets(nums1) << endl; + // 6 + + vector nums2 = {4, 2, 3, 15}; + cout << Solution().numberOfGoodSubsets(nums2) << endl; + // 5 + + return 0; +} diff --git a/1501-2000/1995-Count-Special-Quadruplets/cpp-1995/CMakeLists.txt b/1501-2000/1995-Count-Special-Quadruplets/cpp-1995/CMakeLists.txt new file mode 100644 index 00000000..76479ef2 --- /dev/null +++ b/1501-2000/1995-Count-Special-Quadruplets/cpp-1995/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main2.cpp) diff --git a/1501-2000/1995-Count-Special-Quadruplets/cpp-1995/main.cpp b/1501-2000/1995-Count-Special-Quadruplets/cpp-1995/main.cpp new file mode 100644 index 00000000..1b3bbcfe --- /dev/null +++ b/1501-2000/1995-Count-Special-Quadruplets/cpp-1995/main.cpp @@ -0,0 +1,31 @@ +/// Source : https://leetcode.com/problems/count-special-quadruplets/ +/// Author : liuyubobobo +/// Time : 2021-09-04 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n^4) +/// Space Complexity: O(1) +class Solution { +public: + int countQuadruplets(vector& nums) { + + int res = 0; + for(int a = 0; a < nums.size(); a ++) + for(int b = a + 1; b < nums.size(); b ++) + for(int c = b + 1; c < nums.size(); c ++) + for(int d = c + 1; d < nums.size(); d ++) + if(nums[a] + nums[b] + nums[c] == nums[d]) res ++; + return res; + } +}; + +int main() { + + return 0; +} diff --git a/1501-2000/1995-Count-Special-Quadruplets/cpp-1995/main2.cpp b/1501-2000/1995-Count-Special-Quadruplets/cpp-1995/main2.cpp new file mode 100644 index 00000000..78121ae1 --- /dev/null +++ b/1501-2000/1995-Count-Special-Quadruplets/cpp-1995/main2.cpp @@ -0,0 +1,41 @@ +/// Source : https://leetcode.com/problems/count-special-quadruplets/ +/// Author : liuyubobobo +/// Time : 2021-09-04 + +#include +#include + +using namespace std; + + +/// Using HashMap +/// Time Complexity: O(n^3) +/// Space Complexity: O(n) +class Solution { +public: + int countQuadruplets(vector& nums) { + + int n = nums.size(), res = 0; + for(int a = 0; a < n; a ++){ + for(int b = a + 1; b < n; b ++){ + int p = nums[a] + nums[b]; + vector f(101, 0); + for(int i = b + 1; i < n; i ++){ + if(nums[i] - p >= 1) res += f[nums[i] - p]; + f[nums[i]] ++; + } + } + } + return res; + } +}; + + +int main() { + + vector nums1 = {1, 2, 3, 6}; + cout << Solution().countQuadruplets(nums1) << endl; + // 1 + + return 0; +} diff --git a/1501-2000/1996-The-Number-of-Weak-Characters-in-the-Game/cpp-1996/CMakeLists.txt b/1501-2000/1996-The-Number-of-Weak-Characters-in-the-Game/cpp-1996/CMakeLists.txt new file mode 100644 index 00000000..084dd354 --- /dev/null +++ b/1501-2000/1996-The-Number-of-Weak-Characters-in-the-Game/cpp-1996/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main2.cpp) diff --git a/1501-2000/1996-The-Number-of-Weak-Characters-in-the-Game/cpp-1996/main.cpp b/1501-2000/1996-The-Number-of-Weak-Characters-in-the-Game/cpp-1996/main.cpp new file mode 100644 index 00000000..3dec6f76 --- /dev/null +++ b/1501-2000/1996-The-Number-of-Weak-Characters-in-the-Game/cpp-1996/main.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/the-number-of-weak-characters-in-the-game/ +/// Author : liuyubobobo +/// Time : 2021-09-04 + +#include +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + int numberOfWeakCharacters(vector>& properties) { + + int n = properties.size(), res = 0; + + sort(properties.begin(), properties.end()); + for(int i = n - 2; i >= 0; i --){ + vector t = {properties[i][0] + 1, INT_MIN}; + vector>::iterator iter = lower_bound(properties.begin(), properties.end(), t); + if(iter != properties.end() && properties[i][1] < (*iter)[1]) res ++; + properties[i][1] = max(properties[i][1], properties[i + 1][1]); + } + return res; + } +}; + + +int main() { + + vector> p1 = {{1, 1}, {2, 1}, {2, 2}, {1, 2}}; + cout << Solution().numberOfWeakCharacters(p1) << endl; + // 1 + + return 0; +} diff --git a/1501-2000/1996-The-Number-of-Weak-Characters-in-the-Game/cpp-1996/main2.cpp b/1501-2000/1996-The-Number-of-Weak-Characters-in-the-Game/cpp-1996/main2.cpp new file mode 100644 index 00000000..5e8bae28 --- /dev/null +++ b/1501-2000/1996-The-Number-of-Weak-Characters-in-the-Game/cpp-1996/main2.cpp @@ -0,0 +1,45 @@ +/// Source : https://leetcode.com/problems/the-number-of-weak-characters-in-the-game/ +/// Author : liuyubobobo +/// Time : 2021-09-04 + +#include +#include +#include + +using namespace std; + + +/// Sorting Tricks +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + int numberOfWeakCharacters(vector>& properties) { + + int n = properties.size(), res = 0; + + sort(properties.begin(), properties.end(), + [](const vector& v1, const vector& v2){ + + if(v1[0] == v2[0]) return v1[1] > v2[1]; + return v1[0] < v2[0]; + }); + + int maxd = 0; + for(int i = n - 1; i >= 0; i --){ + res += properties[i][1] < maxd; + maxd = max(maxd, properties[i][1]); + } + return res; + } +}; + + +int main() { + + vector> p1 = {{1, 1}, {2, 1}, {2, 2}, {1, 2}}; + cout << Solution().numberOfWeakCharacters(p1) << endl; + // 1 + + return 0; +} diff --git a/1501-2000/1997-First-Day-Where-You-Have-Been-in-All-the-Rooms/cpp-1997/CMakeLists.txt b/1501-2000/1997-First-Day-Where-You-Have-Been-in-All-the-Rooms/cpp-1997/CMakeLists.txt new file mode 100644 index 00000000..cad75f71 --- /dev/null +++ b/1501-2000/1997-First-Day-Where-You-Have-Been-in-All-the-Rooms/cpp-1997/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/1501-2000/1997-First-Day-Where-You-Have-Been-in-All-the-Rooms/cpp-1997/main.cpp b/1501-2000/1997-First-Day-Where-You-Have-Been-in-All-the-Rooms/cpp-1997/main.cpp new file mode 100644 index 00000000..18679b8c --- /dev/null +++ b/1501-2000/1997-First-Day-Where-You-Have-Been-in-All-the-Rooms/cpp-1997/main.cpp @@ -0,0 +1,56 @@ +/// Source : https://leetcode.com/problems/first-day-where-you-have-been-in-all-the-rooms/ +/// Author : liuyubobobo +/// Time : 2021-09-04 + +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +private: + const long long MOD = 1e9 + 7; + +public: + int firstDayBeenInAllRooms(vector& nextVisit) { + + int n = nextVisit.size(), res = 0; + vector dp(n, 0); + dp[1] = 2; + + for(int i = 2; i < n; i ++) + if(nextVisit[i - 1] == i - 1) + dp[i] = (dp[i - 1] + 2) % MOD; + else + dp[i] = (dp[i - 1] + (dp[i - 1] - dp[nextVisit[i - 1]]) + 2 + MOD) % MOD; + + return dp.back(); + } +}; + + +int main() { + + vector next1 = {0, 0}; + cout << Solution().firstDayBeenInAllRooms(next1) << endl; + // 2 + + vector next2 = {0, 0, 2}; + cout << Solution().firstDayBeenInAllRooms(next2) << endl; + // 6 + + vector next3 = {0, 1, 2, 0}; + cout << Solution().firstDayBeenInAllRooms(next3) << endl; + // 6 + + vector next4 = {0,0,0,0,0,0,0,0,0,9,1,8}; + cout << Solution().firstDayBeenInAllRooms(next4) << endl; + // 2048 + + return 0; +} diff --git a/1501-2000/1998-GCD-Sort-of-an-Array/cpp-1998/CMakeLists.txt b/1501-2000/1998-GCD-Sort-of-an-Array/cpp-1998/CMakeLists.txt new file mode 100644 index 00000000..a0d16fe6 --- /dev/null +++ b/1501-2000/1998-GCD-Sort-of-an-Array/cpp-1998/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) diff --git a/1501-2000/1998-GCD-Sort-of-an-Array/cpp-1998/main.cpp b/1501-2000/1998-GCD-Sort-of-an-Array/cpp-1998/main.cpp new file mode 100644 index 00000000..c8916ddc --- /dev/null +++ b/1501-2000/1998-GCD-Sort-of-an-Array/cpp-1998/main.cpp @@ -0,0 +1,124 @@ +/// Source : https://leetcode.com/problems/gcd-sort-of-an-array/ +/// Author : liuyubobobo +/// Time : 2021-09-04 + +#include +#include +#include +#include + +using namespace std; + + +/// Prime Shieve + UF +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class UF{ + +private: + vector parent; + +public: + UF(int n) : parent(n){ + for(int i = 0 ; i < n ; i ++) + parent[i] = i; + } + + int find(int p){ + if(p != parent[p]) + parent[p] = find(parent[p]); + return parent[p]; + } + + bool is_connected(int p, int q){ + return find(p) == find(q); + } + + void union_elements(int p, int q){ + + int p_root = find(p), q_root = find(q); + + if(p_root == q_root) return; + + parent[p_root] = q_root; + } +}; + +class Solution { +public: + bool gcdSort(vector& nums) { + + int maxv = *max_element(nums.begin(), nums.end()); + vector table = get_table(maxv + 1); + + int n = nums.size(); + map> f2pos; + for(int i = 0; i < n; i ++){ + set fs = get_factors(nums[i], table); + for(int f: fs) f2pos[f].push_back(i); + } + + UF uf(n); + for(const pair>& p: f2pos){ + for(int i = 1; i < p.second.size(); i ++) + uf.union_elements(p.second[i - 1], p.second[i]); + } + + map> cc; + for(int i = 0; i < n; i ++) + cc[uf.find(i)].push_back(i); + + vector res(n); + for(const pair>& p: cc){ + vector data; + for(int e: p.second) data.push_back(nums[e]); + sort(data.begin(), data.end()); + for(int i = 0; i < p.second.size(); i ++) + res[p.second[i]] = data[i]; + } + + for(int i = 1; i < n; i ++) + if(res[i] < res[i - 1]) return false; + return true; + } + +private: + set get_factors(int num, const vector& table){ + + set factors; + while(num != 1){ + factors.insert(table[num]); + num /= table[num]; + } + if(factors.size() == 0) factors.insert(1); + return factors; + } + + vector get_table(int n){ + + vector table(n, 0); + table[1] = 1; + for(int i = 2; i < n; i ++) + if(table[i] == 0) + for(int j = i; j < n; j += i) table[j] = i; + return table; + } +}; + + +int main() { + + vector nums1 = {7, 21, 3}; + cout << Solution().gcdSort(nums1) << endl; + // 1 + + vector nums2 = {5, 2, 6, 2}; + cout << Solution().gcdSort(nums2) << endl; + // 0 + + vector nums3 = {10, 5, 9, 3, 15}; + cout << Solution().gcdSort(nums3) << endl; + // 1 + + return 0; +} diff --git a/1501-2000/1999-Smallest-Greater-Multiple-Made-of-Two-Digits/cpp-1999/CMakeLists.txt b/1501-2000/1999-Smallest-Greater-Multiple-Made-of-Two-Digits/cpp-1999/CMakeLists.txt new file mode 100644 index 00000000..b3f03ab1 --- /dev/null +++ b/1501-2000/1999-Smallest-Greater-Multiple-Made-of-Two-Digits/cpp-1999/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_1999) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_1999 main.cpp) diff --git a/1501-2000/1999-Smallest-Greater-Multiple-Made-of-Two-Digits/cpp-1999/main.cpp b/1501-2000/1999-Smallest-Greater-Multiple-Made-of-Two-Digits/cpp-1999/main.cpp new file mode 100644 index 00000000..e8d2654d --- /dev/null +++ b/1501-2000/1999-Smallest-Greater-Multiple-Made-of-Two-Digits/cpp-1999/main.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/smallest-greater-multiple-made-of-two-digits/ +/// Author : liuyubobobo +/// Time : 2021-09-12 + +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(2^(k + 1)) +/// Space Complexity: O(1) +class Solution { +public: + int findInteger(int k, int digit1, int digit2) { + + int res = INT_MAX; + for(int len = 1; len <= 10 && res == INT_MAX; len ++){ + for(int state = 0; state < (1 << len); state ++){ + string s = generate(len, state, digit1, digit2); + if(len == 10 && s > "2147483647") continue; + int num = atoi(s.c_str()); + if(num > k && num % k == 0) res = min(res, num); + } + } + return res == INT_MAX ? -1 : res; + } + +private: + string generate(int len, int state, int d1, int d2){ + + string s(len, ' '); + for(int i = 0; i < len; i ++){ + s[i] = '0' + (state % 2 ? d1 : d2); + state /= 2; + } + return s; + } +}; + + +int main() { + + cout << Solution().findInteger(2, 0, 2) << endl; + // 20 + + cout << Solution().findInteger(3, 4, 2) << endl; + // 24 + + cout << Solution().findInteger(2, 0, 0) << endl; + // -1 + + cout << Solution().findInteger(1, 0, 4) << endl; + // 4 + + return 0; +} diff --git a/1501-2000/2000-Reverse-Prefix-of-Word/cpp-2000/CMakeLists.txt b/1501-2000/2000-Reverse-Prefix-of-Word/cpp-2000/CMakeLists.txt new file mode 100644 index 00000000..2ae8397c --- /dev/null +++ b/1501-2000/2000-Reverse-Prefix-of-Word/cpp-2000/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/1501-2000/2000-Reverse-Prefix-of-Word/cpp-2000/main.cpp b/1501-2000/2000-Reverse-Prefix-of-Word/cpp-2000/main.cpp new file mode 100644 index 00000000..0769616a --- /dev/null +++ b/1501-2000/2000-Reverse-Prefix-of-Word/cpp-2000/main.cpp @@ -0,0 +1,30 @@ +/// Source : https://leetcode.com/problems/reverse-prefix-of-word/ +/// Author : liuyubobobo +/// Time : 2021-09-11 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + string reversePrefix(string word, char ch) { + + int p = word.find(ch); + if(p == string::npos) return word; + + reverse(word.begin(), word.begin() + (p + 1)); + return word; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2001-Number-of-Pairs-of-Interchangeable-Rectangles/cpp-2001/CMakeLists.txt b/2001-2500/2001-Number-of-Pairs-of-Interchangeable-Rectangles/cpp-2001/CMakeLists.txt new file mode 100644 index 00000000..084dd354 --- /dev/null +++ b/2001-2500/2001-Number-of-Pairs-of-Interchangeable-Rectangles/cpp-2001/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main2.cpp) diff --git a/2001-2500/2001-Number-of-Pairs-of-Interchangeable-Rectangles/cpp-2001/main.cpp b/2001-2500/2001-Number-of-Pairs-of-Interchangeable-Rectangles/cpp-2001/main.cpp new file mode 100644 index 00000000..a3e8e005 --- /dev/null +++ b/2001-2500/2001-Number-of-Pairs-of-Interchangeable-Rectangles/cpp-2001/main.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/number-of-pairs-of-interchangeable-rectangles/ +/// Author : liuyubobobo +/// Time : 2021-09-11 + +#include +#include +#include + +using namespace std; + + +/// Using HashMap +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + long long interchangeableRectangles(vector>& rectangles) { + + map, int> table; + for(const vector& rec: rectangles){ + int w = rec[0], h = rec[1]; + int g = gcd(w, h); + w /= g, h /= g; + table[{w, h}] ++; + } + + long long res = 0ll; + for(const pair, int>& p: table){ + long long n = p.second; + res += n * (n - 1) / 2; + } + return res; + } + +private: + int gcd(int a, int b){ + if(a > b) swap(a, b); + if (a == 0) return b; + return gcd(b % a, a); + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2001-Number-of-Pairs-of-Interchangeable-Rectangles/cpp-2001/main2.cpp b/2001-2500/2001-Number-of-Pairs-of-Interchangeable-Rectangles/cpp-2001/main2.cpp new file mode 100644 index 00000000..5f089af8 --- /dev/null +++ b/2001-2500/2001-Number-of-Pairs-of-Interchangeable-Rectangles/cpp-2001/main2.cpp @@ -0,0 +1,45 @@ +/// Source : https://leetcode.com/problems/number-of-pairs-of-interchangeable-rectangles/ +/// Author : liuyubobobo +/// Time : 2021-09-11 + +#include +#include +#include + +using namespace std; + + +/// Using HashMap +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + long long interchangeableRectangles(vector>& rectangles) { + + map, int> table; + long long res = 0ll; + for(const vector& rec: rectangles){ + int w = rec[0], h = rec[1], g = gcd(min(w, h), max(w, h)); + w /= g, h /= g; + if(table.count({w, h})){ + int v = table[{w, h}]; + res += v; + table[{w, h}] = v + 1; + } + else table[{w, h}] = 1; + } + return res; + } + +private: + int gcd(int a, int b){ + if (a == 0) return b; + return gcd(b % a, a); + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2002-Maximum-Product-of-the-Length-of-Two-Palindromic Subsequences/cpp-2002/CMakeLists.txt b/2001-2500/2002-Maximum-Product-of-the-Length-of-Two-Palindromic Subsequences/cpp-2002/CMakeLists.txt new file mode 100644 index 00000000..cad75f71 --- /dev/null +++ b/2001-2500/2002-Maximum-Product-of-the-Length-of-Two-Palindromic Subsequences/cpp-2002/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/2001-2500/2002-Maximum-Product-of-the-Length-of-Two-Palindromic Subsequences/cpp-2002/main.cpp b/2001-2500/2002-Maximum-Product-of-the-Length-of-Two-Palindromic Subsequences/cpp-2002/main.cpp new file mode 100644 index 00000000..3d58b043 --- /dev/null +++ b/2001-2500/2002-Maximum-Product-of-the-Length-of-Two-Palindromic Subsequences/cpp-2002/main.cpp @@ -0,0 +1,67 @@ +/// Source : https://leetcode.com/problems/maximum-product-of-the-length-of-two-palindromic-subsequences/ +/// Author : liuyubobobo +/// Time : 2021-09-11 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(2^n * 3^n) +/// Space Complexity: O(2^n) +class Solution { +public: + int maxProduct(string s) { + + int n = s.size(); + vector table(1 << n, false); + vector len(1 << n, 0); + for(int state = 1; state < (1 << n); state ++) + calc(s, state, n, table, len); + + int res = 0; + for(int state = 1; state + 1 < (1 << n); state ++) + if(table[state]){ + int u = (1 << n) - 1 - state; + for (int s = u; s; s = (s - 1) & u) + if(table[s]) res = max(res, len[state] * len[s]); + } + return res; + } + +private: + void calc(const string& s, int state, int n, + vector& table, vector& len){ + + string t = ""; + for(int i = 0; i < n; i ++) + if(state & (1 << i)) t += s[i]; + + len[state] = t.size(); + + bool is_pal = true; + for(int i = 0, j = t.size() - 1; i < j; i ++, j --) + if(t[i] != t[j]){ + is_pal = false; + break; + } + table[state] = is_pal; + } +}; + + +int main() { + + cout << Solution().maxProduct("leetcodecom") << endl; + // 9 + + cout << Solution().maxProduct("bb") << endl; + // 1 + + cout << Solution().maxProduct("accbcaxxcxx") << endl; + // 25 + + return 0; +} diff --git a/2001-2500/2003-Smallest-Missing-Genetic-Value-in-Each-Subtree/cpp-2003/CMakeLists.txt b/2001-2500/2003-Smallest-Missing-Genetic-Value-in-Each-Subtree/cpp-2003/CMakeLists.txt new file mode 100644 index 00000000..a0d16fe6 --- /dev/null +++ b/2001-2500/2003-Smallest-Missing-Genetic-Value-in-Each-Subtree/cpp-2003/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) diff --git a/2001-2500/2003-Smallest-Missing-Genetic-Value-in-Each-Subtree/cpp-2003/main.cpp b/2001-2500/2003-Smallest-Missing-Genetic-Value-in-Each-Subtree/cpp-2003/main.cpp new file mode 100644 index 00000000..9c3a283d --- /dev/null +++ b/2001-2500/2003-Smallest-Missing-Genetic-Value-in-Each-Subtree/cpp-2003/main.cpp @@ -0,0 +1,74 @@ +/// Source : https://leetcode.com/problems/smallest-missing-genetic-value-in-each-subtree/ +/// Author : liuyubobobo +/// Time : 2021-09-12 + +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +public: + vector smallestMissingValueSubtree(vector& parents, vector& nums) { + + int n = parents.size(); + vector res(n, 1); + + vector::iterator iter = find(nums.begin(), nums.end(), 1); + if(iter == nums.end()) + return res; + + vector> tree(n); + for(int i = 1; i < n; i ++) + tree[i].push_back(parents[i]), tree[parents[i]].push_back(i); + + int cur = iter - nums.begin(); + vector visited(100005, false); + int v = 1; + while(cur != -1){ + dfs(tree, nums, cur, parents[cur], visited); + while(visited[v]) v ++; + res[cur] = v; + cur = parents[cur]; + } + return res; + } + +private: + void dfs(const vector>& tree, vector& nums, + int u, int p, vector& visited){ + + visited[nums[u]] = true; + + for(int v: tree[u]) + if(v != p && !visited[nums[v]]) + dfs(tree, nums, v, u, visited); + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << ' '; cout << endl; +} + +int main() { + + vector parents1 = {-1,0,0,2}, nums1 = {1,2,3,4}; + print_vec(Solution().smallestMissingValueSubtree(parents1, nums1)); + // 5 1 1 1 + + vector parents2 = {-1,0,1,0,3,3}, nums2 = {5,4,6,2,1,3}; + print_vec(Solution().smallestMissingValueSubtree(parents2, nums2)); + // 7,1,1,4,2,1 + + vector parents3 = {-1,2,3,0,2,4,1}, nums3 = {2,3,4,5,6,7,8}; + print_vec(Solution().smallestMissingValueSubtree(parents3, nums3)); + // 1,1,1,1,1,1,1 + + return 0; +} diff --git a/2001-2500/2005-Subtree-Removal-Game-with-Fibonacci-Tree/cpp-2005/CMakeLists.txt b/2001-2500/2005-Subtree-Removal-Game-with-Fibonacci-Tree/cpp-2005/CMakeLists.txt new file mode 100644 index 00000000..ccb6302a --- /dev/null +++ b/2001-2500/2005-Subtree-Removal-Game-with-Fibonacci-Tree/cpp-2005/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_2005) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2005 main.cpp) diff --git a/2001-2500/2005-Subtree-Removal-Game-with-Fibonacci-Tree/cpp-2005/main.cpp b/2001-2500/2005-Subtree-Removal-Game-with-Fibonacci-Tree/cpp-2005/main.cpp new file mode 100644 index 00000000..28cc78dd --- /dev/null +++ b/2001-2500/2005-Subtree-Removal-Game-with-Fibonacci-Tree/cpp-2005/main.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/subtree-removal-game-with-fibonacci-tree/ +/// Author : liuyubobobo +/// Time : 2021-09-21 + +#include +#include + +using namespace std; + + +/// Nim +/// Time Compelxity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + bool findGameWinner(int n) { + + if(n == 1) return false; + + vector dp(n, 0); + dp[1] = 1; + for(int i = 2; i < n; i ++) + dp[i] = (dp[i - 1] ^ dp[i - 2]) + 1; + return dp[n - 1] ^ dp[n - 2]; + } +}; + + +int main() { + + cout << Solution().findGameWinner(3) << endl; + + return 0; +} diff --git a/2001-2500/2006-Count-Number-of-Pairs-With-Absolute-Difference-K/cpp-2006/CMakeLists.txt b/2001-2500/2006-Count-Number-of-Pairs-With-Absolute-Difference-K/cpp-2006/CMakeLists.txt new file mode 100644 index 00000000..6ff31986 --- /dev/null +++ b/2001-2500/2006-Count-Number-of-Pairs-With-Absolute-Difference-K/cpp-2006/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_2006) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2006 main3.cpp) diff --git a/2001-2500/2006-Count-Number-of-Pairs-With-Absolute-Difference-K/cpp-2006/main.cpp b/2001-2500/2006-Count-Number-of-Pairs-With-Absolute-Difference-K/cpp-2006/main.cpp new file mode 100644 index 00000000..2bf71960 --- /dev/null +++ b/2001-2500/2006-Count-Number-of-Pairs-With-Absolute-Difference-K/cpp-2006/main.cpp @@ -0,0 +1,30 @@ +/// Source : https://leetcode.com/problems/count-number-of-pairs-with-absolute-difference-k/ +/// Author : liuyubobobo +/// Time : 2021-09-18 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n^2) +/// Space Complexity: O(1) +class Solution { +public: + int countKDifference(vector& nums, int k) { + + int res = 0; + for(int i = 0; i < nums.size(); i ++) + for(int j = i + 1; j < nums.size(); j ++) + res += abs(nums[i] - nums[j]) == k; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2006-Count-Number-of-Pairs-With-Absolute-Difference-K/cpp-2006/main2.cpp b/2001-2500/2006-Count-Number-of-Pairs-With-Absolute-Difference-K/cpp-2006/main2.cpp new file mode 100644 index 00000000..a5ffab08 --- /dev/null +++ b/2001-2500/2006-Count-Number-of-Pairs-With-Absolute-Difference-K/cpp-2006/main2.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/count-number-of-pairs-with-absolute-difference-k/ +/// Author : liuyubobobo +/// Time : 2021-09-18 + +#include +#include + +using namespace std; + + +/// Sorting + Binary Search +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + int countKDifference(vector& nums, int k) { + + sort(nums.begin(), nums.end()); + int res = 0; + for(int e: nums){ + vector::iterator iter1 = lower_bound(nums.begin(), nums.end(), e + k); + if(iter1 == nums.end() || *iter1 != e + k) continue; + + vector::iterator iter2 = upper_bound(nums.begin(), nums.end(), e + k); + res += (iter2 - iter1); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2006-Count-Number-of-Pairs-With-Absolute-Difference-K/cpp-2006/main3.cpp b/2001-2500/2006-Count-Number-of-Pairs-With-Absolute-Difference-K/cpp-2006/main3.cpp new file mode 100644 index 00000000..3ae6d2c5 --- /dev/null +++ b/2001-2500/2006-Count-Number-of-Pairs-With-Absolute-Difference-K/cpp-2006/main3.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/count-number-of-pairs-with-absolute-difference-k/ +/// Author : liuyubobobo +/// Time : 2021-09-18 + +#include +#include +#include + +using namespace std; + + +/// Sorting + Using HashMap +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + int countKDifference(vector& nums, int k) { + + sort(nums.begin(), nums.end()); + int res = 0; + unordered_map f; + for(int e: nums){ + if(f.count(e - k)) res += f[e - k]; + f[e] ++; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2007-Find-Original-Array-From-Doubled-Array/cpp-2007/CMakeLists.txt b/2001-2500/2007-Find-Original-Array-From-Doubled-Array/cpp-2007/CMakeLists.txt new file mode 100644 index 00000000..34601fdb --- /dev/null +++ b/2001-2500/2007-Find-Original-Array-From-Doubled-Array/cpp-2007/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_2007) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2007 main.cpp) diff --git a/2001-2500/2007-Find-Original-Array-From-Doubled-Array/cpp-2007/main.cpp b/2001-2500/2007-Find-Original-Array-From-Doubled-Array/cpp-2007/main.cpp new file mode 100644 index 00000000..5f467067 --- /dev/null +++ b/2001-2500/2007-Find-Original-Array-From-Doubled-Array/cpp-2007/main.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/find-original-array-from-doubled-array/ +/// Author : liuyubobobo +/// Time : 2021-09-18 + +#include +#include +#include + +using namespace std; + + +/// Greedy + Using Set +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + vector findOriginalArray(vector& changed) { + + sort(changed.begin(), changed.end()); + + set> data; // value, index + for(int i = 0; i < changed.size(); i ++) + data.insert({changed[i], i}); + + set visited; + vector res; + for(int i = 0; i < changed.size(); i ++){ + data.erase({changed[i], i}); + if(!visited.count(i)){ + set>::iterator iter = data.lower_bound(make_pair(changed[i] * 2, INT_MIN)); + if(iter == data.end() || iter->first != changed[i] * 2) return {}; + + int ii = iter->second; + visited.insert(i); visited.insert(ii); + data.erase(iter); + res.push_back(changed[i]); + } + } + return res; + } +}; + +int main() { + + return 0; +} diff --git a/2001-2500/2008-Maximum-Earnings-From-Taxi/cpp-2008/CMakeLists.txt b/2001-2500/2008-Maximum-Earnings-From-Taxi/cpp-2008/CMakeLists.txt new file mode 100644 index 00000000..bf6b76c4 --- /dev/null +++ b/2001-2500/2008-Maximum-Earnings-From-Taxi/cpp-2008/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_2008) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2008 main2.cpp) diff --git a/2001-2500/2008-Maximum-Earnings-From-Taxi/cpp-2008/main.cpp b/2001-2500/2008-Maximum-Earnings-From-Taxi/cpp-2008/main.cpp new file mode 100644 index 00000000..9714de2b --- /dev/null +++ b/2001-2500/2008-Maximum-Earnings-From-Taxi/cpp-2008/main.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/maximum-earnings-from-taxi/ +/// Author : liuyubobobo +/// Time : 2021-09-18 + +#include +#include + +using namespace std; + + +/// Sorting + DP + Binary Search +/// Time Complexity: O(mlogm + nlogm + m) +/// Space Complexity: O(n) +class Solution { +public: + long long maxTaxiEarnings(int n, vector>& rides) { + + sort(rides.begin(), rides.end()); + vector dp(n + 2, 0ll); + for(int i = n; i >= 1; i --){ + dp[i] = dp[i + 1]; + vector t = {i, i, 0}; + vector>::iterator iter = lower_bound(rides.begin(), rides.end(), t); + while(iter != rides.end() && (*iter)[0] == i){ + dp[i] = max(dp[i], (*iter)[1] - (*iter)[0] + (*iter)[2] + dp[(*iter)[1]]); + iter ++; + } + } + return dp[1]; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2008-Maximum-Earnings-From-Taxi/cpp-2008/main2.cpp b/2001-2500/2008-Maximum-Earnings-From-Taxi/cpp-2008/main2.cpp new file mode 100644 index 00000000..c9ef37cb --- /dev/null +++ b/2001-2500/2008-Maximum-Earnings-From-Taxi/cpp-2008/main2.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/maximum-earnings-from-taxi/ +/// Author : liuyubobobo +/// Time : 2021-09-18 + +#include +#include + +using namespace std; + + +/// Sorting + DP (No Binary Search) +/// Time Complexity: O(mlogm + n + m) +/// Space Complexity: O(n) +class Solution { +public: + long long maxTaxiEarnings(int n, vector>& rides) { + + sort(rides.begin(), rides.end()); + int j = rides.size() - 1; + + vector dp(n + 2, 0ll); + for(int i = n; i >= 1; i --){ + dp[i] = dp[i + 1]; + while(j >= 0 && rides[j][0] == i){ + dp[i] = max(dp[i], rides[j][1] - rides[j][0] + rides[j][2] + dp[rides[j][1]]); + j --; + } + } + return dp[1]; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2009-Minimum-Number-of-Operations-to-Make-Array-Continuous/cpp-2009/CMakeLists.txt b/2001-2500/2009-Minimum-Number-of-Operations-to-Make-Array-Continuous/cpp-2009/CMakeLists.txt new file mode 100644 index 00000000..2a23883c --- /dev/null +++ b/2001-2500/2009-Minimum-Number-of-Operations-to-Make-Array-Continuous/cpp-2009/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_2009) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2009 main.cpp) diff --git a/2001-2500/2009-Minimum-Number-of-Operations-to-Make-Array-Continuous/cpp-2009/main.cpp b/2001-2500/2009-Minimum-Number-of-Operations-to-Make-Array-Continuous/cpp-2009/main.cpp new file mode 100644 index 00000000..8622964c --- /dev/null +++ b/2001-2500/2009-Minimum-Number-of-Operations-to-Make-Array-Continuous/cpp-2009/main.cpp @@ -0,0 +1,48 @@ +/// Source : https://leetcode.com/problems/minimum-number-of-operations-to-make-array-continuous/ +/// Author : liuyubobobo +/// Time : 2021-09-18 + +#include +#include +#include +#include + +using namespace std; + + +/// Greedy + Binary Search +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + int minOperations(vector& nums) { + + set unique_nums; + for(int e: nums) unique_nums.insert(e); + vector data(unique_nums.begin(), unique_nums.end()); + + int n = data.size(); + + int res = (int)nums.size(); + for(int i = 0; i < n; i ++){ + vector::iterator iter1 = lower_bound(data.begin(), data.end(), data[i] + nums.size()); + int k = (iter1 - data.begin()) - i; + res = min(res, (int)nums.size()- k); + } + return res; + } +}; + + +int main() { + + vector nums1 = {8, 5, 9, 9, 8, 4}; + cout << Solution().minOperations(nums1) << endl; + // 2 + + vector nums2 = {8,10,16,18,10,10,16,13,13,16}; + cout << Solution().minOperations(nums2) << endl; + // 6 + + return 0; +} diff --git a/2001-2500/2011-Final-Value-of-Variable-After-Performing-Operations/cpp-2011/CMakeLists.txt b/2001-2500/2011-Final-Value-of-Variable-After-Performing-Operations/cpp-2011/CMakeLists.txt new file mode 100644 index 00000000..2ae8397c --- /dev/null +++ b/2001-2500/2011-Final-Value-of-Variable-After-Performing-Operations/cpp-2011/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/2001-2500/2011-Final-Value-of-Variable-After-Performing-Operations/cpp-2011/main.cpp b/2001-2500/2011-Final-Value-of-Variable-After-Performing-Operations/cpp-2011/main.cpp new file mode 100644 index 00000000..4a3ab597 --- /dev/null +++ b/2001-2500/2011-Final-Value-of-Variable-After-Performing-Operations/cpp-2011/main.cpp @@ -0,0 +1,30 @@ +/// Source : https://leetcode.com/problems/final-value-of-variable-after-performing-operations/ +/// Author : liuyubobobo +/// Time : 2021-09-18 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int finalValueAfterOperations(vector& operations) { + + int x = 0; + for(const string& op: operations) + if(op[1] == '+') x ++; + else x --; + return x; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2012-Sum-of-Beauty-in-the-Array/cpp-2012/CMakeLists.txt b/2001-2500/2012-Sum-of-Beauty-in-the-Array/cpp-2012/CMakeLists.txt new file mode 100644 index 00000000..3f98647f --- /dev/null +++ b/2001-2500/2012-Sum-of-Beauty-in-the-Array/cpp-2012/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/2001-2500/2012-Sum-of-Beauty-in-the-Array/cpp-2012/main.cpp b/2001-2500/2012-Sum-of-Beauty-in-the-Array/cpp-2012/main.cpp new file mode 100644 index 00000000..0aee4c92 --- /dev/null +++ b/2001-2500/2012-Sum-of-Beauty-in-the-Array/cpp-2012/main.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/sum-of-beauty-in-the-array/ +/// Author : liuyubobobo +/// Time : 2021-09-18 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int sumOfBeauties(vector& nums) { + + int n = nums.size(); + + vector left(n, false); + int cur_max = nums[0]; + for(int i = 1; i < n; i ++){ + if(cur_max < nums[i]) left[i] = true; + cur_max = max(cur_max, nums[i]); + } + + vector right(n, false); + int cur_min = nums[n - 1]; + for(int i = n - 2; i >= 0; i --){ + if(nums[i] < cur_min) right[i] = true; + cur_min = min(cur_min, nums[i]); + } + + int res = 0; + for(int i = 1; i + 1 < n; i ++){ + if(left[i] && right[i]) res += 2; + else res += (nums[i - 1] < nums[i] && nums[i] < nums[i + 1]); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2013-Detect-Squares/cpp-2013/CMakeLists.txt b/2001-2500/2013-Detect-Squares/cpp-2013/CMakeLists.txt new file mode 100644 index 00000000..cad75f71 --- /dev/null +++ b/2001-2500/2013-Detect-Squares/cpp-2013/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/2001-2500/2013-Detect-Squares/cpp-2013/main.cpp b/2001-2500/2013-Detect-Squares/cpp-2013/main.cpp new file mode 100644 index 00000000..fa7123cb --- /dev/null +++ b/2001-2500/2013-Detect-Squares/cpp-2013/main.cpp @@ -0,0 +1,61 @@ +/// Source : https://leetcode.com/problems/detect-squares/ +/// Author : liuyubobobo +/// Time : 2021-09-18 + +#include +#include +#include +#include + +using namespace std; + + +/// Using Map +/// Time Complexity: init: O(1) +/// add: O(1) +/// count: O(n) +/// Space Cpmlexity: O(n) +class DetectSquares { + +private: + map> points; + +public: + DetectSquares() {} + + void add(vector point) { + + int x = point[0], y = point[1]; + points[x][y] ++; + } + + int count(vector point) { + + int x0 = point[0], y0 = point[1], res = 0; + + if(points.count(x0)){ + map& yset = points[x0]; + for(const pair& p: yset){ + + int y1 = p.first; + if(y1 == y0) continue; + + int s = abs(y0 - y1); + int c1 = points[x0 - s][y0]; + int c2 = points[x0 - s][y1]; + res += p.second * c1 * c2; + + c1 = points[x0 + s][y0]; + c2 = points[x0 + s][y1]; + res += p.second * c1 * c2; + } + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2014-Longest-Subsequence-Repeated-k-Times/cpp-2014/CMakeLists.txt b/2001-2500/2014-Longest-Subsequence-Repeated-k-Times/cpp-2014/CMakeLists.txt new file mode 100644 index 00000000..77f8b0fb --- /dev/null +++ b/2001-2500/2014-Longest-Subsequence-Repeated-k-Times/cpp-2014/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_2014) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2014 main2.cpp) diff --git a/2001-2500/2014-Longest-Subsequence-Repeated-k-Times/cpp-2014/main.cpp b/2001-2500/2014-Longest-Subsequence-Repeated-k-Times/cpp-2014/main.cpp new file mode 100644 index 00000000..ef0c881c --- /dev/null +++ b/2001-2500/2014-Longest-Subsequence-Repeated-k-Times/cpp-2014/main.cpp @@ -0,0 +1,67 @@ +/// Source : https://leetcode.com/problems/longest-subsequence-repeated-k-times/ +/// Author : liuyubobobo +/// Time : 2021-09-20 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + string longestSubsequenceRepeatedK(string s, int k) { + + vector f(26, 0); + for(char c: s) f[c - 'a'] ++; + + string p = ""; + for(int i = 0; i < 26;){ + if(f[i] >= k) p += ('a' + i), f[i] -= k; + else i ++; + } + if(p == "") return ""; + + int maxlen = s.size() / k; + string res = ""; + for(int l = maxlen; l >= 1; l --){ + sort(p.begin(), p.end()); + do{ + string t = p.substr(0, l); + if(ok(s, t, k)){ + if(res == "") res = t; + else res = max(res, t); + } + }while(next_permutation(p.begin(), p.end())); + + if(res != "") break; + } + return res; + } + +private: + bool ok(const string& s, const string& p, int k){ + + int j = 0; + for(int i = 0; i < s.size(); i ++){ + if(s[i] == p[j]) j ++; + if(j == p.size()) j = 0, k --; + } + return k <= 0; + } +}; + + +int main() { + + cout << Solution().longestSubsequenceRepeatedK("ab", 2) << endl; + // "" + + cout << Solution().longestSubsequenceRepeatedK("memzememeflmemrfemekxzmemememwememefmqemxememzedmoememnrcmekmeemejhsuamelcmermemdjemezwmkemememxgyemenwhmemxaebmememeimeemienmemtnetmftemememeooimememememezmecmemqemeewnimyhlemiuemkhwnstbiiemedmemizememeemememrlemememebmemyenafmemehmemvweumhiemewmemetmemtetcmedwbpmeylwomegjmzfeetmuemzemuwemeymsncemmememememeewyumqenmemetyqmebmemmemeofjmehmteamegmbihememnemneegppm", 108) << endl; + // me + + return 0; +} diff --git a/2001-2500/2014-Longest-Subsequence-Repeated-k-Times/cpp-2014/main2.cpp b/2001-2500/2014-Longest-Subsequence-Repeated-k-Times/cpp-2014/main2.cpp new file mode 100644 index 00000000..46a17b17 --- /dev/null +++ b/2001-2500/2014-Longest-Subsequence-Repeated-k-Times/cpp-2014/main2.cpp @@ -0,0 +1,62 @@ +/// Source : https://leetcode.com/problems/longest-subsequence-repeated-k-times/ +/// Author : liuyubobobo +/// Time : 2021-09-20 + +#include +#include +#include + +using namespace std; + + +/// BFS +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + string longestSubsequenceRepeatedK(string s, int k) { + + int maxlen = s.size() / k; + + queue q; + q.push(""); + string res = ""; + while(!q.empty()){ + string cur = q.front(); q.pop(); + if(cur.size() == maxlen) continue; + + for(char c = 'a'; c <= 'z'; c ++){ + string p = cur + c; + if(ok(s, p, k)){ + if(p.size() > res.size()) res = p; + else if(p.size() == res.size()) res = max(res, p); + q.push(p); + } + } + } + return res; + } + +private: + bool ok(const string& s, const string& p, int k){ + + int j = 0; + for(int i = 0; i < s.size(); i ++){ + if(s[i] == p[j]) j ++; + if(j == p.size()) j = 0, k --; + } + return k <= 0; + } +}; + + +int main() { + + cout << Solution().longestSubsequenceRepeatedK("ab", 2) << endl; + // "" + + cout << Solution().longestSubsequenceRepeatedK("memzememeflmemrfemekxzmemememwememefmqemxememzedmoememnrcmekmeemejhsuamelcmermemdjemezwmkemememxgyemenwhmemxaebmememeimeemienmemtnetmftemememeooimememememezmecmemqemeewnimyhlemiuemkhwnstbiiemedmemizememeemememrlemememebmemyenafmemehmemvweumhiemewmemetmemtetcmedwbpmeylwomegjmzfeetmuemzemuwemeymsncemmememememeewyumqenmemetyqmebmemmemeofjmehmteamegmbihememnemneegppm", 108) << endl; + // me + + return 0; +} diff --git a/2001-2500/2015-Average-Height-of-Buildings-in-Each-Segment/cpp-2015/CMakeLists.txt b/2001-2500/2015-Average-Height-of-Buildings-in-Each-Segment/cpp-2015/CMakeLists.txt new file mode 100644 index 00000000..7a4c2cb4 --- /dev/null +++ b/2001-2500/2015-Average-Height-of-Buildings-in-Each-Segment/cpp-2015/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_2015) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2015 main.cpp) diff --git a/2001-2500/2015-Average-Height-of-Buildings-in-Each-Segment/cpp-2015/main.cpp b/2001-2500/2015-Average-Height-of-Buildings-in-Each-Segment/cpp-2015/main.cpp new file mode 100644 index 00000000..c61c0202 --- /dev/null +++ b/2001-2500/2015-Average-Height-of-Buildings-in-Each-Segment/cpp-2015/main.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/average-height-of-buildings-in-each-segment/ +/// Author : liuyubobobo +/// Time : 2021-09-24 + +#include +#include + +using namespace std; + + +/// Sweep Line +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + vector> averageHeightOfBuildings(vector>& buildings) { + + vector> seg; + for(const vector& b: buildings) + seg.push_back({b[0], b[2]}), + seg.push_back({b[1], -b[2]}); + sort(seg.begin(), seg.end()); + + vector> res; + int start = seg[0].first, cur_h = seg[0].second, cur_cnt = 1; + for(int i = 1; i < seg.size(); i ++){ + if(cur_cnt && seg[i].first != start){ + vector x = {start, seg[i].first, cur_h / cur_cnt}; + if(!res.empty() && x[2] != res.back()[2] && x[0] == res.back()[1]) + res.back()[1] = x[1]; + else + res.push_back(x); + } + + start = seg[i].first; + cur_h += seg[i].second; + cur_cnt += sign(seg[i].second); + } + return res; + } + +private: + int sign(int x){ + if(x > 0) return 1; + return x < 0 ? -1 : 0; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2016-Maximum-Difference-Between-Increasing-Elements/cpp-2016/CMakeLists.txt b/2001-2500/2016-Maximum-Difference-Between-Increasing-Elements/cpp-2016/CMakeLists.txt new file mode 100644 index 00000000..76479ef2 --- /dev/null +++ b/2001-2500/2016-Maximum-Difference-Between-Increasing-Elements/cpp-2016/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main2.cpp) diff --git a/2001-2500/2016-Maximum-Difference-Between-Increasing-Elements/cpp-2016/main.cpp b/2001-2500/2016-Maximum-Difference-Between-Increasing-Elements/cpp-2016/main.cpp new file mode 100644 index 00000000..d4894a56 --- /dev/null +++ b/2001-2500/2016-Maximum-Difference-Between-Increasing-Elements/cpp-2016/main.cpp @@ -0,0 +1,31 @@ +/// Source : https://leetcode.com/problems/maximum-difference-between-increasing-elements/ +/// Author : liuyubobobo +/// Time : 2021-09-25 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n^2) +/// Space Complexity: O(1) +class Solution { +public: + int maximumDifference(vector& nums) { + + int n = nums.size(), res = -1; + for(int i = 0; i < n; i ++) + for(int j = i + 1; j < n; j ++) + if(nums[i] < nums[j]) + res = max(res, nums[j] - nums[i]); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2016-Maximum-Difference-Between-Increasing-Elements/cpp-2016/main2.cpp b/2001-2500/2016-Maximum-Difference-Between-Increasing-Elements/cpp-2016/main2.cpp new file mode 100644 index 00000000..ba85d9e9 --- /dev/null +++ b/2001-2500/2016-Maximum-Difference-Between-Increasing-Elements/cpp-2016/main2.cpp @@ -0,0 +1,31 @@ +/// Source : https://leetcode.com/problems/maximum-difference-between-increasing-elements/ +/// Author : liuyubobobo +/// Time : 2021-09-25 + +#include +#include + +using namespace std; + + +/// Linear Scan and record the minimum element +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int maximumDifference(vector& nums) { + + int n = nums.size(), res = -1, minv = nums[0]; + for(int i = 1; i < n; i ++){ + if(minv < nums[i]) res = max(res, nums[i] - minv); + minv = min(minv, nums[i]); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2017-Grid-Game/cpp-2017/CMakeLists.txt b/2001-2500/2017-Grid-Game/cpp-2017/CMakeLists.txt new file mode 100644 index 00000000..3f98647f --- /dev/null +++ b/2001-2500/2017-Grid-Game/cpp-2017/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/2001-2500/2017-Grid-Game/cpp-2017/main.cpp b/2001-2500/2017-Grid-Game/cpp-2017/main.cpp new file mode 100644 index 00000000..43eb364c --- /dev/null +++ b/2001-2500/2017-Grid-Game/cpp-2017/main.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/grid-game/ +/// Author : liuyubobobo +/// Time : 2021-09-25 + +#include +#include + +using namespace std; + + +/// Presum +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + long long gridGame(vector>& grid) { + + int n = grid[0].size(); + vector> presum(2, vector(n + 1, 0ll)); + for(int r = 0; r < 2; r ++) + for(int i = 0; i < n; i ++) + presum[r][i + 1] = presum[r][i] + grid[r][i]; + + long long res = LONG_LONG_MAX; + for(int i = 0; i < n; i ++) + res = min(res, max(presum[0][n] - presum[0][i + 1], presum[1][i])); + return res; + } +}; + + +int main() { + + vector> grid1 = {{2, 5, 4}, {1, 5, 1}}; + cout << Solution().gridGame(grid1) << endl; + // 4 + + vector> grid2 = {{3, 3, 1}, {8, 5, 2}}; + cout << Solution().gridGame(grid1) << endl; + // 4 + + vector> grid3 = {{1, 3, 1, 15}, {1, 3, 3, 1}}; + cout << Solution().gridGame(grid3) << endl; + // 7 + + return 0; +} diff --git a/2001-2500/2018-Check-if-Word-Can-Be-Placed-In-Crossword/cpp-2018/CMakeLists.txt b/2001-2500/2018-Check-if-Word-Can-Be-Placed-In-Crossword/cpp-2018/CMakeLists.txt new file mode 100644 index 00000000..cad75f71 --- /dev/null +++ b/2001-2500/2018-Check-if-Word-Can-Be-Placed-In-Crossword/cpp-2018/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/2001-2500/2018-Check-if-Word-Can-Be-Placed-In-Crossword/cpp-2018/main.cpp b/2001-2500/2018-Check-if-Word-Can-Be-Placed-In-Crossword/cpp-2018/main.cpp new file mode 100644 index 00000000..a712cfc8 --- /dev/null +++ b/2001-2500/2018-Check-if-Word-Can-Be-Placed-In-Crossword/cpp-2018/main.cpp @@ -0,0 +1,98 @@ +/// Source : https://leetcode.com/problems/check-if-word-can-be-placed-in-crossword/ +/// Author : liuyubobobo +/// Time : 2021-09-25 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(R * C) +/// Space Complexity: O(R * C) +class Solution { + +private: + int R, C; + +public: + bool placeWordInCrossword(vector>& board, string word) { + + R = board.size(), C = board[0].size(); + + string p = ""; + for(int i = 0; i < R; i ++){ + p = ""; + for(int j = 0; j < C; j ++) + if(board[i][j] != '#' && (j == 0 || board[i][j - 1] == '#')){ + int k; + for(k = j; k < C && board[i][k] != '#'; k ++) + p += board[i][k]; +// cout << "(" << p << ") " << p.size() << endl; + if(ok(p, word)) return true; + j = k; + p = ""; + } + } + + for(int j = 0; j < C; j ++){ + p = ""; + for(int i = 0; i < R; i ++) + if(board[i][j] != '#' && (i == 0 || board[i - 1][j] == '#')){ + int k; + for(k = i; k < R && board[k][j] != '#'; k ++) + p += board[k][j]; +// cout << "(" << p << ") " << p.size() << endl; + if(ok(p, word)) return true; + i = k; + p = ""; + } + } + + return false; + } + +private: + bool ok(const string& p, const string& word){ + +// cout << "(" << p << ") " << p.size() << endl; + + if(p.size() != word.size()) return false; + + bool ok = true; + for(int i = 0; i < p.size(); i ++) + if(p[i] != ' ' && p[i] != word[i]){ + ok = false; + break; + } + + if(ok) return true; + + string word2 = word; + reverse(word2.begin(), word2.end()); + for(int i = 0; i < p.size(); i ++) + if(p[i] != ' ' && p[i] != word2[i]) + return false; + + return true; + } +}; + + +int main() { + + vector> board2 = {{' ', '#', 'a'}, {' ', '#', 'c'}, {' ', '#', 'a'}}; + cout << Solution().placeWordInCrossword(board2, "ac") << endl; + // 0 + + vector> board3 = {{'#', ' ', '#'}, {' ', ' ', '#'}, {'#', ' ', 'c'}}; + cout << Solution().placeWordInCrossword(board3, "ca") << endl; + // 1 + + vector> board4 = {{'#', ' ', '#'}, {' ', ' ', '#'}, {'#', 'c', ' '}}; + cout << Solution().placeWordInCrossword(board4, "abc") << endl; + // 1 + + return 0; +} diff --git a/2001-2500/2019-The-Score-of-Students-Solving-Math-Expression/cpp-2019/CMakeLists.txt b/2001-2500/2019-The-Score-of-Students-Solving-Math-Expression/cpp-2019/CMakeLists.txt new file mode 100644 index 00000000..a0d16fe6 --- /dev/null +++ b/2001-2500/2019-The-Score-of-Students-Solving-Math-Expression/cpp-2019/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) diff --git a/2001-2500/2019-The-Score-of-Students-Solving-Math-Expression/cpp-2019/main.cpp b/2001-2500/2019-The-Score-of-Students-Solving-Math-Expression/cpp-2019/main.cpp new file mode 100644 index 00000000..0481fffa --- /dev/null +++ b/2001-2500/2019-The-Score-of-Students-Solving-Math-Expression/cpp-2019/main.cpp @@ -0,0 +1,88 @@ +/// Source : https://leetcode.com/problems/the-score-of-students-solving-math-expression/ +/// Author : liuyubobobo +/// Time : 2021-09-25 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(15^3 * 1000^2 + |answers|) +/// Space Complexity: O(15^3 * 1000) +class Solution { +public: + int scoreOfStudents(string s, vector& answers) { + + vector nums = {s[0] - '0'}; + vector ops; + for(int i = 1; i < s.size(); i += 2){ + ops.push_back(s[i]); + nums.push_back(s[i + 1] - '0'); + } + + int n = nums.size(); + vector>> dp(n, vector>(n)); + for(int i = 0; i < n; i ++) dp[i][i].insert(nums[i]); + for(int sz = 2; sz <= n; sz ++) + for(int l = 0; l + sz <= n; l ++){ + // dp[l][l + sz - 1] + for(int lsz = 1; lsz < sz; lsz ++){ + for(int e1: dp[l][l + lsz - 1]) + for(int e2: dp[l + lsz][l + sz - 1]){ + if(ops[l + lsz - 1] == '+' && e1 + e2 <= 1000) + dp[l][l + sz - 1].insert(e1 + e2); + else if(ops[l + lsz - 1] == '*' && e1 * e2 <= 1000) + dp[l][l + sz - 1].insert(e1 * e2); + } + } + } + + int correct_ans = get_correct_ans(nums, ops); + int res = 0; + for(int ans: answers) + if(ans == correct_ans) res += 5; + else if(dp[0][n - 1].count(ans)) res += 2; + return res; + } + +private: + int get_correct_ans(const vector& nums, const vector& ops){ + + vector stack = {nums[0]}; + for(int i = 0; i < ops.size(); i ++) { + if (ops[i] == '*') { + int first = stack.back(); + stack.pop_back(); + stack.push_back(first * nums[i + 1]); + } else stack.push_back(nums[i + 1]); + } + + return accumulate(stack.begin(), stack.end(), 0); + } +}; + + +int main() { + + vector ans1 = {20, 13, 42}; + cout << Solution().scoreOfStudents("7+3*1*2", ans1) << endl; + // 7 + + vector ans2 = {13,0,10,13,13,16,16}; + cout << Solution().scoreOfStudents("3+5*2", ans2) << endl; + // 19 + + vector ans3 = {12,9,6,4,8,6}; + cout << Solution().scoreOfStudents("6+0*1", ans3) << endl; + // 10 + + vector ans4 = {12,9,6,4,8,6}; + cout << Solution().scoreOfStudents("9*9*3+6*6+3*3+6*6+6*3+9*9+6*3", ans4) << endl; + + return 0; +} diff --git a/2001-2500/2021-Brightest-Position-on-Street/CMakeLists.txt b/2001-2500/2021-Brightest-Position-on-Street/CMakeLists.txt new file mode 100644 index 00000000..72c76ace --- /dev/null +++ b/2001-2500/2021-Brightest-Position-on-Street/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(2021_Brightest_Position_on_Street) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(2021_Brightest_Position_on_Street main.cpp) diff --git a/2001-2500/2021-Brightest-Position-on-Street/main.cpp b/2001-2500/2021-Brightest-Position-on-Street/main.cpp new file mode 100644 index 00000000..ca0d0949 --- /dev/null +++ b/2001-2500/2021-Brightest-Position-on-Street/main.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/brightest-position-on-street/ +/// Author : liuyubobobo +/// Time : 2021-10-02 + +#include +#include + +using namespace std; + + +/// Sweep line +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + int brightestPosition(vector>& lights) { + + const int START = 0, END = 1; + + int n = lights.size(); + vector> v(2 * n); + for(int i = 0; i < n; i ++){ + v[2 * i] = {lights[i][0] - lights[i][1], START}; + v[2 * i + 1] = {lights[i][0] + lights[i][1], END}; + } + + sort(v.begin(), v.end()); + + int cur_brightness = 0, max_brightness = 0, res = INT_MIN; + for(const pair& p: v) + if(p.second == START){ + cur_brightness ++; + if(cur_brightness > max_brightness) + max_brightness = cur_brightness, res = p.first; + } + else + cur_brightness --; + return res; + } +}; + + +int main() { + + vector> lights = {{-3, 2}, {1, 2}, {3, 3}}; + cout << Solution().brightestPosition(lights) << endl; + // -1 + + return 0; +} diff --git a/2001-2500/2022-Convert-1D-Array-Into-2D-Array/cpp-2022/CMakeLists.txt b/2001-2500/2022-Convert-1D-Array-Into-2D-Array/cpp-2022/CMakeLists.txt new file mode 100644 index 00000000..2ae8397c --- /dev/null +++ b/2001-2500/2022-Convert-1D-Array-Into-2D-Array/cpp-2022/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/2001-2500/2022-Convert-1D-Array-Into-2D-Array/cpp-2022/main.cpp b/2001-2500/2022-Convert-1D-Array-Into-2D-Array/cpp-2022/main.cpp new file mode 100644 index 00000000..ae1ecd91 --- /dev/null +++ b/2001-2500/2022-Convert-1D-Array-Into-2D-Array/cpp-2022/main.cpp @@ -0,0 +1,31 @@ +/// Source : https://leetcode.com/problems/convert-1d-array-into-2d-array/ +/// Author : liuyubobobo +/// Time : 2021-10-02 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(m * n) +/// Space Complexity: O(1) +class Solution { +public: + vector> construct2DArray(vector& original, int m, int n) { + + if(original.size() != m * n) return {}; + + vector> res(m, vector(n)); + for(int i = 0; i < original.size(); i ++) + res[i / n][i % n] = original[i]; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2023-Number-of-Pairs-of-Strings-With-Concatenation-Equal-to-Target/cpp-2023/CMakeLists.txt b/2001-2500/2023-Number-of-Pairs-of-Strings-With-Concatenation-Equal-to-Target/cpp-2023/CMakeLists.txt new file mode 100644 index 00000000..084dd354 --- /dev/null +++ b/2001-2500/2023-Number-of-Pairs-of-Strings-With-Concatenation-Equal-to-Target/cpp-2023/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main2.cpp) diff --git a/2001-2500/2023-Number-of-Pairs-of-Strings-With-Concatenation-Equal-to-Target/cpp-2023/main.cpp b/2001-2500/2023-Number-of-Pairs-of-Strings-With-Concatenation-Equal-to-Target/cpp-2023/main.cpp new file mode 100644 index 00000000..d215ed52 --- /dev/null +++ b/2001-2500/2023-Number-of-Pairs-of-Strings-With-Concatenation-Equal-to-Target/cpp-2023/main.cpp @@ -0,0 +1,30 @@ +/// Source : https://leetcode.com/problems/number-of-pairs-of-strings-with-concatenation-equal-to-target/ +/// Author : liuyubobobo +/// Time : 2021-10-02 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n^2 * |nums[i].length|) +/// Space Complexity: O(1) +class Solution { +public: + int numOfPairs(vector& nums, string target) { + + int res = 0, n = nums.size(); + for(int i = 0; i < n; i ++) + for(int j = 0; j < n; j ++) + if(i != j) res += nums[i] + nums[j] == target; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2023-Number-of-Pairs-of-Strings-With-Concatenation-Equal-to-Target/cpp-2023/main2.cpp b/2001-2500/2023-Number-of-Pairs-of-Strings-With-Concatenation-Equal-to-Target/cpp-2023/main2.cpp new file mode 100644 index 00000000..35201afb --- /dev/null +++ b/2001-2500/2023-Number-of-Pairs-of-Strings-With-Concatenation-Equal-to-Target/cpp-2023/main2.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/number-of-pairs-of-strings-with-concatenation-equal-to-target/ +/// Author : liuyubobobo +/// Time : 2021-10-02 + +#include +#include +#include + +using namespace std; + + +/// Split target + Using HashMap +/// Time Complexity: O(|t| * |nums[i].length|) +/// Space Complexity: O(n) +class Solution { +public: + int numOfPairs(vector& nums, string target) { + + int res = 0; + map f; + + for(const string& s: nums) f[s] ++; + for(int len = 1; len + 1 <= target.size(); len ++){ + string a = target.substr(0, len), b = target.substr(len); + if(a == b && f.count(a)){ + int n = f[a]; + res += n * (n - 1); + } + else if(a != b && f.count(a) && f.count(b)) + res += f[a] * f[b]; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2024-Maximize-the-Confusion-of-an-Exam/cpp-2024/CMakeLists.txt b/2001-2500/2024-Maximize-the-Confusion-of-an-Exam/cpp-2024/CMakeLists.txt new file mode 100644 index 00000000..cad75f71 --- /dev/null +++ b/2001-2500/2024-Maximize-the-Confusion-of-an-Exam/cpp-2024/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/2001-2500/2024-Maximize-the-Confusion-of-an-Exam/cpp-2024/main.cpp b/2001-2500/2024-Maximize-the-Confusion-of-an-Exam/cpp-2024/main.cpp new file mode 100644 index 00000000..02557b59 --- /dev/null +++ b/2001-2500/2024-Maximize-the-Confusion-of-an-Exam/cpp-2024/main.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/maximize-the-confusion-of-an-exam/ +/// Author : liuyubobobo +/// Time : 2021-10-02 + +#include +#include + +using namespace std; + + +/// Sliding Window +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int maxConsecutiveAnswers(string answerKey, int k) { + + int n = answerKey.size(); + return max(get_res(n, answerKey, 'T', k), get_res(n, answerKey, 'F', k)); + } + +private: + int get_res(int n, const string answerKey, char c, int k){ + + int res = 0, l = 0, r = -1, cur = 0; + while(l < n){ + if(r + 1 < n && cur + (answerKey[r + 1] == c) <= k) + cur += answerKey[++ r] == c; + else + cur -= answerKey[l ++] == c; + res = max(res, r - l + 1); + } + return res; + } +}; + + +int main() { + + cout << Solution().maxConsecutiveAnswers("TTFF", 2) << endl; + // 4 + + cout << Solution().maxConsecutiveAnswers("TFFT", 1) << endl; + // 3 + + cout << Solution().maxConsecutiveAnswers("TTFTTFTT", 1) << endl; + // 5 + + return 0; +} diff --git a/2001-2500/2025-Maximum-Number-of-Ways-to-Partition-an-Array/cpp-2025/CMakeLists.txt b/2001-2500/2025-Maximum-Number-of-Ways-to-Partition-an-Array/cpp-2025/CMakeLists.txt new file mode 100644 index 00000000..a0d16fe6 --- /dev/null +++ b/2001-2500/2025-Maximum-Number-of-Ways-to-Partition-an-Array/cpp-2025/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) diff --git a/2001-2500/2025-Maximum-Number-of-Ways-to-Partition-an-Array/cpp-2025/main.cpp b/2001-2500/2025-Maximum-Number-of-Ways-to-Partition-an-Array/cpp-2025/main.cpp new file mode 100644 index 00000000..b4ed66b4 --- /dev/null +++ b/2001-2500/2025-Maximum-Number-of-Ways-to-Partition-an-Array/cpp-2025/main.cpp @@ -0,0 +1,92 @@ +/// Source : https://leetcode.com/problems/maximum-number-of-ways-to-partition-an-array/ +/// Author : liuyubobobo +/// Time : 2021-10-03 + +#include +#include +#include +#include + +using namespace std; + + +/// Presum + Using HashSet + Binary Search +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + int waysToPartition(vector& nums, int k) { + + int n = nums.size(); + vector presum(n, nums[0]); + for(int i = 1; i < n; i ++) + presum[i] = presum[i - 1] + nums[i]; + + int res = 0; + for(int p = 0; p + 1 < n; p ++) { + // [0...p] == [p + 1... n - 1] + if (presum[p] == presum[n - 1] - presum[p]) + res ++; + } + + map> f; + for(int i = 0; i + 1 < n; i ++) + f[presum[i]].push_back(i); + + for(int i = 0; i < n; i ++){ + // try to change nums[i] to k + long long delta = k - nums[i]; + if(delta == 0) continue; + + int tres = 0; + + if((presum[n - 1] - delta) % 2 == 0){ + vector& v1 = f[(presum[n - 1] - delta) / 2]; + tres += v1.end() - lower_bound(v1.begin(), v1.end(), i); + } + + if((presum[n - 1] + delta) % 2 == 0){ + vector& v2 = f[(presum[n - 1] + delta) / 2]; + auto iter = lower_bound(v2.begin(), v2.end(), i); + tres += iter - v2.begin(); + } + + res = max(res, tres); + } + + return res; + } +}; + +int main() { + + vector nums0 = {0,0,100,0}; + cout << Solution().waysToPartition(nums0, 0) << endl; + // 3 + + vector nums1 = {2, -1, 2}; + cout << Solution().waysToPartition(nums1, 3) << endl; + // 1 + + vector nums2 = {0, 0, 0}; + cout << Solution().waysToPartition(nums2, 1) << endl; + // 2 + + vector nums3 = {22,4,-25,-20,-15,15,-16,7,19,-10,0,-13,-14}; + cout << Solution().waysToPartition(nums3, -33) << endl; + // 4 + + vector nums4 = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,30827,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; + cout << Solution().waysToPartition(nums4, 0) << endl; + // 33 + + vector nums5 = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,99,0,0,0,0,-99,0}; + cout << Solution().waysToPartition(nums5, 0) << endl; + // 60 + + vector nums6 = {0,0,0,1077,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,70590,0,0,0,0,0,0,0,0,0,0,0,0,0}; + cout << Solution().waysToPartition(nums6, 1077) << endl; + // 57 + + return 0; +} diff --git a/2001-2500/2027-Minimum-Moves-to-Convert-String/cpp-2027/CMakeLists.txt b/2001-2500/2027-Minimum-Moves-to-Convert-String/cpp-2027/CMakeLists.txt new file mode 100644 index 00000000..2ae8397c --- /dev/null +++ b/2001-2500/2027-Minimum-Moves-to-Convert-String/cpp-2027/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/2001-2500/2027-Minimum-Moves-to-Convert-String/cpp-2027/main.cpp b/2001-2500/2027-Minimum-Moves-to-Convert-String/cpp-2027/main.cpp new file mode 100644 index 00000000..2071b817 --- /dev/null +++ b/2001-2500/2027-Minimum-Moves-to-Convert-String/cpp-2027/main.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/minimum-moves-to-convert-string/ +/// Author : liuyubobobo +/// Time : 2021-10-02 + +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int minimumMoves(string s) { + + int n = s.size(), res = 0; + for(int i = 0; i < n; i ++){ + if(s[i] == 'X'){ + res ++; + s[i] = 'O'; + if(i + 1 < n) s[i + 1] = 'O'; + if(i + 2 < n) s[i + 2] = 'O'; + } + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2028-Find-Missing-Observations/cpp-2028/CMakeLists.txt b/2001-2500/2028-Find-Missing-Observations/cpp-2028/CMakeLists.txt new file mode 100644 index 00000000..3f98647f --- /dev/null +++ b/2001-2500/2028-Find-Missing-Observations/cpp-2028/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/2001-2500/2028-Find-Missing-Observations/cpp-2028/main.cpp b/2001-2500/2028-Find-Missing-Observations/cpp-2028/main.cpp new file mode 100644 index 00000000..c41f289c --- /dev/null +++ b/2001-2500/2028-Find-Missing-Observations/cpp-2028/main.cpp @@ -0,0 +1,62 @@ +/// Source : https://leetcode.com/problems/find-missing-observations/ +/// Author : liuyubobobo +/// Time : 2021-10-02 + +#include +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity : O(m + n) +/// Space Complexity: O(1) +class Solution { +public: + vector missingRolls(vector& rolls, int mean, int n) { + + int m = rolls.size(), rolls_sum = accumulate(rolls.begin(), rolls.end(), 0); + + int total = mean * (m + n), left_total = total - rolls_sum; + + if(n <= left_total && left_total <= 6 * n){ + + vector res(n, 1); + left_total -= n; + for(int i = 0; i < n && left_total; i ++){ + int t = min(5, left_total); + res[i] += t; + left_total -= t; + } + return res; + } + return {}; + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << ' '; cout << '\n'; +} + +int main() { + + vector rolls1 = {3, 2, 4, 3}; + print_vec(Solution().missingRolls(rolls1, 4, 2)); + // 6 6 + + vector rolls2 = {1, 5, 6}; + print_vec(Solution().missingRolls(rolls2, 3, 4)); + // 2 3 2 2 + + vector rolls3 = {1, 2, 3, 4}; + print_vec(Solution().missingRolls(rolls3, 6, 4)); + // empty + + vector rolls4 = {1}; + print_vec(Solution().missingRolls(rolls4, 3, 1)); + // 5 + + return 0; +} diff --git a/2001-2500/2029-Stone-Game-IX/cpp-2029/CMakeLists.txt b/2001-2500/2029-Stone-Game-IX/cpp-2029/CMakeLists.txt new file mode 100644 index 00000000..cad75f71 --- /dev/null +++ b/2001-2500/2029-Stone-Game-IX/cpp-2029/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/2001-2500/2029-Stone-Game-IX/cpp-2029/main.cpp b/2001-2500/2029-Stone-Game-IX/cpp-2029/main.cpp new file mode 100644 index 00000000..70ea0b37 --- /dev/null +++ b/2001-2500/2029-Stone-Game-IX/cpp-2029/main.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/stone-game-ix/ +/// Author : liuyubobobo +/// Time : 2021-10-03 + +#include +#include +#include + +using namespace std; + + +/// Game Theory - Ad-Hoc +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + bool stoneGameIX(vector& stones) { + + vector f(3, 0); + for(int e: stones) f[e % 3] ++; + + // 112121212... + int start_one_len = 0; + if(f[1]){ + start_one_len += 1; + int one_left = f[1] - 1, two_left = f[2]; + start_one_len += min(one_left, two_left) * 2; + if(one_left > two_left) start_one_len += 1; + + start_one_len += f[0]; + if(start_one_len < stones.size() && start_one_len % 2) return true; + } + + // 22121212121... + int start_two_len = 0; + if(f[2]){ + start_two_len += 1; + int one_left = f[1], two_left = f[2] - 1; + start_two_len += min(one_left, two_left) * 2; + if(two_left > one_left) start_two_len += 1; + + start_two_len += f[0]; + if(start_two_len < stones.size() && start_two_len % 2) return true; + } + + return false; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2030-Smallest-K-Length-Subsequence-With-Occurrences-of-a-Letter/cpp-2030/CMakeLists.txt b/2001-2500/2030-Smallest-K-Length-Subsequence-With-Occurrences-of-a-Letter/cpp-2030/CMakeLists.txt new file mode 100644 index 00000000..2a7f1f76 --- /dev/null +++ b/2001-2500/2030-Smallest-K-Length-Subsequence-With-Occurrences-of-a-Letter/cpp-2030/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main2.cpp) diff --git a/2001-2500/2030-Smallest-K-Length-Subsequence-With-Occurrences-of-a-Letter/cpp-2030/main.cpp b/2001-2500/2030-Smallest-K-Length-Subsequence-With-Occurrences-of-a-Letter/cpp-2030/main.cpp new file mode 100644 index 00000000..f5dd0a7e --- /dev/null +++ b/2001-2500/2030-Smallest-K-Length-Subsequence-With-Occurrences-of-a-Letter/cpp-2030/main.cpp @@ -0,0 +1,120 @@ +/// Source : https://leetcode.com/problems/smallest-k-length-subsequence-with-occurrences-of-a-letter/ +/// Author : liuyubobobo +/// Time : 2021-10-02 + +#include +#include +#include + +using namespace std; + + +/// Greedy with ST Range Query (Segment Tree got TLE) +/// Time Complexity: O(nlogn) +/// Space Complexity: O(nlogn) +class SparseTable{ + +private: + int n; + vector data; + vector> table; + vector log2; + +public: + SparseTable(const vector& data): n(data.size()), data(data), log2(n + 1, 1){ + + int len = 2, k = 1; + for(int i = 1; i <= n; i ++){ + if(i >= len) len <<= 1, k ++; + log2[i] = k; + } + + int K = log2[n]; + table = vector>(K, vector(n)); + + for(int i = 0; i < n; i ++) + table[0][i] = i; + + for(int k = 1; k < K; k ++) + for(int i = 0; i + (1 << (k - 1)) < n; i ++) + table[k][i] = data[table[k - 1][i]] <= data[table[k - 1][i + (1 << (k - 1))]] ? + table[k - 1][i] : table[k - 1][i + (1 << (k - 1))]; + } + + int query(int l, int r){ + + int k = log2[r - l + 1]; + return data[table[k - 1][l]] <= data[table[k - 1][r + 1 - (1 << (k - 1))]] ? + table[k - 1][l] : table[k - 1][r + 1 - (1 << (k - 1))]; + } +}; + +class Solution { + +private: + SparseTable *st; + string res = ""; + +public: + string smallestSubsequence(string s, int k, char letter, int repetition) { + + int n = s.size(); + + vector v(n, 0); + for(int i = 0; i < n; i ++) v[i] = s[i] - 'a'; + + st = new SparseTable(v); + + map letter_pos; + letter_pos[0] = n - 1; + int cur = 0; + for(int i = n - 1; i >= 0; i --) + if(s[i] == letter){ + cur ++; + letter_pos[cur] = i; + } + + res = ""; + dfs(n, s, letter, 0, k, repetition, letter_pos); + return res; + } + +private: + void dfs(int n, const string& s, char letter, + int l, int len, int rep, map& letter_pos){ + + if(len == 0) return; + if(len == n - l){res += s.substr(l); return;} + if(len == rep){res += string(rep, letter); return;} + +// assert(n - l >= len && l <= r); + + int p = letter_pos[rep]; +// assert(l <= p); + int min_index = st->query(l, min(p, n - len)); + + res += s[min_index]; + dfs(n, s, letter, min_index + 1, len - 1, max(rep - (s[min_index] == letter), 0), letter_pos); + } +}; + + +int main() { + + cout << Solution().smallestSubsequence("leet", 3, 'e', 1) << endl; + // eet + + cout << Solution().smallestSubsequence("leetcode", 4, 'e', 2) << endl; + // ecde + + cout << Solution().smallestSubsequence("bb", 2, 'b', 2) << endl; + // bb + + cout << Solution().smallestSubsequence("aaabbbcccddd", 3, 'b', 2) << endl; + // abb + + cout << Solution().smallestSubsequence("eeeexeeeyexyyeyxeyexyxeyexeexyexxxxyxeye", 7, 'e', 2) << endl; + // abb + + return 0; +} diff --git a/2001-2500/2030-Smallest-K-Length-Subsequence-With-Occurrences-of-a-Letter/cpp-2030/main2.cpp b/2001-2500/2030-Smallest-K-Length-Subsequence-With-Occurrences-of-a-Letter/cpp-2030/main2.cpp new file mode 100644 index 00000000..525446af --- /dev/null +++ b/2001-2500/2030-Smallest-K-Length-Subsequence-With-Occurrences-of-a-Letter/cpp-2030/main2.cpp @@ -0,0 +1,71 @@ +/// Source : https://leetcode.com/problems/smallest-k-length-subsequence-with-occurrences-of-a-letter/ +/// Author : liuyubobobo +/// Time : 2021-10-03 + +#include +#include +#include + +using namespace std; + + +/// Greedy using Stack +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +public: + string smallestSubsequence(string s, int k, char target, int reps) { + + int n = s.size(); + + int target_num = 0; + for(char c: s) target_num += (c == target); + + string res = ""; + for(int i = 0; i < n; i ++){ + + while(!res.empty() && + s[i] < res.back() && n - i >= k + 1 && target_num >= reps + (res.back() == target)){ + + reps += (res.back() == target); + k ++; + res.pop_back(); + } + + if(k && k - 1 >= reps - (s[i] == target)){ + reps -= (s[i] == target); + k --; + res += s[i]; + } + + target_num -= (s[i] == target); + } + + return res; + } +}; + + +int main() { + + cout << Solution().smallestSubsequence("leet", 3, 'e', 1) << endl; + // eet + + cout << Solution().smallestSubsequence("leetcode", 4, 'e', 2) << endl; + // ecde + + cout << Solution().smallestSubsequence("bb", 2, 'b', 2) << endl; + // bb + + cout << Solution().smallestSubsequence("aaabbbcccddd", 3, 'b', 2) << endl; + // abb + + cout << Solution().smallestSubsequence("exexe", 3, 'e', 2) << endl; + // eee + + cout << Solution().smallestSubsequence("eeeexeeeyexyyeyxeyexyxeyexeexyexxxxyxeye", 7, 'e', 2) << endl; + // eeeeeee + + return 0; +} diff --git a/2001-2500/2031-Count-Subarrays-With-More-Ones-Than-Zeros/cpp-2031/CMakeLists.txt b/2001-2500/2031-Count-Subarrays-With-More-Ones-Than-Zeros/cpp-2031/CMakeLists.txt new file mode 100644 index 00000000..338dc22e --- /dev/null +++ b/2001-2500/2031-Count-Subarrays-With-More-Ones-Than-Zeros/cpp-2031/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_2031) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2031 main.cpp) diff --git a/2001-2500/2031-Count-Subarrays-With-More-Ones-Than-Zeros/cpp-2031/main.cpp b/2001-2500/2031-Count-Subarrays-With-More-Ones-Than-Zeros/cpp-2031/main.cpp new file mode 100644 index 00000000..4aec6dc6 --- /dev/null +++ b/2001-2500/2031-Count-Subarrays-With-More-Ones-Than-Zeros/cpp-2031/main.cpp @@ -0,0 +1,152 @@ +/// Source : https://leetcode.com/problems/count-subarrays-with-more-ones-than-zeros/ +/// Author : liuyubobobo +/// Time : 2021-10-10 + +#include +#include + +using namespace std; + + +/// More one than zero in [l...r] means 2(presum[r] - presum[l - 1]) > (r - l + 1) +/// So: 2*presum[r] - r > 2*presum[l - 1] - (l - 1) +/// for every r, fond the number of l satisfy the above condition +/// Using segment tree +/// +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +template +class SegmentTree{ + +private: + int n; + vector data, tree; + T (*combine)(T a, T b); + +public: + SegmentTree(const vector& data, T (*combine)(T a, T b)): n(data.size()), data(data), tree(4 * n, 0){ + this->combine = combine; + buildSegTree(0, 0, n - 1); + } + + SegmentTree(int n, T (*combine)(T a, T b)): n(n), data(n, 0), tree(4 * n, 0){ + this->combine = combine; + } + + void update(int index, T value){ + if(data[index] == value) return; + data[index] = value; + update(0, 0, n - 1, index, value); + } + + T query(int index){ + assert(0 <= index && index < n); + return data[index]; + } + + T query(int l, int r){ + if(l >r) return 0; + assert(0 <= l && l < n); + assert(0 <= r && r < n); + return query(0, 0, n - 1, l, r); + } + +private: + void buildSegTree(int treeID, int l, int r){ + + if(l == r){ + tree[treeID] = data[l]; + return; + } + + int mid = (l + r) / 2; + buildSegTree(treeID * 2 + 1, l, mid); + buildSegTree(treeID * 2 + 2, mid + 1, r); + tree[treeID] = combine(tree[treeID * 2 + 1], tree[treeID * 2 + 2]); + return; + } + + void update(int treeID, int l, int r, int index, T value){ + + if(l == r){ + assert(l == index); + tree[treeID] = value; + return; + } + + int mid = (l + r) / 2; + if(index <= mid) update(treeID * 2 + 1, l, mid, index, value); + else update(treeID * 2 + 2, mid + 1, r, index, value); + + tree[treeID] = combine(tree[treeID * 2 + 1], tree[treeID * 2 + 2]); + return; + } + + T query(int treeID, int l, int r, int ql, int qr){ + + if(ql == l && qr == r) + return tree[treeID]; + + int mid = (l + r) / 2; + if(qr <= mid) return query(treeID * 2 + 1, l, mid, ql, qr); + else if(ql > mid) return query(treeID * 2 + 2, mid + 1, r, ql, qr); + + T resl = query(treeID * 2 + 1, l, mid, ql, mid); + T resr = query(treeID * 2 + 2, mid + 1, r, mid + 1, qr); + return combine(resl, resr); + } +}; + +class Solution { +public: + int subarraysWithMoreZerosThanOnes(vector& nums) { + + int n = nums.size(); + vector presum(n + 1, 0); + for(int i = 0; i < n; i ++) + presum[i + 1] = presum[i] + nums[i]; + + for(int i = 0; i <= n; i ++) + presum[i] = 2 * presum[i] - i; + +// for(int e: presum) cout << e << ' '; cout << '\n'; + + vector> data(n + 1); + for(int i = 0; i <= n; i ++) + data[i] = {presum[i], i}; + sort(data.begin(), data.end(), + [](const pair& p1, const pair& p2){ + if(p1.first != p2.first) return p1.first > p2.first; + return p1.second < p2.second; + }); + + SegmentTree seg_tree(vector(n + 1, 1), [](int a, int b){return a + b;}); + + int res = 0, MOD = 1e9 + 7; + for(const pair& p: data){ + int index = p.second; + res += seg_tree.query(0, p.second - 1); + res %= MOD; + seg_tree.update(index, 0); + } + return res; + } +}; + + +int main() { + + vector nums1 = {0, 1, 1, 0, 1}; + cout << Solution().subarraysWithMoreZerosThanOnes(nums1) << endl; + // 9 + + vector nums2 = {0}; + cout << Solution().subarraysWithMoreZerosThanOnes(nums2) << endl; + // 0 + + vector nums3 = {1}; + cout << Solution().subarraysWithMoreZerosThanOnes(nums3) << endl; + // 1 + + return 0; +} diff --git a/2001-2500/2032-Two-Out-of-Three/cpp-2032/CMakeLists.txt b/2001-2500/2032-Two-Out-of-Three/cpp-2032/CMakeLists.txt new file mode 100644 index 00000000..76479ef2 --- /dev/null +++ b/2001-2500/2032-Two-Out-of-Three/cpp-2032/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main2.cpp) diff --git a/2001-2500/2032-Two-Out-of-Three/cpp-2032/main.cpp b/2001-2500/2032-Two-Out-of-Three/cpp-2032/main.cpp new file mode 100644 index 00000000..6273d6b5 --- /dev/null +++ b/2001-2500/2032-Two-Out-of-Three/cpp-2032/main.cpp @@ -0,0 +1,39 @@ +/// Source : https://leetcode.com/problems/two-out-of-three/ +/// Author : liuyubobobo +/// Time : 2021-10-09 + +#include +#include +#include + +using namespace std; + + +/// Using Set +/// Time Complexity: O(n1logn1 + n2logn2 + n3logn3) +/// Space Complexity: O(n1 + n2 + n3) +class Solution { +public: + vector twoOutOfThree(vector& nums1, vector& nums2, vector& nums3) { + + set set1(nums1.begin(), nums1.end()); + set set2(nums2.begin(), nums2.end()); + set set3(nums3.begin(), nums3.end()); + + vector f(101, 0); + for(int e: set1) f[e] ++; + for(int e: set2) f[e] ++; + for(int e: set3) f[e] ++; + + vector res; + for(int i = 0; i <= 100; i ++) + if(f[i] >= 2) res.push_back(i); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2032-Two-Out-of-Three/cpp-2032/main2.cpp b/2001-2500/2032-Two-Out-of-Three/cpp-2032/main2.cpp new file mode 100644 index 00000000..769bcd19 --- /dev/null +++ b/2001-2500/2032-Two-Out-of-Three/cpp-2032/main2.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/two-out-of-three/ +/// Author : liuyubobobo +/// Time : 2021-10-10 + +#include +#include + +using namespace std; + + +/// Using Array instead of Set +/// Time Complexity: O(n1 + n2 + n3) +/// Space Complexity: O(n1 + n2 + n3) +class Solution { +public: + vector twoOutOfThree(vector& nums1, vector& nums2, vector& nums3) { + + vector f1(101, false), f2(101, false), f3(101, false); + for(int e: nums1) f1[e] = true; + for(int e: nums2) f2[e] = true; + for(int e: nums3) f3[e] = true; + + vector res; + for(int i = 0; i <= 100; i ++) + if(f1[i] + f2[i] + f3[i] >= 2) res.push_back(i); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2033-Minimum-Operations-to-Make-a-Uni-Value-Grid/cpp-2033/CMakeLists.txt b/2001-2500/2033-Minimum-Operations-to-Make-a-Uni-Value-Grid/cpp-2033/CMakeLists.txt new file mode 100644 index 00000000..3f98647f --- /dev/null +++ b/2001-2500/2033-Minimum-Operations-to-Make-a-Uni-Value-Grid/cpp-2033/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/2001-2500/2033-Minimum-Operations-to-Make-a-Uni-Value-Grid/cpp-2033/main.cpp b/2001-2500/2033-Minimum-Operations-to-Make-a-Uni-Value-Grid/cpp-2033/main.cpp new file mode 100644 index 00000000..ecc890f8 --- /dev/null +++ b/2001-2500/2033-Minimum-Operations-to-Make-a-Uni-Value-Grid/cpp-2033/main.cpp @@ -0,0 +1,58 @@ +/// Source : https://leetcode.com/problems/minimum-operations-to-make-a-uni-value-grid/ +/// Author : liuyubobobo +/// Time : 2021-10-09 + +#include +#include + +using namespace std; + + +/// Go to median +/// Time Complexity: O(R * C * log(R * C)) +/// Space Complexity: O() +class Solution { + +private: + int R, C; + +public: + int minOperations(vector>& grid, int x) { + + R = grid.size(), C = grid[0].size(); + + int len = R * C; + vector A; + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++) + A.push_back(grid[i][j]); + + sort(A.begin(), A.end()); + + if(len % 2 == 1) + return solve(grid, x, A[len / 2]); + + int tres = solve(grid, x, A[len / 2]); + if(tres != -1) return tres; + return solve(grid, x, A[(len - 1) / 2]); + } + +private: + int solve(const vector>& grid, int x, int t){ + + int res = 0; + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++){ + int k = abs(grid[i][j] - t); + if(k % x) return -1; + res += k / x; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2034-Stock-Price-Fluctuation/cpp-2034/CMakeLists.txt b/2001-2500/2034-Stock-Price-Fluctuation/cpp-2034/CMakeLists.txt new file mode 100644 index 00000000..0ffd6e97 --- /dev/null +++ b/2001-2500/2034-Stock-Price-Fluctuation/cpp-2034/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main2.cpp) diff --git a/2001-2500/2034-Stock-Price-Fluctuation/cpp-2034/main.cpp b/2001-2500/2034-Stock-Price-Fluctuation/cpp-2034/main.cpp new file mode 100644 index 00000000..ee7d7f25 --- /dev/null +++ b/2001-2500/2034-Stock-Price-Fluctuation/cpp-2034/main.cpp @@ -0,0 +1,59 @@ +/// Source : https://leetcode.com/problems/stock-price-fluctuation/ +/// Author : liuyubobobo +/// Time : 2021-10-09 + +#include +#include +#include + +using namespace std; + + +/// Using Set +/// Time Complexity: O(logn) +/// Space Complexity: O(n) +class StockPrice { + +private: + map stocks; // time, price + set> prices; // (price, time) + +public: + StockPrice() {} + + void update(int timestamp, int price) { + + if(stocks.count(timestamp)){ + int p = stocks[timestamp]; + prices.erase({p, timestamp}); + } + + stocks[timestamp] = price; + prices.insert({price, timestamp}); + } + + int current() { + return stocks.rbegin()->second; + } + + int maximum() { + return prices.rbegin()->first; + } + + int minimum() { + return prices.begin()->first; + } +}; + +int main() { + + StockPrice st; + st.update(1, 10); + st.update(2, 5); + cout << st.current() << endl; + cout << st.maximum() << endl; + st.update(1, 3); + cout << st.maximum() << endl; // 5 + + return 0; +} diff --git a/2001-2500/2034-Stock-Price-Fluctuation/cpp-2034/main2.cpp b/2001-2500/2034-Stock-Price-Fluctuation/cpp-2034/main2.cpp new file mode 100644 index 00000000..6b177890 --- /dev/null +++ b/2001-2500/2034-Stock-Price-Fluctuation/cpp-2034/main2.cpp @@ -0,0 +1,58 @@ +/// Source : https://leetcode.com/problems/stock-price-fluctuation/ +/// Author : liuyubobobo +/// Time : 2021-10-10 + +#include +#include +#include + +using namespace std; + + +/// Using MultiSet +/// Time Complexity: O(logn) +/// Space Complexity: O(n) +class StockPrice { + +private: + map stocks; // time, price + multiset prices; // (price, time) + +public: + StockPrice() {} + + void update(int timestamp, int price) { + + if(stocks.count(timestamp)) + prices.erase(prices.find(stocks[timestamp])); + + stocks[timestamp] = price; + prices.insert(price); + } + + int current() { + return stocks.rbegin()->second; + } + + int maximum() { + return *prices.rbegin(); + } + + int minimum() { + return *prices.begin(); + } +}; + + +int main() { + + StockPrice st; + st.update(1, 10); + st.update(2, 5); + cout << st.current() << endl; + cout << st.maximum() << endl; + st.update(1, 3); + cout << st.maximum() << endl; // 5 + + return 0; +} diff --git a/2001-2500/2035-Partition-Array-Into-Two-Arrays-to-Minimize-Sum-Difference/cpp-2035/CMakeLists.txt b/2001-2500/2035-Partition-Array-Into-Two-Arrays-to-Minimize-Sum-Difference/cpp-2035/CMakeLists.txt new file mode 100644 index 00000000..a0d16fe6 --- /dev/null +++ b/2001-2500/2035-Partition-Array-Into-Two-Arrays-to-Minimize-Sum-Difference/cpp-2035/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) diff --git a/2001-2500/2035-Partition-Array-Into-Two-Arrays-to-Minimize-Sum-Difference/cpp-2035/main.cpp b/2001-2500/2035-Partition-Array-Into-Two-Arrays-to-Minimize-Sum-Difference/cpp-2035/main.cpp new file mode 100644 index 00000000..dd351645 --- /dev/null +++ b/2001-2500/2035-Partition-Array-Into-Two-Arrays-to-Minimize-Sum-Difference/cpp-2035/main.cpp @@ -0,0 +1,79 @@ +/// Source : https://leetcode.com/problems/partition-array-into-two-arrays-to-minimize-sum-difference/ +/// Author : liuyubobobo +/// Time : 2021-10-09 + +#include +#include + +using namespace std; + + +/// Bit Mask + Binary Search +/// Time Complexity: O(2 ^ (n / 2) * (n / 2)) +/// Space Complexity: O(2 ^ (n / 2)) +class Solution { +public: + int minimumDifference(vector& nums) { + + int n = nums.size(); + int half = n / 2; + + vector sum1(1 << half, 0); + for(int state = 1; state < (1 << half); state ++){ + int p = __builtin_ffs(state) - 1; + sum1[state] = sum1[state - (1 << p)] + nums[p]; + } + + vector sum2(1 << half, 0); + for(int state = 1; state < (1 << half); state ++){ + int p = __builtin_ffs(state) - 1; + sum2[state] = sum2[state - (1 << p)] + nums[half + p]; + } + + vector> ones(16); + for(int state = 0; state < (1 << half); state ++){ + int k = __builtin_popcount(state); + ones[k].push_back(sum2[state] - sum2[(1 << half) - 1 - state]); + } + for(int i = 0; i <= 15; i ++) + sort(ones[i].begin(), ones[i].end()); + + int res = INT_MAX; + for(int state1 = 0; state1 < (1 << half); state1 ++){ + int k1 = __builtin_popcount(state1); + int k2 = half - k1; + + int cur = sum1[state1] - sum1[(1 << half) - 1 - state1]; + vector::iterator iter = lower_bound(ones[k2].begin(), ones[k2].end(), -cur); + if(iter != ones[k2].end()) + res = min(res, abs(cur + *iter)); + if(iter != ones[k2].begin()){ + iter --; + res = min(res, abs(cur + *iter)); + } + } + return res; + } +}; + + +int main() { + + vector nums1 = {3, 9, 7, 3}; + cout << Solution().minimumDifference(nums1) << endl; + // 2 + + vector nums2 = {36, -36}; + cout << Solution().minimumDifference(nums2) << endl; + // 72 + + vector nums3 = {2,-1,0,4,-2,-9}; + cout << Solution().minimumDifference(nums3) << endl; + // 0 + + vector nums4 = {76,8,45,20,74,84,28,1}; + cout << Solution().minimumDifference(nums4) << endl; + // 2 + + return 0; +} diff --git a/2001-2500/2036-Maximum-Alternating-Subarray-Sum/cpp-2036/CMakeLists.txt b/2001-2500/2036-Maximum-Alternating-Subarray-Sum/cpp-2036/CMakeLists.txt new file mode 100644 index 00000000..d5716076 --- /dev/null +++ b/2001-2500/2036-Maximum-Alternating-Subarray-Sum/cpp-2036/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_2036) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2036 main.cpp) diff --git a/2001-2500/2036-Maximum-Alternating-Subarray-Sum/cpp-2036/main.cpp b/2001-2500/2036-Maximum-Alternating-Subarray-Sum/cpp-2036/main.cpp new file mode 100644 index 00000000..a61a0040 --- /dev/null +++ b/2001-2500/2036-Maximum-Alternating-Subarray-Sum/cpp-2036/main.cpp @@ -0,0 +1,64 @@ +/// Source : https://leetcode.com/problems/maximum-alternating-subarray-sum/ +/// Author : liuyubobobo +/// Time : 2021-10-18 + +#include +#include + +using namespace std; + + +/// Presum +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + long long maximumAlternatingSubarraySum(vector& nums) { + + int n = nums.size(); + + vector even(n, nums[0]); + for(int i = 1; i < n; i ++) + if(i % 2) even[i] = even[i - 1] - nums[i]; + else even[i] = even[i - 1] + nums[i]; + + vector odd(n, 0); + for(int i = 1; i < n; i ++) + if(i % 2) odd[i] = odd[i - 1] + nums[i]; + else odd[i] = odd[i - 1] - nums[i]; + + long long even_max = LONG_LONG_MIN, odd_max = LONG_LONG_MIN; + long long res = LONG_LONG_MIN; + for(int i = n - 1; i >= 0; i --){ + even_max = max(even_max, even[i]); + odd_max = max(odd_max, odd[i]); + if(i % 2 == 0) + res = max(res, even_max - (i - 1 >= 0 ? even[i - 1] : 0)); + else + res = max(res, odd_max - (i - 1 >= 0 ? odd[i - 1] : 0)); + } + return res; + } +}; + + +int main() { + + vector nums1 = {3, -1, 1, 2}; + cout << Solution().maximumAlternatingSubarraySum(nums1) << endl; + // 5 + + vector nums2 = {2,2,2,2,2}; + cout << Solution().maximumAlternatingSubarraySum(nums2) << endl; + // 2 + + vector nums3 = {1}; + cout << Solution().maximumAlternatingSubarraySum(nums3) << endl; + // 1 + + vector nums4 = {5, 100}; + cout << Solution().maximumAlternatingSubarraySum(nums4) << endl; + // 100 + + return 0; +} diff --git a/2001-2500/2037-Minimum-Number-of-Moves-to-Seat-Everyone/cpp-2037/CMakeLists.txt b/2001-2500/2037-Minimum-Number-of-Moves-to-Seat-Everyone/cpp-2037/CMakeLists.txt new file mode 100644 index 00000000..006b6fc4 --- /dev/null +++ b/2001-2500/2037-Minimum-Number-of-Moves-to-Seat-Everyone/cpp-2037/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_2037) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2037 main.cpp) diff --git a/2001-2500/2037-Minimum-Number-of-Moves-to-Seat-Everyone/cpp-2037/main.cpp b/2001-2500/2037-Minimum-Number-of-Moves-to-Seat-Everyone/cpp-2037/main.cpp new file mode 100644 index 00000000..89e75047 --- /dev/null +++ b/2001-2500/2037-Minimum-Number-of-Moves-to-Seat-Everyone/cpp-2037/main.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/minimum-number-of-moves-to-seat-everyone/ +/// Author : liuyubobobo +/// Time : 2021-10-17 + +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + int minMovesToSeat(vector& seats, vector& students) { + + int n = seats.size(); + sort(seats.begin(), seats.end()); + sort(students.begin(), students.end()); + + int res = 0; + for(int i = 0; i < n; i ++) + res += abs(seats[i] - students[i]); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2038-Remove-Colored-Pieces-if-Both-Neighbors-are-the-Same Color/cpp-2038/CMakeLists.txt b/2001-2500/2038-Remove-Colored-Pieces-if-Both-Neighbors-are-the-Same Color/cpp-2038/CMakeLists.txt new file mode 100644 index 00000000..f5479dc6 --- /dev/null +++ b/2001-2500/2038-Remove-Colored-Pieces-if-Both-Neighbors-are-the-Same Color/cpp-2038/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_2038) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2038 main.cpp) diff --git a/2001-2500/2038-Remove-Colored-Pieces-if-Both-Neighbors-are-the-Same Color/cpp-2038/main.cpp b/2001-2500/2038-Remove-Colored-Pieces-if-Both-Neighbors-are-the-Same Color/cpp-2038/main.cpp new file mode 100644 index 00000000..3862242a --- /dev/null +++ b/2001-2500/2038-Remove-Colored-Pieces-if-Both-Neighbors-are-the-Same Color/cpp-2038/main.cpp @@ -0,0 +1,36 @@ +/// Source : https://leetcode.com/problems/remove-colored-pieces-if-both-neighbors-are-the-same-color/ +/// Author : liuyubobobo +/// Time : 2021-10-17 + +#include + +using namespace std; + + +/// String Split +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + bool winnerOfGame(string colors) { + + int a = 0, b = 0; + for(int start = 0, i = 1; i <= colors.size(); i ++) + if(i == colors.size() || colors[i] != colors[start]){ + int len = i - start; + if(len >= 3){ + if(colors[start] == 'A') a += len - 2; + else b += len - 2; + } + start = i; + } + + return a >= b + 1; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2039-The-Time-When-the-Network-Becomes-Idle/cpp-2039/CMakeLists.txt b/2001-2500/2039-The-Time-When-the-Network-Becomes-Idle/cpp-2039/CMakeLists.txt new file mode 100644 index 00000000..4a501120 --- /dev/null +++ b/2001-2500/2039-The-Time-When-the-Network-Becomes-Idle/cpp-2039/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_2039) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2039 main.cpp) diff --git a/2001-2500/2039-The-Time-When-the-Network-Becomes-Idle/cpp-2039/main.cpp b/2001-2500/2039-The-Time-When-the-Network-Becomes-Idle/cpp-2039/main.cpp new file mode 100644 index 00000000..eed47dbe --- /dev/null +++ b/2001-2500/2039-The-Time-When-the-Network-Becomes-Idle/cpp-2039/main.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/the-time-when-the-network-becomes-idle/ +/// Author : liuyubobobo +/// Time : 2021-10-18 + +#include +#include +#include + +using namespace std; + + +/// BFS +/// Time Complexity: O(n + m) +/// Space Complexity: O(n + m) +class Solution { +public: + int networkBecomesIdle(vector>& edges, vector& patience) { + + int n = patience.size(); + + vector> g(n); + for(const vector& e: edges) + g[e[0]].push_back(e[1]), g[e[1]].push_back(e[0]); + + vector dis(n, -1); + queue q; + q.push(0); + dis[0] = 0; + while(!q.empty()){ + int u = q.front();q.pop(); + + for(int v: g[u]) + if(dis[v] == -1){ + dis[v] = dis[u] + 1; + q.push(v); + } + } + + int res = 0; + for(int i = 1; i < n; i ++){ + int d = 2 * dis[i]; + int num = (d - 1) / patience[i]; + res = max(res, patience[i] * num + d); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2040-Kth-Smallest-Product-of-Two-Sorted-Arrays/cpp-2040/CMakeLists.txt b/2001-2500/2040-Kth-Smallest-Product-of-Two-Sorted-Arrays/cpp-2040/CMakeLists.txt new file mode 100644 index 00000000..7dd01674 --- /dev/null +++ b/2001-2500/2040-Kth-Smallest-Product-of-Two-Sorted-Arrays/cpp-2040/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_2040) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2040 main.cpp) diff --git a/2001-2500/2040-Kth-Smallest-Product-of-Two-Sorted-Arrays/cpp-2040/main.cpp b/2001-2500/2040-Kth-Smallest-Product-of-Two-Sorted-Arrays/cpp-2040/main.cpp new file mode 100644 index 00000000..c454b9ca --- /dev/null +++ b/2001-2500/2040-Kth-Smallest-Product-of-Two-Sorted-Arrays/cpp-2040/main.cpp @@ -0,0 +1,115 @@ +/// Source : https://leetcode.com/problems/kth-smallest-product-of-two-sorted-arrays/ +/// Author : liuyubobobo +/// Time : 2021-10-18 + +#include +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + long long kthSmallestProduct(vector& nums1, vector& nums2, long long k) { + + vector neg1, zero1, pos1; + for(int e: nums1) { + if (e < 0) neg1.push_back(e); + else if (e == 0) zero1.push_back(e); + else pos1.push_back(e); + } + + vector neg2, zero2, pos2; + for(int e: nums2) + if(e < 0) neg2.push_back(e); + else if(e == 0) zero2.push_back(e); + else pos2.push_back(e); + + long long neg_cnt = (long long)neg1.size() * pos2.size() + (long long)neg2.size() * pos1.size(); + long long zero_cnt = (long long)zero1.size() * nums2.size() + (long long)zero2.size() * nums1.size() - (long long)zero1.size() * zero2.size(); + long long pos_cnt = (long long)neg1.size() * neg2.size() + (long long)pos1.size() * pos2.size(); + assert(neg_cnt + zero_cnt + pos_cnt == (long long)nums1.size() * nums2.size()); + + for(long long& e: neg1) e = -e; + for(long long& e: neg2) e = -e; + reverse(neg1.begin(), neg1.end()); + reverse(neg2.begin(), neg2.end()); + + if(k <= neg_cnt) + return - solve(neg1, pos2, neg2, pos1, neg_cnt + 1 - k); + else if(k <= neg_cnt + zero_cnt) + return 0; + + return solve(neg1, neg2, pos1, pos2, k - neg_cnt - zero_cnt); + } + +private: + long long solve(const vector& a1, const vector& b1, + const vector& a2, const vector& b2, long long k){ + + assert(k > 0 && k <= (long long)a1.size() * b1.size() + (long long)a2.size() * b2.size()); + + long long l = 1, r = 0; + if(!a1.empty() && !b1.empty()) r = max(r, a1.back() * b1.back()); + if(!a2.empty() && !b2.empty()) r = max(r, a2.back() * b2.back()); + assert(r); + + while(l < r){ + long long mid = (l + r) / 2; + if(count(a1, b1, a2, b2, mid) >= k) r = mid; + else l = mid + 1; + } + return l; + } + + long long count(const vector& a1, const vector& b1, + const vector& a2, const vector& b2, long long t){ + + long long res = 0; + + int r = b1.size() - 1; + for(long long e: a1){ + long long x = t / e; + while(r >= 0 && b1[r] > x) r --; + res += r + 1; + } + + r = b2.size() - 1; + for(long long e: a2){ + long long x = t / e; + while(r >= 0 && b2[r] > x) r --; + res += r + 1; + } + return res; + } +}; + + +int main() { + + vector nums11 = {2, 5}, nums12 = {3, 4}; + cout << Solution().kthSmallestProduct(nums11, nums12, 2) << endl; + // 8 + + vector nums21 = {-4, -2, 0, 3}, nums22 = {2, 4}; + cout << Solution().kthSmallestProduct(nums21, nums22, 6) << endl; + // 0 + + vector nums31 = {-2, -1, 0, 1, 2}, nums32 = {-3, -1, 2, 4, 5}; + cout << Solution().kthSmallestProduct(nums31, nums32, 3) << endl; + // -6 + + vector nums41 = {-9, -9, -8, -6, -1, 0, 5, 8, 10, 10}, nums42 = {0, 4, 9}; + cout << Solution().kthSmallestProduct(nums41, nums42, 19) << endl; + // 0 + + vector nums51 = {1, 9, 10, 10}, nums52 = {-6, -4, -4, -2, -2, 1, 1, 2, 9}; + cout << Solution().kthSmallestProduct(nums51, nums52, 22) << endl; + // 1 + + return 0; +} diff --git a/2001-2500/2042-Check-if-Numbers-Are-Ascending-in-a-Sentence/cpp-2042/CMakeLists.txt b/2001-2500/2042-Check-if-Numbers-Are-Ascending-in-a-Sentence/cpp-2042/CMakeLists.txt new file mode 100644 index 00000000..2ae8397c --- /dev/null +++ b/2001-2500/2042-Check-if-Numbers-Are-Ascending-in-a-Sentence/cpp-2042/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/2001-2500/2042-Check-if-Numbers-Are-Ascending-in-a-Sentence/cpp-2042/main.cpp b/2001-2500/2042-Check-if-Numbers-Are-Ascending-in-a-Sentence/cpp-2042/main.cpp new file mode 100644 index 00000000..59fbd6ec --- /dev/null +++ b/2001-2500/2042-Check-if-Numbers-Are-Ascending-in-a-Sentence/cpp-2042/main.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/check-if-numbers-are-ascending-in-a-sentence/ +/// Author : liuyubobobo +/// Time : 2021-10-16 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(|s|) +/// Space Complexity: O(|s|) +class Solution { +public: + bool areNumbersAscending(string s) { + + vector nums; + for(int i = 0; i < s.size(); i ++) + if(isdigit(s[i])){ + int j = i; + for(; j < s.size(); j ++) + if(s[j] == ' ') break; + nums.push_back(atoi(s.substr(i, j - i).c_str())); + i = j; + } + +// for(int e: nums) cout << e << ' '; cout << endl; + + for(int i = 1; i < nums.size(); i ++) + if(nums[i] <= nums[i - 1]) return false; + return true; + } +}; + + +int main() { + + cout << Solution().areNumbersAscending("1 box has 3 blue 4 red 6 green and 12 yellow marbles") << endl; + // 1 + + cout << Solution().areNumbersAscending("hello world 5 x 5") << endl; + // 0 + + cout << Solution().areNumbersAscending("sunset is at 7 51 pm overnight lows will be in the low 50 and 60 s") << endl; + // 0 + + cout << Solution().areNumbersAscending("4 5 11 26") << endl; + // 1 + + return 0; +} diff --git a/2001-2500/2043-Simple-Bank-System/cpp-2043/CMakeLists.txt b/2001-2500/2043-Simple-Bank-System/cpp-2043/CMakeLists.txt new file mode 100644 index 00000000..3f98647f --- /dev/null +++ b/2001-2500/2043-Simple-Bank-System/cpp-2043/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/2001-2500/2043-Simple-Bank-System/cpp-2043/main.cpp b/2001-2500/2043-Simple-Bank-System/cpp-2043/main.cpp new file mode 100644 index 00000000..1656a800 --- /dev/null +++ b/2001-2500/2043-Simple-Bank-System/cpp-2043/main.cpp @@ -0,0 +1,56 @@ +/// Source : https://leetcode.com/problems/simple-bank-system/ +/// Author : liuyubobobo +/// Time : 2021-10-17 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(1) for all ops +/// Space Complexity: O(n) +class Bank { + +private: + int n; + vector balance; + +public: + Bank(vector& balance) : balance(balance), n(balance.size()) {} + + bool transfer(int account1, int account2, long long money) { + + account1 --; + account2 --; + if(account1 < 0 || account1 >= n) return false; + if(account2 < 0 || account2 >= n) return false; + if(balance[account1] < money) return false; + + balance[account1] -= money; + balance[account2] += money; + return true; + } + + bool deposit(int account, long long money) { + account --; + if(account < 0 || account >= n) return false; + balance[account] += money; + return true; + } + + bool withdraw(int account, long long money) { + account --; + if(account < 0 || account >= n) return false; + if(balance[account] < money) return false; + balance[account] -= money; + return true; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2044-Count-Number-of-Maximum-Bitwise-OR-Subsets/cpp-2044/CMakeLists.txt b/2001-2500/2044-Count-Number-of-Maximum-Bitwise-OR-Subsets/cpp-2044/CMakeLists.txt new file mode 100644 index 00000000..cad75f71 --- /dev/null +++ b/2001-2500/2044-Count-Number-of-Maximum-Bitwise-OR-Subsets/cpp-2044/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/2001-2500/2044-Count-Number-of-Maximum-Bitwise-OR-Subsets/cpp-2044/main.cpp b/2001-2500/2044-Count-Number-of-Maximum-Bitwise-OR-Subsets/cpp-2044/main.cpp new file mode 100644 index 00000000..0bca6d25 --- /dev/null +++ b/2001-2500/2044-Count-Number-of-Maximum-Bitwise-OR-Subsets/cpp-2044/main.cpp @@ -0,0 +1,48 @@ +/// Source : https://leetcode.com/problems/count-number-of-maximum-bitwise-or-subsets/ +/// Author : liuyubobobo +/// Time : 2021-10-16 + +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(2^n) +/// Space Complexity: O(2^n) +class Solution { +public: + int countMaxOrSubsets(vector& nums) { + + int t = 0; + for(int e: nums) t |= e; + + int n = nums.size(), res = 0; + vector dp(1 << n, 0); + for(int state = 1; state < (1 << n); state ++){ + int p = __builtin_ffs(state) - 1; + dp[state] = dp[state - (1 << p)] | nums[p]; + res += dp[state] == t; + } + return res; + } +}; + + +int main() { + + vector nums1 = {3, 1}; + cout << Solution().countMaxOrSubsets(nums1) << endl; + // 2 + + vector nums2 = {2, 2, 2}; + cout << Solution().countMaxOrSubsets(nums2) << endl; + // 7 + + vector nums3 = {3, 2, 1, 5}; + cout << Solution().countMaxOrSubsets(nums3) << endl; + // 6 + + return 0; +} diff --git a/2001-2500/2045-Second-Minimum-Time-to-Reach-Destination/cpp-2045/CMakeLists.txt b/2001-2500/2045-Second-Minimum-Time-to-Reach-Destination/cpp-2045/CMakeLists.txt new file mode 100644 index 00000000..2a7f1f76 --- /dev/null +++ b/2001-2500/2045-Second-Minimum-Time-to-Reach-Destination/cpp-2045/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main2.cpp) diff --git a/2001-2500/2045-Second-Minimum-Time-to-Reach-Destination/cpp-2045/main.cpp b/2001-2500/2045-Second-Minimum-Time-to-Reach-Destination/cpp-2045/main.cpp new file mode 100644 index 00000000..b7efb27a --- /dev/null +++ b/2001-2500/2045-Second-Minimum-Time-to-Reach-Destination/cpp-2045/main.cpp @@ -0,0 +1,87 @@ +#include +#include +#include +#include + +using namespace std; + + +class Solution { +public: + int secondMinimum(int n, vector>& edges, int time, int change) { + + vector> g(n); + for(const vector& e: edges){ + int u = e[0] - 1, v = e[1] - 1; + g[u].insert(v), g[v].insert(u); + } + + int min_t = dij(n, g, change, time); +// cout << "min_t = " << min_t << endl; + + int res = min_t + (min_t % (2 * change) < change ? 0 : (2 * change - min_t % (2 * change))) + time; + res += (res % (2 * change) < change ? 0 : (2 * change - res % (2 * change))) + time; +// cout << "init res = " << res << endl; + + for(const vector& e: edges){ + int u = e[0] - 1, v = e[1] - 1; + g[u].erase(v), g[v].erase(u); + int tres = dij(n, g, change, time); + if(tres != min_t){ +// cout << tres << endl; + assert(tres > min_t); + res = min(res, tres); + } + g[u].insert(v), g[v].insert(u); + } + return res; + } + +private: + int dij(int n, const vector>& g, int change, int time){ + + vector dis(n, INT_MAX); + vector visited(n, false); + // t, u + priority_queue, vector>, greater>> pq; + + dis[0] = 0; + pq.push({0, 0}); + while(!pq.empty()){ + int d = pq.top().first, u = pq.top().second; + pq.pop(); + + if(visited[u]) continue; + visited[u] = true; + + for(int v: g[u]) + if(!visited[v]){ + int nextd = d + (d % (2 * change) < change ? 0 : (2 * change - d % (2 * change))) + time; + if(nextd < dis[v]){ + dis[v] = nextd; + pq.push({nextd, v}); + } + } + } + return dis.back(); + } +}; + +int main() { + + vector> edges1 = { + {1, 2}, {1, 3}, {1, 4}, {3, 4}, {4, 5} + }; + cout << Solution().secondMinimum(5, edges1, 3, 5) << endl; + // min_t : 6 + // 13 + + vector> edges2 = { + {1, 2} + }; + cout << Solution().secondMinimum(2, edges2, 3, 2) << endl; + // min_t : 3 + // 11 + + return 0; +} diff --git a/2001-2500/2045-Second-Minimum-Time-to-Reach-Destination/cpp-2045/main2.cpp b/2001-2500/2045-Second-Minimum-Time-to-Reach-Destination/cpp-2045/main2.cpp new file mode 100644 index 00000000..e74db287 --- /dev/null +++ b/2001-2500/2045-Second-Minimum-Time-to-Reach-Destination/cpp-2045/main2.cpp @@ -0,0 +1,73 @@ +/// Source : https://leetcode.com/problems/second-minimum-time-to-reach-destination/ +/// Author : liuyubobobo +/// Time : 2021-10-17 + +#include +#include +#include +#include + +using namespace std; + + +/// Dijkstra Modified +/// Time Complexity: O((n + m) * logm) +/// Space Complexity: O(n + m) +class Solution { +public: + int secondMinimum(int n, vector>& edges, int time, int change) { + + vector> g(n); + for(const vector& e: edges){ + int u = e[0] - 1, v = e[1] - 1; + g[u].push_back(v), g[v].push_back(u); + } + + vector> dis(n, vector(2, INT_MAX)); + vector visited(n, false); + // t, u + priority_queue, vector>, greater>> pq; + + dis[0][0] = 0; + pq.push({0, 0}); + while(!pq.empty()){ + int d = pq.top().first, u = pq.top().second; + pq.pop(); + + if(d > dis[u][1]) continue; + + for(int v: g[u]) + if(!visited[v]){ + int nextd = d + (d % (2 * change) < change ? 0 : (2 * change - d % (2 * change))) + time; + if(nextd < dis[v][1] && nextd != dis[v][0]){ + dis[v][1] = nextd; + pq.push({nextd, v}); + if(dis[v][0] > dis[v][1]) swap(dis[v][0], dis[v][1]); + } + } + } + +// cout << dis[n - 1][0] << ' ' << dis[n - 1][1] << '\n'; + return dis[n - 1][1]; + } +}; + + +int main() { + + vector> edges1 = { + {1, 2}, {1, 3}, {1, 4}, {3, 4}, {4, 5} + }; + cout << Solution().secondMinimum(5, edges1, 3, 5) << endl; + // min_t : 6 + // 13 + + vector> edges2 = { + {1, 2} + }; + cout << Solution().secondMinimum(2, edges2, 3, 2) << endl; + // min_t : 3 + // 11 + + return 0; +} diff --git a/2001-2500/2046-Sort-Linked-List-Already-Sorted-Using-Absolute-Values/cpp-2046/CMakeLists.txt b/2001-2500/2046-Sort-Linked-List-Already-Sorted-Using-Absolute-Values/cpp-2046/CMakeLists.txt new file mode 100644 index 00000000..3745a097 --- /dev/null +++ b/2001-2500/2046-Sort-Linked-List-Already-Sorted-Using-Absolute-Values/cpp-2046/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_2046) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2046 main.cpp) diff --git a/2001-2500/2046-Sort-Linked-List-Already-Sorted-Using-Absolute-Values/cpp-2046/main.cpp b/2001-2500/2046-Sort-Linked-List-Already-Sorted-Using-Absolute-Values/cpp-2046/main.cpp new file mode 100644 index 00000000..32424b8c --- /dev/null +++ b/2001-2500/2046-Sort-Linked-List-Already-Sorted-Using-Absolute-Values/cpp-2046/main.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/sort-linked-list-already-sorted-using-absolute-values/ +/// Author : liuyubobobo +/// Time : 2021-10-20 + +#include + +using namespace std; + + +/// Linked List +/// Time Complexity: O(n) +/// Space Complexity: O(1) + +/// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode() : val(0), next(nullptr) {} + ListNode(int x) : val(x), next(nullptr) {} + ListNode(int x, ListNode *next) : val(x), next(next) {} +}; + +class Solution { +public: + ListNode* sortLinkedList(ListNode* head) { + + ListNode* neg_head = nullptr, *neg_tail = nullptr; + + ListNode* dummy = new ListNode(0, head); + ListNode* cur = dummy; + while(cur->next){ + if(cur->next->val < 0){ + ListNode* neg_node = cur->next; + cur->next = neg_node->next; + neg_node->next = neg_head; + neg_head = neg_node; + if(neg_head->next == nullptr) neg_tail = neg_head; + } + else cur = cur->next; + } + + if(!neg_head) return dummy->next; + + neg_tail->next = dummy->next; + dummy->next = neg_head; + return dummy->next; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2047-Number-of-Valid-Words-in-a-Sentence/cpp-2047/CMakeLists.txt b/2001-2500/2047-Number-of-Valid-Words-in-a-Sentence/cpp-2047/CMakeLists.txt new file mode 100644 index 00000000..2ae8397c --- /dev/null +++ b/2001-2500/2047-Number-of-Valid-Words-in-a-Sentence/cpp-2047/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/2001-2500/2047-Number-of-Valid-Words-in-a-Sentence/cpp-2047/main.cpp b/2001-2500/2047-Number-of-Valid-Words-in-a-Sentence/cpp-2047/main.cpp new file mode 100644 index 00000000..85e817ae --- /dev/null +++ b/2001-2500/2047-Number-of-Valid-Words-in-a-Sentence/cpp-2047/main.cpp @@ -0,0 +1,80 @@ +/// Source : https://leetcode.com/problems/number-of-valid-words-in-a-sentence/ +/// Author : liuyubobobo +/// Time : 2021-10-23 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int countValidWords(string s) { + + int res = 0; + for(int start = next_non_space(s, 0), i = start + 1; i <= s.size(); i ++) + if(i == s.size() || s[i] == ' '){ + string word = s.substr(start, i - start); + res += check(word); + + start = next_non_space(s, i); + i = start; + } + return res; + } + +private: + bool check(const string& s){ + + for(char c: s) if(isdigit(c)) return false; + + int hyphen = -1; + for(int i = 0; i < s.size(); i ++) + if(s[i] == '-'){ + if(hyphen != -1) return false; + hyphen = i; + } + if(hyphen != -1) { + if (hyphen == 0 || hyphen == s.size() - 1) return false; + if (!islower(s[hyphen - 1])) return false; + if (!islower(s[hyphen + 1])) return false; + } + + int dot = -1; + for(int i = 0; i < s.size(); i ++) + if(s[i] == '!' || s[i] == '.' || s[i] == ','){ + if(dot != -1) return false; + dot = i; + } + return dot == -1 || dot == s.size() - 1; + } + + int next_non_space(const string& s, int start){ + + for(int i = start; i < s.size(); i ++) + if(s[i] != ' ') return i; + return s.size(); + } +}; + + +int main() { + + cout << Solution().countValidWords("cat and dog") << endl; + // 3 + + cout << Solution().countValidWords("!this 1-s b8d!") << endl; + // 0 + + cout << Solution().countValidWords("alice and bob are playing stone-game10") << endl; + // 5 + + cout << Solution().countValidWords("he bought 2 pencils, 3 erasers, and 1 pencil-sharpener.") << endl; + // 6 + + return 0; +} diff --git a/2001-2500/2048-Next-Greater-Numerically-Balanced-Number/cpp-2048/CMakeLists.txt b/2001-2500/2048-Next-Greater-Numerically-Balanced-Number/cpp-2048/CMakeLists.txt new file mode 100644 index 00000000..3f98647f --- /dev/null +++ b/2001-2500/2048-Next-Greater-Numerically-Balanced-Number/cpp-2048/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/2001-2500/2048-Next-Greater-Numerically-Balanced-Number/cpp-2048/main.cpp b/2001-2500/2048-Next-Greater-Numerically-Balanced-Number/cpp-2048/main.cpp new file mode 100644 index 00000000..28ce5dd0 --- /dev/null +++ b/2001-2500/2048-Next-Greater-Numerically-Balanced-Number/cpp-2048/main.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/next-greater-numerically-balanced-number/ +/// Author : liuyubobobo +/// Time : 2021-10-23 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + int nextBeautifulNumber(int n) { + + for(int x = n + 1;;x ++) + if(ok(x)) return x; + assert(false); + return -1; + } + +private: + bool ok(int x){ + + vector f(10, 0); + while(x) f[x % 10] ++, x /= 10; + + if(f[0]) return false; + for(int i = 1; i < 10; i ++) + if(f[i] && f[i] != i) return false; + return true; + } +}; + + +int main() { + + cout << Solution().nextBeautifulNumber(1) << endl; + // 22 + + cout << Solution().nextBeautifulNumber(1000) << endl; + // 1333 + + cout << Solution().nextBeautifulNumber(3000) << endl; + // 3133 + + return 0; +} diff --git a/2001-2500/2049-Count-Nodes-With-the-Highest-Score/cpp-2049/CMakeLists.txt b/2001-2500/2049-Count-Nodes-With-the-Highest-Score/cpp-2049/CMakeLists.txt new file mode 100644 index 00000000..cad75f71 --- /dev/null +++ b/2001-2500/2049-Count-Nodes-With-the-Highest-Score/cpp-2049/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/2001-2500/2049-Count-Nodes-With-the-Highest-Score/cpp-2049/main.cpp b/2001-2500/2049-Count-Nodes-With-the-Highest-Score/cpp-2049/main.cpp new file mode 100644 index 00000000..ed28175e --- /dev/null +++ b/2001-2500/2049-Count-Nodes-With-the-Highest-Score/cpp-2049/main.cpp @@ -0,0 +1,67 @@ +/// Source : https://leetcode.com/problems/count-nodes-with-the-highest-score/ +/// Author : liuyubobobo +/// Time : 2021-10-23 + +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int countHighestScoreNodes(vector& parents) { + + int n = parents.size(); + vector> g(n); + for(int u = 1; u < n; u ++){ + int v = parents[u]; + g[v].push_back(u); + } + + vector sz(n, 0); + dfs_sz(g, 0, sz); + + long long max_score = -1; + int max_score_f = 0; + dfs(n, g, 0, sz, max_score, max_score_f); + return max_score_f; + } + +private: + void dfs(int n, const vector>& g, int u, const vector& sz, + long long& max_score, int& max_score_f){ + + long long score = 1; + int count = 1; + for(int v: g[u]){ + score *= sz[v]; + count += sz[v]; + } + if(n - count) score *= (n - count); + + if(score > max_score) max_score = score, max_score_f = 1; + else if(score == max_score) max_score_f ++; + + for(int v: g[u]) + dfs(n, g, v, sz, max_score, max_score_f); + } + + void dfs_sz(const vector>& g, int u, vector& sz){ + + sz[u] = 1; + for(int v: g[u]){ + dfs_sz(g, v, sz); + sz[u] += sz[v]; + } + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2050-Parallel-Courses-III/cpp-2050/CMakeLists.txt b/2001-2500/2050-Parallel-Courses-III/cpp-2050/CMakeLists.txt new file mode 100644 index 00000000..a0d16fe6 --- /dev/null +++ b/2001-2500/2050-Parallel-Courses-III/cpp-2050/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) diff --git a/2001-2500/2050-Parallel-Courses-III/cpp-2050/main.cpp b/2001-2500/2050-Parallel-Courses-III/cpp-2050/main.cpp new file mode 100644 index 00000000..ca655e7d --- /dev/null +++ b/2001-2500/2050-Parallel-Courses-III/cpp-2050/main.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/parallel-courses-iii/ +/// Author : liuyubobobo +/// Time : 2021-10-23 + +#include +#include +#include + +using namespace std; + + +/// BFS +/// Time Complexity: O((n + m) * logn) +/// Space Complexity: O(n + m) +class Solution { +public: + int minimumTime(int n, vector>& relations, vector& time) { + + vector> g(n); + vector in_degrees(n, 0); + for(const vector& e: relations){ + int u = e[0] - 1, v = e[1] - 1; + g[u].push_back(v); + in_degrees[v] ++; + } + + priority_queue, vector>, greater>> pq; // complete time, index + for(int u = 0; u < n; u ++) + if(in_degrees[u] == 0) pq.push({time[u], u}); + + int res = 0; + while(!pq.empty()){ + int complete_time = pq.top().first, u = pq.top().second; + pq.pop(); + + res = max(res, complete_time); + + for(int v: g[u]){ + in_degrees[v] --; + if(in_degrees[v] == 0) + pq.push({complete_time + time[v], v}); + } + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2052-Minimum-Cost-to-Separate-Sentence-Into-Rows/cpp-2052/CMakeLists.txt b/2001-2500/2052-Minimum-Cost-to-Separate-Sentence-Into-Rows/cpp-2052/CMakeLists.txt new file mode 100644 index 00000000..3c25da9b --- /dev/null +++ b/2001-2500/2052-Minimum-Cost-to-Separate-Sentence-Into-Rows/cpp-2052/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_2052) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2052 main.cpp) diff --git a/2001-2500/2052-Minimum-Cost-to-Separate-Sentence-Into-Rows/cpp-2052/main.cpp b/2001-2500/2052-Minimum-Cost-to-Separate-Sentence-Into-Rows/cpp-2052/main.cpp new file mode 100644 index 00000000..2994ece6 --- /dev/null +++ b/2001-2500/2052-Minimum-Cost-to-Separate-Sentence-Into-Rows/cpp-2052/main.cpp @@ -0,0 +1,68 @@ +/// Source : https://leetcode.com/problems/minimum-cost-to-separate-sentence-into-rows/ +/// Author : liuyubobobo +/// Time : 2021-10-29 + +#include +#include + +using namespace std; + + +/// Memoization +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { +public: + int minimumCost(string sentence, int k) { + + vector v; + for(int start = 0, i = 1; i <= sentence.size(); i ++){ + if(i == sentence.size() || sentence[i] == ' '){ + v.push_back(i - start); + start = i + 1; + i = start; + } + } + + int last = v.size() - 1; + int cur = v.back(); + for(int i = (int)v.size() - 2; i >= 0; i --) + if(cur + 1 + v[i] <= k){ + last = i; + cur += 1 + v[i]; + } + else break; + + vector dp(v.size(), -1); + return dfs(v, 0, k, last, dp); + } + +private: + int dfs(const vector& v, int index, int k, int last, vector& dp){ + + if(index >= last) return 0; + if(dp[index] != -1) return dp[index]; + + int cur = v[index]; + int res = (cur - k) * (cur - k) + dfs(v, index + 1, k, last, dp); + for(int i = index + 1; i < v.size(); i ++) + if(cur + 1 + v[i] <= k){ + if(i + 1 == v.size()) return 0; + cur += (1 + v[i]); + res = min(res, (cur - k) * (cur - k) + dfs(v, i + 1, k, last, dp)); + } + else break; + return dp[index] = res; + } +}; + + +int main() { + + string s1 = "a"; + while(s1.size() + 2 < 5000) s1 += " a"; + cout << Solution().minimumCost(s1, 5000) << endl; + // + + return 0; +} diff --git a/2001-2500/2053-Kth-Distinct-String-in-an-Array/cpp-2053/CMakeLists.txt b/2001-2500/2053-Kth-Distinct-String-in-an-Array/cpp-2053/CMakeLists.txt new file mode 100644 index 00000000..2ae8397c --- /dev/null +++ b/2001-2500/2053-Kth-Distinct-String-in-an-Array/cpp-2053/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/2001-2500/2053-Kth-Distinct-String-in-an-Array/cpp-2053/main.cpp b/2001-2500/2053-Kth-Distinct-String-in-an-Array/cpp-2053/main.cpp new file mode 100644 index 00000000..48db1526 --- /dev/null +++ b/2001-2500/2053-Kth-Distinct-String-in-an-Array/cpp-2053/main.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/kth-distinct-string-in-an-array/ +/// Author : liuyubobobo +/// Time : 2021-10-30 + +#include +#include +#include + +using namespace std; + + +/// Using Map +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + string kthDistinct(vector& arr, int k) { + + map f; + for(string& s: arr) f[s] ++; + + for(string& s: arr){ + if(f[s] == 1) k--; + if(!k) return s; + } + return ""; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2054-Two-Best-Non-Overlapping-Events/cpp-2054/CMakeLists.txt b/2001-2500/2054-Two-Best-Non-Overlapping-Events/cpp-2054/CMakeLists.txt new file mode 100644 index 00000000..3f98647f --- /dev/null +++ b/2001-2500/2054-Two-Best-Non-Overlapping-Events/cpp-2054/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/2001-2500/2054-Two-Best-Non-Overlapping-Events/cpp-2054/main.cpp b/2001-2500/2054-Two-Best-Non-Overlapping-Events/cpp-2054/main.cpp new file mode 100644 index 00000000..adb77ff1 --- /dev/null +++ b/2001-2500/2054-Two-Best-Non-Overlapping-Events/cpp-2054/main.cpp @@ -0,0 +1,44 @@ +/// Source : https://leetcode.com/problems/two-best-non-overlapping-events/ +/// Author : liuyubobobo +/// Time : 2021-10-30 + +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + int maxTwoEvents(vector>& events) { + + sort(events.begin(), events.end()); + + int n = events.size(); + vector max_value(n, events.back()[2]); + for(int i = n - 2; i >= 0; i --) + max_value[i] = max(events[i][2], max_value[i + 1]); + + int res = 0; + for(int i = 0; i < n; i ++){ + res = max(res, events[i][2]); + + vector t = {events[i][1] + 1, INT_MIN, INT_MIN}; + vector>::iterator iter = lower_bound(events.begin(), events.end(), t); + if(iter != events.end()){ + int index = iter - events.begin(); + res = max(res, events[i][2] + max_value[index]); + } + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2055-Plates-Between-Candles/cpp-2055/CMakeLists.txt b/2001-2500/2055-Plates-Between-Candles/cpp-2055/CMakeLists.txt new file mode 100644 index 00000000..0ffd6e97 --- /dev/null +++ b/2001-2500/2055-Plates-Between-Candles/cpp-2055/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main2.cpp) diff --git a/2001-2500/2055-Plates-Between-Candles/cpp-2055/main.cpp b/2001-2500/2055-Plates-Between-Candles/cpp-2055/main.cpp new file mode 100644 index 00000000..cb70b410 --- /dev/null +++ b/2001-2500/2055-Plates-Between-Candles/cpp-2055/main.cpp @@ -0,0 +1,106 @@ +/// Source : https://leetcode.com/problems/plates-between-candles/ +/// Author : liuyubobobo +/// Time : 2021-10-30 + +#include +#include + +using namespace std; + + +/// Using BIT +/// Time Complexity: O(nlogn + qlogn) +/// Space Complexity: O(n) +template +class BIT{ + +private: + int n; + vector data; + vector tree; + +public: + BIT(const vector& arr) : n(arr.size()), data(arr.begin(), arr.end()), tree(n + 1){ + + for(int i = 0; i < n; i ++) + tree[i + 1]= data[i]; + + for(int i = 1; i <= n; i ++){ + int parent = i + (i & -i); + if(parent <= n) tree[parent] += tree[i]; + } + } + + void add(int index, T v){ + assert(0 <= index && index < n); + + data[index] += v; + + index ++; + for(;index <= n; index += (index & -index)) + tree[index] += v; + } + + T query(int l, int r){ + assert(0 <= l && l < n); + assert(0 <= r && r < n); + assert(l <= r); + return prefix_sum(r + 1) - prefix_sum(l); + } + + void set(int index, T v){ + assert(0 <= index && index < n); + add(index, v - data[index]); + } + +private: + // r is 1-based + T prefix_sum(int r){ + + T res = 0; + for(; r; r -= (r & -r)) + res += tree[r]; + return res; + } +}; + +class Solution { +public: + vector platesBetweenCandles(string s, vector>& queries) { + + int n = s.size(); + + vector left(n, -1); + int cur = -1; + for(int i = 0; i < n; i ++){ + if(s[i] == '|') cur = i; + left[i] = cur; + } + + vector right(n, n); + cur = n; + for(int i = n - 1; i >= 0; i --){ + if(s[i] == '|') cur = i; + right[i] = cur; + } + + vector data(n, 0); + for(int i = 0; i < n; i ++) + if(s[i] == '*') data[i] = 1; + BIT tree(data); + + vector res(queries.size(), 0); + for(int i = 0; i < queries.size(); i ++){ + int ql = queries[i][0], qr = queries[i][1]; + int l = right[ql], r = left[qr]; + if(l <= r) res[i] = tree.query(l, r); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2055-Plates-Between-Candles/cpp-2055/main2.cpp b/2001-2500/2055-Plates-Between-Candles/cpp-2055/main2.cpp new file mode 100644 index 00000000..0253b805 --- /dev/null +++ b/2001-2500/2055-Plates-Between-Candles/cpp-2055/main2.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/plates-between-candles/ +/// Author : liuyubobobo +/// Time : 2021-10-30 + +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(nlogn + qlogn) +/// Space Complexity: O(n) +class Solution { +public: + vector platesBetweenCandles(string s, vector>& queries) { + + int n = s.size(); + + vector bars; + for(int i = 0; i < n; i ++) + if(s[i] == '|') bars.push_back(i); + + vector presum(n + 1, 0); + for(int i = 0; i < n; i ++) + presum[i + 1] = presum[i] + (s[i] == '*'); + + vector res(queries.size(), 0); + vector::iterator iter; + for(int i = 0; i < queries.size(); i ++){ + int ql = queries[i][0], qr = queries[i][1], l, r; + + iter = lower_bound(bars.begin(), bars.end(), ql); + if(iter == bars.end()) continue; + l = *iter; + + iter = lower_bound(bars.begin(), bars.end(), qr); + if(iter == bars.begin() && *iter > qr) continue; + if(iter == bars.end() || *iter > qr) iter --; + r = *iter; + + if(l <= r) res[i] = presum[r + 1] - presum[l]; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2056-Number-of-Valid-Move-Combinations-On-Chessboard/cpp-2056/CMakeLists.txt b/2001-2500/2056-Number-of-Valid-Move-Combinations-On-Chessboard/cpp-2056/CMakeLists.txt new file mode 100644 index 00000000..a0d16fe6 --- /dev/null +++ b/2001-2500/2056-Number-of-Valid-Move-Combinations-On-Chessboard/cpp-2056/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) diff --git a/2001-2500/2056-Number-of-Valid-Move-Combinations-On-Chessboard/cpp-2056/main.cpp b/2001-2500/2056-Number-of-Valid-Move-Combinations-On-Chessboard/cpp-2056/main.cpp new file mode 100644 index 00000000..a8719cd7 --- /dev/null +++ b/2001-2500/2056-Number-of-Valid-Move-Combinations-On-Chessboard/cpp-2056/main.cpp @@ -0,0 +1,155 @@ +/// Source : https://leetcode.com/problems/number-of-valid-move-combinations-on-chessboard/ +/// Author : liuyubobobo +/// Time : 2021-11-03 + +#include +#include +#include + +using namespace std; + + +/// Simulation +/// Time Compelxity: O(9^n * 7*n * n) +/// Space Complexity: O(n) +class Solution { + +private: + vector>> dirs; + +public: + int countCombinations(vector& pieces, vector>& positions) { + + dirs.assign(3, vector>()); + + // rook + dirs[0] = {{0, 0}, {1, 0}, {-1, 0}, {0, 1}, {0, -1}}; + // queen + dirs[1] = {{0, 0}, {1, 0}, {-1, 0}, {0, 1}, {0, -1}, + {1, 1}, {1, -1}, {-1, 1}, {-1, -1}}; + // bishop + dirs[2] = {{0, 0}, {1, 1}, {1, -1}, {-1, 1}, {-1, -1}}; + + int n = pieces.size(); + vector p(n, 0); + vector> pos(n); + for(int i = 0; i < n; i ++){ + pos[i].first = positions[i][0] - 1; + pos[i].second = positions[i][1] - 1; + if(pieces[i] == "queen") p[i] = 1; + if(pieces[i] == "bishop") p[i] = 2; + } + + vector d(n), s(n); + return dfs_directions(n, p, pos, d, s, 0); + } + +private: + int dfs_directions(int n, const vector& pieces, const vector>& pos, + vector& d, vector& s, int index){ + + if(index == n) + return dfs_steps(n, pieces, pos, d, s, 0); + + int res = 0, L = dirs[pieces[index]].size(); + for(int i = 0; i < L; i ++){ + d[index] = i; + res += dfs_directions(n, pieces, pos, d, s, index + 1); + } + return res; + } + + int dfs_steps(int n, const vector& pieces, const vector>& pos, + const vector& d, vector&s, int index){ + + if(index == n){ + vector> cur = pos; + vector left = s; + return dfs_check(n, cur, pieces, d, left); + } + + int res = 0; + if(d[index] == 0){ + s[index] = 0; + res += dfs_steps(n, pieces, pos, d, s, index + 1); + } + else{ + int dx = dirs[pieces[index]][d[index]].first, dy = dirs[pieces[index]][d[index]].second; + int cx = pos[index].first, cy = pos[index].second; + for(int i = 1; i < 8; i ++){ + if(in_area(cx += dx, cy += dy)){ + s[index] = i; + res += dfs_steps(n, pieces, pos, d, s, index + 1); + } + else break; + } + } + return res; + } + + bool dfs_check(int n, vector>& pos, const vector& pieces, + const vector& d, vector& left){ + + bool all_zero = true; + for(int i = 0; i < n; i ++) + if(left[i]){ + pos[i].first += dirs[pieces[i]][d[i]].first; + pos[i].second += dirs[pieces[i]][d[i]].second; + all_zero = false; + left[i] --; + } + + if(all_zero) return true; + + for(int i = 0; i < n; i ++) + for(int j = i + 1; j < n; j ++) + if(pos[i] == pos[j]) return false; + + return dfs_check(n, pos, pieces, d, left); + } + + bool in_area(int x, int y){ + return x >= 0 && x < 8 && y >= 0 && y < 8; + } +}; + + +int main() { + + vector pieces1 = {"rook"}; + vector> pos1 = {{1, 1}}; + cout << Solution().countCombinations(pieces1, pos1) << endl; + // 15 + + vector pieces2 = {"queen"}; + vector> pos2 = {{1, 1}}; + cout << Solution().countCombinations(pieces2, pos2) << endl; + // 22 + + vector pieces3 = {"bishop"}; + vector> pos3 = {{4, 3}}; + cout << Solution().countCombinations(pieces3, pos3) << endl; + // 12 + + vector pieces4 = {"rook", "rook"}; + vector> pos4 = {{1, 1}, {8, 8}}; + cout << Solution().countCombinations(pieces4, pos4) << endl; + // 223 + + vector pieces5 = {"queen", "bishop"}; + vector> pos5 = {{5, 7}, {3, 4}}; + cout << Solution().countCombinations(pieces5, pos5) << endl; + // 281 + + vector pieces6 = {"rook", "queen", "rook", "rook"}; + vector> pos6 = {{3, 8}, {6, 8}, {5, 3}, {2, 3}}; + cout << Solution().countCombinations(pieces6, pos6) << endl; + // 55717 + + vector pieces7 = {"bishop", "queen", "bishop", "bishop"}; + vector> pos7 = {{3, 7}, {7, 3}, {2, 4}, {4, 1}}; + cout << Solution().countCombinations(pieces7, pos7) << endl; + // 15126 + + return 0; +} diff --git a/2001-2500/2057-Smallest-Index-With-Equal-Value/cpp-2057/CMakeLists.txt b/2001-2500/2057-Smallest-Index-With-Equal-Value/cpp-2057/CMakeLists.txt new file mode 100644 index 00000000..2ae8397c --- /dev/null +++ b/2001-2500/2057-Smallest-Index-With-Equal-Value/cpp-2057/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/2001-2500/2057-Smallest-Index-With-Equal-Value/cpp-2057/main.cpp b/2001-2500/2057-Smallest-Index-With-Equal-Value/cpp-2057/main.cpp new file mode 100644 index 00000000..1fd2bcbb --- /dev/null +++ b/2001-2500/2057-Smallest-Index-With-Equal-Value/cpp-2057/main.cpp @@ -0,0 +1,28 @@ +/// Source : https://leetcode.com/problems/smallest-index-with-equal-value/ +/// Author : liuyubobobo +/// Time : 2021-10-30 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int smallestEqual(vector& nums) { + + for(int i = 0; i < nums.size(); i ++) + if(i % 10 == nums[i]) return i; + return -1; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2058-Find-the-Minimum-and-Maximum-Number-of-Nodes-Between-Critical-Points/cpp-2058/CMakeLists.txt b/2001-2500/2058-Find-the-Minimum-and-Maximum-Number-of-Nodes-Between-Critical-Points/cpp-2058/CMakeLists.txt new file mode 100644 index 00000000..084dd354 --- /dev/null +++ b/2001-2500/2058-Find-the-Minimum-and-Maximum-Number-of-Nodes-Between-Critical-Points/cpp-2058/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main2.cpp) diff --git a/2001-2500/2058-Find-the-Minimum-and-Maximum-Number-of-Nodes-Between-Critical-Points/cpp-2058/main.cpp b/2001-2500/2058-Find-the-Minimum-and-Maximum-Number-of-Nodes-Between-Critical-Points/cpp-2058/main.cpp new file mode 100644 index 00000000..a7352994 --- /dev/null +++ b/2001-2500/2058-Find-the-Minimum-and-Maximum-Number-of-Nodes-Between-Critical-Points/cpp-2058/main.cpp @@ -0,0 +1,56 @@ +/// Source : https://leetcode.com/problems/find-the-minimum-and-maximum-number-of-nodes-between-critical-points/ +/// Author : liuyubobobo +/// Time : 2021-10-30 + +#include +#include + +using namespace std; + + +/// Using Array +/// Time Compelxity: O(n) +/// Space Compelxity: O(n) + +/// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode() : val(0), next(nullptr) {} + ListNode(int x) : val(x), next(nullptr) {} + ListNode(int x, ListNode *next) : val(x), next(next) {} +}; + +class Solution { +public: + vector nodesBetweenCriticalPoints(ListNode* head) { + + vector data; + while(head){ + data.push_back(head->val); + head = head->next; + } + + int n = data.size(); + vector pos; + for(int i = 1; i + 1 < n; i ++){ + if(data[i - 1] < data[i] && data[i] > data[i + 1]) + pos.push_back(i); + else if(data[i - 1] > data[i] && data[i] < data[i + 1]) + pos.push_back(i); + } + + if(pos.size() < 2) return {-1, -1}; + + int min_dis = INT_MAX; + for(int i = 1; i < pos.size(); i ++) + min_dis = min(min_dis, pos[i] - pos[i - 1]); + return {min_dis, pos.back() - pos[0]}; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2058-Find-the-Minimum-and-Maximum-Number-of-Nodes-Between-Critical-Points/cpp-2058/main2.cpp b/2001-2500/2058-Find-the-Minimum-and-Maximum-Number-of-Nodes-Between-Critical-Points/cpp-2058/main2.cpp new file mode 100644 index 00000000..3d26708a --- /dev/null +++ b/2001-2500/2058-Find-the-Minimum-and-Maximum-Number-of-Nodes-Between-Critical-Points/cpp-2058/main2.cpp @@ -0,0 +1,51 @@ +/// Source : https://leetcode.com/problems/find-the-minimum-and-maximum-number-of-nodes-between-critical-points/ +/// Author : liuyubobobo +/// Time : 2021-10-31 + +#include +#include + +using namespace std; + + +/// One Pass in Linked List and O(1) Space +/// Time Compelxity: O(n) +/// Space Compelxity: O(1) + +/// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode() : val(0), next(nullptr) {} + ListNode(int x) : val(x), next(nullptr) {} + ListNode(int x, ListNode *next) : val(x), next(next) {} +}; + +class Solution { +public: + vector nodesBetweenCriticalPoints(ListNode* head) { + + int prev_node_val = head->val, prev_local = -1, first_local = -1, last_local = -1, min_dis = INT_MAX; + ListNode* cur = head->next; + for(int i = 1; cur->next; i ++, cur = cur->next){ + if((prev_node_val < cur->val && cur->val > cur->next->val) || + (prev_node_val > cur->val && cur->val < cur->next->val)){ + + if(first_local == -1) first_local = i; + last_local = max(last_local, i); + if(prev_local != -1) min_dis = min(min_dis, i - prev_local); + prev_local = i; + } + prev_node_val = cur->val; + } + + if(min_dis == INT_MAX) return {-1, -1}; + return {min_dis, last_local - first_local}; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2059-Minimum-Operations-to-Convert-Number/cpp-2059/CMakeLists.txt b/2001-2500/2059-Minimum-Operations-to-Convert-Number/cpp-2059/CMakeLists.txt new file mode 100644 index 00000000..cad75f71 --- /dev/null +++ b/2001-2500/2059-Minimum-Operations-to-Convert-Number/cpp-2059/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/2001-2500/2059-Minimum-Operations-to-Convert-Number/cpp-2059/main.cpp b/2001-2500/2059-Minimum-Operations-to-Convert-Number/cpp-2059/main.cpp new file mode 100644 index 00000000..667b0c50 --- /dev/null +++ b/2001-2500/2059-Minimum-Operations-to-Convert-Number/cpp-2059/main.cpp @@ -0,0 +1,77 @@ +/// Source : https://leetcode.com/problems/minimum-operations-to-convert-number/ +/// Author : liuyubobobo +/// Time : 2021-10-30 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// BFS +/// Time Compelxity: O(1000n) +/// Space Compelxity: O(1000n) +class Solution { +public: + int minimumOperations(vector& nums, int start, int goal) { + + vector dis(1001, -1); + dis[start] = 0; + + queue q; + q.push(start); + + while(!q.empty()){ + int cur = q.front(); q.pop(); + + int d = dis[cur]; + for(int num: nums){ + int a = cur + num; + if(a == goal) return d + 1; + if(0 <= a && a <= 1000 && dis[a] == -1) q.push(a), dis[a] = d + 1; + + int b = cur - num; + if(b == goal) return d + 1; + if(0 <= b && b <= 1000 && dis[b] == -1) q.push(b), dis[b] = d + 1; + + int c = cur ^ num; + if(c == goal) return d + 1; + if(0 <= c && c <= 1000 && dis[c] == -1) q.push(c), dis[c] = d + 1; + } + } + return -1; + } +}; + + +int main() { + + vector nums1 = {1, 3}; + cout << Solution().minimumOperations(nums1, 6, 4) << endl; + // 2 + + vector nums2 = {2, 4, 12}; + cout << Solution().minimumOperations(nums2, 2, 12) << endl; + // 2 + + vector nums3 = {3, 5, 7}; + cout << Solution().minimumOperations(nums3, 0, -4) << endl; + // 2 + + vector nums4 = {2, 8, 16}; + cout << Solution().minimumOperations(nums4, 0, 1) << endl; + // -1 + + vector nums5 = {1}; + cout << Solution().minimumOperations(nums5, 0, 3) << endl; + // 3 + + vector nums6 = {274504599,-437121852,-283671014,-795227961,504793587,-655990799,-903306522,44919307,-873921107,435103173,-233943318,-364255446,-559614087,-727247460,-187800152,-228958874,373958305,637920438,235436095,-596133383,464339218,-67824712,-155028908,168017302,361823236,195637352,-495807030,-283876713,517899793,-562939689,884969425,-144330241,140538827,-536479469,768251206,-640028608,806134401,243968407,928102192,-480188410,-652340704,-862758854,137351112,648721527,249762676,624620853,-392218813,-999179129,731919183,330383470,861417443,-679928265,-850093860,105372736,-331113772,377702286,265400395,-511047215,492824547,118533263,802729743,91293283,-596122218,503153602,-392161752,-536359573,469464778,-519480260,-437818942,43191911,-325148088,914414872,-779527485,499668349,604223142,158035493,-133335863,452500770,593642940,881994837,-393244441,-740955862,369681444,-649744897,-329622834,-727346152,216135938,660402034,157047130,98520751,389074028,332247407,-209362397,-405846547,-976164396,179697702,482640852,113156802,-764726927,21196820,475924861,-501387010,-521285998,-73340730,-341407987,-410283280,-618814157,388062458,-52090234,-943486285,438909665,386411224,829785577,878471402,306505406,-4019276,242674243,133684521,626711549,427600365,-907767977,-58201536,-768231545,357227318,-830719646,608805401,-189212199,288239474,692386759,908023931,-120320781,-239958589,680092226,207253648,274039857,157541875,216046740,577951839,345003653,-380997882,837933318,-372547856,-593257214,-376937702,-215397501,-490627366,397047895,171228292,239947581,574138161,133786400,-349032470,224529998,812411777,647669892,488917,-674063913,768370921,-37596428,-656866372,367475563,4811396,-864970305,-22343842,781134974,-320627062,-943951001,-724118919,23519930,-372268648,714884514,-921267107,-629610933,-210498943,629593893,-543099666,989641699,-520568809,302398795,462461247,-493362512,-517267543,896586688,738136629,792759663,77849471,163099930,-294652452,-586051267,138373545,-45443242,-178006635,126656767,-370740793,-142028216,-656478789,-909865539,-45016267,-331506071,-875778621,-575234905,-795010054,-217915587,28709532,410822428,-253100539,542188248,-292261868,-628494325,-137807006,-62295850,-960968938,651503967,-804449486,-912908442,407895859,-312220179,-373281077,-126441710,587251290,807148112,-542439701,-437800095,136518757,947027117,-162031226,-883838131,-441985931,105920835,300258318,-461749685,312341616,-722559772,553077273,100170653,-791911093,260884109,-515528241,519874204,726741845,116213300,396117093,-646099763,896174142,484441559,170623996,731971679,-683531213,429220971,51501373,-980518207,337856564,932447220,790777174,-164285774,184598181,542501755,-295103903,322292600,-515696143,466063434,268858116,19617585,-668148351,595835834,-875679692,306780299,465852737,-749476049,496973136,108307092,-62169373,-613000035,-15802981,380806050,-15599477,224196161,-786436446,-102721720,966016112,-449681577,-571359760,-30870357,907947772,-397757285,-415978672,204756474,-676646192,879829138,154543119,-37915616,353546466,121384343,679059598,-575886433,-58814987,375756597,-737810759,-640442425,-830225084,-131054299,-448790015,-121208252,-182631226,-828929325,860254702,-966027942,693239701,221755949,954184244,609025156,602818238,348029234,191806330,-776743553,217516433,625978431,146580109,-176159863,142705862,332507932,-911208273,607714224,-487331269,-491001799,31873551,-890999237,203866747,831181692,-474880013,-414589485,708339893,-68899679,35636137,43747302,-970885272,301068191,175227438,906089806,-622934104,613550487,212679441,237390198,-383871498,359829413,-18858272,-564035296,-68723821,902159573,925503754,841238795,-550055927,-710708273,473810306,-942061728,-630129098,473871569,-38610927,798344511,-585307353,17981580,575350042,-708955832,438058040,-225128624,441551583,-669250624,-904359642,67471216,836221913,377382388,986685062,614075075,-969748019,-688247479,234834944,1}; + cout << Solution().minimumOperations(nums6, 704, 884969425) << endl; + // 705 + + return 0; +} diff --git a/2001-2500/2060-Check-if-an-Original-String-Exists-Given-Two-Encoded Strings/cpp-2060/CMakeLists.txt b/2001-2500/2060-Check-if-an-Original-String-Exists-Given-Two-Encoded Strings/cpp-2060/CMakeLists.txt new file mode 100644 index 00000000..a0d16fe6 --- /dev/null +++ b/2001-2500/2060-Check-if-an-Original-String-Exists-Given-Two-Encoded Strings/cpp-2060/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) diff --git a/2001-2500/2060-Check-if-an-Original-String-Exists-Given-Two-Encoded Strings/cpp-2060/main.cpp b/2001-2500/2060-Check-if-an-Original-String-Exists-Given-Two-Encoded Strings/cpp-2060/main.cpp new file mode 100644 index 00000000..3541fef5 --- /dev/null +++ b/2001-2500/2060-Check-if-an-Original-String-Exists-Given-Two-Encoded Strings/cpp-2060/main.cpp @@ -0,0 +1,123 @@ +/// Source : https://leetcode.com/problems/check-if-an-original-string-exists-given-two-encoded-strings/ +/// Author : liuyubobobo +/// Time : 2021-11-01 + +#include +#include +#include + +using namespace std; + + +/// Memoization +/// Time Compelxity: O(n1 * n2 * 10000) +/// Space Compelxity: O(n1 * n2 * 10000) +class Solution { +public: + bool possiblyEquals(string s1, string s2) { + + map, int>, bool> dp; // (i1, i2), diff = line1 - line2 + return dfs(s1, s2, 0, 0, 0, dp); + } + +private: + bool dfs(const string& s1, const string& s2, int i1, int i2, int diff, + map, int>, bool>& dp){ + + if(i1 == s1.size() && i2 == s2.size()) return diff == 0; + + pair, int> cur_state = {{i1, i2}, diff}; + if(dp.count(cur_state)) return dp[cur_state]; + + if(i1 == s1.size()){ + if(diff <= 0) return false; + + if(!isdigit(s2[i2])) + return dp[cur_state] = dfs(s1, s2, i1, i2 + 1, diff - 1, dp); + + for(int len = 0; len < 3 && i2 + len < s2.size() && isdigit(s2[i2 + len]); len ++) + if(dfs(s1, s2, i1, i2 + len + 1, diff - atoi(s2.substr(i2, len + 1).c_str()), dp)) + return dp[cur_state] = true; + return dp[cur_state] = false; + } + + if(i2 == s2.size()){ + if(diff >= 0) return false; + + if(!isdigit(s1[i1])) + return dp[cur_state] = dfs(s1, s2, i1 + 1, i2, diff + 1, dp); + + for(int len = 0; len < 3 && i1 + len < s1.size() && isdigit(s1[i1 + len]); len ++) + if(dfs(s1, s2, i1 + len + 1, i2, diff + atoi(s1.substr(i1, len + 1).c_str()), dp)) + return dp[cur_state] = true; + return dp[cur_state] = false; + } + + if(!isdigit(s1[i1]) && !isdigit(s2[i2])){ + if(diff){ + if(diff > 0) return dp[cur_state] = dfs(s1, s2, i1, i2 + 1, diff - 1, dp); + return dp[cur_state] = dfs(s1, s2, i1 + 1, i2, diff + 1, dp); + } + + if(s1[i1] == s2[i2]) + return dp[cur_state] = dfs(s1, s2, i1 + 1, i2 + 1, diff, dp); + return dp[cur_state] = false; + } + + if(!isdigit(s1[i1]) && isdigit(s2[i2])){ + if(diff < 0) + return dp[cur_state] = dfs(s1, s2, i1 + 1, i2, diff + 1, dp); + + for(int len = 0; len < 3 && i2 + len < s2.size() && isdigit(s2[i2 + len]); len ++) + if(dfs(s1, s2, i1, i2 + len + 1, diff - atoi(s2.substr(i2, len + 1).c_str()), dp)) + return dp[cur_state] = true; + return dp[cur_state] = false; + } + + if(isdigit(s1[i1]) && !isdigit(s2[i2])){ + if(diff > 0) + return dp[cur_state] = dfs(s1, s2, i1, i2 + 1, diff - 1, dp); + + for(int len = 0; len < 3 && i1 + len < s1.size() && isdigit(s1[i1 + len]); len ++) + if(dfs(s1, s2, i1 + len + 1, i2, diff + atoi(s1.substr(i1, len + 1).c_str()), dp)) + return dp[cur_state] = true; + return dp[cur_state] = false; + } + + assert(isdigit(s1[i1]) && isdigit(s2[i2])); + for(int len1 = 0; len1 < 3 && i1 + len1 < s1.size() && isdigit(s1[i1 + len1]); len1 ++) + if(dfs(s1, s2, i1 + len1 + 1, i2, diff + atoi(s1.substr(i1, len1 + 1).c_str()), dp)) + return dp[cur_state] = true; + return dp[cur_state] = false; + } +}; + + +int main() { + + cout << Solution().possiblyEquals("internationalization", "i18n") << endl; + // true + + cout << Solution().possiblyEquals("l123e", "44") << endl; + // true + + cout << Solution().possiblyEquals("a5b", "c5b") << endl; + // false + + cout << Solution().possiblyEquals("112s", "g841") << endl; + // true + + cout << Solution().possiblyEquals("ab", "a2") << endl; + // false + + cout << Solution().possiblyEquals("1", "z") << endl; + // true + + cout << Solution().possiblyEquals("a312b4a77", "a428a1a8a") << endl; + // true + + cout << Solution().possiblyEquals("98u8v8v8v89u888u998v88u98v88u9v99u989v8u", "9v898u98v888v89v998u98v9v888u9v899v998u9") << endl; + // false + + return 0; +} diff --git a/2001-2500/2061-Number-of-Spaces-Cleaning-Robot-Cleaned/cpp-2061/CMakeLists.txt b/2001-2500/2061-Number-of-Spaces-Cleaning-Robot-Cleaned/cpp-2061/CMakeLists.txt new file mode 100644 index 00000000..5e9840d7 --- /dev/null +++ b/2001-2500/2061-Number-of-Spaces-Cleaning-Robot-Cleaned/cpp-2061/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_2061) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2061 main.cpp) diff --git a/2001-2500/2061-Number-of-Spaces-Cleaning-Robot-Cleaned/cpp-2061/main.cpp b/2001-2500/2061-Number-of-Spaces-Cleaning-Robot-Cleaned/cpp-2061/main.cpp new file mode 100644 index 00000000..1d305e88 --- /dev/null +++ b/2001-2500/2061-Number-of-Spaces-Cleaning-Robot-Cleaned/cpp-2061/main.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/number-of-spaces-cleaning-robot-cleaned/ +/// Author : liuyubobobo +/// Time : 2021-11-04 + +#include +#include +#include + +using namespace std; + + +/// Simualtion +/// Time Complexity: O(R * C) +/// Space Complexity: O(R * C) +class Solution { + +private: + const int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + int R, C; + +public: + int numberOfCleanRooms(vector>& room) { + + R = room.size(), C = room[0].size(); + + set> visited; + set res; + int curx = 0, cury = 0, d = 0; + visited.insert({curx * C + cury, d}); + res.insert(curx * C + cury); + while(true){ + if(in_area(curx + dirs[d][0], cury + dirs[d][1]) && room[curx + dirs[d][0]][cury + dirs[d][1]] == 0) + curx += dirs[d][0], cury += dirs[d][1]; + else + d = (d + 1) % 4; + + if(visited.count({curx * C + cury, d})) break; + visited.insert({curx * C + cury, d}); + res.insert(curx * C + cury); + } + return res.size(); + } + +private: + bool in_area(int x, int y){ + return 0 <= x && x < R && 0 <= y && y < C; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2062-Count-Vowel-Substrings-of-a-String/cpp-2062/CMakeLists.txt b/2001-2500/2062-Count-Vowel-Substrings-of-a-String/cpp-2062/CMakeLists.txt new file mode 100644 index 00000000..2ae8397c --- /dev/null +++ b/2001-2500/2062-Count-Vowel-Substrings-of-a-String/cpp-2062/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/2001-2500/2062-Count-Vowel-Substrings-of-a-String/cpp-2062/main.cpp b/2001-2500/2062-Count-Vowel-Substrings-of-a-String/cpp-2062/main.cpp new file mode 100644 index 00000000..bb7c2972 --- /dev/null +++ b/2001-2500/2062-Count-Vowel-Substrings-of-a-String/cpp-2062/main.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/count-vowel-substrings-of-a-string/ +/// Author : liuyubobobo +/// Time : 2021-11-06 + +#include +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Co,plexity: O(n^3) +/// Space Complexity: O(1) +class Solution { +public: + int countVowelSubstrings(string word) { + + int n = word.size(), res = 0; + for(int i = 0; i < n; i ++) + for(int j = i; j < n; j ++) + res += check(word.substr(i, j - i + 1)); + return res; + } + +private: + bool check(const string& s){ + + if(s.size() < 5) return false; + + vector f(26, 0); + int cnt = 0; + for(char c: s){ + if(c != 'a' && c != 'e' && c != 'i' && c != 'o' && c != 'u') + return false; + f[c - 'a'] ++; + cnt += f[c - 'a'] == 1; + } + return cnt == 5; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2063-Vowels-of-All-Substrings/cpp-2063/CMakeLists.txt b/2001-2500/2063-Vowels-of-All-Substrings/cpp-2063/CMakeLists.txt new file mode 100644 index 00000000..3f98647f --- /dev/null +++ b/2001-2500/2063-Vowels-of-All-Substrings/cpp-2063/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/2001-2500/2063-Vowels-of-All-Substrings/cpp-2063/main.cpp b/2001-2500/2063-Vowels-of-All-Substrings/cpp-2063/main.cpp new file mode 100644 index 00000000..36828bd6 --- /dev/null +++ b/2001-2500/2063-Vowels-of-All-Substrings/cpp-2063/main.cpp @@ -0,0 +1,44 @@ +/// Source : https://leetcode.com/problems/vowels-of-all-substrings/ +/// Author : liuyubobobo +/// Time : 2021-11-06 + +#include + +using namespace std; + + +/// Mathematics +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + long long countVowels(string word) { + + int n = word.size(); + long long res = 0; + for(int i = 0; i < n; i ++) + if(is_vowel(word[i])) + res += (long long)(i + 1) * (n - i); + return res; + } + +private: + bool is_vowel(char c){ + return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'; + } +}; + + +int main() { + + cout << Solution().countVowels("aba") << endl; + // 6 + + cout << Solution().countVowels("abc") << endl; + // 3 + + cout << Solution().countVowels("ltcd") << endl; + // 0 + + return 0; +} diff --git a/2001-2500/2064-Minimized-Maximum-of-Products-Distributed-to-Any-Store/cpp-2064/CMakeLists.txt b/2001-2500/2064-Minimized-Maximum-of-Products-Distributed-to-Any-Store/cpp-2064/CMakeLists.txt new file mode 100644 index 00000000..cad75f71 --- /dev/null +++ b/2001-2500/2064-Minimized-Maximum-of-Products-Distributed-to-Any-Store/cpp-2064/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/2001-2500/2064-Minimized-Maximum-of-Products-Distributed-to-Any-Store/cpp-2064/main.cpp b/2001-2500/2064-Minimized-Maximum-of-Products-Distributed-to-Any-Store/cpp-2064/main.cpp new file mode 100644 index 00000000..67452fb9 --- /dev/null +++ b/2001-2500/2064-Minimized-Maximum-of-Products-Distributed-to-Any-Store/cpp-2064/main.cpp @@ -0,0 +1,60 @@ +/// Source : https://leetcode.com/problems/minimized-maximum-of-products-distributed-to-any-store/ +/// Author : liuyubobobo +/// Time : 2021-11-06 + +#include +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(m * log(sum(quantities))) +/// Space Compelxity: O(1) +class Solution { +public: + int minimizedMaximum(int n, vector& quantities) { + + long long sum = accumulate(quantities.begin(), quantities.end(), 0ll); + + long long l = 1, r = sum; + while(l < r){ + long long m = (l + r) / 2; + if(ok(n, quantities, m)) r = m; + else l = m + 1; + } + return l; + } + +private: + bool ok(int n, const vector& q, long long x){ + + int cur = 0; + for(int e: q) + cur += e / x + !!(e % x); + return cur <= n; + } +}; + + +int main() { + + vector q1 = {11, 6}; + cout << Solution().minimizedMaximum(6, q1) << endl; + // 3 + + vector q2 = {15, 10, 10}; + cout << Solution().minimizedMaximum(7, q2) << endl; + // 5 + + vector q3 = {100000}; + cout << Solution().minimizedMaximum(1, q3) << endl; + // 100000 + + vector q4 = {24,18,12,6,3,24,5,19,10,20,2,18,27,3,13,22,11,16,19,13}; + cout << Solution().minimizedMaximum(26, q4) << endl; + // 19 + + return 0; +} diff --git a/2001-2500/2065-Maximum-Path-Quality-of-a-Graph/cpp-2065/CMakeLists.txt b/2001-2500/2065-Maximum-Path-Quality-of-a-Graph/cpp-2065/CMakeLists.txt new file mode 100644 index 00000000..a0d16fe6 --- /dev/null +++ b/2001-2500/2065-Maximum-Path-Quality-of-a-Graph/cpp-2065/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) diff --git a/2001-2500/2065-Maximum-Path-Quality-of-a-Graph/cpp-2065/main.cpp b/2001-2500/2065-Maximum-Path-Quality-of-a-Graph/cpp-2065/main.cpp new file mode 100644 index 00000000..de2aac53 --- /dev/null +++ b/2001-2500/2065-Maximum-Path-Quality-of-a-Graph/cpp-2065/main.cpp @@ -0,0 +1,78 @@ +/// Source : https://leetcode.com/problems/maximum-path-quality-of-a-graph/ +/// Author : liuyubobobo +/// Time : 2021-11-06 + +#include +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(|d|^10) where d is the degree of vertexs and at most 4 according to the problem +/// Space Complexity: O(n + m) +class Solution { +public: + int maximalPathQuality(vector& values, vector>& edges, int maxTime) { + + int n = values.size(); + vector>> g(n); + for(const vector& e: edges){ + g[e[0]].push_back({e[1], e[2]}); + g[e[1]].push_back({e[0], e[2]}); + } + + long long res = 0ll; + vector path = {0}; + dfs(n, g, 0, maxTime, path, values, res); + return res; + } + +private: + void dfs(int n, const vector>>& g, int u, int t, + vector& path, const vector& values, long long& res){ + + if(u == 0){ + set vset(path.begin(), path.end()); + long long tres = 0; + for(int v: vset) tres += values[v]; + res = max(res, tres); + } + + for(const pair& p: g[u]){ + int v = p.first, w = p.second; + if(t - w >= 0){ + path.push_back(v); + dfs(n, g, v, t - w, path, values, res); + path.pop_back(); + } + } + } +}; + + +int main() { + + vector values1 = {0, 32, 10, 43}; + vector> edges1 = {{0, 1, 10}, {1, 2, 15}, {0, 3, 10}}; + cout << Solution().maximalPathQuality(values1, edges1, 49) << endl; + // 75 + + vector values2 = {5, 10, 15, 20}; + vector> edges2 = {{0, 1, 10}, {1, 2, 10}, {0, 3, 10}}; + cout << Solution().maximalPathQuality(values2, edges2, 30) << endl; + // 25 + + vector values3 = {1, 2, 3, 4}; + vector> edges3 = {{0, 1, 10}, {1, 2, 11}, {2, 3, 12}, {1, 3, 13}}; + cout << Solution().maximalPathQuality(values3, edges3, 50) << endl; + // 7 + + vector values4 = {0, 1, 2}; + vector> edges4 = {{1, 2, 10}}; + cout << Solution().maximalPathQuality(values4, edges4, 10) << endl; + // 0 + + return 0; +} diff --git a/2001-2500/2067-Number-of-Equal-Count-Substrings/cpp-2067/CMakeLists.txt b/2001-2500/2067-Number-of-Equal-Count-Substrings/cpp-2067/CMakeLists.txt new file mode 100644 index 00000000..c8d34e67 --- /dev/null +++ b/2001-2500/2067-Number-of-Equal-Count-Substrings/cpp-2067/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_2067) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2067 main.cpp) diff --git a/2001-2500/2067-Number-of-Equal-Count-Substrings/cpp-2067/main.cpp b/2001-2500/2067-Number-of-Equal-Count-Substrings/cpp-2067/main.cpp new file mode 100644 index 00000000..30264299 --- /dev/null +++ b/2001-2500/2067-Number-of-Equal-Count-Substrings/cpp-2067/main.cpp @@ -0,0 +1,64 @@ +/// Source : https://leetcode.com/problems/number-of-equal-count-substrings/ +/// Author : liuyubobobo +/// Time : 2021-11-16 + +#include +#include + +using namespace std; + + +/// Sliding Window +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int equalCountSubstrings(string s, int count) { + + int res = 0; + for(int k = 1; k <= 26; k ++){ + + vector f(26, 0); + int cur_k = 0, ok_k = 0, l = 0, r = -1; + while(l < s.size()){ + if(r + 1 < s.size() && cur_k + !f[s[r + 1] - 'a'] <= k && f[s[r + 1] - 'a'] + 1 <= count){ + cur_k += !f[s[r + 1] - 'a']; + f[s[r + 1] - 'a'] ++; + if(f[s[r + 1] - 'a'] == count) ok_k ++; + r ++; + } + else{ + if(f[s[l] - 'a'] == count) ok_k --; + f[s[l] - 'a'] --; + if(f[s[l] - 'a'] == 0) cur_k --; + l ++; + } + + res += ok_k == k; + } + } + return res; + } +}; + + +int main() { + + cout << Solution().equalCountSubstrings("aaabcbbcc", 3) << endl; + // 3 + + cout << Solution().equalCountSubstrings("abcd", 2) << endl; + // 0 + + cout << Solution().equalCountSubstrings("a", 5) << endl; + // 0 + + cout << Solution().equalCountSubstrings("abcdabcdabcdabcd", 4) << endl; + // 1 + + cout << Solution().equalCountSubstrings("abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuv" + , 1) << endl; + // 779675 + + return 0; +} diff --git a/2001-2500/2068-Check-Whether-Two-Strings-are-Almost-Equivalent/cpp-2068/CMakeLists.txt b/2001-2500/2068-Check-Whether-Two-Strings-are-Almost-Equivalent/cpp-2068/CMakeLists.txt new file mode 100644 index 00000000..e0ab18f1 --- /dev/null +++ b/2001-2500/2068-Check-Whether-Two-Strings-are-Almost-Equivalent/cpp-2068/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_2068) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2068 main.cpp) diff --git a/2001-2500/2068-Check-Whether-Two-Strings-are-Almost-Equivalent/cpp-2068/main.cpp b/2001-2500/2068-Check-Whether-Two-Strings-are-Almost-Equivalent/cpp-2068/main.cpp new file mode 100644 index 00000000..89c85588 --- /dev/null +++ b/2001-2500/2068-Check-Whether-Two-Strings-are-Almost-Equivalent/cpp-2068/main.cpp @@ -0,0 +1,32 @@ +/// Source : https://leetcode.com/problems/check-whether-two-strings-are-almost-equivalent/ +/// Author : liuyubobobo +/// Time : 2021-11-14 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + bool checkAlmostEquivalent(string word1, string word2) { + + vector f1(26, 0), f2(26, 0); + for(char c: word1) f1[c - 'a'] ++; + for(char c: word2) f2[c - 'a'] ++; + + for(int i = 0; i < 26; i ++) + if(abs(f1[i] - f2[i]) > 3) return false; + return true; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2069-Walking-Robot-Simulation-II/cpp-2069/CMakeLists.txt b/2001-2500/2069-Walking-Robot-Simulation-II/cpp-2069/CMakeLists.txt new file mode 100644 index 00000000..709a56f5 --- /dev/null +++ b/2001-2500/2069-Walking-Robot-Simulation-II/cpp-2069/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_2069) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2069 main.cpp) diff --git a/2001-2500/2069-Walking-Robot-Simulation-II/cpp-2069/main.cpp b/2001-2500/2069-Walking-Robot-Simulation-II/cpp-2069/main.cpp new file mode 100644 index 00000000..5447d378 --- /dev/null +++ b/2001-2500/2069-Walking-Robot-Simulation-II/cpp-2069/main.cpp @@ -0,0 +1,65 @@ +/// Source : https://leetcode.com/problems/walking-robot-simulation-ii/ +/// Author : liuyubobobo +/// Time : 2021-11-14 + +#include +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: init: O(1) +/// move: O(with + height) +/// get: O(1) +class Robot { + +private: + int W, H; + int cx = 0, cy = 0; + int d = 3; + const int dirs[4][2] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; + bool first = true; + +public: + Robot(int width, int height) : W(width), H(height){} + + void move(int num) { + + if(num) first = false; + num %= (2 * (W + H - 2)); + + while(num){ + int nx = cx + dirs[d][0], ny = cy + dirs[d][1]; + if(in_area(nx, ny)){ + cx = nx, cy = ny; + num --; + } + else d = (d + 1) % 4; + } + } + + vector getPos() { + return {cx, cy}; + } + + string getDir() { + if(first || d == 0) return "East"; + if(d == 1) return "North"; + if(d == 2) return "West"; + assert(d == 3); + return "South"; + } + +private: + bool in_area(int x, int y){ + return x >= 0 && x < W && y >= 0 && y < H; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2070-Most-Beautiful-Item-for-Each-Query/cpp-2070/CMakeLists.txt b/2001-2500/2070-Most-Beautiful-Item-for-Each-Query/cpp-2070/CMakeLists.txt new file mode 100644 index 00000000..e5b871e0 --- /dev/null +++ b/2001-2500/2070-Most-Beautiful-Item-for-Each-Query/cpp-2070/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_2070) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2070 main.cpp) diff --git a/2001-2500/2070-Most-Beautiful-Item-for-Each-Query/cpp-2070/main.cpp b/2001-2500/2070-Most-Beautiful-Item-for-Each-Query/cpp-2070/main.cpp new file mode 100644 index 00000000..5cbcf232 --- /dev/null +++ b/2001-2500/2070-Most-Beautiful-Item-for-Each-Query/cpp-2070/main.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/most-beautiful-item-for-each-query/ +/// Author : liuyubobobo +/// Time : 2021-11-14 + +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(nlogn + qlogn) +/// Space Complexity: O(n) +class Solution { +public: + vector maximumBeauty(vector>& items, vector& queries) { + + vector> data(items.size()); + for(int i = 0; i < items.size(); i ++) data[i] = {items[i][0], items[i][1]}; + sort(data.begin(), data.end()); + + for(int i = 1; i < data.size(); i ++) + data[i].second = max(data[i].second, data[i - 1].second); + + vector res(queries.size()); + for(int i = 0; i < queries.size(); i ++){ + int t = queries[i]; + vector>::iterator iter = upper_bound(data.begin(), data.end(), make_pair(t, INT_MAX)); + int index = iter - data.begin() - 1; + res[i] = (index == -1 ? 0 : data[index].second); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2071-Maximum-Number-of-Tasks-You-Can-Assign/cpp-2071/CMakeLists.txt b/2001-2500/2071-Maximum-Number-of-Tasks-You-Can-Assign/cpp-2071/CMakeLists.txt new file mode 100644 index 00000000..29523910 --- /dev/null +++ b/2001-2500/2071-Maximum-Number-of-Tasks-You-Can-Assign/cpp-2071/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_2071) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2071 main.cpp) diff --git a/2001-2500/2071-Maximum-Number-of-Tasks-You-Can-Assign/cpp-2071/main.cpp b/2001-2500/2071-Maximum-Number-of-Tasks-You-Can-Assign/cpp-2071/main.cpp new file mode 100644 index 00000000..ed103a30 --- /dev/null +++ b/2001-2500/2071-Maximum-Number-of-Tasks-You-Can-Assign/cpp-2071/main.cpp @@ -0,0 +1,73 @@ +/// Source : https://leetcode.com/problems/maximum-number-of-tasks-you-can-assign/ +/// Author : liuyubobobo +/// Time : 2021-11-16 + +#include +#include +#include + +using namespace std; + + +/// Binary Serch + Greedy +/// Time Complexity: O(log(min(m, n)) * mlogn), where m = |tasks|, n = |workers| +/// Space Complexity: O(n) +class Solution { +public: + int maxTaskAssign(vector& tasks, vector& workers, int pills, int strength) { + + sort(tasks.begin(), tasks.end()); + multiset worker_set(workers.begin(), workers.end()); + + int l = 0, r = tasks.size(); + while(l < r){ + int mid = (l + r + 1) / 2; + if(ok(tasks, worker_set, mid, pills, strength)) + l = mid; + else + r = mid - 1; + } + return l; + } + +private: + bool ok(const vector& tasks, multiset workers, int k, int pills, int str){ + + for(int i = k - 1; i >= 0; i --) + if(!workers.empty() && *workers.rbegin() >= tasks[i]) + workers.erase(prev(workers.end())); + else if(pills){ + auto it = workers.lower_bound(tasks[i] - str); + if(it == workers.end()) return false; + workers.erase(it); + pills --; + } + else return false; + return true; + } +}; + +int main() { + + vector task1 = {3, 2, 1}, workers1 = {0, 3, 3}; + cout << Solution().maxTaskAssign(task1, workers1, 1, 1) << endl; + // 3 + + vector task2 = {5, 4}, workers2 = {0, 0, 0}; + cout << Solution().maxTaskAssign(task2, workers2, 1, 5) << endl; + // 1 + + vector task3 = {10, 15, 30}, workers3 = {0, 10, 10, 10, 10}; + cout << Solution().maxTaskAssign(task3, workers3, 3, 10) << endl; + // 2 + + vector task4 = {5, 9, 8, 5, 9}, workers4 = {1, 6, 4, 2, 6}; + cout << Solution().maxTaskAssign(task4, workers4, 1, 5) << endl; + // 3 + + vector task5 = {74,41,64,20,28,52,30,4,4,63}, workers5 = {38}; + cout << Solution().maxTaskAssign(task5, workers5, 0, 68) << endl; + // 1 + + return 0; +} diff --git a/2001-2500/2073-Time-Needed-to-Buy-Tickets/cpp-2073/CMakeLists.txt b/2001-2500/2073-Time-Needed-to-Buy-Tickets/cpp-2073/CMakeLists.txt new file mode 100644 index 00000000..2ae8397c --- /dev/null +++ b/2001-2500/2073-Time-Needed-to-Buy-Tickets/cpp-2073/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/2001-2500/2073-Time-Needed-to-Buy-Tickets/cpp-2073/main.cpp b/2001-2500/2073-Time-Needed-to-Buy-Tickets/cpp-2073/main.cpp new file mode 100644 index 00000000..a7303a43 --- /dev/null +++ b/2001-2500/2073-Time-Needed-to-Buy-Tickets/cpp-2073/main.cpp @@ -0,0 +1,38 @@ +/// Source : https://leetcode.com/problems/time-needed-to-buy-tickets/ +/// Author : liuyubobobo +/// Time : 2021-11-13 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(sum(tickets)) +/// Space Complexity: O(1) +class Solution { +public: + int timeRequiredToBuy(vector& tickets, int k) { + + int res = 0; + while(tickets[k] > 1){ + for(int& e: tickets) + if(e) res ++, e --; + } + + for(int i = 0; i <= k; i ++) + if(tickets[i] > 0) res ++; + return res; + } +}; + + +int main() { + + vector t1 = {84,49,5,24,70,77,87,8}; + cout << Solution().timeRequiredToBuy(t1, 3) << endl; + // 154 + + return 0; +} diff --git a/2001-2500/2074-Reverse-Nodes-in-Even-Length-Groups/cpp-2074/CMakeLists.txt b/2001-2500/2074-Reverse-Nodes-in-Even-Length-Groups/cpp-2074/CMakeLists.txt new file mode 100644 index 00000000..3f98647f --- /dev/null +++ b/2001-2500/2074-Reverse-Nodes-in-Even-Length-Groups/cpp-2074/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/2001-2500/2074-Reverse-Nodes-in-Even-Length-Groups/cpp-2074/main.cpp b/2001-2500/2074-Reverse-Nodes-in-Even-Length-Groups/cpp-2074/main.cpp new file mode 100644 index 00000000..5c6dcc80 --- /dev/null +++ b/2001-2500/2074-Reverse-Nodes-in-Even-Length-Groups/cpp-2074/main.cpp @@ -0,0 +1,61 @@ +/// Source : https://leetcode.com/problems/reverse-nodes-in-even-length-groups/ +/// Author : liuyubobobo +/// Time : 2021-11-13 + +#include +#include + +using namespace std; + + +/// Using Array to store +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode() : val(0), next(nullptr) {} + ListNode(int x) : val(x), next(nullptr) {} + ListNode(int x, ListNode *next) : val(x), next(next) {} +}; + +class Solution { +public: + ListNode* reverseEvenLengthGroups(ListNode* head) { + + vector data; + ListNode* cur = head; + while(cur) data.push_back(cur->val), cur = cur->next; + + int n = data.size(); + int len = 1, index = 0; + while(index < n){ + int start = index, end = min(index + len - 1, n - 1); + if((end - start + 1) % 2 == 0) + reverse(data, start, end); + index = end + 1; + len ++; + } + + ListNode* dummy = new ListNode(-1); + cur = dummy; + for(int i = 0; i < n; i ++) + cur->next = new ListNode(data[i]), cur = cur->next; + return dummy->next; + } + +private: + void reverse(vector& data, int start, int end){ + + int l = start, r = end; + while(l < r) swap(data[l], data[r]), l ++, r --; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2075-Decode-the-Slanted-Ciphertext/cpp-2075/CMakeLists.txt b/2001-2500/2075-Decode-the-Slanted-Ciphertext/cpp-2075/CMakeLists.txt new file mode 100644 index 00000000..cad75f71 --- /dev/null +++ b/2001-2500/2075-Decode-the-Slanted-Ciphertext/cpp-2075/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/2001-2500/2075-Decode-the-Slanted-Ciphertext/cpp-2075/main.cpp b/2001-2500/2075-Decode-the-Slanted-Ciphertext/cpp-2075/main.cpp new file mode 100644 index 00000000..6598e57c --- /dev/null +++ b/2001-2500/2075-Decode-the-Slanted-Ciphertext/cpp-2075/main.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/decode-the-slanted-ciphertext/ +/// Author : liuyubobobo +/// Time : 2021-11-13 + +#include +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(|s|) +/// Space Complextiy: O(|s|) +class Solution { +public: + string decodeCiphertext(string encodedText, int R) { + + int n = encodedText.size(); + assert(n % R == 0); + int C = n / R; + + vector M(R, string(C, ' ')); + for(int i = 0; i < n; i ++) + M[i / C][i % C] = encodedText[i]; + + string res = ""; + for(int c = 0; c < C; c ++) + for(int r = 0; r < R && c + r < C; r ++) + res += M[r][c + r]; + while(res.back() == ' ') res.pop_back(); + return res; + } +}; + + +int main() { + + cout << Solution().decodeCiphertext("ch ie pr", 3) << endl; + // cipher + + cout << Solution().decodeCiphertext("iveo eed l te olc", 4) << endl; + // i love leetcode + + cout << Solution().decodeCiphertext("coding", 1) << endl; + // coding + + cout << Solution().decodeCiphertext(" b ac", 2) << endl; + // _abc + + return 0; +} diff --git a/2001-2500/2076-Process-Restricted-Friend-Requests/cpp-2076/CMakeLists.txt b/2001-2500/2076-Process-Restricted-Friend-Requests/cpp-2076/CMakeLists.txt new file mode 100644 index 00000000..a0d16fe6 --- /dev/null +++ b/2001-2500/2076-Process-Restricted-Friend-Requests/cpp-2076/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) diff --git a/2001-2500/2076-Process-Restricted-Friend-Requests/cpp-2076/main.cpp b/2001-2500/2076-Process-Restricted-Friend-Requests/cpp-2076/main.cpp new file mode 100644 index 00000000..1f3acd2f --- /dev/null +++ b/2001-2500/2076-Process-Restricted-Friend-Requests/cpp-2076/main.cpp @@ -0,0 +1,74 @@ +/// Source : https://leetcode.com/problems/process-restricted-friend-requests/ +/// Author : liuyubobobo +/// Time : 2021-11-13 + +#include +#include + +using namespace std; + + +/// UF - restore the old UF +/// Time Complexity: O(m * n) +/// Space Complexity: O(n) +class UF{ + +public: + vector parent; + + UF(int n) : parent(n){ + for(int i = 0 ; i < n ; i ++) + parent[i] = i; + } + + int find(int p){ + if(p != parent[p]) + parent[p] = find(parent[p]); + return parent[p]; + } + + bool is_connected(int p, int q){ + return find(p) == find(q); + } + + void union_elements(int p, int q){ + + int p_root = find(p), q_root = find(q); + + if(p_root == q_root) return; + + parent[p_root] = q_root; + } +}; + +class Solution { +public: + vector friendRequests(int n, vector>& restrictions, vector>& requests) { + + UF uf(n); + + int q = requests.size(); + vector res(q); + for(int i = 0; i < q; i ++){ + + vector old_uf = uf.parent; + + int a = requests[i][0], b = requests[i][1]; + uf.union_elements(a, b); + + bool ok = true; + for(const vector& r: restrictions) + if(uf.is_connected(r[0], r[1])){ok = false; break;} + + res[i] = ok; + if(!ok) uf.parent = old_uf; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2077-Paths-in-Maze-That-Lead-to-Same-Room/cpp-2077/CMakeLists.txt b/2001-2500/2077-Paths-in-Maze-That-Lead-to-Same-Room/cpp-2077/CMakeLists.txt new file mode 100644 index 00000000..0afb07ba --- /dev/null +++ b/2001-2500/2077-Paths-in-Maze-That-Lead-to-Same-Room/cpp-2077/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_2077) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2077 main.cpp) diff --git a/2001-2500/2077-Paths-in-Maze-That-Lead-to-Same-Room/cpp-2077/main.cpp b/2001-2500/2077-Paths-in-Maze-That-Lead-to-Same-Room/cpp-2077/main.cpp new file mode 100644 index 00000000..4eb8e6b1 --- /dev/null +++ b/2001-2500/2077-Paths-in-Maze-That-Lead-to-Same-Room/cpp-2077/main.cpp @@ -0,0 +1,41 @@ +/// Source : https://leetcode.com/problems/paths-in-maze-that-lead-to-same-room/ +/// Author : liuyubobobo +/// Time : 2021-11-19 + +#include +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n + m) +/// Space Complexity: O(n^2) +class Solution { +public: + int numberOfPaths(int n, vector>& corridors) { + + vector> M(n, vector(n, false)); + vector> g(n); + vector> edges(corridors.size()); + for(int i = 0; i < corridors.size(); i ++){ + int a = corridors[i][0] - 1, b = corridors[i][1] - 1; + M[a][b] = M[b][a] = true; + g[a].push_back(b), g[b].push_back(a); + edges[i] = {a, b}; + } + + int res = 0; + for(const pair& e: edges) + for(int v: g[e.first]) + res += (v != e.second && M[v][e.second]); + return res / 3; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2078-Two-Furthest-Houses-With-Different-Colors/cpp-2078/CMakeLists.txt b/2001-2500/2078-Two-Furthest-Houses-With-Different-Colors/cpp-2078/CMakeLists.txt new file mode 100644 index 00000000..2ae8397c --- /dev/null +++ b/2001-2500/2078-Two-Furthest-Houses-With-Different-Colors/cpp-2078/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/2001-2500/2078-Two-Furthest-Houses-With-Different-Colors/cpp-2078/main.cpp b/2001-2500/2078-Two-Furthest-Houses-With-Different-Colors/cpp-2078/main.cpp new file mode 100644 index 00000000..57a23451 --- /dev/null +++ b/2001-2500/2078-Two-Furthest-Houses-With-Different-Colors/cpp-2078/main.cpp @@ -0,0 +1,30 @@ +/// Source : https://leetcode.com/problems/two-furthest-houses-with-different-colors/ +/// Author : liuyubobobo +/// Time : 2021-11-20 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n^2) +/// Space Complexity: O(1) +class Solution { +public: + int maxDistance(vector& colors) { + + int res = 0; + for(int i = 0; i < colors.size(); i ++) + for(int j = i + 1; j < colors.size(); j ++) + if(colors[i] != colors[j]) res = max(res, j - i); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2079-Watering-Plants/cpp-2079/CMakeLists.txt b/2001-2500/2079-Watering-Plants/cpp-2079/CMakeLists.txt new file mode 100644 index 00000000..3f98647f --- /dev/null +++ b/2001-2500/2079-Watering-Plants/cpp-2079/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/2001-2500/2079-Watering-Plants/cpp-2079/main.cpp b/2001-2500/2079-Watering-Plants/cpp-2079/main.cpp new file mode 100644 index 00000000..a225014f --- /dev/null +++ b/2001-2500/2079-Watering-Plants/cpp-2079/main.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/watering-plants/ +/// Author : liuyubobobo +/// Time : 2021-11-20 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int wateringPlants(vector& plants, int capacity) { + + int res = 0, cur = -1, left = capacity; + for(int i = 0; i < plants.size();) + if(left >= plants[i]){ + res ++; + left -= plants[i]; + cur ++; + i ++; + } + else{ + res += (cur + 1) * 2; + left = capacity; + } + return res; + } +}; + + +int main() { + + vector plants1 = {2, 2, 3, 3}; + cout << Solution().wateringPlants(plants1, 5) << endl; + // 14 + + vector plants2 = {1, 1, 1, 4, 2, 3}; + cout << Solution().wateringPlants(plants2, 4) << endl; + // 30 + + vector plants3 = {7,7,7,7,7,7,7}; + cout << Solution().wateringPlants(plants3, 8) << endl; + // 49 + + return 0; +} diff --git a/2001-2500/2080-Range-Frequency-Queries/cpp-2080/CMakeLists.txt b/2001-2500/2080-Range-Frequency-Queries/cpp-2080/CMakeLists.txt new file mode 100644 index 00000000..cad75f71 --- /dev/null +++ b/2001-2500/2080-Range-Frequency-Queries/cpp-2080/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/2001-2500/2080-Range-Frequency-Queries/cpp-2080/main.cpp b/2001-2500/2080-Range-Frequency-Queries/cpp-2080/main.cpp new file mode 100644 index 00000000..c2b9812e --- /dev/null +++ b/2001-2500/2080-Range-Frequency-Queries/cpp-2080/main.cpp @@ -0,0 +1,38 @@ +/// Source : https://leetcode.com/problems/range-frequency-queries/ +/// Author : liuyubobobo +/// Time : 2021-11-20 + +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: init: O(n) +/// query: O(logn) +/// Space Complexity: O(maxa) +class RangeFreqQuery { + +private: + vector> f; + +public: + RangeFreqQuery(vector& arr) : f(10001) { + for(int i = 0; i < arr.size(); i ++) + f[arr[i]].push_back(i); + } + + int query(int left, int right, int value) { + + int l = lower_bound(f[value].begin(), f[value].end(), left) - f[value].begin(); + int r = upper_bound(f[value].begin(), f[value].end(), right) - f[value].begin(); + return max(r - l, 0); + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2081-Sum-of-k-Mirror-Numbers/cpp-2081/CMakeLists.txt b/2001-2500/2081-Sum-of-k-Mirror-Numbers/cpp-2081/CMakeLists.txt new file mode 100644 index 00000000..a0d16fe6 --- /dev/null +++ b/2001-2500/2081-Sum-of-k-Mirror-Numbers/cpp-2081/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) diff --git a/2001-2500/2081-Sum-of-k-Mirror-Numbers/cpp-2081/main.cpp b/2001-2500/2081-Sum-of-k-Mirror-Numbers/cpp-2081/main.cpp new file mode 100644 index 00000000..c6e9dbfa --- /dev/null +++ b/2001-2500/2081-Sum-of-k-Mirror-Numbers/cpp-2081/main.cpp @@ -0,0 +1,74 @@ +/// Source : https://leetcode.com/problems/sum-of-k-mirror-numbers/ +/// Author : liuyubobobo +/// Time : 2021-11-20 + +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(sqrt(max_num) * logn) +/// Space Complexity: O(log(max_num) + logn) +class Solution { +public: + long long kMirror(int k, int n) { + + long long sum = 0; + vector numk(1000); + for(int sz = 1;n;sz ++){ + vector num(sz); + dfs(sz, num, numk, 0, k, n, sum); + } + return sum; + } + +private: + void dfs(int sz, vector& num, vector& numk, + int index, int k, int& n, long long& sum){ + + if(n == 0) return; + + if(index >= ((sz + 1) >> 1)){ + long long a = 0ll; + for(int e: num) a = a * 10 + e; + if(ok(a, k, numk)) sum += a, n --; + return; + } + + for(int i = (index == 0 ? 1 : 0); i <= 9 && n; i ++){ + num[index] = num[sz - 1 - index] = i; + dfs(sz, num, numk, index + 1, k, n, sum); + } + } + + bool ok(long long a, int k, vector& numk){ + + int w = 0; + while(a) numk[w ++] = a % k, a /= k; + + int half = w / 2; + for(int i = 0; i < half; i ++) + if(numk[i] != numk[w - 1 - i]) return false; + return true; + } +}; + + +int main() { + + cout << Solution().kMirror(2, 5) << endl; + // 25 + + cout << Solution().kMirror(3, 7) << endl; + // 499 + + cout << Solution().kMirror(4, 30) << endl; + // 53393239260 + + for(int k = 2; k <= 9; k ++) + cout << Solution().kMirror(k, 30) << endl; + + return 0; +} diff --git a/2001-2500/2083-Substrings-That-Begin-and-End-With-the-Same-Letter/cpp-2083/CMakeLists.txt b/2001-2500/2083-Substrings-That-Begin-and-End-With-the-Same-Letter/cpp-2083/CMakeLists.txt new file mode 100644 index 00000000..91ae7865 --- /dev/null +++ b/2001-2500/2083-Substrings-That-Begin-and-End-With-the-Same-Letter/cpp-2083/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_2083) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2083 main.cpp) diff --git a/2001-2500/2083-Substrings-That-Begin-and-End-With-the-Same-Letter/cpp-2083/main.cpp b/2001-2500/2083-Substrings-That-Begin-and-End-With-the-Same-Letter/cpp-2083/main.cpp new file mode 100644 index 00000000..9acd1455 --- /dev/null +++ b/2001-2500/2083-Substrings-That-Begin-and-End-With-the-Same-Letter/cpp-2083/main.cpp @@ -0,0 +1,32 @@ +/// Source : https://leetcode.com/problems/substrings-that-begin-and-end-with-the-same-letter/ +/// Author : liuyubobobo +/// Time : 2021-11-27 + +#include +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + long long numberOfSubstrings(string s) { + + vector f(26, 0); + long long res = 0; + for(int i = 0; i < s.size(); i ++){ + f[s[i] - 'a'] ++; + res += f[s[i] - 'a']; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2085-Count-Common-Words-With-One-Occurrence/cpp-2085/CMakeLists.txt b/2001-2500/2085-Count-Common-Words-With-One-Occurrence/cpp-2085/CMakeLists.txt new file mode 100644 index 00000000..2d8278c0 --- /dev/null +++ b/2001-2500/2085-Count-Common-Words-With-One-Occurrence/cpp-2085/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_2085) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2085 main.cpp) diff --git a/2001-2500/2085-Count-Common-Words-With-One-Occurrence/cpp-2085/main.cpp b/2001-2500/2085-Count-Common-Words-With-One-Occurrence/cpp-2085/main.cpp new file mode 100644 index 00000000..0f88931e --- /dev/null +++ b/2001-2500/2085-Count-Common-Words-With-One-Occurrence/cpp-2085/main.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/count-common-words-with-one-occurrence/ +/// Author : liuyubobobo +/// Time : 2021-11-27 + +#include +#include +#include + +using namespace std; + + +/// Using Map +/// Time Complexity: O(n + m) +/// Space Complexity: O(n + m) +class Solution { +public: + int countWords(vector& words1, vector& words2) { + + map map1, map2; + for(const string& s: words1) map1[s] ++; + for(const string& s: words2) map2[s] ++; + + int res = 0; + for(const pair& p: map1) + if(p.second == 1 && map2.count(p.first) && map2[p.first] == 1) res ++; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2086-Minimum-Number-of-Buckets-Required-to-Collect-Rainwater-from-Houses/cpp-2086/CMakeLists.txt b/2001-2500/2086-Minimum-Number-of-Buckets-Required-to-Collect-Rainwater-from-Houses/cpp-2086/CMakeLists.txt new file mode 100644 index 00000000..3d936d76 --- /dev/null +++ b/2001-2500/2086-Minimum-Number-of-Buckets-Required-to-Collect-Rainwater-from-Houses/cpp-2086/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_2086) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2086 main.cpp) diff --git a/2001-2500/2086-Minimum-Number-of-Buckets-Required-to-Collect-Rainwater-from-Houses/cpp-2086/main.cpp b/2001-2500/2086-Minimum-Number-of-Buckets-Required-to-Collect-Rainwater-from-Houses/cpp-2086/main.cpp new file mode 100644 index 00000000..bb7730d9 --- /dev/null +++ b/2001-2500/2086-Minimum-Number-of-Buckets-Required-to-Collect-Rainwater-from-Houses/cpp-2086/main.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/minimum-number-of-buckets-required-to-collect-rainwater-from-houses/ +/// Author : liuyubobobo +/// Time : 2021-11-27 + +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int minimumBuckets(string s) { + + int n = s.size(); + int res = 0; + for(int i = 0; i < n; i ++) + if(s[i] == 'H'){ + if(i - 1 >= 0 && s[i - 1] == 'W') continue; + else if(i + 1 < n && s[i + 1] == '.'){s[i + 1] = 'W', res ++;} + else if(i - 1 >= 0 && s[i - 1] == '.'){s[i - 1] = 'W', res ++;} + else return -1; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2087-Minimum-Cost-Homecoming-of-a-Robot-in-a-Grid/cpp-2087/CMakeLists.txt b/2001-2500/2087-Minimum-Cost-Homecoming-of-a-Robot-in-a-Grid/cpp-2087/CMakeLists.txt new file mode 100644 index 00000000..15a2d509 --- /dev/null +++ b/2001-2500/2087-Minimum-Cost-Homecoming-of-a-Robot-in-a-Grid/cpp-2087/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_2087) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2087 main.cpp) diff --git a/2001-2500/2087-Minimum-Cost-Homecoming-of-a-Robot-in-a-Grid/cpp-2087/main.cpp b/2001-2500/2087-Minimum-Cost-Homecoming-of-a-Robot-in-a-Grid/cpp-2087/main.cpp new file mode 100644 index 00000000..e6639ff4 --- /dev/null +++ b/2001-2500/2087-Minimum-Cost-Homecoming-of-a-Robot-in-a-Grid/cpp-2087/main.cpp @@ -0,0 +1,49 @@ +/// Source : https://leetcode.com/problems/minimum-cost-homecoming-of-a-robot-in-a-grid/ +/// Author : liuyubobobo +/// Time : 2021-11-27 + +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(m + n) +/// Space Complexity: O(1) +class Solution { +public: + int minCost(vector& startPos, vector& homePos, + vector& rowCosts, vector& colCosts) { + + int res = 0; + + int x0 = startPos[0], x1 = homePos[0]; + if(x0 < x1) { + for (int i = x0 + 1; i <= x1; i ++) + res += rowCosts[i]; + } + if(x0 > x1){ + for (int i = x0 - 1; i >= x1; i --) + res += rowCosts[i]; + } + + int y0 = startPos[1], y1 = homePos[1]; + if(y0 < y1){ + for(int i = y0 + 1; i <= y1; i ++) + res += colCosts[i]; + } + if(y0 > y1){ + for(int i = y0 - 1; i >= y1; i --) + res += colCosts[i]; + } + + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2088-Count-Fertile-Pyramids-in-a-Land/cpp-2088/CMakeLists.txt b/2001-2500/2088-Count-Fertile-Pyramids-in-a-Land/cpp-2088/CMakeLists.txt new file mode 100644 index 00000000..5c7d391b --- /dev/null +++ b/2001-2500/2088-Count-Fertile-Pyramids-in-a-Land/cpp-2088/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_2088) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2088 main2.cpp) diff --git a/2001-2500/2088-Count-Fertile-Pyramids-in-a-Land/cpp-2088/main.cpp b/2001-2500/2088-Count-Fertile-Pyramids-in-a-Land/cpp-2088/main.cpp new file mode 100644 index 00000000..98122b45 --- /dev/null +++ b/2001-2500/2088-Count-Fertile-Pyramids-in-a-Land/cpp-2088/main.cpp @@ -0,0 +1,85 @@ +/// Source : https://leetcode.com/problems/count-fertile-pyramids-in-a-land/ +/// Author : liuyubobobo +/// Time : 2021-11-27 + +#include +#include + +using namespace std; + + +/// DP + Two Pointers +/// Time Complexity: O(R * C) +/// Space Complexity: O(R * C) +class Solution { +public: + int countPyramids(vector>& grid) { + + int R = grid.size(), C = grid[0].size(); + + vector> A(R, vector(C, 0)); + vector left(C, 0), right(C, 0); + for(int i = 0; i < R; i ++){ + left[0] = grid[i][0]; + for(int j = 1; j < C; j ++) + left[j] = (grid[i][j] ? left[j - 1] + 1 : 0); + + right[C - 1] = grid[i][C - 1]; + for(int j = C - 2; j >= 0; j --) + right[j] = (grid[i][j] ? right[j + 1] + 1 : 0); + + for(int j = 0; j < C; j ++) A[i][j] = min(left[j], right[j]); + } + +// for(int i = 0; i < R; i ++){ +// for(int j = 0; j < C; j ++) cout << A[i][j] << ' '; +// cout << '\n'; +// } + + int res = 0; + for(int j = 1; j + 1 < C; j ++){ + vector v(R); + for(int i = 0; i < R; i ++) v[i] = A[i][j]; + res += solve(R, v); + + reverse(v.begin(), v.end()); + res += solve(R, v); + } + + return res; + } + +private: + int solve(int n, const vector& v){ + + int res = 0; + for(int start = 0, end = 0; start < n; start ++){ + if(v[start] == 0) continue; + if(end < start) end = start; + while(end < n && v[end] >= end - start + 1) end ++; + if(end - start > 1) res += end - start - 1; + } + return res; + } +}; + +int main() { + + vector> grid1 = {{0, 1, 1, 0}, {1, 1, 1, 1}}; + cout << Solution().countPyramids(grid1) << endl; + // 2 + + vector> grid2 = {{1, 1, 1}, {1, 1, 1}}; + cout << Solution().countPyramids(grid2) << endl; + // 2 + + vector> grid3 = {{1, 0, 1}, {0, 0, 0}, {1, 0, 1}}; + cout << Solution().countPyramids(grid3) << endl; + // 0 + + vector> grid4 = {{1,1,1,1,0}, {1,1,1,1,1}, {1,1,1,1,1}, {0,1,0,0,1}}; + cout << Solution().countPyramids(grid4) << endl; + // 13 + + return 0; +} diff --git a/2001-2500/2088-Count-Fertile-Pyramids-in-a-Land/cpp-2088/main2.cpp b/2001-2500/2088-Count-Fertile-Pyramids-in-a-Land/cpp-2088/main2.cpp new file mode 100644 index 00000000..e73675f8 --- /dev/null +++ b/2001-2500/2088-Count-Fertile-Pyramids-in-a-Land/cpp-2088/main2.cpp @@ -0,0 +1,61 @@ +/// Source : https://leetcode.com/problems/count-fertile-pyramids-in-a-land/ +/// Author : liuyubobobo +/// Time : 2021-11-27 + +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(R * C) +/// Space Complexity: O(R * C) +class Solution { +public: + int countPyramids(vector>& grid) { + + int res = solve(grid); + reverse(grid.begin(), grid.end()); + res += solve(grid); + + return res; + } + +private: + int solve(vector>& g){ + + int R = g.size(), C = g[0].size(); + vector> dp(R, vector(C, 0)); + + int res = 0; + for(int i = R - 2; i >= 0; i --) + for(int j = 1; j + 1 < C; j ++){ + if(g[i][j] && g[i + 1][j - 1] && g[i + 1][j] && g[i + 1][j + 1]) + dp[i][j] = 1 + min(min(dp[i + 1][j - 1], dp[i + 1][j]), dp[i + 1][j + 1]); + res += dp[i][j]; + } + return res; + } +}; + +int main() { + + vector> grid1 = {{0, 1, 1, 0}, {1, 1, 1, 1}}; + cout << Solution().countPyramids(grid1) << endl; + // 2 + + vector> grid2 = {{1, 1, 1}, {1, 1, 1}}; + cout << Solution().countPyramids(grid2) << endl; + // 2 + + vector> grid3 = {{1, 0, 1}, {0, 0, 0}, {1, 0, 1}}; + cout << Solution().countPyramids(grid3) << endl; + // 0 + + vector> grid4 = {{1,1,1,1,0}, {1,1,1,1,1}, {1,1,1,1,1}, {0,1,0,0,1}}; + cout << Solution().countPyramids(grid4) << endl; + // 13 + + return 0; +} diff --git a/2001-2500/2089-Find-Target-Indices-After-Sorting-Array/cpp-2089/CMakeLists.txt b/2001-2500/2089-Find-Target-Indices-After-Sorting-Array/cpp-2089/CMakeLists.txt new file mode 100644 index 00000000..76479ef2 --- /dev/null +++ b/2001-2500/2089-Find-Target-Indices-After-Sorting-Array/cpp-2089/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main2.cpp) diff --git a/2001-2500/2089-Find-Target-Indices-After-Sorting-Array/cpp-2089/main.cpp b/2001-2500/2089-Find-Target-Indices-After-Sorting-Array/cpp-2089/main.cpp new file mode 100644 index 00000000..f1f08815 --- /dev/null +++ b/2001-2500/2089-Find-Target-Indices-After-Sorting-Array/cpp-2089/main.cpp @@ -0,0 +1,31 @@ +/// Source : https://leetcode.com/problems/find-target-indices-after-sorting-array/ +/// Author : liuyubobobo +/// Time : 2021-11-27 + +#include +#include + +using namespace std; + + +/// Sorting + Brute Force +/// Time Complexity: O(nlogn + n) +/// Space Complexity: O(1) +class Solution { +public: + vector targetIndices(vector& nums, int target) { + + sort(nums.begin(), nums.end()); + + vector res; + for(int i = 0; i < nums.size(); i ++) + if(nums[i] == target) res.push_back(i); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2089-Find-Target-Indices-After-Sorting-Array/cpp-2089/main2.cpp b/2001-2500/2089-Find-Target-Indices-After-Sorting-Array/cpp-2089/main2.cpp new file mode 100644 index 00000000..52cb0861 --- /dev/null +++ b/2001-2500/2089-Find-Target-Indices-After-Sorting-Array/cpp-2089/main2.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/find-target-indices-after-sorting-array/ +/// Author : liuyubobobo +/// Time : 2021-11-27 + +#include +#include + +using namespace std; + + +/// Sorting + Binary Search +/// Time Complexity: O(nlogn + n) +/// Space Complexity: O(1) +class Solution { +public: + vector targetIndices(vector& nums, int target) { + + sort(nums.begin(), nums.end()); + + int l = lower_bound(nums.begin(), nums.end(), target) - nums.begin(); + int r = upper_bound(nums.begin(), nums.end(), target) - nums.begin(); + + vector res; + for(int i = l; i < r; i ++) res.push_back(i); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2090-K-Radius-Subarray-Averages/cpp-2090/CMakeLists.txt b/2001-2500/2090-K-Radius-Subarray-Averages/cpp-2090/CMakeLists.txt new file mode 100644 index 00000000..3f98647f --- /dev/null +++ b/2001-2500/2090-K-Radius-Subarray-Averages/cpp-2090/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/2001-2500/2090-K-Radius-Subarray-Averages/cpp-2090/main.cpp b/2001-2500/2090-K-Radius-Subarray-Averages/cpp-2090/main.cpp new file mode 100644 index 00000000..a1177024 --- /dev/null +++ b/2001-2500/2090-K-Radius-Subarray-Averages/cpp-2090/main.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/k-radius-subarray-averages/ +/// Author : liuyubobobo +/// Time : 2021-11-27 + +#include +#include + +using namespace std; + + +/// Presum +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector getAverages(vector& nums, int k) { + + int n = nums.size(); + vector presum(n + 1, 0ll); + for(int i = 0; i < n; i ++) presum[i + 1] = presum[i] + nums[i]; + + vector res(n, -1); + for(int i = k; i + k < n; i ++) + res[i] = (presum[i + k + 1] - presum[i - k]) / (2ll * k + 1); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2091-Removing-Minimum-and-Maximum-From-Array/cpp-2091/CMakeLists.txt b/2001-2500/2091-Removing-Minimum-and-Maximum-From-Array/cpp-2091/CMakeLists.txt new file mode 100644 index 00000000..cad75f71 --- /dev/null +++ b/2001-2500/2091-Removing-Minimum-and-Maximum-From-Array/cpp-2091/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/2001-2500/2091-Removing-Minimum-and-Maximum-From-Array/cpp-2091/main.cpp b/2001-2500/2091-Removing-Minimum-and-Maximum-From-Array/cpp-2091/main.cpp new file mode 100644 index 00000000..9f51e47e --- /dev/null +++ b/2001-2500/2091-Removing-Minimum-and-Maximum-From-Array/cpp-2091/main.cpp @@ -0,0 +1,36 @@ +/// Source : https://leetcode.com/problems/removing-minimum-and-maximum-from-array/ +/// Author : liuyubobobo +/// Time : 2021-11-27 + +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int minimumDeletions(vector& nums) { + + int n = nums.size(); + if(n == 1) return 1; + + int a = min_element(nums.begin(), nums.end()) - nums.begin(); + int b = max_element(nums.begin(), nums.end()) - nums.begin(); + if(a > b) swap(a, b); + + int res = b + 1; + res = min(res, n - a); + res = min(res, a + 1 + n - b); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2092-Find-All-People-With-Secret/cpp-2092/CMakeLists.txt b/2001-2500/2092-Find-All-People-With-Secret/cpp-2092/CMakeLists.txt new file mode 100644 index 00000000..a0d16fe6 --- /dev/null +++ b/2001-2500/2092-Find-All-People-With-Secret/cpp-2092/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) diff --git a/2001-2500/2092-Find-All-People-With-Secret/cpp-2092/main.cpp b/2001-2500/2092-Find-All-People-With-Secret/cpp-2092/main.cpp new file mode 100644 index 00000000..8e7bb02a --- /dev/null +++ b/2001-2500/2092-Find-All-People-With-Secret/cpp-2092/main.cpp @@ -0,0 +1,119 @@ +/// Source : https://leetcode.com/problems/find-all-people-with-secret/ +/// Author : liuyubobobo +/// Time : 2021-11-27 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// UF + BFS +/// Time Complexity: O(n + m) +/// Space Complexity: O(n) +class UF{ + +private: + vector parent; + +public: + UF(int n) : parent(n){ + for(int i = 0 ; i < n ; i ++) + parent[i] = i; + } + + int find(int p){ + if(p != parent[p]) + parent[p] = find(parent[p]); + return parent[p]; + } + + bool is_connected(int p, int q){ + return find(p) == find(q); + } + + void union_elements(int p, int q){ + + int p_root = find(p), q_root = find(q); + + if(p_root == q_root) return; + + parent[p_root] = q_root; + } +}; + +class Solution { +public: + vector findAllPeople(int n, vector>& meetings, int firstPerson) { + + UF uf(n); + uf.union_elements(0, firstPerson); + + sort(meetings.begin(), meetings.end(), + [](const vector& v1, const vector& v2){ + return v1[2] < v2[2]; + }); + + for(int start = 0, i = 1; i <= meetings.size(); i ++) + if(i == meetings.size() || meetings[i][2] != meetings[start][2]){ + + set visited; + map> g; + for(int j = start; j < i; j ++){ + int u = meetings[j][0], v = meetings[j][1]; + g[u].insert(v), g[v].insert(u); + if(uf.is_connected(0, u)) visited.insert(u); + if(uf.is_connected(0, v)) visited.insert(v); + } + + queue q; + for(int u: visited) q.push(u); + while(!q.empty()){ + int u = q.front(); q.pop(); + for(int v: g[u]) + if(!visited.count(v)){ + q.push(v); + visited.insert(v); + } + } + + for(int u: visited) uf.union_elements(0, u); + + start = i; + } + + vector res; + for(int i = 0; i < n; i ++) + if(uf.is_connected(0, i)) res.push_back(i); + return res; + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << ' '; cout << '\n'; +} + +int main() { + + vector> meetings1 = {{1, 2, 5}, {2, 3, 8}, {1, 5, 10}}; + print_vec(Solution().findAllPeople(6, meetings1, 1) ); + // 0 1 2 3 5 + + vector> meetings2 = {{3, 1, 3}, {1, 2, 2}, {0, 3, 3}}; + print_vec(Solution().findAllPeople(4, meetings2, 3) ); + // 0 1 3 + + vector> meetings3 = {{3, 4, 2}, {1, 2, 1}, {2, 3, 1}}; + print_vec(Solution().findAllPeople(5, meetings3, 1) ); + // 0 1 2 3 4 + + vector> meetings4 = {{0, 2, 1}, {1, 3, 1}, {4, 5, 1}}; + print_vec(Solution().findAllPeople(6, meetings4, 1) ); + // 0 1 2 3 + + return 0; +} diff --git a/2001-2500/2093-Minimum-Cost-to-Reach-City-With-Discounts/cpp-2093/CMakeLists.txt b/2001-2500/2093-Minimum-Cost-to-Reach-City-With-Discounts/cpp-2093/CMakeLists.txt new file mode 100644 index 00000000..d168fa2d --- /dev/null +++ b/2001-2500/2093-Minimum-Cost-to-Reach-City-With-Discounts/cpp-2093/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_2093) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2093 main.cpp) diff --git a/2001-2500/2093-Minimum-Cost-to-Reach-City-With-Discounts/cpp-2093/main.cpp b/2001-2500/2093-Minimum-Cost-to-Reach-City-With-Discounts/cpp-2093/main.cpp new file mode 100644 index 00000000..32c91467 --- /dev/null +++ b/2001-2500/2093-Minimum-Cost-to-Reach-City-With-Discounts/cpp-2093/main.cpp @@ -0,0 +1,63 @@ +/// Source : https://leetcode.com/problems/minimum-cost-to-reach-city-with-discounts/ +/// Author : liuyubobobo +/// Time : 2021-12-03 + +#include +#include +#include + +using namespace std; + + +/// Dijkstra +/// Time Complexity: O(discount * E * log(discount * E)) +/// Space Complexity: O(discount * V) +class Solution { +public: + int minimumCost(int n, vector>& highways, int discounts) { + + vector>> g(n); + for(const vector& e: highways){ + int u = e[0], v = e[1], w = e[2]; + g[u].push_back({v, w}), g[v].push_back({u, w}); + } + + vector> dis(discounts + 1, vector(n, INT_MAX / 2)); + vector> visited(discounts + 1, vector(n, false)); + + // dis, {discount, u} + priority_queue>, vector>>, greater>>> pq; + pq.push({0, {discounts, 0}}); + while(!pq.empty()){ + int d = pq.top().first; + int discount = pq.top().second.first, u = pq.top().second.second; + pq.pop(); + + if(visited[discount][u]) continue; + visited[discount][u] = true; + + for(const pair& p: g[u]){ + int v = p.first, w = p.second; + if(d + w < dis[discount][v]){ + dis[discount][v] = d + w; + pq.push({d + w, {discount, v}}); + } + if(discount && d + w / 2 < dis[discount - 1][v]){ + dis[discount - 1][v] = d + w / 2; + pq.push({d + w / 2, {discount - 1, v}}); + } + } + } + + int res = INT_MAX / 2; + for(int discount = 0; discount <= discounts; discount ++) + res = min(res, dis[discount][n - 1]); + return res == INT_MAX / 2 ? -1 : res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2094-Finding-3-Digit-Even-Numbers/cpp-2094/CMakeLists.txt b/2001-2500/2094-Finding-3-Digit-Even-Numbers/cpp-2094/CMakeLists.txt new file mode 100644 index 00000000..74b3bc2c --- /dev/null +++ b/2001-2500/2094-Finding-3-Digit-Even-Numbers/cpp-2094/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main2.cpp) diff --git a/2001-2500/2094-Finding-3-Digit-Even-Numbers/cpp-2094/main.cpp b/2001-2500/2094-Finding-3-Digit-Even-Numbers/cpp-2094/main.cpp new file mode 100644 index 00000000..0ed53368 --- /dev/null +++ b/2001-2500/2094-Finding-3-Digit-Even-Numbers/cpp-2094/main.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/finding-3-digit-even-numbers/ +/// Author : liuyubobobo +/// Time : 2021-12-04 + +#include +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n^3) +/// Space Complexity: O(1) +class Solution { +public: + vector findEvenNumbers(vector& d) { + + int n = d.size(); + + set res; + for(int i = 0; i < n; i ++) + for(int j = i + 1; j < n; j ++) + for(int k = j + 1; k < n; k ++){ + if(d[i]){ + if(d[k] % 2 == 0) res.insert(d[i] * 100 + d[j] * 10 + d[k]); + if(d[j] % 2 == 0) res.insert(d[i] * 100 + d[k] * 10 + d[j]); + } + if(d[j]){ + if(d[k] % 2 == 0) res.insert(d[j] * 100 + d[i] * 10 + d[k]); + if(d[i] % 2 == 0) res.insert(d[j] * 100 + d[k] * 10 + d[i]); + } + if(d[k]){ + if(d[j] % 2 == 0) res.insert(d[k] * 100 + d[i] * 10 + d[j]); + if(d[i] % 2 == 0) res.insert(d[k] * 100 + d[j] * 10 + d[i]); + } + } + + return vector(res.begin(), res.end()); + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2094-Finding-3-Digit-Even-Numbers/cpp-2094/main2.cpp b/2001-2500/2094-Finding-3-Digit-Even-Numbers/cpp-2094/main2.cpp new file mode 100644 index 00000000..8f816260 --- /dev/null +++ b/2001-2500/2094-Finding-3-Digit-Even-Numbers/cpp-2094/main2.cpp @@ -0,0 +1,41 @@ +/// Source : https://leetcode.com/problems/finding-3-digit-even-numbers/ +/// Author : liuyubobobo +/// Time : 2021-12-04 + +#include +#include +#include + +using namespace std; + + +/// Check every even number between [100, 999] +/// Time Complexity: O(999) +/// Space Complexity: O(1) +class Solution { +public: + vector findEvenNumbers(vector& d) { + + vector f(10, 0); + for(int e: d) f[e] ++; + + vector curf(10, 0), res; + for(int i = 100; i <= 999; i += 2){ + fill(curf.begin(), curf.end(), 0); + int x = i; + while(x) curf[x % 10] ++, x /= 10; + + bool ok = true; + for(int i = 0; i < 10; i ++) + if(curf[i] > f[i]){ok = false; break;} + if(ok) res.push_back(i); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2095-Delete-the-Middle-Node-of-a-Linked-List/cpp-2095/CMakeLists.txt b/2001-2500/2095-Delete-the-Middle-Node-of-a-Linked-List/cpp-2095/CMakeLists.txt new file mode 100644 index 00000000..029d64e5 --- /dev/null +++ b/2001-2500/2095-Delete-the-Middle-Node-of-a-Linked-List/cpp-2095/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main2.cpp) diff --git a/2001-2500/2095-Delete-the-Middle-Node-of-a-Linked-List/cpp-2095/main.cpp b/2001-2500/2095-Delete-the-Middle-Node-of-a-Linked-List/cpp-2095/main.cpp new file mode 100644 index 00000000..133363b6 --- /dev/null +++ b/2001-2500/2095-Delete-the-Middle-Node-of-a-Linked-List/cpp-2095/main.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/delete-the-middle-node-of-a-linked-list/ +/// Author : liuyubobobo +/// Time : 2021-12-04 + +#include +#include + +using namespace std; + + +/// Two Pass +/// Time Complexity: O(n) +/// Space Complexity: O(1) + +/// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode() : val(0), next(nullptr) {} + ListNode(int x) : val(x), next(nullptr) {} + ListNode(int x, ListNode *next) : val(x), next(next) {} +}; + +class Solution { +public: + ListNode* deleteMiddle(ListNode* head) { + + int len = 0; + ListNode* cur = head; + while(cur) len ++, cur = cur->next; + + int x = len / 2; + ListNode* dummy_head = new ListNode(-1, head); + cur = dummy_head; + for(int i = 0; i < x; i ++) cur = cur -> next; + + cur->next = cur->next->next; + + return dummy_head->next; + } +}; + +int main() { + + return 0; +} diff --git a/2001-2500/2095-Delete-the-Middle-Node-of-a-Linked-List/cpp-2095/main2.cpp b/2001-2500/2095-Delete-the-Middle-Node-of-a-Linked-List/cpp-2095/main2.cpp new file mode 100644 index 00000000..0e5b7b50 --- /dev/null +++ b/2001-2500/2095-Delete-the-Middle-Node-of-a-Linked-List/cpp-2095/main2.cpp @@ -0,0 +1,45 @@ +/// Source : https://leetcode.com/problems/delete-the-middle-node-of-a-linked-list/ +/// Author : liuyubobobo +/// Time : 2021-12-04 + +#include +#include + +using namespace std; + + +/// One Pass +/// Time Complexity: O(n) +/// Space Complexity: O(1) + +/// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode() : val(0), next(nullptr) {} + ListNode(int x) : val(x), next(nullptr) {} + ListNode(int x, ListNode *next) : val(x), next(next) {} +}; + +class Solution { +public: + ListNode* deleteMiddle(ListNode* head) { + + ListNode* dummy_head = new ListNode(-1, head); + ListNode* fast = head, *slow = dummy_head; + + while(fast && fast->next){ + fast = fast->next; + if(fast) fast = fast->next; + slow = slow->next; + } + slow->next = slow->next->next; + + return dummy_head->next; + } +}; + +int main() { + + return 0; +} diff --git a/2001-2500/2096-Step-By-Step-Directions-From-a-Binary-Tree-Node-to-Another/cpp-2096/CMakeLists.txt b/2001-2500/2096-Step-By-Step-Directions-From-a-Binary-Tree-Node-to-Another/cpp-2096/CMakeLists.txt new file mode 100644 index 00000000..e85d4767 --- /dev/null +++ b/2001-2500/2096-Step-By-Step-Directions-From-a-Binary-Tree-Node-to-Another/cpp-2096/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main2.cpp) diff --git a/2001-2500/2096-Step-By-Step-Directions-From-a-Binary-Tree-Node-to-Another/cpp-2096/main.cpp b/2001-2500/2096-Step-By-Step-Directions-From-a-Binary-Tree-Node-to-Another/cpp-2096/main.cpp new file mode 100644 index 00000000..2fef2f5e --- /dev/null +++ b/2001-2500/2096-Step-By-Step-Directions-From-a-Binary-Tree-Node-to-Another/cpp-2096/main.cpp @@ -0,0 +1,102 @@ +/// Source : https://leetcode.com/problems/step-by-step-directions-from-a-binary-tree-node-to-another/ +/// Author : liuyubobobo +/// Time : 2021-12-04 + +#include +#include +#include + +using namespace std; + + +/// BFS +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// 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: + string getDirections(TreeNode* root, int s, int t) { + + int n = sz(root); + + vector>> g(n + 1); + dfs(root, g); + + vector> pre(n + 1, {-1, ' '}); + queue q; + q.push(s); + pre[s] = {s, ' '}; + while(!q.empty()){ + int u = q.front(); + q.pop(); + + if(u == t) break; + + for(const pair& p: g[u]){ + int v = p.first; + if(pre[v].first == -1){ + pre[v] = {u, p.second}; + q.push(v); + } + } + } + + string res = ""; + int cur = t; + while(pre[cur].first != cur){ + res += pre[cur].second; + cur = pre[cur].first; + } + reverse(res.begin(), res.end()); + return res; + } + +private: + void dfs(TreeNode* node, vector>>& g){ + + if(!node) return; + + if(node->left){ + g[node->val].push_back({node->left->val, 'L'}); + g[node->left->val].push_back({node->val, 'U'}); + } + if(node->right){ + g[node->val].push_back({node->right->val, 'R'}); + g[node->right->val].push_back({node->val, 'U'}); + } + + dfs(node->left, g); + dfs(node->right, g); + } + + int sz(TreeNode* node){ + + if(!node) return 0; + + int res = 1; + if(node->left) res += sz(node->left); + if(node->right) res += sz(node->right); + return res; + } +}; + +int main() { + + TreeNode* left = new TreeNode(1, new TreeNode(3), nullptr); + TreeNode* right = new TreeNode(2, new TreeNode(6), new TreeNode(4)); + TreeNode* root = new TreeNode(5, left, right); + cout << Solution().getDirections(root, 3, 6) << endl; + // UURL + + return 0; +} diff --git a/2001-2500/2096-Step-By-Step-Directions-From-a-Binary-Tree-Node-to-Another/cpp-2096/main2.cpp b/2001-2500/2096-Step-By-Step-Directions-From-a-Binary-Tree-Node-to-Another/cpp-2096/main2.cpp new file mode 100644 index 00000000..09e143b8 --- /dev/null +++ b/2001-2500/2096-Step-By-Step-Directions-From-a-Binary-Tree-Node-to-Another/cpp-2096/main2.cpp @@ -0,0 +1,76 @@ +/// Source : https://leetcode.com/problems/step-by-step-directions-from-a-binary-tree-node-to-another/ +/// Author : liuyubobobo +/// Time : 2021-12-04 + +#include +#include +#include + +using namespace std; + + +/// LCA +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// 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: + string getDirections(TreeNode* root, int s, int t) { + + root = lca(root, s, t); + + string path1 = "", path2 = ""; + get_path(root, s, path1); + get_path(root, t, path2); + return string(path1.size(), 'U') + path2; + } + +private: + bool get_path(TreeNode* node, int x, string& path){ + + if(!node) return false; + if(node->val == x) return true; + + path += "L"; + if(get_path(node->left, x, path)) return true; + + path.back() = 'R'; + if(get_path(node->right, x, path)) return true; + path.pop_back(); + + return false; + } + + TreeNode* lca(TreeNode* node, int a, int b){ + + if(!node) return nullptr; + if(node->val == a || node->val == b) return node; + + TreeNode* l = lca(node->left, a, b); + TreeNode* r = lca(node->right, a, b); + if(l && r) return node; + return l ? l : r; + } +}; + + +int main() { + + TreeNode* left = new TreeNode(1, new TreeNode(3), nullptr); + TreeNode* right = new TreeNode(2, new TreeNode(6), new TreeNode(4)); + TreeNode* root = new TreeNode(5, left, right); + cout << Solution().getDirections(root, 3, 6) << endl; + // UURL + + return 0; +} diff --git a/2001-2500/2097-Valid-Arrangement-of-Pairs/cpp-2097/CMakeLists.txt b/2001-2500/2097-Valid-Arrangement-of-Pairs/cpp-2097/CMakeLists.txt new file mode 100644 index 00000000..9031340e --- /dev/null +++ b/2001-2500/2097-Valid-Arrangement-of-Pairs/cpp-2097/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) diff --git a/2001-2500/2097-Valid-Arrangement-of-Pairs/cpp-2097/main.cpp b/2001-2500/2097-Valid-Arrangement-of-Pairs/cpp-2097/main.cpp new file mode 100644 index 00000000..fba12beb --- /dev/null +++ b/2001-2500/2097-Valid-Arrangement-of-Pairs/cpp-2097/main.cpp @@ -0,0 +1,78 @@ +/// Source : https://leetcode.com/problems/valid-arrangement-of-pairs/ +/// Author : liuyubobobo +/// Time : 2021-12-05 + +#include +#include +#include +#include + +using namespace std; + + +/// Hierholzer’s Algorithm +/// Time Complexity: O(V + E) +/// Space Complexity: O(V + E) +class Solution { +public: + vector> validArrangement(vector>& pairs) { + + unordered_map> g; + unordered_map in_degrees; + for(const vector& p: pairs){ + g[p[0]].push_back(p[1]); + in_degrees[p[1]] ++; + } + + int s = g.begin()->first; + for(const pair>& p: g) + if(p.second.size() - in_degrees[p.first] == 1){ + s = p.first; + break; + } + + vector res; + + stack stack; + int curv = s; + stack.push(curv); + while(!stack.empty()){ + if(g[stack.top()].size()){ + int u = stack.top(), v = g[u].back(); + stack.push(v); + g[u].pop_back(); + } + else{ + res.push_back(stack.top()); + stack.pop(); + } + } + + vector> ret; + for(int i = res.size() - 1; i >= 1; i --) + ret.push_back({res[i], res[i - 1]}); + return ret; + } +}; + + +void print_vec(const vector>& v){ + + for(const vector& p: v) + cout << "(" << p[0] << "," << p[1] << ")"; + cout << endl; +} + +int main() { + + vector> pairs1 = {{5, 1}, {4, 5}, {11, 9}, {9, 4}}; + print_vec(Solution().validArrangement(pairs1)); + + vector> pairs2 = {{1, 3}, {3, 2}, {2, 1}}; + print_vec(Solution().validArrangement(pairs2)); + + vector> pairs3 = {{1, 2}, {1, 3}, {2, 1}}; + print_vec(Solution().validArrangement(pairs3)); + + return 0; +} diff --git a/2001-2500/2098-Subsequence-of-Size-K-With-the-Largest-Even-Sum/cpp-2098/CMakeLists.txt b/2001-2500/2098-Subsequence-of-Size-K-With-the-Largest-Even-Sum/cpp-2098/CMakeLists.txt new file mode 100644 index 00000000..c848ea8f --- /dev/null +++ b/2001-2500/2098-Subsequence-of-Size-K-With-the-Largest-Even-Sum/cpp-2098/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_2098) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2098 main.cpp) diff --git a/2001-2500/2098-Subsequence-of-Size-K-With-the-Largest-Even-Sum/cpp-2098/main.cpp b/2001-2500/2098-Subsequence-of-Size-K-With-the-Largest-Even-Sum/cpp-2098/main.cpp new file mode 100644 index 00000000..1a66429c --- /dev/null +++ b/2001-2500/2098-Subsequence-of-Size-K-With-the-Largest-Even-Sum/cpp-2098/main.cpp @@ -0,0 +1,59 @@ +/// Source : https://leetcode.com/problems/subsequence-of-size-k-with-the-largest-even-sum/ +/// Author : liuyubobobo +/// Time : 2021-12-11 + +#include +#include + +using namespace std; + + +/// Sorting +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + long long largestEvenSum(vector& nums, int k) { + + vector odd, even; + for(int e: nums) + if(e % 2) odd.push_back(e); + else even.push_back(e); + + sort(odd.begin(), odd.end(), greater()); + sort(even.begin(), even.end(), greater()); + + vector odd_presum(odd.size() + 1, 0), even_presum(even.size() + 1, 0); + for(int i = 0; i < odd.size(); i ++) + odd_presum[i + 1] = odd_presum[i] + odd[i]; + for(int i = 0; i < even.size(); i ++) + even_presum[i + 1] = even_presum[i] + even[i]; + + long long res = -1; + for(int odd_num = 0; odd_num <= odd.size(); odd_num += 2){ + int even_num = k - odd_num; + if(even_num < 0 || even_num > even.size()) continue; + + res = max(res, odd_presum[odd_num] + even_presum[even_num]); + } + return res; + } +}; + + +int main() { + + vector nums1 = {4, 1, 5, 3, 1}; + cout << Solution().largestEvenSum(nums1, 3) << endl; + // 12 + + vector nums2 = {4, 6, 2}; + cout << Solution().largestEvenSum(nums2, 3) << endl; + // 12 + + vector nums3 = {1, 3, 5}; + cout << Solution().largestEvenSum(nums3, 1) << endl; + // -1 + + return 0; +} diff --git a/2001-2500/2099-Find-Subsequence-of-Length-K-With-the-Largest-Sum/cpp-2099/CMakeLists.txt b/2001-2500/2099-Find-Subsequence-of-Length-K-With-the-Largest-Sum/cpp-2099/CMakeLists.txt new file mode 100644 index 00000000..892bf351 --- /dev/null +++ b/2001-2500/2099-Find-Subsequence-of-Length-K-With-the-Largest-Sum/cpp-2099/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_2099) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2099 main.cpp) diff --git a/2001-2500/2099-Find-Subsequence-of-Length-K-With-the-Largest-Sum/cpp-2099/main.cpp b/2001-2500/2099-Find-Subsequence-of-Length-K-With-the-Largest-Sum/cpp-2099/main.cpp new file mode 100644 index 00000000..6a6debb0 --- /dev/null +++ b/2001-2500/2099-Find-Subsequence-of-Length-K-With-the-Largest-Sum/cpp-2099/main.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/find-subsequence-of-length-k-with-the-largest-sum/ +/// Author : liuyubobobo +/// Time : 2021-12-11 + +#include +#include + +using namespace std; + + +/// Sorting +/// Time Complexity: O(nlogn + klogk) +/// Space Complexity: O(n) +class Solution { +public: + vector maxSubsequence(vector& nums, int k) { + + vector> data(nums.size()); + for(int i = 0; i < nums.size(); i ++) data[i] = {nums[i], i}; + + sort(data.begin(), data.end(), greater>()); + while(data.size() > k) data.pop_back(); + + sort(data.begin(), data.end(), + [](const pair& p1, const pair& p2){ + return p1.second < p2.second; + }); + + vector res(k); + for(int i = 0; i < k; i ++) + res[i] = data[i].first; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2100-Find-Good-Days-to-Rob-the-Bank/cpp-2100/CMakeLists.txt b/2001-2500/2100-Find-Good-Days-to-Rob-the-Bank/cpp-2100/CMakeLists.txt new file mode 100644 index 00000000..b837f0a2 --- /dev/null +++ b/2001-2500/2100-Find-Good-Days-to-Rob-the-Bank/cpp-2100/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_2100) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2100 main.cpp) diff --git a/2001-2500/2100-Find-Good-Days-to-Rob-the-Bank/cpp-2100/main.cpp b/2001-2500/2100-Find-Good-Days-to-Rob-the-Bank/cpp-2100/main.cpp new file mode 100644 index 00000000..f220332c --- /dev/null +++ b/2001-2500/2100-Find-Good-Days-to-Rob-the-Bank/cpp-2100/main.cpp @@ -0,0 +1,60 @@ +/// Source : https://leetcode.com/problems/find-good-days-to-rob-the-bank/ +/// Author : liuyubobobo +/// Time : 2021-12-12 + +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector goodDaysToRobBank(vector& security, int time) { + + int n = security.size(); + + vector a(n, 1), b(n, 1); + for(int i = 1; i < n; i ++) + if(security[i] <= security[i - 1]) a[i] = a[i - 1] + 1; +// for(int e: a) cout << e << ' '; cout << '\n'; + + for(int i = n - 2; i >= 0; i --) + if(security[i] <= security[i + 1]) b[i] = b[i + 1] + 1; +// for(int e: b) cout << e << ' '; cout << '\n'; + + vector res; + for(int i = 0; i < n; i ++) + if(a[i] >= time + 1 && b[i] >= time + 1) res.push_back(i); + return res; + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << ' '; cout << '\n'; +} + +int main() { + + vector security1 = {5, 3, 3, 3, 5, 6, 2}; + print_vec(Solution().goodDaysToRobBank(security1, 2)); + // 2 3 + + vector security2 = {1, 1, 1, 1, 1}; + print_vec(Solution().goodDaysToRobBank(security2, 0)); + // 0 1 2 3 4 + + vector security3 = {1, 2, 3, 4, 5, 6}; + print_vec(Solution().goodDaysToRobBank(security3, 2)); + // empty + + vector security4 = {1}; + print_vec(Solution().goodDaysToRobBank(security4, 5)); + // empty + + return 0; +} diff --git a/2001-2500/2101-Detonate-the-Maximum-Bombs/cpp-2101/CMakeLists.txt b/2001-2500/2101-Detonate-the-Maximum-Bombs/cpp-2101/CMakeLists.txt new file mode 100644 index 00000000..40ff3fb6 --- /dev/null +++ b/2001-2500/2101-Detonate-the-Maximum-Bombs/cpp-2101/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_2101) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2101 main.cpp) diff --git a/2001-2500/2101-Detonate-the-Maximum-Bombs/cpp-2101/main.cpp b/2001-2500/2101-Detonate-the-Maximum-Bombs/cpp-2101/main.cpp new file mode 100644 index 00000000..7c3d833e --- /dev/null +++ b/2001-2500/2101-Detonate-the-Maximum-Bombs/cpp-2101/main.cpp @@ -0,0 +1,55 @@ +/// Source : https://leetcode.com/problems/detonate-the-maximum-bombs/ +/// Author : liuyubobobo +/// Time : 2021-12-12 + +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n^3) +/// Space Complexity: O(n^2) +class Solution { +public: + int maximumDetonation(vector>& bombs) { + + int n = bombs.size(); + + vector> g(n); + for(int i = 0; i < n; i ++) + for(int j = 0; j < n; j ++){ + if(i == j) continue; + if(dis_sq(bombs[i][0], bombs[i][1], bombs[j][0], bombs[j][1]) <= (long long)bombs[i][2] * bombs[i][2]) + g[i].push_back(j); + } + + int res = 1; + for(int i = 0; i < n; i ++){ + vector visited(n, false); + res = max(res, dfs(g, i, visited)); + } + return res; + } + +private: + int dfs(const vector>& g, int u, vector& visited){ + + visited[u] = true; + int res = 1; + for(int v: g[u]) + if(!visited[v]) res += dfs(g, v, visited); + return res; + } + + long long dis_sq(long long x1, long long y1, long long x2, long long y2){ + return (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2); + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2102-Sequentially-Ordinal-Rank-Tracker/cpp-2102/CMakeLists.txt b/2001-2500/2102-Sequentially-Ordinal-Rank-Tracker/cpp-2102/CMakeLists.txt new file mode 100644 index 00000000..599acd05 --- /dev/null +++ b/2001-2500/2102-Sequentially-Ordinal-Rank-Tracker/cpp-2102/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_2102) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2102 main.cpp) diff --git a/2001-2500/2102-Sequentially-Ordinal-Rank-Tracker/cpp-2102/main.cpp b/2001-2500/2102-Sequentially-Ordinal-Rank-Tracker/cpp-2102/main.cpp new file mode 100644 index 00000000..cd3e6f37 --- /dev/null +++ b/2001-2500/2102-Sequentially-Ordinal-Rank-Tracker/cpp-2102/main.cpp @@ -0,0 +1,327 @@ +/// Source : https://leetcode.com/problems/sequentially-ordinal-rank-tracker/ +/// Author : liuyubobobo +/// Time : 2021-12-12 + +#include + +using namespace std; + + +/// Using AVLTree +/// Time Complexity: init: O(1) +/// add: O(logn) +/// query: O(logn) +/// Space Complexity: O(n) +template +class AVLTreeSet{ + +private: + class Node{ + public: + Key key; + Node *left = nullptr, *right = nullptr; + int height = 1, size = 1; + + Node(const Key& key): key(key){} + }; + + Node* root = nullptr; + +public: + AVLTreeSet(){} + + int size(){ + return size(root); + } + + void add(const Key& key){ + root = add(root, key); + } + + void remove(const Key& key){ + root = remove(root, key); + } + + bool contains(const Key& key){ + return get_node(root, key) != nullptr; + } + + // 0-based rank + int get_index(const Key& key){ + + Node* node = get_node(root, key); + assert(node); + + return size_less_than(key); + } + + // 0-based select + Key select(int index){ + + assert(index < size(root)); + return select(root, index); + } + + // < key 的元素有几个? + int size_less_than(const Key& key){ + return size_less_than(root, key); + } + + // <= key 的元素有几个? + int size_less_than_or_equal_to(const Key& key){ + return size_less_than_or_equal_to(root, key); + } + + // > key 的元素有几个? + int size_larger_than(const Key& key){ + return size_larger_than(root, key); + } + + // >= key 的元素有几个? + int size_larger_than_or_equal_to(const Key& key){ + return size_larger_than_or_equal_to(root, key); + } + +private: + int size(Node* node){ + return node ? node->size : 0; + } + + int height(Node* node){ + return node ? node->height : 0; + } + + int get_balance_factor(Node* node){ + return height(node->left) - height(node->right); + } + + Node* right_rotate(Node* y) { + Node* x = y->left; + Node* T3 = x->right; + + // 向右旋转过程 + x->right = y; + y->left = T3; + + // 更新 height 和 size + y->height = max(height(y->left), height(y->right)) + 1; + x->height = max(height(x->left), height(x->right)) + 1; + + y->size = size(y->left) + size(y->right) + 1; + x->size = size(x->left) + size(x->right) + 1; + + return x; + } + + Node* left_rotate(Node* y) { + Node* x = y->right; + Node* T2 = x->left; + + // 向左旋转过程 + x->left = y; + y->right = T2; + + // 更新 height 和 size + y->height = max(height(y->left), height(y->right)) + 1; + x->height = max(height(x->left), height(x->right)) + 1; + + y->size = size(y->left) + size(y->right) + 1; + x->size = size(x->left) + size(x->right) + 1; + + return x; + } + + // 向以node为根的二分搜索树中插入元素(key, value),递归算法 + // 返回插入新节点后二分搜索树的根 + Node* add(Node* node, const Key& key){ + + if(node == nullptr) + return new Node(key); + + if(key < node->key) + node->left = add(node->left, key); + else if(key > node->key) + node->right = add(node->right, key); + else + return node; + + return keep_balance(node); + } + + Node* remove(Node* node, const Key& key){ + + if(node == nullptr) + return nullptr; + + Node* ret_node; + if(key < node->key){ + node->left = remove(node->left, key); + ret_node = node; + } + else if(key > node->key){ + node->right = remove(node->right, key); + ret_node = node; + } + else{ + + // 待删除节点左子树为空的情况 + if(node->left == nullptr){ + Node* right_node = node->right; + node->right = nullptr; + ret_node = right_node; + } + // 待删除节点右子树为空的情况 + else if(node->right == nullptr){ + Node* left_node = node->left; + node->left = nullptr; + ret_node = left_node; + } + // 待删除节点左右子树均不为空的情况 + else{ + // 找到比待删除节点大的最小节点, 即待删除节点右子树的最小节点 + // 用这个节点顶替待删除节点的位置 + Node* min_node = get_min_node(node->right); + assert(min_node); + node->key = min_node->key; + + node->right = remove_min(node->right); + ret_node = node; + } + } + + return keep_balance(ret_node); + } + + Node* remove_min(Node* node){ + + if(node == nullptr) + return nullptr; + + Node* ret_node; + if(node->left) { + node->left = remove_min(node->left); + ret_node = node; + } + else + ret_node = node->right; + + return keep_balance(ret_node); + } + + Node* get_min_node(Node* node){ + + if(!node) return nullptr; + + if(node->left) return get_min_node(node->left); + return node; + } + + Node* keep_balance(Node* node){ + + if(!node) return nullptr; + + // 更新 height 和 size + node->height = 1 + max(height(node->left), height(node->right)); + node->size = 1 + size(node->left) + size(node->right); + + // 计算平衡因子 + int balance_factor = get_balance_factor(node); + + // 平衡维护 + // LL + if (balance_factor > 1 && get_balance_factor(node->left) >= 0) + return right_rotate(node); + + // RR + if (balance_factor < -1 && get_balance_factor(node->right) <= 0) + return left_rotate(node); + + // LR + if (balance_factor > 1 && get_balance_factor(node->left) < 0) { + node->left = left_rotate(node->left); + return right_rotate(node); + } + + // RL + if (balance_factor < -1 && get_balance_factor(node->right) > 0) { + node->right = right_rotate(node->right); + return left_rotate(node); + } + + return node; + } + + Node* get_node(Node* node, const Key& key){ + + if(node == nullptr) + return nullptr; + + if(key == node->key) + return node; + else if(key < node->key) + return get_node(node->left, key); + else + return get_node(node->right, key); + } + + Key select(Node* node, int index){ + + if(index < size(node->left)) return select(node->left, index); + + if(index == size(node->left)) return node->key; + + return select(node->right, index - size(node->left) - 1); + } + + // < key 的元素有几个 + int size_less_than(Node* node, const Key& key){ + if(!node) return 0; + if(key <= node->key) return size_less_than(node->left, key); + return size(node->left) + 1 + size_less_than(node->right, key); + } + + // <= key 的元素有几个 + int size_less_than_or_equal_to(Node* node, const Key& key){ + if(!node) return 0; + if(key < node->key) return size_less_than_or_equal_to(node->left, key); + return size(node->left) + 1 + size_less_than_or_equal_to(node->right, key); + } + + // > key 的元素有几个 + int size_larger_than(Node* node, const Key& key){ + if(!node) return 0; + if(key >= node->key) return size_larger_than(node->right, key); + return size_larger_than(node->left, key) + 1 + size(node->right); + } + + // >= key 的元素有几个 + int size_larger_than_or_equal_to(Node* node, const Key& key){ + if(!node) return 0; + if(key > node->key) return size_larger_than_or_equal_to(node->right, key); + return size_larger_than_or_equal_to(node->left, key) + 1 + size(node->right); + } +}; + +class SORTracker { + +private: + AVLTreeSet> tree; + int time; + +public: + SORTracker() : time(0) {} + + void add(string name, int score) { + tree.add({-score, name}); + } + + string get() { + return tree.select(time ++).second; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2103-Rings-and-Rods/cpp-2103/CMakeLists.txt b/2001-2500/2103-Rings-and-Rods/cpp-2103/CMakeLists.txt new file mode 100644 index 00000000..2ae8397c --- /dev/null +++ b/2001-2500/2103-Rings-and-Rods/cpp-2103/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/2001-2500/2103-Rings-and-Rods/cpp-2103/main.cpp b/2001-2500/2103-Rings-and-Rods/cpp-2103/main.cpp new file mode 100644 index 00000000..0645d92b --- /dev/null +++ b/2001-2500/2103-Rings-and-Rods/cpp-2103/main.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/rings-and-rods/ +/// Author : liuyubobobo +/// Time : 2021-12-11 + +#include +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int countPoints(string rings) { + + vector> poles(10); + for(int i = 0; i < rings.size(); i += 2) + poles[rings[i + 1] - '0'].insert(rings[i]); + + int res = 0; + for(int i = 0; i < 10; i ++) + res += poles[i].size() == 3; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2104-Sum-of-Subarray-Ranges/cpp-2104/CMakeLists.txt b/2001-2500/2104-Sum-of-Subarray-Ranges/cpp-2104/CMakeLists.txt new file mode 100644 index 00000000..084dd354 --- /dev/null +++ b/2001-2500/2104-Sum-of-Subarray-Ranges/cpp-2104/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main2.cpp) diff --git a/2001-2500/2104-Sum-of-Subarray-Ranges/cpp-2104/main.cpp b/2001-2500/2104-Sum-of-Subarray-Ranges/cpp-2104/main.cpp new file mode 100644 index 00000000..8928008c --- /dev/null +++ b/2001-2500/2104-Sum-of-Subarray-Ranges/cpp-2104/main.cpp @@ -0,0 +1,74 @@ +/// Source : https://leetcode.com/problems/sum-of-subarray-ranges/ +/// Author : liuyubobobo +/// Time : 2021-12-11 + +#include +#include + +using namespace std; + + +/// ST +/// Time Complexity: O(nlogn + n^2) +/// Space Complexity: O(n) +template +class SparseTable{ + +private: + int n; + vector> table; + vector log2; + T (*combine)(T a, T b); + +public: + SparseTable(const vector& data, T (*combine)(T a, T b)): n(data.size()), log2(n + 1, 1){ + + this->combine = combine; + + int len = 2, k = 1; + for(int i = 1; i <= n; i ++){ + if(i >= len) len <<= 1, k ++; + log2[i] = k; + } + + int K = log2[n]; + table = vector>(K, vector(n)); + + for(int i = 0; i < n; i ++) + table[0][i] = data[i]; + + for(int k = 1; k < K; k ++) + for(int i = 0; i + (1 << (k - 1)) < n; i ++) + table[k][i] = combine(table[k - 1][i], table[k - 1][i + (1 << (k - 1))]); + } + + T query(int l, int r){ + + int k = log2[r - l + 1]; + return combine(table[k - 1][l], table[k - 1][r + 1 - (1 << (k - 1))]); + } +}; + +class Solution { +public: + long long subArrayRanges(vector& nums) { + + auto max_f = [](int a, int b){return max(a, b);}; + auto min_f = [](int a, int b){return min(a, b);}; + SparseTable st_min(nums, min_f); + SparseTable st_max(nums, max_f); + + int n = nums.size(); + long long res = 0; + for(int l = 0; l < n; l ++) + for(int r = l + 1; r < n; r ++) + res += (long long)st_max.query(l, r) - st_min.query(l, r); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2104-Sum-of-Subarray-Ranges/cpp-2104/main2.cpp b/2001-2500/2104-Sum-of-Subarray-Ranges/cpp-2104/main2.cpp new file mode 100644 index 00000000..222e9d13 --- /dev/null +++ b/2001-2500/2104-Sum-of-Subarray-Ranges/cpp-2104/main2.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/sum-of-subarray-ranges/ +/// Author : liuyubobobo +/// Time : 2021-12-11 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n^2) +/// Space Complexity: O(1) +class Solution { +public: + long long subArrayRanges(vector& nums) { + + int n = nums.size(); + long long res = 0; + for(int l = 0; l < n; l ++){ + int minv = nums[l], maxv = nums[l]; + for(int r = l + 1; r < n; r ++){ + minv = min(minv, nums[r]), maxv = max(maxv, nums[r]); + res += (maxv - minv); + } + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2105-Watering-Plants-II/cpp-2105/CMakeLists.txt b/2001-2500/2105-Watering-Plants-II/cpp-2105/CMakeLists.txt new file mode 100644 index 00000000..cad75f71 --- /dev/null +++ b/2001-2500/2105-Watering-Plants-II/cpp-2105/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/2001-2500/2105-Watering-Plants-II/cpp-2105/main.cpp b/2001-2500/2105-Watering-Plants-II/cpp-2105/main.cpp new file mode 100644 index 00000000..8775fbad --- /dev/null +++ b/2001-2500/2105-Watering-Plants-II/cpp-2105/main.cpp @@ -0,0 +1,67 @@ +/// Source : https://leetcode.com/problems/watering-plants-ii/ +/// Author : liuyubobobo +/// Time : 2021-12-11 + +#include +#include + +using namespace std; + + +/// Two Pointers Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int minimumRefill(vector& plants, int capacityA, int capacityB) { + + int n = plants.size(); + int l = 0, r = n - 1, res = 0, A = capacityA, B = capacityB; + while(l < r){ + water(plants[l], A, res, capacityA); + water(plants[r], B, res, capacityB); + l ++, r --; + } + + if(l == r){ + if(A >= B) water(plants[l], A, res, capacityA); + else water(plants[l], B, res, capacityB); + } + return res; + } + +private: + void water(const int need, int& cur, int& res, const int cap){ + if(cur >= need) cur -= need; + else{ + res ++; + cur = cap - need; + } + } +}; + + +int main() { + + vector plants1 = {2, 2, 3, 3}; + cout << Solution().minimumRefill(plants1, 5, 5) << endl; + // 1 + + vector plants2 = {2, 2, 3, 3}; + cout << Solution().minimumRefill(plants2, 3, 4) << endl; + // 2 + + vector plants3 = {5}; + cout << Solution().minimumRefill(plants3, 10, 8) << endl; + // 0 + + vector plants4 = {1, 2, 4, 5, 5}; + cout << Solution().minimumRefill(plants4, 6, 5) << endl; + // 2 + + vector plants5 = {2, 2, 5, 2, 2}; + cout << Solution().minimumRefill(plants5, 5, 5) << endl; + // 1 + + return 0; +} diff --git a/2001-2500/2106-Maximum-Fruits-Harvested-After-at-Most-K-Steps/cpp-2106/CMakeLists.txt b/2001-2500/2106-Maximum-Fruits-Harvested-After-at-Most-K-Steps/cpp-2106/CMakeLists.txt new file mode 100644 index 00000000..a0d16fe6 --- /dev/null +++ b/2001-2500/2106-Maximum-Fruits-Harvested-After-at-Most-K-Steps/cpp-2106/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) diff --git a/2001-2500/2106-Maximum-Fruits-Harvested-After-at-Most-K-Steps/cpp-2106/main.cpp b/2001-2500/2106-Maximum-Fruits-Harvested-After-at-Most-K-Steps/cpp-2106/main.cpp new file mode 100644 index 00000000..d63028ff --- /dev/null +++ b/2001-2500/2106-Maximum-Fruits-Harvested-After-at-Most-K-Steps/cpp-2106/main.cpp @@ -0,0 +1,71 @@ +/// Source : https://leetcode.com/problems/maximum-fruits-harvested-after-at-most-k-steps/ +/// Author : liuyubobobo +/// Time : 2021-12-11 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(max_pos) +/// Space Complexity: O(max_pos) +class Solution { +public: + int maxTotalFruits(vector>& fruits, int startPos, int k) { + + int max_pos = startPos; + for(const vector& e: fruits) + max_pos = max(max_pos, e[0]); + + vector data(max_pos + 1, 0); + for(const vector& e: fruits) + data[e[0]] += e[1]; + + vector presum(data.size() + 1, 0); + for(int i = 0; i < data.size(); i ++) + presum[i + 1] = presum[i] + data[i]; + + long long res = 0; + for(int i = 0; startPos + i < data.size() && i <= k; i ++) { + int r = startPos + i; + int l = startPos; + if(k - 2 * i > 0) l = max(0, startPos - (k - 2 * i)); + res = max(res, presum[r + 1] - presum[l]); + } + for(int i = 0; startPos - i >= 0 && i <= k; i ++){ + int l = startPos - i; + int r = startPos; + if(k - 2 * i > 0) r = min(startPos + (k - 2 * i), (int)data.size() - 1); + res = max(res, presum[r + 1] - presum[l]); + } + return res; + } +}; + + +int main() { + + vector> fruits1 = {{2, 8}, {6, 3}, {8, 6}}; + cout << Solution().maxTotalFruits(fruits1, 5, 4) << endl; + // 9 + + vector> fruits2 = {{0, 9}, {4, 1}, {5, 7}, {6, 2}, {7, 4}, {10, 9}}; + cout << Solution().maxTotalFruits(fruits2, 5, 4) << endl; + // 14 + + vector> fruits3 = {{0, 3}, {6, 4}, {8, 5}}; + cout << Solution().maxTotalFruits(fruits3, 3, 2) << endl; + // 0 + + vector> fruits4 = {{200000, 10000}}; + cout << Solution().maxTotalFruits(fruits4, 200000, 0) << endl; + // 10000 + + vector> fruits5 = {{0, 10000}}; + cout << Solution().maxTotalFruits(fruits5, 200000, 200000) << endl; + // 10000 + + return 0; +} diff --git a/2001-2500/2107-Number-of-Unique-Flavors-After-Sharing-K-Candies/cpp-2107/CMakeLists.txt b/2001-2500/2107-Number-of-Unique-Flavors-After-Sharing-K-Candies/cpp-2107/CMakeLists.txt new file mode 100644 index 00000000..40263f94 --- /dev/null +++ b/2001-2500/2107-Number-of-Unique-Flavors-After-Sharing-K-Candies/cpp-2107/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_2107) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2107 main.cpp) diff --git a/2001-2500/2107-Number-of-Unique-Flavors-After-Sharing-K-Candies/cpp-2107/main.cpp b/2001-2500/2107-Number-of-Unique-Flavors-After-Sharing-K-Candies/cpp-2107/main.cpp new file mode 100644 index 00000000..d5ff92fd --- /dev/null +++ b/2001-2500/2107-Number-of-Unique-Flavors-After-Sharing-K-Candies/cpp-2107/main.cpp @@ -0,0 +1,41 @@ +/// Source : https://leetcode.com/problems/number-of-unique-flavors-after-sharing-k-candies/ +/// Author : liuyubobobo +/// Time : 2021-12-16 + +#include +#include +#include + +using namespace std; + + +/// Sliding Window +/// Time Complexity: O(n) +/// Space Complexity: O(k) +class Solution { +public: + int shareCandies(vector& candies, int k) { + + map f; + int n = candies.size(); + for(int i = k; i < n; i ++) + f[candies[i]] ++; + + int res = f.size(); + for(int i = k; i < n; i ++){ + + f[candies[i - k]] ++; + f[candies[i]] --; + if(f[candies[i]] == 0) f.erase(candies[i]); + + res = max(res, (int)f.size()); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2108-Find-First-Palindromic-String-in-the-Array/cpp-2108/CMakeLists.txt b/2001-2500/2108-Find-First-Palindromic-String-in-the-Array/cpp-2108/CMakeLists.txt new file mode 100644 index 00000000..2ae8397c --- /dev/null +++ b/2001-2500/2108-Find-First-Palindromic-String-in-the-Array/cpp-2108/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/2001-2500/2108-Find-First-Palindromic-String-in-the-Array/cpp-2108/main.cpp b/2001-2500/2108-Find-First-Palindromic-String-in-the-Array/cpp-2108/main.cpp new file mode 100644 index 00000000..d5b368f6 --- /dev/null +++ b/2001-2500/2108-Find-First-Palindromic-String-in-the-Array/cpp-2108/main.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/find-first-palindromic-string-in-the-array/ +/// Author : liuyubobobo +/// Time : 2021-12-18 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n * |s|) +/// Space Complexity: O(1) +class Solution { +public: + string firstPalindrome(vector& words) { + + for(const string& s: words) + if(is_palindrome(s)) return s; + return ""; + } + +private: + bool is_palindrome(const string& s){ + + int n = s.size(); + for(int i = 0; i < n; i ++) + if(s[i] != s[n - 1 - i]) return false; + return true; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2109-Adding-Spaces-to-a-String/cpp-2109/CMakeLists.txt b/2001-2500/2109-Adding-Spaces-to-a-String/cpp-2109/CMakeLists.txt new file mode 100644 index 00000000..3f98647f --- /dev/null +++ b/2001-2500/2109-Adding-Spaces-to-a-String/cpp-2109/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/2001-2500/2109-Adding-Spaces-to-a-String/cpp-2109/main.cpp b/2001-2500/2109-Adding-Spaces-to-a-String/cpp-2109/main.cpp new file mode 100644 index 00000000..02a90ce3 --- /dev/null +++ b/2001-2500/2109-Adding-Spaces-to-a-String/cpp-2109/main.cpp @@ -0,0 +1,32 @@ +/// Source : https://leetcode.com/problems/adding-spaces-to-a-string/ +/// Author : liuyubobobo +/// Time : 2021-12-18 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + string addSpaces(string s, vector& spaces) { + + string res = ""; + for(int i = 0, p = 0; i < s.size(); i ++){ + if(p < spaces.size() && i == spaces[p]) + res += (char)(' '), p ++; + res += s[i]; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2110-Number-of-Smooth-Descent-Periods-of-a-Stock/cpp-2110/CMakeLists.txt b/2001-2500/2110-Number-of-Smooth-Descent-Periods-of-a-Stock/cpp-2110/CMakeLists.txt new file mode 100644 index 00000000..cad75f71 --- /dev/null +++ b/2001-2500/2110-Number-of-Smooth-Descent-Periods-of-a-Stock/cpp-2110/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/2001-2500/2110-Number-of-Smooth-Descent-Periods-of-a-Stock/cpp-2110/main.cpp b/2001-2500/2110-Number-of-Smooth-Descent-Periods-of-a-Stock/cpp-2110/main.cpp new file mode 100644 index 00000000..e8ce2c61 --- /dev/null +++ b/2001-2500/2110-Number-of-Smooth-Descent-Periods-of-a-Stock/cpp-2110/main.cpp @@ -0,0 +1,36 @@ +/// Source : https://leetcode.com/problems/number-of-smooth-descent-periods-of-a-stock/ +/// Author : liuyubobobo +/// Time : 2021-12-18 + +#include +#include + +using namespace std; + + +/// Split +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + long long getDescentPeriods(vector& prices) { + + int n = prices.size(); + + long long res = 0; + for(int start = 0, i = 1; i <= n; i ++) + if(i == n || prices[i] + 1 != prices[i - 1]){ + long long len = i - start; + res += (len + 1ll) * len / 2ll; + + start = i; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2111-Minimum-Operations-to-Make-the-Array-K-Increasing/cpp-2111/CMakeLists.txt b/2001-2500/2111-Minimum-Operations-to-Make-the-Array-K-Increasing/cpp-2111/CMakeLists.txt new file mode 100644 index 00000000..a0d16fe6 --- /dev/null +++ b/2001-2500/2111-Minimum-Operations-to-Make-the-Array-K-Increasing/cpp-2111/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) diff --git a/2001-2500/2111-Minimum-Operations-to-Make-the-Array-K-Increasing/cpp-2111/main.cpp b/2001-2500/2111-Minimum-Operations-to-Make-the-Array-K-Increasing/cpp-2111/main.cpp new file mode 100644 index 00000000..fb1775ec --- /dev/null +++ b/2001-2500/2111-Minimum-Operations-to-Make-the-Array-K-Increasing/cpp-2111/main.cpp @@ -0,0 +1,62 @@ +/// Source : https://leetcode.com/problems/minimum-operations-to-make-the-array-k-increasing/ +/// Author : liuyubobobo +/// Time : 2021-12-18 + +#include +#include + +using namespace std; + + +/// LIS +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + int kIncreasing(vector& arr, int k) { + + int n = arr.size(); + + int res = 0; + for(int start = 0; start < k; start ++){ + vector A; + for(int i = start; i < n; i += k) A.push_back(arr[i]); + res += A.size() - lis(A); + } + return res; + } + +private: + int lis(const vector& A){ + + vector dp; + for(int e: A) + if(dp.empty() || e >= dp.back()) + dp.push_back(e); + else + dp[upper_bound(dp.begin(), dp.end(), e) - dp.begin()] = e; + return dp.size(); + } +}; + + +int main() { + + vector arr1 = {5,4,3,2,1}; + cout << Solution().kIncreasing(arr1, 1) << endl; + // 4 + + vector arr2 = {4,1,5,2,6,2}; + cout << Solution().kIncreasing(arr2, 2) << endl; + // 0 + + vector arr3 = {4,1,5,2,6,2}; + cout << Solution().kIncreasing(arr3, 3) << endl; + // 2 + + vector arr4 = {2,2,2,2,2,1,1,4,4,3,3,3,3,3}; + cout << Solution().kIncreasing(arr4, 1) << endl; + // 4 + + return 0; +} diff --git a/2001-2500/2113-Elements-in-Array-After-Removing-and-Replacing-Elements/cpp-2113/CMakeLists.txt b/2001-2500/2113-Elements-in-Array-After-Removing-and-Replacing-Elements/cpp-2113/CMakeLists.txt new file mode 100644 index 00000000..967f1941 --- /dev/null +++ b/2001-2500/2113-Elements-in-Array-After-Removing-and-Replacing-Elements/cpp-2113/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_2113) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2113 main.cpp) diff --git a/2001-2500/2113-Elements-in-Array-After-Removing-and-Replacing-Elements/cpp-2113/main.cpp b/2001-2500/2113-Elements-in-Array-After-Removing-and-Replacing-Elements/cpp-2113/main.cpp new file mode 100644 index 00000000..b1808625 --- /dev/null +++ b/2001-2500/2113-Elements-in-Array-After-Removing-and-Replacing-Elements/cpp-2113/main.cpp @@ -0,0 +1,55 @@ +/// Source : https://leetcode.com/problems/elements-in-array-after-removing-and-replacing-elements/ +/// Author : liuyubobobo +/// Time : 2021-12-24 + +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(q) +/// Space Complexity: O(1) +class Solution { +public: + vector elementInNums(vector& nums, vector>& queries) { + + int n = nums.size(); + + vector res(queries.size()); + for(int i = 0; i < queries.size(); i ++){ + int t = queries[i][0], index = queries[i][1]; + + t %= (2 * n); + int m; + if(t < n) m = n - t; + else m = t - n; + + if(index >= m) res[i] = -1; + else if(t < n) res[i] = nums[index + t]; + else res[i] = nums[index]; + } + return res; + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << ' '; cout << '\n'; +} + +int main() { + + vector nums1 = {0, 1, 2}; + vector> queries1 = {{0, 2}, {2, 0}, {3, 2}, {5, 0}}; + print_vec(Solution().elementInNums(nums1, queries1)); + // 2 2 -1 0 + + vector nums2 = {2}; + vector> queries2 = {{0, 0}, {1, 0}, {2, 0}, {3, 0}}; + print_vec(Solution().elementInNums(nums2, queries2)); + // 2 -1 2 -1 + + return 0; +} diff --git a/2001-2500/2114-Maximum-Number-of-Words-Found-in-Sentences/cpp-2114/CMakeLists.txt b/2001-2500/2114-Maximum-Number-of-Words-Found-in-Sentences/cpp-2114/CMakeLists.txt new file mode 100644 index 00000000..83aeba7d --- /dev/null +++ b/2001-2500/2114-Maximum-Number-of-Words-Found-in-Sentences/cpp-2114/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_2114) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2114 main.cpp) diff --git a/2001-2500/2114-Maximum-Number-of-Words-Found-in-Sentences/cpp-2114/main.cpp b/2001-2500/2114-Maximum-Number-of-Words-Found-in-Sentences/cpp-2114/main.cpp new file mode 100644 index 00000000..8475fa58 --- /dev/null +++ b/2001-2500/2114-Maximum-Number-of-Words-Found-in-Sentences/cpp-2114/main.cpp @@ -0,0 +1,42 @@ +/// Source : https://leetcode.com/problems/maximum-number-of-words-found-in-sentences/ +/// Author : liuyubobobo +/// Time : 2021-08-02 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n) +/// Space Compelxity: O(1) +class Solution { +public: + int mostWordsFound(vector& sentences) { + + int res = 0; + for(const string& s: sentences) + res = max(res, count_words(s)); + return res; + } + +private: + int count_words(const string& s){ + + int res = 0; + for(int start = 0, i = 1; i <= s.size(); i ++) + if(i == s.size() || s[i] == ' '){ + res ++; + start = i + 1; + i = start; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2115-Find-All-Possible-Recipes-from-Given-Supplies/cpp-2115/CMakeLists.txt b/2001-2500/2115-Find-All-Possible-Recipes-from-Given-Supplies/cpp-2115/CMakeLists.txt new file mode 100644 index 00000000..25bc8ba6 --- /dev/null +++ b/2001-2500/2115-Find-All-Possible-Recipes-from-Given-Supplies/cpp-2115/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_2115) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2115 main2.cpp) diff --git a/2001-2500/2115-Find-All-Possible-Recipes-from-Given-Supplies/cpp-2115/main.cpp b/2001-2500/2115-Find-All-Possible-Recipes-from-Given-Supplies/cpp-2115/main.cpp new file mode 100644 index 00000000..a81ceec4 --- /dev/null +++ b/2001-2500/2115-Find-All-Possible-Recipes-from-Given-Supplies/cpp-2115/main.cpp @@ -0,0 +1,120 @@ +/// Source : https://leetcode.com/problems/find-all-possible-recipes-from-given-supplies/ +/// Author : liuyubobobo +/// Time : 2021-12-26 + +#include +#include +#include +#include + +using namespace std; + + +/// Brute Force DFS +/// Directed Graph Cycle Finding +/// Time Complexity: O(q(n + m)) +/// Space Compplexity: O(n + m) +class Solution { + +private: + // 0-recipes; 1-ingredients + map str2index; + vector index2str; + vector is_ing; + +public: + vector findAllRecipes(vector& recipes, vector>& ingredients, vector& supplies) { + + for(const string& recipe: recipes) + if(!str2index.count(recipe)){ + str2index[recipe] = index2str.size(); + index2str.push_back(recipe); + is_ing.push_back(0); + } + + for(const vector& v: ingredients) + for(const string& ing: v) + if(!str2index.count(ing)){ + str2index[ing] = index2str.size(); + index2str.push_back(ing); + is_ing.push_back(1); + } + + vector> g(str2index.size(), vector()); + for(int i = 0; i < ingredients.size(); i ++){ + assert(str2index.count(recipes[i])); + int u = str2index[recipes[i]]; + for(const string& ing: ingredients[i]){ + assert(str2index.count(ing)); + int v = str2index[ing]; + g[u].push_back(v); + } + } + + set all(supplies.begin(), supplies.end()); + + vector res; + for(const string& recipe: recipes){ + assert(str2index.count(recipe)); + int s = str2index[recipe]; + vector visited(g.size(), false); + vector instack(g.size(), false); + if(!dfs(g, s, visited, instack)) continue; + + bool ok = true; + for(int i = 0; i < g.size(); i ++) + if(visited[i] && is_ing[i] && !all.count(index2str[i])){ + ok = false; + break; + } + if(ok) res.push_back(recipe); + } + return res; + } + +private: + bool dfs(const vector>& g, int u, + vector& visited, vector& instack){ + + assert(0 <= u && u < visited.size()); + visited[u] = true; + instack[u] = true; + for(int v: g[u]) + if(!visited[v]){ + if(!dfs(g, v, visited, instack)) return false; + } + else if(instack[v]) return false; + instack[u] = false; + return true; + } +}; + + +void print_vec(const vector& v){ + for(const string& s: v) cout << s << ' '; cout << endl; +} + +int main() { + + vector recipes1 = {"bread","sandwich","burger"}; + vector> ingredients1 = {{"yeast","flour"},{"bread","meat"},{"sandwich","meat","bread"}}; + vector supplies1 = {"yeast","flour","meat"}; + print_vec(Solution().findAllRecipes(recipes1, ingredients1, supplies1)); + // "bread","sandwich","burger" + + vector recipe2 = {"ju","fzjnm","x","e","zpmcz","h","q"}; + vector> ingredients2 = { + {"d"}, + {"hveml","f","cpivl"}, + {"cpivl","zpmcz","h","e","fzjnm","ju"}, + {"cpivl","hveml","zpmcz","ju","h"}, + {"h","fzjnm","e","q","x"}, + {"d","hveml","cpivl","q","zpmcz","ju","e","x"}, + {"f","hveml","cpivl"} + }; + vector supplies2 = {"f","hveml","cpivl","d"}; + print_vec(Solution().findAllRecipes(recipe2, ingredients2, supplies2)); + // ju fzjnm q + + return 0; +} diff --git a/2001-2500/2115-Find-All-Possible-Recipes-from-Given-Supplies/cpp-2115/main2.cpp b/2001-2500/2115-Find-All-Possible-Recipes-from-Given-Supplies/cpp-2115/main2.cpp new file mode 100644 index 00000000..12b92a7e --- /dev/null +++ b/2001-2500/2115-Find-All-Possible-Recipes-from-Given-Supplies/cpp-2115/main2.cpp @@ -0,0 +1,110 @@ +/// Source : https://leetcode.com/problems/find-all-possible-recipes-from-given-supplies/ +/// Author : liuyubobobo +/// Time : 2021-12-26 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// Topological Sorting +/// Time Complexity: O((n + m)) +/// Space Compplexity: O(n + m) +class Solution { + +private: + // 0-recipes; 1-ingredients + map str2index; + vector index2str; + vector is_ing; + +public: + vector findAllRecipes(vector& recipes, vector>& ingredients, vector& supplies) { + + for(const string& recipe: recipes) + if(!str2index.count(recipe)){ + str2index[recipe] = index2str.size(); + index2str.push_back(recipe); + is_ing.push_back(0); + } + + for(const vector& v: ingredients) + for(const string& ing: v) + if(!str2index.count(ing)){ + str2index[ing] = index2str.size(); + index2str.push_back(ing); + is_ing.push_back(1); + } + + vector> g(str2index.size(), vector()); + vector degrees(g.size(), 0); + for(int i = 0; i < ingredients.size(); i ++){ + assert(str2index.count(recipes[i])); + int u = str2index[recipes[i]]; + for(const string& ing: ingredients[i]){ + assert(str2index.count(ing)); + int v = str2index[ing]; + g[v].push_back(u); + degrees[u] ++; + } + } + + set all(supplies.begin(), supplies.end()); + vector res; + + queue q; + for(string s: supplies) + if(str2index.count(s)) q.push(str2index[s]); + + while(!q.empty()){ + int u = q.front(); q.pop(); + if(is_ing[u] == 0) res.push_back(index2str[u]); + + for(int v: g[u]){ + degrees[v] --; + if(degrees[v] == 0) q.push(v); + } + } + return res; + } +}; + + +void print_vec(const vector& v){ + for(const string& s: v) cout << s << ' '; cout << endl; +} + +int main() { + + vector recipes1 = {"bread","sandwich","burger"}; + vector> ingredients1 = {{"yeast","flour"},{"bread","meat"},{"sandwich","meat","bread"}}; + vector supplies1 = {"yeast","flour","meat"}; + print_vec(Solution().findAllRecipes(recipes1, ingredients1, supplies1)); + // "bread","sandwich","burger" + + vector recipe2 = {"ju","fzjnm","x","e","zpmcz","h","q"}; + vector> ingredients2 = { + {"d"}, + {"hveml","f","cpivl"}, + {"cpivl","zpmcz","h","e","fzjnm","ju"}, + {"cpivl","hveml","zpmcz","ju","h"}, + {"h","fzjnm","e","q","x"}, + {"d","hveml","cpivl","q","zpmcz","ju","e","x"}, + {"f","hveml","cpivl"} + }; + vector supplies2 = {"f","hveml","cpivl","d"}; + print_vec(Solution().findAllRecipes(recipe2, ingredients2, supplies2)); + // ju fzjnm q + + vector recipes3 = {"bread"}; + vector> ingredients3 = {{"yeast","flour"}}; + vector supplies3 = {"yeast","flour","corn"}; + print_vec(Solution().findAllRecipes(recipes3, ingredients3, supplies3)); + // "bread" + + return 0; +} diff --git a/2001-2500/2116-Check-if-a-Parentheses-String-Can-Be-Valid/cpp-2116/CMakeLists.txt b/2001-2500/2116-Check-if-a-Parentheses-String-Can-Be-Valid/cpp-2116/CMakeLists.txt new file mode 100644 index 00000000..15cf0291 --- /dev/null +++ b/2001-2500/2116-Check-if-a-Parentheses-String-Can-Be-Valid/cpp-2116/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_2116) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2116 main.cpp) diff --git a/2001-2500/2116-Check-if-a-Parentheses-String-Can-Be-Valid/cpp-2116/main.cpp b/2001-2500/2116-Check-if-a-Parentheses-String-Can-Be-Valid/cpp-2116/main.cpp new file mode 100644 index 00000000..bb2fddb0 --- /dev/null +++ b/2001-2500/2116-Check-if-a-Parentheses-String-Can-Be-Valid/cpp-2116/main.cpp @@ -0,0 +1,64 @@ +/// Source : https://leetcode.com/problems/check-if-a-parentheses-string-can-be-valid/ +/// Author : liuyubobobo +/// Time : 2022-01-28 + +#include +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + bool canBeValid(string s, string locked) { + + int n = s.size(); + if(n % 2 == 1) return false; + + int open = 0, locked_num = 0; + for(int i = 0; i < n; i ++){ + if(locked[i] == '1'){ + locked_num ++; + if(s[i] == '(') open ++; + else open --; + } + int t = (i + 1) - locked_num; + if(open < 0 && t < abs(open)) return false; + } + + open = 0, locked_num = 0; + for(int i = n - 1; i >= 0; i --){ + if(locked[i] == '1'){ + locked_num ++; + if(s[i] == ')') open ++; + else open --; + } + int t = (n - i) - locked_num; + if(open < 0 && t < abs(open)) return false; + } + return true; + } +}; + + +int main() { + + string s1 = "))()))", locked1 = "010100"; + cout << Solution().canBeValid(s1, locked1) << endl; + // 1 + + string s2 = "())(()(()(())()())(())((())(()())((())))))(((((((())(()))))("; + string locked2 = "100011110110011011010111100111011101111110000101001101001111"; + cout << Solution().canBeValid(s2, locked2) << endl; + // 0 + + string s3 = "((()(()()))()((()()))))()((()(()"; + string locked3 = "10111100100101001110100010001001"; + cout << Solution().canBeValid(s3, locked3) << endl; + // 1 + + return 0; +} diff --git a/2001-2500/2117-Abbreviating-the-Product-of-a-Range/cpp-2117/CMakeLists.txt b/2001-2500/2117-Abbreviating-the-Product-of-a-Range/cpp-2117/CMakeLists.txt new file mode 100644 index 00000000..e88017ff --- /dev/null +++ b/2001-2500/2117-Abbreviating-the-Product-of-a-Range/cpp-2117/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_2117) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2117 main.cpp) diff --git a/2001-2500/2117-Abbreviating-the-Product-of-a-Range/cpp-2117/main.cpp b/2001-2500/2117-Abbreviating-the-Product-of-a-Range/cpp-2117/main.cpp new file mode 100644 index 00000000..ec9eacd7 --- /dev/null +++ b/2001-2500/2117-Abbreviating-the-Product-of-a-Range/cpp-2117/main.cpp @@ -0,0 +1,131 @@ +/// Source : https://leetcode.com/problems/abbreviating-the-product-of-a-range/ +/// Author : liuyubobobo +/// Time : 2022-01-28 + +#include +#include +#include +#include + +using namespace std; + + +/// Big Number Simulation +/// Time Complexity: O(right - left) +/// Space Complexity: O(right - left) +class BigNumber{ + +private: + long long pre = 0, suf = 0; + const int d = 14; + const long long pow10e14 = 100000000000000ll; + +public: + BigNumber(int num) : suf(num){}; + + BigNumber& operator*=(int num){ + + if(pre == 0){ + suf *= num; + if(to_string(suf).size() <= d) return *this; + + pre = suf / pow10e14; + suf %= pow10e14; + return *this; + } + + suf *= num; + + long long carry = suf / pow10e14; + suf %= pow10e14; + + if(to_string(pre).size() < 19){ + pre *= num; + pre += carry; + } + else pre *= num; + + string pres = to_string(pre); + pre = stoll(pres.substr(0, d).c_str()); + + return *this; + } + + string str(){ + if(pre == 0){ + string sufs = to_string(suf); + if(sufs.size() <= 10) return sufs; + + string a = sufs.substr(0, 5), b = sufs.substr(sufs.size() - 5); + return a + "..." + b; + } + + string pres = to_string(pre), sufs = to_string(suf); + if(pres.size() + sufs.size() < 2 * d){ + string s = pres + sufs; + string a = s.substr(0, 5), b = s.substr(s.size() - 5); + return a + "..." + b; + } + + return pres.substr(0, 5) + "..." + sufs.substr(sufs.size() - 5); + } +}; + +class Solution { +public: + string abbreviateProduct(int left, int right) { + + vector nums; + int twos = 0, fives = 0; + for(int i = left; i <= right; i ++){ + nums.push_back(i); + twos += get(i, 2); + fives += get(i, 5); + } + + int zeros = min(twos, fives); + int cnt_twos = zeros, cnt_fives = zeros; + for(int i = 0; i < nums.size() && (cnt_twos || cnt_fives); i ++){ + erase(nums[i], 2, cnt_twos); + erase(nums[i], 5, cnt_fives); + } + + BigNumber number(nums[0]); + for(int i = 1; i < nums.size(); i ++) + number *= nums[i]; + return number.str() + "e" + to_string(zeros); + } + +private: + void erase(int& num, int p, int& cnt){ + while(cnt && num % p == 0) + cnt --, num /= p; + } + + int get(int num, int p){ + int res = 0; + while(num % p == 0) res ++, num /= p; + return res; + } +}; + + +int main() { + + cout << Solution().abbreviateProduct(1, 4) << endl; + // 24e0 + + cout << Solution().abbreviateProduct(2, 11) << endl; + // 399168e2 + + cout << Solution().abbreviateProduct(371, 375) << endl; + // 7219856259e3 + + cout << Solution().abbreviateProduct(981, 3082) << endl; + // 34865...63744e524 + + cout << Solution().abbreviateProduct(4838, 6186) << endl; + // 36088...36896e337 + + return 0; +} diff --git a/2001-2500/2119-A-Number-After-a-Double-Reversal/cpp-2119/CMakeLists.txt b/2001-2500/2119-A-Number-After-a-Double-Reversal/cpp-2119/CMakeLists.txt new file mode 100644 index 00000000..2ae8397c --- /dev/null +++ b/2001-2500/2119-A-Number-After-a-Double-Reversal/cpp-2119/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/2001-2500/2119-A-Number-After-a-Double-Reversal/cpp-2119/main.cpp b/2001-2500/2119-A-Number-After-a-Double-Reversal/cpp-2119/main.cpp new file mode 100644 index 00000000..fb5c5438 --- /dev/null +++ b/2001-2500/2119-A-Number-After-a-Double-Reversal/cpp-2119/main.cpp @@ -0,0 +1,27 @@ +/// Source : https://leetcode.com/problems/a-number-after-a-double-reversal/ +/// Author : liuyubobobo +/// Time : 2021-12-25 + +#include +#include + +using namespace std; + + +/// Mathematics +/// Time Complexity: O(1) +/// Space Complexity: O(1) +class Solution { +public: + bool isSameAfterReversals(int num) { + + if(num == 0) return true; + return num % 10 != 0; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2120-Execution-of-All-Suffix-Instructions-Staying-in-a-Grid/cpp-2120/CMakeLists.txt b/2001-2500/2120-Execution-of-All-Suffix-Instructions-Staying-in-a-Grid/cpp-2120/CMakeLists.txt new file mode 100644 index 00000000..3f98647f --- /dev/null +++ b/2001-2500/2120-Execution-of-All-Suffix-Instructions-Staying-in-a-Grid/cpp-2120/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/2001-2500/2120-Execution-of-All-Suffix-Instructions-Staying-in-a-Grid/cpp-2120/main.cpp b/2001-2500/2120-Execution-of-All-Suffix-Instructions-Staying-in-a-Grid/cpp-2120/main.cpp new file mode 100644 index 00000000..2109a02c --- /dev/null +++ b/2001-2500/2120-Execution-of-All-Suffix-Instructions-Staying-in-a-Grid/cpp-2120/main.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/execution-of-all-suffix-instructions-staying-in-a-grid/ +/// Author : liuyubobobo +/// Time : 2021-12-25 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(m * n) +/// Space Compelxity: O(1) +class Solution { +private: + int N; + +public: + vector executeInstructions(int n, vector& startPos, string s) { + + N = n; + + int m = s.size(); + vector res(m); + for(int i = 0; i < m; i ++) + res[i] = go(s, startPos[0], startPos[1], i); + return res; + } + +private: + int go(const string& s, int x, int y, int start){ + + int res = 0; + for(int i = start; i < s.size(); i ++){ + if(s[i] == 'R') y ++; + else if(s[i] == 'L') y --; + else if(s[i] == 'U') x --; + else if(s[i] == 'D') x ++; + if((x >= 0 && x < N && y >= 0 && y < N)) res ++; + else break; + } + return res; + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << ' '; cout << '\n'; +} + +int main() { + + vector start1 = {0, 1}; + print_vec(Solution().executeInstructions(3, start1, "RRDDLU")); + + return 0; +} diff --git a/2001-2500/2121-Intervals-Between-Identical-Elements/cpp-2121/CMakeLists.txt b/2001-2500/2121-Intervals-Between-Identical-Elements/cpp-2121/CMakeLists.txt new file mode 100644 index 00000000..0ffd6e97 --- /dev/null +++ b/2001-2500/2121-Intervals-Between-Identical-Elements/cpp-2121/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main2.cpp) diff --git a/2001-2500/2121-Intervals-Between-Identical-Elements/cpp-2121/main.cpp b/2001-2500/2121-Intervals-Between-Identical-Elements/cpp-2121/main.cpp new file mode 100644 index 00000000..0362e442 --- /dev/null +++ b/2001-2500/2121-Intervals-Between-Identical-Elements/cpp-2121/main.cpp @@ -0,0 +1,60 @@ +/// Source : https://leetcode.com/problems/intervals-between-identical-elements/ +/// Author : liuyubobobo +/// Time : 2021-12-25 + +#include +#include +#include + +using namespace std; + + +/// Using Map and Linear Scan +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector getDistances(vector& arr) { + + int n = arr.size(); + map> table; + for(int i = 0; i < n; i ++) + table[arr[i]].push_back(i); + + vector res(n, 0); + for(const pair>& p: table){ + const vector& v = p.second; + long long sum = 0ll; + for(int i = 1; i < v.size(); i ++) sum += v[i] - v[0]; + res[v[0]] = sum; + + long long x = v.size() - 1, y = 1; + for(int i = 1; i < v.size(); i ++){ + sum -= x * (v[i] - v[i - 1]); + sum += y * (v[i] - v[i - 1]); + res[v[i]] = sum; + x --; y ++; + } + } + return res; + } +}; + + +void print_vec(const vector& v){ + for(long long e: v) cout << e << ' '; + cout << '\n'; +} + +int main() { + + vector arr1 = {2,1,3,1,2,3,3}; + print_vec(Solution().getDistances(arr1)); + // 4 2 7 2 4 4 5 + + vector arr2 = {10,5,10,10}; + print_vec(Solution().getDistances(arr2)); + // 5 0 3 4 + + return 0; +} diff --git a/2001-2500/2121-Intervals-Between-Identical-Elements/cpp-2121/main2.cpp b/2001-2500/2121-Intervals-Between-Identical-Elements/cpp-2121/main2.cpp new file mode 100644 index 00000000..8fe176a7 --- /dev/null +++ b/2001-2500/2121-Intervals-Between-Identical-Elements/cpp-2121/main2.cpp @@ -0,0 +1,59 @@ +/// Source : https://leetcode.com/problems/intervals-between-identical-elements/ +/// Author : liuyubobobo +/// Time : 2021-12-25 + +#include +#include +#include + +using namespace std; + + +/// Using Map +/// Pre + Suf, more intuitive +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector getDistances(vector& arr) { + + int n = arr.size(); + map> table; + for(int i = 0; i < n; i ++) + table[arr[i]].push_back(i); + + vector res(n, 0); + for(const pair>& p: table){ + const vector& v = p.second; + + vector pre(v.size(), 0); + for(int i = 1; i < v.size(); i ++) pre[i] = pre[i - 1] + (long long)i * (v[i] - v[i - 1]); + + vector suf(v.size(), 0); + for(int i = (int)suf.size() - 2; i >= 0; i --) suf[i] = suf[i + 1] + ((long long)suf.size() - 1 - i) * (v[i + 1] - v[i]); + + for(int i = 0; i < v.size(); i ++) + res[v[i]] = pre[i] + suf[i]; + } + return res; + } +}; + + +void print_vec(const vector& v){ + for(long long e: v) cout << e << ' '; + cout << '\n'; +} + +int main() { + + vector arr1 = {2,1,3,1,2,3,3}; + print_vec(Solution().getDistances(arr1)); + // 4 2 7 2 4 4 5 + + vector arr2 = {10,5,10,10}; + print_vec(Solution().getDistances(arr2)); + // 5 0 3 4 + + return 0; +} diff --git a/2001-2500/2122-Recover-the-Original-Array/cpp-2122/CMakeLists.txt b/2001-2500/2122-Recover-the-Original-Array/cpp-2122/CMakeLists.txt new file mode 100644 index 00000000..a0d16fe6 --- /dev/null +++ b/2001-2500/2122-Recover-the-Original-Array/cpp-2122/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) diff --git a/2001-2500/2122-Recover-the-Original-Array/cpp-2122/main.cpp b/2001-2500/2122-Recover-the-Original-Array/cpp-2122/main.cpp new file mode 100644 index 00000000..6ef61af4 --- /dev/null +++ b/2001-2500/2122-Recover-the-Original-Array/cpp-2122/main.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/recover-the-original-array/ +/// Author : liuyubobobo +/// Time : 2021-12-25 + +#include +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Compelxity: O(n^2) +/// Space Complexity: O(n) +class Solution { +public: + vector recoverArray(vector& nums) { + + int n2 = nums.size(), n = n2 / 2; + + sort(nums.begin(), nums.end()); + for(int i = 1; i < n2; i ++){ + vector res = solve(nums, i); + if(!res.empty()) return res; + } + return {}; + } + +private: + vector solve(const vector& nums, int right){ + + int r = nums[right] - nums[0]; + if(r == 0 || r % 2) return {}; + + int k = r / 2; + + multiset set; + for(int e: nums) set.insert(e); + vector res; + while(!set.empty()){ + int a = *set.begin(); + if(set.count(a + 2 * k)){ + res.push_back(a + k); + set.erase(set.begin()); + set.erase(set.find(a + 2 * k)); + } + else return {}; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2123-Minimum-Operations-to-Remove-Adjacent-Ones-in-Matrix/cpp-2123/CMakeLists.txt b/2001-2500/2123-Minimum-Operations-to-Remove-Adjacent-Ones-in-Matrix/cpp-2123/CMakeLists.txt new file mode 100644 index 00000000..10042729 --- /dev/null +++ b/2001-2500/2123-Minimum-Operations-to-Remove-Adjacent-Ones-in-Matrix/cpp-2123/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_2123) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2123 main.cpp) diff --git a/2001-2500/2123-Minimum-Operations-to-Remove-Adjacent-Ones-in-Matrix/cpp-2123/main.cpp b/2001-2500/2123-Minimum-Operations-to-Remove-Adjacent-Ones-in-Matrix/cpp-2123/main.cpp new file mode 100644 index 00000000..33b4fffc --- /dev/null +++ b/2001-2500/2123-Minimum-Operations-to-Remove-Adjacent-Ones-in-Matrix/cpp-2123/main.cpp @@ -0,0 +1,153 @@ +/// Source : https://leetcode.com/problems/minimum-operations-to-remove-adjacent-ones-in-matrix/ +/// Author : liuyubobobo +/// Time : 2022-01-06 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// Bipartite Graph +/// Time Complexity: O(R * C) +/// Space Complexity: O(R * C) +class Hungarian{ + +private: + int n, m; // m - row size, n = column size + vector> g; + vector matching; + + bool is_solved = false; + int max_matching_value; + vector> best_matching; + +public: + Hungarian(int n, int m) : n(n), m(m), g(n), is_solved(false), matching(m, -1){} + + void add_edge(int u, int v){ + assert(u >= 0 && u < n); + assert(v >= 0 && v < m); + g[u].push_back(v); + } + + int get_max_matching_value(){ + if(!is_solved) solve(); + return max_matching_value; + } + + const vector> get_matching(){ + + if(!is_solved) solve(); + return best_matching; + } + +private: + void solve(){ + + int res = 0; + for(int i = 0; i < n; i ++){ + vector visited(m, false); + if(dfs(i, visited)) res ++; + } + + max_matching_value = res; + + best_matching.clear(); + for(int i = 0; i < m; i ++) + if(matching[i] != -1) best_matching.push_back({matching[i], i}); + + is_solved = true; + } + + bool dfs(int u, vector& visited){ + + for(int v: g[u]) + if(!visited[v]){ + visited[v] = true; + if(matching[v] == -1 || dfs(matching[v], visited)){ + matching[v] = u; + return true; + } + } + return false; + } +}; + +class Solution { + +private: + int R, C; + const int dirs[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; + +public: + int minimumOperations(vector>& grid) { + + R = grid.size(), C = grid[0].size(); + + vector> visited(R, vector(C, false)); + int res = 0; + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++) + if(grid[i][j] == 1 && !visited[i][j]){ + + set> points; + dfs(grid, i, j, visited, points); + + map, int> odd, even; + for(const pair& p: points) + if((p.first + p.second) % 2) odd[p] = odd.size(); + else even[p] = even.size(); + + Hungarian solver(odd.size(), even.size()); + for(const pair, int>& p: odd){ + int x = p.first.first, y = p.first.second, index = p.second; + for(int d = 0; d < 4; d ++){ + if(even.count({x + dirs[d][0], y + dirs[d][1]})) + solver.add_edge(index, even[{x + dirs[d][0], y + dirs[d][1]}]); + } + } + res += solver.get_max_matching_value(); + } + return res; + } + +private: + void dfs(const vector>& grid, int x, int y, + vector>& visited, set>& points){ + + visited[x][y] = true; + points.insert({x, y}); + + for(int d = 0; d < 4; d ++){ + int nx = x + dirs[d][0], ny = y + dirs[d][1]; + if(in_area(nx, ny) && grid[nx][ny] == 1 && !visited[nx][ny]) + dfs(grid, nx, ny, visited, points); + } + } + + bool in_area(int x, int y){ + return 0 <= x && x < R && 0 <= y && y < C; + } +}; + + +int main() { + + vector> grid1 = { + {1, 1, 0}, {0, 1, 1}, {1, 1, 1} + }; + cout << Solution().minimumOperations(grid1) << endl; + // 3 + + vector> grid2 = { + {0, 1, 0, 0, 1, 0}, {1, 1, 1, 1, 1, 1}, {0, 1, 0, 0, 1, 0} + }; + cout << Solution().minimumOperations(grid2) << endl; + // 3 + + return 0; +} diff --git a/2001-2500/2124-Check-if-All-As-Appears-Before-All-Bs/cpp-2124/CMakeLists.txt b/2001-2500/2124-Check-if-All-As-Appears-Before-All-Bs/cpp-2124/CMakeLists.txt new file mode 100644 index 00000000..a3422f8f --- /dev/null +++ b/2001-2500/2124-Check-if-All-As-Appears-Before-All-Bs/cpp-2124/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/2001-2500/2124-Check-if-All-As-Appears-Before-All-Bs/cpp-2124/main.cpp b/2001-2500/2124-Check-if-All-As-Appears-Before-All-Bs/cpp-2124/main.cpp new file mode 100644 index 00000000..70899c3c --- /dev/null +++ b/2001-2500/2124-Check-if-All-As-Appears-Before-All-Bs/cpp-2124/main.cpp @@ -0,0 +1,30 @@ +/// Source : https://leetcode.com/problems/check-if-all-as-appears-before-all-bs/ +/// Author : liuyubobobo +/// Time : 2022-01-01 + +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + bool checkString(string s) { + + int lasta = -1, firstb = s.size(); + for(int i = 0; i < s.size(); i ++) + if(s[i] == 'a') lasta = max(lasta, i); + else firstb = min(firstb, i); + return lasta < firstb; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2125-Number-of-Laser-Beams-in-a-Bank/cpp-2125/CMakeLists.txt b/2001-2500/2125-Number-of-Laser-Beams-in-a-Bank/cpp-2125/CMakeLists.txt new file mode 100644 index 00000000..0700646a --- /dev/null +++ b/2001-2500/2125-Number-of-Laser-Beams-in-a-Bank/cpp-2125/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/2001-2500/2125-Number-of-Laser-Beams-in-a-Bank/cpp-2125/main.cpp b/2001-2500/2125-Number-of-Laser-Beams-in-a-Bank/cpp-2125/main.cpp new file mode 100644 index 00000000..dba38b34 --- /dev/null +++ b/2001-2500/2125-Number-of-Laser-Beams-in-a-Bank/cpp-2125/main.cpp @@ -0,0 +1,36 @@ +/// Source : https://leetcode.com/problems/number-of-laser-beams-in-a-bank/ +/// Author : liuyubobobo +/// Time : 2022-01-01 + +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(R * C) +class Solution { +public: + int numberOfBeams(vector& bank) { + + vector data; + for(const string& s: bank){ + int num = 0; + for(char c: s) num += c == '1'; + + if(num) data.push_back(num); + } + + int res = 0; + for(int i = 1; i < data.size(); i ++) + res += data[i - 1] * data[i]; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2126-Destroying-Asteroids/cpp-2126/CMakeLists.txt b/2001-2500/2126-Destroying-Asteroids/cpp-2126/CMakeLists.txt new file mode 100644 index 00000000..e85d4767 --- /dev/null +++ b/2001-2500/2126-Destroying-Asteroids/cpp-2126/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main2.cpp) diff --git a/2001-2500/2126-Destroying-Asteroids/cpp-2126/main.cpp b/2001-2500/2126-Destroying-Asteroids/cpp-2126/main.cpp new file mode 100644 index 00000000..3e1afc2a --- /dev/null +++ b/2001-2500/2126-Destroying-Asteroids/cpp-2126/main.cpp @@ -0,0 +1,38 @@ +/// Source : https://leetcode.com/problems/destroying-asteroids/ +/// Author : liuyubobobo +/// Time : 2022-01-01 + +#include +#include +#include + +using namespace std; + + +/// Using Multiset +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + bool asteroidsDestroyed(int mass, vector& asteroids) { + + multiset> data; + for(int e: asteroids) data.insert((long long)e); + + long long cur = mass; + while(!data.empty()){ + multiset>::iterator iter = data.lower_bound(cur); + if(iter == data.end()) return false; + + cur += *iter; + data.erase(iter); + } + return true; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2126-Destroying-Asteroids/cpp-2126/main2.cpp b/2001-2500/2126-Destroying-Asteroids/cpp-2126/main2.cpp new file mode 100644 index 00000000..0af949f7 --- /dev/null +++ b/2001-2500/2126-Destroying-Asteroids/cpp-2126/main2.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/destroying-asteroids/ +/// Author : liuyubobobo +/// Time : 2022-01-01 + +#include +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + bool asteroidsDestroyed(int mass, vector& asteroids) { + + sort(asteroids.begin(), asteroids.end()); + + long long cur = mass; + for(int e: asteroids) + if(cur >= e) cur += e; + else return false; + return true; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2127-Maximum-Employees-to-Be-Invited-to-a-Meeting/cpp-2127/CMakeLists.txt b/2001-2500/2127-Maximum-Employees-to-Be-Invited-to-a-Meeting/cpp-2127/CMakeLists.txt new file mode 100644 index 00000000..9031340e --- /dev/null +++ b/2001-2500/2127-Maximum-Employees-to-Be-Invited-to-a-Meeting/cpp-2127/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) diff --git a/2001-2500/2127-Maximum-Employees-to-Be-Invited-to-a-Meeting/cpp-2127/main.cpp b/2001-2500/2127-Maximum-Employees-to-Be-Invited-to-a-Meeting/cpp-2127/main.cpp new file mode 100644 index 00000000..e0e8218b --- /dev/null +++ b/2001-2500/2127-Maximum-Employees-to-Be-Invited-to-a-Meeting/cpp-2127/main.cpp @@ -0,0 +1,114 @@ +/// Source : https://leetcode.com/problems/maximum-employees-to-be-invited-to-a-meeting/ +/// Author : liuyubobobo +/// Time : 2022-01-01 + +#include +#include + +using namespace std; + + +/// Successor Graph +/// This problem is not a very standard Successor Graph Problem, a little bit harder and Ad-Hoc +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int maximumInvitations(vector& favorite) { + + int n = favorite.size(); + + vector in_degrees(n, 0); + for(int u = 0; u < n; u ++) + in_degrees[favorite[u]] ++; + + vector in_tree(n, false); + for(int u = 0; u < n; u ++) + if(!in_tree[u] && in_degrees[u] == 0){ + int cur = u; + while(in_degrees[cur] == 0){ + in_tree[cur] = true; + cur = favorite[cur]; + in_degrees[cur] --; + } + } + + vector> g(n); + for(int u = 0; u < n; u ++) + g[favorite[u]].push_back(u); + + vector max_d(n, 0); + vector visited(n, false); + int res = 0, max2 = 0; + for(int u = 0; u < n; u ++){ + if(in_tree[u]) continue; + + int s = u; + vector cycle_points; + while(!visited[s]){ + cycle_points.push_back(s); + visited[s] = true; + s = favorite[s]; + } + + int first = 0, second = 0; + for(int v: cycle_points){ + dfs(g, v, in_tree, visited, max_d); + if(max_d[v] - 1 > first) second = first, first = max_d[v] - 1; + else if(max_d[v] - 1 > second) second = max_d[v] - 1; + } + + if(cycle_points.size() == 2) max2 += 2 + first + second; + else res = max(res, (int)cycle_points.size()); + } + return max(res, max2); + } + +private: + void dfs(const vector>& g, int u, const vector& in_tree, + vector& visited, vector& max_d){ + + visited[u] = true; + int res = 1; + for(int v: g[u]) + if(!visited[v] && in_tree[v]){ + dfs(g, v, in_tree, visited, max_d); + res = max(res, 1 + max_d[v]); + } + max_d[u] = res; + } +}; + + +int main() { + + vector fav1 = {2, 2, 1, 2}; + cout << Solution().maximumInvitations(fav1) << endl; + // 3 + + vector fav2 = {1, 2, 0}; + cout << Solution().maximumInvitations(fav2) << endl; + // 3 + + vector fav3 = {3, 0, 1, 4, 1}; + cout << Solution().maximumInvitations(fav3) << endl; + // 4 + + vector fav4 = {1,2,3,4,5,6,3,8,9,10,11,8}; + cout << Solution().maximumInvitations(fav4) << endl; + // 4 + + vector fav5 = {1,0,0,2,1,4,7,8,9,6,7,10,8}; + cout << Solution().maximumInvitations(fav5) << endl; + // 6 + + vector fav6 = {1,0,3,2,5,6,7,4,9,8,11,10,11,12,10}; + cout << Solution().maximumInvitations(fav6) << endl; + // 11 + + vector fav7 = {6,10,10,0,6,0,4,4,1,3,3}; + cout << Solution().maximumInvitations(fav7) << endl; + // 8 + + return 0; +} diff --git a/2001-2500/2128-Remove-All-Ones-With-Row-and-Column-Flips/cpp-2128/CMakeLists.txt b/2001-2500/2128-Remove-All-Ones-With-Row-and-Column-Flips/cpp-2128/CMakeLists.txt new file mode 100644 index 00000000..118dc64c --- /dev/null +++ b/2001-2500/2128-Remove-All-Ones-With-Row-and-Column-Flips/cpp-2128/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_2128) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2128 main.cpp) diff --git a/2001-2500/2128-Remove-All-Ones-With-Row-and-Column-Flips/cpp-2128/main.cpp b/2001-2500/2128-Remove-All-Ones-With-Row-and-Column-Flips/cpp-2128/main.cpp new file mode 100644 index 00000000..c4fb9090 --- /dev/null +++ b/2001-2500/2128-Remove-All-Ones-With-Row-and-Column-Flips/cpp-2128/main.cpp @@ -0,0 +1,42 @@ +/// Source : https://leetcode.com/problems/remove-all-ones-with-row-and-column-flips/ +/// Author : liuyubobobo +/// Time : 2022-01-06 + +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(R * C) +/// Space Complexity: O(1) +class Solution { +public: + bool removeOnes(vector>& grid) { + + int R = grid.size(), C = grid[0].size(); + for(int j = 0; j < C; j ++) + if(grid[0][j]){ + for(int i = 0; i < R; i ++) grid[i][j] ^= 1; + } + + for(int i = 0; i < R; i ++) + if(!ok(grid[i])) return false; + return true; + } + +private: + bool ok(const vector& v){ + + for(int i = 1; i < v.size(); i ++) + if(v[i] != v[0]) return false; + return true; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2129-Capitalize-the-Title/cpp-2129/CMakeLists.txt b/2001-2500/2129-Capitalize-the-Title/cpp-2129/CMakeLists.txt new file mode 100644 index 00000000..dcdb5d86 --- /dev/null +++ b/2001-2500/2129-Capitalize-the-Title/cpp-2129/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_2129) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2129 main.cpp) diff --git a/2001-2500/2129-Capitalize-the-Title/cpp-2129/main.cpp b/2001-2500/2129-Capitalize-the-Title/cpp-2129/main.cpp new file mode 100644 index 00000000..96b21309 --- /dev/null +++ b/2001-2500/2129-Capitalize-the-Title/cpp-2129/main.cpp @@ -0,0 +1,41 @@ +/// Source : https://leetcode.com/problems/capitalize-the-title/ +/// Author : liuyubobobo +/// Time : 2022-01-08 + +#include +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + string capitalizeTitle(string title) { + + int n = title.size(); + for(int start = 0, i = 1; i <= n; i ++) + if(i == n || title[i] == ' '){ + int len = i - start; + if(len <= 2){ + for(int j = start; j < i; j ++) title[j] = tolower(title[j]); + } + else{ + title[start] = toupper(title[start]); + for(int j = start + 1; j < i; j ++) title[j] = tolower(title[j]); + } + + start = i + 1; + i = start; + } + return title; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2130-Maximum-Twin-Sum-of-a-Linked-List/cpp-2130/CMakeLists.txt b/2001-2500/2130-Maximum-Twin-Sum-of-a-Linked-List/cpp-2130/CMakeLists.txt new file mode 100644 index 00000000..7083108a --- /dev/null +++ b/2001-2500/2130-Maximum-Twin-Sum-of-a-Linked-List/cpp-2130/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_2130) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2130 main.cpp) diff --git a/2001-2500/2130-Maximum-Twin-Sum-of-a-Linked-List/cpp-2130/main.cpp b/2001-2500/2130-Maximum-Twin-Sum-of-a-Linked-List/cpp-2130/main.cpp new file mode 100644 index 00000000..0d6ee9e6 --- /dev/null +++ b/2001-2500/2130-Maximum-Twin-Sum-of-a-Linked-List/cpp-2130/main.cpp @@ -0,0 +1,44 @@ +/// Source : https://leetcode.com/problems/maximum-twin-sum-of-a-linked-list/ +/// Author : liuyubobobo +/// Time : 2022-01-08 + +#include +#include + +using namespace std; + + +/// Using Array +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode() : val(0), next(nullptr) {} + ListNode(int x) : val(x), next(nullptr) {} + ListNode(int x, ListNode *next) : val(x), next(next) {} +}; + +class Solution { +public: + int pairSum(ListNode* head) { + + vector data; + for(ListNode* node = head; node; node = node->next) + data.push_back(node->val); + + int n = data.size(); + int res = 0; + for(int i = 0; i + i < n; i ++) + res = max(res, data[i] + data[n - i - 1]); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2131-Longest-Palindrome-by-Concatenating-Two-Letter-Words/cpp-2131/CMakeLists.txt b/2001-2500/2131-Longest-Palindrome-by-Concatenating-Two-Letter-Words/cpp-2131/CMakeLists.txt new file mode 100644 index 00000000..82ba3543 --- /dev/null +++ b/2001-2500/2131-Longest-Palindrome-by-Concatenating-Two-Letter-Words/cpp-2131/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_2131) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2131 main.cpp) diff --git a/2001-2500/2131-Longest-Palindrome-by-Concatenating-Two-Letter-Words/cpp-2131/main.cpp b/2001-2500/2131-Longest-Palindrome-by-Concatenating-Two-Letter-Words/cpp-2131/main.cpp new file mode 100644 index 00000000..5171eca3 --- /dev/null +++ b/2001-2500/2131-Longest-Palindrome-by-Concatenating-Two-Letter-Words/cpp-2131/main.cpp @@ -0,0 +1,42 @@ +/// Source : https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/ +/// Author : liuyubobobo +/// Time : 2022-01-08 + +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int longestPalindrome(vector& words) { + + vector> f(26, vector(26, 0)); + for(const string& word: words) + f[word[0] - 'a'][word[1] - 'a'] ++; + + int res = 0; + for(int i = 0; i < 26; i ++) + for(int j = i + 1; j < 26; j ++) + res += min(f[i][j], f[j][i]) * 4; + + bool middle = false; + for(int i = 0; i < 26; i ++){ + res += f[i][i] / 2 * 2 * 2; + if(f[i][i] % 2) middle = true; + } + + if(middle) res += 2; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2132-Stamping-the-Grid/cpp-2132/CMakeLists.txt b/2001-2500/2132-Stamping-the-Grid/cpp-2132/CMakeLists.txt new file mode 100644 index 00000000..7efea53c --- /dev/null +++ b/2001-2500/2132-Stamping-the-Grid/cpp-2132/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_2132) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2132 main.cpp) diff --git a/2001-2500/2132-Stamping-the-Grid/cpp-2132/main.cpp b/2001-2500/2132-Stamping-the-Grid/cpp-2132/main.cpp new file mode 100644 index 00000000..7557f2d1 --- /dev/null +++ b/2001-2500/2132-Stamping-the-Grid/cpp-2132/main.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/stamping-the-grid/ +/// Author : liuyubobobo +/// Time : 2022-01-08 + +#include +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(R * C) +/// Space Complexity: O(R * C) +class Solution { +public: + bool possibleToStamp(vector>& grid, int H, int W) { + + int R = grid.size(), C = grid[0].size(); + vector> presum(R + 1, vector(C + 1, 0)); + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++) + presum[i + 1][j + 1] = presum[i + 1][j] + presum[i][j + 1] + grid[i][j] - presum[i][j]; + + vector> draw(R, vector(C, 0)); + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++) + if(!grid[i][j]){ + if(draw[i][j] == 0){ + if(i + H - 1 >= R || j + W - 1 >= C || + presum[i + H][j + W] - presum[i + H][j] - presum[i][j + W] + presum[i][j]) + return false; + + for(int ii = 0; ii < H && draw[i + ii][j] == 0; ii ++) + for(int jj = 0; jj < W && draw[i + ii][j + jj] == 0; jj ++) + draw[i + ii][j + jj] = 1; + } + else if(i + H - 1 < R && j + W - 1 < C && + presum[i + H][j + W] - presum[i + H][j] - presum[i][j + W] + presum[i][j] == 0){ + + for(int ii = H - 1; ii >= 0 && draw[i + ii][j + W - 1] == 0; ii --) + for(int jj = W - 1; jj >= 0 && draw[i + ii][j + jj] == 0; jj --) + draw[i + ii][j + jj] = 1; + } + } + return true; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2133-Check-if-Every-Row-and-Column-Contains-All-Numbers/cpp-2133/CMakeLists.txt b/2001-2500/2133-Check-if-Every-Row-and-Column-Contains-All-Numbers/cpp-2133/CMakeLists.txt new file mode 100644 index 00000000..a3422f8f --- /dev/null +++ b/2001-2500/2133-Check-if-Every-Row-and-Column-Contains-All-Numbers/cpp-2133/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/2001-2500/2133-Check-if-Every-Row-and-Column-Contains-All-Numbers/cpp-2133/main.cpp b/2001-2500/2133-Check-if-Every-Row-and-Column-Contains-All-Numbers/cpp-2133/main.cpp new file mode 100644 index 00000000..3b1320be --- /dev/null +++ b/2001-2500/2133-Check-if-Every-Row-and-Column-Contains-All-Numbers/cpp-2133/main.cpp @@ -0,0 +1,43 @@ +/// Source : https://leetcode.com/problems/check-if-every-row-and-column-contains-all-numbers/ +/// Author : liuyubobobo +/// Time : 2022-01-08 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n^2) +/// Space Complexity: O(n^2) +class Solution { +public: + bool checkValid(vector>& matrix) { + + int n = matrix.size(); + for(int i = 0; i < n; i ++){ + vector ok(n + 1, false); + for(int j = 0; j < n; j ++) + ok[matrix[i][j]] = true; + for(int k = 1; k <= n; k ++) + if(!ok[k]) return false; + } + + for(int j = 0; j < n; j ++){ + vector ok(n + 1, false); + for(int i = 0; i < n; i ++) + ok[matrix[i][j]] = true; + for(int k = 1; k <= n; k ++) + if(!ok[k]) return false; + } + + return true; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2134-Minimum-Swaps-to-Group-All-1s-Together-II/cpp-2134/CMakeLists.txt b/2001-2500/2134-Minimum-Swaps-to-Group-All-1s-Together-II/cpp-2134/CMakeLists.txt new file mode 100644 index 00000000..0700646a --- /dev/null +++ b/2001-2500/2134-Minimum-Swaps-to-Group-All-1s-Together-II/cpp-2134/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/2001-2500/2134-Minimum-Swaps-to-Group-All-1s-Together-II/cpp-2134/main.cpp b/2001-2500/2134-Minimum-Swaps-to-Group-All-1s-Together-II/cpp-2134/main.cpp new file mode 100644 index 00000000..d3066e18 --- /dev/null +++ b/2001-2500/2134-Minimum-Swaps-to-Group-All-1s-Together-II/cpp-2134/main.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/minimum-swaps-to-group-all-1s-together-ii/ +/// Author : liuyubobobo +/// Time : 2022-01-08 + +#include +#include +#include + +using namespace std; + + +/// Presum +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int minSwaps(vector& nums) { + + int n = nums.size(); + + vector A = nums; + for(int e: nums) A.push_back(e); + + vector presum(2 * n + 1, 0); + for(int i = 0; i < A.size(); i ++) + presum[i + 1] = presum[i] + A[i]; + + int k = accumulate(nums.begin(), nums.end(), 0); + int res = INT_MAX; + for(int i = 0; i < n; i ++) + res = min(res, k - (presum[i + k] - presum[i])); + return res; + } +}; + + +int main() { + + vector nums1 = {0, 1, 0, 1, 1, 0, 0}; + cout << Solution().minSwaps(nums1) << endl; + // 1 + + vector nums2 = {0,1,1,1,0,0,1,1,0}; + cout << Solution().minSwaps(nums2) << endl; + // 2 + + vector nums3 = {1,1,0,0,1}; + cout << Solution().minSwaps(nums3) << endl; + // 0 + + return 0; +} diff --git a/2001-2500/2135-Count-Words-Obtained-After-Adding-a-Letter/cpp-2135/CMakeLists.txt b/2001-2500/2135-Count-Words-Obtained-After-Adding-a-Letter/cpp-2135/CMakeLists.txt new file mode 100644 index 00000000..e85d4767 --- /dev/null +++ b/2001-2500/2135-Count-Words-Obtained-After-Adding-a-Letter/cpp-2135/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main2.cpp) diff --git a/2001-2500/2135-Count-Words-Obtained-After-Adding-a-Letter/cpp-2135/main.cpp b/2001-2500/2135-Count-Words-Obtained-After-Adding-a-Letter/cpp-2135/main.cpp new file mode 100644 index 00000000..0dbea1cc --- /dev/null +++ b/2001-2500/2135-Count-Words-Obtained-After-Adding-a-Letter/cpp-2135/main.cpp @@ -0,0 +1,59 @@ +/// Source : https://leetcode.com/problems/count-words-obtained-after-adding-a-letter/ +/// Author : liuyubobobo +/// Time : 2022-01-08 + +#include +#include +#include + +using namespace std; + + +/// Map +/// Time Complexity: O(|startWords| + |targetWords|) +/// Space Complexity: O(|targetWords|) +class Solution { +public: + int wordCount(vector& startWords, vector& targetWords) { + + unordered_map target_map; + for(string word: targetWords){ + sort(word.begin(), word.end()); + target_map[word] ++; + } + + int res = 0; + vector used(26); + for(const string& word: startWords){ + used.assign(26, false); + for(char c: word) used[c - 'a'] = true; + for(int i = 0; i < 26; i ++) + if(!used[i]){ + string new_word = word + (char)('a' + i); + sort(new_word.begin(), new_word.end()); + auto iter = target_map.find(new_word); + if(iter != target_map.end()){ + res += iter->second; + target_map.erase(iter); + } + } + } + return res; + } +}; + + +int main() { + + vector startWords1 = {"ant","act","tack"}; + vector targetWords1 = {"tack","act","acti"}; + cout << Solution().wordCount(startWords1, targetWords1) << endl; + // 2 + + vector startWords2 = {"ab","a"}; + vector targetWords2 = {"abc","abcd"}; + cout << Solution().wordCount(startWords2, targetWords2) << endl; + // 1 + + return 0; +} diff --git a/2001-2500/2135-Count-Words-Obtained-After-Adding-a-Letter/cpp-2135/main2.cpp b/2001-2500/2135-Count-Words-Obtained-After-Adding-a-Letter/cpp-2135/main2.cpp new file mode 100644 index 00000000..e21e6b3b --- /dev/null +++ b/2001-2500/2135-Count-Words-Obtained-After-Adding-a-Letter/cpp-2135/main2.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/count-words-obtained-after-adding-a-letter/ +/// Author : liuyubobobo +/// Time : 2022-01-08 + +#include +#include +#include + +using namespace std; + + +/// Map, Using Bitwise +/// Time Complexity: O(|startWords| + |targetWords|) +/// Space Complexity: O(|targetWords|) +class Solution { +public: + int wordCount(vector& startWords, vector& targetWords) { + + unordered_map target_map; + for(string word: targetWords){ + int state = 0; + for(char c: word) state |= (1 << (c - 'a')); + target_map[state] ++; + } + + int res = 0; + for(const string& word: startWords){ + int state = 0; + for(char c: word) state |= (1 << (c - 'a')); + for(int i = 0; i < 26; i ++) + if((state & (1 << i)) == 0){ + auto iter = target_map.find(state | (1 << i)); + if(iter != target_map.end()){ + res += iter->second; + target_map.erase(iter); + } + } + } + return res; + } +}; + + +int main() { + + vector startWords1 = {"ant","act","tack"}; + vector targetWords1 = {"tack","act","acti"}; + cout << Solution().wordCount(startWords1, targetWords1) << endl; + // 2 + + vector startWords2 = {"ab","a"}; + vector targetWords2 = {"abc","abcd"}; + cout << Solution().wordCount(startWords2, targetWords2) << endl; + // 1 + + return 0; +} diff --git a/2001-2500/2136-Earliest-Possible-Day-of-Full-Bloom/cpp-2136/CMakeLists.txt b/2001-2500/2136-Earliest-Possible-Day-of-Full-Bloom/cpp-2136/CMakeLists.txt new file mode 100644 index 00000000..9031340e --- /dev/null +++ b/2001-2500/2136-Earliest-Possible-Day-of-Full-Bloom/cpp-2136/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) diff --git a/2001-2500/2136-Earliest-Possible-Day-of-Full-Bloom/cpp-2136/main.cpp b/2001-2500/2136-Earliest-Possible-Day-of-Full-Bloom/cpp-2136/main.cpp new file mode 100644 index 00000000..52397dea --- /dev/null +++ b/2001-2500/2136-Earliest-Possible-Day-of-Full-Bloom/cpp-2136/main.cpp @@ -0,0 +1,55 @@ +/// Source : https://leetcode.com/problems/earliest-possible-day-of-full-bloom/ +/// Author : liuyubobobo +/// Time : 2022-01-08 + +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + int earliestFullBloom(vector& plantTime, vector& growTime) { + + int n = plantTime.size(); + + vector> data(n); + for(int i = 0; i < n; i ++) + data[i].first = plantTime[i], data[i].second = growTime[i]; + + sort(data.begin(), data.end(), + [](const pair& p1, const pair& p2){ + if(p1.second != p2.second) return p1.second > p2.second; + return p1.first + p1.second > p2.first + p2.second; + }); + + int res = 0, cur = 0; + for(const pair& p: data){ + res = max(res, cur + p.first + p.second); + cur += p.first; + } + return res; + } +}; + + +int main() { + + vector plantTime1 = {1, 4, 3}, growTime1 = {2, 3 , 1}; + cout << Solution().earliestFullBloom(plantTime1, growTime1) << endl; + // 9 + + vector plantTime2 = {1, 2, 3, 2}, growTime2 = {2, 1, 2, 1}; + cout << Solution().earliestFullBloom(plantTime2, growTime2) << endl; + // 9 + + vector plantTime3 = {1}, growTime3 = {1}; + cout << Solution().earliestFullBloom(plantTime3, growTime3) << endl; + // 2 + + return 0; +} diff --git a/2001-2500/2137-Pour-Water-Between-Buckets-to-Make-Water-Levels-Equal/cpp-2137/CMakeLists.txt b/2001-2500/2137-Pour-Water-Between-Buckets-to-Make-Water-Levels-Equal/cpp-2137/CMakeLists.txt new file mode 100644 index 00000000..8b51d62f --- /dev/null +++ b/2001-2500/2137-Pour-Water-Between-Buckets-to-Make-Water-Levels-Equal/cpp-2137/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_2137) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2137 main.cpp) diff --git a/2001-2500/2137-Pour-Water-Between-Buckets-to-Make-Water-Levels-Equal/cpp-2137/main.cpp b/2001-2500/2137-Pour-Water-Between-Buckets-to-Make-Water-Levels-Equal/cpp-2137/main.cpp new file mode 100644 index 00000000..56068513 --- /dev/null +++ b/2001-2500/2137-Pour-Water-Between-Buckets-to-Make-Water-Levels-Equal/cpp-2137/main.cpp @@ -0,0 +1,85 @@ +/// Source : https://leetcode.com/problems/pour-water-between-buckets-to-make-water-levels-equal/ +/// Author : liuyubobobo +/// Time : 2022-01-13 + +#include +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(nlog(MAX_RANGE)) +/// Space Complexity: O(n) +class Solution { + +private: + const double eps = 1e-6; + +public: + double equalizeWater(vector& buckets, int loss) { + + int n = buckets.size(); + + vector B(n); + for(int i = 0; i < n; i ++) B[i] = buckets[i]; + sort(B.begin(), B.end()); + + double p = 1.0 - (double)loss / 100.0; + + double l = B[0], r = accumulate(B.begin(), B.end(), 0.0) / n; + while(!eq(l, r)){ + double m = (l + r) / 2; + if(ok(n, B, m, p)) l = m; + else r = m; + } + return l; + } + +private: + bool ok(int n, vector B, double t, double p){ + + for(int i = 0, j = 0; i < n;) + if(B[i] < t){ + while(j < n && B[j] <= t) j ++; + if(j == n) return false; + + double need = t - B[i]; + double can_pour = (B[j] - t) * p; + if(need >= can_pour){ + B[i] += can_pour; + B[j] = t; + if(B[i] >= t) i ++; + } + else{ + B[i] = t; + B[j] -= need / p; + i ++; + } + } + else i ++; + return true; + } + + bool eq(double a, double b){ + return abs(a - b) <= eps; + } +}; + +int main() { + + vector bucket1 = {1, 2, 7}; + cout << Solution().equalizeWater(bucket1, 80) << endl; + // 2.0 + + vector bucket2 = {2, 4, 6}; + cout << Solution().equalizeWater(bucket2, 50) << endl; + // 3.5 + + vector bucket3 = {3, 3, 3, 3}; + cout << Solution().equalizeWater(bucket3, 40) << endl; + // 3 + + return 0; +} diff --git a/2001-2500/2138-Divide-a-String-Into-Groups-of-Size-k/cpp-2138/CMakeLists.txt b/2001-2500/2138-Divide-a-String-Into-Groups-of-Size-k/cpp-2138/CMakeLists.txt new file mode 100644 index 00000000..a3422f8f --- /dev/null +++ b/2001-2500/2138-Divide-a-String-Into-Groups-of-Size-k/cpp-2138/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/2001-2500/2138-Divide-a-String-Into-Groups-of-Size-k/cpp-2138/main.cpp b/2001-2500/2138-Divide-a-String-Into-Groups-of-Size-k/cpp-2138/main.cpp new file mode 100644 index 00000000..85721d86 --- /dev/null +++ b/2001-2500/2138-Divide-a-String-Into-Groups-of-Size-k/cpp-2138/main.cpp @@ -0,0 +1,32 @@ +/// Source : https://leetcode.com/problems/divide-a-string-into-groups-of-size-k/ +/// Author : liuyubobobo +/// Time : 2022-01-15 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + vector divideString(string s, int k, char fill) { + + vector res; + for(int i = 0; i < s.size(); i += k) + res.push_back(s.substr(i, k)); + while(res.back().size() != k) res.back() += fill; + return res; + } +}; + + +int main() { + + Solution().divideString("abcdefghi", 3, 'x'); + + return 0; +} diff --git a/2001-2500/2139-Minimum-Moves-to-Reach-Target-Score/cpp-2139/CMakeLists.txt b/2001-2500/2139-Minimum-Moves-to-Reach-Target-Score/cpp-2139/CMakeLists.txt new file mode 100644 index 00000000..0700646a --- /dev/null +++ b/2001-2500/2139-Minimum-Moves-to-Reach-Target-Score/cpp-2139/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/2001-2500/2139-Minimum-Moves-to-Reach-Target-Score/cpp-2139/main.cpp b/2001-2500/2139-Minimum-Moves-to-Reach-Target-Score/cpp-2139/main.cpp new file mode 100644 index 00000000..5e4941c6 --- /dev/null +++ b/2001-2500/2139-Minimum-Moves-to-Reach-Target-Score/cpp-2139/main.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/minimum-moves-to-reach-target-score/ +/// Author : liuyubobobo +/// Time : 2022-01-15 + +#include +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(min(log(taarget), maxDoubles)) +/// Space Complexity: O(1) +class Solution { +public: + int minMoves(int target, int maxDoubles) { + + if(maxDoubles == 0) return target - 1; + + int res = 0, cur = target; + while(maxDoubles && cur != 1){ + if(cur & 1) cur --, res ++; + else cur >>= 1, res ++, maxDoubles --; + } + res += (cur - 1); + return res; + } +}; + + +int main() { + + cout << Solution().minMoves(5, 0) << endl; + // 4 + + cout << Solution().minMoves(19, 2) << endl; + // 7 + + cout << Solution().minMoves(10, 4) << endl; + // 4 + + cout << Solution().minMoves(4, 4) << endl; + // 2 + + return 0; +} diff --git a/2001-2500/2140-Solving-Questions-With-Brainpower/cpp-2140/CMakeLists.txt b/2001-2500/2140-Solving-Questions-With-Brainpower/cpp-2140/CMakeLists.txt new file mode 100644 index 00000000..8accde5b --- /dev/null +++ b/2001-2500/2140-Solving-Questions-With-Brainpower/cpp-2140/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/2001-2500/2140-Solving-Questions-With-Brainpower/cpp-2140/main.cpp b/2001-2500/2140-Solving-Questions-With-Brainpower/cpp-2140/main.cpp new file mode 100644 index 00000000..29a8b0a7 --- /dev/null +++ b/2001-2500/2140-Solving-Questions-With-Brainpower/cpp-2140/main.cpp @@ -0,0 +1,49 @@ +/// Source : https://leetcode.com/problems/solving-questions-with-brainpower/ +/// Author : liuyubobobo +/// Time : 2022-01-15 + +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +public: + long long mostPoints(vector>& questions) { + + int n = questions.size(); + vector dp(n, -1); + return dfs(n, questions, 0, dp); + } + +private: + long long dfs(int n, const vector>& questions, int index, + vector& dp){ + + if(index >= n) return 0; + if(dp[index] != -1) return dp[index]; + + long long res = dfs(n, questions, index + 1, dp); + res = max(res, (long long)questions[index][0] + dfs(n, questions, index + questions[index][1] + 1, dp)); + return dp[index] = res; + } +}; + + +int main() { + + vector> q1 = {{3,2},{4,3},{4,4},{2,5}}; + cout << Solution().mostPoints(q1) << endl; + // 5 + + vector> q2 = {{1,1},{2,2},{3, 3}, {4,4},{5,5}}; + cout << Solution().mostPoints(q2) << endl; + // 7 + + return 0; +} diff --git a/2001-2500/2141-Maximum-Running-Time-of-N-Computers/cpp-2141/CMakeLists.txt b/2001-2500/2141-Maximum-Running-Time-of-N-Computers/cpp-2141/CMakeLists.txt new file mode 100644 index 00000000..9031340e --- /dev/null +++ b/2001-2500/2141-Maximum-Running-Time-of-N-Computers/cpp-2141/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) diff --git a/2001-2500/2141-Maximum-Running-Time-of-N-Computers/cpp-2141/main.cpp b/2001-2500/2141-Maximum-Running-Time-of-N-Computers/cpp-2141/main.cpp new file mode 100644 index 00000000..df86d654 --- /dev/null +++ b/2001-2500/2141-Maximum-Running-Time-of-N-Computers/cpp-2141/main.cpp @@ -0,0 +1,68 @@ +/// Source : https://leetcode.com/problems/maximum-running-time-of-n-computers/ +/// Author : liuyubobobo +/// Time : 2022-01-15 + +#include +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(nlogn + nlog(sum/n)) +/// Space Complexity: O(1) +class Solution { + +public: + long long maxRunTime(int n, vector& batteries) { + + long long l = 1, r = accumulate(batteries.begin(), batteries.end(), 0ll) / n; + sort(batteries.begin(), batteries.end(), greater()); + while(l < r){ + long long mid = (l + r + 1) / 2; + if(ok(n, batteries, mid)) l = mid; + else r = mid - 1; + } + return l; + } + +private: + bool ok(int n, const vector& v, long long t){ + + int cnt = 0, i; + for(i = 0; i < n; i ++){ + if(v[i] >= t) cnt ++; + else break; + } + + long long cur = 0; + for(; i < v.size(); i ++){ + cur += v[i]; + if(cur >= t) cnt ++, cur -= t; + } + return cnt >= n; + } +}; + + +int main() { + + vector battery1 = {3, 3, 3}; + cout << Solution().maxRunTime(2, battery1) << endl; + // 4 + + vector battery2 = {1, 1, 1, 1}; + cout << Solution().maxRunTime(2, battery2) << endl; + // 2 + + vector battery3 = {6251,4133,9898,1536,5475,6340,7430,4413,2558,3941,6934,7326,7948,7736,1408,5752,836,4511,7684,3939,1376,2305,2090,8419,3813,4430,890,4120,3415,9706,879,158,2239,5462,5773,5285,5540,305,2211,691,4335,5912,3542,5229,996,2609,2173,87,5683,2946,1456,9590,3625,1807,6909,1328,1548,8182,1690,7440,8310,8502,320,2654,2254,1306,7696,7187,3977,3270,2989,1629,5725,7937,5317,9763,9238,3712,1925,2,1463,6309,4997,7786,1811,7579,3290,8355,63,5010,3574,5364,748,1877,106,1735,7809,5060,9677,4831,1524,9663,6557,9399,5976,801,8800,4297,9636,4828,3972,6946,6170,9984,5710,3318,4156,7838,6856,2866,5900,4623,5228,8063,2514,9149,3509,4033,854,2884,7160,8195,1936,8134,4277,9442,5263,555,5515,2341,2820,3095,2974,7648,9116,6886,8545,4055,2398,2425,4861,2114,9280,5045,3678,6569,7948,1912,7856,6831,4286,1645,9654,5552,880,1864,6386,6616,3961,7427,8649,2323,8084,7334,8256,6187,2244,9738,6869,5888,3862,886,1419,2067,15,428,4732,2098,7710,5586,1972,5388,5171,9239,4810,2461,3639,8120,5296,9522,3475,5703,2358,1957,9823,6561,3690,1856,8202,1343,1868,5851,3177,7036,4901,4891,4640,5927,7610,9204,3538,7508,411,3814,7545,7094,6841,3125,2884,2205,8271,9920,2322,20,8850,1747,3317,2873,558,7201,6688,9097,9399,2096,5846,9502,5028,2907,1667,4049,5810,5850,4628,4511,2415,1194,6477,9198,6645,1281,3920,7117,3301,1892,4402,8180,2915,3548,211,5855,2190,6552,5992,7280,1291,4064,6139,9585,6729,3481,5274,2498,9484,3486,863,1913,2921,4733,544,62,5139,4408,6174,9175,1119,7858,6215,2901,4862,4020,7371,2778,3086,6559,9187,7591,6007,8762,3577,8984,6653,4975,3939,1385,4076,6350,3248,3102,8331,194,9552,409,1527,6387,8477,5410,3223,1168,6578,4004,3442,1767,5979,8644,4893,8495,5152,5450,2221,7171,8308,6288,8536,5671,6642,6999,4134,5572,3639,884,9915,7104,8288,994,9765,9467,627,2549,2237,713,9487,9727,569,5755,2975,5248,894,3083,7820,7696,4780,952,9787,6791,1939,682,2917,6001,1781,2712,5098,2002,5641,9202,7651,4817,7685,3900,8720,7808,8628,2196,4155,3357,7890,1361,7537,6157,7107,2972,5548,2297,9888,6257,2596,9319,850,2181,2284,6877,9344,1177,2238,5140,6476,6289,2673,3266,5291,3098,541,81,8251,8235,8118,8717,2289,4159,2926,478,9137,3921,2591,669,8164,6245,5742,6076,3839,4243,4656,2448,1168,4481,3734,2909,4499,1479,4204,3693,5440,2921,4044,9615,7430,2716,7520,3354,3683,6058,4212,4940,5645,5101,9339,2422,3201,813,2753,8796,5485,1080,4433,3875,831,33,1689,6643,5753,7352,1670,2525,3606,34,5768,5256,531,427,4931,8174,8413,6014,3464,3793,6932,3943,7916,3954,1452,4165,4047,2844,9685,6882,9535,4995,7836,5296,1140,2403,7723,4388,4791,4967,3788,3694,9258,370,7174,8340,9182,7522,7852,242,1429,5904,7794,7736,2421,3885,819,3136,8815,5737,2043,6398,9528,9011,5056,7761,6120,9561,6053,8264,1648,4598,3448,2563,4717,9078,5032,1163,7788,2227,4478,4172}; + cout << Solution().maxRunTime(13, battery3) << endl; + // 207113 + + vector battery4 = {10, 10, 3, 5}; + cout << Solution().maxRunTime(3, battery4) << endl; + // 8 + + return 0; +} diff --git a/2001-2500/2143-Choose-Numbers-From-Two-Arrays-in-Range/cpp-2143/CMakeLists.txt b/2001-2500/2143-Choose-Numbers-From-Two-Arrays-in-Range/cpp-2143/CMakeLists.txt new file mode 100644 index 00000000..96a735a2 --- /dev/null +++ b/2001-2500/2143-Choose-Numbers-From-Two-Arrays-in-Range/cpp-2143/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_2143) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2143 main.cpp) diff --git a/2001-2500/2143-Choose-Numbers-From-Two-Arrays-in-Range/cpp-2143/main.cpp b/2001-2500/2143-Choose-Numbers-From-Two-Arrays-in-Range/cpp-2143/main.cpp new file mode 100644 index 00000000..92bd1202 --- /dev/null +++ b/2001-2500/2143-Choose-Numbers-From-Two-Arrays-in-Range/cpp-2143/main.cpp @@ -0,0 +1,62 @@ +/// Source : https://leetcode.com/problems/choose-numbers-from-two-arrays-in-range/ +/// Author : liuyubobobo +/// Time : 2022-01-28 + +#include +#include +#include + +using namespace std; + + +/// Memoization +/// Time Complexity: O(n * (sum1 + sum2)) +/// Space Complexity: O(n * (sum1 + sum2)) +class Solution { + +private: + const long long MOD = 1e9 + 7; + +public: + int countSubranges(vector& nums1, vector& nums2) { + + int n = nums1.size(); + int sum1 = accumulate(nums1.begin(), nums1.end(), 0); + int sum2 = accumulate(nums2.begin(), nums2.end(), 0); + vector> dp(n, vector(sum1 + sum2 + 1, -1)); // index, sum -> cnt + + int res = 0; + for(int i = 0; i < n; i ++) + res += dfs(n, nums1, nums2, i, 0, dp, sum2), res %= MOD; + return res; + } + +private: + int dfs(int n, const vector& nums1, const vector& nums2, int index, int target, + vector>& dp, int offset){ + + if(index == n) return 0; + if(dp[index][target + offset] != -1) return dp[index][target + offset]; + + int res = 0; + if(nums1[index] == target) res ++; + if(nums2[index] == -target) res ++; + res += dfs(n, nums1, nums2, index + 1, target - nums1[index], dp, offset); + res += dfs(n, nums1, nums2, index + 1, target + nums2[index], dp, offset); + return dp[index][target + offset] = res % MOD; + } +}; + + +int main() { + + vector nums11 = {1, 2, 5}, nums12 = {2, 6, 3}; + cout << Solution().countSubranges(nums11, nums12) << endl; + // 3 + + vector nums21 = {0, 1}, nums22 = {1, 0}; + cout << Solution().countSubranges(nums21, nums22) << endl; + // 4 + + return 0; +} diff --git a/2001-2500/2144-Minimum-Cost-of-Buying-Candies-With-Discount/cpp-2144/CMakeLists.txt b/2001-2500/2144-Minimum-Cost-of-Buying-Candies-With-Discount/cpp-2144/CMakeLists.txt new file mode 100644 index 00000000..85873c27 --- /dev/null +++ b/2001-2500/2144-Minimum-Cost-of-Buying-Candies-With-Discount/cpp-2144/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_2144) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2144 main.cpp) diff --git a/2001-2500/2144-Minimum-Cost-of-Buying-Candies-With-Discount/cpp-2144/main.cpp b/2001-2500/2144-Minimum-Cost-of-Buying-Candies-With-Discount/cpp-2144/main.cpp new file mode 100644 index 00000000..028a8d91 --- /dev/null +++ b/2001-2500/2144-Minimum-Cost-of-Buying-Candies-With-Discount/cpp-2144/main.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/minimum-cost-of-buying-candies-with-discount/ +/// Author : liuyubobobo +/// Time : 2022-01-22 + +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + int minimumCost(vector& cost) { + + sort(cost.begin(), cost.end(), greater()); + + int res = 0; + for(int i = 0; i < cost.size(); i += 3){ + res += cost[i]; + if(i + 1 < cost.size()) res += cost[i + 1]; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2145-Count-the-Hidden-Sequences/cpp-2145/CMakeLists.txt b/2001-2500/2145-Count-the-Hidden-Sequences/cpp-2145/CMakeLists.txt new file mode 100644 index 00000000..c147d6af --- /dev/null +++ b/2001-2500/2145-Count-the-Hidden-Sequences/cpp-2145/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_2145) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2145 main.cpp) diff --git a/2001-2500/2145-Count-the-Hidden-Sequences/cpp-2145/main.cpp b/2001-2500/2145-Count-the-Hidden-Sequences/cpp-2145/main.cpp new file mode 100644 index 00000000..e5f73012 --- /dev/null +++ b/2001-2500/2145-Count-the-Hidden-Sequences/cpp-2145/main.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/count-the-hidden-sequences/ +/// Author : liuyubobobo +/// Time : 2022-01-22 + +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int numberOfArrays(vector& differences, int lower, int upper) { + + int n = differences.size(); + + long long minv = differences[0], maxv = differences[0]; + long long cur = differences[0]; + for(int i = 1; i < n; i ++) + cur += differences[i], minv = min(minv, cur), maxv = max(maxv, cur); + + int l = max(lower, (int)(lower - minv)), r = min(upper, (int)(upper - maxv)); + return max(0, r - l + 1); + } +}; + + +int main() { + + vector diff1 = {1, -3, 4}; + cout << Solution().numberOfArrays(diff1, 1, 6) << endl; + // 2 + + vector diff2 = {3, -4, 5, 1, -2}; + cout << Solution().numberOfArrays(diff2, -4, 5) << endl; + // 4 + + vector diff3 = {4, -7, 2}; + cout << Solution().numberOfArrays(diff3, 3, 6) << endl; + // 0 + + vector diff4 = {-40}; + cout << Solution().numberOfArrays(diff4, -46, 53) << endl; + // 60 + + return 0; +} diff --git a/2001-2500/2146-K-Highest-Ranked-Items-Within-a-Price-Range/cpp-2146/CMakeLists.txt b/2001-2500/2146-K-Highest-Ranked-Items-Within-a-Price-Range/cpp-2146/CMakeLists.txt new file mode 100644 index 00000000..a14b3c7f --- /dev/null +++ b/2001-2500/2146-K-Highest-Ranked-Items-Within-a-Price-Range/cpp-2146/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_2146) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2146 main.cpp) diff --git a/2001-2500/2146-K-Highest-Ranked-Items-Within-a-Price-Range/cpp-2146/main.cpp b/2001-2500/2146-K-Highest-Ranked-Items-Within-a-Price-Range/cpp-2146/main.cpp new file mode 100644 index 00000000..489ce307 --- /dev/null +++ b/2001-2500/2146-K-Highest-Ranked-Items-Within-a-Price-Range/cpp-2146/main.cpp @@ -0,0 +1,64 @@ +/// Source : https://leetcode.com/problems/k-highest-ranked-items-within-a-price-range/ +/// Author : liuyubobobo +/// Time : 2022-01-22 + +#include +#include +#include + +using namespace std; + + +/// BFS +/// Time Complexity: O(R * C + klogk) +/// Space Complexity: O(R * C + k) +class Solution { + +private: + const int dirs[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; + int R, C; + +public: + vector> highestRankedKItems(vector>& grid, vector& pricing, vector& start, int k) { + + R = grid.size(), C = grid[0].size(); + vector> dis(R, vector(C, -1)); + + queue> q; + q.push({start[0], start[1]}); + dis[start[0]][start[1]] = 0; + vector, pair>> items; // dis, price, r, c + while(!q.empty()){ + int x = q.front().first, y = q.front().second; + q.pop(); + + if(grid[x][y] > 1 && pricing[0] <= grid[x][y] && grid[x][y] <= pricing[1]) + items.push_back({{dis[x][y], grid[x][y]}, {x, y}}); + + for(int d = 0; d < 4; d ++){ + int nx = x + dirs[d][0], ny = y + dirs[d][1]; + if(in_area(nx, ny) && grid[nx][ny] && dis[nx][ny] == -1){ + q.push({nx, ny}); + dis[nx][ny] = dis[x][y] + 1; + } + } + } + + sort(items.begin(), items.end()); + vector> res; + for(int i = 0; i < items.size() && i < k; i ++) + res.push_back({items[i].second.first, items[i].second.second}); + return res; + } + +private: + bool in_area(int x, int y){ + return 0 <= x && x < R && 0 <= y && y < C; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2147-Number-of-Ways-to-Divide-a-Long-Corridor/cpp-2147/CMakeLists.txt b/2001-2500/2147-Number-of-Ways-to-Divide-a-Long-Corridor/cpp-2147/CMakeLists.txt new file mode 100644 index 00000000..b1fbb527 --- /dev/null +++ b/2001-2500/2147-Number-of-Ways-to-Divide-a-Long-Corridor/cpp-2147/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_2147) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2147 main.cpp) diff --git a/2001-2500/2147-Number-of-Ways-to-Divide-a-Long-Corridor/cpp-2147/main.cpp b/2001-2500/2147-Number-of-Ways-to-Divide-a-Long-Corridor/cpp-2147/main.cpp new file mode 100644 index 00000000..6825bc27 --- /dev/null +++ b/2001-2500/2147-Number-of-Ways-to-Divide-a-Long-Corridor/cpp-2147/main.cpp @@ -0,0 +1,62 @@ +/// Source : https://leetcode.com/problems/number-of-ways-to-divide-a-long-corridor/ +/// Author : liuyubobobo +/// Time : 2022-01-22 + +#include +#include + +using namespace std; + + +/// Mathematics +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { + +private: + const long long MOD = 1e9 + 7; + +public: + int numberOfWays(string corridor) { + + int n = corridor.size(); + vector total_seats(n); + total_seats[0] = corridor[0] == 'S'; + for(int i = 1; i < n; i ++) + total_seats[i] = total_seats[i - 1] + (corridor[i] == 'S'); + + if(total_seats.back() & 1) return 0; + if(total_seats.back() <= 1) return 0; +// if(total_seats.back() == 2) return 1; + + long long res = 1; + int cur = 2; + while(cur != total_seats.back()){ + int l = lower_bound(total_seats.begin(), total_seats.end(), cur) - total_seats.begin(); + int r = lower_bound(total_seats.begin(), total_seats.end(), cur + 1) - total_seats.begin(); + res *= (r - l); + res %= MOD; + + cur += 2; + } + return res; + } +}; + + +int main() { + + string corridor1 = "SSPPSPS"; + cout << Solution().numberOfWays(corridor1) << endl; + // 3 + + string corridor2 = "PPSPSP"; + cout << Solution().numberOfWays(corridor2) << endl; + // 1 + + string corridor3 = "S"; + cout << Solution().numberOfWays(corridor3) << endl; + // 0 + + return 0; +} diff --git a/2001-2500/2148-Count-Elements-With-Strictly-Smaller-and-Greater-Elements/cpp-2148/CMakeLists.txt b/2001-2500/2148-Count-Elements-With-Strictly-Smaller-and-Greater-Elements/cpp-2148/CMakeLists.txt new file mode 100644 index 00000000..a3422f8f --- /dev/null +++ b/2001-2500/2148-Count-Elements-With-Strictly-Smaller-and-Greater-Elements/cpp-2148/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/2001-2500/2148-Count-Elements-With-Strictly-Smaller-and-Greater-Elements/cpp-2148/main.cpp b/2001-2500/2148-Count-Elements-With-Strictly-Smaller-and-Greater-Elements/cpp-2148/main.cpp new file mode 100644 index 00000000..90840bd5 --- /dev/null +++ b/2001-2500/2148-Count-Elements-With-Strictly-Smaller-and-Greater-Elements/cpp-2148/main.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/count-elements-with-strictly-smaller-and-greater-elements/ +/// Author : liuyubobobo +/// Time : 2022-01-22 + +#include +#include +#include + +using namespace std; + + +/// Using Map +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int countElements(vector& nums) { + + map f; + for(int e: nums) f[e] ++; + + int res = 0; + for(const pair& p: f) + if(p.first != f.begin()->first && p.first != f.rbegin()->first) + res += p.second; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2149-Rearrange-Array-Elements-by-Sign/cpp-2149/CMakeLists.txt b/2001-2500/2149-Rearrange-Array-Elements-by-Sign/cpp-2149/CMakeLists.txt new file mode 100644 index 00000000..0700646a --- /dev/null +++ b/2001-2500/2149-Rearrange-Array-Elements-by-Sign/cpp-2149/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/2001-2500/2149-Rearrange-Array-Elements-by-Sign/cpp-2149/main.cpp b/2001-2500/2149-Rearrange-Array-Elements-by-Sign/cpp-2149/main.cpp new file mode 100644 index 00000000..e6eed84b --- /dev/null +++ b/2001-2500/2149-Rearrange-Array-Elements-by-Sign/cpp-2149/main.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/rearrange-array-elements-by-sign/ +/// Author : liuyubobobo +/// Time : 2022-01-22 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + vector rearrangeArray(vector& nums) { + + int n = nums.size(); + vector res(n); + for(int i = 0, posi = 0, negi = 1; i < n; i ++) + if(nums[i] > 0) + res[posi] = nums[i], posi += 2; + else + res[negi] = nums[i], negi += 2; + + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2150-Find-All-Lonely-Numbers-in-the-Array/cpp-2150/CMakeLists.txt b/2001-2500/2150-Find-All-Lonely-Numbers-in-the-Array/cpp-2150/CMakeLists.txt new file mode 100644 index 00000000..8accde5b --- /dev/null +++ b/2001-2500/2150-Find-All-Lonely-Numbers-in-the-Array/cpp-2150/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/2001-2500/2150-Find-All-Lonely-Numbers-in-the-Array/cpp-2150/main.cpp b/2001-2500/2150-Find-All-Lonely-Numbers-in-the-Array/cpp-2150/main.cpp new file mode 100644 index 00000000..96cc99dc --- /dev/null +++ b/2001-2500/2150-Find-All-Lonely-Numbers-in-the-Array/cpp-2150/main.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/find-all-lonely-numbers-in-the-array/ +/// Author : liuyubobobo +/// Time : 2022-01-22 + +#include +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector findLonely(vector& nums) { + + map f; + for(int e: nums) f[e] ++; + + vector res; + for(const pair& p: f) + if(p.second == 1 && !f.count(p.first - 1) && !f.count(p.first + 1)) + res.push_back(p.first); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2151-Maximum-Good-People-Based-on-Statements/cpp-2151/CMakeLists.txt b/2001-2500/2151-Maximum-Good-People-Based-on-Statements/cpp-2151/CMakeLists.txt new file mode 100644 index 00000000..2552f642 --- /dev/null +++ b/2001-2500/2151-Maximum-Good-People-Based-on-Statements/cpp-2151/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main2.cpp) diff --git a/2001-2500/2151-Maximum-Good-People-Based-on-Statements/cpp-2151/main.cpp b/2001-2500/2151-Maximum-Good-People-Based-on-Statements/cpp-2151/main.cpp new file mode 100644 index 00000000..c9410a8c --- /dev/null +++ b/2001-2500/2151-Maximum-Good-People-Based-on-Statements/cpp-2151/main.cpp @@ -0,0 +1,55 @@ +/// Source : https://leetcode.com/problems/maximum-good-people-based-on-statements/ +/// Author : liuyubobobo +/// Time : 2022-01-22 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(2^n * (n^2)) +/// Space Complexity: O(2^n) +class Solution { +public: + int maximumGood(vector>& statements) { + + int n = statements.size(); + + vector> states(n + 1); + for(int state = 0; state < (1 << n); state ++) + states[__builtin_popcount(state)].push_back(state); + + for(int good_num = n; good_num > 0; good_num --) + for(int state: states[good_num]) + if(ok(n, state, statements)) return good_num; + return 0; + } + +private: + bool ok(int n, int state, const vector>& say){ + + vector good(n, false); + for(int i = 0; i < n; i ++) + good[i] = !!(state & (1 << i)); + + for(int i = 0; i < n; i ++){ + if(!good[i]) continue; + + for(int j = 0; j < n; j ++){ + if(say[i][j] == 2) continue; + + if(say[i][j] == 0 && good[j]) return false; + if(say[i][j] == 1 && !good[j]) return false; + } + } + return true; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2151-Maximum-Good-People-Based-on-Statements/cpp-2151/main2.cpp b/2001-2500/2151-Maximum-Good-People-Based-on-Statements/cpp-2151/main2.cpp new file mode 100644 index 00000000..1639e0ab --- /dev/null +++ b/2001-2500/2151-Maximum-Good-People-Based-on-Statements/cpp-2151/main2.cpp @@ -0,0 +1,55 @@ +/// Source : https://leetcode.com/problems/maximum-good-people-based-on-statements/ +/// Author : liuyubobobo +/// Time : 2022-01-22 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(2^n * (n^2)) +/// Space Complexity: O(1) +class Solution { +public: + int maximumGood(vector>& statements) { + + int n = statements.size(); + + vector> states(n + 1); + int res = 0; + for(int state = 0; state < (1 << n); state ++){ + int bitcnt = __builtin_popcount(state); + if(bitcnt <= res) continue; + if(ok(n, state, statements)) res = bitcnt; + } + return res; + } + +private: + bool ok(int n, int state, const vector>& say){ + + vector good(n, false); + for(int i = 0; i < n; i ++) + good[i] = !!(state & (1 << i)); + + for(int i = 0; i < n; i ++){ + if(!good[i]) continue; + + for(int j = 0; j < n; j ++){ + if(say[i][j] == 2) continue; + + if(say[i][j] == 0 && good[j]) return false; + if(say[i][j] == 1 && !good[j]) return false; + } + } + return true; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2152-Minimum-Number-of-Lines-to-Cover-Points/cpp-2152/CMakeLists.txt b/2001-2500/2152-Minimum-Number-of-Lines-to-Cover-Points/cpp-2152/CMakeLists.txt new file mode 100644 index 00000000..bb65fecd --- /dev/null +++ b/2001-2500/2152-Minimum-Number-of-Lines-to-Cover-Points/cpp-2152/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_2152) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2152 main.cpp) diff --git a/2001-2500/2152-Minimum-Number-of-Lines-to-Cover-Points/cpp-2152/main.cpp b/2001-2500/2152-Minimum-Number-of-Lines-to-Cover-Points/cpp-2152/main.cpp new file mode 100644 index 00000000..a0563968 --- /dev/null +++ b/2001-2500/2152-Minimum-Number-of-Lines-to-Cover-Points/cpp-2152/main.cpp @@ -0,0 +1,70 @@ +/// Source : https://leetcode.com/problems/minimum-number-of-lines-to-cover-points/ +/// Author : liuyubobobo +/// Time : 2022-01-27 + +#include +#include +#include + +using namespace std; + + +/// Memoization +/// Time Complexity: O(2^n * n^2) +/// Space Complexity: O(2^n) +class Solution { + +public: + int minimumLines(vector>& points) { + + int n = points.size(); + vector dp(1 << n, -1); + return dfs(n, points, 0, dp); + } + +private: + int dfs(int n, const vector>& points, int state, vector& dp){ + + int used_total = __builtin_popcount(state); + if(n - used_total == 0) return 0; + if(n - used_total <= 2) return 1; + if(dp[state] != -1) return dp[state]; + + int res = INT_MAX; + for(int i = 0; i < n; i ++){ + if(state & (1 << i)) continue; + for(int j = i + 1; j < n; j ++){ + if(state & (1 << j)) continue; + + vector in_line_index = {i, j}; + for(int k = j + 1; k < n; k ++){ + if(state & (1 << k)) continue; + if(in_line(points[i][0], points[i][1], points[j][0], points[j][1], points[k][0], points[k][1])) + in_line_index.push_back(k); + } + + for(int index: in_line_index) state |= (1 << index); + res = min(res, 1 + dfs(n, points, state, dp)); + for(int index: in_line_index) state -= (1 << index); + } + } + return dp[state] = res; + } + + bool in_line(int x1, int y1, int x2, int y2, int x, int y){ + return (y - y1) * (x - x2) == (y - y2) * (x - x1); + } +}; + + +int main() { + + vector> points1 = { + {4,-8},{-7,5},{9,7},{-10,10},{6,8}, + {-3,-6},{-1,3},{-10,9},{1,-3},{8,3} + }; + cout << Solution().minimumLines(points1) << endl; + // 5 + + return 0; +} diff --git a/2001-2500/2154-Keep-Multiplying-Found-Values-by-Two/cpp-2154/CMakeLists.txt b/2001-2500/2154-Keep-Multiplying-Found-Values-by-Two/cpp-2154/CMakeLists.txt new file mode 100644 index 00000000..a3422f8f --- /dev/null +++ b/2001-2500/2154-Keep-Multiplying-Found-Values-by-Two/cpp-2154/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/2001-2500/2154-Keep-Multiplying-Found-Values-by-Two/cpp-2154/main.cpp b/2001-2500/2154-Keep-Multiplying-Found-Values-by-Two/cpp-2154/main.cpp new file mode 100644 index 00000000..d3f70dd1 --- /dev/null +++ b/2001-2500/2154-Keep-Multiplying-Found-Values-by-Two/cpp-2154/main.cpp @@ -0,0 +1,30 @@ +/// Source : https://leetcode.com/problems/keep-multiplying-found-values-by-two/ +/// Author : liuyubobobo +/// Time : 2022-01-29 + +#include +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(log(max_num)) +/// Space Compexity: O(n) +class Solution { +public: + int findFinalValue(vector& nums, int original) { + + unordered_set table(nums.begin(), nums.end()); + while(table.count(original)) + original *= 2; + return original; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2155-All-Divisions-With-the-Highest-Score-of-a-Binary-Array/cpp-2155/CMakeLists.txt b/2001-2500/2155-All-Divisions-With-the-Highest-Score-of-a-Binary-Array/cpp-2155/CMakeLists.txt new file mode 100644 index 00000000..0700646a --- /dev/null +++ b/2001-2500/2155-All-Divisions-With-the-Highest-Score-of-a-Binary-Array/cpp-2155/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/2001-2500/2155-All-Divisions-With-the-Highest-Score-of-a-Binary-Array/cpp-2155/main.cpp b/2001-2500/2155-All-Divisions-With-the-Highest-Score-of-a-Binary-Array/cpp-2155/main.cpp new file mode 100644 index 00000000..fd62429a --- /dev/null +++ b/2001-2500/2155-All-Divisions-With-the-Highest-Score-of-a-Binary-Array/cpp-2155/main.cpp @@ -0,0 +1,44 @@ +/// Source : https://leetcode.com/problems/all-divisions-with-the-highest-score-of-a-binary-array/ +/// Author : liuyubobobo +/// Time : 2022-01-29 + +#include +#include + +using namespace std; + + +/// Presum + Sufsum +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector maxScoreIndices(vector& nums) { + + int n = nums.size(); + + vector pre0(n + 1, 0); + for(int i = 0; i < n; i ++) pre0[i + 1] = pre0[i] + (nums[i] == 0); + + vector suf1(n + 1, 0); + for(int i = n - 1; i >= 0; i --) suf1[i] = suf1[i + 1] + (nums[i] == 1); + + int max_score = -1; + vector res; + for(int i = 0; i <= n; i ++){ + int score = pre0[i] + suf1[i]; + if(score > max_score){ + max_score = score; res = {i}; + } + else if(score == max_score) res.push_back(i); + } + + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2156-Find-Substring-With-Given-Hash-Value/cpp-2156/CMakeLists.txt b/2001-2500/2156-Find-Substring-With-Given-Hash-Value/cpp-2156/CMakeLists.txt new file mode 100644 index 00000000..8accde5b --- /dev/null +++ b/2001-2500/2156-Find-Substring-With-Given-Hash-Value/cpp-2156/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/2001-2500/2156-Find-Substring-With-Given-Hash-Value/cpp-2156/main.cpp b/2001-2500/2156-Find-Substring-With-Given-Hash-Value/cpp-2156/main.cpp new file mode 100644 index 00000000..09d590dd --- /dev/null +++ b/2001-2500/2156-Find-Substring-With-Given-Hash-Value/cpp-2156/main.cpp @@ -0,0 +1,67 @@ +/// Source : https://leetcode.com/problems/find-substring-with-given-hash-value/ +/// Author : liuyubobobo +/// Time : 2022-01-29 + +#include +#include + +using namespace std; + + +/// String Hash +/// Time Complexity: O(n) +/// Space Comlexity: O(n) +template +class StringHash{ + +private: + int n; + T B, MOD; + vector h, p; + +public: + StringHash(const string& s, T B = 128, T MOD = 1e9+ 7) : + n(s.size()), h(n + 1, 0), p(n + 1, 1), B(B), MOD(MOD){ + + for(int i = 0; i < n; i ++){ + h[i + 1] = (h[i] * B + (s[i] - 'a' + 1)) % MOD; + p[i + 1] = p[i] * B % MOD; + } + } + + T get_hash(int l, int r){ +// assert(l >= 0 && l < n); +// assert(r >= 0 && r < n); + + T res = (h[r + 1] - h[l] * p[r - l + 1]) % MOD; + return res < 0 ? res + MOD : res; + } +}; + +class Solution { +public: + string subStrHash(string s, int power, int modulo, int k, int hashValue) { + + reverse(s.begin(), s.end()); + StringHash hash(s, power, modulo); + + string res = ""; + for(int i = 0; i + k - 1 < s.size(); i ++) + if(hash.get_hash(i, i + k - 1) == hashValue) + res = s.substr(i, k); + reverse(res.begin(), res.end()); + return res; + } +}; + + +int main() { + + cout << Solution().subStrHash("leetcode", 7, 20, 2, 0) << endl; + // ee + + cout << Solution().subStrHash("fbxzaad", 31, 100, 3, 32) << endl; + // fbx + + return 0; +} diff --git a/2001-2500/2157-Groups-of-Strings/cpp-2157/CMakeLists.txt b/2001-2500/2157-Groups-of-Strings/cpp-2157/CMakeLists.txt new file mode 100644 index 00000000..9031340e --- /dev/null +++ b/2001-2500/2157-Groups-of-Strings/cpp-2157/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) diff --git a/2001-2500/2157-Groups-of-Strings/cpp-2157/main.cpp b/2001-2500/2157-Groups-of-Strings/cpp-2157/main.cpp new file mode 100644 index 00000000..e7cc27d1 --- /dev/null +++ b/2001-2500/2157-Groups-of-Strings/cpp-2157/main.cpp @@ -0,0 +1,138 @@ +/// Source : https://leetcode.com/problems/groups-of-strings/ +/// Author : liuyubobobo +/// Time : 2022-01-29 + +#include +#include +#include +#include + +using namespace std; + + +/// UF +/// Time Complexity: O(26 * 26 * n) +/// Space Complexity: O(2^26 + n) +class UF{ + +private: + vector parent, sz; + +public: + UF(int n) : parent(n), sz(n, 1){ + for(int i = 0 ; i < n ; i ++) + parent[i] = i; + } + + int find(int p){ + if(p != parent[p]) + parent[p] = find(parent[p]); + return parent[p]; + } + + bool is_connected(int p , int q){ + return find(p) == find(q); + } + + void union_elements(int p, int q){ + + int p_root = find(p), q_root = find(q); + + if(p_root == q_root) return; + + parent[p_root] = q_root; + sz[q_root] += sz[p_root]; + } + + int size(int p){ + return sz[find(p)]; + } +}; + +class Solution { +public: + vector groupStrings(vector& words) { + + int n = words.size(); + + vector data(n); + for(int i = 0; i < n; i ++){ + int state = 0; + for(char c: words[i]) + state |= (1 << (c - 'a')); + data[i] = state; + } + + sort(data.begin(), data.end()); + + unordered_map state2index; + for(int i = 0; i < n; i ++) state2index[data[i]] = i; + + UF uf(n); + for(int start = 0, i = 1; i <= n; i ++){ + + if(i < n && data[i] == data[start]) continue; + + for(int index = start + 1; index < i; index ++) + uf.union_elements(start, index); + + for(int p = 0; p < 26; p ++){ + int state = data[start] ^ (1 << p); + auto iter = state2index.find(state); + if(iter != state2index.end()){ + uf.union_elements(start, iter->second); + } + } + + for(int p1 = 0; p1 < 26; p1 ++){ + if(data[start] & (1 << p1)) continue; + // data[i][p1] = 0; + for(int p2 = 0; p2 < 26; p2 ++){ + if((data[start] & (1 << p2)) == 0) continue; + // data[i][p2] = 1; + int state = data[start] ^ (1 << p1) ^ (1 << p2); + auto iter = state2index.find(state); + if(iter != state2index.end()){ + uf.union_elements(start, iter->second); + } + } + } + + start = i; + } + + unordered_set groups; + int max_sz = 0; + for(int i = 0; i < n; i ++){ + groups.insert(uf.find(i)); + max_sz = max(max_sz, uf.size(i)); + } + return {(int)groups.size(), max_sz}; + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << ' '; cout << '\n'; +} + +int main() { + + vector words1 = {"a", "b", "ab", "cde"}; + print_vec(Solution().groupStrings(words1)); + // 2, 3 + + vector words2 = {"a", "ab", "abc"}; + print_vec(Solution().groupStrings(words2)); + // 1, 3 + + vector words3 = {"a", "b", "bc", "cd"}; + print_vec(Solution().groupStrings(words3)); + // 1, 4 + + vector words4 = {"a", "z", "bc", "zb"}; + print_vec(Solution().groupStrings(words4)); + // 1, 4 + + return 0; +} diff --git a/2001-2500/2158-Amount-of-New-Area-Painted-Each-Day/cpp-2158/CMakeLists.txt b/2001-2500/2158-Amount-of-New-Area-Painted-Each-Day/cpp-2158/CMakeLists.txt new file mode 100644 index 00000000..2db18c3a --- /dev/null +++ b/2001-2500/2158-Amount-of-New-Area-Painted-Each-Day/cpp-2158/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_2158) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2158 main.cpp) diff --git a/2001-2500/2158-Amount-of-New-Area-Painted-Each-Day/cpp-2158/main.cpp b/2001-2500/2158-Amount-of-New-Area-Painted-Each-Day/cpp-2158/main.cpp new file mode 100644 index 00000000..eaf9ab11 --- /dev/null +++ b/2001-2500/2158-Amount-of-New-Area-Painted-Each-Day/cpp-2158/main.cpp @@ -0,0 +1,126 @@ +/// Source : https://leetcode.com/problems/amount-of-new-area-painted-each-day/ +/// Author : liuyubobobo +/// Time : 2022-02-04 + +#include +#include + +using namespace std; + + +/// Segment Tree +/// Time Complexity: O(q * log(max_end)) +/// Space Complexity: O(max_end) +template +class SegmentTree{ + +private: + int n; + vector tree, lazy; + T (*combine)(T a, T b); + +public: + SegmentTree(int n, T (*combine)(T a, T b)): + n(n), tree(4 * n, 0), lazy(4 * n, 0){ + this->combine = combine; + } + + void update(int uL, int uR, T v){ + assert(0 <= uL && uL < n); + assert(0 <= uR && uR < n); + assert(uL <= uR); + update(0, 0, n-1, uL, uR, v); + } + + T query(int qL, int qR){ + assert(0 <= qL && qL < n); + assert(0 <= qR && qR < n); + assert(qL <= qR); + return query(0, 0, n - 1, qL, qR); + } + +private: + void update(int treeID, int treeL, int treeR, int uL, int uR, T v){ + + if(uL > treeR || uR < treeL) return; + + if(uL <= treeL && treeR <= uR){ + tree[treeID] = (treeR - treeL + 1) * v; + lazy[treeID] = v; + return; + } + + if(lazy[treeID]) + push(treeID, treeL, treeR); + + int mid = (treeL + treeR) / 2; + update(2 * treeID + 1, treeL, mid, uL, uR, v); + update(2 * treeID + 2, mid + 1, treeR, uL, uR, v); + tree[treeID] = combine(tree[treeID * 2 + 1], tree[treeID * 2 + 2]); + return; + } + + T query(int treeID, int treeL, int treeR, int qL, int qR){ + + if(qL <= treeL && treeR <= qR) + return tree[treeID]; + + if(lazy[treeID]) + push(treeID, treeL, treeR); + + int mid = (treeL + treeR) / 2; + if(qR <= mid) return query(2 * treeID + 1, treeL, mid, qL, qR); + if(qL >= mid + 1) return query(2 * treeID + 2, mid + 1, treeR, qL, qR); + + T resl = query(2 * treeID + 1, treeL, mid, qL, qR); + T resr = query(2 * treeID + 2, mid + 1, treeR, qL, qR); + T res = combine(resl, resr); + return res; + } + +private: + void push(int treeID, int treeL, int treeR){ + + if(treeL == treeR) return; + + T v = lazy[treeID]; + + int mid = (treeL + treeR) / 2; + int tn = treeR - treeL + 1, tnl = mid - treeL + 1, tnr = tn - tnl; + + tree[treeID * 2 + 1] = v * tnl; + tree[treeID * 2 + 2] = v * tnr; + + lazy[treeID * 2 + 1] = v; + lazy[treeID * 2 + 2] = v; + + lazy[treeID] = 0; + } +}; + +class Solution { +public: + vector amountPainted(vector>& paint) { + + int max_end = 0; + for(const vector& seg: paint) max_end = max(max_end, seg[1]); + + SegmentTree seg_tree(max_end, [](int a, int b){return a + b;}); + + int n = paint.size(); + vector res(n); + for(int i = 0; i < n; i ++){ + int l = paint[i][0], r = paint[i][1] - 1; + int sum = seg_tree.query(l, r); + res[i] = (r - l + 1) - sum; + seg_tree.update(l, r, 1); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2160-Minimum-Sum-of-Four-Digit-Number-After-Splitting-Digits/cpp-2160/CMakeLists.txt b/2001-2500/2160-Minimum-Sum-of-Four-Digit-Number-After-Splitting-Digits/cpp-2160/CMakeLists.txt new file mode 100644 index 00000000..50e95cdc --- /dev/null +++ b/2001-2500/2160-Minimum-Sum-of-Four-Digit-Number-After-Splitting-Digits/cpp-2160/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_2160) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2160 main.cpp) diff --git a/2001-2500/2160-Minimum-Sum-of-Four-Digit-Number-After-Splitting-Digits/cpp-2160/main.cpp b/2001-2500/2160-Minimum-Sum-of-Four-Digit-Number-After-Splitting-Digits/cpp-2160/main.cpp new file mode 100644 index 00000000..b1c06b5f --- /dev/null +++ b/2001-2500/2160-Minimum-Sum-of-Four-Digit-Number-After-Splitting-Digits/cpp-2160/main.cpp @@ -0,0 +1,36 @@ +/// Source : https://leetcode.com/problems/minimum-sum-of-four-digit-number-after-splitting-digits/ +/// Author : liuyubobobo +/// Time : 2022-02-06 + +#include +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(4! * 3 * 4) +/// Space Complexity: O(1) +class Solution { +public: + int minimumSum(int num) { + + string s = to_string(num); + sort(s.begin(), s.end()); + + int res = INT_MAX; + do{ + for(int i = 1; i < 4; i ++) + res = min(res, atoi(s.substr(0, i).c_str()) + atoi(s.substr(i).c_str())); + }while(next_permutation(s.begin(), s.end())); + + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2161-Partition-Array-According-to-Given-Pivot/cpp-2161/CMakeLists.txt b/2001-2500/2161-Partition-Array-According-to-Given-Pivot/cpp-2161/CMakeLists.txt new file mode 100644 index 00000000..4fdc18e8 --- /dev/null +++ b/2001-2500/2161-Partition-Array-According-to-Given-Pivot/cpp-2161/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_2161) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2161 main.cpp) diff --git a/2001-2500/2161-Partition-Array-According-to-Given-Pivot/cpp-2161/main.cpp b/2001-2500/2161-Partition-Array-According-to-Given-Pivot/cpp-2161/main.cpp new file mode 100644 index 00000000..6c576335 --- /dev/null +++ b/2001-2500/2161-Partition-Array-According-to-Given-Pivot/cpp-2161/main.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/partition-array-according-to-given-pivot/ +/// Author : liuyubobobo +/// Time : 2022-02-06 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector pivotArray(vector& nums, int pivot) { + + vector pre, middle, post; + for(int e: nums) + if(e < pivot) pre.push_back(e); + else if(e == pivot) middle.push_back(e); + else post.push_back(e); + + pre.insert(pre.end(), middle.begin(), middle.end()); + pre.insert(pre.end(), post.begin(), post.end()); + return pre; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2162-Minimum-Cost-to-Set-Cooking-Time/cpp-2162/CMakeLists.txt b/2001-2500/2162-Minimum-Cost-to-Set-Cooking-Time/cpp-2162/CMakeLists.txt new file mode 100644 index 00000000..998db4a4 --- /dev/null +++ b/2001-2500/2162-Minimum-Cost-to-Set-Cooking-Time/cpp-2162/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_2162) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2162 main.cpp) diff --git a/2001-2500/2162-Minimum-Cost-to-Set-Cooking-Time/cpp-2162/main.cpp b/2001-2500/2162-Minimum-Cost-to-Set-Cooking-Time/cpp-2162/main.cpp new file mode 100644 index 00000000..025d7fd1 --- /dev/null +++ b/2001-2500/2162-Minimum-Cost-to-Set-Cooking-Time/cpp-2162/main.cpp @@ -0,0 +1,56 @@ +/// Source : https://leetcode.com/problems/minimum-cost-to-set-cooking-time/ +/// Author : liuyubobobo +/// Time : 2021-02-06 + +#include +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(targetSeconds / 60) +/// Space Complexity: O(1) +class Solution { +public: + int minCostSetTime(int startAt, int moveCost, int pushCost, int targetSeconds) { + + int res = INT_MAX; + for(int minutes = 0; minutes <= 99 && minutes * 60 <= targetSeconds; minutes ++){ + int seconds = targetSeconds - minutes * 60; + if(seconds > 99) continue; + res = min(res, get_time(startAt, moveCost, pushCost, minutes, seconds)); + } + return res; + } + +private: + int get_time(int startAt, int moveCost, int pushCost, int minute, int seconds){ + + vector v(4); + v[0] = minute / 10, v[1] = minute % 10, v[2] = seconds / 10, v[3] = seconds % 10; + + while(!v.empty() && v[0] == 0) v.erase(v.begin()); + assert(!v.empty()); + + int cur_pos = startAt, res = 0; + for(int e: v){ + if(cur_pos != e) res += moveCost, cur_pos = e; + res += pushCost; + } + return res; + } +}; + + +int main() { + + cout << Solution().minCostSetTime(1, 2, 1, 600) << endl; + // 6 + + cout << Solution().minCostSetTime(0, 1, 2, 76) << endl; + // 6 + + return 0; +} diff --git a/2001-2500/2163-Minimum-Difference-in-Sums-After-Removal-of-Elements/cpp-2163/CMakeLists.txt b/2001-2500/2163-Minimum-Difference-in-Sums-After-Removal-of-Elements/cpp-2163/CMakeLists.txt new file mode 100644 index 00000000..75f32f2f --- /dev/null +++ b/2001-2500/2163-Minimum-Difference-in-Sums-After-Removal-of-Elements/cpp-2163/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_2163) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2163 main2.cpp) diff --git a/2001-2500/2163-Minimum-Difference-in-Sums-After-Removal-of-Elements/cpp-2163/main.cpp b/2001-2500/2163-Minimum-Difference-in-Sums-After-Removal-of-Elements/cpp-2163/main.cpp new file mode 100644 index 00000000..cecde7a3 --- /dev/null +++ b/2001-2500/2163-Minimum-Difference-in-Sums-After-Removal-of-Elements/cpp-2163/main.cpp @@ -0,0 +1,126 @@ +/// Source : https://leetcode.com/problems/minimum-difference-in-sums-after-removal-of-elements/ +/// Author : liuyubobobo +/// Time : 2022-02-06 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// Custom define two structures +/// Time Complexity: O(nlogn) +/// Space Compelxity: O(n) +class MinNSum{ + +private: + priority_queue pq; + long long min_sum = 0; + int n; + +public: + MinNSum(const vector& nums) : n(nums.size()){ + for(int e: nums){ + pq.push(e); + min_sum += e; + } + } + + long long get_min_sum(){ + return min_sum; + } + + void add(int e){ + pq.push(e); + min_sum += e; + + int maxv = pq.top(); + pq.pop(); + min_sum -= maxv; + +// assert(pq.size() == n); + } +}; + +class MaxNSum{ + +private: + multiset min_set, max_set; + long long max_sum = 0; + int n; + +public: + MaxNSum(vector nums){ + int n2 = nums.size(); + n = n2 / 2; + + sort(nums.begin(), nums.end()); + for(int i = 0; i < n; i ++) min_set.insert(nums[i]); + for(int i = n; i < n2; i ++){ + max_set.insert(nums[i]); + max_sum += nums[i]; + } + } + + long long get_max_sum(){ + return max_sum; + } + + void remove(int e){ + auto iter = min_set.find(e); + if(iter != min_set.end()){ + min_set.erase(iter); + return; + } + +// assert(max_set.count(e)); + max_set.erase(max_set.find(e)); + max_sum -= e; + +// assert(!min_set.empty()); + int maxv = *min_set.rbegin(); + iter = min_set.end(); + iter --; + min_set.erase(iter); + max_set.insert(maxv); + max_sum += maxv; + } +}; + +class Solution { +public: + long long minimumDifference(vector& nums) { + + int n3 = nums.size(), n = n3 / 3; + + vector first(nums.begin(), nums.begin() + n); + vector second(nums.begin() + n, nums.end()); + + MinNSum minNSum(first); + MaxNSum maxNSum(second); + long long res = minNSum.get_min_sum() - maxNSum.get_max_sum(); + for(int i = n ; i < n + n; i ++){ + minNSum.add(nums[i]); + maxNSum.remove(nums[i]); + res = min(res, minNSum.get_min_sum() - maxNSum.get_max_sum()); + } + return res; + } +}; + + +int main() { + + vector nums1 = {3, 1, 2}; + cout << Solution().minimumDifference(nums1) << endl; + // -1 + + vector nums2 = {7, 9, 5, 8, 1, 3}; + cout << Solution().minimumDifference(nums2) << endl; + // 1 + + return 0; +} diff --git a/2001-2500/2163-Minimum-Difference-in-Sums-After-Removal-of-Elements/cpp-2163/main2.cpp b/2001-2500/2163-Minimum-Difference-in-Sums-After-Removal-of-Elements/cpp-2163/main2.cpp new file mode 100644 index 00000000..c3b2600e --- /dev/null +++ b/2001-2500/2163-Minimum-Difference-in-Sums-After-Removal-of-Elements/cpp-2163/main2.cpp @@ -0,0 +1,70 @@ +/// Source : https://leetcode.com/problems/minimum-difference-in-sums-after-removal-of-elements/ +/// Author : liuyubobobo +/// Time : 2022-02-06 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// Premin + Sufmax, only using priority queues +/// Time Complexity: O(nlogn) +/// Space Compelxity: O(n) +class Solution { +public: + long long minimumDifference(vector& nums) { + + int n3 = nums.size(), n = n3 / 3, n2 = 2 * n; + + // premin + vector premin(n3, 0); + priority_queue pq; + long long sum = 0; + for(int i = 0; i < n; i ++) + pq.push(nums[i]), sum += nums[i]; + + premin[n - 1] = sum; + for(int i = n; i < n2; i ++){ + pq.push(nums[i]), sum += nums[i]; + int maxv = pq.top(); pq.pop(); sum -= maxv; + premin[i] = sum; + } + + // sufmax + vector sufmax(n3, 0); + priority_queue, greater> pq2; + sum = 0; + for(int i = n3 - 1; i >= n2; i --) + pq2.push(nums[i]), sum += nums[i]; + + sufmax[n2] = sum; + for(int i = n2 - 1; i >= n; i --){ + pq2.push(nums[i]), sum += nums[i]; + int minv = pq2.top(); pq2.pop(); sum -= minv; + sufmax[i] = sum; + } + + long long res = LONG_LONG_MAX; + for(int i = n - 1; i < n2; i ++) + res = min(res, premin[i] - sufmax[i + 1]); + return res; + } +}; + + +int main() { + + vector nums1 = {3, 1, 2}; + cout << Solution().minimumDifference(nums1) << endl; + // -1 + + vector nums2 = {7, 9, 5, 8, 1, 3}; + cout << Solution().minimumDifference(nums2) << endl; + // 1 + + return 0; +} diff --git a/2001-2500/2164-Sort-Even-and-Odd-Indices-Independently/cpp-2164/CMakeLists.txt b/2001-2500/2164-Sort-Even-and-Odd-Indices-Independently/cpp-2164/CMakeLists.txt new file mode 100644 index 00000000..a3422f8f --- /dev/null +++ b/2001-2500/2164-Sort-Even-and-Odd-Indices-Independently/cpp-2164/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/2001-2500/2164-Sort-Even-and-Odd-Indices-Independently/cpp-2164/main.cpp b/2001-2500/2164-Sort-Even-and-Odd-Indices-Independently/cpp-2164/main.cpp new file mode 100644 index 00000000..36dd377c --- /dev/null +++ b/2001-2500/2164-Sort-Even-and-Odd-Indices-Independently/cpp-2164/main.cpp @@ -0,0 +1,38 @@ +/// Source : https://leetcode.com/problems/sort-even-and-odd-indices-independently/ +/// Author : liuyubobobo +/// Time : 2021-02-06 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + vector sortEvenOdd(vector& nums) { + + vector odd, even; + for(int i = 0; i < nums.size(); i ++) + if(i % 2 == 0) even.push_back(nums[i]); + else odd.push_back(nums[i]); + + sort(odd.begin(), odd.end(), greater()); + sort(even.begin(), even.end()); + + vector res; + for(int k = 0, i = 0, j = 0; k < nums.size(); k ++) + if(k % 2 == 0) res.push_back(even[i ++]); + else res.push_back(odd[j ++]); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2165-Smallest-Value-of-the-Rearranged-Number/cpp-2165/CMakeLists.txt b/2001-2500/2165-Smallest-Value-of-the-Rearranged-Number/cpp-2165/CMakeLists.txt new file mode 100644 index 00000000..0700646a --- /dev/null +++ b/2001-2500/2165-Smallest-Value-of-the-Rearranged-Number/cpp-2165/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/2001-2500/2165-Smallest-Value-of-the-Rearranged-Number/cpp-2165/main.cpp b/2001-2500/2165-Smallest-Value-of-the-Rearranged-Number/cpp-2165/main.cpp new file mode 100644 index 00000000..6248ef65 --- /dev/null +++ b/2001-2500/2165-Smallest-Value-of-the-Rearranged-Number/cpp-2165/main.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/smallest-value-of-the-rearranged-number/ +/// Author : liuyubobobo +/// Time : 2022-02-06 + +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(|num|log|num|) +/// Space Complexity: O(|num|) +class Solution { +public: + long long smallestNumber(long long num) { + + if(num == 0) return 0; + + if(num > 0){ + string s = to_string(num); + sort(s.begin(), s.end()); + + int non_zero = 0; + for(;non_zero < s.size() && s[non_zero] == '0'; non_zero ++); + string res = string(1, s[non_zero]) + s.substr(0, non_zero) + s.substr(non_zero + 1); + return atoll(res.c_str()); + } + + string s = to_string(num).substr(1); + sort(s.begin(), s.end(), greater()); + return atoll(s.c_str()) * -1ll; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2166-Design-Bitset/cpp-2166/CMakeLists.txt b/2001-2500/2166-Design-Bitset/cpp-2166/CMakeLists.txt new file mode 100644 index 00000000..8accde5b --- /dev/null +++ b/2001-2500/2166-Design-Bitset/cpp-2166/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/2001-2500/2166-Design-Bitset/cpp-2166/main.cpp b/2001-2500/2166-Design-Bitset/cpp-2166/main.cpp new file mode 100644 index 00000000..7d83905f --- /dev/null +++ b/2001-2500/2166-Design-Bitset/cpp-2166/main.cpp @@ -0,0 +1,79 @@ +/// Source : https://leetcode.com/problems/design-bitset/ +/// Author : liuyubobobo +/// Time : 2021-02-06 + +#include +#include +#include + +using namespace std; + + +/// Using Array +/// Time Complexity: init: O(1) +/// fix: O(1) +/// unfix: O(1) +/// flip: O(1) +/// all: O(1) +/// one: O(1) +/// count: O(1) +/// toString: O(sz) +/// Space Complexity: O(sz) +class Bitset { + +private: + int sz; + vector v; + int ones, flipped; + +public: + Bitset(int size) : sz(size), v(sz, 0), ones(0), flipped(0) { + } + + void fix(int idx) { + if(!flipped){ + if(v[idx] == 0) v[idx] = 1, ones ++; + } + else{ + if(v[idx] == 1) v[idx] = 0, ones ++; + } + } + + void unfix(int idx) { + if(!flipped){ + if(v[idx] == 1) v[idx] = 0, ones --; + } + else{ + if(v[idx] == 0) v[idx] = 1, ones --; + } + } + + void flip() { + flipped ^= 1; + ones = sz - ones; + } + + bool all() { + return ones == sz; + } + + bool one() { + return ones; + } + + int count() { + return ones; + } + + string toString() { + string res = ""; + for(int e: v) res += (char)('0' + (flipped ? 1 - e : e)); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2166-Design-Bitset/cpp-2166/main2.cpp b/2001-2500/2166-Design-Bitset/cpp-2166/main2.cpp new file mode 100644 index 00000000..5cb40c78 --- /dev/null +++ b/2001-2500/2166-Design-Bitset/cpp-2166/main2.cpp @@ -0,0 +1,68 @@ +/// Source : https://leetcode.com/problems/design-bitset/ +/// Author : liuyubobobo +/// Time : 2021-02-06 + +#include +#include +#include + +using namespace std; + + +/// Using C++ STL Bitset +/// Time Complexity: init: O(sz) +/// fix: O(1) +/// unfix: O(1) +/// flip: O(MAXN) +/// all: O(MAXN) +/// one: O(MAXN) +/// count: O(MAXN) +/// toString: O(sz) +/// Space Complexity: O(MAXN) +class Bitset { + +private: + int sz; + bitset<100000> o, mask; + +public: + Bitset(int size) : sz(size), mask(0) { + for(int i = 0; i < size; i ++) + mask.set(i); + } + + void fix(int idx) { + o.set(sz - 1- idx); + } + + void unfix(int idx) { + o.reset(sz - 1- idx); + } + + void flip() { + o.flip(); + o &= mask; + } + + bool all() { + return (o & mask).count() == sz; + } + + bool one() { + return (o & mask).any(); + } + + int count() { + return (o & mask).count(); + } + + string toString() { + return o.to_string().substr(100000 - sz); + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2167-Minimum-Time-to-Remove-All-Cars-Containing-Illegal-Goods/cpp-2167/CMakeLists.txt b/2001-2500/2167-Minimum-Time-to-Remove-All-Cars-Containing-Illegal-Goods/cpp-2167/CMakeLists.txt new file mode 100644 index 00000000..9031340e --- /dev/null +++ b/2001-2500/2167-Minimum-Time-to-Remove-All-Cars-Containing-Illegal-Goods/cpp-2167/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) diff --git a/2001-2500/2167-Minimum-Time-to-Remove-All-Cars-Containing-Illegal-Goods/cpp-2167/main.cpp b/2001-2500/2167-Minimum-Time-to-Remove-All-Cars-Containing-Illegal-Goods/cpp-2167/main.cpp new file mode 100644 index 00000000..0224caef --- /dev/null +++ b/2001-2500/2167-Minimum-Time-to-Remove-All-Cars-Containing-Illegal-Goods/cpp-2167/main.cpp @@ -0,0 +1,45 @@ +/// Source : https://leetcode.com/problems/minimum-time-to-remove-all-cars-containing-illegal-goods/ +/// Author : liuyubobobo +/// Time : 2022-02-06 + +#include +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int minimumTime(string s) { + + int n = s.size(); + + int res = n, minv = 0; + for(int r = 0; r < n; r ++){ + minv = min(r, minv) + 2 * (s[r] == '1'); + res = min(res, n - 1 - r + minv); + } + return res; + } +}; + + +int main() { + + string s1 = "1100101"; + cout << Solution().minimumTime(s1) << endl; + // 5 + + string s2 = "0010"; + cout << Solution().minimumTime(s2) << endl; + // 2 + + string s3 = "011001111111101001010000001010011"; + cout << Solution().minimumTime(s3) << endl; + // 25 + + return 0; +} diff --git a/2001-2500/2168-Unique-Substrings-With-Equal-Digit-Frequency/cpp-2168/CMakeLists.txt b/2001-2500/2168-Unique-Substrings-With-Equal-Digit-Frequency/cpp-2168/CMakeLists.txt new file mode 100644 index 00000000..26408b80 --- /dev/null +++ b/2001-2500/2168-Unique-Substrings-With-Equal-Digit-Frequency/cpp-2168/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_2168) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2168 main2.cpp) diff --git a/2001-2500/2168-Unique-Substrings-With-Equal-Digit-Frequency/cpp-2168/main.cpp b/2001-2500/2168-Unique-Substrings-With-Equal-Digit-Frequency/cpp-2168/main.cpp new file mode 100644 index 00000000..dbe35006 --- /dev/null +++ b/2001-2500/2168-Unique-Substrings-With-Equal-Digit-Frequency/cpp-2168/main.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/unique-substrings-with-equal-digit-frequency/ +/// Author : liuyubobobo +/// Time : 2022-02-13 + +#include +#include +#include + +using namespace std; + + +/// Presum + HashSet +/// Time Complexity: O(n^2) +/// Space Complexity: O(n^2) +class Solution { +public: + int equalDigitFrequency(string s) { + + int n = s.size(); + + vector> presum(n + 1, vector(10, 0)); + for(int i = 0; i < s.size(); i ++){ + presum[i + 1][s[i] - '0'] ++; + for(int j = 0; j < 10; j ++) + presum[i + 1][j] += presum[i][j]; + } + + unordered_set set; + for(int r = 0; r < n; r ++){ + for(int l = 0; l <= r; l ++){ + int f = 0; + bool ok = true; + for(int k = 0; k < 10 && ok; k ++) + if(presum[r + 1][k] - presum[l][k]){ + if(f && presum[r + 1][k] - presum[l][k] != f) + ok = false; + else f = presum[r + 1][k] - presum[l][k]; + } + if(ok) set.insert(s.substr(l, r - l + 1)); + } + } + return set.size(); + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2168-Unique-Substrings-With-Equal-Digit-Frequency/cpp-2168/main2.cpp b/2001-2500/2168-Unique-Substrings-With-Equal-Digit-Frequency/cpp-2168/main2.cpp new file mode 100644 index 00000000..f9077b28 --- /dev/null +++ b/2001-2500/2168-Unique-Substrings-With-Equal-Digit-Frequency/cpp-2168/main2.cpp @@ -0,0 +1,76 @@ +/// Source : https://leetcode.com/problems/unique-substrings-with-equal-digit-frequency/ +/// Author : liuyubobobo +/// Time : 2022-02-13 + +#include +#include +#include + +using namespace std; + + +/// Presum + HashSet + Rolling Hash +/// Time Complexity: O(n^2) +/// Space Complexity: O(n^2) +class StringHashU{ + +private: + int n; + unsigned long long B; + vector h, p; + +public: + StringHashU(const string& s, unsigned long long B = 131) : + n(s.size()), h(n + 1, 0), p(n + 1, 1), B(B){ + + for(int i = 0; i < n; i ++){ + h[i + 1] = h[i] * B + s[i]; + p[i + 1] = p[i] * B; + } + } + + unsigned long long get_hash(int l, int r){ + assert(l >= 0 && l < n); + assert(r >= 0 && r < n); + return h[r + 1] - h[l] * p[r - l + 1]; + } +}; + +class Solution { +public: + int equalDigitFrequency(string s) { + + int n = s.size(); + + vector> presum(n + 1, vector(10, 0)); + for(int i = 0; i < s.size(); i ++){ + presum[i + 1][s[i] - '0'] ++; + for(int j = 0; j < 10; j ++) + presum[i + 1][j] += presum[i][j]; + } + + StringHashU stringHash(s); + + unordered_set set; + for(int r = 0; r < n; r ++){ + for(int l = 0; l <= r; l ++){ + int f = 0; + bool ok = true; + for(int k = 0; k < 10 && ok; k ++) + if(presum[r + 1][k] - presum[l][k]){ + if(f && presum[r + 1][k] - presum[l][k] != f) + ok = false; + else f = presum[r + 1][k] - presum[l][k]; + } + if(ok) set.insert(stringHash.get_hash(l, r)); + } + } + return set.size(); + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2169-Count-Operations-to-Obtain-Zero/cpp-2169/CMakeLists.txt b/2001-2500/2169-Count-Operations-to-Obtain-Zero/cpp-2169/CMakeLists.txt new file mode 100644 index 00000000..a3422f8f --- /dev/null +++ b/2001-2500/2169-Count-Operations-to-Obtain-Zero/cpp-2169/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/2001-2500/2169-Count-Operations-to-Obtain-Zero/cpp-2169/main.cpp b/2001-2500/2169-Count-Operations-to-Obtain-Zero/cpp-2169/main.cpp new file mode 100644 index 00000000..1b15c8ef --- /dev/null +++ b/2001-2500/2169-Count-Operations-to-Obtain-Zero/cpp-2169/main.cpp @@ -0,0 +1,32 @@ +/// Source : https://leetcode.com/problems/count-operations-to-obtain-zero/ +/// Author : liuyubobobo +/// Time : 2022-02-12 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(max(num1, num2) / min(num1, num2)) +/// Space Compelxity: O(1) +class Solution { +public: + int countOperations(int num1, int num2) { + + int res = 0; + while(num1 && num2){ + if(num1 >= num2) num1 -= num2; + else num2 -= num1; + res ++; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2170-Minimum-Operations-to-Make-the-Array-Alternating/cpp-2170/CMakeLists.txt b/2001-2500/2170-Minimum-Operations-to-Make-the-Array-Alternating/cpp-2170/CMakeLists.txt new file mode 100644 index 00000000..0700646a --- /dev/null +++ b/2001-2500/2170-Minimum-Operations-to-Make-the-Array-Alternating/cpp-2170/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/2001-2500/2170-Minimum-Operations-to-Make-the-Array-Alternating/cpp-2170/main.cpp b/2001-2500/2170-Minimum-Operations-to-Make-the-Array-Alternating/cpp-2170/main.cpp new file mode 100644 index 00000000..c1d950b5 --- /dev/null +++ b/2001-2500/2170-Minimum-Operations-to-Make-the-Array-Alternating/cpp-2170/main.cpp @@ -0,0 +1,60 @@ +/// Source : https://leetcode.com/problems/minimum-operations-to-make-the-array-alternating/ +/// Author : liuyubobobo +/// Time : 2022-02-12 + +#include +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int minimumOperations(vector& nums) { + + int n = nums.size(); + if(n == 1) return 0; + + unordered_map sen, others; + for(int i = 0; i < n; i ++) { + if (i % 2 == 0) sen[nums[i]]++; + else others[nums[i]]++; + } + + vector> sen_v, others_v; + for(const pair& p: sen) + sen_v.push_back({p.second, p.first}); + for(const pair& p: others) + others_v.push_back({p.second, p.first}); + + sort(sen_v.begin(), sen_v.end(), greater>()); + sort(others_v.begin(), others_v.end(), greater>()); + + int sen_num = (n + 1) / 2, others_num = n - sen_num; + int res = n; + if(sen_v[0].second != others_v[0].second){ + res = min(res, n - sen_v[0].first - others_v[0].first); + } + else{ + if(others_v.size() >= 2) + res = min(res, n - sen_v[0].first - others_v[1].first); + else res = min(res, n - sen_v[0].first); + + if(sen_v.size() >= 2) + res = min(res, n - sen_v[1].first - others_v[0].first); + else res = min(res, n - others_v[0].first); + } + + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2171-Removing-Minimum-Number-of-Magic-Beans/cpp-2171/CMakeLists.txt b/2001-2500/2171-Removing-Minimum-Number-of-Magic-Beans/cpp-2171/CMakeLists.txt new file mode 100644 index 00000000..8accde5b --- /dev/null +++ b/2001-2500/2171-Removing-Minimum-Number-of-Magic-Beans/cpp-2171/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/2001-2500/2171-Removing-Minimum-Number-of-Magic-Beans/cpp-2171/main.cpp b/2001-2500/2171-Removing-Minimum-Number-of-Magic-Beans/cpp-2171/main.cpp new file mode 100644 index 00000000..cb934077 --- /dev/null +++ b/2001-2500/2171-Removing-Minimum-Number-of-Magic-Beans/cpp-2171/main.cpp @@ -0,0 +1,49 @@ +/// Source : https://leetcode.com/problems/removing-minimum-number-of-magic-beans/ +/// Author : liuyubobobo +/// Time : 2022-02-12 + +#include +#include +#include + +using namespace std; + + +/// Sorting +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + long long minimumRemoval(vector& beans) { + + int n = beans.size(); + + sort(beans.begin(), beans.end()); + vector presum(n + 1, 0); + for(int i = 0; i < n; i ++) presum[i + 1] = presum[i] + beans[i]; + + long long res = presum.back(); + for(int i = 0; i < n; i ++){ + if(i && beans[i] == beans[i - 1]) continue; + + long long tres = presum[i]; + tres += presum[n] - presum[i] - (long long)(n - i) * beans[i]; + res = min(res, tres); + } + return res; + } +}; + + +int main() { + + vector beans1 = {4, 1, 6, 5}; + cout << Solution().minimumRemoval(beans1) << endl; + // 4 + + vector beans2 = {2, 10, 3, 2}; + cout << Solution().minimumRemoval(beans2) << endl; + // 7 + + return 0; +} diff --git a/2001-2500/2172-Maximum-AND-Sum-of-Array/cpp-2172/CMakeLists.txt b/2001-2500/2172-Maximum-AND-Sum-of-Array/cpp-2172/CMakeLists.txt new file mode 100644 index 00000000..9031340e --- /dev/null +++ b/2001-2500/2172-Maximum-AND-Sum-of-Array/cpp-2172/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) diff --git a/2001-2500/2172-Maximum-AND-Sum-of-Array/cpp-2172/main.cpp b/2001-2500/2172-Maximum-AND-Sum-of-Array/cpp-2172/main.cpp new file mode 100644 index 00000000..0a10d7e5 --- /dev/null +++ b/2001-2500/2172-Maximum-AND-Sum-of-Array/cpp-2172/main.cpp @@ -0,0 +1,68 @@ +/// Source : https://leetcode.com/problems/maximum-and-sum-of-array/ +/// Author : liuyubobobo +/// Time : 2022-02-12 + +#include +#include +#include + +using namespace std; + + +/// State Compression DP +/// Time Complexity: O(n * 3^|numSlots| * numSlots) +/// Space Complexity: O(n * 3^|numSlots|) +class Solution { + +public: + int maximumANDSum(vector& nums, int numSlots) { + + int n = nums.size(); + vector slots(numSlots, 2); + + vector> dp(n, vector(get_state(slots) + 1, INT_MIN)); + return dfs(n, nums, 0, slots, dp); + } + +private: + int dfs(int n, const vector& nums, int index, vector& slots, + vector>& dp){ + + if(index == n) return 0; + + int slots_state = get_state(slots); + + if(dp[index][slots_state] != INT_MIN) + return dp[index][slots_state]; + + int res = INT_MIN; + for(int i = 0; i < slots.size(); i ++) + if(slots[i]){ + slots[i] --; + res = max(res, (nums[index] & (i + 1)) + dfs(n, nums, index + 1, slots, dp)); + slots[i] ++; + } + return dp[index][slots_state] = res; + } + + int get_state(const vector& v){ + + int res = 0; + for(int e: v) res = res * 3 + e; + return res; + } +}; + + +int main() { + + vector nums1 = {1, 2, 3, 4, 5, 6}; + cout << Solution().maximumANDSum(nums1, 3) << endl; + // 9 + + vector nums2 = {1, 3, 10, 4, 7, 1}; + cout << Solution().maximumANDSum(nums2, 9) << endl; + // 24 + + return 0; +} diff --git a/2001-2500/2174-Remove-All-Ones-With-Row-and-Column-Flips-II/cpp-2174/CMakeLists.txt b/2001-2500/2174-Remove-All-Ones-With-Row-and-Column-Flips-II/cpp-2174/CMakeLists.txt new file mode 100644 index 00000000..9ee5693b --- /dev/null +++ b/2001-2500/2174-Remove-All-Ones-With-Row-and-Column-Flips-II/cpp-2174/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_2174) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2174 main.cpp) diff --git a/2001-2500/2174-Remove-All-Ones-With-Row-and-Column-Flips-II/cpp-2174/main.cpp b/2001-2500/2174-Remove-All-Ones-With-Row-and-Column-Flips-II/cpp-2174/main.cpp new file mode 100644 index 00000000..2a802b92 --- /dev/null +++ b/2001-2500/2174-Remove-All-Ones-With-Row-and-Column-Flips-II/cpp-2174/main.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/remove-all-ones-with-row-and-column-flips-ii/ +/// Author : liuyubobobo +/// Time : 2022-02-18 + +#include +#include + +using namespace std; + + +/// State-Comppression Memoization +/// Time Complexity: O(R * C * 2^(R * C)) +/// Space Complexity: O(2^(R * C)) +class Solution { + +public: + int removeOnes(vector>& grid) { + + int R = grid.size(), C = grid[0].size(); + + vector dp(1 << (R * C), -1); + return dfs(R, C, grid, dp); + } + +private: + int dfs(int R, int C, const vector> grid, vector& dp){ + + int state = 0; + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++) + if(grid[i][j]) state |= (1 << (i * C + j)); + + if(state == 0) return 0; + if(dp[state] != -1) return dp[state]; + + int res = INT_MAX; + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++) + if(grid[i][j]){ + vector> t = grid; + for(int k = 0; k < R; k ++) t[k][j] = 0; + for(int k = 0; k < C; k ++) t[i][k] = 0; + res = min(res, 1 + dfs(R, C, t, dp)); + } + return dp[state] = res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2176-Count-Equal-and-Divisible-Pairs-in-an-Array/cpp-2176/CMakeLists.txt b/2001-2500/2176-Count-Equal-and-Divisible-Pairs-in-an-Array/cpp-2176/CMakeLists.txt new file mode 100644 index 00000000..5d16bd4b --- /dev/null +++ b/2001-2500/2176-Count-Equal-and-Divisible-Pairs-in-an-Array/cpp-2176/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_2176) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2176 main.cpp) diff --git a/2001-2500/2176-Count-Equal-and-Divisible-Pairs-in-an-Array/cpp-2176/main.cpp b/2001-2500/2176-Count-Equal-and-Divisible-Pairs-in-an-Array/cpp-2176/main.cpp new file mode 100644 index 00000000..9293787e --- /dev/null +++ b/2001-2500/2176-Count-Equal-and-Divisible-Pairs-in-an-Array/cpp-2176/main.cpp @@ -0,0 +1,30 @@ +/// Source : https://leetcode.com/problems/count-equal-and-divisible-pairs-in-an-array/ +/// Author : liuyubobobo +/// Time : 2022-02-19 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n^2) +/// Space Complexity: O(1) +class Solution { +public: + int countPairs(vector& nums, int k) { + + int n = nums.size(), res = 0; + for(int i = 0; i < n; i ++) + for(int j = i + 1; j < n; j ++) + if(nums[i] == nums[j] && (i * j) % k == 0) res ++; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2177-Find-Three-Consecutive-Integers-That-Sum-to-a-Given-Number/cpp-2177/CMakeLists.txt b/2001-2500/2177-Find-Three-Consecutive-Integers-That-Sum-to-a-Given-Number/cpp-2177/CMakeLists.txt new file mode 100644 index 00000000..3c233e08 --- /dev/null +++ b/2001-2500/2177-Find-Three-Consecutive-Integers-That-Sum-to-a-Given-Number/cpp-2177/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_2177) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2177 main.cpp) diff --git a/2001-2500/2177-Find-Three-Consecutive-Integers-That-Sum-to-a-Given-Number/cpp-2177/main.cpp b/2001-2500/2177-Find-Three-Consecutive-Integers-That-Sum-to-a-Given-Number/cpp-2177/main.cpp new file mode 100644 index 00000000..345d841f --- /dev/null +++ b/2001-2500/2177-Find-Three-Consecutive-Integers-That-Sum-to-a-Given-Number/cpp-2177/main.cpp @@ -0,0 +1,27 @@ +/// Source : https://leetcode.com/problems/find-three-consecutive-integers-that-sum-to-a-given-number/ +/// Author : liuyubobobo +/// Time : 2022-02-19 + +#include +#include + +using namespace std; + + +/// Math +/// Time Complexity: O(1) +/// Space Complexity: O(1) +class Solution { +public: + vector sumOfThree(long long num) { + + if(num % 3ll) return {}; + return {num / 3 - 1, num / 3, num / 3 + 1}; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2178-Maximum-Split-of-Positive-Even-Integers/cpp-2178/CMakeLists.txt b/2001-2500/2178-Maximum-Split-of-Positive-Even-Integers/cpp-2178/CMakeLists.txt new file mode 100644 index 00000000..36385f67 --- /dev/null +++ b/2001-2500/2178-Maximum-Split-of-Positive-Even-Integers/cpp-2178/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_2178) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2178 main.cpp) diff --git a/2001-2500/2178-Maximum-Split-of-Positive-Even-Integers/cpp-2178/main.cpp b/2001-2500/2178-Maximum-Split-of-Positive-Even-Integers/cpp-2178/main.cpp new file mode 100644 index 00000000..e897709c --- /dev/null +++ b/2001-2500/2178-Maximum-Split-of-Positive-Even-Integers/cpp-2178/main.cpp @@ -0,0 +1,38 @@ +/// Source : https://leetcode.com/problems/maximum-split-of-positive-even-integers/ +/// Author : liuyubobobo +/// Time : 2022-02-19 + +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(sqrt(sum)) +/// Space Complexity: O(1) +class Solution { +public: + vector maximumEvenSplit(long long finalSum) { + + if(finalSum % 2ll) return {}; + + vector res; + long long cur = 2; + while(finalSum >= cur){ + res.push_back(cur); + finalSum -= cur; + cur += 2; + } + + if(finalSum == 0) return res; + res.back() += finalSum; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2179-Count-Good-Triplets-in-an-Array/cpp-2179/CMakeLists.txt b/2001-2500/2179-Count-Good-Triplets-in-an-Array/cpp-2179/CMakeLists.txt new file mode 100644 index 00000000..e69f946e --- /dev/null +++ b/2001-2500/2179-Count-Good-Triplets-in-an-Array/cpp-2179/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_2179) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2179 main.cpp) diff --git a/2001-2500/2179-Count-Good-Triplets-in-an-Array/cpp-2179/main.cpp b/2001-2500/2179-Count-Good-Triplets-in-an-Array/cpp-2179/main.cpp new file mode 100644 index 00000000..abab1e63 --- /dev/null +++ b/2001-2500/2179-Count-Good-Triplets-in-an-Array/cpp-2179/main.cpp @@ -0,0 +1,136 @@ +/// Source : https://leetcode.com/problems/count-good-triplets-in-an-array/ +/// Author : liuyubobobo +/// Time : 2022-02-20 + +#include +#include + +using namespace std; + + +/// Using Segment Tree +/// Time Complexity: O(nlogn) +/// Space Compelxity: O(n) +template +class SegmentTree{ + +private: + int n; + vector data, tree; + T (*combine)(T a, T b); + +public: + SegmentTree(const vector& data, T (*combine)(T a, T b)): n(data.size()), data(data), tree(4 * n, 0){ + this->combine = combine; + buildSegTree(0, 0, n - 1); + } + + SegmentTree(int n, T (*combine)(T a, T b)): n(n), data(n, 0), tree(4 * n, 0){ + this->combine = combine; + } + + void add(int index, T value){ +// if(data[index] == value) return; + data[index] += value; + add(0, 0, n - 1, index, value); + } + + T query(int index){ + assert(0 <= index && index < n); + return data[index]; + } + + T query(int l, int r){ + + if(l <= r && 0 <= l && l < n && 0 <= r && r < n) + return query(0, 0, n - 1, l, r); + return 0; + } + +private: + void buildSegTree(int treeID, int l, int r){ + + if(l == r){ + tree[treeID] = data[l]; + return; + } + + int mid = (l + r) / 2; + buildSegTree(treeID * 2 + 1, l, mid); + buildSegTree(treeID * 2 + 2, mid + 1, r); + tree[treeID] = combine(tree[treeID * 2 + 1], tree[treeID * 2 + 2]); + return; + } + + void add(int treeID, int l, int r, int index, T value){ + + if(l == r){ + assert(l == index); + tree[treeID] += value; + return; + } + + int mid = (l + r) / 2; + if(index <= mid) add(treeID * 2 + 1, l, mid, index, value); + else add(treeID * 2 + 2, mid + 1, r, index, value); + + tree[treeID] = combine(tree[treeID * 2 + 1], tree[treeID * 2 + 2]); + return; + } + + T query(int treeID, int l, int r, int ql, int qr){ + + if(ql == l && qr == r) + return tree[treeID]; + + int mid = (l + r) / 2; + if(qr <= mid) return query(treeID * 2 + 1, l, mid, ql, qr); + else if(ql > mid) return query(treeID * 2 + 2, mid + 1, r, ql, qr); + + T resl = query(treeID * 2 + 1, l, mid, ql, mid); + T resr = query(treeID * 2 + 2, mid + 1, r, mid + 1, qr); + return combine(resl, resr); + } +}; + +class Solution { +public: + long long goodTriplets(vector& nums1, vector& nums2) { + + int n = nums1.size(); + + vector nums2pos(n); + for(int i = 0; i < nums2.size(); i ++) + nums2pos[nums2[i]] = i; + + auto add = [](long long a, long long b){return a + b;}; + SegmentTree seg_tree(n, add); + SegmentTree good2_for_nums1(n, add), good2_for_nums2(n, add); + long long res = 0; + for(int i = n - 1; i >= 0; i --){ + long long t = seg_tree.query(nums2pos[nums1[i]], n - 1); + good2_for_nums1.add(i, t); + good2_for_nums2.add(nums2pos[nums1[i]], t); + + res += min(good2_for_nums1.query(i + 1, n - 1), good2_for_nums2.query(nums2pos[nums1[i]] + 1, n - 1)); + seg_tree.add(nums2pos[nums1[i]], 1); + + } + + return res; + } +}; + + +int main() { + + vector nums11 = {2, 0, 1, 3}, nums12 = {0, 1, 2, 3}; + cout << Solution().goodTriplets(nums11, nums12) << endl; + // 1 + + vector nums21 = {4, 0, 1, 3, 2}, nums22 = {4, 1, 0, 2, 3}; + cout << Solution().goodTriplets(nums21, nums22) << endl; + // 4 + + return 0; +} diff --git a/2001-2500/2180-Count-Integers-With-Even-Digit-Sum/cpp-2180/CMakeLists.txt b/2001-2500/2180-Count-Integers-With-Even-Digit-Sum/cpp-2180/CMakeLists.txt new file mode 100644 index 00000000..a3422f8f --- /dev/null +++ b/2001-2500/2180-Count-Integers-With-Even-Digit-Sum/cpp-2180/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/2001-2500/2180-Count-Integers-With-Even-Digit-Sum/cpp-2180/main.cpp b/2001-2500/2180-Count-Integers-With-Even-Digit-Sum/cpp-2180/main.cpp new file mode 100644 index 00000000..879a05ce --- /dev/null +++ b/2001-2500/2180-Count-Integers-With-Even-Digit-Sum/cpp-2180/main.cpp @@ -0,0 +1,42 @@ +/// Source : https://leetcode.com/problems/count-integers-with-even-digit-sum/ +/// Author : liuyubobobo +/// Time : 2022-02-19 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + int countEven(int num) { + + int res = 0; + for(int e = 1; e <= num; e ++) + res += ok(e); + return res; + } + +private: + bool ok(int e){ + int res = 0; + while(e) res += e % 10, e /= 10; + return res % 2 == 0; + } +}; + + +int main() { + + cout << Solution().countEven(4) << endl; + // 2 + + cout << Solution().countEven(30) << endl; + // 14 + + return 0; +} diff --git a/2001-2500/2181-Merge-Nodes-in-Between-Zeros/cpp-2181/CMakeLists.txt b/2001-2500/2181-Merge-Nodes-in-Between-Zeros/cpp-2181/CMakeLists.txt new file mode 100644 index 00000000..0700646a --- /dev/null +++ b/2001-2500/2181-Merge-Nodes-in-Between-Zeros/cpp-2181/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/2001-2500/2181-Merge-Nodes-in-Between-Zeros/cpp-2181/main.cpp b/2001-2500/2181-Merge-Nodes-in-Between-Zeros/cpp-2181/main.cpp new file mode 100644 index 00000000..2dfa9a5a --- /dev/null +++ b/2001-2500/2181-Merge-Nodes-in-Between-Zeros/cpp-2181/main.cpp @@ -0,0 +1,48 @@ +/// Source : https://leetcode.com/problems/merge-nodes-in-between-zeros/ +/// Author : liuyubobobo +/// Time : 2022-02-19 + +#include +#include + +using namespace std; + + +/// Linked List +/// Time Complexity: O(n) +/// Space Complexity: O(1) + +/// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode() : val(0), next(nullptr) {} + ListNode(int x) : val(x), next(nullptr) {} + ListNode(int x, ListNode *next) : val(x), next(next) {} +}; + +class Solution { +public: + ListNode* mergeNodes(ListNode* head) { + + ListNode* dummy_head = new ListNode(-1); + ListNode* res_cur = dummy_head; + + int sum = 0; + for(ListNode* cur = head->next; cur; cur = cur->next){ + if(cur->val == 0){ + res_cur->next = new ListNode(sum); + res_cur = res_cur->next; + sum = 0; + } + else sum += cur->val; + } + return dummy_head->next; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2182-Construct-String-With-Repeat-Limit/cpp-2182/CMakeLists.txt b/2001-2500/2182-Construct-String-With-Repeat-Limit/cpp-2182/CMakeLists.txt new file mode 100644 index 00000000..8accde5b --- /dev/null +++ b/2001-2500/2182-Construct-String-With-Repeat-Limit/cpp-2182/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/2001-2500/2182-Construct-String-With-Repeat-Limit/cpp-2182/main.cpp b/2001-2500/2182-Construct-String-With-Repeat-Limit/cpp-2182/main.cpp new file mode 100644 index 00000000..d4b72d16 --- /dev/null +++ b/2001-2500/2182-Construct-String-With-Repeat-Limit/cpp-2182/main.cpp @@ -0,0 +1,69 @@ +/// Source : https://leetcode.com/problems/construct-string-with-repeat-limit/ +/// Author : liuyubobobo +/// Time : 2022-02-19 + +#include +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + string repeatLimitedString(string s, int repeatLimit) { + + vector f(26, 0); + for(char c: s) f[c - 'a'] ++; + + string res = ""; + while(true){ + pair p = get_first_and_second(f); + int first = p.first, second = p.second; + if(first == -1 || first == res.back() - 'a') break; + + int k = min(f[first], repeatLimit); + res += string(k, 'a' + first); + f[first] -= k; + + if(f[first] && second != -1){ + res += (char)('a' + second); + f[second] -= 1; + } + } + return res; + } + +private: + pair get_first_and_second(const vector& f){ + + int first = -1; + for(int i = 25; i >= 0; i --) + if(f[i]){ + first = i; + break; + } + + int second = -1; + for(int i = first - 1; i >= 0; i --) + if(f[i]){ + second = i; + break; + } + return {first, second}; + } +}; + +int main() { + + cout << Solution().repeatLimitedString("cczazcc", 3) << endl; + // zzcccac + + cout << Solution().repeatLimitedString("aababab", 2) << endl; + // bbabaa + + return 0; +} diff --git a/2001-2500/2183-Count-Array-Pairs-Divisible-by-K/cpp-2183/CMakeLists.txt b/2001-2500/2183-Count-Array-Pairs-Divisible-by-K/cpp-2183/CMakeLists.txt new file mode 100644 index 00000000..2552f642 --- /dev/null +++ b/2001-2500/2183-Count-Array-Pairs-Divisible-by-K/cpp-2183/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main2.cpp) diff --git a/2001-2500/2183-Count-Array-Pairs-Divisible-by-K/cpp-2183/main.cpp b/2001-2500/2183-Count-Array-Pairs-Divisible-by-K/cpp-2183/main.cpp new file mode 100644 index 00000000..c83e1a58 --- /dev/null +++ b/2001-2500/2183-Count-Array-Pairs-Divisible-by-K/cpp-2183/main.cpp @@ -0,0 +1,59 @@ +/// Source : https://leetcode.com/problems/count-array-pairs-divisible-by-k/ +/// Author : liuyubobobo +/// Time : 2022-02-19 + +#include +#include +#include +#include + +using namespace std; + + +/// Get all divisors for every number +/// Time Complexity: O(n*sqrt(n)) +/// Space Complexity: O(maxn) +class Solution { +public: + long long countPairs(vector& nums, int k) { + + int maxn = max(*max_element(nums.begin(), nums.end()), k); + + vector f(maxn + 1, 0); + long long res = 0; + for(int e: nums){ + vector divisors; + for(int d = 1; d * d <= e; d ++) + if(e % d == 0){ + divisors.push_back(d); + if(d * d < e) divisors.push_back(e / d); + } + sort(divisors.begin(), divisors.end()); + + int left = -1; + for(int i = (int)divisors.size() - 1; i >= 0; i --) + if(k % divisors[i] == 0){ + left = k / divisors[i]; + break; + } + res += f[left]; + + for(int d: divisors) f[d] ++; + } + return res; + } +}; + + +int main() { + + vector nums1 = {1, 2, 3, 4, 5}; + cout << Solution().countPairs(nums1, 2) << endl; + // 7 + + vector nums2 = {1, 2, 3, 4}; + cout << Solution().countPairs(nums2, 5) << endl; + // 0 + + return 0; +} diff --git a/2001-2500/2183-Count-Array-Pairs-Divisible-by-K/cpp-2183/main2.cpp b/2001-2500/2183-Count-Array-Pairs-Divisible-by-K/cpp-2183/main2.cpp new file mode 100644 index 00000000..ecd12835 --- /dev/null +++ b/2001-2500/2183-Count-Array-Pairs-Divisible-by-K/cpp-2183/main2.cpp @@ -0,0 +1,58 @@ +/// Source : https://leetcode.com/problems/count-array-pairs-divisible-by-k/ +/// Author : liuyubobobo +/// Time : 2022-02-20 + +#include +#include +#include +#include + +using namespace std; + + +/// Get all divisors for k +/// Time Complexity: O(n*sqrt(k)) +/// Space Complexity: O(k) +class Solution { +public: + long long countPairs(vector& nums, int k) { + + vector divisors; + for(int d = 1; d * d <= k; d ++) + if(k % d == 0){ + divisors.push_back(d); + if(d * d < k) divisors.push_back(k / d); + } + sort(divisors.begin(), divisors.end()); + + vector f(k + 1, 0); + long long res = 0; + for(int e: nums){ + + int left = -1; + for(int i = (int)divisors.size() - 1; i >= 0; i --) + if(e % divisors[i] == 0){ + left = k / divisors[i]; + break; + } + res += f[left]; + + for(int d: divisors) if(e % d == 0) f[d] ++; + } + return res; + } +}; + + +int main() { + + vector nums1 = {1, 2, 3, 4, 5}; + cout << Solution().countPairs(nums1, 2) << endl; + // 7 + + vector nums2 = {1, 2, 3, 4}; + cout << Solution().countPairs(nums2, 5) << endl; + // 0 + + return 0; +} diff --git a/2001-2500/2184-Number-of-Ways-to-Build-Sturdy-Brick-Wall/cpp-2184/CMakeLists.txt b/2001-2500/2184-Number-of-Ways-to-Build-Sturdy-Brick-Wall/cpp-2184/CMakeLists.txt new file mode 100644 index 00000000..1b860ca2 --- /dev/null +++ b/2001-2500/2184-Number-of-Ways-to-Build-Sturdy-Brick-Wall/cpp-2184/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_2184) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2184 main.cpp) diff --git a/2001-2500/2184-Number-of-Ways-to-Build-Sturdy-Brick-Wall/cpp-2184/main.cpp b/2001-2500/2184-Number-of-Ways-to-Build-Sturdy-Brick-Wall/cpp-2184/main.cpp new file mode 100644 index 00000000..8c707d57 --- /dev/null +++ b/2001-2500/2184-Number-of-Ways-to-Build-Sturdy-Brick-Wall/cpp-2184/main.cpp @@ -0,0 +1,96 @@ +/// Source : https://leetcode.com/problems/number-of-ways-to-build-sturdy-brick-wall/ +/// Author : liuyubobobo +/// Time : 2022-02-25 + +#include +#include +#include + +using namespace std; + + +/// Backtrack + DP +/// Time Complexity: O(|brick|^|brick| + k^2 * height) where k is the way to fill one row +/// Space Complexity: O(k) +class Solution { + +private: + const long long MOD = 1e9 + 7; + +public: + int buildWall(int height, int width, vector& bricks) { + + vector> rows; + vector row; + dfs(bricks, width, row, rows); + + for(vector& row: rows){ + for(int i = 1; i < row.size(); i ++) + row[i] += row[i - 1]; + assert(row.back() == width); + row.pop_back(); + } + + int n = rows.size(); + if(n == 0) return 0; + + vector> ok(n, vector(n, false)); + for(int i = 0; i < n; i ++) + for(int j = i; j < n; j ++) + ok[i][j] = get_ok(rows[i], rows[j]), ok[j][i] = ok[i][j]; + + vector dp(n, 1); + for(int h = 2; h <= height; h ++){ + vector tdp(n, 0); + for(int i = 0; i < n; i ++){ + for(int j = 0; j < n; j ++) + tdp[i] += dp[j] * ok[i][j]; + tdp[i] %= MOD; + } + dp = tdp; + } + return accumulate(dp.begin(), dp.end(), 0ll) % MOD; + } + +private: + bool get_ok(const vector& r1, const vector& r2){ + int i = 0, j = 0; + while(i < r1.size() && j < r2.size()){ + if(r1[i] == r2[j]) return false; + if(r1[i] < r2[j]) i ++; + else j ++; + } + return true; + } + + void dfs(const vector& bricks, int left, vector& row, vector>& rows){ + + if(left == 0) rows.push_back(row); + if(left <= 0) return; + + for(int brick: bricks){ + row.push_back(brick); + dfs(bricks, left - brick, row, rows); + row.pop_back(); + } + return; + } +}; + + +int main() { + + vector bricks1 = {1, 2}; + cout << Solution().buildWall(2, 3, bricks1) << endl; + // 2 + + vector bricks2 = {5}; + cout << Solution().buildWall(1, 1, bricks2) << endl; + // 0 + + vector bricks3 = {6, 3, 5, 1, 9}; + cout << Solution().buildWall(76, 9, bricks3) << endl; + // 201495766 + + return 0; +} diff --git a/2001-2500/2184-Number-of-Ways-to-Build-Sturdy-Brick-Wall/cpp-2184/main2.cpp b/2001-2500/2184-Number-of-Ways-to-Build-Sturdy-Brick-Wall/cpp-2184/main2.cpp new file mode 100644 index 00000000..2fae1f40 --- /dev/null +++ b/2001-2500/2184-Number-of-Ways-to-Build-Sturdy-Brick-Wall/cpp-2184/main2.cpp @@ -0,0 +1,75 @@ +/// Source : https://leetcode.com/problems/number-of-ways-to-build-sturdy-brick-wall/ +/// Author : liuyubobobo +/// Time : 2022-02-25 + +#include +#include +#include + +using namespace std; + + +/// Backtrack + DP +/// Using bit compression +/// Time Complexity: O(|brick|^|brick| + k^2 * height) where k is the way to fill one row +/// Space Complexity: O(k) +class Solution { + +private: + const long long MOD = 1e9 + 7; + +public: + int buildWall(int height, int width, vector& bricks) { + + vector rows; + dfs(bricks, width, 0, 0, rows); + + int n = rows.size(); + if(n == 0) return 0; + + vector dp(n, 1), tdp(n, 0); + for(int h = 2; h <= height; h ++){ + tdp.assign(n, 0); + for(int i = 0; i < n; i ++){ + for(int j = 0; j < n; j ++) + tdp[i] += dp[j] * !!!(rows[j] & rows[i]); + tdp[i] %= MOD; + } + dp = tdp; + } + + return accumulate(dp.begin(), dp.end(), 0ll) % MOD; + } + +private: + void dfs(const vector& bricks, int width, int cur, int state, vector& rows){ + + if(cur == width){ + rows.push_back(state ^ (1 << width)); + return; + } + + for(int brick: bricks) + if(cur + brick <= width) + dfs(bricks, width, cur + brick, state | (1 << (cur + brick)), rows); + return; + } +}; + + +int main() { + + vector bricks1 = {1, 2}; + cout << Solution().buildWall(2, 3, bricks1) << endl; + // 2 + + vector bricks2 = {5}; + cout << Solution().buildWall(1, 1, bricks2) << endl; + // 0 + + vector bricks3 = {6, 3, 5, 1, 9}; + cout << Solution().buildWall(76, 9, bricks3) << endl; + // 201495766 + + return 0; +} diff --git a/2001-2500/2185-Counting-Words-With-a-Given-Prefix/A/CMakeLists.txt b/2001-2500/2185-Counting-Words-With-a-Given-Prefix/A/CMakeLists.txt new file mode 100644 index 00000000..a3422f8f --- /dev/null +++ b/2001-2500/2185-Counting-Words-With-a-Given-Prefix/A/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/2001-2500/2185-Counting-Words-With-a-Given-Prefix/A/main.cpp b/2001-2500/2185-Counting-Words-With-a-Given-Prefix/A/main.cpp new file mode 100644 index 00000000..118c2a6b --- /dev/null +++ b/2001-2500/2185-Counting-Words-With-a-Given-Prefix/A/main.cpp @@ -0,0 +1,29 @@ +/// Source : https://leetcode.com/problems/counting-words-with-a-given-prefix/ +/// Author : liuyubobobo +/// Time : 2022-02-26 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n * len) +/// Space Complexity: O(1) +class Solution { +public: + int prefixCount(vector& words, string pref) { + + int res = 0; + for(const string& word: words) + if(word.find(pref) == 0) res ++; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2186-Minimum-Number-of-Steps-to-Make-Two-Strings-Anagram-II/cpp-2186/CMakeLists.txt b/2001-2500/2186-Minimum-Number-of-Steps-to-Make-Two-Strings-Anagram-II/cpp-2186/CMakeLists.txt new file mode 100644 index 00000000..0700646a --- /dev/null +++ b/2001-2500/2186-Minimum-Number-of-Steps-to-Make-Two-Strings-Anagram-II/cpp-2186/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/2001-2500/2186-Minimum-Number-of-Steps-to-Make-Two-Strings-Anagram-II/cpp-2186/main.cpp b/2001-2500/2186-Minimum-Number-of-Steps-to-Make-Two-Strings-Anagram-II/cpp-2186/main.cpp new file mode 100644 index 00000000..b8b20487 --- /dev/null +++ b/2001-2500/2186-Minimum-Number-of-Steps-to-Make-Two-Strings-Anagram-II/cpp-2186/main.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/minimum-number-of-steps-to-make-two-strings-anagram-ii/ +/// Author : liuyubobobo +/// Time : 2022-02-26 + +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(|s| + |t|) +/// Space Complexity: O(1) +class Solution { +public: + int minSteps(string s, string t) { + + vector sf(26, 0), tf(26, 0); + for(char c: s) sf[c - 'a'] ++; + for(char c: t) tf[c - 'a'] ++; + + int res = 0; + for(int i = 0; i < 26; i ++) + res += abs(sf[i] - tf[i]); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2187-Minimum-Time-to-Complete-Trips/cpp-2187/CMakeLists.txt b/2001-2500/2187-Minimum-Time-to-Complete-Trips/cpp-2187/CMakeLists.txt new file mode 100644 index 00000000..8accde5b --- /dev/null +++ b/2001-2500/2187-Minimum-Time-to-Complete-Trips/cpp-2187/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/2001-2500/2187-Minimum-Time-to-Complete-Trips/cpp-2187/main.cpp b/2001-2500/2187-Minimum-Time-to-Complete-Trips/cpp-2187/main.cpp new file mode 100644 index 00000000..92baa1f7 --- /dev/null +++ b/2001-2500/2187-Minimum-Time-to-Complete-Trips/cpp-2187/main.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/minimum-time-to-complete-trips/ +/// Author : liuyubobobo +/// Time : 2022-02-26 + +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(n * log(MAXN)) +/// Space Complexity: O(1) +class Solution { +public: + long long minimumTime(vector& time, int totalTrips) { + + long long l = 0, r = 1e14; + while(l < r){ + long long mid = (l + r) / 2ll; + if(ok(time, mid, totalTrips)) r = mid; + else l = mid + 1; + } + return l; + } + +private: + bool ok(const vector& time, long long mid, int totalTrips){ + long long res = 0; + for(int t: time){ + res += mid / t; + if(res >= totalTrips) break; + } + return res >= totalTrips; + } +}; + + +int main() { + + vector time1 = {1, 2, 3}; + cout << Solution().minimumTime(time1, 5) << endl; + // 3 + + vector time2 = {2}; + cout << Solution().minimumTime(time2, 1) << endl; + // 2 + + return 0; +} diff --git a/2001-2500/2188-Minimum-Time-to-Finish-the-Race/cpp-2188/CMakeLists.txt b/2001-2500/2188-Minimum-Time-to-Finish-the-Race/cpp-2188/CMakeLists.txt new file mode 100644 index 00000000..9031340e --- /dev/null +++ b/2001-2500/2188-Minimum-Time-to-Finish-the-Race/cpp-2188/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) diff --git a/2001-2500/2188-Minimum-Time-to-Finish-the-Race/cpp-2188/main.cpp b/2001-2500/2188-Minimum-Time-to-Finish-the-Race/cpp-2188/main.cpp new file mode 100644 index 00000000..2a80faa7 --- /dev/null +++ b/2001-2500/2188-Minimum-Time-to-Finish-the-Race/cpp-2188/main.cpp @@ -0,0 +1,67 @@ +/// Source : https://leetcode.com/problems/minimum-time-to-finish-the-race/ +/// Author : liuyubobobo +/// Time : 2022-02-26 + +#include +#include +#include + +using namespace std; + + +/// Memoization +/// Time Complexity: O(n * log(MAX_TIME) + numLaps ^ 2) +/// Space Complexity: O(n + numLaps^2) +class Solution { +public: + int minimumFinishTime(vector>& tires, long long changeTime, long long numLaps) { + + int n = tires.size(); + sort(tires.begin(), tires.end()); + + long long L = (numLaps - 1ll) * changeTime + numLaps * tires[0][0]; + vector minT(numLaps + 1, LONG_LONG_MAX); + for(int i = 0; i < n; i ++){ + long long sum = 0, cur = tires[i][0]; + for(int j = 1; j <= numLaps && sum <= L; j ++){ + sum += cur; + cur *= tires[i][1]; + minT[j] = min(minT[j], sum); + } + } + + vector dp(numLaps + 1, -1); + return dfs(numLaps, minT, changeTime, dp); + } + +private: + long long dfs(int left, const vector& minT, long long changeTime, + vector& dp){ + + if(left == 0) return 0; + if(dp[left] != -1) return dp[left]; + + long long res = LONG_LONG_MAX; + for(int i = 1; i <= left && minT[i] != LONG_LONG_MAX; i ++){ + long long tres = minT[i] + (i == left ? 0 : changeTime) + dfs(left - i, minT, changeTime, dp); + res = min(res, tres); + } + return dp[left] = res; + } +}; + + +int main() { + + vector> tires1 = {{2, 3}, {3, 4}}; + int changeTime1 = 5, numLaps1 = 4; + cout << Solution().minimumFinishTime(tires1, changeTime1, numLaps1) << endl; + // 21 + + vector> tires2 = {{1, 10}, {2, 2}, {3, 4}}; + int changeTime2 = 6, numLaps2 = 5; + cout << Solution().minimumFinishTime(tires2, changeTime2, numLaps2) << endl; + // 25 + + return 0; +} diff --git a/2001-2500/2189-Number-of-Ways-to-Build-House-of-Cards/cpp-2189/CMakeLists.txt b/2001-2500/2189-Number-of-Ways-to-Build-House-of-Cards/cpp-2189/CMakeLists.txt new file mode 100644 index 00000000..29ccd364 --- /dev/null +++ b/2001-2500/2189-Number-of-Ways-to-Build-House-of-Cards/cpp-2189/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_2189) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2189 main.cpp) diff --git a/2001-2500/2189-Number-of-Ways-to-Build-House-of-Cards/cpp-2189/main.cpp b/2001-2500/2189-Number-of-Ways-to-Build-House-of-Cards/cpp-2189/main.cpp new file mode 100644 index 00000000..5dbb8ed9 --- /dev/null +++ b/2001-2500/2189-Number-of-Ways-to-Build-House-of-Cards/cpp-2189/main.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/number-of-ways-to-build-house-of-cards/ +/// Author : liuyubobobo +/// Time : 2022-03-04 + +#include +#include + +using namespace std; + + +/// Memoization +/// Time Complexity: O(n^3) +/// Space Complexity: O(n^2) +class Solution { +public: + int houseOfCards(int n) { + + if(n < 2) return 0; + + int max_count = 1 + (n - 2) / 3 + !!((n - 2) % 3); + vector> dp(max_count + 1, vector(n + 1, -1)); + return dfs(max_count, n, dp); + } + +private: + int dfs(int max_count, int n, vector>& dp){ + + if(n == 0) return 1; + if(n == 1 || max_count == 0) return 0; + if(dp[max_count][n] != -1) return dp[max_count][n]; + + int res = dfs(0, n - 2, dp); + for(int cnt = 5; cnt <= n && 1 + (cnt - 2) / 3 <= max_count; cnt += 3) + res += dfs((cnt - 2) / 3, n - cnt, dp); + return dp[max_count][n] = res; + } +}; + + +int main() { + + cout << Solution().houseOfCards(16) << '\n'; + // 2 + + cout << Solution().houseOfCards(2) << '\n'; + // 1 + + cout << Solution().houseOfCards(4) << '\n'; + // 0 + + return 0; +} diff --git a/2001-2500/2190-Most-Frequent-Number-Following-Key-In-an-Array/cpp-2190/CMakeLists.txt b/2001-2500/2190-Most-Frequent-Number-Following-Key-In-an-Array/cpp-2190/CMakeLists.txt new file mode 100644 index 00000000..7d086ba6 --- /dev/null +++ b/2001-2500/2190-Most-Frequent-Number-Following-Key-In-an-Array/cpp-2190/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_2190) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2190 main.cpp) diff --git a/2001-2500/2190-Most-Frequent-Number-Following-Key-In-an-Array/cpp-2190/main.cpp b/2001-2500/2190-Most-Frequent-Number-Following-Key-In-an-Array/cpp-2190/main.cpp new file mode 100644 index 00000000..6f2bdf9a --- /dev/null +++ b/2001-2500/2190-Most-Frequent-Number-Following-Key-In-an-Array/cpp-2190/main.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/most-frequent-number-following-key-in-an-array/ +/// Author : liuyubobobo +/// Time : 2022-03-05 + +#include +#include +#include + +using namespace std; + + +/// Using Map +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int mostFrequent(vector& nums, int key) { + + map f; + for(int i = 0; i + 1 < nums.size(); i ++) + if(nums[i] == key) f[nums[i + 1]] ++; + + int max_cnt = 0, res; + for(const pair& p: f) + if(p.second > max_cnt) max_cnt = p.second, res = p.first; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2191-Sort-the-Jumbled-Numbers/cpp-2191/CMakeLists.txt b/2001-2500/2191-Sort-the-Jumbled-Numbers/cpp-2191/CMakeLists.txt new file mode 100644 index 00000000..9ea5dd80 --- /dev/null +++ b/2001-2500/2191-Sort-the-Jumbled-Numbers/cpp-2191/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_2191) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2191 main.cpp) diff --git a/2001-2500/2191-Sort-the-Jumbled-Numbers/cpp-2191/main.cpp b/2001-2500/2191-Sort-the-Jumbled-Numbers/cpp-2191/main.cpp new file mode 100644 index 00000000..1345e6e8 --- /dev/null +++ b/2001-2500/2191-Sort-the-Jumbled-Numbers/cpp-2191/main.cpp @@ -0,0 +1,41 @@ +/// Source : https://leetcode.com/problems/sort-the-jumbled-numbers/ +/// Author : liuyubobobo +/// Time : 2022-03-05 + +#include +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(nlogn * log(num)) +/// Space Complexity: O(n) +class Solution { +public: + vector sortJumbled(vector& mapping, vector& nums) { + + int n = nums.size(); + vector> data(n); + for(int i = 0; i < n; i ++){ + data[i] = {0, i}; + + string s = to_string(nums[i]); + for(char& c: s) c = '0' + mapping[c - '0']; + data[i].first = atoi(s.c_str()); + } + + sort(data.begin(), data.end()); + + vector res(n); + for(int i = 0; i < n; i ++) res[i] = nums[data[i].second]; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2192-All-Ancestors-of-a-Node-in-a-Directed-Acyclic-Graph/cpp-2192/CMakeLists.txt b/2001-2500/2192-All-Ancestors-of-a-Node-in-a-Directed-Acyclic-Graph/cpp-2192/CMakeLists.txt new file mode 100644 index 00000000..1043e210 --- /dev/null +++ b/2001-2500/2192-All-Ancestors-of-a-Node-in-a-Directed-Acyclic-Graph/cpp-2192/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_2192) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2192 main.cpp) diff --git a/2001-2500/2192-All-Ancestors-of-a-Node-in-a-Directed-Acyclic-Graph/cpp-2192/main.cpp b/2001-2500/2192-All-Ancestors-of-a-Node-in-a-Directed-Acyclic-Graph/cpp-2192/main.cpp new file mode 100644 index 00000000..87848623 --- /dev/null +++ b/2001-2500/2192-All-Ancestors-of-a-Node-in-a-Directed-Acyclic-Graph/cpp-2192/main.cpp @@ -0,0 +1,56 @@ +/// Source : https://leetcode.com/problems/all-ancestors-of-a-node-in-a-directed-acyclic-graph/ +/// Author : liuyubobobo +/// Time : 2022-03-05 + +#include +#include +#include +#include + +using namespace std; + + +/// Topological Sort + Bitset +/// Time Complexity: O(n + m) +/// Space Complexity: O(n + m) +class Solution { +public: + vector> getAncestors(int n, vector>& edges) { + + vector> g(n); + for(const vector& e: edges) + g[e[0]].push_back(e[1]); + + vector in_degrees(n, 0); + for(int u = 0; u < n; u ++) + for(int v: g[u]) in_degrees[v] ++; + + queue q; + for(int u = 0; u < n; u ++) + if(in_degrees[u] == 0) q.push(u); + vector> res(n); + + while(!q.empty()){ + int u = q.front(); q.pop(); + + for(int v: g[u]){ + res[v].set(u); + res[v] |= res[u]; + in_degrees[v] --; + if(in_degrees[v] == 0) q.push(v); + } + } + + vector> ret(n); + for(int i = 0; i < n; i ++) + for(int j = 0; j < n; j ++) + if(res[i].test(j)) ret[i].push_back(j); + return ret; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2193-Minimum-Number-of-Moves-to-Make-Palindrome/cpp-2193/CMakeLists.txt b/2001-2500/2193-Minimum-Number-of-Moves-to-Make-Palindrome/cpp-2193/CMakeLists.txt new file mode 100644 index 00000000..7cc7d493 --- /dev/null +++ b/2001-2500/2193-Minimum-Number-of-Moves-to-Make-Palindrome/cpp-2193/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_2193) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2193 main.cpp) diff --git a/2001-2500/2193-Minimum-Number-of-Moves-to-Make-Palindrome/cpp-2193/main.cpp b/2001-2500/2193-Minimum-Number-of-Moves-to-Make-Palindrome/cpp-2193/main.cpp new file mode 100644 index 00000000..f3d12db4 --- /dev/null +++ b/2001-2500/2193-Minimum-Number-of-Moves-to-Make-Palindrome/cpp-2193/main.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/minimum-number-of-moves-to-make-palindrome/ +/// Author : liuyubobobo +/// Time : 2022-03-06 + +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { +public: + int minMovesToMakePalindrome(string s) { + + return dfs(s, 0, s.size() - 1); + } + +private: + int dfs(string& s, int l, int r){ + + if(l >= r) return 0; + if(s[l] == s[r]) return dfs(s, l + 1, r - 1); + + int front_pos, tail_pos, front_swaps = 0, tail_swaps = 0; + for(front_pos = l; front_pos <= r && s[front_pos] != s[r]; front_pos ++, front_swaps ++); + for(tail_pos = r; tail_pos >= l && s[tail_pos] != s[l]; tail_pos --, tail_swaps ++); + + + if(front_swaps <= tail_swaps){ + for(int i = front_pos - 1; i >= l; i --) swap(s[i], s[i + 1]); + return front_swaps + dfs(s, l + 1, r - 1); + } + + for(int i = tail_pos + 1; i <= r; i ++) swap(s[i - 1], s[i]); + return tail_swaps + dfs(s, l + 1, r - 1); + } +}; + + +int main() { + + cout << Solution().minMovesToMakePalindrome("aabb") << endl; + // 2 + + cout << Solution().minMovesToMakePalindrome("letelt") << endl; + // 2 + + cout << Solution().minMovesToMakePalindrome("eqvvhtcsaaqtqesvvqch") << endl; + // 17 + + return 0; +} diff --git a/2001-2500/2194-Cells-in-a-Range-on-an-Excel-Sheet/cpp-2194/CMakeLists.txt b/2001-2500/2194-Cells-in-a-Range-on-an-Excel-Sheet/cpp-2194/CMakeLists.txt new file mode 100644 index 00000000..a3422f8f --- /dev/null +++ b/2001-2500/2194-Cells-in-a-Range-on-an-Excel-Sheet/cpp-2194/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/2001-2500/2194-Cells-in-a-Range-on-an-Excel-Sheet/cpp-2194/main.cpp b/2001-2500/2194-Cells-in-a-Range-on-an-Excel-Sheet/cpp-2194/main.cpp new file mode 100644 index 00000000..315f2d24 --- /dev/null +++ b/2001-2500/2194-Cells-in-a-Range-on-an-Excel-Sheet/cpp-2194/main.cpp @@ -0,0 +1,36 @@ +/// Source : https://leetcode.com/problems/cells-in-a-range-on-an-excel-sheet/ +/// Author : liuyubobobo +/// Time : 2022-03-05 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: ((c2 - c1) * (r2 - r1) +/// Space Complexity: O(1) +class Solution { +public: + vector cellsInRange(string s) { + + char c1 = s[0], c2 = s[3]; + char r1 = s[1], r2 = s[4]; + + vector res; + for(char c = c1; c <= c2; c ++) + for(char r = r1; r <= r2; r ++){ + string t = ""; + t += c, t += r; + res.push_back(t); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2195-Append-K-Integers-With-Minimal-Sum/cpp-2195/CMakeLists.txt b/2001-2500/2195-Append-K-Integers-With-Minimal-Sum/cpp-2195/CMakeLists.txt new file mode 100644 index 00000000..0700646a --- /dev/null +++ b/2001-2500/2195-Append-K-Integers-With-Minimal-Sum/cpp-2195/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/2001-2500/2195-Append-K-Integers-With-Minimal-Sum/cpp-2195/main.cpp b/2001-2500/2195-Append-K-Integers-With-Minimal-Sum/cpp-2195/main.cpp new file mode 100644 index 00000000..831aa8f7 --- /dev/null +++ b/2001-2500/2195-Append-K-Integers-With-Minimal-Sum/cpp-2195/main.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/append-k-integers-with-minimal-sum/ +/// Author : liuyubobobo +/// Time : 2022-03-05 + +#include +#include + +using namespace std; + + +/// Sorting +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + long long minimalKSum(vector& nums, int k) { + + nums.push_back(0); + nums.push_back(INT_MAX); + sort(nums.begin(), nums.end()); + + long long res = 0; + for(int i = 1; i < nums.size() && k; i ++){ + long long l = nums[i - 1] + 1, r = nums[i] - 1; + long long len = r - l + 1; + if(len <= 0) continue; + + if(len <= k){ + res += (l + r) * len / 2ll; + k -= len; + } + else{ + len = k, r = l + len - 1ll; + res += (l + r) * len / 2ll; + k = 0; + } + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2196-Create-Binary-Tree-From-Descriptions/cpp-2196/CMakeLists.txt b/2001-2500/2196-Create-Binary-Tree-From-Descriptions/cpp-2196/CMakeLists.txt new file mode 100644 index 00000000..8accde5b --- /dev/null +++ b/2001-2500/2196-Create-Binary-Tree-From-Descriptions/cpp-2196/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/2001-2500/2196-Create-Binary-Tree-From-Descriptions/cpp-2196/main.cpp b/2001-2500/2196-Create-Binary-Tree-From-Descriptions/cpp-2196/main.cpp new file mode 100644 index 00000000..39d8714f --- /dev/null +++ b/2001-2500/2196-Create-Binary-Tree-From-Descriptions/cpp-2196/main.cpp @@ -0,0 +1,70 @@ +/// Source : https://leetcode.com/problems/create-binary-tree-from-descriptions/ +/// Author : liuyubobobo +/// Time : 2022-03-05 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(1) + +/// 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* createBinaryTree(vector>& descriptions) { + + map value2node; + set is_child; + for(const vector& des: descriptions){ + int parent_value = des[0]; + TreeNode* parent_node = nullptr; + if(value2node.count(parent_value)) + parent_node = value2node[parent_value]; + else{ + parent_node = new TreeNode(parent_value); + value2node[parent_value] = parent_node; + } + + int child_value = des[1]; + TreeNode* child_node = nullptr; + if(value2node.count(child_value)) + child_node = value2node[child_value]; + else{ + child_node = new TreeNode(child_value); + value2node[child_value] = child_node; + } + + if(des[2]) parent_node->left = child_node; + else parent_node->right = child_node; + + is_child.insert(child_value); + } + + for(const vector& des: descriptions) + if(!is_child.count(des[0])) return value2node[des[0]]; + assert(false); + return nullptr; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2197-Replace-Non-Coprime-Numbers-in-Array/cpp-2197/CMakeLists.txt b/2001-2500/2197-Replace-Non-Coprime-Numbers-in-Array/cpp-2197/CMakeLists.txt new file mode 100644 index 00000000..9031340e --- /dev/null +++ b/2001-2500/2197-Replace-Non-Coprime-Numbers-in-Array/cpp-2197/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) diff --git a/2001-2500/2197-Replace-Non-Coprime-Numbers-in-Array/cpp-2197/main.cpp b/2001-2500/2197-Replace-Non-Coprime-Numbers-in-Array/cpp-2197/main.cpp new file mode 100644 index 00000000..7312570a --- /dev/null +++ b/2001-2500/2197-Replace-Non-Coprime-Numbers-in-Array/cpp-2197/main.cpp @@ -0,0 +1,62 @@ +/// Source : https://leetcode.com/problems/replace-non-coprime-numbers-in-array/ +/// Author : liuyubobobo +/// Time : 2022-03-05 + +#include +#include +#include + +using namespace std; + + +/// Stack +/// Time Complexity: O(nlogn) +/// Space Complexity:O(logn) +class Solution { +public: + vector replaceNonCoprimes(vector& nums) { + + vector res; + for(int num: nums){ + int x = num, g; + while(!res.empty() && (g = gcd(x, res.back())) != 1){ + res.back() *= x / g; + x = res.back(); + res.pop_back(); + } + + res.push_back(x); + } + return res; + } + +private: + int gcd(int a, int b) + { + if(a > b) swap(a, b); + if (a == 0) return b; + return gcd(b % a, a); + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << ' '; cout << '\n'; +} + +int main() { + + vector nums1 = {6,4,3,2,7,6,2}; + print_vec(Solution().replaceNonCoprimes(nums1)); + // 12 7 6 + + vector nums2 = {2,2,1,1,3,3,3}; + print_vec(Solution().replaceNonCoprimes(nums2)); + // 2 1 1 3 + + vector nums3 = {287,41,49,287,899,23,23,20677,5,825}; + print_vec(Solution().replaceNonCoprimes(nums3)); + // 2009,20677,825 + + return 0; +} diff --git a/2001-2500/2198-Number-of-Single-Divisor-Triplets/cpp-2198/CMakeLists.txt b/2001-2500/2198-Number-of-Single-Divisor-Triplets/cpp-2198/CMakeLists.txt new file mode 100644 index 00000000..22b9be0b --- /dev/null +++ b/2001-2500/2198-Number-of-Single-Divisor-Triplets/cpp-2198/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_2198) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2198 main.cpp) diff --git a/2001-2500/2198-Number-of-Single-Divisor-Triplets/cpp-2198/main.cpp b/2001-2500/2198-Number-of-Single-Divisor-Triplets/cpp-2198/main.cpp new file mode 100644 index 00000000..4c7565ae --- /dev/null +++ b/2001-2500/2198-Number-of-Single-Divisor-Triplets/cpp-2198/main.cpp @@ -0,0 +1,67 @@ +/// Source : https://leetcode.com/problems/number-of-single-divisor-triplets/ +/// Author : liuyubobobo +/// Time : 2022-03-12 + +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(maxv^3) +/// Space Complexity: O(maxv) +class Solution { +public: + long long singleDivisorTriplet(vector& nums) { + + int maxv = 0; + vector f(101, 0); + for(int num: nums){ + f[num] ++; + maxv = max(maxv, num); + } + + long long res = 0ll; + for(int t1 = 1; t1 <= maxv; t1 ++) if(f[t1]) + for(int t2 = t1 + 1; t2 <= maxv; t2 ++) if(f[t2]) + for(int t3 = t2 + 1; t3 <= maxv; t3 ++) if(f[t3]){ + bool a = (t1 + t2 + t3) % t1; + bool b = (t1 + t2 + t3) % t2; + bool c = (t1 + t2 + t3) % t3; + if(a + b + c == 2) + res += f[t1] * f[t2] * f[t3] * 6; + } + + for(int t1 = 1; t1 <= maxv; t1 ++) if(f[t1]) + for(int t2 = t1 + 1; t2 <= maxv; t2 ++) if(f[t2]){ + if(f[t1] >= 2 && (t1 * 2 + t2) % t1 && (t1 * 2 + t2) % t2 == 0) + res += f[t1] * (f[t1] - 1) / 2 * f[t2] * 6; + if(f[t2] >= 2 && (t1 + t2 * 2) % t2 && (t1 + t2 * 2) % t1 == 0) + res += f[t2] * (f[t2] - 1) / 2 * f[t1] * 6; + } + return res; + } +}; + + +int main() { + + vector nums1 = {4,6,7,3,2}; + cout << Solution().singleDivisorTriplet(nums1) << '\n'; + // 12 + + vector nums2 = {1,2,2}; + cout << Solution().singleDivisorTriplet(nums2) << '\n'; + // 6 + + vector nums3 = {1,1,1}; + cout << Solution().singleDivisorTriplet(nums3) << '\n'; + // 0 + + vector nums4 = {71,2,88,93,15,88,69}; + cout << Solution().singleDivisorTriplet(nums4) << '\n'; + // 48 + + return 0; +} diff --git a/2001-2500/2200-Find-All-K-Distant-Indices-in-an-Array/cpp-2200/CMakeLists.txt b/2001-2500/2200-Find-All-K-Distant-Indices-in-an-Array/cpp-2200/CMakeLists.txt new file mode 100644 index 00000000..a3422f8f --- /dev/null +++ b/2001-2500/2200-Find-All-K-Distant-Indices-in-an-Array/cpp-2200/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/2001-2500/2200-Find-All-K-Distant-Indices-in-an-Array/cpp-2200/main.cpp b/2001-2500/2200-Find-All-K-Distant-Indices-in-an-Array/cpp-2200/main.cpp new file mode 100644 index 00000000..eaa5f1ac --- /dev/null +++ b/2001-2500/2200-Find-All-K-Distant-Indices-in-an-Array/cpp-2200/main.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/find-all-k-distant-indices-in-an-array/ +/// Author : liuyubobobo +/// Time : 2022-03-12 + +#include +#include +#include + +using namespace std; + + +/// BruteForce +/// Time Complexity: O(n^2) +/// Space Complexity: O(1) +class Solution { +public: + vector findKDistantIndices(vector& nums, int key, int k) { + + int n = nums.size(); + vector res; + for(int i = 0; i < n; i ++) + for(int j = max(i - k, 0); j <= min(i + k, n - 1); j ++) + if(nums[j] == key){ + res.push_back(i); + break; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2201-Count-Artifacts-That-Can-Be-Extracted/cpp-2201/CMakeLists.txt b/2001-2500/2201-Count-Artifacts-That-Can-Be-Extracted/cpp-2201/CMakeLists.txt new file mode 100644 index 00000000..0700646a --- /dev/null +++ b/2001-2500/2201-Count-Artifacts-That-Can-Be-Extracted/cpp-2201/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/2001-2500/2201-Count-Artifacts-That-Can-Be-Extracted/cpp-2201/main.cpp b/2001-2500/2201-Count-Artifacts-That-Can-Be-Extracted/cpp-2201/main.cpp new file mode 100644 index 00000000..b082d924 --- /dev/null +++ b/2001-2500/2201-Count-Artifacts-That-Can-Be-Extracted/cpp-2201/main.cpp @@ -0,0 +1,41 @@ +/// Source : https://leetcode.com/problems/count-artifacts-that-can-be-extracted/ +/// Author : liuyubobobo +/// Time : 2022-03-12 + +#include +#include + +using namespace std; + + +/// 2D Presum +/// Time Complexity: O(n^2 + |dig| + |artifacts|) +/// Space Complexity: O(n^2) +class Solution { +public: + int digArtifacts(int n, vector>& artifacts, vector>& dig) { + + vector> g(n, vector(n, 1)); + for(const vector& p: dig) + g[p[0]][p[1]] = 0; + + vector> presum(n + 1, vector(n + 1, 0)); + for(int i = 0; i < n; i ++) + for(int j = 0; j < n; j ++) + presum[i + 1][j + 1] = g[i][j] + presum[i][j + 1] + presum[i + 1][j] - presum[i][j]; + + int res = 0; + for(const vector& p: artifacts){ + int x1 = p[0], y1 = p[1], x2 = p[2], y2 = p[3]; + int sum = presum[x2 + 1][y2 + 1] - presum[x1][y2 + 1] - presum[x2 + 1][y1] + presum[x1][y1]; + res += (sum == 0); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2202-Maximize-the-Topmost-Element-After-K-Moves/cpp-2202/CMakeLists.txt b/2001-2500/2202-Maximize-the-Topmost-Element-After-K-Moves/cpp-2202/CMakeLists.txt new file mode 100644 index 00000000..8accde5b --- /dev/null +++ b/2001-2500/2202-Maximize-the-Topmost-Element-After-K-Moves/cpp-2202/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/2001-2500/2202-Maximize-the-Topmost-Element-After-K-Moves/cpp-2202/main.cpp b/2001-2500/2202-Maximize-the-Topmost-Element-After-K-Moves/cpp-2202/main.cpp new file mode 100644 index 00000000..b29a8c9e --- /dev/null +++ b/2001-2500/2202-Maximize-the-Topmost-Element-After-K-Moves/cpp-2202/main.cpp @@ -0,0 +1,72 @@ +/// Source : https://leetcode.com/problems/maximize-the-topmost-element-after-k-moves/ +/// Author : liuyubobobo +/// Time : 2022-03-12 + +#include +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int maximumTop(vector& nums, int k) { + + int n = nums.size(); + + if(k == 0) return n > 0 ? nums[0] : -1; + if(k == 1) return n == 1 ? -1 : nums[1]; + + int res = -1, left_op = k, can_add_max = -1; + for(int i = 0; i < min(k, n); i ++){ + left_op --; + + can_add_max = max(can_add_max, nums[i]); + + if(i + 1 < n && left_op % 2 == 0) + res = max(res, nums[i + 1]); + + if(left_op && (left_op % 2 || i)) + res = max(res, can_add_max); + } + return res; + } +}; + + +int main() { + + vector nums1 = {5,2,2,4,0,6}; + cout << Solution().maximumTop(nums1, 4) << '\n'; + // 5 + + vector nums2 = {2}; + cout << Solution().maximumTop(nums2, 1) << '\n'; + // -1 + + vector nums3 = {31,15,92,84,19,92,55}; + cout << Solution().maximumTop(nums3, 4) << '\n'; + // 92 + + vector nums4 = {55,39,99,57,82,48,39,91,82,68,86,4,64,38,73,40,51,66,58,44,55,6,100,6,49,91,34,87,42,22,77,74,31,67,15,99,57,21,61,79,93,98,29,9,34,51,89,67,83,49,2,17,14,29,73,7,41,64,93,83,21,89,66,100,38,45,27,31,25,16,78,32,74,21,48,99,77,65,8,47,93,67}; + cout << Solution().maximumTop(nums4, 40) << '\n'; + // 100 + + vector nums5 = {52,98,7,10,27,1,33,17,14,70,79,41,37,83,58,69,52,14,66,7,36,32,39,69,65,64,45,90,34,68,44,51,36,49,71,54,63,76,73,76,67,26,54,76,89,92,89,69,26,55,93,89,15,3,54,91,21,93,78,29,79,59,14,80,70,29,5,80,93,69,29,22,3,6,2,36,31,3,22,96,32,25,97,82,78,10,83,46,98,30,1,93,89}; + cout << Solution().maximumTop(nums5, 27) << '\n'; + // 98 + + vector nums6 = {91,98,17,79,15,55,47,86,4,5,17,79,68,60,60,31,72,85,25,77,8,78,40,96,76,69,95,2,42,87,48,72,45,25,40,60,21,91,32,79,2,87,80,97,82,94,69,43,18,19,21,36,44,81,99}; + cout << Solution().maximumTop(nums6, 2) << '\n'; + // 91 + + vector nums7 = {4,6,1,0,6,2,4}; + cout << Solution().maximumTop(nums7, 0) << '\n'; + // 4 + + return 0; +} diff --git a/2001-2500/2203-Minimum-Weighted-Subgraph-With-the-Required-Paths/cpp-2203/CMakeLists.txt b/2001-2500/2203-Minimum-Weighted-Subgraph-With-the-Required-Paths/cpp-2203/CMakeLists.txt new file mode 100644 index 00000000..9031340e --- /dev/null +++ b/2001-2500/2203-Minimum-Weighted-Subgraph-With-the-Required-Paths/cpp-2203/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) diff --git a/2001-2500/2203-Minimum-Weighted-Subgraph-With-the-Required-Paths/cpp-2203/main.cpp b/2001-2500/2203-Minimum-Weighted-Subgraph-With-the-Required-Paths/cpp-2203/main.cpp new file mode 100644 index 00000000..7db74345 --- /dev/null +++ b/2001-2500/2203-Minimum-Weighted-Subgraph-With-the-Required-Paths/cpp-2203/main.cpp @@ -0,0 +1,85 @@ +/// Source : https://leetcode.com/problems/minimum-weighted-subgraph-with-the-required-paths/ +/// Author : liuyubobobo +/// Time : 2022-03-12 + +#include +#include +#include +#include + +using namespace std; + + +/// Dijkstra +/// Time Complexity: O(nlogn) +/// Space Complexity: O(V + E) +class Solution { + +private: + long long INF = LONG_LONG_MAX / 3; + +public: + long long minimumWeight(int n, vector>& edges, int src1, int src2, int dest) { + + vector>> g(n), rg(n); + for(const vector& e: edges){ + int u = e[0], v = e[1]; + long long w = e[2]; + g[u].push_back({v, w}); + rg[v].push_back({u, w}); + } + + vector dis1 = dij(n, g, src1); + if(dis1[dest] >= INF) return -1; + + vector dis2 = dij(n, g, src2); + if(dis2[dest] >= INF) return -1; + + vector rdis = dij(n, rg, dest); + + long long res = rdis[src1] + rdis[src2]; + for(int i = 0; i < n; i ++) + res = min(res, rdis[i] + dis1[i] + dis2[i]); + return res; + } + +private: + vector dij(int n, const vector>>& g, int s){ + + vector dis(n, INF); + vector visited(n, false); + priority_queue, vector>, greater>> pq; + pq.push({0, s}); + dis[s] = 0; + while(!pq.empty()){ + long long d = pq.top().first; + int u = pq.top().second; + pq.pop(); + + if(visited[u]) continue; + visited[u] = true; + + for(const pair& p: g[u]){ + int v = p.first; + long long w = p.second; + if(!visited[v] && d + w < dis[v]){ + dis[v] = d + w; + pq.push({dis[v], v}); + } + } + } + return dis; + } +}; + + +int main() { + + vector> edges1 = { + {0,2,2},{0,5,6},{1,0,3},{1,4,5},{2,1,1},{2,3,3},{2,3,4},{3,4,2},{4,5,1} + }; + cout << Solution().minimumWeight(6, edges1, 0, 1, 5) << '\n'; + // 9 + + return 0; +} diff --git a/2001-2500/2204-Distance-to-a-Cycle-in-Undirected-Graph/cpp-2204/CMakeLists.txt b/2001-2500/2204-Distance-to-a-Cycle-in-Undirected-Graph/cpp-2204/CMakeLists.txt new file mode 100644 index 00000000..2139f045 --- /dev/null +++ b/2001-2500/2204-Distance-to-a-Cycle-in-Undirected-Graph/cpp-2204/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_2204) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2204 main.cpp) diff --git a/2001-2500/2204-Distance-to-a-Cycle-in-Undirected-Graph/cpp-2204/main.cpp b/2001-2500/2204-Distance-to-a-Cycle-in-Undirected-Graph/cpp-2204/main.cpp new file mode 100644 index 00000000..c38476de --- /dev/null +++ b/2001-2500/2204-Distance-to-a-Cycle-in-Undirected-Graph/cpp-2204/main.cpp @@ -0,0 +1,95 @@ +/// Source : https://leetcode.com/problems/distance-to-a-cycle-in-undirected-graph/ +/// Author : liuyubobobo +/// Time : 2022-03-19 + +#include +#include +#include + +using namespace std; + + +/// Graph get cycle and BFS +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector distanceToCycle(int n, vector>& edges) { + + vector> g(n); + for(const vector& e: edges) + g[e[0]].push_back(e[1]), g[e[1]].push_back(e[0]); + + vector cycle = get_cycle(n, g); +// for(int e: cycle) cout << e << ' '; cout << '\n'; + + queue q; + vector res(n, -1); + for(int e: cycle){ + q.push(e); + res[e] = 0; + } + + while(!q.empty()){ + int u = q.front(); q.pop(); + + for(int v: g[u]){ + if(res[v] != -1) continue; + res[v] = res[u] + 1; + q.push(v); + } + } + return res; + } + +private: + vector get_cycle(int n, const vector>& g){ + + vector visited(n, false); + vector pre(n, -1); + vector cycle; + dfs(g, 0, -1, visited, pre, cycle); + return cycle; + } + + bool dfs(const vector>& g, int u, int p, + vector& visited, vector& pre, vector& cycle){ + + visited[u] = true; + pre[u] = p; + for(int v: g[u]){ + if(v == p) continue; + if(!visited[v]){ + if(dfs(g, v, u, visited, pre, cycle)) return true; + } + else{ + cycle.push_back(v); + int cur = u; + while(cur != v){ + cycle.push_back(cur); + cur = pre[cur]; + } + return true; + } + } + return false; + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << ' '; cout << '\n'; +} + +int main() { + + vector> edges1 = {{1,2},{2,3},{3,4},{4,1},{0,1},{5,2},{6,5}}; + print_vec(Solution().distanceToCycle(7, edges1)); + // 1 0 0 0 0 1 2 + + vector> edges2 = {{0,1},{1,2},{0,2},{2,6},{6,7},{6,8},{1,3},{3,4},{3,5}}; + print_vec(Solution().distanceToCycle(9, edges2)); + // 0,0,0,1,2,2,1,2,2 + + return 0; +} diff --git a/2001-2500/2206-Divide-Array-Into-Equal-Pairs/cpp-2206/CMakeLists.txt b/2001-2500/2206-Divide-Array-Into-Equal-Pairs/cpp-2206/CMakeLists.txt new file mode 100644 index 00000000..a3422f8f --- /dev/null +++ b/2001-2500/2206-Divide-Array-Into-Equal-Pairs/cpp-2206/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/2001-2500/2206-Divide-Array-Into-Equal-Pairs/cpp-2206/main.cpp b/2001-2500/2206-Divide-Array-Into-Equal-Pairs/cpp-2206/main.cpp new file mode 100644 index 00000000..3c694edc --- /dev/null +++ b/2001-2500/2206-Divide-Array-Into-Equal-Pairs/cpp-2206/main.cpp @@ -0,0 +1,32 @@ +/// Source : https://leetcode.com/problems/divide-array-into-equal-pairs/ +/// Author : liuyubobobo +/// Time : 2022-03-19 + +#include +#include +#include + +using namespace std; + + +/// Using Map +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + bool divideArray(vector& nums) { + + unordered_map f; + for(int e: nums) f[e] ++; + + for(const pair& p: f) + if(p.second % 2) return false; + return true; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2207-Maximize-Number-of-Subsequences-in-a-String/cpp-2207/CMakeLists.txt b/2001-2500/2207-Maximize-Number-of-Subsequences-in-a-String/cpp-2207/CMakeLists.txt new file mode 100644 index 00000000..0700646a --- /dev/null +++ b/2001-2500/2207-Maximize-Number-of-Subsequences-in-a-String/cpp-2207/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/2001-2500/2207-Maximize-Number-of-Subsequences-in-a-String/cpp-2207/main.cpp b/2001-2500/2207-Maximize-Number-of-Subsequences-in-a-String/cpp-2207/main.cpp new file mode 100644 index 00000000..55c2bf7f --- /dev/null +++ b/2001-2500/2207-Maximize-Number-of-Subsequences-in-a-String/cpp-2207/main.cpp @@ -0,0 +1,56 @@ +/// Source : https://leetcode.com/problems/maximize-number-of-subsequences-in-a-string/ +/// Author : liuyubobobo +/// Time : 2022-03-19 + +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + long long maximumSubsequenceCount(string text, string pattern) { + + string s1 = string(1, pattern[0]) + text; + long long res1 = get_res(s1, pattern[0], pattern[1]); + + string s2 = text + pattern[1]; + long long res2 = get_res(s2, pattern[0], pattern[1]); + + return max(res1, res2); + } + +private: + long long get_res(const string& s, char a, char b){ + + long long bnum = 0; + for(char c: s) bnum += (c == b); + + if(a == b) return bnum * (bnum - 1) / 2ll; + + long long res = 0, anum = 0; + for(char c: s) + if(c == a) anum ++, res += bnum; + else if(c == b) bnum --; + return res; + } +}; + + +int main() { + + cout << Solution().maximumSubsequenceCount("abdcdbc", "ac") << '\n'; + // 4 + + cout << Solution().maximumSubsequenceCount("aabb", "ab") << '\n'; + // 6 + + cout << Solution().maximumSubsequenceCount("mffiqmrvjmkfmbnaivajzecfdta", "hh") << '\n'; + // 0 + + return 0; +} diff --git a/2001-2500/2208-Minimum-Operations-to-Halve-Array-Sum/cpp-2208/CMakeLists.txt b/2001-2500/2208-Minimum-Operations-to-Halve-Array-Sum/cpp-2208/CMakeLists.txt new file mode 100644 index 00000000..8accde5b --- /dev/null +++ b/2001-2500/2208-Minimum-Operations-to-Halve-Array-Sum/cpp-2208/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/2001-2500/2208-Minimum-Operations-to-Halve-Array-Sum/cpp-2208/main.cpp b/2001-2500/2208-Minimum-Operations-to-Halve-Array-Sum/cpp-2208/main.cpp new file mode 100644 index 00000000..c0a08ccf --- /dev/null +++ b/2001-2500/2208-Minimum-Operations-to-Halve-Array-Sum/cpp-2208/main.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/minimum-operations-to-halve-array-sum/ +/// Author : liuyubobobo +/// Time : 2022-03-19 + +#include +#include +#include +#include + +using namespace std; + + +/// Using Priority Queue +/// Time Complexity: O(xlogn) +/// Space Complexity: O(n) +class Solution { +public: + int halveArray(vector& nums) { + + long long sum = accumulate(nums.begin(), nums.end(), 0ll); + long double target = sum / 2.0; + + priority_queue pq; + for(int e: nums) pq.push(e); + + long double cur = 0; + int res = 0; + while(cur < target){ + long double x = pq.top(); + pq.pop(); + + cur += x / 2.0; + res ++; + + pq.push(x / 2.0); + } + return res; + } +}; + + +int main() { + + vector nums1 = {5, 19, 8, 1}; + cout << Solution().halveArray(nums1) << '\n'; + // 3 + + vector nums2 = {3, 8, 20}; + cout << Solution().halveArray(nums2) << '\n'; + // 3 + + return 0; +} diff --git a/2001-2500/2209-Minimum-White-Tiles-After-Covering-With-Carpets/cpp-2209/CMakeLists.txt b/2001-2500/2209-Minimum-White-Tiles-After-Covering-With-Carpets/cpp-2209/CMakeLists.txt new file mode 100644 index 00000000..9031340e --- /dev/null +++ b/2001-2500/2209-Minimum-White-Tiles-After-Covering-With-Carpets/cpp-2209/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) diff --git a/2001-2500/2209-Minimum-White-Tiles-After-Covering-With-Carpets/cpp-2209/main.cpp b/2001-2500/2209-Minimum-White-Tiles-After-Covering-With-Carpets/cpp-2209/main.cpp new file mode 100644 index 00000000..16952d61 --- /dev/null +++ b/2001-2500/2209-Minimum-White-Tiles-After-Covering-With-Carpets/cpp-2209/main.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/minimum-white-tiles-after-covering-with-carpets/ +/// Author : liuyubobobo +/// Time : 2022-03-19 + +#include +#include + +using namespace std; + + +/// Memoization +/// Time Complexity: O(n^2) +/// Space Complexity: O(n^2) +class Solution { +public: + int minimumWhiteTiles(string floor, int numCarpets, int carpetLen) { + + int n = floor.size(); + vector presum(n + 1, 0); + for(int i = 0; i < n; i ++) presum[i + 1] = presum[i] + (floor[i] == '1'); + + vector> dp(n, vector(numCarpets + 1, -1)); + return dfs(n, floor, presum, carpetLen, 0, numCarpets, dp); + } + +private: + int dfs(int n, const string& floor, const vector& presum, int len, + int index, int num, vector>& dp){ + + if(index == n) return 0; + if(num == 0) return presum[n] - presum[index]; + if(dp[index][num] != -1) return dp[index][num]; + + int r = min(index + len - 1, n - 1); + int res = dfs(n, floor, presum, len, r + 1, num - 1, dp); + + res = min(res, (floor[index] == '1') + dfs(n, floor, presum, len, index + 1, num, dp)); + return dp[index][num] = res; + } +}; + + +int main() { + + cout << Solution().minimumWhiteTiles("10110101", 2, 2) << '\n'; + // 2 + + cout << Solution().minimumWhiteTiles("11111", 2, 3) << '\n'; + // 0 + + return 0; +} diff --git a/2001-2500/2210-Count-Hills-and-Valleys-in-an-Array/cpp-2210/CMakeLists.txt b/2001-2500/2210-Count-Hills-and-Valleys-in-an-Array/cpp-2210/CMakeLists.txt new file mode 100644 index 00000000..a3422f8f --- /dev/null +++ b/2001-2500/2210-Count-Hills-and-Valleys-in-an-Array/cpp-2210/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/2001-2500/2210-Count-Hills-and-Valleys-in-an-Array/cpp-2210/main.cpp b/2001-2500/2210-Count-Hills-and-Valleys-in-an-Array/cpp-2210/main.cpp new file mode 100644 index 00000000..d7123f1d --- /dev/null +++ b/2001-2500/2210-Count-Hills-and-Valleys-in-an-Array/cpp-2210/main.cpp @@ -0,0 +1,58 @@ +/// Source : https://leetcode.com/problems/count-hills-and-valleys-in-an-array/ +/// Author : liuyubobobo +/// Time : 2022-03-19 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n^2) +/// Space Complexity: O(1) +class Solution { +public: + int countHillValley(vector& nums) { + + int n = nums.size(), res = 0; + for(int start = 0, i = 1; i <= n; i ++){ + if(i == n || nums[i] != nums[start]){ + int left = -1, right = -1; + for(int j = start - 1; j >= 0; j --) + if(nums[j] != nums[start]){ + left = nums[j]; + break; + } + for(int j = start + 1; j < n; j ++) + if(nums[j] != nums[start]){ + right = nums[j]; + break; + } + if(left == -1 || right == -1){ + start = i; + continue; + } + if((left > nums[start] && right > nums[start]) || (left < nums[start] && right < nums[start])) + res ++; + + start = i; + } + } + return res; + } +}; + + +int main() { + + vector nums1 = {2, 4, 1, 1, 6, 5}; + cout << Solution().countHillValley(nums1) << '\n'; + // 3 + + vector nums2 = {6,6,5,5,4,1}; + cout << Solution().countHillValley(nums2) << '\n'; + // 0 + + return 0; +} diff --git a/2001-2500/2211-Count-Collisions-on-a-Road/cpp-2211/CMakeLists.txt b/2001-2500/2211-Count-Collisions-on-a-Road/cpp-2211/CMakeLists.txt new file mode 100644 index 00000000..0700646a --- /dev/null +++ b/2001-2500/2211-Count-Collisions-on-a-Road/cpp-2211/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/2001-2500/2211-Count-Collisions-on-a-Road/cpp-2211/main.cpp b/2001-2500/2211-Count-Collisions-on-a-Road/cpp-2211/main.cpp new file mode 100644 index 00000000..5ad1d8f6 --- /dev/null +++ b/2001-2500/2211-Count-Collisions-on-a-Road/cpp-2211/main.cpp @@ -0,0 +1,55 @@ +/// Source : https://leetcode.com/problems/count-collisions-on-a-road/ +/// Author : liuyubobobo +/// Time : 2022-03-19 + +#include +#include + +using namespace std; + + +/// Stack +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int countCollisions(string directions) { + + int res = 0; + string stack = ""; + for(char c: directions) + if(c == 'R') stack += c; + else if(c == 'L'){ + if(stack.empty()) continue; + else if(stack.back() == 'R'){ + res += 2, stack.pop_back(); + while(!stack.empty() && stack.back() == 'R') res ++, stack.pop_back(); + stack += 'S'; + } + else res ++; + } + else if(c == 'S'){ + if(stack.empty()) stack += 'S'; + else if(stack.back() == 'R'){ + while(!stack.empty() && stack.back() == 'R') res ++, stack.pop_back(); + stack += 'S'; + } + } + return res; + } +}; + + +int main() { + + cout << Solution().countCollisions("RLRSLL") << '\n'; + // 5 + + cout << Solution().countCollisions("LLRR") << '\n'; + // 0 + + cout << Solution().countCollisions("SSRSSRLLRSLLRSRSSRLRRRRLLRRLSSRR") << '\n'; + // 20 + + return 0; +} diff --git a/2001-2500/2212-Maximum-Points-in-an-Archery-Competition/cpp-2212/CMakeLists.txt b/2001-2500/2212-Maximum-Points-in-an-Archery-Competition/cpp-2212/CMakeLists.txt new file mode 100644 index 00000000..8accde5b --- /dev/null +++ b/2001-2500/2212-Maximum-Points-in-an-Archery-Competition/cpp-2212/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/2001-2500/2212-Maximum-Points-in-an-Archery-Competition/cpp-2212/main.cpp b/2001-2500/2212-Maximum-Points-in-an-Archery-Competition/cpp-2212/main.cpp new file mode 100644 index 00000000..7f69550b --- /dev/null +++ b/2001-2500/2212-Maximum-Points-in-an-Archery-Competition/cpp-2212/main.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/maximum-points-in-an-archery-competition/ +/// Author : liuyubobobo +/// Time : 2022-03-19 + +#include +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(2^12 * 12) +/// Space Complexity: O(12) +class Solution { +public: + vector maximumBobPoints(int numArrows, vector& aliceArrows) { + + int best_score = 0; + vector res(12, 0); + res[0] = numArrows; + + for(int state = 1; state < (1 << 12); state ++){ + vector tres(12, 0); + int tscore = 0; + for(int i = 0; i < 12; i ++) + if(state & (1 << i)){ + tres[i] = aliceArrows[i] + 1; + tscore += i; + } + if(tscore <= best_score) continue; + + int sum = accumulate(tres.begin(), tres.end(), 0); + if(sum > numArrows) continue; + + for(int i = 0; i < 12; i ++) + if(state & (1 << i)){ + tres[i] += (numArrows - sum); + break; + } + + best_score = tscore; + res = tres; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2213-Longest-Substring-of-One-Repeating-Character/cpp-2213/CMakeLists.txt b/2001-2500/2213-Longest-Substring-of-One-Repeating-Character/cpp-2213/CMakeLists.txt new file mode 100644 index 00000000..9031340e --- /dev/null +++ b/2001-2500/2213-Longest-Substring-of-One-Repeating-Character/cpp-2213/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) diff --git a/2001-2500/2213-Longest-Substring-of-One-Repeating-Character/cpp-2213/main.cpp b/2001-2500/2213-Longest-Substring-of-One-Repeating-Character/cpp-2213/main.cpp new file mode 100644 index 00000000..3bf795e3 --- /dev/null +++ b/2001-2500/2213-Longest-Substring-of-One-Repeating-Character/cpp-2213/main.cpp @@ -0,0 +1,111 @@ +/// Source : https://leetcode.com/problems/longest-substring-of-one-repeating-character/ +/// Author : liuyubobobo +/// Time : 2022-03-19 + +#include +#include +#include +#include +#include +#include + +using namespace std; + + +/// Using Tree Map and TreeSet to store segments +/// Time Complexity: O(nlogn + qlogn) +/// Space Complexity: O(n) +class Solution { +private: + map, char> segs; + multiset lens; + +public: + vector longestRepeating(string s, string queryCharacters, vector& queryIndices) { + + for(int start = 0, i = 1; i <= s.size(); i ++) + if(i == s.size() || s[i] != s[start]){ + segs[{start, i - 1}] = s[start]; + lens.insert(i - start); + start = i; + } + + vector res(queryCharacters.size()); + for(int q = 0; q < queryCharacters.size(); q ++){ + int index = queryIndices[q], qch = queryCharacters[q]; + + auto iter = segs.upper_bound({index, INT_MAX}); + iter --; + + int l = iter->first.first, r = iter->first.second; + char och = iter->second; + if(qch != och){ + + segs.erase(iter); + lens.erase(lens.find(r - l + 1)); + + if(l <= index - 1){ + segs[{l, index - 1}] = och; + lens.insert(index - 1 - l + 1); + } + if(index + 1 <= r){ + segs[{index + 1, r}] = och; + lens.insert(r - (index + 1) + 1); + } + insert(index, index, qch); + } + + res[q] = *lens.rbegin(); + } + return res; + } + +private: + void insert(int insert_l, int insert_r, char ch){ + + auto iter = segs.upper_bound({insert_l, INT_MAX}); + if(iter != segs.end() && iter->second == ch){ + int l = iter->first.first, r = iter->first.second; + segs.erase(iter); + lens.erase(lens.find(r - l + 1)); + + insert(insert_l, r, ch); + return; + } + + iter = segs.upper_bound({insert_l, INT_MAX}); + if(iter != segs.begin()){ + iter --; + if(iter->second == ch){ + int l = iter->first.first, r = iter->first.second; + segs.erase(iter); + lens.erase(lens.find(r - l + 1)); + + segs[{l, insert_r}] = ch; + lens.insert(insert_r - l + 1); + return; + } + } + + segs[{insert_l, insert_r}] = ch; + lens.insert(insert_r - insert_l + 1); + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << ' '; cout << '\n'; +} + +int main() { + + vector q1 = {1, 3, 3}; + print_vec(Solution().longestRepeating("babacc", "bcb", q1)); + // 3 3 4 + + vector q2 = {2, 1}; + print_vec(Solution().longestRepeating("abyzz", "aa", q2)); + // 2 3 + + return 0; +} diff --git a/2001-2500/2214-Minimum-Health-to-Beat-Game/cpp-2214/CMakeLists.txt b/2001-2500/2214-Minimum-Health-to-Beat-Game/cpp-2214/CMakeLists.txt new file mode 100644 index 00000000..481c8260 --- /dev/null +++ b/2001-2500/2214-Minimum-Health-to-Beat-Game/cpp-2214/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_2214) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2214 main.cpp) diff --git a/2001-2500/2214-Minimum-Health-to-Beat-Game/cpp-2214/main.cpp b/2001-2500/2214-Minimum-Health-to-Beat-Game/cpp-2214/main.cpp new file mode 100644 index 00000000..facb1c5f --- /dev/null +++ b/2001-2500/2214-Minimum-Health-to-Beat-Game/cpp-2214/main.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/minimum-health-to-beat-game/ +/// Author : liuyubobobo +/// Time : 2022-03-24 + +#include +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + long long minimumHealth(vector& damage, int armor) { + + int max_damage = *max_element(damage.begin(), damage.end()); + long long sum = accumulate(damage.begin(), damage.end(), 0ll); + + if(max_damage >= armor) sum -= armor; + else sum -= max_damage; + + return sum + 1; + } +}; + + +int main() { + + vector damage1 = {2, 7, 4, 3}; + cout << Solution().minimumHealth(damage1, 4) << '\n'; + // 13 + + return 0; +} diff --git a/2001-2500/2215-Find-the-Difference-of-Two-Arrays/cpp-2215/CMakeLists.txt b/2001-2500/2215-Find-the-Difference-of-Two-Arrays/cpp-2215/CMakeLists.txt new file mode 100644 index 00000000..a3422f8f --- /dev/null +++ b/2001-2500/2215-Find-the-Difference-of-Two-Arrays/cpp-2215/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/2001-2500/2215-Find-the-Difference-of-Two-Arrays/cpp-2215/main.cpp b/2001-2500/2215-Find-the-Difference-of-Two-Arrays/cpp-2215/main.cpp new file mode 100644 index 00000000..35434319 --- /dev/null +++ b/2001-2500/2215-Find-the-Difference-of-Two-Arrays/cpp-2215/main.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/find-the-difference-of-two-arrays/ +/// Author : liuyubobobo +/// Time : 2022-03-26 + +#include +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { +public: + vector> findDifference(vector& nums1, vector& nums2) { + + set res1; + for(int e: nums1) + if(find(nums2.begin(), nums2.end(), e) == nums2.end()) res1.insert(e); + + set res2; + for(int e: nums2) + if(find(nums1.begin(), nums1.end(), e) == nums1.end()) res2.insert(e); + + return {vector(res1.begin(), res1.end()), vector(res2.begin(), res2.end())}; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2216-Minimum-Deletions-to-Make-Array-Beautiful/cpp-2216/CMakeLists.txt b/2001-2500/2216-Minimum-Deletions-to-Make-Array-Beautiful/cpp-2216/CMakeLists.txt new file mode 100644 index 00000000..0700646a --- /dev/null +++ b/2001-2500/2216-Minimum-Deletions-to-Make-Array-Beautiful/cpp-2216/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/2001-2500/2216-Minimum-Deletions-to-Make-Array-Beautiful/cpp-2216/main.cpp b/2001-2500/2216-Minimum-Deletions-to-Make-Array-Beautiful/cpp-2216/main.cpp new file mode 100644 index 00000000..667df973 --- /dev/null +++ b/2001-2500/2216-Minimum-Deletions-to-Make-Array-Beautiful/cpp-2216/main.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/minimum-deletions-to-make-array-beautiful/ +/// Author : liuyubobobo +/// Time : 2022-03-26 + +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int minDeletion(vector& nums) { + + vector v; + int res = 0; + for(int e: nums) + if(v.size() % 2 == 0) v.push_back(e); + else if(e == v.back()) res ++; + else v.push_back(e); + + if(v.size() % 2 == 1) res ++; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2217-Find-Palindrome-With-Fixed-Length/cpp-2217/CMakeLists.txt b/2001-2500/2217-Find-Palindrome-With-Fixed-Length/cpp-2217/CMakeLists.txt new file mode 100644 index 00000000..e85d4767 --- /dev/null +++ b/2001-2500/2217-Find-Palindrome-With-Fixed-Length/cpp-2217/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main2.cpp) diff --git a/2001-2500/2217-Find-Palindrome-With-Fixed-Length/cpp-2217/main.cpp b/2001-2500/2217-Find-Palindrome-With-Fixed-Length/cpp-2217/main.cpp new file mode 100644 index 00000000..7e2d808b --- /dev/null +++ b/2001-2500/2217-Find-Palindrome-With-Fixed-Length/cpp-2217/main.cpp @@ -0,0 +1,47 @@ +#include +#include +#include + +using namespace std; + + +class Solution { + +public: + vector kthPalindrome(vector& queries, int intLength) { + + set data_set; + string s(intLength, ' '); + dfs(s, 0, intLength, data_set); + + vector data(data_set.begin(), data_set.end()); + vector res(queries.size(), -1); + for(int i = 0; i < queries.size(); i ++){ + int q = queries[i] - 1; + if(q < data.size()) res[i] = data[q]; + } + return res; + } + +private: + void dfs(string& s, int index, int len, set& data){ + + if(index > len - index - 1){ + data.insert(atoll(s.c_str())); + return; + } + + for(int d = (index == 0 ? 1 : 0); d <= 9; d ++){ + s[index] = s[len - index - 1] = (char)('0' + d); + dfs(s, index + 1, len, data); + } + } +}; + +int main() { + + vector queries1 = {97,902143467,332084633,15,139128663,347073005,167961442,32,15}; + Solution().kthPalindrome(queries1, 11); + + return 0; +} diff --git a/2001-2500/2217-Find-Palindrome-With-Fixed-Length/cpp-2217/main2.cpp b/2001-2500/2217-Find-Palindrome-With-Fixed-Length/cpp-2217/main2.cpp new file mode 100644 index 00000000..37def476 --- /dev/null +++ b/2001-2500/2217-Find-Palindrome-With-Fixed-Length/cpp-2217/main2.cpp @@ -0,0 +1,67 @@ +/// Source : https://leetcode.com/problems/find-palindrome-with-fixed-length/ +/// Author : liuyubobobo +/// Time : 2022-03-26 + +#include +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(intLength) for each query +/// Space Complexity: O(intLength) +class Solution { + +private: + vector pow10; + +public: + vector kthPalindrome(vector& queries, int intLength) { + + pow10 = {1ll}; + for(int i = 1; i <= 18; i ++) + pow10.push_back(pow10[i - 1] * 10ll); + + long long base = pow10[(intLength + 1) / 2 - 1]; + long long top = base * 10ll; + + vector res(queries.size(), -1); + for(int i = 0; i < queries.size(); i ++){ + int q = queries[i] - 1; + if(base + q >= top) continue; + + res[i] = get_palindrome(base + q, intLength); + } + return res; + } + +private: + long long get_palindrome(long long cur, int len){ + + if(len == 1) return cur; + + string s = to_string(cur); + if(len & 1) s.pop_back(); + reverse(s.begin(), s.end()); + long long second = atoll(s.c_str()); + return cur * pow10[s.size()] + second; + } +}; + + +void print_vec(const vector& v){ + for(long long e: v) cout << e << ' '; cout << '\n'; +} + +int main() { + + vector queries1 = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,9,8}; + print_vec(Solution().kthPalindrome(queries1, 1)); + + vector queries2 = {97,902143467,332084633,15,139128663,347073005,167961442,32,15}; + print_vec(Solution().kthPalindrome(queries2, 11)); + + return 0; +} diff --git a/2001-2500/2218-Maximum-Value-of-K-Coins-From-Piles/cpp-2218/CMakeLists.txt b/2001-2500/2218-Maximum-Value-of-K-Coins-From-Piles/cpp-2218/CMakeLists.txt new file mode 100644 index 00000000..9031340e --- /dev/null +++ b/2001-2500/2218-Maximum-Value-of-K-Coins-From-Piles/cpp-2218/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) diff --git a/2001-2500/2218-Maximum-Value-of-K-Coins-From-Piles/cpp-2218/main.cpp b/2001-2500/2218-Maximum-Value-of-K-Coins-From-Piles/cpp-2218/main.cpp new file mode 100644 index 00000000..97dbba2a --- /dev/null +++ b/2001-2500/2218-Maximum-Value-of-K-Coins-From-Piles/cpp-2218/main.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/maximum-value-of-k-coins-from-piles/ +/// Author : liuyubobobo +/// Time : 2022-03-26 + +#include +#include +#include + +using namespace std; + + +/// Memoization +/// Time Complexity: O(n * k) +/// Space Complexity: O(n * k) +class Solution { + +public: + int maxValueOfCoins(vector>& piles, int k) { + + int n = piles.size(); + vector> dp(n, vector(k + 1, INT_MIN)); + return dfs(n, piles, 0, k, dp); + } + +private: + int dfs(int n, const vector>& piles, + int index, int k, vector>& dp){ + + if(k == 0) return 0; + if(index == n) return INT_MIN / 2; + if(dp[index][k] != INT_MIN) return dp[index][k]; + + int res = dfs(n, piles, index + 1, k, dp); + int sum = 0, cnt = 0; + for(int e: piles[index]){ + sum += e; + cnt ++; + if(cnt > k) break; + res = max(res, sum + dfs(n, piles, index + 1, k - cnt, dp)); + } + return dp[index][k] = res; + } +}; + + +int main() { + + vector> piles1 = {{1, 100, 3}, {7, 8, 9}}; + cout << Solution().maxValueOfCoins(piles1, 2) << '\n'; + // 101 + + vector> piles2 = {{100}, {100}, {100}, {100}, {100}, {100}, {1,1,1,1,1,1,700}}; + cout << Solution().maxValueOfCoins(piles2, 7) << '\n'; + // 706 + + return 0; +} diff --git a/2001-2500/2219-Maximum-Sum-Score-of-Array/cpp-2219/CMakeLists.txt b/2001-2500/2219-Maximum-Sum-Score-of-Array/cpp-2219/CMakeLists.txt new file mode 100644 index 00000000..f9dfc97f --- /dev/null +++ b/2001-2500/2219-Maximum-Sum-Score-of-Array/cpp-2219/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_2219) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2219 main.cpp) diff --git a/2001-2500/2219-Maximum-Sum-Score-of-Array/cpp-2219/main.cpp b/2001-2500/2219-Maximum-Sum-Score-of-Array/cpp-2219/main.cpp new file mode 100644 index 00000000..c7c0bd4a --- /dev/null +++ b/2001-2500/2219-Maximum-Sum-Score-of-Array/cpp-2219/main.cpp @@ -0,0 +1,36 @@ +/// Source : https://leetcode.com/problems/maximum-sum-score-of-array/ +/// Author : liuyubobobo +/// Time : 2022-04-01 + +#include +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(n) +/// Space Compelxity: O(1) +class Solution { +public: + long long maximumSumScore(vector& nums) { + + long long tail = 0; + for(int e: nums) tail += e; + + long long front = nums[0]; + long long res = max(front, tail); + for(int i = 1; i < nums.size(); i ++){ + front += nums[i]; + tail -= nums[i - 1]; + res = max(res, max(front, tail)); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2220-Minimum-Bit-Flips-to-Convert-Number/cpp-2220/CMakeLists.txt b/2001-2500/2220-Minimum-Bit-Flips-to-Convert-Number/cpp-2220/CMakeLists.txt new file mode 100644 index 00000000..57079339 --- /dev/null +++ b/2001-2500/2220-Minimum-Bit-Flips-to-Convert-Number/cpp-2220/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_2220) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2220 main.cpp) diff --git a/2001-2500/2220-Minimum-Bit-Flips-to-Convert-Number/cpp-2220/main.cpp b/2001-2500/2220-Minimum-Bit-Flips-to-Convert-Number/cpp-2220/main.cpp new file mode 100644 index 00000000..54fb7af4 --- /dev/null +++ b/2001-2500/2220-Minimum-Bit-Flips-to-Convert-Number/cpp-2220/main.cpp @@ -0,0 +1,30 @@ +/// Source : https://leetcode.com/problems/minimum-bit-flips-to-convert-number/ +/// Author : liuyubobobo +/// Time : 2022-04-02 + +#include + +using namespace std; + + +/// Bitwise +/// Time Complexity: O(logn) +/// Space Complexity: O(1) +class Solution { +public: + int minBitFlips(int start, int goal) { + + int res = 0; + for(int b = 0; b <= 30; b ++) + res += ((start & (1 << b)) != (goal & (1 << b))); + return res; + } +}; + + +int main() { + + cout << Solution().minBitFlips(10, 7) << '\n'; + + return 0; +} diff --git a/2001-2500/2221-Find-Triangular-Sum-of-an-Array/cpp-2221/CMakeLists.txt b/2001-2500/2221-Find-Triangular-Sum-of-an-Array/cpp-2221/CMakeLists.txt new file mode 100644 index 00000000..170b4696 --- /dev/null +++ b/2001-2500/2221-Find-Triangular-Sum-of-an-Array/cpp-2221/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_2221) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2221 main.cpp) diff --git a/2001-2500/2221-Find-Triangular-Sum-of-an-Array/cpp-2221/main.cpp b/2001-2500/2221-Find-Triangular-Sum-of-an-Array/cpp-2221/main.cpp new file mode 100644 index 00000000..fa56476f --- /dev/null +++ b/2001-2500/2221-Find-Triangular-Sum-of-an-Array/cpp-2221/main.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/find-triangular-sum-of-an-array/ +/// Author : liuyubobobo +/// Time : 2022-04-02 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { +public: + int triangularSum(vector& nums) { + + vector t; + while(nums.size() > 1){ + for(int i = 1; i < nums.size(); i ++) + t.push_back((nums[i - 1] + nums[i]) % 10); + nums = t; + t.clear(); + } + return nums[0]; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2222-Number-of-Ways-to-Select-Buildings/cpp-2222/CMakeLists.txt b/2001-2500/2222-Number-of-Ways-to-Select-Buildings/cpp-2222/CMakeLists.txt new file mode 100644 index 00000000..94f43b63 --- /dev/null +++ b/2001-2500/2222-Number-of-Ways-to-Select-Buildings/cpp-2222/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_2222) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2222 main.cpp) diff --git a/2001-2500/2222-Number-of-Ways-to-Select-Buildings/cpp-2222/main.cpp b/2001-2500/2222-Number-of-Ways-to-Select-Buildings/cpp-2222/main.cpp new file mode 100644 index 00000000..77cab765 --- /dev/null +++ b/2001-2500/2222-Number-of-Ways-to-Select-Buildings/cpp-2222/main.cpp @@ -0,0 +1,42 @@ +/// Source : https://leetcode.com/problems/number-of-ways-to-select-buildings/ +/// Author : liuyubobobo +/// Time : 2022-04-02 + +#include +#include + +using namespace std; + + +/// Memoization +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + long long numberOfWays(string s) { + + int n = s.size(); + vector>> dp(2, vector>(4, vector(n, -1))); + return dfs(n, s, 0, 3, 0, dp) + dfs(n, s, 1, 3, 0, dp); + } + +private: + long long dfs(int n, const string& s, int select, int left, int index, + vector>>& dp){ + + if(left == 0) return 1; + if(index == n) return 0; + if(dp[select][left][index] != -1) return dp[select][left][index]; + + long long res = dfs(n, s, select, left, index + 1, dp); + if(s[index] == (char)('0' + select)) + res += dfs(n, s, 1 - select, left - 1, index + 1, dp); + return dp[select][left][index] = res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2223-Sum-of-Scores-of-Built-Strings/cpp-2223/CMakeLists.txt b/2001-2500/2223-Sum-of-Scores-of-Built-Strings/cpp-2223/CMakeLists.txt new file mode 100644 index 00000000..19d320e4 --- /dev/null +++ b/2001-2500/2223-Sum-of-Scores-of-Built-Strings/cpp-2223/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_2223) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2223 main.cpp) diff --git a/2001-2500/2223-Sum-of-Scores-of-Built-Strings/cpp-2223/main.cpp b/2001-2500/2223-Sum-of-Scores-of-Built-Strings/cpp-2223/main.cpp new file mode 100644 index 00000000..8c124251 --- /dev/null +++ b/2001-2500/2223-Sum-of-Scores-of-Built-Strings/cpp-2223/main.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/sum-of-scores-of-built-strings/ +/// Author : liuyubobobo +/// Time : 2022-04-02 + +#include +#include + +using namespace std; + + +/// z-algo +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + long long sumScores(string s) { + + vector v = z_function(s); +// for(int e: v) cout << e << ' '; cout << '\n'; + + long long res = 0; + for(int e: v) res += e; + return res + (long long)s.size(); + } + +private: + vector z_function(string s) { + + int n = (int)s.length(); + vector z(n); + + for (int i = 1, l = 0, r = 0; i < n; ++i) { + if (i <= r && z[i - l] < r - i + 1) + z[i] = z[i - l]; + else{ + z[i] = max(0, r - i + 1); + while (i + z[i] < n && s[z[i]] == s[i + z[i]]) ++z[i]; + } + + if (i + z[i] - 1 > r) + l = i, r = i + z[i] - 1; + } + return z; + } +}; + + +int main() { + + cout << Solution().sumScores("babab") << '\n'; + + return 0; +} diff --git a/2001-2500/2224-Minimum-Number-of-Operations-to-Convert-Time/cpp-2224/CMakeLists.txt b/2001-2500/2224-Minimum-Number-of-Operations-to-Convert-Time/cpp-2224/CMakeLists.txt new file mode 100644 index 00000000..a3422f8f --- /dev/null +++ b/2001-2500/2224-Minimum-Number-of-Operations-to-Convert-Time/cpp-2224/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/2001-2500/2224-Minimum-Number-of-Operations-to-Convert-Time/cpp-2224/main.cpp b/2001-2500/2224-Minimum-Number-of-Operations-to-Convert-Time/cpp-2224/main.cpp new file mode 100644 index 00000000..9e042700 --- /dev/null +++ b/2001-2500/2224-Minimum-Number-of-Operations-to-Convert-Time/cpp-2224/main.cpp @@ -0,0 +1,42 @@ +/// Source : https://leetcode.com/problems/minimum-number-of-operations-to-convert-time/ +/// Author : liuyubobobo +/// Time : 2022-04-02 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(t) +/// Space Complexity: O(1) +class Solution { +public: + int convertTime(string current, string correct) { + + int a = get_time(current), b = get_time(correct); + int d = b - a; + + int res = 0; + while(d >= 60) d -= 60, res ++; + while(d >= 15) d -= 15, res ++; + while(d >= 5) d -= 5, res ++; + res += d; + return res; + } + +private: + int get_time(const string& t){ + + int h = atoi(t.substr(0, 2).c_str()); + int m = atoi(t.substr(3, 2).c_str()); + return h * 60 + m; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2225-Find-Players-With-Zero-or-One-Losses/cpp-2225/CMakeLists.txt b/2001-2500/2225-Find-Players-With-Zero-or-One-Losses/cpp-2225/CMakeLists.txt new file mode 100644 index 00000000..0700646a --- /dev/null +++ b/2001-2500/2225-Find-Players-With-Zero-or-One-Losses/cpp-2225/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/2001-2500/2225-Find-Players-With-Zero-or-One-Losses/cpp-2225/main.cpp b/2001-2500/2225-Find-Players-With-Zero-or-One-Losses/cpp-2225/main.cpp new file mode 100644 index 00000000..0d519bc8 --- /dev/null +++ b/2001-2500/2225-Find-Players-With-Zero-or-One-Losses/cpp-2225/main.cpp @@ -0,0 +1,45 @@ +/// Source : https://leetcode.com/problems/find-players-with-zero-or-one-losses/ +/// Author : liuyubobobo +/// Time : 2022-04-02 + +#include +#include +#include +#include + +using namespace std; + + +/// Simulation, using map and set +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector> findWinners(vector>& matches) { + + set all_players; + + map losers; + for(const vector& match: matches){ + losers[match[1]] ++; + + all_players.insert(match[0]); + all_players.insert(match[1]); + } + + vector> res(2); + for(int player: all_players) + if(!losers.count(player)) res[0].push_back(player); + + for(const pair& p: losers) + if(p.second == 1) res[1].push_back(p.first); + + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2226-Maximum-Candies-Allocated-to-K-Children/cpp-2226/CMakeLists.txt b/2001-2500/2226-Maximum-Candies-Allocated-to-K-Children/cpp-2226/CMakeLists.txt new file mode 100644 index 00000000..8accde5b --- /dev/null +++ b/2001-2500/2226-Maximum-Candies-Allocated-to-K-Children/cpp-2226/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/2001-2500/2226-Maximum-Candies-Allocated-to-K-Children/cpp-2226/main.cpp b/2001-2500/2226-Maximum-Candies-Allocated-to-K-Children/cpp-2226/main.cpp new file mode 100644 index 00000000..b88373e2 --- /dev/null +++ b/2001-2500/2226-Maximum-Candies-Allocated-to-K-Children/cpp-2226/main.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/find-players-with-zero-or-one-losses/ +/// Author : liuyubobobo +/// Time : 2022-04-02 + +#include +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Compelxity: O(nlog(sum)) +/// Space Complexity: O(1) +class Solution { +public: + int maximumCandies(vector& candies, long long k) { + + int n = candies.size(); + vector data(n); + for(int i = 0; i < n; i ++) data[i] = candies[i]; + + long long sum = accumulate(data.begin(), data.end(), 0ll); + + long long l = 0, r = sum / k; + while(l < r){ + long long mid = (l + r + 1) / 2; + if(ok(n, data, mid, k)) l = mid; + else r = mid - 1; + } + return l; + } + +private: + bool ok(int n, const vector& data, long long t, long long k){ + + long long num = 0; + for(long long e: data) num += e / t; + return num >= k; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2227-Encrypt-and-Decrypt-Strings/cpp-2227/CMakeLists.txt b/2001-2500/2227-Encrypt-and-Decrypt-Strings/cpp-2227/CMakeLists.txt new file mode 100644 index 00000000..2552f642 --- /dev/null +++ b/2001-2500/2227-Encrypt-and-Decrypt-Strings/cpp-2227/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main2.cpp) diff --git a/2001-2500/2227-Encrypt-and-Decrypt-Strings/cpp-2227/main.cpp b/2001-2500/2227-Encrypt-and-Decrypt-Strings/cpp-2227/main.cpp new file mode 100644 index 00000000..e1c88a30 --- /dev/null +++ b/2001-2500/2227-Encrypt-and-Decrypt-Strings/cpp-2227/main.cpp @@ -0,0 +1,94 @@ +/// Source : https://leetcode.com/problems/encrypt-and-decrypt-strings/ +/// Author : liuyubobobo +/// Time : 2022-04-02 + +#include +#include +#include + +using namespace std; + + +/// Using Trie +/// Time Complexity: init: O(|keys| + |values| + character_number_in_dictionary) +/// encrypt: O(|word1|) +/// decrypt: O(min(|word2|^26, all_nodes_in_trie)) +/// Space Compelxity: O(|keys| + |values| + character_number_in_dictionary) +class Encrypter { + +private: + class Node{ + + public: + vector next; + bool is_word; + + Node() : next(26, nullptr), is_word(false) {}; + }; + + vector char2index; + vector index2char; + vector index2values; + map> len2s2indexes; + Node* root; + +public: + Encrypter(vector& keys, vector& values, vector& dictionary) : + index2char(keys), char2index(256, -1), + index2values(values), root(new Node()){ + + for(int i = 0; i < keys.size(); i ++) + char2index[keys[i]] = i; + + for(int i = 0; i < values.size(); i ++) + len2s2indexes[values[i]].push_back(i); + + for(const string& s: dictionary) + insert(s); + } + + string encrypt(string word1) { + + string res = ""; + for(char c: word1) + res += index2values[char2index[c]]; + return res; + } + + int decrypt(string word2) { + return dfs(word2, 0, root); + } + +private: + int dfs(const string& s, int index, Node* node){ + + if(index == s.size()) return node->is_word; + + string len2s = s.substr(index, 2); + vector& v = len2s2indexes[len2s]; + + int res = 0; + for(int i: v) + if(i < index2char.size() && node->next[index2char[i] - 'a']) + res += dfs(s, index + 2, node->next[index2char[i] - 'a']); + return res; + } + + void insert(const string& word) { + + Node* cur = root; + for(char c: word){ + if(cur->next[c - 'a'] == nullptr) + cur->next[c - 'a'] = new Node(); + cur = cur->next[c - 'a']; + } + + cur->is_word = true; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2227-Encrypt-and-Decrypt-Strings/cpp-2227/main2.cpp b/2001-2500/2227-Encrypt-and-Decrypt-Strings/cpp-2227/main2.cpp new file mode 100644 index 00000000..792b8efb --- /dev/null +++ b/2001-2500/2227-Encrypt-and-Decrypt-Strings/cpp-2227/main2.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/encrypt-and-decrypt-strings/ +/// Author : liuyubobobo +/// Time : 2022-04-02 + +#include +#include +#include + +using namespace std; + + +/// Reverse Thinking, Store all encrypt result in dictionary +/// Time Complexity: init: O(|keys| + |values| + |dictionary|) +/// encrypt: O(|word1|) +/// decrypt: O(|word2|) +/// Space Compelxity: O(|keys| + |values| + |dictionary|) +class Encrypter { + +private: + vector char2index; + vector index2values; + map table; + +public: + Encrypter(vector& keys, vector& values, vector& dictionary) : + char2index(256, -1), index2values(values){ + + for(int i = 0; i < keys.size(); i ++) + char2index[keys[i]] = i; + + for(const string& s: dictionary) + table[encrypt(s)] ++; + } + + string encrypt(string word1) { + + string res = ""; + for(char c: word1) + res += index2values[char2index[c]]; + return res; + } + + int decrypt(string word2) { + return table[word2]; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2229-Check-if-an-Array-Is-Consecutive/cpp-2229/CMakeLists.txt b/2001-2500/2229-Check-if-an-Array-Is-Consecutive/cpp-2229/CMakeLists.txt new file mode 100644 index 00000000..4ff8d070 --- /dev/null +++ b/2001-2500/2229-Check-if-an-Array-Is-Consecutive/cpp-2229/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_2229) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2229 main.cpp) diff --git a/2001-2500/2229-Check-if-an-Array-Is-Consecutive/cpp-2229/main.cpp b/2001-2500/2229-Check-if-an-Array-Is-Consecutive/cpp-2229/main.cpp new file mode 100644 index 00000000..dd812324 --- /dev/null +++ b/2001-2500/2229-Check-if-an-Array-Is-Consecutive/cpp-2229/main.cpp @@ -0,0 +1,30 @@ +/// Source : https://leetcode.com/problems/check-if-an-array-is-consecutive/ +/// Author : liuyubobobo +/// Time : 2022-04-08 + +#include +#include +#include + +using namespace std; + + +/// Sorting +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + bool isConsecutive(vector& nums) { + + sort(nums.begin(), nums.end()); + for(int i = 0; i < nums.size(); i ++) + if(nums[i] != nums[0] + i) return false; + return true; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2231-Largest-Number-After-Digit-Swaps-by-Parity/cpp-2231/CMakeLists.txt b/2001-2500/2231-Largest-Number-After-Digit-Swaps-by-Parity/cpp-2231/CMakeLists.txt new file mode 100644 index 00000000..a3422f8f --- /dev/null +++ b/2001-2500/2231-Largest-Number-After-Digit-Swaps-by-Parity/cpp-2231/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/2001-2500/2231-Largest-Number-After-Digit-Swaps-by-Parity/cpp-2231/main.cpp b/2001-2500/2231-Largest-Number-After-Digit-Swaps-by-Parity/cpp-2231/main.cpp new file mode 100644 index 00000000..a79ac97b --- /dev/null +++ b/2001-2500/2231-Largest-Number-After-Digit-Swaps-by-Parity/cpp-2231/main.cpp @@ -0,0 +1,48 @@ +/// Source : https://leetcode.com/problems/largest-number-after-digit-swaps-by-parity/ +/// Author : liuyubobobo +/// Time : 2022-04-10 + +#include +#include + +using namespace std; + + +/// Sorting +/// Time Complexity: O(logn * log(logn)) +/// Space Compelxity: O(logn) +class Solution { +public: + int largestInteger(int num) { + + vector even, odd; + vector is_even; + for(int i = 0; num; i ++){ + int d = num % 10; num /= 10; + if(d % 2){ + odd.push_back(d); + is_even.push_back(false); + } + else{ + even.push_back(d); + is_even.push_back(true); + } + } + + sort(even.begin(), even.end(), greater()); + sort(odd.begin(), odd.end(), greater()); + int even_p = 0, odd_p = 0, res = 0; + for(int i = is_even.size() - 1; i >= 0 ; i --){ + if(is_even[i]) res = res * 10 + even[even_p ++]; + else res = res * 10 + odd[odd_p ++]; + } + return res; + + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2232-Minimize-Result-by-Adding-Parentheses-to-Expression/cpp-2232/CMakeLists.txt b/2001-2500/2232-Minimize-Result-by-Adding-Parentheses-to-Expression/cpp-2232/CMakeLists.txt new file mode 100644 index 00000000..0700646a --- /dev/null +++ b/2001-2500/2232-Minimize-Result-by-Adding-Parentheses-to-Expression/cpp-2232/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/2001-2500/2232-Minimize-Result-by-Adding-Parentheses-to-Expression/cpp-2232/main.cpp b/2001-2500/2232-Minimize-Result-by-Adding-Parentheses-to-Expression/cpp-2232/main.cpp new file mode 100644 index 00000000..61595415 --- /dev/null +++ b/2001-2500/2232-Minimize-Result-by-Adding-Parentheses-to-Expression/cpp-2232/main.cpp @@ -0,0 +1,61 @@ +/// Source : https://leetcode.com/problems/minimize-result-by-adding-parentheses-to-expression/ +/// Author : liuyubobobo +/// Time : 2022-04-10 + +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(|exp|^2) +/// Space Complexity: O(|exp|) +class Solution { +public: + string minimizeResult(string expression) { + + int add_pos = expression.find('+'); + string a = expression.substr(0, add_pos), b = expression.substr(add_pos + 1); + + long long best_exp_res = LONG_LONG_MAX; + string best_exp = ""; + for(int l_len = 0; l_len < a.size(); l_len ++) + for(int r_len = 1; r_len <= b.size(); r_len ++){ + long long l1 = l_len == 0 ? 1ll : atoll(a.substr(0, l_len).c_str()); + long long l2 = atoll(a.substr(l_len).c_str()); + long long r1 = atoll(b.substr(0, r_len).c_str()); + long long r2 = r_len == b.size() ? 1ll : atoll(b.substr(r_len).c_str()); + + long long tres = l1 * (l2 + r1) * r2; +// cout << l1 << ' ' << l2 << ' ' << r1 << ' ' << r2 << ' ' << tres << '\n'; + if(tres < best_exp_res){ + string exp = a.substr(0, l_len); + exp += "("; + exp += a.substr(l_len); + exp += "+"; + exp += b.substr(0, r_len); + exp += ")"; + exp += b.substr(r_len); + + best_exp = exp; + best_exp_res = tres; + } + } + return best_exp; + } +}; + + +int main() { + + cout << Solution().minimizeResult("247+38") << '\n'; + // 2(47+38) + + cout << Solution().minimizeResult("12+34") << '\n'; + // 1(2+3)4 + + cout << Solution().minimizeResult("999+999") << '\n'; + // (999+999) + + return 0; +} diff --git a/2001-2500/2233-Maximum-Product-After-K-Increments/cpp-2233/CMakeLists.txt b/2001-2500/2233-Maximum-Product-After-K-Increments/cpp-2233/CMakeLists.txt new file mode 100644 index 00000000..8accde5b --- /dev/null +++ b/2001-2500/2233-Maximum-Product-After-K-Increments/cpp-2233/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/2001-2500/2233-Maximum-Product-After-K-Increments/cpp-2233/main.cpp b/2001-2500/2233-Maximum-Product-After-K-Increments/cpp-2233/main.cpp new file mode 100644 index 00000000..9d5e6a44 --- /dev/null +++ b/2001-2500/2233-Maximum-Product-After-K-Increments/cpp-2233/main.cpp @@ -0,0 +1,42 @@ +/// Source : https://leetcode.com/problems/maximum-product-after-k-increments/ +/// Author : liuyubobobo +/// Time : 2022-04-10 + +#include +#include +#include + +using namespace std; + + +/// Using PQ +/// Time Complexity: O(klogn + nlogn) +/// Space Complexity: O(n) +class Solution { +public: + int maximumProduct(vector& nums, int k) { + + priority_queue, greater> pq; + for(int e: nums) pq.push(e); + + while(k --){ + int e = pq.top(); pq.pop(); + e ++; + pq.push(e); + } + + long long res = 1ll, MOD = 1e9 + 7; + while(!pq.empty()){ + int e = pq.top(); pq.pop(); + res *= e; + res %= MOD; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2234-Maximum-Total-Beauty-of-the-Gardens/cpp-2234/CMakeLists.txt b/2001-2500/2234-Maximum-Total-Beauty-of-the-Gardens/cpp-2234/CMakeLists.txt new file mode 100644 index 00000000..9031340e --- /dev/null +++ b/2001-2500/2234-Maximum-Total-Beauty-of-the-Gardens/cpp-2234/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) diff --git a/2001-2500/2234-Maximum-Total-Beauty-of-the-Gardens/cpp-2234/main.cpp b/2001-2500/2234-Maximum-Total-Beauty-of-the-Gardens/cpp-2234/main.cpp new file mode 100644 index 00000000..67f3181b --- /dev/null +++ b/2001-2500/2234-Maximum-Total-Beauty-of-the-Gardens/cpp-2234/main.cpp @@ -0,0 +1,118 @@ +/// Source : https://leetcode.com/problems/maximum-total-beauty-of-the-gardens/ +/// Author : liuyubobobo +/// Time : 2022-04-10 + +#include +#include +#include + +using namespace std; + + +/// Greedy +/// Time Compelxity: O(nlogn + nlogt + n) +/// Space Complexity: O(1) +class Solution { +public: + long long maximumBeauty(vector& flowers, + long long newFlowers, long long t, long long full, long long partial) { + + long long n = flowers.size(); + sort(flowers.begin(), flowers.end(), greater()); + + long long full_num = 0; + for(int i = 0; i < flowers.size(); i ++) + if(flowers[i] >= t) full_num ++; + else break; + + long long max_min_height = get_max_min_height(flowers, t - 1, newFlowers); + long long left = newFlowers; + for(int e: flowers) left -= max(max_min_height - e, 0ll); + + int index; + for(index = 0; index < n; index ++) + if(max_min_height - flowers[index] > 0) break; + // 从 index 的位置开始使用了 newFlowers + + long long res = f(full, partial, n, full_num, max_min_height); + for(int i = full_num; i < n; i ++){ + long long need2full = t - max((long long)flowers[i], max_min_height); + assert(need2full >= 0); + + index = max(index, i + 1); + if(left >= need2full){ + left -= need2full; + full_num ++; + res = max(res, f(full, partial, n, full_num, max_min_height)); + } + else{ + need2full -= left; + left = 0; + + while(need2full && index < n){ + assert(max_min_height >= flowers[index]); + long long cur = (long long)(max_min_height - flowers[index]) * (n - index); + if(need2full >= cur){ + need2full -= cur; + max_min_height = flowers[index]; + index ++; + } + else{ + long long remove_h = need2full / (n - index); + need2full -= remove_h * (n - index); + max_min_height -= remove_h; + if(need2full){ + max_min_height --; + left = n - index - need2full; + need2full = 0; + } + } + } + + if(need2full) break; + full_num ++; + res = max(res, f(full, partial, n, full_num, max_min_height)); + } + } + return res; + } + +private: + long long get_max_min_height(const vector& flowers, long long r, long long k){ + + long long l = min((long long)flowers.back(), r); + while(l < r){ + long long mid = (l + r + 1) / 2; + + long long sum = 0; + for(int e: flowers) + sum += max(mid - e, 0ll); + if(k >= sum) l = mid; + else r = mid - 1; + } + return l; + } + + long long f(long long full, long long partial, + long long n, long long full_num, long long max_min_height){ + return full * full_num + (full_num == n ? 0 : partial * max_min_height); + } +}; + + +int main() { + + vector flowers1 = {1, 3, 1, 1}; + cout << Solution().maximumBeauty(flowers1, 7, 6, 12, 1) << '\n'; + // 14 + + vector flowers2 = {2, 4, 5, 3}; + cout << Solution().maximumBeauty(flowers2, 10, 5, 2, 6) << '\n'; + // 30 + + vector flowers3 = {18, 16, 10, 10, 5}; + cout << Solution().maximumBeauty(flowers3, 10, 3, 15, 4) << '\n'; + // 75 + + return 0; +} diff --git a/2001-2500/2235-Add-Two-Integers/cpp-2235/CMakeLists.txt b/2001-2500/2235-Add-Two-Integers/cpp-2235/CMakeLists.txt new file mode 100644 index 00000000..e59503a6 --- /dev/null +++ b/2001-2500/2235-Add-Two-Integers/cpp-2235/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_2235) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2235 main.cpp) diff --git a/2001-2500/2235-Add-Two-Integers/cpp-2235/main.cpp b/2001-2500/2235-Add-Two-Integers/cpp-2235/main.cpp new file mode 100644 index 00000000..bb3ec453 --- /dev/null +++ b/2001-2500/2235-Add-Two-Integers/cpp-2235/main.cpp @@ -0,0 +1,24 @@ +/// Source : https://leetcode.com/problems/add-two-integers/ +/// Author : liuyubobobo +/// Time : 2022-04-13 + +#include + +using namespace std; + + +/// Math +/// Time Complexity: O(1) +/// Space Complexity: O(1) +class Solution { +public: + int sum(int num1, int num2) { + return num1 + num2; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2236-Root-Equals-Sum-of-Children/cpp-2236/CMakeLists.txt b/2001-2500/2236-Root-Equals-Sum-of-Children/cpp-2236/CMakeLists.txt new file mode 100644 index 00000000..73e8d34b --- /dev/null +++ b/2001-2500/2236-Root-Equals-Sum-of-Children/cpp-2236/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_2236) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2236 main.cpp) diff --git a/2001-2500/2236-Root-Equals-Sum-of-Children/cpp-2236/main.cpp b/2001-2500/2236-Root-Equals-Sum-of-Children/cpp-2236/main.cpp new file mode 100644 index 00000000..88756e33 --- /dev/null +++ b/2001-2500/2236-Root-Equals-Sum-of-Children/cpp-2236/main.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/root-equals-sum-of-children/ +/// Author : liuyubobobo +/// Time : 2022-04-13 + +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(1) +/// Space Complexity: O(1) + +/// 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 checkTree(TreeNode* root) { + return root->val == root->left->val + root->right->val; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2237-Count-Positions-on-Street-With-Required-Brightness/cpp-2237/CMakeLists.txt b/2001-2500/2237-Count-Positions-on-Street-With-Required-Brightness/cpp-2237/CMakeLists.txt new file mode 100644 index 00000000..4fe34c35 --- /dev/null +++ b/2001-2500/2237-Count-Positions-on-Street-With-Required-Brightness/cpp-2237/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_2237) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2237 main.cpp) diff --git a/2001-2500/2237-Count-Positions-on-Street-With-Required-Brightness/cpp-2237/main.cpp b/2001-2500/2237-Count-Positions-on-Street-With-Required-Brightness/cpp-2237/main.cpp new file mode 100644 index 00000000..4bc448f2 --- /dev/null +++ b/2001-2500/2237-Count-Positions-on-Street-With-Required-Brightness/cpp-2237/main.cpp @@ -0,0 +1,39 @@ +/// Source : https://leetcode.com/problems/count-positions-on-street-with-required-brightness/ +/// Author : liuyubobobo +/// Time : 2022-04-13 + +#include +#include + +using namespace std; + + +/// Diff Array +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int meetRequirement(int n, vector>& lights, vector& requirement) { + + vector diff(n + 1, 0); + for(const vector& light: lights){ + int pos = light[0], range = light[1]; + int l = max(0, pos - range), r = min(n - 1, pos + range); + + diff[l] += 1, diff[r + 1] -= 1; + } + + int cur = 0, res = 0; + for(int i = 0; i < n; i ++){ + cur += diff[i]; + res += (cur >= requirement[i]); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2239-Find-Closest-Number-to-Zero/cpp-2239/CMakeLists.txt b/2001-2500/2239-Find-Closest-Number-to-Zero/cpp-2239/CMakeLists.txt new file mode 100644 index 00000000..ad45c5db --- /dev/null +++ b/2001-2500/2239-Find-Closest-Number-to-Zero/cpp-2239/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_2239) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2239 main.cpp) diff --git a/2001-2500/2239-Find-Closest-Number-to-Zero/cpp-2239/main.cpp b/2001-2500/2239-Find-Closest-Number-to-Zero/cpp-2239/main.cpp new file mode 100644 index 00000000..24ebc634 --- /dev/null +++ b/2001-2500/2239-Find-Closest-Number-to-Zero/cpp-2239/main.cpp @@ -0,0 +1,32 @@ +/// Source : https://leetcode.com/problems/find-closest-number-to-zero/ +/// Author : liuyubobobo +/// Time : 2022-04-16 + +#include +#include +#include + +using namespace std; + + +/// Linear Search +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int findClosestNumber(vector& nums) { + + int best = INT_MAX, res = 0; + for(int e: nums){ + if(abs(e) < best) res = e, best = abs(e); + else if(abs(e) == best) res = max(res, e); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2240-Number-of-Ways-to-Buy-Pens-and-Pencils/cpp-2240/CMakeLists.txt b/2001-2500/2240-Number-of-Ways-to-Buy-Pens-and-Pencils/cpp-2240/CMakeLists.txt new file mode 100644 index 00000000..ac581fb9 --- /dev/null +++ b/2001-2500/2240-Number-of-Ways-to-Buy-Pens-and-Pencils/cpp-2240/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_2240) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2240 main.cpp) diff --git a/2001-2500/2240-Number-of-Ways-to-Buy-Pens-and-Pencils/cpp-2240/main.cpp b/2001-2500/2240-Number-of-Ways-to-Buy-Pens-and-Pencils/cpp-2240/main.cpp new file mode 100644 index 00000000..bc2855c9 --- /dev/null +++ b/2001-2500/2240-Number-of-Ways-to-Buy-Pens-and-Pencils/cpp-2240/main.cpp @@ -0,0 +1,29 @@ +/// Source : https://leetcode.com/problems/number-of-ways-to-buy-pens-and-pencils/ +/// Author : liuyubobobo +/// Time : 2022-04-16 + +#include + +using namespace std; + + +/// Math +/// Time Complexity: O(total / cost1) +/// Space Complexity: O(1) +class Solution { +public: + long long waysToBuyPensPencils(int total, int cost1, int cost2) { + + long long res = 0; + for(int cnt1 = 0; cost1 * cnt1 <= total; cnt1 ++){ + res += (total - cost1 * cnt1) / cost2 + 1; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2241-Design-an-ATM-Machine/cpp-2241/CMakeLists.txt b/2001-2500/2241-Design-an-ATM-Machine/cpp-2241/CMakeLists.txt new file mode 100644 index 00000000..9b165d59 --- /dev/null +++ b/2001-2500/2241-Design-an-ATM-Machine/cpp-2241/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_2241) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2241 main.cpp) diff --git a/2001-2500/2241-Design-an-ATM-Machine/cpp-2241/main.cpp b/2001-2500/2241-Design-an-ATM-Machine/cpp-2241/main.cpp new file mode 100644 index 00000000..b378477c --- /dev/null +++ b/2001-2500/2241-Design-an-ATM-Machine/cpp-2241/main.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/design-an-atm-machine/ +/// Author : liuyubobobo +/// Time : 2022-04-16 + +#include +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(1) for every operation +/// Space Complexity: O(1) +class ATM { + +private: + const vector values = {20, 50, 100, 200, 500}; + const int dnum = 5; + vector cnt; + +public: + ATM() : cnt(dnum, 0) {} + + void deposit(vector banknotesCount) { + + assert(banknotesCount.size() == dnum); + for(int i = 0; i < dnum; i ++) + cnt[i] += banknotesCount[i]; + } + + vector withdraw(int amount) { + + vector res(dnum, 0); + for(int i = dnum - 1; i >= 0 && amount; i --){ + long long t = min(amount / values[i], cnt[i]); + cnt[i] -= t; + res[i] += t; + amount -= t * values[i]; + } + + if(amount == 0) return res; + + deposit(res); + return {-1}; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2242-Maximum-Score-of-a-Node-Sequence/cpp-2242/CMakeLists.txt b/2001-2500/2242-Maximum-Score-of-a-Node-Sequence/cpp-2242/CMakeLists.txt new file mode 100644 index 00000000..c3b127c5 --- /dev/null +++ b/2001-2500/2242-Maximum-Score-of-a-Node-Sequence/cpp-2242/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_2242) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2242 main.cpp) diff --git a/2001-2500/2242-Maximum-Score-of-a-Node-Sequence/cpp-2242/main.cpp b/2001-2500/2242-Maximum-Score-of-a-Node-Sequence/cpp-2242/main.cpp new file mode 100644 index 00000000..43d8c74b --- /dev/null +++ b/2001-2500/2242-Maximum-Score-of-a-Node-Sequence/cpp-2242/main.cpp @@ -0,0 +1,48 @@ +#include +#include + +using namespace std; + + +class Solution { +public: + int maximumScore(vector& scores, vector>& edges) { + + int n = -1; + for(const vector& e: edges){ + n = max(n, e[0]); + n = max(n, e[1]); + } + n ++; + + vector>> g(n); + for(const vector& e: edges){ + int u = e[0], v = e[1]; + g[u].emplace_back(scores[v], v); + g[v].emplace_back(scores[u], u); + } + + for(int i = 0; i < n; i ++) + sort(g[i].begin(), g[i].end(), greater>()); + + int res = -1; + for(const vector& e: edges){ + int u = e[0], v = e[1]; + for(int i = 0; i < 3 && i < g[u].size(); i ++) + if(g[u][i].second != v){ + int x = g[u][i].second; + for(int j = 0; j < 3 && j < g[v].size(); j ++) + if(g[v][j].second != u && g[v][j].second != x){ + int y = g[v][j].second; + res = max(res, scores[x] + scores[u] + scores[v] + scores[y]); + } + } + } + return res; + } +}; + +int main() { + + return 0; +} diff --git a/2001-2500/2243-Calculate-Digit-Sum-of-a-String/cpp-2243/CMakeLists.txt b/2001-2500/2243-Calculate-Digit-Sum-of-a-String/cpp-2243/CMakeLists.txt new file mode 100644 index 00000000..a3422f8f --- /dev/null +++ b/2001-2500/2243-Calculate-Digit-Sum-of-a-String/cpp-2243/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/2001-2500/2243-Calculate-Digit-Sum-of-a-String/cpp-2243/main.cpp b/2001-2500/2243-Calculate-Digit-Sum-of-a-String/cpp-2243/main.cpp new file mode 100644 index 00000000..86817c25 --- /dev/null +++ b/2001-2500/2243-Calculate-Digit-Sum-of-a-String/cpp-2243/main.cpp @@ -0,0 +1,41 @@ +/// Source : https://leetcode.com/problems/calculate-digit-sum-of-a-string/ +/// Author : liuyubobobo +/// Time : 2022-04-16 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(|s|) +/// Space Complexity: O(1) +class Solution { +public: + string digitSum(string s, int k) { + + while(s.size() > k){ + + string nexts = ""; + for(int i = 0; i < s.size(); i += k) + nexts += to_string(sum(s.substr(i, k))); + s = nexts; + } + return s; + } + +private: + int sum(const string& s){ + int res = 0; + for(int i = 0; i < s.size(); i ++) + res += (s[i] - '0'); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2244-Minimum-Rounds-to-Complete-All-Tasks/cpp-2244/CMakeLists.txt b/2001-2500/2244-Minimum-Rounds-to-Complete-All-Tasks/cpp-2244/CMakeLists.txt new file mode 100644 index 00000000..0700646a --- /dev/null +++ b/2001-2500/2244-Minimum-Rounds-to-Complete-All-Tasks/cpp-2244/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/2001-2500/2244-Minimum-Rounds-to-Complete-All-Tasks/cpp-2244/main.cpp b/2001-2500/2244-Minimum-Rounds-to-Complete-All-Tasks/cpp-2244/main.cpp new file mode 100644 index 00000000..03daf13c --- /dev/null +++ b/2001-2500/2244-Minimum-Rounds-to-Complete-All-Tasks/cpp-2244/main.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/minimum-rounds-to-complete-all-tasks/ +/// Author : liuyubobobo +/// Time : 2022-04-16 + +#include +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int minimumRounds(vector& tasks) { + + map f; + for(int e: tasks) f[e] ++; + + int res = 0; + for(const pair& p: f){ + if(p.second == 1) return -1; + res += (p.second / 3 + !!(p.second % 3)); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2245-Maximum-Trailing-Zeros-in-a-Cornered-Path/cpp-2245/CMakeLists.txt b/2001-2500/2245-Maximum-Trailing-Zeros-in-a-Cornered-Path/cpp-2245/CMakeLists.txt new file mode 100644 index 00000000..8accde5b --- /dev/null +++ b/2001-2500/2245-Maximum-Trailing-Zeros-in-a-Cornered-Path/cpp-2245/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/2001-2500/2245-Maximum-Trailing-Zeros-in-a-Cornered-Path/cpp-2245/main.cpp b/2001-2500/2245-Maximum-Trailing-Zeros-in-a-Cornered-Path/cpp-2245/main.cpp new file mode 100644 index 00000000..3fb2df7a --- /dev/null +++ b/2001-2500/2245-Maximum-Trailing-Zeros-in-a-Cornered-Path/cpp-2245/main.cpp @@ -0,0 +1,78 @@ +/// Source : https://leetcode.com/problems/maximum-trailing-zeros-in-a-cornered-path/ +/// Author : liuyubobobo +/// Time : 2022-04-16 + +#include +#include + +using namespace std; + + +/// Presum +/// Time Complexity: O(R * C) +/// Space Complexity: O(R * C) +class Solution { +public: + int maxTrailingZeros(vector>& grid) { + + int R = grid.size(), C = grid[0].size(); + + vector> two(R, vector(C, 0)), five(R, vector(C, 0)); + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++){ + int num = grid[i][j]; + int two_num = 0, five_num = 0; + while(num % 2 == 0) two_num ++, num /= 2; + while(num % 5 == 0) five_num ++, num /= 5; + two[i][j] = two_num; + five[i][j] = five_num; + } + + vector> presum_row_two(R, vector(C + 1, 0)), presum_row_five(R, vector(C + 1, 0)); + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++){ + presum_row_two[i][j + 1] = presum_row_two[i][j] + two[i][j]; + presum_row_five[i][j + 1] = presum_row_five[i][j] + five[i][j]; + } + + vector> presum_col_two(R + 1, vector(C, 0)), presum_col_five(R + 1, vector(C, 0)); + for(int j = 0; j < C; j ++) + for(int i = 0; i < R; i ++){ + presum_col_two[i + 1][j] = presum_col_two[i][j] + two[i][j]; + presum_col_five[i + 1][j] = presum_col_five[i][j] + five[i][j]; + } + + int res = 0; + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++){ + int up_two = presum_col_two[i][j], up_five = presum_col_five[i][j]; + int down_two = presum_col_two[R][j] - presum_col_two[i + 1][j], down_five = presum_col_five[R][j] - presum_col_five[i + 1][j]; + int left_two = presum_row_two[i][j], left_five = presum_row_five[i][j]; + int right_two = presum_row_two[i][C] - presum_row_two[i][j + 1], right_five = presum_row_five[i][C] - presum_row_five[i][j + 1]; + + res = max(res, min(up_two + left_two + two[i][j], up_five + left_five + five[i][j])); + res = max(res, min(up_two + right_two + two[i][j], up_five + right_five + five[i][j])); + res = max(res, min(down_two + left_two + two[i][j], down_five + left_five + five[i][j])); + res = max(res, min(down_two + right_two + two[i][j], down_five + right_five + five[i][j])); + } + return res; + } +}; + + +int main() { + + vector> grid1 = {{23,17,15,3,20},{8,1,20,27,11},{9,4,6,2,21},{40,9,1,10,6},{22,7,4,5,3}}; + cout << Solution().maxTrailingZeros(grid1) << '\n'; + // 3 + + vector> grid2 = {{4,3,2},{7,6,1},{8,8,8}}; + cout << Solution().maxTrailingZeros(grid2) << '\n'; + // 0 + + vector> grid3 = {{10}, {6}, {15}}; + cout << Solution().maxTrailingZeros(grid3) << '\n'; + // 2 + + return 0; +} diff --git a/2001-2500/2246-Longest-Path-With-Different-Adjacent-Characters/cpp-2246/CMakeLists.txt b/2001-2500/2246-Longest-Path-With-Different-Adjacent-Characters/cpp-2246/CMakeLists.txt new file mode 100644 index 00000000..2552f642 --- /dev/null +++ b/2001-2500/2246-Longest-Path-With-Different-Adjacent-Characters/cpp-2246/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main2.cpp) diff --git a/2001-2500/2246-Longest-Path-With-Different-Adjacent-Characters/cpp-2246/main.cpp b/2001-2500/2246-Longest-Path-With-Different-Adjacent-Characters/cpp-2246/main.cpp new file mode 100644 index 00000000..6f63cafd --- /dev/null +++ b/2001-2500/2246-Longest-Path-With-Different-Adjacent-Characters/cpp-2246/main.cpp @@ -0,0 +1,86 @@ +/// Source : https://leetcode.com/problems/longest-path-with-different-adjacent-characters/ +/// Author : liuyubobobo +/// Time : 2022-04-16 + +#include +#include + +using namespace std; + + +/// DFS - Two Pass +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int longestPath(vector& parent, string s) { + + int n = parent.size(); + vector> g(n); + for(int u = 1; u < n; u ++){ + int v = parent[u]; + g[u].push_back(v), g[v].push_back(u); + } + + vector dp1(n, 1); + dfs1(g, 0, -1, s, dp1); + +// for(int e: dp1) cout << e << ' '; cout << '\n'; + + int res = 1; + dfs2(g, 0, -1, dp1, s, res); + return res; + } + +private: + void dfs2(const vector>& g, int u, int p, const vector& dp, const string& s, + int& res){ + + vector len; + for(int v: g[u]){ + if(v == p) continue; + dfs2(g, v, u, dp, s, res); + if(s[u] != s[v]) + len.push_back(dp[v]); + } + + if(len.size() == 0) + res = max(res, 1); + else if(len.size() == 1) + res = max(res, len[0] + 1); + else{ + sort(len.begin(), len.end(), greater()); + res = max(res, len[0] + len[1] + 1); + } + } + + void dfs1(const vector>& g, int u, int p, const string& s, + vector& dp){ + + int res = 1; + for(int v: g[u]){ + if(v == p) continue; + + dfs1(g, v, u, s, dp); + if(s[v] != s[u]) + res = max(res, 1 + dp[v]); + } + dp[u] = res; + } +}; + + +int main() { + + vector parent1 = {-1,0,0,1,1,2}; + string s1 = "abacbe"; + cout << Solution().longestPath(parent1, s1) << '\n'; + // 3 + + vector parent2 = {-1,0,0,0}; + string s2 = "aabc"; + cout << Solution().longestPath(parent2, s2) << '\n'; + // 3 + + return 0; +} diff --git a/2001-2500/2246-Longest-Path-With-Different-Adjacent-Characters/cpp-2246/main2.cpp b/2001-2500/2246-Longest-Path-With-Different-Adjacent-Characters/cpp-2246/main2.cpp new file mode 100644 index 00000000..de1fd5fd --- /dev/null +++ b/2001-2500/2246-Longest-Path-With-Different-Adjacent-Characters/cpp-2246/main2.cpp @@ -0,0 +1,71 @@ +/// Source : https://leetcode.com/problems/longest-path-with-different-adjacent-characters/ +/// Author : liuyubobobo +/// Time : 2022-04-16 + +#include +#include + +using namespace std; + + +/// DFS - One Pass +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int longestPath(vector& parent, string s) { + + int n = parent.size(); + vector> g(n); + for(int u = 1; u < n; u ++){ + int v = parent[u]; + g[u].push_back(v), g[v].push_back(u); + } + + int res = 0; + dfs(g, 0, -1, s, res); + return res; + } + +private: + int dfs(const vector>& g, int u, int p, const string& s, + int& res){ + + vector len; + int maxl = 1; + for(int v: g[u]){ + if(v == p) continue; + int l = dfs(g, v, u, s, res); + if(s[u] != s[v]){ + len.push_back(l); + maxl = max(maxl, 1 + l); + } + } + + if(len.size() == 0) + res = max(res, 1); + else if(len.size() == 1) + res = max(res, len[0] + 1); + else{ + sort(len.begin(), len.end(), greater()); + res = max(res, len[0] + len[1] + 1); + } + return maxl; + } +}; + + +int main() { + + vector parent1 = {-1,0,0,1,1,2}; + string s1 = "abacbe"; + cout << Solution().longestPath(parent1, s1) << '\n'; + // 3 + + vector parent2 = {-1,0,0,0}; + string s2 = "aabc"; + cout << Solution().longestPath(parent2, s2) << '\n'; + // 3 + + return 0; +} diff --git a/2001-2500/2247-Maximum-Cost-of-Trip-With-K-Highways/cpp-2247/CMakeLists.txt b/2001-2500/2247-Maximum-Cost-of-Trip-With-K-Highways/cpp-2247/CMakeLists.txt new file mode 100644 index 00000000..79f82a6b --- /dev/null +++ b/2001-2500/2247-Maximum-Cost-of-Trip-With-K-Highways/cpp-2247/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(cpp_2247) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2247 main.cpp) diff --git a/2001-2500/2247-Maximum-Cost-of-Trip-With-K-Highways/cpp-2247/main.cpp b/2001-2500/2247-Maximum-Cost-of-Trip-With-K-Highways/cpp-2247/main.cpp new file mode 100644 index 00000000..5451c683 --- /dev/null +++ b/2001-2500/2247-Maximum-Cost-of-Trip-With-K-Highways/cpp-2247/main.cpp @@ -0,0 +1,66 @@ +/// Source : https://leetcode.com/problems/maximum-cost-of-trip-with-k-highways/ +/// Author : liuyubobobo +/// Time : 2022-04-22 + +#include +#include + +using namespace std; + + +/// State Compression Memoization +/// Time Complexity: O(2^n * n^2) +/// Space Complexity: O(2^n * n) +class Solution { +public: + int maximumCost(int n, vector>& highways, int k) { + + vector>> g(n); + for(const vector& e: highways){ + int u = e[0], v = e[1], w = e[2]; + g[u].push_back({v, w}); + g[v].push_back({u, w}); + } + + vector> dp(1 << n, vector(n, INT_MIN)); + int res = INT_MIN / 2; + for(int s = 0; s < n; s ++) + res = max(res, dfs(g, 1 << s, s, k, dp)); + return res < 0 ? -1 : res; + } + +private: + int dfs(const vector>>& g, int state, int u, int k, + vector>& dp){ + + int v_num = __builtin_popcount(state); + if(v_num == k + 1) return 0; + if(dp[state][u] != INT_MIN) return dp[state][u]; + + int res = INT_MIN / 2; + for(const pair& p: g[u]){ + int v = p.first, w = p.second; + if((state & (1 << v)) == 0) + res = max(res, w + dfs(g, state | (1 << v), v, k, dp)); + } + return dp[state][u] = res; + } +}; + + +int main() { + + vector> highways1 = {{0,1,4},{2,1,3},{1,4,11},{3,2,3},{3,4,2}}; + cout << Solution().maximumCost(5, highways1, 3) << '\n'; + // 17 + + vector> highways2 = {{0,1,3},{2,3,2}}; + cout << Solution().maximumCost(4, highways2, 2) << '\n'; + // -1 + + vector> highways3 = {{0,1,0}}; + cout << Solution().maximumCost(2, highways3, 1) << '\n'; + // 0 + + return 0; +} diff --git a/2001-2500/2248-Intersection-of-Multiple-Arrays/cpp-2248/CMakeLists.txt b/2001-2500/2248-Intersection-of-Multiple-Arrays/cpp-2248/CMakeLists.txt new file mode 100644 index 00000000..a3422f8f --- /dev/null +++ b/2001-2500/2248-Intersection-of-Multiple-Arrays/cpp-2248/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/2001-2500/2248-Intersection-of-Multiple-Arrays/cpp-2248/main.cpp b/2001-2500/2248-Intersection-of-Multiple-Arrays/cpp-2248/main.cpp new file mode 100644 index 00000000..e5793e40 --- /dev/null +++ b/2001-2500/2248-Intersection-of-Multiple-Arrays/cpp-2248/main.cpp @@ -0,0 +1,38 @@ +/// Source : https://leetcode.com/problems/intersection-of-multiple-arrays/ +/// Author : liuyubobobo +/// Time : 2022-04-23 + +#include +#include +#include + +using namespace std; + + +/// Using Set +/// Time Complexity: O(sum(nums[i][j])) +/// Space Complexity: O(min(nums[i])) +class Solution { +public: + vector intersection(vector>& nums) { + + set res_set(nums[0].begin(), nums[0].end()); + for(int i = 1; i < nums.size(); i ++) + res_set = intersect(res_set, nums[i]); + return vector(res_set.begin(), res_set.end()); + } + +private: + set intersect(const set& s, const vector& v){ + + set res; + for(int e: v) if(s.count(e)) res.insert(e); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2249-Count-Lattice-Points-Inside-a-Circle/cpp-2249/CMakeLists.txt b/2001-2500/2249-Count-Lattice-Points-Inside-a-Circle/cpp-2249/CMakeLists.txt new file mode 100644 index 00000000..0700646a --- /dev/null +++ b/2001-2500/2249-Count-Lattice-Points-Inside-a-Circle/cpp-2249/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/2001-2500/2249-Count-Lattice-Points-Inside-a-Circle/cpp-2249/main.cpp b/2001-2500/2249-Count-Lattice-Points-Inside-a-Circle/cpp-2249/main.cpp new file mode 100644 index 00000000..cf70d4c4 --- /dev/null +++ b/2001-2500/2249-Count-Lattice-Points-Inside-a-Circle/cpp-2249/main.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/count-lattice-points-inside-a-circle/ +/// Author : liuyubobobo +/// Time : 2022-04-23 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(x_range * y_range * |circles|) +/// Space Compelxity: O(1) +class Solution { +public: + int countLatticePoints(vector>& circles) { + + int minx = INT_MAX, maxx = INT_MIN, miny = INT_MAX, maxy = INT_MIN; + for(const vector& circle: circles){ + int x = circle[0], y = circle[1], r = circle[2]; + minx = min(minx, x - r), maxx = max(maxx, x + r); + miny = min(miny, y - r), maxy = max(maxy, y + r); + } + + int res = 0; + for(int x = minx; x <= maxx; x ++) + for(int y = miny; y <= maxy; y ++){ + bool ok = false; + for(const vector& circle: circles){ + int x0 = circle[0], y0 = circle[1], r0 = circle[2]; + if((x - x0) * (x - x0) + (y - y0) * (y - y0) <= r0 * r0){ + ok = true; + break; + } + } + res += ok; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2250-Count-Number-of-Rectangles-Containing-Each-Point/cpp-2250/CMakeLists.txt b/2001-2500/2250-Count-Number-of-Rectangles-Containing-Each-Point/cpp-2250/CMakeLists.txt new file mode 100644 index 00000000..8accde5b --- /dev/null +++ b/2001-2500/2250-Count-Number-of-Rectangles-Containing-Each-Point/cpp-2250/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/2001-2500/2250-Count-Number-of-Rectangles-Containing-Each-Point/cpp-2250/main.cpp b/2001-2500/2250-Count-Number-of-Rectangles-Containing-Each-Point/cpp-2250/main.cpp new file mode 100644 index 00000000..320e95f9 --- /dev/null +++ b/2001-2500/2250-Count-Number-of-Rectangles-Containing-Each-Point/cpp-2250/main.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/count-number-of-rectangles-containing-each-point/ +/// Author : liuyubobobo +/// Time : 2022-04-23 + +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(|rec|log|rec| + |point|log|rec|) +/// Space Complexity: O(|rec|) +class Solution { +public: + vector countRectangles(vector>& rectangles, vector>& points) { + + vector> h_rec(101); + for(const vector& rec: rectangles){ + int l = rec[0], h = rec[1]; + h_rec[h].push_back(l); + } + + for(int i = 0; i <= 100; i ++) sort(h_rec[i].begin(), h_rec[i].end()); + + vector res(points.size()); + for(int i = 0; i < points.size(); i ++){ + int x = points[i][0], y = points[i][1]; + int tres = 0; + for(int h = y; h <= 100; h ++){ + if(h_rec.empty()) continue; + auto iter = lower_bound(h_rec[h].begin(), h_rec[h].end(), x); + if(iter != h_rec[h].end()){ + int index = iter - h_rec[h].begin(); + tres += h_rec[h].size() - index; + } + } + res[i] = tres; + } + return res; + } +}; + + +int main() { + + vector> rectangles1 = {{1, 2}, {2, 3}, {2, 5}}; + vector> points1 = {{2, 1}, {1, 4}}; + Solution().countRectangles(rectangles1, points1); + + return 0; +} diff --git a/2001-2500/2251-Number-of-Flowers-in-Full-Bloom/cpp-2251/CMakeLists.txt b/2001-2500/2251-Number-of-Flowers-in-Full-Bloom/cpp-2251/CMakeLists.txt new file mode 100644 index 00000000..9031340e --- /dev/null +++ b/2001-2500/2251-Number-of-Flowers-in-Full-Bloom/cpp-2251/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) diff --git a/2001-2500/2251-Number-of-Flowers-in-Full-Bloom/cpp-2251/main.cpp b/2001-2500/2251-Number-of-Flowers-in-Full-Bloom/cpp-2251/main.cpp new file mode 100644 index 00000000..004e4781 --- /dev/null +++ b/2001-2500/2251-Number-of-Flowers-in-Full-Bloom/cpp-2251/main.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/number-of-flowers-in-full-bloom/ +/// Author : liuyubobobo +/// Time : 2022-04-23 + +#include +#include +#include + +using namespace std; + + +/// Sweep line +/// Time Complexity: O(|2 * flowers + persons| * log|2 * flowers + persons|) +/// Space Complexity: O(|2 * flowers + persons|) +class Solution { +public: + vector fullBloomFlowers(vector>& flowers, vector& persons) { + + vector> events; + // event flower: start_time 0 0 + // end_time 0 1 + // person query_time 1 index + + for(const vector& flower: flowers){ + int start = flower[0], end = flower[1]; + events.push_back({start, 0, 0}); + events.push_back({end + 1, 0, 1}); + } + for(int i = 0; i < persons.size(); i ++) + events.push_back({persons[i], 1, i}); + + sort(events.begin(), events.end()); + vector res(persons.size(), 0); + int cur = 0; + for(const vector& event: events){ + int type = event[1]; + if(type == 0){ + cur += (event[2] == 0 ? 1 : -1); + } + else res[event[2]] = cur; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2254-Design-Video-Sharing-Platform/cpp-2254/CMakeLists.txt b/2001-2500/2254-Design-Video-Sharing-Platform/cpp-2254/CMakeLists.txt new file mode 100644 index 00000000..9bcef8ac --- /dev/null +++ b/2001-2500/2254-Design-Video-Sharing-Platform/cpp-2254/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_2254) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2254 main.cpp) diff --git a/2001-2500/2254-Design-Video-Sharing-Platform/cpp-2254/main.cpp b/2001-2500/2254-Design-Video-Sharing-Platform/cpp-2254/main.cpp new file mode 100644 index 00000000..ad01ddd3 --- /dev/null +++ b/2001-2500/2254-Design-Video-Sharing-Platform/cpp-2254/main.cpp @@ -0,0 +1,95 @@ +/// Source : https://leetcode.com/problems/design-video-sharing-platform/ +/// Author : liuyubobobo +/// Time : 2022-04-29 + +#include +#include +#include +#include + +using namespace std; + + +/// Using Priority Queue to maintain available ids +/// Time Complexity: init: O(1) +/// others: O(logn) +/// Space Complexity: O(n) +class VideoSharingPlatform { + +private: + int MAX_ID = 128; + const int D = 128; + priority_queue, greater> available_ids; + + map> videos; // video, watched, like, dislike + +public: + VideoSharingPlatform() { + for(int i = 0; i < MAX_ID; i ++) available_ids.push(i); + } + + int upload(const string& video) { + + if(available_ids.empty()){ + int start = MAX_ID; + MAX_ID += D; + for(int i = start; i < MAX_ID; i ++) available_ids.push(i); + } + + int new_id = available_ids.top(); + available_ids.pop(); + + videos[new_id] = {video, 0, 0, 0}; + return new_id; + } + + void remove(int videoId) { + if(videos.count(videoId)){ + videos.erase(videoId); + available_ids.push(videoId); + } + } + + string watch(int videoId, int startMinute, int endMinute) { + auto iter = videos.find(videoId); + if(iter != videos.end()){ + get<1>(iter->second) ++; + return get<0>(iter->second).substr(startMinute, endMinute - startMinute + 1); + } + return "-1"; + } + + void like(int videoId) { + auto iter = videos.find(videoId); + if(iter != videos.end()){ + get<2>(iter->second) ++; + } + } + + void dislike(int videoId) { + auto iter = videos.find(videoId); + if(iter != videos.end()){ + get<3>(iter->second) ++; + } + } + + vector getLikesAndDislikes(int videoId) { + auto iter = videos.find(videoId); + if(iter != videos.end()){ + return {get<2>(iter->second), get<3>(iter->second)}; + } + return {-1}; + } + + int getViews(int videoId) { + auto iter = videos.find(videoId); + if(iter != videos.end()) return get<1>(iter->second); + return -1; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2255-Count-Prefixes-of-a-Given-String/cpp-2255/CMakeLists.txt b/2001-2500/2255-Count-Prefixes-of-a-Given-String/cpp-2255/CMakeLists.txt new file mode 100644 index 00000000..8243a242 --- /dev/null +++ b/2001-2500/2255-Count-Prefixes-of-a-Given-String/cpp-2255/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_2255) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2255 main.cpp) diff --git a/2001-2500/2255-Count-Prefixes-of-a-Given-String/cpp-2255/main.cpp b/2001-2500/2255-Count-Prefixes-of-a-Given-String/cpp-2255/main.cpp new file mode 100644 index 00000000..cb7acfac --- /dev/null +++ b/2001-2500/2255-Count-Prefixes-of-a-Given-String/cpp-2255/main.cpp @@ -0,0 +1,30 @@ +/// Source : https://leetcode.com/problems/count-prefixes-of-a-given-string/ +/// Author : liuyubobobo +/// Time : 2022-04-30 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n * |s|) +/// Space Complexity: O(|s|) +class Solution { +public: + int countPrefixes(vector& words, string s) { + + int res = 0; + for(const string& word: words){ + res += (word.size() <= s.size() && s.substr(0, word.size()) == word); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2256-Minimum-Average-Difference/cpp-2256/CMakeLists.txt b/2001-2500/2256-Minimum-Average-Difference/cpp-2256/CMakeLists.txt new file mode 100644 index 00000000..4de84433 --- /dev/null +++ b/2001-2500/2256-Minimum-Average-Difference/cpp-2256/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_2256) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2256 main.cpp) diff --git a/2001-2500/2256-Minimum-Average-Difference/cpp-2256/main.cpp b/2001-2500/2256-Minimum-Average-Difference/cpp-2256/main.cpp new file mode 100644 index 00000000..acdf3e54 --- /dev/null +++ b/2001-2500/2256-Minimum-Average-Difference/cpp-2256/main.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/minimum-average-difference/ +/// Author : liuyubobobo +/// Time : 2022-05-03 + +#include +#include +#include +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(n) +/// Space Compelxity: O(1) +class Solution { +public: + int minimumAverageDifference(vector& nums) { + + int n = nums.size(); + + long long sum = accumulate(nums.begin(), nums.end(), 0ll); + + long long min_diff = LONG_LONG_MAX, pre = 0ll, post = sum; + int res = n - 1; + for(int i = 0; i < n; i ++){ + pre += nums[i]; + post -= nums[i]; + + long long t = abs(pre / (i + 1) - (n - i - 1 == 0 ? 0 : post / (n - i - 1))); +// cout << i << ' ' << t << '\n'; + if(t < min_diff) res = i, min_diff = t; + } + return res; + } +}; + + +int main() { + + vector nums1 = {2, 5, 3, 9, 5, 3}; + cout << Solution().minimumAverageDifference(nums1) << '\n'; + // 3 + + vector nums2 = {4, 2, 0}; + cout << Solution().minimumAverageDifference(nums2) << '\n'; + // 2 + + return 0; +} diff --git a/2001-2500/2257-Count-Unguarded-Cells-in-the-Grid/cpp-2257/CMakeLists.txt b/2001-2500/2257-Count-Unguarded-Cells-in-the-Grid/cpp-2257/CMakeLists.txt new file mode 100644 index 00000000..8d244544 --- /dev/null +++ b/2001-2500/2257-Count-Unguarded-Cells-in-the-Grid/cpp-2257/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_2257) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2257 main.cpp) diff --git a/2001-2500/2257-Count-Unguarded-Cells-in-the-Grid/cpp-2257/main.cpp b/2001-2500/2257-Count-Unguarded-Cells-in-the-Grid/cpp-2257/main.cpp new file mode 100644 index 00000000..c3c63411 --- /dev/null +++ b/2001-2500/2257-Count-Unguarded-Cells-in-the-Grid/cpp-2257/main.cpp @@ -0,0 +1,93 @@ +/// Source : https://leetcode.com/problems/count-unguarded-cells-in-the-grid/ +/// Author : liuyubobobo +/// Time : 2022-05-03 + +#include +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(m * n) +/// Space Complexity: O(m * n) +class Solution { + +private: + const int dirs[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; + int R, C; + +public: + int countUnguarded(int m, int n, vector>& guards, vector>& walls) { + + R = m, C = n; + + vector g(R, string(C, '.')); + for(const vector& guard: guards) + g[guard[0]][guard[1]] = 'G'; + for(const vector& wall: walls) + g[wall[0]][wall[1]] = 'W'; + + vector>> seen(2, vector>(R, vector(C, false))); + for(int i = 0; i < R; i ++) { + for (int j = 0; j < C; j++) { + + if(g[i][j] != '.'){ + seen[0][i][j] = seen[1][i][j] = true; + } + + if (g[i][j] != 'G') continue; + assert(g[i][j] == 'G'); + for (int d = 0; d < 4; d ++) { + for (int step = 1;; step ++) { + int nx = i + dirs[d][0] * step, ny = j + dirs[d][1] * step; + if (!in_area(nx, ny) || g[nx][ny] != '.' || seen[d / 2][nx][ny]) break; + seen[d / 2][nx][ny] = true; + } + } + } + } + +// for(int i = 0; i < R; i ++) { +// for (int j = 0; j < C; j++) +// cout << seen[0][i][j] << ' '; +// cout << '\n'; +// }cout << '\n'; +// +// for(int i = 0; i < R; i ++) { +// for (int j = 0; j < C; j++) +// cout << seen[1][i][j] << ' '; +// cout << '\n'; +// }cout << '\n'; + +// for(int i = 0; i < R; i ++){ +// for(int j = 0; j < C; j ++) +// cout << (g[i][j] == '.' && !seen[0][i][j] && !seen[1][i][j]) << ' '; +// cout << '\n'; +// } + + int res = 0; + for(int i = 0; i < R; i ++) + for (int j = 0; j < C; j++) + res += (g[i][j] == '.' && !seen[0][i][j] && !seen[1][i][j]); + + return res; + } + +private: + bool in_area(int x, int y){ + return 0 <= x && x < R && 0 <= y && y < C; + } +}; + + +int main() { + + vector> guards1 = {{0,0},{1,1},{2,3}}; + vector> walls1 = {{0,1},{2,2},{1,4}}; + cout << Solution().countUnguarded(4, 6, guards1, walls1) << '\n'; + // 7 + + return 0; +} diff --git a/2001-2500/2258-Escape-the-Spreading-Fire/cpp-2258/CMakeLists.txt b/2001-2500/2258-Escape-the-Spreading-Fire/cpp-2258/CMakeLists.txt new file mode 100644 index 00000000..cc253742 --- /dev/null +++ b/2001-2500/2258-Escape-the-Spreading-Fire/cpp-2258/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_2258) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2258 main.cpp) diff --git a/2001-2500/2258-Escape-the-Spreading-Fire/cpp-2258/main.cpp b/2001-2500/2258-Escape-the-Spreading-Fire/cpp-2258/main.cpp new file mode 100644 index 00000000..80adba3e --- /dev/null +++ b/2001-2500/2258-Escape-the-Spreading-Fire/cpp-2258/main.cpp @@ -0,0 +1,122 @@ +/// Source : https://leetcode.com/problems/escape-the-spreading-fire/ +/// Author : liuyubobobo +/// Time : 2022-05-03 + +#include +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(m * n * log(m * n)) +/// Space Complexity: O(m * n) +class Solution { + +private: + const int dirs[4][2] {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; + int R, C; + +public: + int maximumMinutes(vector>& grid) { + + R = grid.size(), C = grid[0].size(); + + vector> fire_time(R, vector(C, 2e9)); + queue q; + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++) + if(grid[i][j] == 1){ + fire_time[i][j] = 0; + q.push(i * C + j); + } + + while(!q.empty()){ + int cx = q.front() / C, cy = q.front() % C, cur_time = fire_time[cx][cy]; + q.pop(); + + for(int d = 0; d < 4; d ++){ + int nx = cx + dirs[d][0], ny = cy + dirs[d][1]; + if(in_area(nx, ny) && grid[nx][ny] != 2 && fire_time[nx][ny] == 2e9){ + fire_time[nx][ny] = cur_time + 1; + q.push(nx * C + ny); + } + } + } + +// for(const vector& row: fire_time){ +// for(int e: row) cout << e << ' '; +// cout << '\n'; +// } + + int l = -1, r = 1e9; + while(l < r){ + int mid = (l + r + 1) / 2; + if(ok(grid, fire_time, mid)) l = mid; + else r = mid - 1; + } + return l; + } + +private: + bool ok(const vector>& grid, const vector>& fire_time, int t){ + + if(grid[0][0] == 2 || t > fire_time[0][0]) return false; + + vector> visited(R, vector(C, -1)); + queue q; + q.push(0); + visited[0][0] = t; + + while(!q.empty()){ + int cx = q.front() / C, cy = q.front() % C, cur_t = visited[cx][cy]; + q.pop(); + + for(int d = 0; d < 4; d ++){ + int nx = cx + dirs[d][0], ny = cy + dirs[d][1]; + if(in_area(nx, ny) && grid[nx][ny] != 2 && visited[nx][ny] == -1){ + + if(cur_t + 1 > fire_time[nx][ny]) continue; + if(nx == R - 1 && ny == C - 1) return true; + + if(cur_t + 1 < fire_time[nx][ny]){ + visited[nx][ny] = cur_t + 1; + q.push(nx * C + ny); + } + } + } + } + return false; + } + + bool in_area(int x, int y){ + return 0 <= x && x < R && 0 <= y && y < C; + } +}; + + +int main() { + + vector> grid1 = { + {0,2,0,0,0,0,0}, + {0,0,0,2,2,1,0}, + {0,2,0,0,1,2,0}, + {0,0,2,2,2,0,2}, + {0,0,0,0,0,0,0} + }; + cout << Solution().maximumMinutes(grid1) << '\n'; + // 3 + + vector> grid2 = { + {0,2,0,0,1}, + {0,2,0,2,2}, + {0,2,0,0,0}, + {0,0,2,2,0}, + {0,0,0,0,0} + }; + cout << Solution().maximumMinutes(grid2) << '\n'; + // 0 + + return 0; +} diff --git a/2001-2500/2259-Remove-Digit-From-Number-to-Maximize-Result/cpp-2259/CMakeLists.txt b/2001-2500/2259-Remove-Digit-From-Number-to-Maximize-Result/cpp-2259/CMakeLists.txt new file mode 100644 index 00000000..fe8bfd9f --- /dev/null +++ b/2001-2500/2259-Remove-Digit-From-Number-to-Maximize-Result/cpp-2259/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/2001-2500/2259-Remove-Digit-From-Number-to-Maximize-Result/cpp-2259/main.cpp b/2001-2500/2259-Remove-Digit-From-Number-to-Maximize-Result/cpp-2259/main.cpp new file mode 100644 index 00000000..ec2c6878 --- /dev/null +++ b/2001-2500/2259-Remove-Digit-From-Number-to-Maximize-Result/cpp-2259/main.cpp @@ -0,0 +1,41 @@ +/// Source : https://leetcode.com/problems/remove-digit-from-number-to-maximize-result/ +/// Author : liuyubobobo +/// Time : 2022-04-30 + +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { +public: + string removeDigit(string number, char digit) { + + string res(number.size() - 1, '0'); + for(int i = 0; i < number.size(); i ++) + if(number[i] == digit){ + string cur = number.substr(0, i) + number.substr(i + 1); +// cout << cur << '\n'; + if(cur > res) res = cur; + } + return res; + } +}; + + +int main() { + + cout << Solution().removeDigit("123", '3') << '\n'; + // 12 + + cout << Solution().removeDigit("1231", '1') << '\n'; + // 231 + + cout << Solution().removeDigit("551", '5') << '\n'; + // 51 + + return 0; +} diff --git a/2001-2500/2260-Minimum-Consecutive-Cards-to-Pick-Up/cpp-2260/CMakeLists.txt b/2001-2500/2260-Minimum-Consecutive-Cards-to-Pick-Up/cpp-2260/CMakeLists.txt new file mode 100644 index 00000000..8494c320 --- /dev/null +++ b/2001-2500/2260-Minimum-Consecutive-Cards-to-Pick-Up/cpp-2260/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/2001-2500/2260-Minimum-Consecutive-Cards-to-Pick-Up/cpp-2260/main.cpp b/2001-2500/2260-Minimum-Consecutive-Cards-to-Pick-Up/cpp-2260/main.cpp new file mode 100644 index 00000000..58220580 --- /dev/null +++ b/2001-2500/2260-Minimum-Consecutive-Cards-to-Pick-Up/cpp-2260/main.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/minimum-consecutive-cards-to-pick-up/ +/// Author : liuyubobobo +/// Time : 2022-04-30 + +#include +#include +#include +#include + +using namespace std; + + +/// Using Map +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int minimumCardPickup(vector& cards) { + + map pos; + int res = INT_MAX; + for(int i = 0; i < cards.size(); i ++){ + if(pos.count(cards[i])){ + res = min(res, i - pos[cards[i]] + 1); + } + pos[cards[i]] = i; + } + return res == INT_MAX ? -1 : res; + } +}; + + +int main() { + + vector cards1 = {3,4,2,3,4,7}; + cout << Solution().minimumCardPickup(cards1) << '\n'; + // 4 + + vector cards2 = {1,0,5,3}; + cout << Solution().minimumCardPickup(cards2) << '\n'; + // -1 + + vector cards3 = {95,11,8,65,5,86,30,27,30,73,15,91,30,7,37,26,55,76,60,43,36,85,47,96,6}; + cout << Solution().minimumCardPickup(cards3) << '\n'; + // 3 + + vector cards4 = {77,10,11,51,69,83,33,94,0,42,86,41,65,40,72,8,53,31,43,22,9,94,45,80,40,0,84,34,76,28,7,79,80,93,20,82,36,74,82,89,74,77,27,54,44,93,98,44,39,74,36,9,22,57,70,98,19,68,33,68,49,86,20,50,43}; + cout << Solution().minimumCardPickup(cards4) << '\n'; + // 3 + + return 0; +} diff --git a/2001-2500/2261-K-Divisible-Elements-Subarrays/cpp-2261/CMakeLists.txt b/2001-2500/2261-K-Divisible-Elements-Subarrays/cpp-2261/CMakeLists.txt new file mode 100644 index 00000000..e69f76e5 --- /dev/null +++ b/2001-2500/2261-K-Divisible-Elements-Subarrays/cpp-2261/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main3.cpp) diff --git a/2001-2500/2261-K-Divisible-Elements-Subarrays/cpp-2261/main.cpp b/2001-2500/2261-K-Divisible-Elements-Subarrays/cpp-2261/main.cpp new file mode 100644 index 00000000..8ea4d0b5 --- /dev/null +++ b/2001-2500/2261-K-Divisible-Elements-Subarrays/cpp-2261/main.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/k-divisible-elements-subarrays/ +/// Author : liuyubobobo +/// Time : 2022-04-30 + +#include +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n^3) +/// Space Compelxity: O(n^3) +class Solution { +public: + int countDistinct(vector& nums, int k, int p) { + + int n = nums.size(); + vector k_divisible(n, 0); + for(int i = 0; i < n; i ++) k_divisible[i] = (nums[i] % p == 0); + + vector presum(n + 1, 0); + for(int i = 0; i < n; i ++) presum[i + 1] = presum[i] + k_divisible[i]; + + vector>> res(k + 1); + for(int l = 0; l < n; l ++) + for(int r = l; r < n; r ++){ + + int t = presum[r + 1] - presum[l]; + if(t <= k) + res[t].insert(vector(nums.begin() + l, nums.begin() + (r + 1))); + else break; + } + + int ret = 0; + for(const set>& s: res) ret += s.size(); + return ret; + } +}; + + +int main() { + + vector nums1 = {2, 3, 3, 2, 2}; + cout << Solution().countDistinct(nums1, 2, 2) << '\n'; + // 11 + + vector nums2 = {1, 2, 3, 4}; + cout << Solution().countDistinct(nums2, 4, 1) << '\n'; + // 10 + + return 0; +} diff --git a/2001-2500/2261-K-Divisible-Elements-Subarrays/cpp-2261/main2.cpp b/2001-2500/2261-K-Divisible-Elements-Subarrays/cpp-2261/main2.cpp new file mode 100644 index 00000000..38188f45 --- /dev/null +++ b/2001-2500/2261-K-Divisible-Elements-Subarrays/cpp-2261/main2.cpp @@ -0,0 +1,65 @@ +/// Source : https://leetcode.com/problems/k-divisible-elements-subarrays/ +/// Author : liuyubobobo +/// Time : 2022-05-01 + +#include +#include +#include +#include + +using namespace std; + + +/// Hash +/// Time Complexity: O(n^3) +/// Space Complexity: O(n^2) +class Solution { + +private: + const unsigned long long B = 13331; + +public: + int countDistinct(vector& nums, int k, int p) { + + int n = nums.size(); + vector k_divisible(n, 0); + for(int i = 0; i < n; i ++) k_divisible[i] = (nums[i] % p == 0); + + vector presum(n + 1, 0); + for(int i = 0; i < n; i ++) presum[i + 1] = presum[i] + k_divisible[i]; + + vector> res(k + 1); + for(int l = 0; l < n; l ++) + for(int r = l; r < n; r ++){ + + int t = presum[r + 1] - presum[l]; + if(t <= k) res[t].insert(vector_to_hash(nums, l, r)); + else break; + } + + int ret = 0; + for(const set& s: res) ret += s.size(); + return ret; + } + +private: + unsigned long long vector_to_hash(const vector& nums, int l, int r){ + unsigned long long res = 0; + for(int i = l; i <= r; i ++) res = res * B + nums[i]; + return res; + } +}; + + +int main() { + + vector nums1 = {2, 3, 3, 2, 2}; + cout << Solution().countDistinct(nums1, 2, 2) << '\n'; + // 11 + + vector nums2 = {1, 2, 3, 4}; + cout << Solution().countDistinct(nums2, 4, 1) << '\n'; + // 10 + + return 0; +} diff --git a/2001-2500/2261-K-Divisible-Elements-Subarrays/cpp-2261/main3.cpp b/2001-2500/2261-K-Divisible-Elements-Subarrays/cpp-2261/main3.cpp new file mode 100644 index 00000000..fb913a20 --- /dev/null +++ b/2001-2500/2261-K-Divisible-Elements-Subarrays/cpp-2261/main3.cpp @@ -0,0 +1,88 @@ +/// Source : https://leetcode.com/problems/k-divisible-elements-subarrays/ +/// Author : liuyubobobo +/// Time : 2022-05-01 + +#include +#include +#include + +using namespace std; + + +/// Trie +/// Time Complexity: O(n^3) +/// Space Complexity: O(n^3) +class Trie { + +private: + class Node{ + + public: + map next; + bool is_end; + + Node() : is_end(false) {}; + }; + + Node* root; + int sz; + +public: + Trie() : root(new Node()), sz(0) {} + + void insert(const vector& word, int l, int r) { + + Node* cur = root; + for(int i = l; i <= r; i ++){ + int c = word[i]; + if(!cur->next.count(c)) + cur->next[c] = new Node(); + cur = cur->next[c]; + + if(!cur->is_end) + cur->is_end = true, sz ++; + } + } + + int size(){ + return sz; + } +}; + +class Solution { + +public: + int countDistinct(vector& nums, int k, int p) { + + int n = nums.size(); + vector k_divisible(n, 0); + for(int i = 0; i < n; i ++) k_divisible[i] = (nums[i] % p == 0); + + vector presum(n + 1, 0); + for(int i = 0; i < n; i ++) presum[i + 1] = presum[i] + k_divisible[i]; + + Trie trie; + for(int l = 0; l < n; l ++){ + auto iter = upper_bound(presum.begin(), presum.end(), presum[l] + k); + int index = iter - presum.begin() - 1; + int r = index - 1; + if(l <= r) + trie.insert(nums, l, r); + } + return trie.size(); + } +}; + + +int main() { + + vector nums1 = {2, 3, 3, 2, 2}; + cout << Solution().countDistinct(nums1, 2, 2) << '\n'; + // 11 + + vector nums2 = {1, 2, 3, 4}; + cout << Solution().countDistinct(nums2, 4, 1) << '\n'; + // 10 + + return 0; +} diff --git a/2001-2500/2262-Total-Appeal-of-A-String/cpp-2262/CMakeLists.txt b/2001-2500/2262-Total-Appeal-of-A-String/cpp-2262/CMakeLists.txt new file mode 100644 index 00000000..bb71ae36 --- /dev/null +++ b/2001-2500/2262-Total-Appeal-of-A-String/cpp-2262/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main2.cpp) diff --git a/2001-2500/2262-Total-Appeal-of-A-String/cpp-2262/main.cpp b/2001-2500/2262-Total-Appeal-of-A-String/cpp-2262/main.cpp new file mode 100644 index 00000000..df6dad2b --- /dev/null +++ b/2001-2500/2262-Total-Appeal-of-A-String/cpp-2262/main.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/total-appeal-of-a-string/ +/// Author : liuyubobobo +/// Time : 2022-04-30 + +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + long long appealSum(string s) { + + int n = s.size(); + + vector> pos(26); + for(int i = 0; i < n; i ++) + pos[s[i] - 'a'].push_back(i); + + long long res = 0; + for(int ch = 0; ch < 26; ch ++){ + vector& v = pos[ch]; + for(int l = 0; l < n; l ++){ + auto iter = lower_bound(v.begin(), v.end(), l); + if(iter != v.end()) + res += n - *iter; + } + } + return res; + } +}; + + +int main() { + + cout << Solution().appealSum("abbca") << '\n'; + // 28 + + cout << Solution().appealSum("code") << '\n'; + // 20 + + return 0; +} diff --git a/2001-2500/2262-Total-Appeal-of-A-String/cpp-2262/main2.cpp b/2001-2500/2262-Total-Appeal-of-A-String/cpp-2262/main2.cpp new file mode 100644 index 00000000..efd5179b --- /dev/null +++ b/2001-2500/2262-Total-Appeal-of-A-String/cpp-2262/main2.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/total-appeal-of-a-string/ +/// Author : liuyubobobo +/// Time : 2022-05-03 + +#include +#include + +using namespace std; + + +/// Two Pointers +/// Time Complexity: O(n) +/// Space Compelxity: O(n) +class Solution { +public: + long long appealSum(string s) { + + int n = s.size(); + + vector> pos(26); + for(int i = 0; i < n; i ++) + pos[s[i] - 'a'].push_back(i); + + long long res = 0; + for(int ch = 0; ch < 26; ch ++){ + vector& v = pos[ch]; + int index = 0; + for(int l = 0; l < n && index < v.size(); l ++){ + res += n - v[index]; + if(v[index] == l) index ++; + } + } + return res; + } +}; + + +int main() { + + cout << Solution().appealSum("abbca") << '\n'; + // 28 + + cout << Solution().appealSum("code") << '\n'; + // 20 + + return 0; +} diff --git a/2001-2500/2263-Make-Array-Non-decreasing-or-Non-increasing/cpp-2263/CMakeLists.txt b/2001-2500/2263-Make-Array-Non-decreasing-or-Non-increasing/cpp-2263/CMakeLists.txt new file mode 100644 index 00000000..3ece3dd8 --- /dev/null +++ b/2001-2500/2263-Make-Array-Non-decreasing-or-Non-increasing/cpp-2263/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_2263) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2263 main.cpp) diff --git a/2001-2500/2263-Make-Array-Non-decreasing-or-Non-increasing/cpp-2263/main.cpp b/2001-2500/2263-Make-Array-Non-decreasing-or-Non-increasing/cpp-2263/main.cpp new file mode 100644 index 00000000..be4716ad --- /dev/null +++ b/2001-2500/2263-Make-Array-Non-decreasing-or-Non-increasing/cpp-2263/main.cpp @@ -0,0 +1,77 @@ +/// Source : https://leetcode.com/problems/make-array-non-decreasing-or-non-increasing/ +/// Author : liuyubobobo +/// Time : 2022-06-09 + +#include +#include +#include + +using namespace std; + + +/// DP + Basic Optimization +/// Time Complexity: O(n * maxv) +/// Space Complexity: O(n * maxv) +class Solution { + +public: + int convertArray(vector& nums) { + + int n = nums.size(), maxv = *max_element(nums.begin(), nums.end()); + + int res1 = solve(n, nums, maxv); + + reverse(nums.begin(), nums.end()); + int res2 = solve(n, nums, maxv); + + return min(res1, res2); + } + +private: + int solve(int n, const vector& nums, int maxv){ + + vector dp(maxv + 1), premin(maxv + 1); + for(int v = 0; v <= maxv; v ++){ + dp[v] = abs(nums[0] - v); + if(v) premin[v] = min(premin[v - 1], dp[v]); + else premin[v] = dp[v]; + } + + for(int i = 1; i < n; i ++){ + vector tdp(maxv + 1); + for(int v = 0; v <= maxv; v ++) + tdp[v] = premin[v] + abs(nums[i] - v); + + premin[0] = tdp[0]; + for(int v = 1; v <= maxv; v ++) premin[v] = min(premin[v - 1], tdp[v]); + dp = tdp; + } + return *min_element(dp.begin(), dp.end()); + } +}; + + +int main() { + + vector nums1 = {3,2,4,5,0}; + cout << Solution().convertArray(nums1) << '\n'; + // 4 + + vector nums2 = {2,2,3,4}; + cout << Solution().convertArray(nums2) << '\n'; + // 0 + + vector nums3 = {0}; + cout << Solution().convertArray(nums3) << '\n'; + // 0 + + vector nums4 = {0,2,8,0,3}; + cout << Solution().convertArray(nums4) << '\n'; + // 8 + + vector nums5 = {4,2,6,7}; + cout << Solution().convertArray(nums5) << '\n'; + // 2 + + return 0; +} diff --git a/2001-2500/2264-Largest-3-Same-Digit-Number-in-String/cpp-2264/CMakeLists.txt b/2001-2500/2264-Largest-3-Same-Digit-Number-in-String/cpp-2264/CMakeLists.txt new file mode 100644 index 00000000..7936f0bd --- /dev/null +++ b/2001-2500/2264-Largest-3-Same-Digit-Number-in-String/cpp-2264/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_2264) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2264 main.cpp) diff --git a/2001-2500/2264-Largest-3-Same-Digit-Number-in-String/cpp-2264/main.cpp b/2001-2500/2264-Largest-3-Same-Digit-Number-in-String/cpp-2264/main.cpp new file mode 100644 index 00000000..dcc0ee54 --- /dev/null +++ b/2001-2500/2264-Largest-3-Same-Digit-Number-in-String/cpp-2264/main.cpp @@ -0,0 +1,29 @@ +/// Source : https://leetcode.com/problems/largest-3-same-digit-number-in-string/ +/// Author : liuyubobobo +/// Time : 2022-05-07 + +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + string largestGoodInteger(string num) { + + int res = -1; + for(int i = 2; i < (int)num.size(); i ++) + if(num[i - 2] == num[i - 1] && num[i - 1] == num[i]) + res = max(res, num[i] - '0'); + return res == -1 ? "" : string(3, '0' + res); + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2265-Count-Nodes-Equal-to-Average-of-Subtree/cpp-2265/CMakeLists.txt b/2001-2500/2265-Count-Nodes-Equal-to-Average-of-Subtree/cpp-2265/CMakeLists.txt new file mode 100644 index 00000000..92334d44 --- /dev/null +++ b/2001-2500/2265-Count-Nodes-Equal-to-Average-of-Subtree/cpp-2265/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_2265) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2265 main.cpp) diff --git a/2001-2500/2265-Count-Nodes-Equal-to-Average-of-Subtree/cpp-2265/main.cpp b/2001-2500/2265-Count-Nodes-Equal-to-Average-of-Subtree/cpp-2265/main.cpp new file mode 100644 index 00000000..ae17774a --- /dev/null +++ b/2001-2500/2265-Count-Nodes-Equal-to-Average-of-Subtree/cpp-2265/main.cpp @@ -0,0 +1,55 @@ +/// Source : https://leetcode.com/problems/count-nodes-equal-to-average-of-subtree/ +/// Author : liuyubobobo +/// Time : 2022-05-07 + +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(h) + +/// 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: + int averageOfSubtree(TreeNode* root) { + + int res = 0; + dfs(root, res); + return res; + } + +private: + // sum, cnt + pair dfs(TreeNode* node, int& res){ + + if(!node) return {0, 0}; + + int sum = node->val, cnt = 1; + pair left_res = dfs(node->left, res); + pair right_res = dfs(node->right, res); + sum += left_res.first + right_res.first; + cnt += left_res.second + right_res.second; + + res += sum / cnt == node->val; + return {sum, cnt}; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2266-Count-Number-of-Texts/cpp-2266/CMakeLists.txt b/2001-2500/2266-Count-Number-of-Texts/cpp-2266/CMakeLists.txt new file mode 100644 index 00000000..b0f928fd --- /dev/null +++ b/2001-2500/2266-Count-Number-of-Texts/cpp-2266/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_2266) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2266 main.cpp) diff --git a/2001-2500/2266-Count-Number-of-Texts/cpp-2266/main.cpp b/2001-2500/2266-Count-Number-of-Texts/cpp-2266/main.cpp new file mode 100644 index 00000000..c9d1b633 --- /dev/null +++ b/2001-2500/2266-Count-Number-of-Texts/cpp-2266/main.cpp @@ -0,0 +1,51 @@ +/// Source : https://leetcode.com/problems/count-number-of-texts/ +/// Author : liuyubobobo +/// Time : 2022-05-07 + +#include +#include + +using namespace std; + + +/// Memoization +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +private: + const vector valid = {0, 0, 3, 3, 3, 3, 3, 4, 3, 4}; + const long long MOD = 1e9 + 7; + +public: + int countTexts(string pressedKeys) { + + int n = pressedKeys.size(); + vector dp(n, -1); + return dfs(n, pressedKeys, 0, dp); + } + +private: + long long dfs(int n, const string& s, int index, vector& dp){ + + if(index == n) return 1; + if(dp[index] != -1) return dp[index]; + + long long res = 0; + for(int i = index; i < n && s[i] == s[index] && i - index + 1 <= valid[s[index] - '0']; i ++) + res += dfs(n, s, i + 1, dp), res %= MOD; + return dp[index] = res; + } +}; + + +int main() { + + cout << Solution().countTexts("22233") << '\n'; + // 8 + + cout << Solution().countTexts("222222222222222222222222222222222222") << '\n'; + // 82876089 + + return 0; +} diff --git a/2001-2500/2267-Check-if-There-Is-a-Valid-Parentheses-String-Path/cpp-2267/CMakeLists.txt b/2001-2500/2267-Check-if-There-Is-a-Valid-Parentheses-String-Path/cpp-2267/CMakeLists.txt new file mode 100644 index 00000000..42565a7a --- /dev/null +++ b/2001-2500/2267-Check-if-There-Is-a-Valid-Parentheses-String-Path/cpp-2267/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_2267) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2267 main.cpp) diff --git a/2001-2500/2267-Check-if-There-Is-a-Valid-Parentheses-String-Path/cpp-2267/main.cpp b/2001-2500/2267-Check-if-There-Is-a-Valid-Parentheses-String-Path/cpp-2267/main.cpp new file mode 100644 index 00000000..4ff5a733 --- /dev/null +++ b/2001-2500/2267-Check-if-There-Is-a-Valid-Parentheses-String-Path/cpp-2267/main.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/check-if-there-is-a-valid-parentheses-string-path/ +/// Author : liuyubobobo +/// Time : 2022-05-07 + +#include +#include + +using namespace std; + + +/// Memoization +/// Time Complexity: O(R * C * (R + C - 1) / 2) +/// Space Complexity: O(R * C * (R + C - 1) / 2) +class Solution { + +private: + int R, C, L; + +public: + bool hasValidPath(vector>& grid) { + + R = grid.size(), C = grid[0].size(); + L = R + C - 1; + if(L % 2) return false; + + vector>> dp(R, vector>(C, vector(L / 2 + 1, -1))); + return dfs(grid, 0, 0, 0, dp); + } + +private: + int dfs(const vector>& g, int x, int y, int value, + vector>>& dp){ + + int next_value = value + (g[x][y] == '(' ? 1 : -1); + if(next_value < 0 || next_value > L / 2) return false; + if(x == R - 1 && y == C - 1) return next_value == 0; + + if(dp[x][y][value] != -1) return dp[x][y][value]; + + int res = 0; + if(in_area(x + 1, y) && dfs(g, x + 1, y, next_value, dp)) + res = 1; + if(!res && in_area(x, y + 1) && dfs(g, x, y + 1, next_value, dp)) + res = 1; + return dp[x][y][value] = res; + } + + bool in_area(int x, int y){ + return 0 <= x && x < R && 0 <= y && y < C; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2268-Minimum-Number-of-Keypresses/cpp-2268/CMakeLists.txt b/2001-2500/2268-Minimum-Number-of-Keypresses/cpp-2268/CMakeLists.txt new file mode 100644 index 00000000..59e7012e --- /dev/null +++ b/2001-2500/2268-Minimum-Number-of-Keypresses/cpp-2268/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_2268) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2268 main.cpp) diff --git a/2001-2500/2268-Minimum-Number-of-Keypresses/cpp-2268/main.cpp b/2001-2500/2268-Minimum-Number-of-Keypresses/cpp-2268/main.cpp new file mode 100644 index 00000000..73c007e0 --- /dev/null +++ b/2001-2500/2268-Minimum-Number-of-Keypresses/cpp-2268/main.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/minimum-number-of-keypresses/ +/// Author : liuyubobobo +/// Time : 2022-05-11 + +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int minimumKeypresses(string s) { + + vector f(26, 0); + for(char c: s) f[c - 'a'] ++; + + sort(f.begin(), f.end(), greater()); + + int res = 0; + for(int i = 0; i < 26; i ++) + res += f[i] * (i / 9 + 1); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2269-Find-the-K-Beauty-of-a-Number/cpp-2269/CMakeLists.txt b/2001-2500/2269-Find-the-K-Beauty-of-a-Number/cpp-2269/CMakeLists.txt new file mode 100644 index 00000000..433dcb8e --- /dev/null +++ b/2001-2500/2269-Find-the-K-Beauty-of-a-Number/cpp-2269/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_2269) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2269 main.cpp) diff --git a/2001-2500/2269-Find-the-K-Beauty-of-a-Number/cpp-2269/main.cpp b/2001-2500/2269-Find-the-K-Beauty-of-a-Number/cpp-2269/main.cpp new file mode 100644 index 00000000..10225951 --- /dev/null +++ b/2001-2500/2269-Find-the-K-Beauty-of-a-Number/cpp-2269/main.cpp @@ -0,0 +1,31 @@ +/// Source : https://leetcode.com/problems/find-the-k-beauty-of-a-number/ +/// Author : liuyubobobo +/// Time : 2022-05-14 + +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n * k) +/// Space Complexity: O(k) +class Solution { +public: + int divisorSubstrings(int num, int k) { + + string num_s = to_string(num); + int res = 0; + for(int i = 0; i + k - 1 < num_s.size(); i ++){ + int x = atoi(num_s.substr(i, k).c_str()); + if(x) res += num % x == 0; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2270-Number-of-Ways-to-Split-Array/cpp-2270/CMakeLists.txt b/2001-2500/2270-Number-of-Ways-to-Split-Array/cpp-2270/CMakeLists.txt new file mode 100644 index 00000000..bb0f0e81 --- /dev/null +++ b/2001-2500/2270-Number-of-Ways-to-Split-Array/cpp-2270/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_2270) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2270 main.cpp) diff --git a/2001-2500/2270-Number-of-Ways-to-Split-Array/cpp-2270/main.cpp b/2001-2500/2270-Number-of-Ways-to-Split-Array/cpp-2270/main.cpp new file mode 100644 index 00000000..b913cf5f --- /dev/null +++ b/2001-2500/2270-Number-of-Ways-to-Split-Array/cpp-2270/main.cpp @@ -0,0 +1,36 @@ +/// Source : https://leetcode.com/problems/number-of-ways-to-split-array/ +/// Author : liuyubobobo +/// Time : 2022-05-14 + +#include +#include + +using namespace std; + + +/// Presum +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int waysToSplitArray(vector& nums) { + + int n = nums.size(); + + vector presum(n + 1, 0ll); + for(int i = 0; i < n; i ++) presum[i + 1] = presum[i] + nums[i]; + + int res = 0; + for(int len = 1; len < n; len ++){ + int l1 = 0, r1 = l1 + len - 1, l2 = l1 + len, r2 = n - 1; + res += presum[r1 + 1] - presum[l1] >= presum[r2 + 1] - presum[l2]; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2271-Maximum-White-Tiles-Covered-by-a-Carpet/cpp-2271/CMakeLists.txt b/2001-2500/2271-Maximum-White-Tiles-Covered-by-a-Carpet/cpp-2271/CMakeLists.txt new file mode 100644 index 00000000..e0f69af1 --- /dev/null +++ b/2001-2500/2271-Maximum-White-Tiles-Covered-by-a-Carpet/cpp-2271/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_2271) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2271 main.cpp) diff --git a/2001-2500/2271-Maximum-White-Tiles-Covered-by-a-Carpet/cpp-2271/main.cpp b/2001-2500/2271-Maximum-White-Tiles-Covered-by-a-Carpet/cpp-2271/main.cpp new file mode 100644 index 00000000..dd5a3816 --- /dev/null +++ b/2001-2500/2271-Maximum-White-Tiles-Covered-by-a-Carpet/cpp-2271/main.cpp @@ -0,0 +1,76 @@ +/// Source : https://leetcode.com/problems/maximum-white-tiles-covered-by-a-carpet/ +/// Author : liuyubobobo +/// Time : 2022-05-14 + +#include +#include +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + int maximumWhiteTiles(vector>& tiles, int carpetLen) { + + int n = tiles.size(); + + vector> data(n); + for(int i = 0; i < n; i ++) data[i] = {tiles[i][0] - 1, tiles[i][1] - 1}; + sort(data.begin(), data.end()); + int res1 = get_res(n, data, carpetLen); + + int max_len = data.back().second + 1; + + for(pair& p: data) + p = {max_len - p.second, max_len - p.first}; + sort(data.begin(), data.end()); + int res2 = get_res(n, data, carpetLen); + + return max(res1, res2); + } + +private: + int get_res(int n, const vector>& data, int len){ + + vector presum(n + 1, 0); + for(int i = 0; i < n; i ++) + presum[i + 1] = presum[i] + (data[i].second - data[i].first + 1); + + int res = 0; + for(int i = 0; i < n; i ++){ + auto iter = lower_bound(data.begin() + i, data.end(), make_pair(data[i].first + len, -1)); + iter --; + int j = iter - data.begin(); + + assert(i <= j); + + int tres = 0; + if(i <= j - 1) tres += presum[j] - presum[i]; + + int pre = data[j].first - data[i].first; + tres += min(len - pre, data[j].second - data[j].first + 1); + + res = max(res, tres); + } + return res; + } +}; + + +int main() { + + vector> tiles1 = {{1,5},{10,11},{12,18},{20,25},{30,32}}; + cout << Solution().maximumWhiteTiles(tiles1, 10) << '\n'; + // 9 + + vector> tiles2 = {{10,11},{1, 1}}; + cout << Solution().maximumWhiteTiles(tiles2, 2) << '\n'; + // 2 + + return 0; +} diff --git a/2001-2500/2272-Substring-With-Largest-Variance/cpp-2272/CMakeLists.txt b/2001-2500/2272-Substring-With-Largest-Variance/cpp-2272/CMakeLists.txt new file mode 100644 index 00000000..ff71f363 --- /dev/null +++ b/2001-2500/2272-Substring-With-Largest-Variance/cpp-2272/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_2272) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2272 main.cpp) diff --git a/2001-2500/2272-Substring-With-Largest-Variance/cpp-2272/main.cpp b/2001-2500/2272-Substring-With-Largest-Variance/cpp-2272/main.cpp new file mode 100644 index 00000000..5f9ec06d --- /dev/null +++ b/2001-2500/2272-Substring-With-Largest-Variance/cpp-2272/main.cpp @@ -0,0 +1,73 @@ +/// Source : https://leetcode.com/problems/substring-with-largest-variance/description/ +/// Author : liuyubobobo +/// Time : 2023-07-09 + +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(n * 26 * 26) +/// Space Complexity: O(n) +class Solution { +public: + int largestVariance(string s) { + + int n = s.size(); + + int res = 0; + for(char max_c = 'a'; max_c <= 'z'; max_c ++) + for(char min_c = 'a'; min_c <= 'z'; min_c ++){ + if(max_c == min_c) continue; + res = max(res, solve(n, s, max_c, min_c)); + res = max(res, solve(n, s, max_c, min_c, true)); + } + return res; + } + +private: + int solve(int n, const string& s, char max_c, char min_c, bool reverse = false){ + + vector v(n); + if(!reverse){ + for(int i = 0; i < n; i ++) + v[i] = ((s[i] == max_c ? 1 : (s[i] == min_c ? -1 : 0))); + } + else{ + for(int i = n - 1; i >= 0; i --) + v[n - 1 - i] = (s[i] == max_c ? 1 : (s[i] == min_c ? -1 : 0)); + } + + int res = 0, cur = 0; + bool hit_neg = false; + for(int e: v){ + if(cur + e >= 0){ + cur += e; + if(e < 0) hit_neg = true; + if(hit_neg) res = max(res, cur); + } + else cur = 0, hit_neg = false; + } + return res; + } +}; + + +int main() { + + string s1 = "aababbb"; + cout << Solution().largestVariance(s1) << '\n'; + // 3 + + string s2 = "abcde"; + cout << Solution().largestVariance(s2) << '\n'; + // 0 + + string s3 = "lripaa"; + cout << Solution().largestVariance(s3) << '\n'; + // 1 + + return 0; +} diff --git a/2001-2500/2273-Find-Resultant-Array-After-Removing-Anagrams/cpp-2273/CMakeLists.txt b/2001-2500/2273-Find-Resultant-Array-After-Removing-Anagrams/cpp-2273/CMakeLists.txt new file mode 100644 index 00000000..fe8bfd9f --- /dev/null +++ b/2001-2500/2273-Find-Resultant-Array-After-Removing-Anagrams/cpp-2273/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/2001-2500/2273-Find-Resultant-Array-After-Removing-Anagrams/cpp-2273/main.cpp b/2001-2500/2273-Find-Resultant-Array-After-Removing-Anagrams/cpp-2273/main.cpp new file mode 100644 index 00000000..b97120d3 --- /dev/null +++ b/2001-2500/2273-Find-Resultant-Array-After-Removing-Anagrams/cpp-2273/main.cpp @@ -0,0 +1,36 @@ +/// Source : https://leetcode.com/problems/find-resultant-array-after-removing-anagrams/ +/// Author : liuyubobobo +/// Time : 2022-05-15 + +#include +#include + +using namespace std; + + +/// Stack +/// Time Complexity: O(n * |word|) +/// Space Complexity: O(1) +class Solution { +public: + vector removeAnagrams(vector& words) { + + vector res; + for(const string& word: words) + if(res.empty() || !same(word, res.back())) res.push_back(word); + return res; + } + +private: + bool same(string a, string b){ + sort(a.begin(), a.end()); + sort(b.begin(), b.end()); + return a == b; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2274-Maximum-Consecutive-Floors-Without-Special-Floors/cpp-2274/CMakeLists.txt b/2001-2500/2274-Maximum-Consecutive-Floors-Without-Special-Floors/cpp-2274/CMakeLists.txt new file mode 100644 index 00000000..8494c320 --- /dev/null +++ b/2001-2500/2274-Maximum-Consecutive-Floors-Without-Special-Floors/cpp-2274/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/2001-2500/2274-Maximum-Consecutive-Floors-Without-Special-Floors/cpp-2274/main.cpp b/2001-2500/2274-Maximum-Consecutive-Floors-Without-Special-Floors/cpp-2274/main.cpp new file mode 100644 index 00000000..73744e11 --- /dev/null +++ b/2001-2500/2274-Maximum-Consecutive-Floors-Without-Special-Floors/cpp-2274/main.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/maximum-consecutive-floors-without-special-floors/ +/// Author : liuyubobobo +/// Time : 2022-05-15 + +#include +#include +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + int maxConsecutive(int bottom, int top, vector& special) { + + special.push_back(top + 1); + sort(special.begin(), special.end()); + + int res = 0; + for(int cur = bottom, i = 0; i < special.size(); i ++){ + res = max(res, special[i] - cur); + cur = special[i] + 1; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2275-Largest-Combination-With-Bitwise-AND-Greater-Than-Zero/cpp-2275/CMakeLists.txt b/2001-2500/2275-Largest-Combination-With-Bitwise-AND-Greater-Than-Zero/cpp-2275/CMakeLists.txt new file mode 100644 index 00000000..830d3093 --- /dev/null +++ b/2001-2500/2275-Largest-Combination-With-Bitwise-AND-Greater-Than-Zero/cpp-2275/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/2001-2500/2275-Largest-Combination-With-Bitwise-AND-Greater-Than-Zero/cpp-2275/main.cpp b/2001-2500/2275-Largest-Combination-With-Bitwise-AND-Greater-Than-Zero/cpp-2275/main.cpp new file mode 100644 index 00000000..c2cdeb0e --- /dev/null +++ b/2001-2500/2275-Largest-Combination-With-Bitwise-AND-Greater-Than-Zero/cpp-2275/main.cpp @@ -0,0 +1,51 @@ +/// Source : https://leetcode.com/problems/largest-combination-with-bitwise-and-greater-than-zero/ +/// Author : liuyubobobo +/// Time : 2022-05-15 + +#include +#include + +using namespace std; + + +/// Bitwise +/// Time Complexity: O(nlogn(MAX_E)) +/// Space Complexity: O(1) +class Solution { +public: + int largestCombination(vector& candidates) { + + vector f(31, 0); + for(int e: candidates) calc(f, e); + + return *max_element(f.begin(), f.end()); + } + +private: + void calc(vector& f, int x){ + + int p = 0; + while(x){ + if(x & 1) f[p] ++; + x >>= 1, p ++; + } + } +}; + + +int main() { + + vector candidates1 = {16,17,71,62,12,24,14}; + cout << Solution().largestCombination(candidates1) << '\n'; + // 4 + + vector candidates2 = {8, 8}; + cout << Solution().largestCombination(candidates2) << '\n'; + // 2 + + vector candidates3 = {33,93,31,99,74,37,3,4,2,94,77,10,75,54,24,95,65,100,41,82,35,65,38,49,85,72,67,21,20,31}; + cout << Solution().largestCombination(candidates3) << '\n'; + // 18 + + return 0; +} diff --git a/2001-2500/2276-Count-Integers-in-Intervals/cpp-2276/CMakeLists.txt b/2001-2500/2276-Count-Integers-in-Intervals/cpp-2276/CMakeLists.txt new file mode 100644 index 00000000..9a6c5c78 --- /dev/null +++ b/2001-2500/2276-Count-Integers-in-Intervals/cpp-2276/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) diff --git a/2001-2500/2276-Count-Integers-in-Intervals/cpp-2276/main.cpp b/2001-2500/2276-Count-Integers-in-Intervals/cpp-2276/main.cpp new file mode 100644 index 00000000..3e66d2ac --- /dev/null +++ b/2001-2500/2276-Count-Integers-in-Intervals/cpp-2276/main.cpp @@ -0,0 +1,82 @@ +/// Source : https://leetcode.com/problems/count-integers-in-intervals/ +/// Author : liuyubobobo +/// Time : 2022-05-15 + +#include +#include + +using namespace std; + + +/// Using Set +/// Time Complexity: init: O(1) +/// add: O(logn) in everage +/// count: O(1) +/// Space Complexity: O(n) +class CountIntervals { + +private: + set> intervals; + int num = 0; + +public: + CountIntervals() { } + + void add(int left, int right) { + + auto iter = intervals.lower_bound({left, left - 1}); + if(iter != intervals.begin()){ + iter --; + if(intersection(left, right, iter->first, iter->second)){ + left = min(left, iter->first); + right = max(right, iter->second); + + num -= (iter->second - iter->first + 1); + intervals.erase(iter); + } + } + + while(true) { + auto iter = intervals.lower_bound({left, left - 1}); + if(iter == intervals.end()) break; + + if(intersection(left, right, iter->first, iter->second)){ + left = min(left, iter->first); + right = max(right, iter->second); + + num -= (iter->second - iter->first + 1); + intervals.erase(iter); + } + else break; + } + + intervals.insert({left, right}); + num += right - left + 1; + } + + int count() { + return num; + } + +private: + bool intersection(int l1, int r1, int l2, int r2){ + if(l1 > l2) swap(l1, l2), swap(r1, r2); + return l2 <= r1; + } +}; + + +int main() { + + CountIntervals obj; + obj.add(2, 3); + cout << obj.count() << '\n'; // 2 + + obj.add(7, 10); + cout << obj.count() << '\n'; // 6 + + obj.add(5, 8); + cout << obj.count() << '\n'; // 8 + + return 0; +} diff --git a/2001-2500/2277-Closest-Node-to-Path-in-Tree/cpp-2277/CMakeLists.txt b/2001-2500/2277-Closest-Node-to-Path-in-Tree/cpp-2277/CMakeLists.txt new file mode 100644 index 00000000..c8cc37a6 --- /dev/null +++ b/2001-2500/2277-Closest-Node-to-Path-in-Tree/cpp-2277/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_2277) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2277 main.cpp) diff --git a/2001-2500/2277-Closest-Node-to-Path-in-Tree/cpp-2277/main.cpp b/2001-2500/2277-Closest-Node-to-Path-in-Tree/cpp-2277/main.cpp new file mode 100644 index 00000000..e7656ed9 --- /dev/null +++ b/2001-2500/2277-Closest-Node-to-Path-in-Tree/cpp-2277/main.cpp @@ -0,0 +1,96 @@ +/// Source : https://leetcode.com/problems/closest-node-to-path-in-tree/ +/// Author : liuyubobobo +/// Time : 2022-05-20 + +#include +#include +#include +#include +#include +#include + +using namespace std; + + +/// BFS +/// Time Complexity: O(q * n * logn) +/// Space Complexity: O(n) +class Solution { +public: + vector closestNode(int n, vector>& edges, vector>& query) { + + vector> g(n); + for(const vector& edge: edges){ + int u = edge[0], v = edge[1]; + g[u].push_back(v), g[v].push_back(u); + } + + vector res; + for(const vector& q: query){ + int start = q[0], end = q[1], node = q[2]; + + set path = get_path(n, g, start, end); + res.push_back(get_res(n, g, node, path)); + } + return res; + } + +private: + int get_res(int n, const vector>& g, int s, const set& t_set){ + + if(t_set.size() == 1) return *t_set.begin(); + + vector visited(n, false); + queue q; + q.push(s); + while(!q.empty()){ + int u = q.front(); q.pop(); + if(t_set.count(u)) return u; + + for(int v: g[u]) + if(!visited[v]){ + visited[v] = true; + q.push(v); + } + } + assert(false); + return -1; + } + + set get_path(int n, const vector>& g, int s, int t){ + + if(s == t) return {s}; + + vector pre(n, -1); + queue q; + q.push(s); + pre[s] = s; + while(!q.empty()){ + int u = q.front(); q.pop(); + if(u == t) break; + + for(int v: g[u]) + if(pre[v] == -1){ + pre[v] = u; + q.push(v); + } + } + + set path; + int cur = t; + while(pre[cur] != cur){ + path.insert(cur); + cur = pre[cur]; + } + path.insert(cur); + + return path; + } +}; + + +int main() { + + + return 0; +} diff --git a/2001-2500/2278-Percentage-of-Letter-in-String/cpp-2278/CMakeLists.txt b/2001-2500/2278-Percentage-of-Letter-in-String/cpp-2278/CMakeLists.txt new file mode 100644 index 00000000..fe8bfd9f --- /dev/null +++ b/2001-2500/2278-Percentage-of-Letter-in-String/cpp-2278/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/2001-2500/2278-Percentage-of-Letter-in-String/cpp-2278/main.cpp b/2001-2500/2278-Percentage-of-Letter-in-String/cpp-2278/main.cpp new file mode 100644 index 00000000..46806ede --- /dev/null +++ b/2001-2500/2278-Percentage-of-Letter-in-String/cpp-2278/main.cpp @@ -0,0 +1,28 @@ +/// Source : https://leetcode.com/problems/percentage-of-letter-in-string/ +/// Author : liuyubobobo +/// Time : 2022-05-21 + +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int percentageLetter(string s, char letter) { + + int k = 0; + for(char c: s) k += c == letter; + + return k * 100 / s.size(); + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2279-Maximum-Bags-With-Full-Capacity-of-Rocks/cpp-2279/CMakeLists.txt b/2001-2500/2279-Maximum-Bags-With-Full-Capacity-of-Rocks/cpp-2279/CMakeLists.txt new file mode 100644 index 00000000..8494c320 --- /dev/null +++ b/2001-2500/2279-Maximum-Bags-With-Full-Capacity-of-Rocks/cpp-2279/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/2001-2500/2279-Maximum-Bags-With-Full-Capacity-of-Rocks/cpp-2279/main.cpp b/2001-2500/2279-Maximum-Bags-With-Full-Capacity-of-Rocks/cpp-2279/main.cpp new file mode 100644 index 00000000..1608687c --- /dev/null +++ b/2001-2500/2279-Maximum-Bags-With-Full-Capacity-of-Rocks/cpp-2279/main.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/maximum-bags-with-full-capacity-of-rocks/ +/// Author : liuyubobobo +/// Time : 2022-05-21 + +#include +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + int maximumBags(vector& capacity, vector& rocks, int additionalRocks) { + + int n = capacity.size(); + for(int i = 0; i < n; i ++) + capacity[i] -= rocks[i]; + + sort(capacity.begin(), capacity.end()); + for(int i = 0; i < n; i ++) + if(capacity[i] <= additionalRocks){ + additionalRocks -= capacity[i]; + capacity[i] = 0; + } + + int res = 0; + for(int e: capacity) res += e == 0; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2280-Minimum-Lines-to-Represent-a-Line-Chart/cpp-2280/CMakeLists.txt b/2001-2500/2280-Minimum-Lines-to-Represent-a-Line-Chart/cpp-2280/CMakeLists.txt new file mode 100644 index 00000000..830d3093 --- /dev/null +++ b/2001-2500/2280-Minimum-Lines-to-Represent-a-Line-Chart/cpp-2280/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/2001-2500/2280-Minimum-Lines-to-Represent-a-Line-Chart/cpp-2280/main.cpp b/2001-2500/2280-Minimum-Lines-to-Represent-a-Line-Chart/cpp-2280/main.cpp new file mode 100644 index 00000000..6855a1de --- /dev/null +++ b/2001-2500/2280-Minimum-Lines-to-Represent-a-Line-Chart/cpp-2280/main.cpp @@ -0,0 +1,49 @@ +/// Source : https://leetcode.com/problems/minimum-lines-to-represent-a-line-chart/ +/// Author : liuyubobobo +/// Time : 2022-05-21 + +#include +#include +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + int minimumLines(vector>& stockPrices) { + + sort(stockPrices.begin(), stockPrices.end()); + + int n = stockPrices.size(); + + vector> k; + for(int i = 1; i < n; i ++){ + int x0 = stockPrices[i - 1][0], y0 = stockPrices[i - 1][1]; + int x1 = stockPrices[i][0], y1 = stockPrices[i][1]; + int a = y1 - y0, b = x1 - x0; + + int g = gcd(min(abs(a), abs(b)), max(abs(a), abs(b))); + a /= g, b /= g; + + pair p = {a, b}; + if(k.empty() || k.back() != p) k.push_back(p); + } + return k.size(); + } + +private: + int gcd(int a, int b){ + if (a == 0) return b; + return gcd(b % a, a); + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2281-Sum-of-Total-Strength-of-Wizards/cpp-2281/CMakeLists.txt b/2001-2500/2281-Sum-of-Total-Strength-of-Wizards/cpp-2281/CMakeLists.txt new file mode 100644 index 00000000..9a6c5c78 --- /dev/null +++ b/2001-2500/2281-Sum-of-Total-Strength-of-Wizards/cpp-2281/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) diff --git a/2001-2500/2281-Sum-of-Total-Strength-of-Wizards/cpp-2281/main.cpp b/2001-2500/2281-Sum-of-Total-Strength-of-Wizards/cpp-2281/main.cpp new file mode 100644 index 00000000..20cfdbb5 --- /dev/null +++ b/2001-2500/2281-Sum-of-Total-Strength-of-Wizards/cpp-2281/main.cpp @@ -0,0 +1,142 @@ +/// Source : https://leetcode.com/problems/sum-of-total-strength-of-wizards/ +/// Author : liuyubobobo +/// Time : 2022-05-21 + +#include +#include + +using namespace std; + + +/// Counting, Segment Tree + Presum +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +template +class SegmentTree{ + +private: + int n; + vector data, tree; + +public: + SegmentTree(const vector& data): n(data.size()), data(data), tree(4 * n, 0){ + buildSegTree(0, 0, n - 1); + } + + T query(int l, int r){ +// assert(l <= r); +// assert(0 <= l && l < n); +// assert(0 <= r && r < n); + return query(0, 0, n - 1, l, r); + } + +private: + void buildSegTree(int treeID, int l, int r){ + + if(l == r){ + tree[treeID] = l; + return; + } + + int mid = (l + r) / 2; + buildSegTree(treeID * 2 + 1, l, mid); + buildSegTree(treeID * 2 + 2, mid + 1, r); + tree[treeID] = data[tree[treeID * 2 + 1]] < data[tree[treeID * 2 + 2]] ? tree[treeID * 2 + 1] : tree[treeID * 2 + 2]; + return; + } + + T query(int treeID, int l, int r, int ql, int qr){ + + if(ql == l && qr == r) + return tree[treeID]; + + int mid = (l + r) / 2; + if(qr <= mid) return query(treeID * 2 + 1, l, mid, ql, qr); + else if(ql > mid) return query(treeID * 2 + 2, mid + 1, r, ql, qr); + + T resl = query(treeID * 2 + 1, l, mid, ql, mid); + T resr = query(treeID * 2 + 2, mid + 1, r, mid + 1, qr); + return data[resl] < data[resr] ? resl : resr; + } +}; + +class Solution { + +private: + const long long MOD = 1e9 + 7; + vector presum, presum_sum, sufsum_sum; + SegmentTree *seg_tree; + +public: + int totalStrength(vector& strength) { + + int n = strength.size(); + + presum.assign(n + 1, 0); + for(int i = 0; i < n; i ++) presum[i + 1] = presum[i] + strength[i]; + + presum_sum.assign(n + 2, 0); + for(int i = 0; i < n; i ++) + presum_sum[i + 1] = ((long long)strength[i] * (i + 1) % MOD + presum_sum[i] ) % MOD; + + sufsum_sum.assign(n + 2, 0); + for(int i = n - 1; i >= 0; i --) + sufsum_sum[i + 1] = ((long long)strength[i] * (n - i) % MOD + sufsum_sum[i + 2]) % MOD; + + seg_tree = new SegmentTree(strength); + return dfs(n, strength, 0, n - 1); + } + +private: + long long dfs(int n, const vector& v, int l, int r){ + + if(l > r) return 0; + if(l == r) return (long long)v[l] * v[l] % MOD; + + int min_index = seg_tree->query(l, r); + long long sum = get_total_sum(n, l, r, min_index); + + long long res = sum * v[min_index] % MOD; + res = (res + dfs(n, v, l, min_index - 1)) % MOD; + res = (res + dfs(n, v, min_index + 1, r)) % MOD; + return res; + } + + long long get_total_sum(int n, int l, int r, int k){ + + long long total_left = (presum_sum[k + 1] - presum_sum[l] + MOD) % MOD; + total_left -= (presum[k + 1] - presum[l] + MOD) % MOD * l % MOD; + total_left = (total_left + MOD) % MOD; + + if(k < r){ + long long additional_right = (sufsum_sum[k + 2] - sufsum_sum[r + 2] + MOD) % MOD; + additional_right -= (presum[r + 1] - presum[k + 1] + MOD) % MOD * (n - r - 1) % MOD; + additional_right = (additional_right + MOD) % MOD; + + long long left_cnt = k - l + 1; + long long right_cnt = r - k; + + additional_right = additional_right * left_cnt % MOD; + + total_left = total_left * (right_cnt + 1) % MOD; + total_left += additional_right; + total_left %= MOD; + } + + return total_left; + } +}; + + +int main() { + + vector strength1 = {1, 3, 1, 2}; + cout << Solution().totalStrength(strength1) << '\n'; + // 44 + + vector strength2 = {5, 4, 6}; + cout << Solution().totalStrength(strength2) << '\n'; + // 213 + + return 0; +} diff --git a/2001-2500/2283-Check-if-Number-Has-Equal-Digit-Count-and-Digit-Value/cpp-2283/CMakeLists.txt b/2001-2500/2283-Check-if-Number-Has-Equal-Digit-Count-and-Digit-Value/cpp-2283/CMakeLists.txt new file mode 100644 index 00000000..e878956b --- /dev/null +++ b/2001-2500/2283-Check-if-Number-Has-Equal-Digit-Count-and-Digit-Value/cpp-2283/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_2283) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2283 main.cpp) diff --git a/2001-2500/2283-Check-if-Number-Has-Equal-Digit-Count-and-Digit-Value/cpp-2283/main.cpp b/2001-2500/2283-Check-if-Number-Has-Equal-Digit-Count-and-Digit-Value/cpp-2283/main.cpp new file mode 100644 index 00000000..6e1ee80c --- /dev/null +++ b/2001-2500/2283-Check-if-Number-Has-Equal-Digit-Count-and-Digit-Value/cpp-2283/main.cpp @@ -0,0 +1,31 @@ +/// Source : https://leetcode.com/problems/check-if-number-has-equal-digit-count-and-digit-value/ +/// Author : liuyubobobo +/// Time : 2021-05-28 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + bool digitCount(string num) { + + vector f(10, 0); + for(char c: num) f[c - '0'] ++; + + for(int i = 0; i < num.size(); i ++) + if(num[i] - '0' != f[i]) return false; + return true; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2284-Sender-With-Largest-Word-Count/cpp-2284/CMakeLists.txt b/2001-2500/2284-Sender-With-Largest-Word-Count/cpp-2284/CMakeLists.txt new file mode 100644 index 00000000..47d416b2 --- /dev/null +++ b/2001-2500/2284-Sender-With-Largest-Word-Count/cpp-2284/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_2284) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2284 main.cpp) diff --git a/2001-2500/2284-Sender-With-Largest-Word-Count/cpp-2284/main.cpp b/2001-2500/2284-Sender-With-Largest-Word-Count/cpp-2284/main.cpp new file mode 100644 index 00000000..0859311e --- /dev/null +++ b/2001-2500/2284-Sender-With-Largest-Word-Count/cpp-2284/main.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/sender-with-largest-word-count/ +/// Author : liuyubobobo +/// Time : 2022-05-28 + +#include +#include +#include + +using namespace std; + + +/// Using Map +/// Time Complexity: O(nlogn * |message|) +/// Space Complexity: O(n) +class Solution { +public: + string largestWordCount(vector& messages, vector& senders) { + + int n = messages.size(); + + map> cnt; + for(int i = 0; i < n; i ++){ + string name = senders[i]; + cnt[name] += get_cnt(messages[i]); + } + + int largest = -1; + string res = ""; + for(const pair& p: cnt) + if(p.second > largest) res = p.first, largest = p.second; + return res; + } + +private: + int get_cnt(const string& s){ + + int res = 0; + for(int start = 0, i = 1; i <= s.size(); i ++) + if(i == s.size() || s[i] == ' '){ + res ++; + start = i + 1; + i = start; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2285-Maximum-Total-Importance-of-Roads/cpp-2285/CMakeLists.txt b/2001-2500/2285-Maximum-Total-Importance-of-Roads/cpp-2285/CMakeLists.txt new file mode 100644 index 00000000..33894595 --- /dev/null +++ b/2001-2500/2285-Maximum-Total-Importance-of-Roads/cpp-2285/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_2285) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2285 main.cpp) diff --git a/2001-2500/2285-Maximum-Total-Importance-of-Roads/cpp-2285/main.cpp b/2001-2500/2285-Maximum-Total-Importance-of-Roads/cpp-2285/main.cpp new file mode 100644 index 00000000..0b0c9acb --- /dev/null +++ b/2001-2500/2285-Maximum-Total-Importance-of-Roads/cpp-2285/main.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/maximum-total-importance-of-roads/ +/// Author : liuyubobobo +/// Time : 2022-05-28 + +#include +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + long long maximumImportance(int n, vector>& roads) { + + vector degrees(n, 0); + for(const vector& road: roads) + degrees[road[0]] ++, degrees[road[1]] ++; + + sort(degrees.begin(), degrees.end(), greater()); + long long res = 0; + for(int i = 0; i < n; i ++) + res += degrees[i] * (n - i); + return res; + } +}; + +int main() { + + return 0; +} diff --git a/2001-2500/2286-Booking-Concert-Tickets-in-Groups/cpp-2286/CMakeLists.txt b/2001-2500/2286-Booking-Concert-Tickets-in-Groups/cpp-2286/CMakeLists.txt new file mode 100644 index 00000000..efee9583 --- /dev/null +++ b/2001-2500/2286-Booking-Concert-Tickets-in-Groups/cpp-2286/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_2286) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2286 main.cpp) diff --git a/2001-2500/2286-Booking-Concert-Tickets-in-Groups/cpp-2286/main.cpp b/2001-2500/2286-Booking-Concert-Tickets-in-Groups/cpp-2286/main.cpp new file mode 100644 index 00000000..999482d8 --- /dev/null +++ b/2001-2500/2286-Booking-Concert-Tickets-in-Groups/cpp-2286/main.cpp @@ -0,0 +1,178 @@ +/// Source : https://leetcode.com/problems/booking-concert-tickets-in-groups/ +/// Author : liuyubobobo +/// Time : 2022-05-28 + +#include +#include +#include + +using namespace std; + + +/// Segment Tree + Binary Search +/// Time Complexity: init: O(nlogn) +/// gather: O(logn * logn) +/// scatter: O(logn) in average +/// Space Complexity: O(n) +template +class SegmentTree{ + +private: + int n; + vector data, max_tree, sum_tree; + +public: + SegmentTree(const vector& data): n(data.size()), data(data), max_tree(4 * n, 0), sum_tree(4 * n, 0){ + buildSegTree(0, 0, n - 1); + } + + void update(int index, T value){ + if(data[index] == value) return; + data[index] = value; + update(0, 0, n - 1, index, value); + } + + T query(int index){ + assert(0 <= index && index < n); + return data[index]; + } + + T query_max(int l, int r){ + if(l > r || l < 0 || l >= n || r < 0 || r >= n) return 0; + return query_max(0, 0, n - 1, l, r); + } + + T query_sum(int l, int r){ + if(l > r || l < 0 || l >= n || r < 0 || r >= n) return 0; + return query_sum(0, 0, n - 1, l, r); + } + +private: + void buildSegTree(int treeID, int l, int r){ + + if(l == r){ + max_tree[treeID] = sum_tree[treeID] = data[l]; + return; + } + + int mid = (l + r) / 2; + buildSegTree(treeID * 2 + 1, l, mid); + buildSegTree(treeID * 2 + 2, mid + 1, r); + max_tree[treeID] = max(max_tree[treeID * 2 + 1], max_tree[treeID * 2 + 2]); + sum_tree[treeID] = sum_tree[treeID * 2 + 1] + sum_tree[treeID * 2 + 2]; + return; + } + + void update(int treeID, int l, int r, int index, T value){ + + if(l == r){ + assert(l == index); + max_tree[treeID] = sum_tree[treeID] = value; + return; + } + + int mid = (l + r) / 2; + if(index <= mid) update(treeID * 2 + 1, l, mid, index, value); + else update(treeID * 2 + 2, mid + 1, r, index, value); + + max_tree[treeID] = max(max_tree[treeID * 2 + 1], max_tree[treeID * 2 + 2]); + sum_tree[treeID] = sum_tree[treeID * 2 + 1] + sum_tree[treeID * 2 + 2]; + return; + } + + T query_max(int treeID, int l, int r, int ql, int qr){ + + if(ql == l && qr == r) + return max_tree[treeID]; + + int mid = (l + r) / 2; + if(qr <= mid) return query_max(treeID * 2 + 1, l, mid, ql, qr); + else if(ql > mid) return query_max(treeID * 2 + 2, mid + 1, r, ql, qr); + + T resl = query_max(treeID * 2 + 1, l, mid, ql, mid); + T resr = query_max(treeID * 2 + 2, mid + 1, r, mid + 1, qr); + return max(resl, resr); + } + + T query_sum(int treeID, int l, int r, int ql, int qr){ + + if(ql == l && qr == r) + return sum_tree[treeID]; + + int mid = (l + r) / 2; + if(qr <= mid) return query_sum(treeID * 2 + 1, l, mid, ql, qr); + else if(ql > mid) return query_sum(treeID * 2 + 2, mid + 1, r, ql, qr); + + T resl = query_sum(treeID * 2 + 1, l, mid, ql, mid); + T resr = query_sum(treeID * 2 + 2, mid + 1, r, mid + 1, qr); + return resl + resr; + } +}; + +class BookMyShow { + +private: + int n, m, first_non_zero_index; + SegmentTree *seg_tree; + +public: + BookMyShow(int n, int m) : n(n), m(m), first_non_zero_index(0) { + seg_tree = new SegmentTree(vector(n, m)); + } + + vector gather(int k, int maxRow) { + + int l = first_non_zero_index, r = maxRow + 1; + if(l > r) return {}; + + while(l < r){ + int mid = (l + r) / 2; + if(seg_tree->query_max(l, mid) >= k) r = mid; + else l = mid + 1; + } + + if(l == maxRow + 1) return {}; + + int left = seg_tree->query(l); + seg_tree->update(l, left - k); + + while(first_non_zero_index < n && seg_tree->query(first_non_zero_index) == 0) + first_non_zero_index ++; + return {l, m - left}; + } + + bool scatter(int k, int maxRow) { + + if(seg_tree->query_sum(first_non_zero_index, maxRow) < k) return false; + + for(int i = first_non_zero_index; i <= maxRow && k; i ++){ + int v = seg_tree->query(i); + int t = min(k, v); + + k -= t; + seg_tree->update(i, v - t); + if(v - t == 0) first_non_zero_index ++; + } + return true; + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << ' '; cout << '\n'; +} + +int main() { + + BookMyShow obj(19, 9); + print_vec(obj.gather(38, 8)); // empty + print_vec(obj.gather(27, 3)); // empty + cout << obj.scatter(36, 14) << '\n'; // 1 + cout << obj.scatter(46, 2) << '\n'; // 0 + print_vec(obj.gather(12, 5)); // empty + cout << obj.scatter(12, 12) << '\n'; // 1 + cout << obj.scatter(43, 12) << '\n'; // 1 + print_vec(obj.gather(30, 5)); // empty + + return 0; +} diff --git a/2001-2500/2287-Rearrange-Characters-to-Make-Target-String/cpp-2287/CMakeLists.txt b/2001-2500/2287-Rearrange-Characters-to-Make-Target-String/cpp-2287/CMakeLists.txt new file mode 100644 index 00000000..fe8bfd9f --- /dev/null +++ b/2001-2500/2287-Rearrange-Characters-to-Make-Target-String/cpp-2287/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/2001-2500/2287-Rearrange-Characters-to-Make-Target-String/cpp-2287/main.cpp b/2001-2500/2287-Rearrange-Characters-to-Make-Target-String/cpp-2287/main.cpp new file mode 100644 index 00000000..184017fd --- /dev/null +++ b/2001-2500/2287-Rearrange-Characters-to-Make-Target-String/cpp-2287/main.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/rearrange-characters-to-make-target-string/ +/// Author : liuyubobobo +/// Time : 2022-05-29 + +#include +#include + +using namespace std; + + +/// Using Map +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int rearrangeCharacters(string s, string target) { + + vector fs(26, 0); + for(char c: s) fs[c - 'a'] ++; + + vector ft(26, 0); + for(char c: target) ft[c - 'a'] ++; + + int res = INT_MAX; + for(int i = 0; i < 26; i ++) + if(ft[i]) res = min(res, fs[i] / ft[i]); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2288-Apply-Discount-to-Prices/cpp-2288/CMakeLists.txt b/2001-2500/2288-Apply-Discount-to-Prices/cpp-2288/CMakeLists.txt new file mode 100644 index 00000000..8494c320 --- /dev/null +++ b/2001-2500/2288-Apply-Discount-to-Prices/cpp-2288/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/2001-2500/2288-Apply-Discount-to-Prices/cpp-2288/main.cpp b/2001-2500/2288-Apply-Discount-to-Prices/cpp-2288/main.cpp new file mode 100644 index 00000000..833abbbf --- /dev/null +++ b/2001-2500/2288-Apply-Discount-to-Prices/cpp-2288/main.cpp @@ -0,0 +1,64 @@ +/// Source : https://leetcode.com/problems/apply-discount-to-prices/ +/// Author : liuyubobobo +/// Time : 2022-05-29 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + string discountPrices(string sentence, int discount) { + + vector words; + for(int start = 0, i = 1; i <= sentence.size(); i ++) + if(i == sentence.size() || sentence[i] == ' '){ + words.push_back(sentence.substr(start, i - start)); + start = i + 1; + i = start; + } + + for(string& word: words) + if(is_price(word)){ + long long price = atoll(word.substr(1).c_str()); + price *= (100 - discount); + + string new_s = to_string(price); + while(new_s.size() < 3) new_s = "0" + new_s; + + int len = new_s.size(); + word = "$" + new_s.substr(0, len - 2) + "." + new_s.substr(len - 2); + } + + string res = ""; + for(int i = 0; i < words.size(); i ++){ + res += words[i]; + if(i + 1 != words.size()) res += " "; + } + return res; + } + +private: + bool is_price(const string& s){ + + if(s.size() == 1) return false; + + if(s[0] != '$') return false; + + for(int i = 1; i < s.size(); i ++) + if(!isdigit(s[i])) return false; + + return true; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2289-Steps-to-Make-Array-Non-decreasing/cpp-2289/CMakeLists.txt b/2001-2500/2289-Steps-to-Make-Array-Non-decreasing/cpp-2289/CMakeLists.txt new file mode 100644 index 00000000..a89245a8 --- /dev/null +++ b/2001-2500/2289-Steps-to-Make-Array-Non-decreasing/cpp-2289/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_2289) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2289 main2.cpp) diff --git a/2001-2500/2289-Steps-to-Make-Array-Non-decreasing/cpp-2289/main.cpp b/2001-2500/2289-Steps-to-Make-Array-Non-decreasing/cpp-2289/main.cpp new file mode 100644 index 00000000..4eba6d36 --- /dev/null +++ b/2001-2500/2289-Steps-to-Make-Array-Non-decreasing/cpp-2289/main.cpp @@ -0,0 +1,113 @@ +/// Source : https://leetcode.com/problems/steps-to-make-array-non-decreasing/ +/// Author : liuyubobobo +/// Time : 2022-06-04 + +#include +#include +#include + +using namespace std; + + +/// Linked List Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(n) +template +class Node{ +public: + T value; + Node* next, *prev; + Node(T v, Node* next, Node* prev) : value(v), next(next), prev(prev){} + Node(T v) : Node(v, nullptr, nullptr){} + Node(): Node(T()){} +}; + +template +class LinkedList{ +public: + Node* head, *tail; + + LinkedList(){ + head = new Node(); + tail = new Node(); + head->next = tail; + tail->prev = head; + } + + void add(Node* pre, T v){ + Node* new_node = new Node(v); + add(pre, new_node); + } + + void add_first(T v){ + add(head, v); + } + + void add_last(T v){ + add(tail->prev, v); + } + + void add(Node* pre, Node* new_node){ + new_node->next = pre->next; + pre->next = new_node; + new_node->next->prev = new_node; + new_node->prev = pre; + } + + void add_first(Node* new_node){ + add(head, new_node); + } + + void add_last(Node* new_node){ + add(tail->prev, new_node); + } + + // return node->next + Node* remove(Node* node){ +// assert(!node); + Node* ret = node->next; + node->prev->next = node->next; + node->next->prev = node->prev; + delete node; + return ret; + } +}; + +class Solution { +public: + int totalSteps(vector& nums) { + + LinkedList linkedList; + deque*> del; + for(int i = (int)nums.size() - 1; i >= 0; i --){ + linkedList.add_first(nums[i]); + if(i - 1 >= 0 && nums[i - 1] > nums[i]) + del.push_back(linkedList.head->next); + } + + int res = 0; + while(!del.empty()){ + int n = del.size(); + for(int i = 0; i < n; i ++){ + Node* del_node = del.front(); del.pop_front(); + Node* next = linkedList.remove(del_node); + if(next != linkedList.tail && next->prev != linkedList.head && next->prev->value > next->value){ + if(del.empty() || del.back() != next) + del.push_back(next); + } + } + res ++; + } + return res; + } +}; + + +int main() { + + vector nums1 = {7, 14, 4, 14, 13, 2, 6, 13}; + cout << Solution().totalSteps(nums1) << '\n'; + // 3 + + return 0; +} diff --git a/2001-2500/2289-Steps-to-Make-Array-Non-decreasing/cpp-2289/main2.cpp b/2001-2500/2289-Steps-to-Make-Array-Non-decreasing/cpp-2289/main2.cpp new file mode 100644 index 00000000..b2f0f049 --- /dev/null +++ b/2001-2500/2289-Steps-to-Make-Array-Non-decreasing/cpp-2289/main2.cpp @@ -0,0 +1,43 @@ +/// Source : https://leetcode.com/problems/steps-to-make-array-non-decreasing/ +/// Author : liuyubobobo +/// Time : 2022-06-04 + +#include +#include +#include + +using namespace std; + + +/// Mono Stack +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int totalSteps(vector& nums) { + + int n = nums.size(); + + vector dp(n, 0); + stack s; + for(int i = n - 1; i >= 0; i --){ + while(!s.empty() && nums[i] > nums[s.top()]){ + dp[i] ++; + dp[i] = max(dp[i], dp[s.top()]); + s.pop(); + } + s.push(i); + } + return *max_element(dp.begin(), dp.end()); + } +}; + + +int main() { + + vector nums1 = {7, 14, 4, 14, 13, 2, 6, 13}; + cout << Solution().totalSteps(nums1) << '\n'; + // 3 + + return 0; +} diff --git a/2001-2500/2290-Minimum-Obstacle-Removal-to-Reach-Corner/cpp-2290/CMakeLists.txt b/2001-2500/2290-Minimum-Obstacle-Removal-to-Reach-Corner/cpp-2290/CMakeLists.txt new file mode 100644 index 00000000..9a6c5c78 --- /dev/null +++ b/2001-2500/2290-Minimum-Obstacle-Removal-to-Reach-Corner/cpp-2290/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) diff --git a/2001-2500/2290-Minimum-Obstacle-Removal-to-Reach-Corner/cpp-2290/main.cpp b/2001-2500/2290-Minimum-Obstacle-Removal-to-Reach-Corner/cpp-2290/main.cpp new file mode 100644 index 00000000..f9de6da0 --- /dev/null +++ b/2001-2500/2290-Minimum-Obstacle-Removal-to-Reach-Corner/cpp-2290/main.cpp @@ -0,0 +1,65 @@ +/// Source : https://leetcode.com/problems/minimum-obstacle-removal-to-reach-corner/ +/// Author : liuyubobobo +/// Time : 2022-05-29 + +#include +#include +#include +#include + +using namespace std; + + +/// 0-1 BFS +/// Time Complexity: O(n * m) +/// Space Complexity: O(n * m) +class Solution { + +private: + const int dirs[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; + int R, C; + +public: + int minimumObstacles(vector>& grid) { + + R = grid.size(), C = grid[0].size(); + + vector dis(R * C, INT_MAX / 2); + vector visited(R * C, false); + deque q; + q.push_back(0); + dis[0] = 0; + while(!q.empty()){ + int u = q.front(); q.pop_front(); + if(visited[u]) continue; + + visited[u] = true; + if(u == R * C - 1) break; + + int cx = u / C, cy = u % C; + for(int d = 0; d < 4; d ++){ + int nx = cx + dirs[d][0], ny = cy + dirs[d][1]; + if(!in_area(nx, ny)) continue; + + int v = nx * C + ny, w = grid[nx][ny]; + if(!visited[v] && dis[u] + w < dis[v]){ + dis[v] = dis[u] + w; + if(w) q.push_back(v); + else q.push_front(v); + } + } + } + return dis[R * C - 1]; + } + +private: + bool in_area(int x, int y){ + return 0 <= x && x < R && 0 <= y && y < C; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2291-Maximum-Profit-From-Trading-Stocks/cpp-2291/CMakeLists.txt b/2001-2500/2291-Maximum-Profit-From-Trading-Stocks/cpp-2291/CMakeLists.txt new file mode 100644 index 00000000..cdc867b5 --- /dev/null +++ b/2001-2500/2291-Maximum-Profit-From-Trading-Stocks/cpp-2291/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_2291) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2291 main.cpp) diff --git a/2001-2500/2291-Maximum-Profit-From-Trading-Stocks/cpp-2291/main.cpp b/2001-2500/2291-Maximum-Profit-From-Trading-Stocks/cpp-2291/main.cpp new file mode 100644 index 00000000..0e57b8cf --- /dev/null +++ b/2001-2500/2291-Maximum-Profit-From-Trading-Stocks/cpp-2291/main.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/maximum-profit-from-trading-stocks/ +/// Author : liuyubobobo +/// Time : 2022-05-31 + +#include +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(n * budget) +/// Space Complexity: O(n + budget) +class Solution { +public: + int maximumProfit(vector& present, vector& future, int budget) { + + int n = present.size(); + + vector values, weight; + for(int i = 0; i < n; i ++) + if(future[i] > present[i] && present[i] <= budget){ + values.push_back(future[i] - present[i]); + weight.push_back(present[i]); + } + + vector dp(budget + 1, 0); + for(int i = 0; i < values.size(); i ++){ + vector tdp = dp; + for(int j = budget; j >= weight[i]; j --) + tdp[j] = max(tdp[j], tdp[j - weight[i]] + values[i]); + dp = tdp; + } + return dp.back(); + } +}; + + +int main() { + + vector present = {2,2,5}, future = {3,4,10}; + cout << Solution().maximumProfit(present, future, 6) << '\n'; + // 5 + + return 0; +} diff --git a/2001-2500/2293-Min-Max-Game/cpp-2293/CMakeLists.txt b/2001-2500/2293-Min-Max-Game/cpp-2293/CMakeLists.txt new file mode 100644 index 00000000..fe8bfd9f --- /dev/null +++ b/2001-2500/2293-Min-Max-Game/cpp-2293/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/2001-2500/2293-Min-Max-Game/cpp-2293/main.cpp b/2001-2500/2293-Min-Max-Game/cpp-2293/main.cpp new file mode 100644 index 00000000..2a17647b --- /dev/null +++ b/2001-2500/2293-Min-Max-Game/cpp-2293/main.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/min-max-game/ +/// Author : liuyubobobo +/// Time : 2022-06-04 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + int minMaxGame(vector& nums) { + + while(nums.size() > 1){ + + vector nums2(nums.size() / 2); + for(int i = 0; i < nums2.size(); i ++) + if(i % 2 == 0) nums2[i] = min(nums[2 * i], nums[2 * i + 1]); + else nums2[i] = max(nums[2 * i], nums[2 * i + 1]); + nums = nums2; + } + return nums[0]; + } +}; + + +int main() { + + + return 0; +} diff --git a/2001-2500/2294-Partition-Array-Such-That-Maximum-Difference-Is-K/cpp-2294/CMakeLists.txt b/2001-2500/2294-Partition-Array-Such-That-Maximum-Difference-Is-K/cpp-2294/CMakeLists.txt new file mode 100644 index 00000000..8494c320 --- /dev/null +++ b/2001-2500/2294-Partition-Array-Such-That-Maximum-Difference-Is-K/cpp-2294/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/2001-2500/2294-Partition-Array-Such-That-Maximum-Difference-Is-K/cpp-2294/main.cpp b/2001-2500/2294-Partition-Array-Such-That-Maximum-Difference-Is-K/cpp-2294/main.cpp new file mode 100644 index 00000000..a5a2d7e1 --- /dev/null +++ b/2001-2500/2294-Partition-Array-Such-That-Maximum-Difference-Is-K/cpp-2294/main.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/partition-array-such-that-maximum-difference-is-k/ +/// Author : liuyubobobo +/// Time : 2022-06-04 + +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + int partitionArray(vector& nums, int k) { + + sort(nums.begin(), nums.end()); + + int res = 0; + for(int start = 0, i = 1; i <= nums.size(); i ++) + if(i == nums.size() || nums[i] - nums[start] > k){ + res ++; + start = i; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2295-Replace-Elements-in-an-Array/cpp-2295/CMakeLists.txt b/2001-2500/2295-Replace-Elements-in-an-Array/cpp-2295/CMakeLists.txt new file mode 100644 index 00000000..830d3093 --- /dev/null +++ b/2001-2500/2295-Replace-Elements-in-an-Array/cpp-2295/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/2001-2500/2295-Replace-Elements-in-an-Array/cpp-2295/main.cpp b/2001-2500/2295-Replace-Elements-in-an-Array/cpp-2295/main.cpp new file mode 100644 index 00000000..5a811886 --- /dev/null +++ b/2001-2500/2295-Replace-Elements-in-an-Array/cpp-2295/main.cpp @@ -0,0 +1,38 @@ +/// Source : https://leetcode.com/problems/replace-elements-in-an-array/ +/// Author : liuyubobobo +/// Time : 2022-06-04 + +#include +#include + +using namespace std; + + +/// Hash Table +/// Time Complexity: O(|op|) +/// Space Complexity: O(max_num) +class Solution { +public: + vector arrayChange(vector& nums, vector>& operations) { + + vector pos(1e6 + 1, -1); + for(int i = 0; i < nums.size(); i ++) + pos[nums[i]] = i; + + for(const vector& op: operations){ + int from_num = op[0], to_num = op[1]; + int from_index = pos[from_num]; + nums[from_index] = to_num; + + pos[from_num] = -1; + pos[to_num] = from_index; + } + return nums; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2296-Design-a-Text-Editor/cpp-2296/CMakeLists.txt b/2001-2500/2296-Design-a-Text-Editor/cpp-2296/CMakeLists.txt new file mode 100644 index 00000000..bb71ae36 --- /dev/null +++ b/2001-2500/2296-Design-a-Text-Editor/cpp-2296/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main2.cpp) diff --git a/2001-2500/2296-Design-a-Text-Editor/cpp-2296/main.cpp b/2001-2500/2296-Design-a-Text-Editor/cpp-2296/main.cpp new file mode 100644 index 00000000..f40cd365 --- /dev/null +++ b/2001-2500/2296-Design-a-Text-Editor/cpp-2296/main.cpp @@ -0,0 +1,131 @@ +/// Source : https://leetcode.com/problems/design-a-text-editor/ +/// Author : liuyubobobo +/// Time : 2022-06-04 + +#include +#include + +using namespace std; + + +/// Using Linked List +/// Time Complexity: init: O(1) +/// add: O(|text|) +/// delete: O(k) +/// move: O(k) +/// Space Complexity: O(all_characters) +template +class Node{ +public: + T value; + Node* next, *prev; + Node(T v, Node* next, Node* prev) : value(v), next(next), prev(prev){} + Node(T v) : Node(v, nullptr, nullptr){} + Node(): Node(T()){} +}; + +template +class LinkedList{ +public: + Node* head, *tail; + + LinkedList(){ + head = new Node(); + tail = new Node(); + head->next = tail; + tail->prev = head; + } + + void add(Node* pre, T v){ + Node* new_node = new Node(v); + add(pre, new_node); + } + + void add_first(T v){ + add(head, v); + } + + void add_last(T v){ + add(tail->prev, v); + } + + void add(Node* pre, Node* new_node){ + new_node->next = pre->next; + pre->next = new_node; + new_node->next->prev = new_node; + new_node->prev = pre; + } + + void add_first(Node* new_node){ + add(head, new_node); + } + + void add_last(Node* new_node){ + add(tail->prev, new_node); + } + + Node* remove(Node* node){ +// assert(!node); + Node* ret = node->prev; + node->prev->next = node->next; + node->next->prev = node->prev; + delete node; + return ret; + } +}; + +class TextEditor { + +private: + LinkedList L; + Node* cur; + +public: + TextEditor() { + cur = L.head; + } + + void addText(string text) { + for(char c: text) + L.add(cur, c), cur = cur->next; + } + + int deleteText(int k) { + + int res = 0; + while(k -- && cur != L.head){ + cur = L.remove(cur); + res ++; + } + return res; + } + + string cursorLeft(int k) { + + while(k -- && cur != L.head) cur = cur->prev; + + string ret = ""; + Node* p = cur; + for(int i = 0; i < 10 && p != L.head; i ++) + ret += p->value, p = p->prev; + reverse(ret.begin(), ret.end()); + return ret; + } + + string cursorRight(int k) { + while(k -- && cur->next != L.tail) cur = cur->next; + + string ret = ""; + Node* p = cur; + for(int i = 0; i < 10 && p != L.head; i ++) + ret += p->value, p = p->prev; + reverse(ret.begin(), ret.end()); + return ret; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2296-Design-a-Text-Editor/cpp-2296/main2.cpp b/2001-2500/2296-Design-a-Text-Editor/cpp-2296/main2.cpp new file mode 100644 index 00000000..d784d00c --- /dev/null +++ b/2001-2500/2296-Design-a-Text-Editor/cpp-2296/main2.cpp @@ -0,0 +1,75 @@ +/// Source : https://leetcode.com/problems/design-a-text-editor/ +/// Author : liuyubobobo +/// Time : 2022-06-04 + +#include +#include + +using namespace std; + + +/// Using C++ list +/// Time Complexity: init: O(1) +/// add: O(|text|) +/// delete: O(k) +/// move: O(k) +/// Space Complexity: O(all_characters) +class TextEditor { + +private: + list L; + list::iterator iter = L.begin(); + +public: + TextEditor() {} + + void addText(string text) { + for(char c: text) + L.insert(iter, c); + } + + int deleteText(int k) { + + int del_len = 0; + while(k -- && iter != L.begin()){ + iter --; + iter = L.erase(iter); + del_len ++; + } + return del_len; + } + + string cursorLeft(int k) { + + while(k -- && iter != L.begin()) iter --; + + auto p = iter; + string ret = ""; + for(int i = 0; i < 10 && p != L.begin(); i ++){ + p --; + ret += *p; + } + reverse(ret.begin(), ret.end()); + return ret; + } + + string cursorRight(int k) { + + while(k -- && iter != L.end()) iter ++; + + auto p = iter; + string ret = ""; + for(int i = 0; i < 10 && p != L.begin(); i ++){ + p --; + ret += *p; + } + reverse(ret.begin(), ret.end()); + return ret; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2297-Jump-Game-IX/cpp-2297/CMakeLists.txt b/2001-2500/2297-Jump-Game-IX/cpp-2297/CMakeLists.txt new file mode 100644 index 00000000..5b098bc9 --- /dev/null +++ b/2001-2500/2297-Jump-Game-IX/cpp-2297/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_2297) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2297 main.cpp) diff --git a/2001-2500/2297-Jump-Game-IX/cpp-2297/main.cpp b/2001-2500/2297-Jump-Game-IX/cpp-2297/main.cpp new file mode 100644 index 00000000..eade4ce4 --- /dev/null +++ b/2001-2500/2297-Jump-Game-IX/cpp-2297/main.cpp @@ -0,0 +1,66 @@ +/// Source : https://leetcode.com/problems/jump-game-ix/ +/// Author : liuyubobobo +/// Time : 2022-06-09 + +#include +#include +#include + +using namespace std; + + +/// Mono Stack + DP +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + long long minCost(vector& nums, vector& costs) { + + int n = nums.size(); + + vector right_larger_or_equal(n, n); + vector stack; + for(int i = n - 1; i >= 0; i --){ + while(!stack.empty() && nums[i] > nums[stack.back()]) stack.pop_back(); + if(!stack.empty()) right_larger_or_equal[i] = stack.back(); + stack.push_back(i); + } +// for(int e: right_larger_or_equal) cout << e << ' '; cout << '\n'; + + vector right_smaller(n, n); + stack.clear(); + for(int i = n - 1; i >= 0; i --){ + while(!stack.empty() && nums[i] <= nums[stack.back()]) stack.pop_back(); + if(!stack.empty()) right_smaller[i] = stack.back(); + stack.push_back(i); + } +// for(int e: right_smaller) cout << e << ' '; cout << '\n'; + + vector dp(n, LONG_LONG_MAX / 2); + dp[0] = 0; + for(int i = 0; i < n; i ++){ + int to = right_larger_or_equal[i]; + if(to < n) + dp[to] = min(dp[to], dp[i] + costs[to]); + + to = right_smaller[i]; + if(to < n) + dp[to] = min(dp[to], dp[i] + costs[to]); + } + return dp.back(); + } +}; + + +int main() { + + vector nums1 = {3, 2, 4, 4, 1}, costs1 = {3, 7, 6, 4, 2}; + cout << Solution().minCost(nums1, costs1) << '\n'; + // 8 + + vector nums2 = {0, 1, 2}, costs2 = {1, 1, 1}; + cout << Solution().minCost(nums2, costs2) << '\n'; + // 2 + + return 0; +} diff --git a/2001-2500/2299-Strong-Password-Checker-II/cpp-2299/CMakeLists.txt b/2001-2500/2299-Strong-Password-Checker-II/cpp-2299/CMakeLists.txt new file mode 100644 index 00000000..fe8bfd9f --- /dev/null +++ b/2001-2500/2299-Strong-Password-Checker-II/cpp-2299/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/2001-2500/2299-Strong-Password-Checker-II/cpp-2299/main.cpp b/2001-2500/2299-Strong-Password-Checker-II/cpp-2299/main.cpp new file mode 100644 index 00000000..dee9e099 --- /dev/null +++ b/2001-2500/2299-Strong-Password-Checker-II/cpp-2299/main.cpp @@ -0,0 +1,48 @@ +/// Source : https://leetcode.com/problems/strong-password-checker-ii/ +/// Author : liuyubobobo +/// Time : 2022-06-11 + +#include +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + bool strongPasswordCheckerII(string password) { + + if(password.size() < 8) return false; + + bool lower_ok = false; + for(char c: password) if(islower(c)) lower_ok = true; + if(!lower_ok) return false; + + bool upper_ok = false; + for(char c: password) if(isupper(c)) upper_ok = true; + if(!upper_ok) return false; + + bool digit_ok = false; + for(char c: password) if(isdigit(c)) digit_ok = true; + if(!digit_ok) return false; + + bool special_ok = false; + string special = "!@#$%^&*()-+"; + for(char c: password) if(special.find(c) != string::npos) special_ok = true; + if(!special_ok) return false; + + for(int i = 1; i < password.size(); i ++) + if(password[i - 1] == password[i]) return false; + return true; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2300-Successful-Pairs-of-Spells-and-Potions/cpp-2300/CMakeLists.txt b/2001-2500/2300-Successful-Pairs-of-Spells-and-Potions/cpp-2300/CMakeLists.txt new file mode 100644 index 00000000..8494c320 --- /dev/null +++ b/2001-2500/2300-Successful-Pairs-of-Spells-and-Potions/cpp-2300/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/2001-2500/2300-Successful-Pairs-of-Spells-and-Potions/cpp-2300/main.cpp b/2001-2500/2300-Successful-Pairs-of-Spells-and-Potions/cpp-2300/main.cpp new file mode 100644 index 00000000..68d51c20 --- /dev/null +++ b/2001-2500/2300-Successful-Pairs-of-Spells-and-Potions/cpp-2300/main.cpp @@ -0,0 +1,44 @@ +/// Source : https://leetcode.com/problems/successful-pairs-of-spells-and-potions/ +/// Author : liuyubobobo +/// Time : 2022-06-11 + +#include +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(nlogm) +/// Space Complexity: O(1) +class Solution { +public: + vector successfulPairs(vector& spells, vector& potions, long long success) { + + vector spells_ll(spells.size()); + for(int i = 0; i < spells.size(); i ++) + spells_ll[i] = spells[i]; + + vector potions_ll(potions.size()); + for(int i = 0; i < potions.size(); i ++) + potions_ll[i] = potions[i]; + sort(potions_ll.begin(), potions_ll.end()); + + vector res(spells.size()); + for(int i = 0; i < spells.size(); i ++){ + long long energy = spells_ll[i]; + long long least_potion = success / energy; + if(least_potion * energy < success) least_potion ++; + + res[i] = potions_ll.end() - lower_bound(potions_ll.begin(), potions_ll.end(), least_potion); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2301-Match-Substring-After-Replacement/cpp-2301/CMakeLists.txt b/2001-2500/2301-Match-Substring-After-Replacement/cpp-2301/CMakeLists.txt new file mode 100644 index 00000000..830d3093 --- /dev/null +++ b/2001-2500/2301-Match-Substring-After-Replacement/cpp-2301/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/2001-2500/2301-Match-Substring-After-Replacement/cpp-2301/main.cpp b/2001-2500/2301-Match-Substring-After-Replacement/cpp-2301/main.cpp new file mode 100644 index 00000000..8ba99bc2 --- /dev/null +++ b/2001-2500/2301-Match-Substring-After-Replacement/cpp-2301/main.cpp @@ -0,0 +1,39 @@ +/// Source : https://leetcode.com/problems/match-substring-after-replacement/ +/// Author : liuyubobobo +/// Time : 2022-06-11 + +#include +#include + +using namespace std; + + +/// Using Map Table +/// Time Complexity: O(n * m) +/// Space Complexity: O(1) +class Solution { +public: + bool matchReplacement(string s, string sub, vector>& mappings) { + + vector> map_table(256, vector(256, false)); + for(const vector& mapping: mappings){ + char old_ch = mapping[0], new_ch = mapping[1]; + map_table[old_ch][new_ch] = true; + } + + for(int i = 0; i + sub.size() <= s.size(); i ++){ + + bool ok = true; + for(int j = 0; j < sub.size() && ok; j ++) + ok = sub[j] == s[i + j] || map_table[sub[j]][s[i + j]]; + if(ok) return true; + } + return false; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2302-Count-Subarrays-With-Score-Less-Than-K/cpp-2302/CMakeLists.txt b/2001-2500/2302-Count-Subarrays-With-Score-Less-Than-K/cpp-2302/CMakeLists.txt new file mode 100644 index 00000000..9a6c5c78 --- /dev/null +++ b/2001-2500/2302-Count-Subarrays-With-Score-Less-Than-K/cpp-2302/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) diff --git a/2001-2500/2302-Count-Subarrays-With-Score-Less-Than-K/cpp-2302/main.cpp b/2001-2500/2302-Count-Subarrays-With-Score-Less-Than-K/cpp-2302/main.cpp new file mode 100644 index 00000000..11396fe6 --- /dev/null +++ b/2001-2500/2302-Count-Subarrays-With-Score-Less-Than-K/cpp-2302/main.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/count-subarrays-with-score-less-than-k/ +/// Author : liuyubobobo +/// Time : 2022-06-11 + +#include +#include + +using namespace std; + + +/// Sliding Window +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + long long countSubarrays(vector& nums, long long k) { + + int l = 0, r = -1, n = nums.size(); + long long cur_sum = 0, res = 0; + while(l < n){ + if(r + 1 < n && 1ll * (cur_sum + nums[r + 1]) * (r + 1 - l + 1) < k){ + r ++; + cur_sum += nums[r]; + } + else{ + if(l <= r){ + res += (r - l + 1); + cur_sum -= nums[l]; + } + l ++; + r = max(r, l - 1); + } + } + return res; + } +}; + + +int main() { + + vector nums1 = {2, 1, 4, 3, 5}; + cout << Solution().countSubarrays(nums1, 10) << '\n'; + // 6 + + vector nums2 = {1, 1, 1}; + cout << Solution().countSubarrays(nums2, 5) << '\n'; + // 5 + + vector nums3 = {2, 1, 4, 3, 5}; + cout << Solution().countSubarrays(nums3, 3) << '\n'; + // 2 + + return 0; +} diff --git a/2001-2500/2303-Calculate-Amount-Paid-in-Taxes/cpp-2303/CMakeLists.txt b/2001-2500/2303-Calculate-Amount-Paid-in-Taxes/cpp-2303/CMakeLists.txt new file mode 100644 index 00000000..fe8bfd9f --- /dev/null +++ b/2001-2500/2303-Calculate-Amount-Paid-in-Taxes/cpp-2303/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/2001-2500/2303-Calculate-Amount-Paid-in-Taxes/cpp-2303/main.cpp b/2001-2500/2303-Calculate-Amount-Paid-in-Taxes/cpp-2303/main.cpp new file mode 100644 index 00000000..ab211112 --- /dev/null +++ b/2001-2500/2303-Calculate-Amount-Paid-in-Taxes/cpp-2303/main.cpp @@ -0,0 +1,41 @@ +/// Source : https://leetcode.com/problems/calculate-amount-paid-in-taxes/ +/// Author : liuyubobobo +/// Time : 2022-06-11 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + double calculateTax(vector>& brackets, int income) { + + if(income <= brackets[0][0]){ + return income * brackets[0][1] / (double)100.0; + } + + int left = income - brackets[0][0]; + double res = brackets[0][0] * brackets[0][1] / (double)100.0; + for(int i = 1; i < brackets.size() && left; i ++){ + int x = brackets[i][0] - brackets[i - 1][0]; + int t = min(x, left); + left -= t; + res += t * brackets[i][1] / (double)100.0; + } + return res; + } +}; + + +int main() { + + vector> br1 = {{3, 50}, {7, 10}, {12, 25}}; + cout << Solution().calculateTax(br1, 10) << '\n'; + + return 0; +} diff --git a/2001-2500/2304-Minimum-Path-Cost-in-a-Grid/cpp-2304/CMakeLists.txt b/2001-2500/2304-Minimum-Path-Cost-in-a-Grid/cpp-2304/CMakeLists.txt new file mode 100644 index 00000000..8494c320 --- /dev/null +++ b/2001-2500/2304-Minimum-Path-Cost-in-a-Grid/cpp-2304/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/2001-2500/2304-Minimum-Path-Cost-in-a-Grid/cpp-2304/main.cpp b/2001-2500/2304-Minimum-Path-Cost-in-a-Grid/cpp-2304/main.cpp new file mode 100644 index 00000000..89862b42 --- /dev/null +++ b/2001-2500/2304-Minimum-Path-Cost-in-a-Grid/cpp-2304/main.cpp @@ -0,0 +1,36 @@ +/// Source : https://leetcode.com/problems/minimum-path-cost-in-a-grid/ +/// Author : liuyubobobo +/// Time : 2022-06-11 + +#include +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(n * m * m) +/// Space Compelxity: O(n * m) +class Solution { +public: + int minPathCost(vector>& grid, vector>& moveCost) { + + int R = grid.size(), C = grid[0].size(); + vector> dp(R, vector(C, INT_MAX)); + for(int j = 0; j < C; j ++) dp[0][j] = grid[0][j]; + + for(int i = 0; i + 1 < R; i ++) + for(int j = 0; j < C; j ++){ + for(int k = 0; k < C; k ++) + dp[i + 1][k] = min(dp[i + 1][k], dp[i][j] + moveCost[grid[i][j]][k] + grid[i + 1][k]); + } + return *min_element(dp[R - 1].begin(), dp[R - 1].end()); + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2305-Fair-Distribution-of-Cookies/cpp-2305/CMakeLists.txt b/2001-2500/2305-Fair-Distribution-of-Cookies/cpp-2305/CMakeLists.txt new file mode 100644 index 00000000..830d3093 --- /dev/null +++ b/2001-2500/2305-Fair-Distribution-of-Cookies/cpp-2305/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/2001-2500/2305-Fair-Distribution-of-Cookies/cpp-2305/main.cpp b/2001-2500/2305-Fair-Distribution-of-Cookies/cpp-2305/main.cpp new file mode 100644 index 00000000..3860c524 --- /dev/null +++ b/2001-2500/2305-Fair-Distribution-of-Cookies/cpp-2305/main.cpp @@ -0,0 +1,48 @@ +/// Source : https://leetcode.com/problems/fair-distribution-of-cookies/ +/// Author : liuyubobobo +/// Time : 2022-06-11 + +#include +#include + +using namespace std; + + +/// Memoization +/// Time Complexity: O(k * 3^n) +/// Space Complexity: O(k * 2^n) +class Solution { +public: + int distributeCookies(vector& cookies, int k) { + + int n = cookies.size(); + + vector table(1 << n, 0); + for(int state = 1; state < (1 << n); state ++){ + int p = __builtin_ffs(state) - 1; + table[state] = table[state - (1 << p)] + cookies[p]; + } + + vector> dp(k + 1, vector(1 << n, -1)); + return dfs((1 << n) - 1, k, table, dp); + } + +private: + int dfs(int state, int k, const vector& table, vector>& dp){ + + if(k == 1) return table[state]; + if(dp[k][state] != -1) return dp[k][state]; + + int res = table[state]; + for (int s = state; s; s = (s - 1) & state) { + res = min(res, max(table[s], dfs(state - s, k - 1, table, dp))); + } + return dp[k][state] = res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2306-Naming-a-Company/cpp-2306/CMakeLists.txt b/2001-2500/2306-Naming-a-Company/cpp-2306/CMakeLists.txt new file mode 100644 index 00000000..9a6c5c78 --- /dev/null +++ b/2001-2500/2306-Naming-a-Company/cpp-2306/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) diff --git a/2001-2500/2306-Naming-a-Company/cpp-2306/main.cpp b/2001-2500/2306-Naming-a-Company/cpp-2306/main.cpp new file mode 100644 index 00000000..ae3f2f5f --- /dev/null +++ b/2001-2500/2306-Naming-a-Company/cpp-2306/main.cpp @@ -0,0 +1,61 @@ +/// Source : https://leetcode.com/problems/naming-a-company/ +/// Author : liuyubobobo +/// Time : 2022-06-11 + +#include +#include +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + long long distinctNames(vector& ideas) { + + int n = ideas.size(); + + unordered_set ideas_set(ideas.begin(), ideas.end()); + + vector> can_change(26, vector(n, false)); + vector> ok(26, vector(26, 0)); + for(int i = 0; i < n; i ++){ + char o_first = ideas[i][0]; + for(char c = 'a'; c <= 'z'; c ++){ + ideas[i][0] = c; + if(c != o_first && !ideas_set.count(ideas[i])){ + can_change[c - 'a'][i] = true; + ok[o_first - 'a'][c - 'a'] ++; + } + + } + ideas[i][0] = o_first; + } + + long long res = 0; + for(int i = 0; i < n; i ++){ + char o_first = ideas[i][0]; + for(char c = 'a'; c <= 'z'; c ++) + if(can_change[c - 'a'][i]) res += ok[c - 'a'][o_first - 'a']; + } + return res; + } +}; + + +int main() { + + vector ideas1 = {"coffee","donuts","time","toffee"}; + cout << Solution().distinctNames(ideas1) << '\n'; + // 6 + + vector ideas2 = {"lack","back"}; + cout << Solution().distinctNames(ideas2) << '\n'; + // 0 + + return 0; +} diff --git a/2001-2500/2309-Greatest-English-Letter-in-Upper-and-Lower-Case/cpp-2309/CMakeLists.txt b/2001-2500/2309-Greatest-English-Letter-in-Upper-and-Lower-Case/cpp-2309/CMakeLists.txt new file mode 100644 index 00000000..fe8bfd9f --- /dev/null +++ b/2001-2500/2309-Greatest-English-Letter-in-Upper-and-Lower-Case/cpp-2309/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/2001-2500/2309-Greatest-English-Letter-in-Upper-and-Lower-Case/cpp-2309/main.cpp b/2001-2500/2309-Greatest-English-Letter-in-Upper-and-Lower-Case/cpp-2309/main.cpp new file mode 100644 index 00000000..73cfd5ad --- /dev/null +++ b/2001-2500/2309-Greatest-English-Letter-in-Upper-and-Lower-Case/cpp-2309/main.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/greatest-english-letter-in-upper-and-lower-case/ +/// Author : liuyubobobo +/// Time : 2022-06-18 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + string greatestLetter(string s) { + + vector upper(26, false), lower(26, false); + for(char c: s){ + if(isupper(c)) upper[c - 'A'] = true; + else lower[c - 'a'] = true; + } + + int res = -1; + for(int i = 0; i < 26; i ++) + if(upper[i] && lower[i]) res = i; + return res == -1 ? "" : string(1, 'A' + res); + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2310-Sum-of-Numbers-With-Units-Digit-K/cpp-2310/CMakeLists.txt b/2001-2500/2310-Sum-of-Numbers-With-Units-Digit-K/cpp-2310/CMakeLists.txt new file mode 100644 index 00000000..8494c320 --- /dev/null +++ b/2001-2500/2310-Sum-of-Numbers-With-Units-Digit-K/cpp-2310/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/2001-2500/2310-Sum-of-Numbers-With-Units-Digit-K/cpp-2310/main.cpp b/2001-2500/2310-Sum-of-Numbers-With-Units-Digit-K/cpp-2310/main.cpp new file mode 100644 index 00000000..a7f269ed --- /dev/null +++ b/2001-2500/2310-Sum-of-Numbers-With-Units-Digit-K/cpp-2310/main.cpp @@ -0,0 +1,42 @@ +/// Source : https://leetcode.com/problems/sum-of-numbers-with-units-digit-k/ +/// Author : liuyubobobo +/// Time : 2022-06-18 + +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(1) +/// Space Complexity: O(1) +class Solution { +public: + int minimumNumbers(int num, int k) { + + if(num == 0) return 0; + + int cnt = 1; + for(cnt = 1; cnt <= 10; cnt ++) + if((cnt * k) % 10 == num % 10) + break; + + if(cnt == 11 ||cnt * k > num) return -1; + return cnt; + } +}; + + +int main() { + + cout << Solution().minimumNumbers(58, 9) << '\n'; + // 2 + + cout << Solution().minimumNumbers(37, 2) << '\n'; + // -1 + + cout << Solution().minimumNumbers(0, 7) << '\n'; + // 0 + + return 0; +} diff --git a/2001-2500/2312-Selling-Pieces-of-Wood/cpp-2312/CMakeLists.txt b/2001-2500/2312-Selling-Pieces-of-Wood/cpp-2312/CMakeLists.txt new file mode 100644 index 00000000..bb71ae36 --- /dev/null +++ b/2001-2500/2312-Selling-Pieces-of-Wood/cpp-2312/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main2.cpp) diff --git a/2001-2500/2312-Selling-Pieces-of-Wood/cpp-2312/main.cpp b/2001-2500/2312-Selling-Pieces-of-Wood/cpp-2312/main.cpp new file mode 100644 index 00000000..90682161 --- /dev/null +++ b/2001-2500/2312-Selling-Pieces-of-Wood/cpp-2312/main.cpp @@ -0,0 +1,108 @@ +/// Source : https://leetcode.com/problems/selling-pieces-of-wood/ +/// Author : liuyubobobo +/// Time : 2022-06-18 + +#include +#include +#include + +using namespace std; + + +/// DP - Knapback +/// Time Complexity: O(m * n * n + n * m * m + m * n * (m + n)) +/// Space Complexity: O(m * n) +class Solution { +public: + long long sellingWood(int m, int n, vector>& prices) { + + // 0 - any, 1 - h is fixed, 2 - w is fixed + vector>> dp(3, vector>(m + 1, vector(n + 1, -1))); + + map> H, W; + for(const vector& price: prices){ + int h = price[0], w = price[1], v = price[2]; + H[h][w] = max(H[h][w], (long long)v); + W[w][h] = max(W[w][h], (long long)v); + } + + vector h_choices; + vector> Hdp(m + 1, vector(n + 1, 0)); + for(const pair>& p: H){ + int h = p.first; + h_choices.push_back(h); + const map& items = p.second; + + for(int W = 1; W <= n; W ++){ + for(const pair& item: items){ + int weight = item.first; + long long value = item.second; + + if(W >= weight) + Hdp[h][W] = max(Hdp[h][W], Hdp[h][W - weight] + value); + } + } + } + + vector w_choices; + vector> Wdp(n + 1, vector(m + 1, 0)); + for(const pair>& p: W){ + int w = p.first; + w_choices.push_back(w); + const map& items = p.second; + + for(int W = 1; W <= m; W ++) { + for (const pair &item: items) { + int weight = item.first; + long long value = item.second; + + if(W >= weight) + Wdp[w][W] = max(Wdp[w][W], Wdp[w][W - weight] + value); + } + } + } + + return dfs(0, m, n, h_choices, w_choices, Hdp, Wdp, dp); + } + +private: + long long dfs(int state, int m, int n, const vector& h_choices, const vector& w_choices, + const vector>& Hdp, const vector>& Wdp, + vector>>& dp){ + + if(m <= 0 || n <= 0) return 0; + if(dp[state][m][n] != -1) return dp[state][m][n]; + + if(state == 1) return dp[state][m][n] = Hdp[m][n]; + if(state == 2) return dp[state][m][n] = Wdp[n][m]; + + long long res = 0; + for(int h_option: h_choices){ + if(h_option > m) break; + res = max(res, dfs(1, h_option, n, h_choices, w_choices, Hdp, Wdp, dp) + dfs(0, m - h_option, n, h_choices, w_choices, Hdp, Wdp, dp)); + } + for(int w_option: w_choices){ + if(w_option > n) break; + res = max(res, dfs(2, m, w_option, h_choices, w_choices, Hdp, Wdp, dp) + dfs(0, m, n - w_option, h_choices, w_choices, Hdp, Wdp, dp)); + } + return dp[state][m][n] = res; + } +}; + + +int main() { + + vector> prices1 = {{1, 4, 2}, {2, 2, 7}, {2, 1, 3}}; + cout << Solution().sellingWood(3, 5, prices1) << '\n'; + // 19 + + vector> prices2 = {{3, 2, 10}, {1, 4, 2}, {4, 1, 3}}; + cout << Solution().sellingWood(4, 6, prices2) << '\n'; + // 32 + + vector> prices3 = {{4, 1, 18}, {4, 2, 5}, {1, 1, 20}, {3, 1, 21}}; + cout << Solution().sellingWood(4, 2, prices3) << '\n'; + // 160 + + return 0; +} diff --git a/2001-2500/2312-Selling-Pieces-of-Wood/cpp-2312/main2.cpp b/2001-2500/2312-Selling-Pieces-of-Wood/cpp-2312/main2.cpp new file mode 100644 index 00000000..6fffab9d --- /dev/null +++ b/2001-2500/2312-Selling-Pieces-of-Wood/cpp-2312/main2.cpp @@ -0,0 +1,62 @@ +/// Source : https://leetcode.com/problems/selling-pieces-of-wood/ +/// Author : liuyubobobo +/// Time : 2022-06-21 + +#include +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(m * n * (m + n)) +/// Space Complexity: O(m * n) +class Solution { +public: + long long sellingWood(int m, int n, vector>& prices) { + + vector> dp(m + 1, vector(n + 1, 0)); + vector> visited(m + 1, vector(n + 1, false)); + + for(const vector& price: prices){ + int h = price[0], w = price[1], p = price[2]; + dp[h][w] = max(dp[h][w], 1ll * p); + } + + return dfs(m, n, dp, visited); + } + +private: + long long dfs(int m, int n, vector>& dp, vector>& visited){ + + if(visited[m][n]) return dp[m][n]; + + long long res = dp[m][n]; + for(int top = 1; top <= m - 1; top ++) + res = max(res, dfs(top, n, dp, visited) + dfs(m - top, n, dp, visited)); + for(int left = 1; left <= n - 1; left ++) + res = max(res, dfs(m, left, dp, visited) + dfs(m, n - left, dp, visited)); + + visited[m][n] = true; + return dp[m][n] = res; + } +}; + + +int main() { + + vector> prices1 = {{1, 4, 2}, {2, 2, 7}, {2, 1, 3}}; + cout << Solution().sellingWood(3, 5, prices1) << '\n'; + // 19 + + vector> prices2 = {{3, 2, 10}, {1, 4, 2}, {4, 1, 3}}; + cout << Solution().sellingWood(4, 6, prices2) << '\n'; + // 32 + + vector> prices3 = {{4, 1, 18}, {4, 2, 5}, {1, 1, 20}, {3, 1, 21}}; + cout << Solution().sellingWood(4, 2, prices3) << '\n'; + // 160 + + return 0; +} diff --git a/2001-2500/2313-Minimum-Flips-in-Binary-Tree-to-Get-Result/cpp-2313/CMakeLists.txt b/2001-2500/2313-Minimum-Flips-in-Binary-Tree-to-Get-Result/cpp-2313/CMakeLists.txt new file mode 100644 index 00000000..e3bbbc38 --- /dev/null +++ b/2001-2500/2313-Minimum-Flips-in-Binary-Tree-to-Get-Result/cpp-2313/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_2313) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2313 main.cpp) diff --git a/2001-2500/2313-Minimum-Flips-in-Binary-Tree-to-Get-Result/cpp-2313/main.cpp b/2001-2500/2313-Minimum-Flips-in-Binary-Tree-to-Get-Result/cpp-2313/main.cpp new file mode 100644 index 00000000..b01d57b1 --- /dev/null +++ b/2001-2500/2313-Minimum-Flips-in-Binary-Tree-to-Get-Result/cpp-2313/main.cpp @@ -0,0 +1,72 @@ +/// Source : https://leetcode.com/problems/minimum-flips-in-binary-tree-to-get-result/ +/// Author : liuyubobobo +/// Time : 2022-06-22 + +#include +#include +#include +#include + +using namespace std; + + +/// Tree DP +/// Time Complexity: O(n) +/// Space Complexity: O(n) +/// 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: + int minimumFlips(TreeNode* root, bool result) { + + vector> dp(2); + return dfs(root, result, dp); + } + +private: + int dfs(TreeNode* node, bool result, vector>& dp){ + + if(node->left == nullptr && node->right == nullptr) + return result != node->val; + + auto iter = dp[result].find(node); + if(iter != dp[result].end()) return iter->second; + + if(node->val == 5){ + TreeNode* child = node->left ? node->left : node->right; + return dp[result][node] = dfs(child, !result, dp); + } + + TreeNode* node1 = node->left, *node2 = node->right; + int res = INT_MAX; + for(int res1 = 0; res1 <= 1; res1 ++) + for(int res2 = 0; res2 <= 1; res2 ++) + if(calc(res1, res2, node->val) == result) + res = min(res, dfs(node1, res1, dp) + dfs(node2, res2, dp)); + return dp[result][node] = res; + } + + int calc(int a, int b, int op){ + switch(op){ + case 2: return a | b; + case 3: return a & b; + case 4: return a ^ b; + default: assert(false); + } + return -1; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2315-Count-Asterisks/cpp-2315/CMakeLists.txt b/2001-2500/2315-Count-Asterisks/cpp-2315/CMakeLists.txt new file mode 100644 index 00000000..e4397848 --- /dev/null +++ b/2001-2500/2315-Count-Asterisks/cpp-2315/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_2315) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2315 main.cpp) diff --git a/2001-2500/2315-Count-Asterisks/cpp-2315/main.cpp b/2001-2500/2315-Count-Asterisks/cpp-2315/main.cpp new file mode 100644 index 00000000..8484600c --- /dev/null +++ b/2001-2500/2315-Count-Asterisks/cpp-2315/main.cpp @@ -0,0 +1,31 @@ +/// Source : https://leetcode.com/problems/count-asterisks/ +/// Author : liuyubobobo +/// Time : 2022-06-25 + +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int countAsterisks(string s) { + + bool out = true; + int res = 0; + for(char c: s){ + if(c == '|') out = !out; + else if(c == '*') res += out; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2316-Count-Unreachable-Pairs-of-Nodes-in-an-Undirected-Graph/cpp-2316/CMakeLists.txt b/2001-2500/2316-Count-Unreachable-Pairs-of-Nodes-in-an-Undirected-Graph/cpp-2316/CMakeLists.txt new file mode 100644 index 00000000..6fbd5c81 --- /dev/null +++ b/2001-2500/2316-Count-Unreachable-Pairs-of-Nodes-in-an-Undirected-Graph/cpp-2316/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_2316) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2316 main.cpp) diff --git a/2001-2500/2316-Count-Unreachable-Pairs-of-Nodes-in-an-Undirected-Graph/cpp-2316/main.cpp b/2001-2500/2316-Count-Unreachable-Pairs-of-Nodes-in-an-Undirected-Graph/cpp-2316/main.cpp new file mode 100644 index 00000000..db05639b --- /dev/null +++ b/2001-2500/2316-Count-Unreachable-Pairs-of-Nodes-in-an-Undirected-Graph/cpp-2316/main.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/count-unreachable-pairs-of-nodes-in-an-undirected-graph/ +/// Author : liuyubobobo +/// Time : 2022-06-25 + +#include +#include + +using namespace std; + + +/// CC +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + long long countPairs(int n, vector>& edges) { + + vector> g(n); + for(const vector& e: edges){ + int u = e[0], v = e[1]; + g[u].push_back(v), g[v].push_back(u); + } + + vector visited(n, false); + vector cc_sz; + for(int i = 0; i < n; i ++) + if(!visited[i]){ + cc_sz.push_back(dfs(g, i, visited)); + } + + long long res = 0; + for(long long sz: cc_sz) + res += sz * (n - sz); + return res / 2; + } + +private: + int dfs(const vector>& g, int u, vector& visited){ + + visited[u] = true; + int res = 1; + for(int v: g[u]){ + if(visited[v]) continue; + res += dfs(g, v, visited); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2317-Maximum-XOR-After-Operations/cpp-2317/CMakeLists.txt b/2001-2500/2317-Maximum-XOR-After-Operations/cpp-2317/CMakeLists.txt new file mode 100644 index 00000000..8d418277 --- /dev/null +++ b/2001-2500/2317-Maximum-XOR-After-Operations/cpp-2317/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_2317) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2317 main.cpp) diff --git a/2001-2500/2317-Maximum-XOR-After-Operations/cpp-2317/main.cpp b/2001-2500/2317-Maximum-XOR-After-Operations/cpp-2317/main.cpp new file mode 100644 index 00000000..24fb26f1 --- /dev/null +++ b/2001-2500/2317-Maximum-XOR-After-Operations/cpp-2317/main.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/maximum-xor-after-operations/ +/// Author : liuyubobobo +/// Time : 2022-06-25 + +#include +#include + +using namespace std; + + +/// bitwise +/// Time Compelxity: O(nlogA) +/// Space Complexity: O(1) +class Solution { +public: + int maximumXOR(vector& nums) { + + int n = nums.size(); + + vector f(31, 0); + for(int num: nums){ + for(int p = 30; p >= 0; p --) + f[p] += ((num >> p) & 1); + } + + int res = 0; + for(int p = 30; p >= 0; p --) + if(f[p]) res += (1 << p); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2318-Number-of-Distinct-Roll-Sequences/cpp-2318/CMakeLists.txt b/2001-2500/2318-Number-of-Distinct-Roll-Sequences/cpp-2318/CMakeLists.txt new file mode 100644 index 00000000..51c1cd8d --- /dev/null +++ b/2001-2500/2318-Number-of-Distinct-Roll-Sequences/cpp-2318/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_2318) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2318 main.cpp) diff --git a/2001-2500/2318-Number-of-Distinct-Roll-Sequences/cpp-2318/main.cpp b/2001-2500/2318-Number-of-Distinct-Roll-Sequences/cpp-2318/main.cpp new file mode 100644 index 00000000..c30e3354 --- /dev/null +++ b/2001-2500/2318-Number-of-Distinct-Roll-Sequences/cpp-2318/main.cpp @@ -0,0 +1,67 @@ +/// Source : https://leetcode.com/problems/number-of-distinct-roll-sequences/ +/// Author : liuyubobobo +/// Time : 2022-06-25 + +#include +#include +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +private: + const long long MOD = 1e9 + 7; + +public: + int distinctSequences(int n) { + + if(n == 1) return 6; + + vector>> dp(7, vector>(7, vector(n, 0))); + for(int cur = 1; cur <= 6; cur ++) dp[0][cur][0] = 1; + + for(int cur = 1; cur <= 6; cur ++) + for(int pre = 1; pre <= 6; pre ++) + if(gcd(pre, cur) == 1 && cur != pre) dp[pre][cur][1] += dp[0][pre][0]; + + for(int i = 2; i < n; i ++){ + for(int cur = 1; cur <= 6; cur ++){ + for(int p1 = 1; p1 <= 6; p1 ++) + for(int p2 = 1; p2 <= 6; p2 ++){ + if(gcd(p2, cur) == 1 && cur != p2 && cur != p1) + dp[p2][cur][i] += dp[p1][p2][i - 1]; + dp[p2][cur][i] %= MOD; + } + } + } + + long long res = 0; + for(int p = 1; p <= 6; p ++) + for(int cur = 1; cur <= 6; cur ++) + res += dp[p][cur][n - 1]; + return res % MOD; + } + +private: + int gcd(int a, int b){ + if(a > b) swap(a, b); + if (a == 0) return b; + return gcd(b % a, a); + } +}; + + +int main() { + + cout << Solution().distinctSequences(2) << '\n'; + + cout << Solution().distinctSequences(4) << '\n'; + + return 0; +} diff --git a/2001-2500/2319-Check-if-Matrix-Is-X-Matrix/cpp-2319/CMakeLists.txt b/2001-2500/2319-Check-if-Matrix-Is-X-Matrix/cpp-2319/CMakeLists.txt new file mode 100644 index 00000000..fe8bfd9f --- /dev/null +++ b/2001-2500/2319-Check-if-Matrix-Is-X-Matrix/cpp-2319/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/2001-2500/2319-Check-if-Matrix-Is-X-Matrix/cpp-2319/main.cpp b/2001-2500/2319-Check-if-Matrix-Is-X-Matrix/cpp-2319/main.cpp new file mode 100644 index 00000000..ce65fb70 --- /dev/null +++ b/2001-2500/2319-Check-if-Matrix-Is-X-Matrix/cpp-2319/main.cpp @@ -0,0 +1,38 @@ +/// Source : https://leetcode.com/problems/check-if-matrix-is-x-matrix/ +/// Author : liuyubobobo +/// Time : 2022-06-25 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n^2) +/// Space Complexity: O(1) +class Solution { +public: + bool checkXMatrix(vector>& grid) { + + int n = grid.size(); + + for(int i = 0; i < n; i ++) + for(int j = 0; j < n; j ++){ + if(is_dia(i, j, n) && grid[i][j] == 0) return false; + if(!is_dia(i, j, n) && grid[i][j] != 0) return false; + } + return true; + } + +private: + bool is_dia(int i, int j, int n){ + return i == j || i + j == n - 1; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2320-Count-Number-of-Ways-to-Place-Houses/cpp-2320/CMakeLists.txt b/2001-2500/2320-Count-Number-of-Ways-to-Place-Houses/cpp-2320/CMakeLists.txt new file mode 100644 index 00000000..6c7077c9 --- /dev/null +++ b/2001-2500/2320-Count-Number-of-Ways-to-Place-Houses/cpp-2320/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main2.cpp) diff --git a/2001-2500/2320-Count-Number-of-Ways-to-Place-Houses/cpp-2320/main.cpp b/2001-2500/2320-Count-Number-of-Ways-to-Place-Houses/cpp-2320/main.cpp new file mode 100644 index 00000000..da855466 --- /dev/null +++ b/2001-2500/2320-Count-Number-of-Ways-to-Place-Houses/cpp-2320/main.cpp @@ -0,0 +1,45 @@ +/// Source : https://leetcode.com/problems/count-number-of-ways-to-place-houses/ +/// Author : liuyubobobo +/// Time : 2022-06-25 + +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +private: + const long long MOD = 1e9 + 7; + +public: + int countHousePlacements(int n) { + + vector> dp(4, vector(n, 0)); + dp[0][0] = dp[1][0] = dp[2][0] = dp[3][0] = 1; + for(int i = 1; i < n; i ++){ + for(int cur_state = 0; cur_state < 4; cur_state ++){ + int cur1 = cur_state / 2, cur2 = cur_state % 2; + for(int pre_state = 0; pre_state < 4; pre_state ++){ + int pre1 = pre_state / 2, pre2 = pre_state % 2; + if((cur1 && pre1) || (cur2 && pre2)) continue; + dp[cur_state][i] += dp[pre_state][i - 1]; + } + dp[cur_state][i] %= MOD; + } + } + + long long res = 0; + for(int state = 0; state < 4; state ++) res += dp[state][n - 1]; + return res % MOD; + } +}; + +int main() { + + return 0; +} diff --git a/2001-2500/2320-Count-Number-of-Ways-to-Place-Houses/cpp-2320/main2.cpp b/2001-2500/2320-Count-Number-of-Ways-to-Place-Houses/cpp-2320/main2.cpp new file mode 100644 index 00000000..4a02ccb0 --- /dev/null +++ b/2001-2500/2320-Count-Number-of-Ways-to-Place-Houses/cpp-2320/main2.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/count-number-of-ways-to-place-houses/ +/// Author : liuyubobobo +/// Time : 2022-06-27 + +#include +#include + +using namespace std; + + +/// DP, just consider one line is enough +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +private: + const long long MOD = 1e9 + 7; + +public: + int countHousePlacements(int n) { + + vector> dp(2, vector(n, 1)); + for(int i = 1; i < n; i ++){ + dp[0][i] = (dp[0][i - 1] + dp[1][i - 1]) % MOD; + dp[1][i] = dp[0][i - 1]; + } + + long long res = (dp[0][n - 1] + dp[1][n - 1]) % MOD; + return res * res % MOD; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2321-Maximum-Score-Of-Spliced-Array/cpp-2321/CMakeLists.txt b/2001-2500/2321-Maximum-Score-Of-Spliced-Array/cpp-2321/CMakeLists.txt new file mode 100644 index 00000000..830d3093 --- /dev/null +++ b/2001-2500/2321-Maximum-Score-Of-Spliced-Array/cpp-2321/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/2001-2500/2321-Maximum-Score-Of-Spliced-Array/cpp-2321/main.cpp b/2001-2500/2321-Maximum-Score-Of-Spliced-Array/cpp-2321/main.cpp new file mode 100644 index 00000000..f950bbe5 --- /dev/null +++ b/2001-2500/2321-Maximum-Score-Of-Spliced-Array/cpp-2321/main.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/maximum-score-of-spliced-array/ +/// Author : liuyubobobo +/// Time : 2022-06-25 + +#include +#include + +using namespace std; + + +/// Math +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int maximumsSplicedArray(vector& nums1, vector& nums2) { + + int n = nums1.size(); + + vector presum1(n + 1, 0), presum2(n + 1, 0); + for(int i = 0; i < n; i ++){ + presum1[i + 1] = presum1[i] + nums1[i]; + presum2[i + 1] = presum2[i] + nums2[i]; + } + + vector presum12(n + 1, 0), presum21(n + 1, 0); + for(int i = 0; i <= n; i ++){ + presum12[i] = presum1[i] - presum2[i]; + presum21[i] = presum2[i] - presum1[i]; + } + + int max12 = 0, max21 = 0, res = max(presum1.back(), presum2.back()); + for(int i = 0; i < n; i ++){ + res = max(res, presum1.back() + presum21[i + 1] + max12); + res = max(res, presum2.back() + presum12[i + 1] + max21); + max12 = max(max12, presum12[i + 1]); + max21 = max(max21, presum21[i + 1]); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2322-Minimum-Score-After-Removals-on-a-Tree/cpp-2322/CMakeLists.txt b/2001-2500/2322-Minimum-Score-After-Removals-on-a-Tree/cpp-2322/CMakeLists.txt new file mode 100644 index 00000000..9a6c5c78 --- /dev/null +++ b/2001-2500/2322-Minimum-Score-After-Removals-on-a-Tree/cpp-2322/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) diff --git a/2001-2500/2322-Minimum-Score-After-Removals-on-a-Tree/cpp-2322/main.cpp b/2001-2500/2322-Minimum-Score-After-Removals-on-a-Tree/cpp-2322/main.cpp new file mode 100644 index 00000000..dd4c5686 --- /dev/null +++ b/2001-2500/2322-Minimum-Score-After-Removals-on-a-Tree/cpp-2322/main.cpp @@ -0,0 +1,110 @@ +/// Source : https://leetcode.com/problems/minimum-score-after-removals-on-a-tree/ +/// Author : liuyubobobo +/// Time : 2022-06-25 + +#include +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n^2) +/// Space Complexity: O(n^2) +class Solution { +public: + int minimumScore(vector& nums, vector>& edges) { + + int n = nums.size(); + vector> tree(n); + for(const vector& e: edges){ + int u = e[0], v = e[1]; + tree[u].push_back(v), tree[v].push_back(u); + } + + vector> is_ancestor(n, vector(n, false)); + vector path; + dfs_ancestor(tree, 0, -1, path, is_ancestor); + + vector xor_subtree(n, 0); + dfs_xor_subtree(tree, 0, -1, nums, xor_subtree); + + int res = INT_MAX; + for(int i = 0; i < edges.size(); i ++){ + for(int j = i + 1; j < edges.size(); j ++){ + + int u1 = edges[i][0], v1 = edges[i][1]; + int root1 = (is_ancestor[u1][v1] ? v1 : u1); + + int xor1 = (xor_subtree[0] ^ xor_subtree[root1]); + int xor2 = xor_subtree[root1]; + int xor3 = 0; + + int u2 = edges[j][0], v2 = edges[j][1]; + int root2 = is_ancestor[u2][v2] ? v2 : u2; + + if(is_ancestor[root1][root2]){ + xor3 = xor_subtree[root2]; + xor2 ^= xor3; + } + else if(is_ancestor[root2][root1]){ + xor1 = (xor_subtree[0] ^ xor_subtree[root2]); + xor3 = xor_subtree[root2] ^ xor2; + } + else{ + assert(is_ancestor[0][root2]); + xor3 = xor_subtree[root2]; + xor1 ^= xor3; + } + + res = min(res, max3(xor1, xor2, xor3) - min3(xor1, xor2, xor3)); + } + } + return res; + } + +private: + int max3(int a, int b, int c){ + return max(a, max(b, c)); + } + + int min3(int a, int b, int c){ + return min(a, min(b, c)); + } + + void dfs_xor_subtree(const vector>& tree, int u, int p, + const vector& nums, vector& xor_subtree){ + + xor_subtree[u] ^= nums[u]; + for(int v: tree[u]){ + if(v == p) continue; + dfs_xor_subtree(tree, v, u, nums, xor_subtree); + xor_subtree[u] ^= xor_subtree[v]; + } + } + + void dfs_ancestor(const vector>& tree, int u, int p, + vector& path, vector>& is_ancestor){ + + for(int x: path) + is_ancestor[x][u] = true; + + path.push_back(u); + for(int v: tree[u]){ + if(v == p) continue; + dfs_ancestor(tree, v, u, path, is_ancestor); + } + path.pop_back(); + } +}; + + +int main() { + + vector nums2 = {5, 5, 2, 4, 4, 2}; + vector> edges2 = {{0, 1}, {1, 2}, {5, 2}, {4, 3}, {1, 3}}; + cout << Solution().minimumScore(nums2, edges2) << '\n'; + + return 0; +} diff --git a/2001-2500/2323-Find-Minimum-Time-to-Finish-All-Jobs-II/cpp-2323/CMakeLists.txt b/2001-2500/2323-Find-Minimum-Time-to-Finish-All-Jobs-II/cpp-2323/CMakeLists.txt new file mode 100644 index 00000000..0caaac65 --- /dev/null +++ b/2001-2500/2323-Find-Minimum-Time-to-Finish-All-Jobs-II/cpp-2323/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_2323) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2323 main2.cpp) diff --git a/2001-2500/2323-Find-Minimum-Time-to-Finish-All-Jobs-II/cpp-2323/main.cpp b/2001-2500/2323-Find-Minimum-Time-to-Finish-All-Jobs-II/cpp-2323/main.cpp new file mode 100644 index 00000000..2fc7d43f --- /dev/null +++ b/2001-2500/2323-Find-Minimum-Time-to-Finish-All-Jobs-II/cpp-2323/main.cpp @@ -0,0 +1,48 @@ +/// Source : https://leetcode.com/problems/find-minimum-time-to-finish-all-jobs-ii/ +/// Author : liuyubobobo +/// Time : 2022-06-30 + +#include +#include +#include + +using namespace std; + + +/// Binary Search + Greedy +/// Time Complexity: O(nlogn + nlog(max_jobs)) +/// Space Complexity: O(1) +class Solution { +public: + int minimumTime(vector& jobs, vector& workers) { + + sort(jobs.begin(), jobs.end()); + sort(workers.begin(), workers.end()); + + int l = 1, r = 1e5; + while(l < r){ + int mid = (l + r) / 2; + if(ok(jobs, workers, mid)) r = mid; + else l = mid + 1; + } + return l; + } + +private: + bool ok(const vector& jobs, const vector& workers, int d){ + + for(int i = 0; i < workers.size(); i ++) + if(1ll * workers[i] * d < 1ll * jobs[i]) return false; + return true; + } +}; + + +int main() { + + vector jobs1 = {5, 2, 4}, workers1 = {1, 7, 5}; + cout << Solution().minimumTime(jobs1, workers1) << '\n'; + // 2 + + return 0; +} diff --git a/2001-2500/2323-Find-Minimum-Time-to-Finish-All-Jobs-II/cpp-2323/main2.cpp b/2001-2500/2323-Find-Minimum-Time-to-Finish-All-Jobs-II/cpp-2323/main2.cpp new file mode 100644 index 00000000..67553178 --- /dev/null +++ b/2001-2500/2323-Find-Minimum-Time-to-Finish-All-Jobs-II/cpp-2323/main2.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/find-minimum-time-to-finish-all-jobs-ii/ +/// Author : liuyubobobo +/// Time : 2022-07-01 + +#include +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + int minimumTime(vector& jobs, vector& workers) { + + sort(jobs.begin(), jobs.end()); + sort(workers.begin(), workers.end()); + + int res = 0; + for(int i = 0; i < jobs.size(); i ++) + res = max(res, jobs[i] / workers[i] + !!(jobs[i] % workers[i])); + return res; + } +}; + + +int main() { + + vector jobs1 = {5, 2, 4}, workers1 = {1, 7, 5}; + cout << Solution().minimumTime(jobs1, workers1) << '\n'; + // 2 + + return 0; +} diff --git a/2001-2500/2325-Decode-the-Message/cpp-2325/CMakeLists.txt b/2001-2500/2325-Decode-the-Message/cpp-2325/CMakeLists.txt new file mode 100644 index 00000000..fe8bfd9f --- /dev/null +++ b/2001-2500/2325-Decode-the-Message/cpp-2325/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/2001-2500/2325-Decode-the-Message/cpp-2325/main.cpp b/2001-2500/2325-Decode-the-Message/cpp-2325/main.cpp new file mode 100644 index 00000000..3c09525b --- /dev/null +++ b/2001-2500/2325-Decode-the-Message/cpp-2325/main.cpp @@ -0,0 +1,39 @@ +/// Source : https://leetcode.com/problems/decode-the-message/ +/// Author : liuyubobobo +/// Time : 2022-07-02 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(|key| + |message|) +/// Space Complexity: O(1) +class Solution { +public: + string decodeMessage(string key, string message) { + + vector used(26, false); + vector table(26); + char ch = 'a'; + for(char c: key){ + if(c == ' ' || used[c - 'a']) continue; + table[c - 'a'] = ch ++; + used[c - 'a'] = true; + } + + for(char& c: message){ + if(c == ' ') continue; + c = table[c - 'a']; + } + return message; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2326-Spiral-Matrix-IV/cpp-2326/CMakeLists.txt b/2001-2500/2326-Spiral-Matrix-IV/cpp-2326/CMakeLists.txt new file mode 100644 index 00000000..8494c320 --- /dev/null +++ b/2001-2500/2326-Spiral-Matrix-IV/cpp-2326/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/2001-2500/2326-Spiral-Matrix-IV/cpp-2326/main.cpp b/2001-2500/2326-Spiral-Matrix-IV/cpp-2326/main.cpp new file mode 100644 index 00000000..1cc5421d --- /dev/null +++ b/2001-2500/2326-Spiral-Matrix-IV/cpp-2326/main.cpp @@ -0,0 +1,63 @@ +/// Source : https://leetcode.com/problems/spiral-matrix-iv/ +/// Author : liuyubobobo +/// Time : 2022-07-02 + +#include +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(m * n) +/// Space Complexity: O(1) + +/// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode() : val(0), next(nullptr) {} + ListNode(int x) : val(x), next(nullptr) {} + ListNode(int x, ListNode *next) : val(x), next(next) {} +}; + +class Solution { + +private: + const int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + int R, C; + +public: + vector> spiralMatrix(int R, int C, ListNode* node) { + + this->R = R, this->C = C; + vector> res(R, vector(C, -1)); + + int cx = 0, cy = -1, d = 0; + while(node){ + int nx = cx + dirs[d][0], ny = cy + dirs[d][1]; + if(!in_area(nx, ny) || res[nx][ny] != -1){ + d = (d + 1) % 4; + nx = cx + dirs[d][0], ny = cy + dirs[d][1]; +// assert(in_area(nx, ny)); + } + + res[nx][ny] = node->val; + node = node->next; + cx = nx, cy = ny; + } + return res; + } + +private: + bool in_area(int x, int y){ + return 0 <= x && x < R && 0 <= y && y < C; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2327-Number-of-People-Aware-of-a-Secret/cpp-2327/CMakeLists.txt b/2001-2500/2327-Number-of-People-Aware-of-a-Secret/cpp-2327/CMakeLists.txt new file mode 100644 index 00000000..586665ca --- /dev/null +++ b/2001-2500/2327-Number-of-People-Aware-of-a-Secret/cpp-2327/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main2.cpp) diff --git a/2001-2500/2327-Number-of-People-Aware-of-a-Secret/cpp-2327/main.cpp b/2001-2500/2327-Number-of-People-Aware-of-a-Secret/cpp-2327/main.cpp new file mode 100644 index 00000000..de612e68 --- /dev/null +++ b/2001-2500/2327-Number-of-People-Aware-of-a-Secret/cpp-2327/main.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/number-of-people-aware-of-a-secret/ +/// Author : liuyubobobo +/// Time : 2022-07-02 + +#include +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { + +private: + const long long MOD = 1e9 + 7; + +public: + int peopleAwareOfSecret(int n, int delay, int forget) { + + vector pos(n, 0), neg(n, 0); + pos[0] = 1; + for(int i = 0; i < n; i ++){ + + for(int j = delay; j < forget && i + j < n; j ++){ + pos[i + j] += pos[i]; + pos[i + j] %= MOD; + } + + if(i + forget < n){ + neg[i + forget] += pos[i]; + neg[i + forget] %= MOD; + } + } + + long long sum_pos = accumulate(pos.begin(), pos.end(), 0ll); + long long sum_neg = accumulate(neg.begin(), neg.end(), 0ll); + return (sum_pos % MOD - sum_neg % MOD + MOD) % MOD; + } +}; + + +int main() { + + cout << Solution().peopleAwareOfSecret(6, 2, 4) << '\n'; + // 5 + + cout << Solution().peopleAwareOfSecret(4, 1, 3) << '\n'; + // 6 + + cout << Solution().peopleAwareOfSecret(6, 1, 2) << '\n'; + // 2 + + return 0; +} diff --git a/2001-2500/2327-Number-of-People-Aware-of-a-Secret/cpp-2327/main2.cpp b/2001-2500/2327-Number-of-People-Aware-of-a-Secret/cpp-2327/main2.cpp new file mode 100644 index 00000000..50f5d0be --- /dev/null +++ b/2001-2500/2327-Number-of-People-Aware-of-a-Secret/cpp-2327/main2.cpp @@ -0,0 +1,73 @@ +/// Source : https://leetcode.com/problems/number-of-people-aware-of-a-secret/ +/// Author : liuyubobobo +/// Time : 2022-07-02 + +#include +#include +#include + +using namespace std; + + +/// DP with diff array +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { + +private: + const long long MOD = 1e9 + 7; + +public: + int peopleAwareOfSecret(int n, int delay, int forget) { + + vector diff_pos(n, 0), neg(n, 0); + diff_pos[0] = 1; + if(1 < n) diff_pos[1] = MOD - 1; + long long presum = 0; + for(int i = 0; i < n; i ++){ + + presum += diff_pos[i]; + presum %= MOD; + + if(i + delay < n){ + diff_pos[i + delay] += presum; + diff_pos[i + delay] %= MOD; + } + + if(i + forget < n){ + diff_pos[i + forget] -= presum; + diff_pos[i + forget] += MOD; + diff_pos[i + forget] %= MOD; + + neg[i + forget] += presum; + neg[i + forget] %= MOD; + } + } + + long long sum_pos = 0; + presum = 0; + for(int i = 0; i < n; i ++){ + presum += diff_pos[i]; + presum %= MOD; + sum_pos += presum; + } + long long sum_neg = accumulate(neg.begin(), neg.end(), 0ll); + + return (sum_pos % MOD - sum_neg % MOD + MOD) % MOD; + } +}; + + +int main() { + + cout << Solution().peopleAwareOfSecret(6, 2, 4) << '\n'; + // 5 + + cout << Solution().peopleAwareOfSecret(4, 1, 3) << '\n'; + // 6 + + cout << Solution().peopleAwareOfSecret(6, 1, 2) << '\n'; + // 2 + + return 0; +} diff --git a/2001-2500/2328-Number-of-Increasing-Paths-in-a-Grid/cpp-2328/CMakeLists.txt b/2001-2500/2328-Number-of-Increasing-Paths-in-a-Grid/cpp-2328/CMakeLists.txt new file mode 100644 index 00000000..9a6c5c78 --- /dev/null +++ b/2001-2500/2328-Number-of-Increasing-Paths-in-a-Grid/cpp-2328/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) diff --git a/2001-2500/2328-Number-of-Increasing-Paths-in-a-Grid/cpp-2328/main.cpp b/2001-2500/2328-Number-of-Increasing-Paths-in-a-Grid/cpp-2328/main.cpp new file mode 100644 index 00000000..2959ce0c --- /dev/null +++ b/2001-2500/2328-Number-of-Increasing-Paths-in-a-Grid/cpp-2328/main.cpp @@ -0,0 +1,67 @@ +/// Source : https://leetcode.com/problems/number-of-increasing-paths-in-a-grid/ +/// Author : liuyubobobo +/// Time : 2022-07-02 + +#include +#include + +using namespace std; + + +/// DAG DP +/// Time Complexity: O(m * n) +/// Space Complexity: O(m * n) +class Solution { + +private: + const long long MOD = 1e9 + 7; + const int dirs[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; + int R, C; + +public: + int countPaths(vector>& grid) { + + R = grid.size(), C = grid[0].size(); + + vector> dp(R, vector(C, -1)); + long long res = 0; + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++) + res += dfs(grid, i, j, dp); + return res % MOD; + } + +private: + long long dfs(const vector>& g, int cx, int cy, + vector>& dp){ + + if(dp[cx][cy] != -1) return dp[cx][cy]; + + long long res = 1; + for(int d = 0; d < 4; d ++){ + int nx = cx + dirs[d][0], ny = cy + dirs[d][1]; + if(!in_area(nx, ny) || g[nx][ny] <= g[cx][cy]) continue; + res += dfs(g, nx, ny, dp); + } + + return dp[cx][cy] = res % MOD; + } + + bool in_area(int x, int y){ + return 0 <= x && x < R && 0 <= y && y < C; + } +}; + + +int main() { + + vector> grid1 = {{1, 1}, {3, 4}}; + cout << Solution().countPaths(grid1) << '\n'; + // 8 + + vector> grid2 = {{1}, {2}}; + cout << Solution().countPaths(grid2) << '\n'; + // 3 + + return 0; +} diff --git a/2001-2500/2330-Valid-Palindrome-IV/cpp-2330/CMakeLists.txt b/2001-2500/2330-Valid-Palindrome-IV/cpp-2330/CMakeLists.txt new file mode 100644 index 00000000..7e1584d9 --- /dev/null +++ b/2001-2500/2330-Valid-Palindrome-IV/cpp-2330/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_2330) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2330 main.cpp) diff --git a/2001-2500/2330-Valid-Palindrome-IV/cpp-2330/main.cpp b/2001-2500/2330-Valid-Palindrome-IV/cpp-2330/main.cpp new file mode 100644 index 00000000..f867a3cd --- /dev/null +++ b/2001-2500/2330-Valid-Palindrome-IV/cpp-2330/main.cpp @@ -0,0 +1,29 @@ +/// Source : https://leetcode.com/problems/valid-palindrome-iv/ +/// Author : liuyubobobo +/// Time : 2022-07-10 + +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + bool makePalindrome(string s) { + + int n = s.size(), res = 0; + for(int i = 0, j = n - 1; i < j; i ++, j --) + res += s[i] != s[j]; + + return res <= 2; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2331-Evaluate-Boolean-Binary-Tree/cpp-2331/CMakeLists.txt b/2001-2500/2331-Evaluate-Boolean-Binary-Tree/cpp-2331/CMakeLists.txt new file mode 100644 index 00000000..fe8bfd9f --- /dev/null +++ b/2001-2500/2331-Evaluate-Boolean-Binary-Tree/cpp-2331/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/2001-2500/2331-Evaluate-Boolean-Binary-Tree/cpp-2331/main.cpp b/2001-2500/2331-Evaluate-Boolean-Binary-Tree/cpp-2331/main.cpp new file mode 100644 index 00000000..4cdf3bd8 --- /dev/null +++ b/2001-2500/2331-Evaluate-Boolean-Binary-Tree/cpp-2331/main.cpp @@ -0,0 +1,43 @@ +/// Source : https://leetcode.com/problems/evaluate-boolean-binary-tree/ +/// Author : liuyubobobo +/// Time : 2022-07-09 + +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(h) + +/// 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 evaluateTree(TreeNode* root) { + + if(root->left == nullptr || root->right == nullptr) + return root->val; + + int a = evaluateTree(root->left); + int b = evaluateTree(root->right); + + if(root->val == 2) return a | b; + return a & b; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2332-The-Latest-Time-to-Catch-a-Bus/cpp-2332/CMakeLists.txt b/2001-2500/2332-The-Latest-Time-to-Catch-a-Bus/cpp-2332/CMakeLists.txt new file mode 100644 index 00000000..be95bd50 --- /dev/null +++ b/2001-2500/2332-The-Latest-Time-to-Catch-a-Bus/cpp-2332/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_2332) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2332 main.cpp) diff --git a/2001-2500/2332-The-Latest-Time-to-Catch-a-Bus/cpp-2332/main.cpp b/2001-2500/2332-The-Latest-Time-to-Catch-a-Bus/cpp-2332/main.cpp new file mode 100644 index 00000000..9ec118ed --- /dev/null +++ b/2001-2500/2332-The-Latest-Time-to-Catch-a-Bus/cpp-2332/main.cpp @@ -0,0 +1,72 @@ +/// Source : https://leetcode.com/problems/the-latest-time-to-catch-a-bus/ +/// Author : liuyubobobo +/// Time : 2022-07-12 + +#include +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n + m) +/// Space Complexity: O(n) +class Solution { +public: + int latestTimeCatchTheBus(vector& buses, vector& passengers, int capacity) { + + sort(buses.begin(), buses.end()); + sort(passengers.begin(), passengers.end()); + + vector pre(passengers.size()); + for(int start = 0, i = 1; i <= passengers.size(); i ++) + if(i == passengers.size() || passengers[i] != passengers[start] + (i - start)){ + for(int j = start; j < i; j ++) pre[j] = passengers[start] - 1; + start = i; + } + + int res = 1; + int pi = 0; + for(int bi = 0; bi < buses.size(); bi ++){ + vector v; + for(; pi < passengers.size() && passengers[pi] <= buses[bi] && v.size() < capacity; pi ++) + v.push_back(pi); + + for(int i: v) + res = max(res, pre[i]); + + if(v.size() < capacity){ + if(v.empty() || passengers[v.back()] != buses[bi]) + res = max(res, buses[bi]); + } + } + return res; + } +}; + + +int main() { + + vector buses1 = {10, 20}, passengers1 = {2, 17, 18, 19}; + cout << Solution().latestTimeCatchTheBus(buses1, passengers1, 2) << '\n'; + // 16 + + vector buses2 = {20, 30, 10}, passengers2 = {19, 13, 26, 4, 25, 11, 21}; + cout << Solution().latestTimeCatchTheBus(buses2, passengers2, 2) << '\n'; + // 20 + + vector buses3 = {2}, passengers3 = {2}; + cout << Solution().latestTimeCatchTheBus(buses3, passengers3, 2) << '\n'; + // 1 + + vector buses4 = {5, 15}, passengers4 = {11, 12, 13, 14, 15}; + cout << Solution().latestTimeCatchTheBus(buses4, passengers4, 2) << '\n'; + // 10 + + vector buses5 = {7,12,15,11,14,13,5,4,2,8,9,19}, passengers5 = {2,5,10,12,8,19,9,14,4,7,15,13}; + cout << Solution().latestTimeCatchTheBus(buses5, passengers5, 2) << '\n'; + // 18 + + return 0; +} diff --git a/2001-2500/2333-Minimum-Sum-of-Squared-Difference/cpp-2333/CMakeLists.txt b/2001-2500/2333-Minimum-Sum-of-Squared-Difference/cpp-2333/CMakeLists.txt new file mode 100644 index 00000000..830d3093 --- /dev/null +++ b/2001-2500/2333-Minimum-Sum-of-Squared-Difference/cpp-2333/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/2001-2500/2333-Minimum-Sum-of-Squared-Difference/cpp-2333/main.cpp b/2001-2500/2333-Minimum-Sum-of-Squared-Difference/cpp-2333/main.cpp new file mode 100644 index 00000000..47aa7a91 --- /dev/null +++ b/2001-2500/2333-Minimum-Sum-of-Squared-Difference/cpp-2333/main.cpp @@ -0,0 +1,76 @@ +/// Source : https://leetcode.com/problems/minimum-sum-of-squared-difference/ +/// Author : liuyubobobo +/// Time : 2022-07-10 + +#include +#include +#include + +using namespace std; + + +/// Soring and Greedy +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + long long minSumSquareDiff(vector& nums1, vector& nums2, int k1, int k2) { + + int n = nums1.size(); + vector d(n); + for(int i = 0; i < n; i ++) d[i] = abs(nums1[i] - nums2[i]); + + sort(d.begin(), d.end(), greater()); + d.push_back(0); + n ++; + + long long k = k1 + k2; + + long long pre = d[0]; + int i; + for(i = 1; i < n; i ++){ + long long cur = d[i]; + long long diff = pre - cur; + if(diff * i <= k){ + k -= diff * i; + pre = cur; + } + else{ + break; + } + } + + if(i < n){ + for(int j = 0; j < i; j ++) d[j] = pre; + + for(int j = 0; j < i; j ++){ + d[j] -= k / i; + if(j < k % i) d[j] --; + } + } + else return 0; + + long long res = 0; + for(int i = 0; i < n; i ++) + res += d[i] * d[i]; + return res; + } +}; + + +int main() { + + vector nums11 = {1, 2, 3, 4}, nums12 = {2, 10, 20, 19}; + cout << Solution().minSumSquareDiff(nums11, nums12, 0, 0) << '\n'; + // 579 + + vector nums21 = {1, 4, 10, 12}, nums22 = {5, 8, 6, 9}; + cout << Solution().minSumSquareDiff(nums21, nums22, 1, 1) << '\n'; + // 43 + + vector nums31 = {19, 18, 19, 18, 18, 19, 19}, nums32 = {1, 0, 1, 0, 0, 1, 1}; + cout << Solution().minSumSquareDiff(nums31, nums32, 10, 33) << '\n'; + // 985 + + return 0; +} diff --git a/2001-2500/2334-Subarray-With-Elements-Greater-Than-Varying-Threshold/cpp-2334/CMakeLists.txt b/2001-2500/2334-Subarray-With-Elements-Greater-Than-Varying-Threshold/cpp-2334/CMakeLists.txt new file mode 100644 index 00000000..9a6c5c78 --- /dev/null +++ b/2001-2500/2334-Subarray-With-Elements-Greater-Than-Varying-Threshold/cpp-2334/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) diff --git a/2001-2500/2334-Subarray-With-Elements-Greater-Than-Varying-Threshold/cpp-2334/main.cpp b/2001-2500/2334-Subarray-With-Elements-Greater-Than-Varying-Threshold/cpp-2334/main.cpp new file mode 100644 index 00000000..21e0cc6a --- /dev/null +++ b/2001-2500/2334-Subarray-With-Elements-Greater-Than-Varying-Threshold/cpp-2334/main.cpp @@ -0,0 +1,112 @@ +/// Source : https://leetcode.com/problems/subarray-with-elements-greater-than-varying-threshold/ +/// Author : liuyubobobo +/// Time : 2022-07-09 + +#include +#include + +using namespace std; + + +/// Divide and Conquer +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +template +class MinIndexSegmentTree{ + +private: + int n; + vector data, tree; + +public: + MinIndexSegmentTree(const vector& data): n(data.size()), data(data), tree(4 * n, 0){ + buildSegTree(0, 0, n - 1); + } + + T query(int index){ + assert(0 <= index && index < n); + return data[index]; + } + + T query(int l, int r){ + assert(l <= r); + assert(0 <= l && l < n); + assert(0 <= r && r < n); + return query(0, 0, n - 1, l, r); + } + +private: + void buildSegTree(int treeID, int l, int r){ + + if(l == r){ + tree[treeID] = l; + return; + } + + int mid = (l + r) / 2; + buildSegTree(treeID * 2 + 1, l, mid); + buildSegTree(treeID * 2 + 2, mid + 1, r); + tree[treeID] = data[tree[treeID * 2 + 1]] < data[tree[treeID * 2 + 2]] ? tree[treeID * 2 + 1] : tree[treeID * 2 + 2]; + return; + } + + T query(int treeID, int l, int r, int ql, int qr){ + + if(ql == l && qr == r) + return tree[treeID]; + + int mid = (l + r) / 2; + if(qr <= mid) return query(treeID * 2 + 1, l, mid, ql, qr); + else if(ql > mid) return query(treeID * 2 + 2, mid + 1, r, ql, qr); + + T resl = query(treeID * 2 + 1, l, mid, ql, mid); + T resr = query(treeID * 2 + 2, mid + 1, r, mid + 1, qr); + return data[resl] < data[resr] ? resl : resr; + } +}; + +class Solution { + +private: + MinIndexSegmentTree *seg_tree; + +public: + int validSubarraySize(vector& nums, int threshold) { + + seg_tree = new MinIndexSegmentTree(nums); + + int res = solve(nums, 0, nums.size() - 1, threshold); + return res ? res : -1; + } + + int solve(const vector& nums, int l, int r, int threshold){ + + if(l > r) return 0; + if(l == r){ + return nums[l] > threshold ? 1: 0; + } + + int min_index = seg_tree->query(l, r); + int min_value = nums[min_index]; + + if(min_value > threshold / (r - l + 1)) return r - l + 1; + + int resl = solve(nums, l, min_index - 1, threshold); + if(resl) return resl; + return solve(nums, min_index + 1, r, threshold); + } +}; + + +int main() { + + vector nums1 = {1, 3, 4, 3, 1}; + cout << Solution().validSubarraySize(nums1, 6) << '\n'; + // 3 + + vector nums2 = {6,5,6,5,8}; + cout << Solution().validSubarraySize(nums2, 7) << '\n'; + // 1 + + return 0; +} diff --git a/2001-2500/2335-Minimum-Amount-of-Time-to-Fill-Cups/cpp-2335/CMakeLists.txt b/2001-2500/2335-Minimum-Amount-of-Time-to-Fill-Cups/cpp-2335/CMakeLists.txt new file mode 100644 index 00000000..fe8bfd9f --- /dev/null +++ b/2001-2500/2335-Minimum-Amount-of-Time-to-Fill-Cups/cpp-2335/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/2001-2500/2335-Minimum-Amount-of-Time-to-Fill-Cups/cpp-2335/main.cpp b/2001-2500/2335-Minimum-Amount-of-Time-to-Fill-Cups/cpp-2335/main.cpp new file mode 100644 index 00000000..65f9fdd4 --- /dev/null +++ b/2001-2500/2335-Minimum-Amount-of-Time-to-Fill-Cups/cpp-2335/main.cpp @@ -0,0 +1,41 @@ +/// Source : https://leetcode.com/problems/minimum-amount-of-time-to-fill-cups/ +/// Author : liuyubobobo +/// Time : 2022-07-10 + +#include +#include +#include + +using namespace std; + + +/// Using PQ +/// Time Complexity: O(sum(amount)) +/// Space Complexity: O(1) +class Solution { +public: + int fillCups(vector& amount) { + + priority_queue pq; + for(int i = 0; i < 3; i ++) + if(amount[i]) pq.push(amount[i]); + + int res = 0; + while(pq.size() >= 2){ + int a = pq.top(); pq.pop(); + int b = pq.top(); pq.pop(); + res ++, a --, b --; + if(a) pq.push(a); + if(b) pq.push(b); + } + + if(pq.size()) res += pq.top(); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2336-Smallest-Number-in-Infinite-Set/cpp-2336/CMakeLists.txt b/2001-2500/2336-Smallest-Number-in-Infinite-Set/cpp-2336/CMakeLists.txt new file mode 100644 index 00000000..8494c320 --- /dev/null +++ b/2001-2500/2336-Smallest-Number-in-Infinite-Set/cpp-2336/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/2001-2500/2336-Smallest-Number-in-Infinite-Set/cpp-2336/main.cpp b/2001-2500/2336-Smallest-Number-in-Infinite-Set/cpp-2336/main.cpp new file mode 100644 index 00000000..adfd494c --- /dev/null +++ b/2001-2500/2336-Smallest-Number-in-Infinite-Set/cpp-2336/main.cpp @@ -0,0 +1,63 @@ +/// Source : https://leetcode.com/problems/smallest-number-in-infinite-set/ +/// Author : liuyubobobo +/// Time : 2022-06-08 + +#include +#include + +using namespace std; + + +/// Using Set +/// Time Complexity: init: O(1) +/// pop: O(logn) +/// add: O(logn) +/// Space Compelxity: O(n) +class SmallestInfiniteSet { + +private: + int start = 1; + set others; + +public: + SmallestInfiniteSet() {} + + int popSmallest() { + + if(!others.empty()){ + int ret = *others.begin(); + others.erase(others.begin()); + return ret; + } + + int ret = start; + start ++; + return ret; + } + + void addBack(int num) { + + if(others.count(num) || num >= start) return; + + if(num == start - 1){ + start --; + while(true){ + auto iter = others.find(start - 1); + if(iter != others.end()){ + others.erase(iter); + start --; + } + else break; + } + } + else{ + others.insert(num); + } + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2337-Move-Pieces-to-Obtain-a-String/cpp-2337/CMakeLists.txt b/2001-2500/2337-Move-Pieces-to-Obtain-a-String/cpp-2337/CMakeLists.txt new file mode 100644 index 00000000..830d3093 --- /dev/null +++ b/2001-2500/2337-Move-Pieces-to-Obtain-a-String/cpp-2337/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/2001-2500/2337-Move-Pieces-to-Obtain-a-String/cpp-2337/main.cpp b/2001-2500/2337-Move-Pieces-to-Obtain-a-String/cpp-2337/main.cpp new file mode 100644 index 00000000..f2b2f9df --- /dev/null +++ b/2001-2500/2337-Move-Pieces-to-Obtain-a-String/cpp-2337/main.cpp @@ -0,0 +1,39 @@ +/// Source : https://leetcode.com/problems/move-pieces-to-obtain-a-string/ +/// Author : liuyubobobo +/// Time : 2022-07-10 + +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + bool canChange(string start, string target) { + + vector> pos1, pos2; + for(int i = 0; i < start.size(); i ++) + if(start[i] != '_') pos1.push_back({start[i], i}); + for(int i = 0; i < target.size(); i ++) + if(target[i] != '_') pos2.push_back({target[i], i}); + + if(pos1.size() != pos2.size()) return false; + + for(int i = 0; i < pos1.size(); i ++){ + if(pos1[i].first != pos2[i].first) return false; + if(pos1[i].first == 'L' && pos1[i].second < pos2[i].second) return false; + if(pos1[i].first == 'R' && pos1[i].second > pos2[i].second) return false; + } + return true; + } +}; + + +int main() { + std::cout << "Hello, World!" << std::endl; + return 0; +} diff --git a/2001-2500/2338-Count-the-Number-of-Ideal-Arrays/cpp-2338/CMakeLists.txt b/2001-2500/2338-Count-the-Number-of-Ideal-Arrays/cpp-2338/CMakeLists.txt new file mode 100644 index 00000000..bb71ae36 --- /dev/null +++ b/2001-2500/2338-Count-the-Number-of-Ideal-Arrays/cpp-2338/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main2.cpp) diff --git a/2001-2500/2338-Count-the-Number-of-Ideal-Arrays/cpp-2338/main.cpp b/2001-2500/2338-Count-the-Number-of-Ideal-Arrays/cpp-2338/main.cpp new file mode 100644 index 00000000..268cb79f --- /dev/null +++ b/2001-2500/2338-Count-the-Number-of-Ideal-Arrays/cpp-2338/main.cpp @@ -0,0 +1,87 @@ +/// Source : https://leetcode.com/problems/count-the-number-of-ideal-arrays/ +/// Author : liuyubobobo +/// Time : 2022-07-10 + +#include +#include + +using namespace std; + + +/// Backtrack + Math +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { + +private: + const long long MOD = 1e9 + 7; + vector fac, ifac; + +public: + Solution(): fac(1e4 + 1, 1), ifac(1e4 + 1){} + + int idealArrays(int n, int maxValue) { + + for(int i = 1; i <= n; i ++) + fac[i] = fac[i - 1] * i % MOD; + for(int i = 0; i <= n; i ++) + ifac[i] = quick_pow(fac[i], MOD - 2); + + vector seq; + return go(seq, n, maxValue); + } + +private: + long long go(vector& seq, int n, int maxValue){ + + long long res = 0; + if(seq.empty()){ + for(int i = 1; i <= maxValue; i ++){ + seq.push_back(i); + res += go(seq, n, maxValue); + seq.pop_back(); + } + return res % MOD; + } + + int k = seq.size() - 1; + res += fac[n - 1] * ifac[k] % MOD * ifac[n - 1 - k] % MOD; + + if(seq.size() == n) return res; + + for(int d = 2; seq.back() * d <= maxValue; d ++){ + seq.push_back(seq.back() * d); + res += go(seq, n, maxValue); + seq.pop_back(); + } + return res % MOD; + } + + long long quick_pow(long long a, long long k) { + long long res = 1ll; + while (k) { + if (k & 1) res = res * a % MOD; + a = a * a % MOD; + k >>= 1; + } + return res % MOD; + } +}; + + +int main() { + + cout << Solution().idealArrays(2, 5) << '\n'; + // 10 + + cout << Solution().idealArrays(5, 3) << '\n'; + // 11 + + cout << Solution().idealArrays(5878, 2900) << '\n'; + // 465040898 + + cout << Solution().idealArrays(1e4, 1e4) << '\n'; + // 22940607 + + return 0; +} diff --git a/2001-2500/2338-Count-the-Number-of-Ideal-Arrays/cpp-2338/main2.cpp b/2001-2500/2338-Count-the-Number-of-Ideal-Arrays/cpp-2338/main2.cpp new file mode 100644 index 00000000..fcb5b2ff --- /dev/null +++ b/2001-2500/2338-Count-the-Number-of-Ideal-Arrays/cpp-2338/main2.cpp @@ -0,0 +1,79 @@ +/// Source : https://leetcode.com/problems/count-the-number-of-ideal-arrays/ +/// Author : liuyubobobo +/// Time : 2022-07-10 + +#include +#include + +using namespace std; + + +/// Backtrack + Math +/// Using dp is faster than multiplication reverse in this problem +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { + +private: + const long long MOD = 1e9 + 7; + +public: + int idealArrays(int n, int maxValue) { + + vector> dp(n + 1, vector(20, 0ll)); + dp[1][0] = dp[1][1] = 1; + for(int i = 2; i <= n; i ++){ + dp[i][0] = 1; + if(i < 20) dp[i][i] = 1; + for(int k = 1; k < min(i, 20); k ++) + dp[i][k] = (dp[i - 1][k - 1] + dp[i - 1][k]) % MOD; + } + + vector seq; + return go(seq, n, maxValue, dp); + } + +private: + long long go(vector& seq, int n, int maxValue, + const vector>& dp){ + + long long res = 0; + if(seq.empty()){ + for(int i = 1; i <= maxValue; i ++){ + seq.push_back(i); + res += go(seq, n, maxValue, dp); + seq.pop_back(); + } + return res % MOD; + } + + res += dp[n - 1][seq.size() - 1]; + + if(seq.size() == n) return res; + + for(int d = 2; seq.back() * d <= maxValue; d ++){ + seq.push_back(seq.back() * d); + res += go(seq, n, maxValue, dp); + seq.pop_back(); + } + return res % MOD; + } +}; + + +int main() { + + cout << Solution().idealArrays(2, 5) << '\n'; + // 10 + + cout << Solution().idealArrays(5, 3) << '\n'; + // 11 + + cout << Solution().idealArrays(5878, 2900) << '\n'; + // 465040898 + + cout << Solution().idealArrays(1e4, 1e4) << '\n'; + // 22940607 + + return 0; +} diff --git a/2001-2500/2340-Minimum-Adjacent-Swaps-to-Make-a-Valid-Array/cpp-2340/CMakeLists.txt b/2001-2500/2340-Minimum-Adjacent-Swaps-to-Make-a-Valid-Array/cpp-2340/CMakeLists.txt new file mode 100644 index 00000000..c26ae715 --- /dev/null +++ b/2001-2500/2340-Minimum-Adjacent-Swaps-to-Make-a-Valid-Array/cpp-2340/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_2340) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2340 main.cpp) diff --git a/2001-2500/2340-Minimum-Adjacent-Swaps-to-Make-a-Valid-Array/cpp-2340/main.cpp b/2001-2500/2340-Minimum-Adjacent-Swaps-to-Make-a-Valid-Array/cpp-2340/main.cpp new file mode 100644 index 00000000..883eb07b --- /dev/null +++ b/2001-2500/2340-Minimum-Adjacent-Swaps-to-Make-a-Valid-Array/cpp-2340/main.cpp @@ -0,0 +1,41 @@ +/// Source : https://leetcode.com/problems/minimum-adjacent-swaps-to-make-a-valid-array/ +/// Author : liuyubobobo +/// Time : 2022-07-14 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int minimumSwaps(vector& nums) { + + int n = nums.size(); + + int min_v = nums[0], min_v_index = 0; + for(int i = 1; i < n; i ++) + if(nums[i] < min_v) min_v = nums[i], min_v_index = i; + + int max_v = nums[0], max_v_index = 0; + for(int i = 1; i < n; i ++) + if(nums[i] >= max_v) max_v = nums[i], max_v_index = i; + + if(min_v_index == 0 && max_v_index == n - 1) return 0; + if(min_v_index < max_v_index) return min_v_index + n - 1 - max_v_index; + return min_v_index + n - 2 - max_v_index; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2341-Maximum-Number-of-Pairs-in-Array/cpp-2341/CMakeLists.txt b/2001-2500/2341-Maximum-Number-of-Pairs-in-Array/cpp-2341/CMakeLists.txt new file mode 100644 index 00000000..fe8bfd9f --- /dev/null +++ b/2001-2500/2341-Maximum-Number-of-Pairs-in-Array/cpp-2341/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/2001-2500/2341-Maximum-Number-of-Pairs-in-Array/cpp-2341/main.cpp b/2001-2500/2341-Maximum-Number-of-Pairs-in-Array/cpp-2341/main.cpp new file mode 100644 index 00000000..7b03871e --- /dev/null +++ b/2001-2500/2341-Maximum-Number-of-Pairs-in-Array/cpp-2341/main.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/maximum-number-of-pairs-in-array/ +/// Author : liuyubobobo +/// Time : 2022-07-16 + +#include +#include +#include + +using namespace std; + + +/// Using Map +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector numberOfPairs(vector& nums) { + + map f; + for(int e: nums) f[e] ++; + + vector res(2, 0); + for(const pair& p: f){ + res[0] += p.second / 2; + res[1] += p.second % 2; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2342-Max-Sum-of-a-Pair-With-Equal-Sum-of-Digits/cpp-2342/CMakeLists.txt b/2001-2500/2342-Max-Sum-of-a-Pair-With-Equal-Sum-of-Digits/cpp-2342/CMakeLists.txt new file mode 100644 index 00000000..6c7077c9 --- /dev/null +++ b/2001-2500/2342-Max-Sum-of-a-Pair-With-Equal-Sum-of-Digits/cpp-2342/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main2.cpp) diff --git a/2001-2500/2342-Max-Sum-of-a-Pair-With-Equal-Sum-of-Digits/cpp-2342/main.cpp b/2001-2500/2342-Max-Sum-of-a-Pair-With-Equal-Sum-of-Digits/cpp-2342/main.cpp new file mode 100644 index 00000000..6f4b3b85 --- /dev/null +++ b/2001-2500/2342-Max-Sum-of-a-Pair-With-Equal-Sum-of-Digits/cpp-2342/main.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/max-sum-of-a-pair-with-equal-sum-of-digits/ +/// Author : liuyubobobo +/// Time : 2022-07-16 + +#include +#include +#include +#include + +using namespace std; + + +/// Using Map +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + int maximumSum(vector& nums) { + + map> f; + for(int e: nums) f[dsum(e)].push_back(e); + + for(const pair>& p: f){ + int sum = p.first; + sort(f[sum].begin(), f[sum].end(), greater()); + } + + int res = -1; + for(const pair>& p: f){ + if(p.second.size() >= 2){ + res = max(res, p.second[0] + p.second[1]); + } + } + return res; + } + +private: + int dsum(int x){ + int res = 0; + while(x){ + res += x % 10; + x /= 10; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2342-Max-Sum-of-a-Pair-With-Equal-Sum-of-Digits/cpp-2342/main2.cpp b/2001-2500/2342-Max-Sum-of-a-Pair-With-Equal-Sum-of-Digits/cpp-2342/main2.cpp new file mode 100644 index 00000000..1a985640 --- /dev/null +++ b/2001-2500/2342-Max-Sum-of-a-Pair-With-Equal-Sum-of-Digits/cpp-2342/main2.cpp @@ -0,0 +1,58 @@ +/// Source : https://leetcode.com/problems/max-sum-of-a-pair-with-equal-sum-of-digits/ +/// Author : liuyubobobo +/// Time : 2022-07-16 + +#include +#include +#include +#include + +using namespace std; + + +/// Using Map, no sorting +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + int maximumSum(vector& nums) { + + map> f; + for(int e: nums){ + int sum = dsum(e); + auto iter = f.find(sum); + if(iter == f.end()) f[sum] = {e, -1}; + else if(e > iter->second.first){ + iter->second.second = iter->second.first; + iter->second.first = e; + } + else{ + iter->second.second = max(e, iter->second.second); + } + } + + int res = -1; + for(const pair>& p: f){ + if(p.second.second != -1){ + res = max(res, p.second.first + p.second.second); + } + } + return res; + } + +private: + int dsum(int x){ + int res = 0; + while(x){ + res += x % 10; + x /= 10; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2343-Query-Kth-Smallest-Trimmed-Number/cpp-2343/CMakeLists.txt b/2001-2500/2343-Query-Kth-Smallest-Trimmed-Number/cpp-2343/CMakeLists.txt new file mode 100644 index 00000000..830d3093 --- /dev/null +++ b/2001-2500/2343-Query-Kth-Smallest-Trimmed-Number/cpp-2343/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/2001-2500/2343-Query-Kth-Smallest-Trimmed-Number/cpp-2343/main.cpp b/2001-2500/2343-Query-Kth-Smallest-Trimmed-Number/cpp-2343/main.cpp new file mode 100644 index 00000000..040ea414 --- /dev/null +++ b/2001-2500/2343-Query-Kth-Smallest-Trimmed-Number/cpp-2343/main.cpp @@ -0,0 +1,42 @@ +/// Source : https://leetcode.com/problems/query-kth-smallest-trimmed-number/ +/// Author : liuyubobobo +/// Time : 2022-07-16 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(q * nlogn * len) +/// Space Complexity: O(n) +class Solution { +public: + vector smallestTrimmedNumbers(vector& nums, vector>& queries) { + + int n = nums.size(), len = nums[0].size(); + + vector res(queries.size()); + for(int i = 0; i < queries.size(); i ++){ + res[i] = solve(n, len, nums, queries[i][0] - 1, queries[i][1]); + } + return res; + } + +private: + int solve(int n, int len, const vector& nums, int k, int x){ + + vector> data(n); + for(int i = 0; i < n; i ++) + data[i] = {nums[i].substr(len - x), i}; + sort(data.begin(), data.end()); + return data[k].second; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2344-Minimum-Deletions-to-Make-Array-Divisible/cpp-2344/CMakeLists.txt b/2001-2500/2344-Minimum-Deletions-to-Make-Array-Divisible/cpp-2344/CMakeLists.txt new file mode 100644 index 00000000..9a6c5c78 --- /dev/null +++ b/2001-2500/2344-Minimum-Deletions-to-Make-Array-Divisible/cpp-2344/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) diff --git a/2001-2500/2344-Minimum-Deletions-to-Make-Array-Divisible/cpp-2344/main.cpp b/2001-2500/2344-Minimum-Deletions-to-Make-Array-Divisible/cpp-2344/main.cpp new file mode 100644 index 00000000..076121d4 --- /dev/null +++ b/2001-2500/2344-Minimum-Deletions-to-Make-Array-Divisible/cpp-2344/main.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/minimum-deletions-to-make-array-divisible/ +/// Author : liuyubobobo +/// Time : 2022-07-16 + +#include +#include +#include + +using namespace std; + + +/// Sorting and Greedy +/// Time Complexity: O(nlog(max(numsDivide)) + nlogn) +/// Space Complexity: O(log(max(numsDivide))) +class Solution { +public: + int minOperations(vector& nums, vector& numsDivide) { + + int t = numsDivide[0]; + for(int i = 1; i < numsDivide.size(); i ++) + t = gcd(min(t, numsDivide[i]), max(t, numsDivide[i])); + + sort(nums.begin(), nums.end()); + for(int i = 0; i < nums.size(); i ++) + if(t % nums[i] == 0) return i; + return -1; + } + +private: + int gcd(int a, int b){ + if (a == 0) return b; + return gcd(b % a, a); + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2345-Finding-the-Number-of-Visible-Mountains/cpp-2345/CMakeLists.txt b/2001-2500/2345-Finding-the-Number-of-Visible-Mountains/cpp-2345/CMakeLists.txt new file mode 100644 index 00000000..9ec33917 --- /dev/null +++ b/2001-2500/2345-Finding-the-Number-of-Visible-Mountains/cpp-2345/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_2345) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2345 main.cpp) diff --git a/2001-2500/2345-Finding-the-Number-of-Visible-Mountains/cpp-2345/main.cpp b/2001-2500/2345-Finding-the-Number-of-Visible-Mountains/cpp-2345/main.cpp new file mode 100644 index 00000000..72496da9 --- /dev/null +++ b/2001-2500/2345-Finding-the-Number-of-Visible-Mountains/cpp-2345/main.cpp @@ -0,0 +1,59 @@ +/// Source : https://leetcode.com/problems/finding-the-number-of-visible-mountains/ +/// Author : liuyubobobo +/// Time : 2022-07-22 + +#include +#include +#include + +using namespace std; + + +/// Points Transformation +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + int visibleMountains(vector>& peaks) { + + int n = peaks.size(); + + vector> points(n); + for(int i = 0; i < n; i ++){ + int x = peaks[i][0], y = peaks[i][1]; + points[i] = {x + y, y - x}; + } + + sort(points.begin(), points.end(), greater>()); + + int res = 0, ylimit = INT_MIN; + for(int i = 0; i < n; i ++){ + int x = points[i].first, y = points[i].second; + + if(i + 1 < n && points[i + 1] == points[i]){ + ylimit = max(ylimit, y); + continue; + } + + if(i && x == points[i - 1].first) continue; + + if(y > ylimit) res ++; + ylimit = max(ylimit, y); + } + return res; + } +}; + + +int main() { + + vector> peaks1 = {{2, 2}, {6, 3}, {5, 4}}; + cout << Solution().visibleMountains(peaks1) << '\n'; + // 2 + + vector> peaks2 = {{1, 3}, {1, 3}}; + cout << Solution().visibleMountains(peaks2) << '\n'; + // 0 + + return 0; +} diff --git a/2001-2500/2347-Best-Poker-Hand/cpp-2347/CMakeLists.txt b/2001-2500/2347-Best-Poker-Hand/cpp-2347/CMakeLists.txt new file mode 100644 index 00000000..3a6d9c1a --- /dev/null +++ b/2001-2500/2347-Best-Poker-Hand/cpp-2347/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_2347) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2347 main.cpp) diff --git a/2001-2500/2347-Best-Poker-Hand/cpp-2347/main.cpp b/2001-2500/2347-Best-Poker-Hand/cpp-2347/main.cpp new file mode 100644 index 00000000..d8ec8156 --- /dev/null +++ b/2001-2500/2347-Best-Poker-Hand/cpp-2347/main.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/best-poker-hand/ +/// Author : liuyubobobo +/// Time : 2022-07-23 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + string bestHand(vector& ranks, vector& suits) { + + if(is_flush(suits)) return "Flush"; + + sort(ranks.begin(), ranks.end()); + int max_same = get_max_same(ranks); + if(max_same >= 3) return "Three of a Kind"; + else if(max_same == 2) return "Pair"; + return "High Card"; + } + +private: + int get_max_same(const vector& data){ + + int n = data.size(), res = 0; + for(int start = 0, i = 1; i <= n; i ++) + if(i == n || data[i] != data[start]){ + res = max(res, i - start); + start = i; + } + return res; + } + + bool is_flush(const vector& suits){ + for(int i = 1; i < suits.size(); i ++) + if(suits[i] != suits[0]) return false; + return true; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2348-Number-of-Zero-Filled-Subarrays/cpp-2348/CMakeLists.txt b/2001-2500/2348-Number-of-Zero-Filled-Subarrays/cpp-2348/CMakeLists.txt new file mode 100644 index 00000000..9c637ccf --- /dev/null +++ b/2001-2500/2348-Number-of-Zero-Filled-Subarrays/cpp-2348/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_2348) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2348 main.cpp) diff --git a/2001-2500/2348-Number-of-Zero-Filled-Subarrays/cpp-2348/main.cpp b/2001-2500/2348-Number-of-Zero-Filled-Subarrays/cpp-2348/main.cpp new file mode 100644 index 00000000..ef235522 --- /dev/null +++ b/2001-2500/2348-Number-of-Zero-Filled-Subarrays/cpp-2348/main.cpp @@ -0,0 +1,36 @@ +/// Source : https://leetcode.com/problems/number-of-zero-filled-subarrays/ +/// Author : liuyubobobo +/// Time : 2022-07-23 + +#include +#include + +using namespace std; + + +/// Split +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + long long zeroFilledSubarray(vector& nums) { + + int n = nums.size(); + long long res = 0; + for(int start = 0, i = 1; i <= n; i ++) + if(i == n || nums[i] != nums[start]){ + if(nums[start] == 0){ + long long len = i - start; + res += (len + 1ll) * len / 2ll; + } + start = i; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2349-Design-a-Number-Container-System/cpp-2349/CMakeLists.txt b/2001-2500/2349-Design-a-Number-Container-System/cpp-2349/CMakeLists.txt new file mode 100644 index 00000000..60f80dba --- /dev/null +++ b/2001-2500/2349-Design-a-Number-Container-System/cpp-2349/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_2349) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2349 main.cpp) diff --git a/2001-2500/2349-Design-a-Number-Container-System/cpp-2349/main.cpp b/2001-2500/2349-Design-a-Number-Container-System/cpp-2349/main.cpp new file mode 100644 index 00000000..ae3cf74c --- /dev/null +++ b/2001-2500/2349-Design-a-Number-Container-System/cpp-2349/main.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/design-a-number-container-system/ +/// Author : liuyubobobo +/// Time : 2022-07-23 + +#include +#include +#include + +using namespace std; + + +/// Using Map +/// Time Complecity: O(logn) for every operation +/// Space Compelxity: O(n) +class NumberContainers { + +private: + map data; + map> num2indice; + +public: + NumberContainers() {} + + void change(int index, int number) { + + auto iter = data.find(index); + if(iter == data.end()){ + data[index] = number; + num2indice[number].insert(index); + return; + } + + int old_number = iter->second; + num2indice[old_number].erase(index); + if(num2indice[old_number].empty()) num2indice.erase(old_number); + + data[index] = number; + num2indice[number].insert(index); + } + + int find(int number) { + return num2indice[number].empty() ? -1 : *num2indice[number].begin(); + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2350-Shortest-Impossible-Sequence-of-Rolls/cpp-2350/CMakeLists.txt b/2001-2500/2350-Shortest-Impossible-Sequence-of-Rolls/cpp-2350/CMakeLists.txt new file mode 100644 index 00000000..c7e3c759 --- /dev/null +++ b/2001-2500/2350-Shortest-Impossible-Sequence-of-Rolls/cpp-2350/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_2350) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2350 main.cpp) diff --git a/2001-2500/2350-Shortest-Impossible-Sequence-of-Rolls/cpp-2350/main.cpp b/2001-2500/2350-Shortest-Impossible-Sequence-of-Rolls/cpp-2350/main.cpp new file mode 100644 index 00000000..8bbb252d --- /dev/null +++ b/2001-2500/2350-Shortest-Impossible-Sequence-of-Rolls/cpp-2350/main.cpp @@ -0,0 +1,39 @@ +/// Source : https://leetcode.com/problems/shortest-impossible-sequence-of-rolls/ +/// Author : liuyubobobo +/// Time : 2022-07-23 + +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(n + k) +/// Space Compelxity: O(k) +class Solution { +public: + int shortestSequence(vector& rolls, int k) { + + vector used(k + 1, false); + int cnt = 0, res = 0; + for(int e: rolls){ + if(!used[e]){ + used[e] = true; + cnt ++; + if(cnt == k){ + res ++; + used.assign(k + 1, false); + cnt = 0; + } + } + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2351-First-Letter-to-Appear-Twice/cpp-2351/CMakeLists.txt b/2001-2500/2351-First-Letter-to-Appear-Twice/cpp-2351/CMakeLists.txt new file mode 100644 index 00000000..fe8bfd9f --- /dev/null +++ b/2001-2500/2351-First-Letter-to-Appear-Twice/cpp-2351/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/2001-2500/2351-First-Letter-to-Appear-Twice/cpp-2351/main.cpp b/2001-2500/2351-First-Letter-to-Appear-Twice/cpp-2351/main.cpp new file mode 100644 index 00000000..a4f05879 --- /dev/null +++ b/2001-2500/2351-First-Letter-to-Appear-Twice/cpp-2351/main.cpp @@ -0,0 +1,31 @@ +/// Source : https://leetcode.com/problems/first-letter-to-appear-twice/ +/// Author : liuyubobobo +/// Time : 2022-07-23 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + char repeatedCharacter(string s) { + + vector f(26, 0); + for(char c: s){ + f[c - 'a'] ++; + if(f[c - 'a'] == 2) return c; + } + return 'a'; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2352-Equal-Row-and-Column-Pairs/cpp-2352/CMakeLists.txt b/2001-2500/2352-Equal-Row-and-Column-Pairs/cpp-2352/CMakeLists.txt new file mode 100644 index 00000000..8494c320 --- /dev/null +++ b/2001-2500/2352-Equal-Row-and-Column-Pairs/cpp-2352/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/2001-2500/2352-Equal-Row-and-Column-Pairs/cpp-2352/main.cpp b/2001-2500/2352-Equal-Row-and-Column-Pairs/cpp-2352/main.cpp new file mode 100644 index 00000000..994b9d23 --- /dev/null +++ b/2001-2500/2352-Equal-Row-and-Column-Pairs/cpp-2352/main.cpp @@ -0,0 +1,36 @@ +/// Source : https://leetcode.com/problems/equal-row-and-column-pairs/ +/// Author : liuyubobobo +/// Time : 2022-07-23 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n^3) +/// Space Complexity: O(n^2) +class Solution { +public: + int equalPairs(vector>& grid) { + + int n = grid.size(); + + vector> cols(n, vector(n)); + for(int j = 0; j < n; j ++) + for(int i = 0; i < n; i ++) cols[j][i] = grid[i][j]; + + int res = 0; + for(int i = 0; i < n; i ++) + for(int j = 0; j < n; j ++) + res += grid[i] == cols[j]; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2353-Design-a-Food-Rating-System/cpp-2353/CMakeLists.txt b/2001-2500/2353-Design-a-Food-Rating-System/cpp-2353/CMakeLists.txt new file mode 100644 index 00000000..830d3093 --- /dev/null +++ b/2001-2500/2353-Design-a-Food-Rating-System/cpp-2353/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/2001-2500/2353-Design-a-Food-Rating-System/cpp-2353/main.cpp b/2001-2500/2353-Design-a-Food-Rating-System/cpp-2353/main.cpp new file mode 100644 index 00000000..4966922e --- /dev/null +++ b/2001-2500/2353-Design-a-Food-Rating-System/cpp-2353/main.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/design-a-food-rating-system/ +/// Author : liuyubobobo +/// Time : 2022-07-23 + +#include +#include +#include +#include + +using namespace std; + + +/// Using Map +/// Time Complexity: O(logn) for every operation +/// Space Complexity: O(n) +class FoodRatings { + +private: + map>> tree; + map> food; + +public: + FoodRatings(vector& foods, vector& cuisines, vector& ratings) { + + int n = foods.size(); + for(int i = 0; i < n; i ++){ + food[foods[i]] = {cuisines[i], ratings[i]}; + tree[cuisines[i]][ratings[i]].insert(foods[i]); + } + } + + void changeRating(string food_name, int newRating) { + + pair p = food[food_name]; + string cuision = p.first; + int oldRating = p.second; + + tree[cuision][oldRating].erase(food_name); + if(tree[cuision][oldRating].empty()) tree[cuision].erase(oldRating); + tree[cuision][newRating].insert(food_name); + + food[food_name].second = newRating; + } + + string highestRated(string cuisine) { + return *(tree[cuisine].rbegin()->second.begin()); + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2354-Number-of-Excellent-Pairs/cpp-2354/CMakeLists.txt b/2001-2500/2354-Number-of-Excellent-Pairs/cpp-2354/CMakeLists.txt new file mode 100644 index 00000000..9a6c5c78 --- /dev/null +++ b/2001-2500/2354-Number-of-Excellent-Pairs/cpp-2354/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) diff --git a/2001-2500/2354-Number-of-Excellent-Pairs/cpp-2354/main.cpp b/2001-2500/2354-Number-of-Excellent-Pairs/cpp-2354/main.cpp new file mode 100644 index 00000000..618b64e2 --- /dev/null +++ b/2001-2500/2354-Number-of-Excellent-Pairs/cpp-2354/main.cpp @@ -0,0 +1,67 @@ +/// Source : https://leetcode.com/problems/number-of-excellent-pairs/ +/// Author : liuyubobobo +/// Time : 2022-07-24 + +#include +#include +#include +#include + +using namespace std; + + +/// bitwise +/// Time Compelxity: O(nlogn(max_a)) +/// Space Complexity: O(n) +class Solution { +public: + long long countExcellentPairs(vector& nums, int k) { + + map ones; + for(int e: nums){ + if(ones.count(e)) continue; + ones[e] = get_ones(e); + } + + vector cnt(63, 0); + for(const pair& p: ones) + cnt[p.second] ++; + + for(int i = 61; i >= 0; i --) + cnt[i] += cnt[i + 1]; + + long long res = 0; + for(const pair& p: ones){ + int e = p.first; + int one = p.second; + + int t = max(k - one, 0); + res += cnt[t]; + } + return res; + } + +private: + int get_ones(int e){ + int res = 0; + while(e){ + res ++; + e &= (e - 1); + } + return res; + } +}; + + +int main() { + + vector nums1 = {1, 2, 3, 1}; + cout << Solution().countExcellentPairs(nums1, 3) << '\n'; + // 5 + + vector nums2 = {5, 1, 1}; + cout << Solution().countExcellentPairs(nums2, 10) << '\n'; + // 0 + + return 0; +} diff --git a/2001-2500/2357-Make-Array-Zero-by-Subtracting-Equal-Amounts/cpp-2357/CMakeLists.txt b/2001-2500/2357-Make-Array-Zero-by-Subtracting-Equal-Amounts/cpp-2357/CMakeLists.txt new file mode 100644 index 00000000..fe8bfd9f --- /dev/null +++ b/2001-2500/2357-Make-Array-Zero-by-Subtracting-Equal-Amounts/cpp-2357/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/2001-2500/2357-Make-Array-Zero-by-Subtracting-Equal-Amounts/cpp-2357/main.cpp b/2001-2500/2357-Make-Array-Zero-by-Subtracting-Equal-Amounts/cpp-2357/main.cpp new file mode 100644 index 00000000..da12316b --- /dev/null +++ b/2001-2500/2357-Make-Array-Zero-by-Subtracting-Equal-Amounts/cpp-2357/main.cpp @@ -0,0 +1,30 @@ +/// Source : https://leetcode.com/problems/make-array-zero-by-subtracting-equal-amounts/ +/// Author : liuyubobobo +/// Time : 2022-07-31 + +#include +#include +#include + +using namespace std; + + +/// Using Set +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int minimumOperations(vector& nums) { + + set s; + for(int e: nums) + if(e) s.insert(e); + return s.size(); + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2358-Maximum-Number-of-Groups-Entering-a-Competition/cpp-2358/CMakeLists.txt b/2001-2500/2358-Maximum-Number-of-Groups-Entering-a-Competition/cpp-2358/CMakeLists.txt new file mode 100644 index 00000000..8e458b10 --- /dev/null +++ b/2001-2500/2358-Maximum-Number-of-Groups-Entering-a-Competition/cpp-2358/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main3.cpp) diff --git a/2001-2500/2358-Maximum-Number-of-Groups-Entering-a-Competition/cpp-2358/main.cpp b/2001-2500/2358-Maximum-Number-of-Groups-Entering-a-Competition/cpp-2358/main.cpp new file mode 100644 index 00000000..71a4c7ee --- /dev/null +++ b/2001-2500/2358-Maximum-Number-of-Groups-Entering-a-Competition/cpp-2358/main.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/maximum-number-of-groups-entering-a-competition/ +/// Author : liuyubobobo +/// Time : 2022-07-31 + +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(sqrt(n)) +/// Space Complexity: O(1) +class Solution { +public: + int maximumGroups(vector& grades) { + + int n = grades.size(); + for(int k = 1; ;k ++) + if((1 + k) * k / 2 >= n){ + return ((1 + k) * k / 2 == n) ? k : (k - 1); + } + return 0; + } +}; + + +int main() { + + vector x = {10,6,12,7,3,5}; + cout << Solution().maximumGroups(x) << '\n'; + // 3 + + return 0; +} diff --git a/2001-2500/2358-Maximum-Number-of-Groups-Entering-a-Competition/cpp-2358/main2.cpp b/2001-2500/2358-Maximum-Number-of-Groups-Entering-a-Competition/cpp-2358/main2.cpp new file mode 100644 index 00000000..ba052441 --- /dev/null +++ b/2001-2500/2358-Maximum-Number-of-Groups-Entering-a-Competition/cpp-2358/main2.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/maximum-number-of-groups-entering-a-competition/ +/// Author : liuyubobobo +/// Time : 2022-07-31 + +#include +#include + +using namespace std; + + +/// Greedy + Binary Search +/// Time Complexity: O(log(n)) +/// Space Complexity: O(1) +class Solution { +public: + int maximumGroups(vector& grades) { + + int n = grades.size(); + int l = 1, r = n; + while(l < r){ + int mid = (l + r + 1) / 2; + if((1ll + mid) * mid / 2 <= n) l = mid; + else r = mid - 1; + } + return l; + } +}; + + +int main() { + + vector x = {10,6,12,7,3,5}; + cout << Solution().maximumGroups(x) << '\n'; + // 3 + + return 0; +} diff --git a/2001-2500/2358-Maximum-Number-of-Groups-Entering-a-Competition/cpp-2358/main3.cpp b/2001-2500/2358-Maximum-Number-of-Groups-Entering-a-Competition/cpp-2358/main3.cpp new file mode 100644 index 00000000..1a851fa7 --- /dev/null +++ b/2001-2500/2358-Maximum-Number-of-Groups-Entering-a-Competition/cpp-2358/main3.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/maximum-number-of-groups-entering-a-competition/ +/// Author : liuyubobobo +/// Time : 2022-07-31 + +#include +#include + +using namespace std; + + +/// Greedy + Math +/// Time Complexity: O(log(n)) - sqrt is not O(1) +/// Space Complexity: O(1) +class Solution { +public: + int maximumGroups(vector& grades) { + + int n = grades.size(); + // (1 + x) * x / 2 <= n + // x^2 + x - 2 * n <= 0 + + return (int)((sqrt(1.0 + 8 * n) - 1.0) / 2.0); + } +}; + + +int main() { + + vector x = {10,6,12,7,3,5}; + cout << Solution().maximumGroups(x) << '\n'; + // 3 + + return 0; +} diff --git a/2001-2500/2359-Find-Closest-Node-to-Given-Two-Nodes/cpp-2359/CMakeLists.txt b/2001-2500/2359-Find-Closest-Node-to-Given-Two-Nodes/cpp-2359/CMakeLists.txt new file mode 100644 index 00000000..830d3093 --- /dev/null +++ b/2001-2500/2359-Find-Closest-Node-to-Given-Two-Nodes/cpp-2359/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/2001-2500/2359-Find-Closest-Node-to-Given-Two-Nodes/cpp-2359/main.cpp b/2001-2500/2359-Find-Closest-Node-to-Given-Two-Nodes/cpp-2359/main.cpp new file mode 100644 index 00000000..54b3fa22 --- /dev/null +++ b/2001-2500/2359-Find-Closest-Node-to-Given-Two-Nodes/cpp-2359/main.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/find-closest-node-to-given-two-nodes/ +/// Author : liuyubobobo +/// Time : 2022-07-31 + +#include +#include +#include +#include + +using namespace std; + + +/// BFS +/// Time Compelxity: O(n) +/// Space Compelxity: O(n) +class Solution { +public: + int closestMeetingNode(vector& g, int node1, int node2) { + + int n = g.size(); + vector dis1 = bfs(n, g, node1); + vector dis2 = bfs(n, g, node2); + + int best = INT_MAX, res = -1; + for(int u = 0; u < n; u ++){ + if(dis1[u] == -1 || dis2[u] == -1) continue; + int d = max(dis1[u], dis2[u]); + if(d < best) best = d, res = u; + } + return res; + } + +private: + vector bfs(int n, const vector& g, int s){ + + vector dis(n, -1); + + queue q; + q.push(s); + dis[s] = 0; + while(!q.empty()){ + int u = q.front(); q.pop(); + int v = g[u]; + if(v == -1 || dis[v] != -1) continue; + + dis[v] = dis[u] + 1; + q.push(v); + } + return dis; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2360-Longest-Cycle-in-a-Graph/cpp-2360/CMakeLists.txt b/2001-2500/2360-Longest-Cycle-in-a-Graph/cpp-2360/CMakeLists.txt new file mode 100644 index 00000000..9a6c5c78 --- /dev/null +++ b/2001-2500/2360-Longest-Cycle-in-a-Graph/cpp-2360/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) diff --git a/2001-2500/2360-Longest-Cycle-in-a-Graph/cpp-2360/main.cpp b/2001-2500/2360-Longest-Cycle-in-a-Graph/cpp-2360/main.cpp new file mode 100644 index 00000000..2e038676 --- /dev/null +++ b/2001-2500/2360-Longest-Cycle-in-a-Graph/cpp-2360/main.cpp @@ -0,0 +1,78 @@ +/// Source : https://leetcode.com/problems/find-closest-node-to-given-two-nodes/ +/// Author : liuyubobobo +/// Time : 2022-07-31 + +#include +#include + +using namespace std; + + +/// Find Cycle in Successor Graph +/// DFS is ok but I think using UF is more elegant:) +/// Time Compelxity: O(n) +/// Space Compelxity: O(n) +class UF{ + +private: + vector parent; + +public: + UF(int n) : parent(n){ + for(int i = 0 ; i < n ; i ++) + parent[i] = i; + } + + int find(int p){ + if(p != parent[p]) + parent[p] = find(parent[p]); + return parent[p]; + } + + bool is_connected(int p, int q){ + return find(p) == find(q); + } + + void union_elements(int p, int q){ + + int p_root = find(p), q_root = find(q); + + if(p_root == q_root) return; + + parent[p_root] = q_root; + } +}; + +class Solution { +public: + int longestCycle(vector& g) { + + int n = g.size(); + UF uf(n); + + int res = -1; + for(int i = 0; i < n; i ++){ + + if(g[i] == -1) continue; + + if(!uf.is_connected(i, g[i])){ + uf.union_elements(i, g[i]); + continue; + } + + int tres = 1, cur = g[i]; + while(cur != i){ + tres ++; + cur = g[cur]; + } + res = max(res, tres); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2361-Minimum-Costs-Using-the-Train-Line/cpp-2361/CMakeLists.txt b/2001-2500/2361-Minimum-Costs-Using-the-Train-Line/cpp-2361/CMakeLists.txt new file mode 100644 index 00000000..ced61bf5 --- /dev/null +++ b/2001-2500/2361-Minimum-Costs-Using-the-Train-Line/cpp-2361/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_2361) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2361 main.cpp) diff --git a/2001-2500/2361-Minimum-Costs-Using-the-Train-Line/cpp-2361/main.cpp b/2001-2500/2361-Minimum-Costs-Using-the-Train-Line/cpp-2361/main.cpp new file mode 100644 index 00000000..8ff3fdab --- /dev/null +++ b/2001-2500/2361-Minimum-Costs-Using-the-Train-Line/cpp-2361/main.cpp @@ -0,0 +1,43 @@ +/// Source : https://leetcode.com/problems/minimum-costs-using-the-train-line/ +/// Author : liuyubobobo +/// Time : 2022-08-03 + +#include +#include + +using namespace std; + + +/// DP +/// Time Compelxity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector minimumCosts(vector& regular, vector& express, int expressCost) { + + int n = regular.size(); + vector> dp(n + 1, vector(2, 0)); + dp[0][1] = expressCost; + + vector res(n); + for(int i = 1; i <= n; i ++){ + dp[i][0] = min(dp[i - 1][0] + regular[i - 1], dp[i - 1][1] + express[i - 1]); + dp[i][1] = min(dp[i - 1][0] + regular[i - 1] + expressCost, dp[i - 1][1] + express[i - 1]); + res[i - 1] = min(dp[i][0], dp[i][1]); + } + return res; + } +}; + + +void print_vec(const vector& res){ + for(long long e: res) cout << e << ' '; cout << '\n'; +} + +int main() { + + vector regular1 = {1, 6, 9, 5}, express1 = {5, 2, 3, 10}; + print_vec(Solution().minimumCosts(regular1, express1, 8)); + + return 0; +} diff --git a/2001-2500/2363-Merge-Similar-Items/cpp-2363/CMakeLists.txt b/2001-2500/2363-Merge-Similar-Items/cpp-2363/CMakeLists.txt new file mode 100644 index 00000000..db600bb0 --- /dev/null +++ b/2001-2500/2363-Merge-Similar-Items/cpp-2363/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_2363) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2363 main.cpp) diff --git a/2001-2500/2363-Merge-Similar-Items/cpp-2363/main.cpp b/2001-2500/2363-Merge-Similar-Items/cpp-2363/main.cpp new file mode 100644 index 00000000..dfeb2abb --- /dev/null +++ b/2001-2500/2363-Merge-Similar-Items/cpp-2363/main.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/merge-similar-items/ +/// Author : liuyubobobo +/// Time : 2022-08-10 + +#include +#include +#include + +using namespace std; + + +/// Using Map +/// Time Complexity: O(|items1| + |items2|) +/// Space Complexity: O(|items1| + |items2|) +class Solution { +public: + vector> mergeSimilarItems(vector>& items1, vector>& items2) { + + map table; + for(const vector& item: items1){ + int v = item[0], w = item[1]; + table[v] += w; + } + for(const vector& item: items2){ + int v = item[0], w = item[1]; + table[v] += w; + } + + vector> res; + for(const pair& p: table) + res.push_back({p.first, p.second}); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2364-Count-Number-of-Bad-Pairs/cpp-2364/CMakeLists.txt b/2001-2500/2364-Count-Number-of-Bad-Pairs/cpp-2364/CMakeLists.txt new file mode 100644 index 00000000..df01c77a --- /dev/null +++ b/2001-2500/2364-Count-Number-of-Bad-Pairs/cpp-2364/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_2364) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2364 main.cpp) diff --git a/2001-2500/2364-Count-Number-of-Bad-Pairs/cpp-2364/main.cpp b/2001-2500/2364-Count-Number-of-Bad-Pairs/cpp-2364/main.cpp new file mode 100644 index 00000000..b7a1bde0 --- /dev/null +++ b/2001-2500/2364-Count-Number-of-Bad-Pairs/cpp-2364/main.cpp @@ -0,0 +1,39 @@ +/// Source : https://leetcode.com/problems/count-number-of-bad-pairs/ +/// Author : liuyubobobo +/// Time : 2022-08-10 + +#include +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + long long countBadPairs(vector& nums) { + + int n = nums.size(); + for(int i = 0; i < n; i ++) + nums[i] -= i; + + map f; + for(int e: nums) f[e] ++; + + long long res = 1ll * n * (n - 1) / 2ll; + for(const pair& p: f){ + long long len = p.second; + res -= len * (len - 1) / 2ll; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2365-Task-Scheduler-II/cpp-2365/CMakeLists.txt b/2001-2500/2365-Task-Scheduler-II/cpp-2365/CMakeLists.txt new file mode 100644 index 00000000..0c690275 --- /dev/null +++ b/2001-2500/2365-Task-Scheduler-II/cpp-2365/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_2365) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2365 main.cpp) diff --git a/2001-2500/2365-Task-Scheduler-II/cpp-2365/main.cpp b/2001-2500/2365-Task-Scheduler-II/cpp-2365/main.cpp new file mode 100644 index 00000000..785f1349 --- /dev/null +++ b/2001-2500/2365-Task-Scheduler-II/cpp-2365/main.cpp @@ -0,0 +1,45 @@ +/// Source : https://leetcode.com/problems/task-scheduler-ii/ +/// Author : liuyubobobo +/// Time : 2022-08-10 + +#include +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + long long taskSchedulerII(vector& tasks, int space) { + + map last; + long long cur = 1; + for(int task: tasks){ + if(!last.count(task)){ + last[task] = cur; + cur ++; + continue; + } + + long long pre = last[task]; + long long next = max(pre + space + 1, cur); + last[task] = next; + cur = next + 1; + } + return cur - 1; + } +}; + + +int main() { + + vector tasks1 = {1, 2, 1, 2, 3, 1}; + cout << Solution().taskSchedulerII(tasks1, 3) << '\n'; + // 9 + + return 0; +} diff --git a/2001-2500/2366-Minimum-Replacements-to-Sort-the-Array/cpp-2366/CMakeLists.txt b/2001-2500/2366-Minimum-Replacements-to-Sort-the-Array/cpp-2366/CMakeLists.txt new file mode 100644 index 00000000..267c7c7b --- /dev/null +++ b/2001-2500/2366-Minimum-Replacements-to-Sort-the-Array/cpp-2366/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_2366) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2366 main.cpp) diff --git a/2001-2500/2366-Minimum-Replacements-to-Sort-the-Array/cpp-2366/main.cpp b/2001-2500/2366-Minimum-Replacements-to-Sort-the-Array/cpp-2366/main.cpp new file mode 100644 index 00000000..22375802 --- /dev/null +++ b/2001-2500/2366-Minimum-Replacements-to-Sort-the-Array/cpp-2366/main.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/minimum-replacements-to-sort-the-array/ +/// Author : liuyubobobo +/// Time : 2022-08-10 + +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + long long minimumReplacement(vector& nums) { + + int n = nums.size(); + + long long res = 0; + int p = nums.back(); + for(int i = n - 2; i >= 0; i --){ + if(nums[i] <= p){ + p = min(p, nums[i]); + continue; + } + + int cnt = nums[i] / p; + int mod = nums[i] % p; + if(mod) cnt ++; + + res += (cnt - 1); + p = min(p, nums[i] / cnt); + } + return res; + } +}; + + +int main() { + + vector nums1 = {12,9,7,6,17,19,21}; + cout << Solution().minimumReplacement(nums1) << '\n'; + // 6 + + return 0; +} diff --git a/2001-2500/2367-Number-of-Arithmetic-Triplets/cpp-2367/CMakeLists.txt b/2001-2500/2367-Number-of-Arithmetic-Triplets/cpp-2367/CMakeLists.txt new file mode 100644 index 00000000..39483f78 --- /dev/null +++ b/2001-2500/2367-Number-of-Arithmetic-Triplets/cpp-2367/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_2367) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2367 main.cpp) diff --git a/2001-2500/2367-Number-of-Arithmetic-Triplets/cpp-2367/main.cpp b/2001-2500/2367-Number-of-Arithmetic-Triplets/cpp-2367/main.cpp new file mode 100644 index 00000000..34b94eff --- /dev/null +++ b/2001-2500/2367-Number-of-Arithmetic-Triplets/cpp-2367/main.cpp @@ -0,0 +1,31 @@ +/// Source : https://leetcode.com/problems/number-of-arithmetic-triplets/ +/// Author : liuyubobobo +/// Time : 2022-08-07 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n^3) +/// Space Complexity: O(1) +class Solution { +public: + int arithmeticTriplets(vector& nums, int diff) { + + int n = nums.size(), res = 0; + for(int i = 0; i < n; i ++) + for(int j = i + 1; j < n; j ++) + for(int k = j + 1; k < n; k ++) + res += (nums[k] - nums[j] == diff && nums[j] - nums[i] == diff); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2368-Reachable-Nodes-With-Restrictions/cpp-2368/CMakeLists.txt b/2001-2500/2368-Reachable-Nodes-With-Restrictions/cpp-2368/CMakeLists.txt new file mode 100644 index 00000000..12a01851 --- /dev/null +++ b/2001-2500/2368-Reachable-Nodes-With-Restrictions/cpp-2368/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_2368) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2368 main.cpp) diff --git a/2001-2500/2368-Reachable-Nodes-With-Restrictions/cpp-2368/main.cpp b/2001-2500/2368-Reachable-Nodes-With-Restrictions/cpp-2368/main.cpp new file mode 100644 index 00000000..3fd377e5 --- /dev/null +++ b/2001-2500/2368-Reachable-Nodes-With-Restrictions/cpp-2368/main.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/reachable-nodes-with-restrictions/ +/// Author : liuyubobobo +/// Time : 2022-08-10 + +#include +#include +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int reachableNodes(int n, vector>& edges, vector& restricted) { + + set restricted_set(restricted.begin(), restricted.end()); + + vector> tree(n); + for(const vector& p: edges){ + int u = p[0], v = p[1]; + tree[u].push_back(v), tree[v].push_back(u); + } + + return dfs(tree, 0, -1, restricted_set); + } + +private: + int dfs(const vector>& tree, int u, int p, set& restricted_set){ + + if(restricted_set.count(u)) return 0; + + int res = 1; + for(int v: tree[u]){ + if(v == p) continue; + res += dfs(tree, v, u, restricted_set); + } + return res; + } +}; + + +int main() { + + + return 0; +} diff --git a/2001-2500/2369-Check-if-There-is-a-Valid-Partition-For-The-Array/cpp-2369/CMakeLists.txt b/2001-2500/2369-Check-if-There-is-a-Valid-Partition-For-The-Array/cpp-2369/CMakeLists.txt new file mode 100644 index 00000000..d1a89ba9 --- /dev/null +++ b/2001-2500/2369-Check-if-There-is-a-Valid-Partition-For-The-Array/cpp-2369/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_2369) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2369 main.cpp) diff --git a/2001-2500/2369-Check-if-There-is-a-Valid-Partition-For-The-Array/cpp-2369/main.cpp b/2001-2500/2369-Check-if-There-is-a-Valid-Partition-For-The-Array/cpp-2369/main.cpp new file mode 100644 index 00000000..c94f1d3b --- /dev/null +++ b/2001-2500/2369-Check-if-There-is-a-Valid-Partition-For-The-Array/cpp-2369/main.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/check-if-there-is-a-valid-partition-for-the-array/ +/// Author : liuyubobobo +/// Time : 2022-08-10 + +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + bool validPartition(vector& nums) { + + int n = nums.size(); + + vector dp(n + 1, false); + dp[0] = true; + dp[2] = (nums[1] == nums[0]); + + for(int i = 2; i < n; i ++){ + if(nums[i] == nums[i - 1] && dp[i - 2 + 1]) + dp[i + 1] = true; + if(nums[i] == nums[i - 1] && nums[i - 1] == nums[i - 2] && dp[i - 3 + 1]) + dp[i + 1] = true; + if(nums[i] - nums[i - 1] == 1 && nums[i - 1] - nums[i - 2] == 1 && dp[i - 3 + 1]) + dp[i + 1] = true; + } + return dp[n]; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2370-Longest-Ideal-Subsequence/cpp-2370/CMakeLists.txt b/2001-2500/2370-Longest-Ideal-Subsequence/cpp-2370/CMakeLists.txt new file mode 100644 index 00000000..0215df13 --- /dev/null +++ b/2001-2500/2370-Longest-Ideal-Subsequence/cpp-2370/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_2370) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2370 main.cpp) diff --git a/2001-2500/2370-Longest-Ideal-Subsequence/cpp-2370/main.cpp b/2001-2500/2370-Longest-Ideal-Subsequence/cpp-2370/main.cpp new file mode 100644 index 00000000..cd22d159 --- /dev/null +++ b/2001-2500/2370-Longest-Ideal-Subsequence/cpp-2370/main.cpp @@ -0,0 +1,39 @@ +/// Source : https://leetcode.com/problems/longest-ideal-subsequence/ +/// Author : liuyubobobo +/// Time : 2022-08-10 + +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int longestIdealString(string s, int k) { + + vector dp(26, 0); + for(char c: s){ + int res = 0; + for(char end = max(c - k, (int)'a'); end <= min(c + k, (int)'z'); end ++) + res = max(res, dp[end - 'a'] + 1); + dp[c - 'a'] = max(dp[c - 'a'], res); + } + return *max_element(dp.begin(), dp.end()); + } +}; + + +int main() { + + cout << Solution().longestIdealString("acfgbd", 2) << '\n'; + // 4 + + cout << Solution().longestIdealString("jxhwaysa", 14) << '\n'; + // 5 + + return 0; +} diff --git a/2001-2500/2373-Largest-Local-Values-in-a-Matrix/cpp-2373/CMakeLists.txt b/2001-2500/2373-Largest-Local-Values-in-a-Matrix/cpp-2373/CMakeLists.txt new file mode 100644 index 00000000..415e0a92 --- /dev/null +++ b/2001-2500/2373-Largest-Local-Values-in-a-Matrix/cpp-2373/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/2001-2500/2373-Largest-Local-Values-in-a-Matrix/cpp-2373/main.cpp b/2001-2500/2373-Largest-Local-Values-in-a-Matrix/cpp-2373/main.cpp new file mode 100644 index 00000000..d506ef05 --- /dev/null +++ b/2001-2500/2373-Largest-Local-Values-in-a-Matrix/cpp-2373/main.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/largest-local-values-in-a-matrix/ +/// Author : liuyubobobo +/// Time : 2022-08-13 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n^2) +/// Space Complexity: O(1) +class Solution { +public: + vector> largestLocal(vector>& grid) { + + int n = grid.size(); + + vector> res(n - 2, vector(n - 2)); + for(int i = 1; i + 1 < n; i ++) + for(int j = 1; j + 1 < n; j ++){ + int t = 0; + for(int d1 = -1; d1 <= 1; d1 ++) + for(int d2 = -1; d2 <= 1; d2 ++) + t = max(t, grid[i + d1][j + d2]); + res[i - 1][j - 1] = t; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2374-Node-With-Highest-Edge-Score/cpp-2374/CMakeLists.txt b/2001-2500/2374-Node-With-Highest-Edge-Score/cpp-2374/CMakeLists.txt new file mode 100644 index 00000000..b1c82ab8 --- /dev/null +++ b/2001-2500/2374-Node-With-Highest-Edge-Score/cpp-2374/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/2001-2500/2374-Node-With-Highest-Edge-Score/cpp-2374/main.cpp b/2001-2500/2374-Node-With-Highest-Edge-Score/cpp-2374/main.cpp new file mode 100644 index 00000000..9d9fd3ea --- /dev/null +++ b/2001-2500/2374-Node-With-Highest-Edge-Score/cpp-2374/main.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/node-with-highest-edge-score/ +/// Author : liuyubobobo +/// Time : 2022-08-13 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int edgeScore(vector& edges) { + + int n = edges.size(); + vector score(n, 0); + for(int u = 0; u < n; u ++) + score[edges[u]] += u; + + long long best = score[0]; + int res = 0; + for(int u = 1; u < n; u ++) + if(score[u] > best) best = score[u], res = u; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2375-Construct-Smallest-Number-From-DI-String/cpp-2375/CMakeLists.txt b/2001-2500/2375-Construct-Smallest-Number-From-DI-String/cpp-2375/CMakeLists.txt new file mode 100644 index 00000000..d0dc1506 --- /dev/null +++ b/2001-2500/2375-Construct-Smallest-Number-From-DI-String/cpp-2375/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/2001-2500/2375-Construct-Smallest-Number-From-DI-String/cpp-2375/main.cpp b/2001-2500/2375-Construct-Smallest-Number-From-DI-String/cpp-2375/main.cpp new file mode 100644 index 00000000..c887b5bf --- /dev/null +++ b/2001-2500/2375-Construct-Smallest-Number-From-DI-String/cpp-2375/main.cpp @@ -0,0 +1,63 @@ +/// Source : https://leetcode.com/problems/construct-smallest-number-from-di-string/ +/// Author : liuyubobobo +/// Time : 2022-08-13 + +#include +#include + +using namespace std; + + +/// Backtrck +/// Time Complexity: O(|pattern|!) +/// Space Complexity: O(|pattern|) +class Solution { +public: + string smallestNumber(string pattern) { + + int n = pattern.size(); + string res(n + 1, '0'); + for(int d = 1; d <= 9; d ++){ + res[0] = (char)('0' + d); + if(dfs(pattern, 0, res, 1 << d)) + break; + } + return res; + } + +private: + bool dfs(const string& pattern, int index, string& res, int state){ + + if(index == pattern.size()) return true; + + if(pattern[index] == 'I'){ + for(int d = res[index] - '0' + 1; d <= 9; d ++){ + if((state & (1 << d)) == 0){ + res[index + 1] = (char)('0' + d); + if(dfs(pattern, index + 1, res, state | (1 << d))) return true; + } + } + } + else{ + for(int d = 1; d < res[index] - '0'; d ++){ + if((state & (1 << d)) == 0){ + res[index + 1] = (char)('0' + d); + if(dfs(pattern, index + 1, res, state | (1 << d))) return true; + } + } + } + return false; + } +}; + + +int main() { + + cout << Solution().smallestNumber("IIIDIDDD") << '\n'; + // 123549876 + + cout << Solution().smallestNumber("DDD") << '\n'; + // 4321 + + return 0; +} diff --git a/2001-2500/2376-Count-Special-Integers/cpp-2376/CMakeLists.txt b/2001-2500/2376-Count-Special-Integers/cpp-2376/CMakeLists.txt new file mode 100644 index 00000000..8148fadd --- /dev/null +++ b/2001-2500/2376-Count-Special-Integers/cpp-2376/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) diff --git a/2001-2500/2376-Count-Special-Integers/cpp-2376/main.cpp b/2001-2500/2376-Count-Special-Integers/cpp-2376/main.cpp new file mode 100644 index 00000000..31b5297d --- /dev/null +++ b/2001-2500/2376-Count-Special-Integers/cpp-2376/main.cpp @@ -0,0 +1,63 @@ +/// Source : https://leetcode.com/problems/count-special-integers/ +/// Author : liuyubobobo +/// Time : 2022-08-13 + +#include +#include + +using namespace std; + + +/// Digital DP +/// Time Complexity: O(|s| * 2^|s|) where s is the string of n +/// Space Complexity: O(|s| * 2^|s|) +class Solution { +public: + int countSpecialNumbers(int n) { + + string s = to_string(n); + + long long res = 0; + for(int len = 1; len <= s.size(); len ++){ + vector>> dp(len, vector>(2, vector(1024, -1))); + res += dfs(len == s.size() ? s : string(len, '9'), 0, false, 0, dp); + } + return res; + } + +private: + long long dfs(const string& s, int index, bool can_up, int state, + vector>>& dp){ + + if(index == s.size()) return 1ll; + if(dp[index][can_up][state] != -1) return dp[index][can_up][state]; + + long long res = 0; + if(can_up){ + for(int d = (index == 0 ? 1 : 0); d <= 9; d ++) + if((state & (1 << d)) == 0) + res += dfs(s, index + 1, can_up, state | (1 << d), dp); + } + else{ + for(int d = (index == 0 ? 1 : 0); d <= s[index] - '0'; d ++) + if((state & (1 << d)) == 0) + res += dfs(s, index + 1, d < s[index] - '0', state | (1 << d), dp); + } + return dp[index][can_up][state] = res; + } +}; + + +int main() { + + cout << Solution().countSpecialNumbers(20) << '\n'; + // 19 + + cout << Solution().countSpecialNumbers(5) << '\n'; + // 5 + + cout << Solution().countSpecialNumbers(135) << '\n'; + // 110 + + return 0; +} diff --git a/2001-2500/2378-Choose-Edges-to-Maximize-Score-in-a-Tree/cpp-2378/CMakeLists.txt b/2001-2500/2378-Choose-Edges-to-Maximize-Score-in-a-Tree/cpp-2378/CMakeLists.txt new file mode 100644 index 00000000..485fca8f --- /dev/null +++ b/2001-2500/2378-Choose-Edges-to-Maximize-Score-in-a-Tree/cpp-2378/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_2378) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2378 main.cpp) diff --git a/2001-2500/2378-Choose-Edges-to-Maximize-Score-in-a-Tree/cpp-2378/main.cpp b/2001-2500/2378-Choose-Edges-to-Maximize-Score-in-a-Tree/cpp-2378/main.cpp new file mode 100644 index 00000000..de88f1c6 --- /dev/null +++ b/2001-2500/2378-Choose-Edges-to-Maximize-Score-in-a-Tree/cpp-2378/main.cpp @@ -0,0 +1,63 @@ +/// Source : https://leetcode.com/problems/choose-edges-to-maximize-score-in-a-tree/ +/// Author : liuyubobobo +/// Time : 2022-08-19 + +#include +#include +#include +#include + +using namespace std; + + +/// Tree DP +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + long long maxScore(vector>& edges) { + + int n = edges.size(); + vector>> tree(n); + + for(int i = 1; i < n; i ++){ + int p = edges[i][0]; + long long w = edges[i][1]; + tree[p].push_back({i, w}); + } + + vector> dp(2, vector(n, -1)); + return dfs(tree, 1, 0, dp); + } + +private: + long long dfs(const vector>>& tree, + int can_choose, int u, vector>& dp){ + + if(dp[can_choose][u] != -1) return dp[can_choose][u]; + + long long sum = 0; + for (const pair &p: tree[u]) + sum += dfs(tree, 1, p.first, dp); + + if(can_choose == 0) { + return dp[can_choose][u] = sum; + } + + long long res = sum; + for(const pair& p: tree[u]){ + long long tres = sum; + tres += p.second; + tres -= dfs(tree, 1, p.first, dp); + tres += dfs(tree, 0, p.first, dp); + res = max(res, tres); + } + return dp[can_choose][u] = res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2379-Minimum-Recolors-to-Get-K-Consecutive-Black-Blocks/cpp-2379/CMakeLists.txt b/2001-2500/2379-Minimum-Recolors-to-Get-K-Consecutive-Black-Blocks/cpp-2379/CMakeLists.txt new file mode 100644 index 00000000..4741167f --- /dev/null +++ b/2001-2500/2379-Minimum-Recolors-to-Get-K-Consecutive-Black-Blocks/cpp-2379/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main2.cpp) diff --git a/2001-2500/2379-Minimum-Recolors-to-Get-K-Consecutive-Black-Blocks/cpp-2379/main.cpp b/2001-2500/2379-Minimum-Recolors-to-Get-K-Consecutive-Black-Blocks/cpp-2379/main.cpp new file mode 100644 index 00000000..ac8165ff --- /dev/null +++ b/2001-2500/2379-Minimum-Recolors-to-Get-K-Consecutive-Black-Blocks/cpp-2379/main.cpp @@ -0,0 +1,36 @@ +/// Source : https://leetcode.com/problems/minimum-recolors-to-get-k-consecutive-black-blocks/ +/// Author : liuyubobobo +/// Time : 2022-08-20 + +#include +#include +#include + +using namespace std; + + +/// Presum +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int minimumRecolors(string blocks, int k) { + + int n = blocks.size(); + vector presum(n + 1, 0); + for(int i = 0; i < n; i ++) presum[i + 1] = presum[i] + (blocks[i] == 'B'); + + int res = INT_MAX; + for(int start = 0; start + k <= n; start ++){ + int b = presum[start + k] - presum[start]; + res = min(res, k - b); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2379-Minimum-Recolors-to-Get-K-Consecutive-Black-Blocks/cpp-2379/main2.cpp b/2001-2500/2379-Minimum-Recolors-to-Get-K-Consecutive-Black-Blocks/cpp-2379/main2.cpp new file mode 100644 index 00000000..ade1d695 --- /dev/null +++ b/2001-2500/2379-Minimum-Recolors-to-Get-K-Consecutive-Black-Blocks/cpp-2379/main2.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/minimum-recolors-to-get-k-consecutive-black-blocks/ +/// Author : liuyubobobo +/// Time : 2022-08-20 + +#include +#include +#include + +using namespace std; + + +/// Sliding Window +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int minimumRecolors(string blocks, int k) { + + int n = blocks.size(); + int b = 0; + for(int i = 0; i + 1 < k; i ++) b += blocks[i] == 'B'; + + int res = INT_MAX; + for(int i = k - 1; i < n; i ++){ + b += blocks[i] == 'B'; + res = min(res, k - b); + b -= blocks[i - (k - 1)] == 'B'; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2380-Time-Needed-to-Rearrange-a-Binary-String/cpp-2380/CMakeLists.txt b/2001-2500/2380-Time-Needed-to-Rearrange-a-Binary-String/cpp-2380/CMakeLists.txt new file mode 100644 index 00000000..b1c82ab8 --- /dev/null +++ b/2001-2500/2380-Time-Needed-to-Rearrange-a-Binary-String/cpp-2380/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/2001-2500/2380-Time-Needed-to-Rearrange-a-Binary-String/cpp-2380/main.cpp b/2001-2500/2380-Time-Needed-to-Rearrange-a-Binary-String/cpp-2380/main.cpp new file mode 100644 index 00000000..74d9f61e --- /dev/null +++ b/2001-2500/2380-Time-Needed-to-Rearrange-a-Binary-String/cpp-2380/main.cpp @@ -0,0 +1,43 @@ +/// Source : https://leetcode.com/problems/time-needed-to-rearrange-a-binary-string/ +/// Author : liuyubobobo +/// Time : 2022-08-20 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n^2) +/// Space Complexity: O(1) +class Solution { +public: + int secondsToRemoveOccurrences(string s) { + + int n = s.size(), res = 0; + while(true){ + + bool changed = false; + for(int i = 0; i + 1 < n; i ++) + if(s[i] == '0' && s[i + 1] == '1'){ + s[i] = '1', s[i + 1] = '0'; + i ++; + changed = true; + } + + if(!changed) break; + res ++; + } + return res; + } +}; + + +int main() { + + cout << Solution().secondsToRemoveOccurrences("0110101") << '\n'; + // 4 + + return 0; +} diff --git a/2001-2500/2381-Shifting-Letters-II/cpp-2381/CMakeLists.txt b/2001-2500/2381-Shifting-Letters-II/cpp-2381/CMakeLists.txt new file mode 100644 index 00000000..d0dc1506 --- /dev/null +++ b/2001-2500/2381-Shifting-Letters-II/cpp-2381/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/2001-2500/2381-Shifting-Letters-II/cpp-2381/main.cpp b/2001-2500/2381-Shifting-Letters-II/cpp-2381/main.cpp new file mode 100644 index 00000000..0d0c2d11 --- /dev/null +++ b/2001-2500/2381-Shifting-Letters-II/cpp-2381/main.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/shifting-letters-ii/ +/// Author : liuyubobobo +/// Time : 2022-08-20 + +#include +#include + +using namespace std; + + +/// Diff Array +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + string shiftingLetters(string s, vector>& shifts) { + + int n = s.size(); + vector diff_array(n + 1, 0); + for(const vector& shift: shifts){ + int start = shift[0], end = shift[1], d = shift[2]; + if(d == 0) d = -1; + diff_array[start] += d, diff_array[end + 1] -= d; + } + + string res = ""; + int cur = 0; + for(int i = 0; i < n; i ++){ + cur += diff_array[i]; + + int d = cur; + if(d < 0) d = d % 26 + 26; + else d %= 26; + + int c = (s[i] - 'a' + d) % 26; + res += (char)('a' + c); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2382-Maximum-Segment-Sum-After-Removals/cpp-2382/CMakeLists.txt b/2001-2500/2382-Maximum-Segment-Sum-After-Removals/cpp-2382/CMakeLists.txt new file mode 100644 index 00000000..541b2eff --- /dev/null +++ b/2001-2500/2382-Maximum-Segment-Sum-After-Removals/cpp-2382/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main2.cpp) diff --git a/2001-2500/2382-Maximum-Segment-Sum-After-Removals/cpp-2382/main.cpp b/2001-2500/2382-Maximum-Segment-Sum-After-Removals/cpp-2382/main.cpp new file mode 100644 index 00000000..06e1b3ff --- /dev/null +++ b/2001-2500/2382-Maximum-Segment-Sum-After-Removals/cpp-2382/main.cpp @@ -0,0 +1,122 @@ +/// Source : https://leetcode.com/problems/maximum-segment-sum-after-removals/ +/// Author : liuyubobobo +/// Time : 2022-08-20 + +#include +#include +#include +#include + +using namespace std; + + +/// UF +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class UF{ + +private: + vector parent; + +public: + UF(int n) : parent(n){ + for(int i = 0 ; i < n ; i ++) + parent[i] = i; + } + + int find(int p){ + if(p != parent[p]) + parent[p] = find(parent[p]); + return parent[p]; + } + + bool is_connected(int p, int q){ + return find(p) == find(q); + } + + void union_elements(int p, int q){ + + int p_root = find(p), q_root = find(q); + + if(p_root == q_root) return; + + parent[p_root] = q_root; + } +}; + +class Solution { +public: + vector maximumSegmentSum(vector& nums, vector& removeQueries) { + + int n = nums.size(); + + vector v(n); + for(int i = 0; i < n; i ++) v[i] = nums[i]; + + for(int index: removeQueries) v[index] = 0; + + UF uf(n); + map sum; + multiset sum_set; + for(int start = 0, i = 1; i <= n; i ++) + if(i == n || get_type(v[i]) != get_type(v[start])){ + if(v[start] != 0){ + long long seg_sum = 0; + for(int j = start; j < i; j ++){ + seg_sum += v[j]; + uf.union_elements(start, j); + } + sum[uf.find(start)] = seg_sum; + sum_set.insert(seg_sum); + } + start = i; + } + + vector res(n); + res[n - 1] = (sum_set.empty() ? 0 : *sum_set.rbegin()); + for(int i = n - 1; i > 0; i --){ + int index = removeQueries[i]; + long long new_seg_sum = nums[index]; + if(index - 1 >= 0 && v[index - 1] != 0){ + long long left_sum = sum[uf.find(index - 1)]; + new_seg_sum += left_sum; + sum.erase(uf.find(index - 1)); + sum_set.erase(sum_set.find(left_sum)); + uf.union_elements(index, index - 1); + } + if(index + 1 < n && v[index + 1] != 0){ + long long right_sum = sum[uf.find(index + 1)]; + new_seg_sum += right_sum; + sum.erase(uf.find(index + 1)); + sum_set.erase(sum_set.find(right_sum)); + uf.union_elements(index, index + 1); + } + + sum[uf.find(index)] = new_seg_sum; + sum_set.insert(new_seg_sum); + res[i - 1] = (sum_set.empty() ? 0 : *sum_set.rbegin()); + v[index] = nums[index]; + } + return res; + } + +private: + bool get_type(long long x){ + return x != 0; + } +}; + + +void print_vec(const vector& v){ + for(long long e: v) cout << e << ' '; cout << '\n'; +} + +int main() { + + vector nums1 = {1, 2, 5, 6, 1}; + vector removeQueries1 = {0, 3, 2, 4, 1}; + print_vec(Solution().maximumSegmentSum(nums1, removeQueries1)); + // 14 7 2 2 0 + + return 0; +} diff --git a/2001-2500/2382-Maximum-Segment-Sum-After-Removals/cpp-2382/main2.cpp b/2001-2500/2382-Maximum-Segment-Sum-After-Removals/cpp-2382/main2.cpp new file mode 100644 index 00000000..ed3dea5b --- /dev/null +++ b/2001-2500/2382-Maximum-Segment-Sum-After-Removals/cpp-2382/main2.cpp @@ -0,0 +1,113 @@ +/// Source : https://leetcode.com/problems/maximum-segment-sum-after-removals/ +/// Author : liuyubobobo +/// Time : 2022-08-20 + +#include +#include + +using namespace std; + + +/// Same idea with main.cpp, but has some optimization +/// Such as declare sum as a vector instead of map +/// ans no need to main sum_set but just just max_sum to keep the best result +/// +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class UF{ + +private: + vector parent; + +public: + UF(int n) : parent(n){ + for(int i = 0 ; i < n ; i ++) + parent[i] = i; + } + + int find(int p){ + if(p != parent[p]) + parent[p] = find(parent[p]); + return parent[p]; + } + + bool is_connected(int p, int q){ + return find(p) == find(q); + } + + void union_elements(int p, int q){ + + int p_root = find(p), q_root = find(q); + + if(p_root == q_root) return; + + parent[p_root] = q_root; + } +}; + +class Solution { +public: + vector maximumSegmentSum(vector& nums, vector& removeQueries) { + + int n = nums.size(); + + vector v(n); + for(int i = 0; i < n; i ++) v[i] = nums[i]; + + for(int index: removeQueries) v[index] = 0; + + UF uf(n); + vector sum(n, 0); + long long max_sum = 0; + for(int start = 0, i = 1; i <= n; i ++) + if(i == n || (v[i] != 0) != (v[start] != 0)){ + if(v[start] != 0){ + long long seg_sum = 0; + for(int j = start; j < i; j ++){ + seg_sum += v[j]; + uf.union_elements(start, j); + } + sum[uf.find(start)] = seg_sum; + max_sum = max(max_sum, seg_sum); + } + start = i; + } + + vector res(n, max_sum); + for(int i = n - 1; i > 0; i --){ + int index = removeQueries[i]; + long long new_seg_sum = nums[index]; + if(index - 1 >= 0 && v[index - 1] != 0){ + long long left_sum = sum[uf.find(index - 1)]; + new_seg_sum += left_sum; + uf.union_elements(index, index - 1); + } + if(index + 1 < n && v[index + 1] != 0){ + long long right_sum = sum[uf.find(index + 1)]; + new_seg_sum += right_sum; + uf.union_elements(index, index + 1); + } + + sum[uf.find(index)] = new_seg_sum; + max_sum = max(max_sum, new_seg_sum); + res[i - 1] = max_sum; + v[index] = nums[index]; + } + return res; + } +}; + + +void print_vec(const vector& v){ + for(long long e: v) cout << e << ' '; cout << '\n'; +} + +int main() { + + vector nums1 = {1, 2, 5, 6, 1}; + vector removeQueries1 = {0, 3, 2, 4, 1}; + print_vec(Solution().maximumSegmentSum(nums1, removeQueries1)); + // 14 7 2 2 0 + + return 0; +} diff --git a/2001-2500/2383-Minimum-Hours-of-Training-to-Win-a-Competition/cpp-2383/CMakeLists.txt b/2001-2500/2383-Minimum-Hours-of-Training-to-Win-a-Competition/cpp-2383/CMakeLists.txt new file mode 100644 index 00000000..415e0a92 --- /dev/null +++ b/2001-2500/2383-Minimum-Hours-of-Training-to-Win-a-Competition/cpp-2383/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/2001-2500/2383-Minimum-Hours-of-Training-to-Win-a-Competition/cpp-2383/main.cpp b/2001-2500/2383-Minimum-Hours-of-Training-to-Win-a-Competition/cpp-2383/main.cpp new file mode 100644 index 00000000..95fd346f --- /dev/null +++ b/2001-2500/2383-Minimum-Hours-of-Training-to-Win-a-Competition/cpp-2383/main.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/minimum-hours-of-training-to-win-a-competition/ +/// Author : liuyubobobo +/// Time : 2022-08-20 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int minNumberOfHours(int initialEnergy, int initialExperience, vector& energy, vector& experience) { + + int need_energy = 0, need_exp = 0, cur_energy = initialEnergy, cur_exp = initialExperience; + + int n = energy.size(); + for(int i = 0; i < n; i ++){ + + if(cur_energy <= energy[i]){ + need_energy += energy[i] + 1 - cur_energy; + cur_energy = energy[i] + 1; + } + if(cur_exp <= experience[i]){ + need_exp += experience[i] + 1 - cur_exp; + cur_exp = experience[i] + 1; + } + + cur_exp += experience[i]; + cur_energy -= energy[i]; + } + return need_exp + need_energy; + } +}; + + +int main() { + + vector energy1 = {1, 4, 3, 2}, experience1 = {2, 6, 3, 1}; + cout << Solution().minNumberOfHours(5, 3, energy1, experience1) << '\n'; + // 8 + + return 0; +} diff --git a/2001-2500/2384-Largest-Palindromic-Number/cpp-2384/CMakeLists.txt b/2001-2500/2384-Largest-Palindromic-Number/cpp-2384/CMakeLists.txt new file mode 100644 index 00000000..b1c82ab8 --- /dev/null +++ b/2001-2500/2384-Largest-Palindromic-Number/cpp-2384/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/2001-2500/2384-Largest-Palindromic-Number/cpp-2384/main.cpp b/2001-2500/2384-Largest-Palindromic-Number/cpp-2384/main.cpp new file mode 100644 index 00000000..a0083dc0 --- /dev/null +++ b/2001-2500/2384-Largest-Palindromic-Number/cpp-2384/main.cpp @@ -0,0 +1,65 @@ +/// Source : https://leetcode.com/problems/largest-palindromic-number/ +/// Author : liuyubobobo +/// Time : 2022-08-20 + +#include +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(|num|) +/// Space Complexity: O(1) +class Solution { +public: + string largestPalindromic(string num) { + + vector f(10, 0); + for(char c: num) f[c - '0'] ++; + + if(f[0] == num.size()) return "0"; + + map> even, odd; + for(int i = 0; i < 10; i ++) + if(f[i]){ + if(f[i] % 2 == 0) even[i] = f[i]; + else{ + odd[i] = 1; + if(f[i] - 1) even[i] = f[i]; + } + } + + string pre = ""; + for(const pair& p: even){ + if(pre == "" && p.first == 0) continue; + pre += string(p.second / 2, '0' + p.first); + } + + string suf = pre; + reverse(suf.begin(), suf.end()); + + if(!odd.empty()) pre += string(1, '0' + odd.begin()->first); + pre += suf; + return pre; + } +}; + + +int main() { + + cout << Solution().largestPalindromic("444947137") << '\n'; + // 7449447 + + cout << Solution().largestPalindromic("00009") << '\n'; + // 9 + + cout << Solution().largestPalindromic("0000") << '\n'; + // 0 + + cout << Solution().largestPalindromic("012303") << '\n'; + // 30203 + + return 0; +} diff --git a/2001-2500/2385-Amount-of-Time-for-Binary-Tree-to-Be-Infected/cpp-2385/CMakeLists.txt b/2001-2500/2385-Amount-of-Time-for-Binary-Tree-to-Be-Infected/cpp-2385/CMakeLists.txt new file mode 100644 index 00000000..d0dc1506 --- /dev/null +++ b/2001-2500/2385-Amount-of-Time-for-Binary-Tree-to-Be-Infected/cpp-2385/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/2001-2500/2385-Amount-of-Time-for-Binary-Tree-to-Be-Infected/cpp-2385/main.cpp b/2001-2500/2385-Amount-of-Time-for-Binary-Tree-to-Be-Infected/cpp-2385/main.cpp new file mode 100644 index 00000000..5744407c --- /dev/null +++ b/2001-2500/2385-Amount-of-Time-for-Binary-Tree-to-Be-Infected/cpp-2385/main.cpp @@ -0,0 +1,82 @@ +/// Source : https://leetcode.com/problems/amount-of-time-for-binary-tree-to-be-infected/ +/// Author : liuyubobobo +/// Time : 2022-08-20 + +#include +#include +#include +#include + +using namespace std; + + +/// DFS + BFS +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// 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: + int amountOfTime(TreeNode* root, int start) { + + vector> edges; + dfs_edges(root, nullptr, edges); + + if(edges.empty()) return 0; + + int max_id = 0; + for(const pair& p: edges){ + max_id = max(max_id, p.first); + max_id = max(max_id, p.second); + } + + vector> tree(max_id + 1); + for(const pair& p: edges){ + int u = p.first, v = p.second; + tree[u].push_back(v), tree[v].push_back(u); + } + + vector dis(max_id + 1, -1); + queue q; + q.push(start); + dis[start] = 0; + int res = 0; + while(!q.empty()){ + int u = q.front(); q.pop(); + for(int v: tree[u]){ + if(dis[v] == -1){ + q.push(v); + dis[v] = dis[u] + 1; + res = max(res, dis[v]); + } + } + } + return res; + } + +private: + void dfs_edges(TreeNode* node, TreeNode* p, vector>& edges){ + + if(p){ + edges.push_back({p->val, node->val}); + } + + if(node->left) dfs_edges(node->left, node, edges); + if(node->right) dfs_edges(node->right, node, edges); + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2387-Median-of-a-Row-Wise-Sorted-Matrix/cpp-2387/CMakeLists.txt b/2001-2500/2387-Median-of-a-Row-Wise-Sorted-Matrix/cpp-2387/CMakeLists.txt new file mode 100644 index 00000000..2c3ab7b3 --- /dev/null +++ b/2001-2500/2387-Median-of-a-Row-Wise-Sorted-Matrix/cpp-2387/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_2387) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2387 main.cpp) diff --git a/2001-2500/2387-Median-of-a-Row-Wise-Sorted-Matrix/cpp-2387/main.cpp b/2001-2500/2387-Median-of-a-Row-Wise-Sorted-Matrix/cpp-2387/main.cpp new file mode 100644 index 00000000..38ee52ea --- /dev/null +++ b/2001-2500/2387-Median-of-a-Row-Wise-Sorted-Matrix/cpp-2387/main.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/median-of-a-row-wise-sorted-matrix/ +/// Author : liuyubobobo +/// Time : 2022-09-07 + +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(R * logC * log(maxv)) +/// Space Complexity: O(1) +class Solution { + +public: + int matrixMedian(vector>& grid) { + + int R = grid.size(), C = grid[0].size(); + + int n = (R * C + 1) / 2; + + int l = 1, r = 1e6; + while(l < r){ + int mid = (l + r) / 2; + if(less_than_or_equal_to(R, grid, mid) < n) l = mid + 1; + else r = mid; + } + return l; + } + +private: + int less_than_or_equal_to(int R, const vector>& grid, int v){ + + int res = 0; + for(int i = 0; i < R; i ++){ + res += upper_bound(grid[i].begin(), grid[i].end(), v) - grid[i].begin(); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2389-Longest-Subsequence-With-Limited-Sum/cpp-2389/CMakeLists.txt b/2001-2500/2389-Longest-Subsequence-With-Limited-Sum/cpp-2389/CMakeLists.txt new file mode 100644 index 00000000..4741167f --- /dev/null +++ b/2001-2500/2389-Longest-Subsequence-With-Limited-Sum/cpp-2389/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main2.cpp) diff --git a/2001-2500/2389-Longest-Subsequence-With-Limited-Sum/cpp-2389/main.cpp b/2001-2500/2389-Longest-Subsequence-With-Limited-Sum/cpp-2389/main.cpp new file mode 100644 index 00000000..879ee2da --- /dev/null +++ b/2001-2500/2389-Longest-Subsequence-With-Limited-Sum/cpp-2389/main.cpp @@ -0,0 +1,38 @@ +/// Source : https://leetcode.com/problems/longest-subsequence-with-limited-sum/ +/// Author : liuyubobobo +/// Time : 2022-08-27 + +#include +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(nlogn + qn) +/// Space Complexity: O(1) +class Solution { +public: + vector answerQueries(vector& nums, vector& queries) { + + sort(nums.begin(), nums.end()); + + vector res(queries.size()); + for(int i = 0; i < queries.size(); i ++){ + int q = queries[i]; + + int cur = 0, j; + for(j = 0; j < nums.size() && cur <= q; j ++) + cur += nums[j]; + res[i] = j - (cur > q); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2389-Longest-Subsequence-With-Limited-Sum/cpp-2389/main2.cpp b/2001-2500/2389-Longest-Subsequence-With-Limited-Sum/cpp-2389/main2.cpp new file mode 100644 index 00000000..b335def2 --- /dev/null +++ b/2001-2500/2389-Longest-Subsequence-With-Limited-Sum/cpp-2389/main2.cpp @@ -0,0 +1,45 @@ +/// Source : https://leetcode.com/problems/longest-subsequence-with-limited-sum/ +/// Author : liuyubobobo +/// Time : 2022-08-27 + +#include +#include +#include + +using namespace std; + + +/// Greedy + Binary Search +/// Time Complexity: O(nlogn + qlogn) +/// Space Complexity: O(n) +class Solution { +public: + vector answerQueries(vector& nums, vector& queries) { + + sort(nums.begin(), nums.end()); + + vector presum(nums.size() + 1, 0); + for(int i = 0; i < nums.size(); i ++) presum[i + 1] = presum[i] + nums[i]; + + vector res(queries.size()); + for(int i = 0; i < queries.size(); i ++){ + int q = queries[i]; + + if(q >= presum.back()){ + res[i] = nums.size(); + continue; + } + + auto iter = upper_bound(presum.begin(), presum.end(), q); + iter --; + res[i] = iter - presum.begin(); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2390-Removing-Stars-From-a-String/cpp-2390/CMakeLists.txt b/2001-2500/2390-Removing-Stars-From-a-String/cpp-2390/CMakeLists.txt new file mode 100644 index 00000000..b1c82ab8 --- /dev/null +++ b/2001-2500/2390-Removing-Stars-From-a-String/cpp-2390/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/2001-2500/2390-Removing-Stars-From-a-String/cpp-2390/main.cpp b/2001-2500/2390-Removing-Stars-From-a-String/cpp-2390/main.cpp new file mode 100644 index 00000000..8a23213b --- /dev/null +++ b/2001-2500/2390-Removing-Stars-From-a-String/cpp-2390/main.cpp @@ -0,0 +1,31 @@ +/// Source : https://leetcode.com/problems/removing-stars-from-a-string/ +/// Author : liuyubobobo +/// Time : 2022-08-27 + +#include +#include + +using namespace std; + + +/// Stack +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + string removeStars(string s) { + + string res = ""; + for(char c: s){ + if(c != '*') res += c; + else if(!res.empty()) res.pop_back(); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2391-Minimum-Amount-of-Time-to-Collect-Garbage/cpp-2391/CMakeLists.txt b/2001-2500/2391-Minimum-Amount-of-Time-to-Collect-Garbage/cpp-2391/CMakeLists.txt new file mode 100644 index 00000000..d0dc1506 --- /dev/null +++ b/2001-2500/2391-Minimum-Amount-of-Time-to-Collect-Garbage/cpp-2391/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/2001-2500/2391-Minimum-Amount-of-Time-to-Collect-Garbage/cpp-2391/main.cpp b/2001-2500/2391-Minimum-Amount-of-Time-to-Collect-Garbage/cpp-2391/main.cpp new file mode 100644 index 00000000..71bbd7c4 --- /dev/null +++ b/2001-2500/2391-Minimum-Amount-of-Time-to-Collect-Garbage/cpp-2391/main.cpp @@ -0,0 +1,60 @@ +/// Source : https://leetcode.com/problems/minimum-amount-of-time-to-collect-garbage/ +/// Author : liuyubobobo +/// Time : 2022-08-27 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int garbageCollection(vector& garbage, vector& travel) { + + int n = garbage.size(); + + vector> g(3, vector(n, 0)); + vector total(3, 0); + for(int i = 0; i < n; i ++){ + for(char c: garbage[i]){ + if(c == 'M') g[0][i] ++, total[0] ++; + if(c == 'P') g[1][i] ++, total[1] ++; + if(c == 'G') g[2][i] ++, total[2] ++; + } + } + + int res = 0; + for(int i = 0; i < 3; i ++) + res += solve(n, total[i], g[i], travel); + return res; + } + +private: + int solve(int n, int total, const vector& g, const vector& travel){ + + if(total == 0) return 0; + + int res = g[0]; + total -= g[0]; + for(int i = 1; i < n && total; i ++){ + res += travel[i - 1]; + res += g[i]; + total -= g[i]; + } + return res; + } +}; + + +int main() { + + vector garbage2 = {"MMM", "PGM", "GP"}; + vector travel2 = {3, 10}; + cout << Solution().garbageCollection(garbage2, travel2) << '\n'; + + return 0; +} diff --git a/2001-2500/2392-Build-a-Matrix-With-Conditions/cpp-2392/CMakeLists.txt b/2001-2500/2392-Build-a-Matrix-With-Conditions/cpp-2392/CMakeLists.txt new file mode 100644 index 00000000..8148fadd --- /dev/null +++ b/2001-2500/2392-Build-a-Matrix-With-Conditions/cpp-2392/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) diff --git a/2001-2500/2392-Build-a-Matrix-With-Conditions/cpp-2392/main.cpp b/2001-2500/2392-Build-a-Matrix-With-Conditions/cpp-2392/main.cpp new file mode 100644 index 00000000..bc8aa5ba --- /dev/null +++ b/2001-2500/2392-Build-a-Matrix-With-Conditions/cpp-2392/main.cpp @@ -0,0 +1,78 @@ +/// Source : https://leetcode.com/problems/build-a-matrix-with-conditions/ +/// Author : liuyubobobo +/// Time : 2022-08-27 + +#include +#include +#include +#include + +using namespace std; + + +/// Topological Sort +/// Time Complexity: O(k + |rowConstions| + |colConditions|) +/// Space Complexity: O(k + |rowConstions| + |colConditions|) +class Solution { +public: + vector> buildMatrix(int k, vector>& rowConditions, vector>& colConditions) { + + vector> rowG(k + 1), colG(k + 1); + for(const vector& rc: rowConditions){ + int u = rc[0], v = rc[1]; + rowG[u].insert(v); + } + for(const vector& cc: colConditions){ + int u = cc[0], v = cc[1]; + colG[u].insert(v); + } + + vector row_res = topo_sort(k, rowG); + if(row_res.size() < k) return {}; + vector col_res = topo_sort(k, colG); + if(col_res.size() < k) return {}; + + vector row(k + 1), col(k + 1); + for(int i = 0; i < k; i ++){ + row[row_res[i]] = i; + col[col_res[i]] = i; + } + + vector> res(k, vector(k, 0)); + for(int i = 1; i <= k; i ++) + res[row[i]][col[i]] = i; + + return res; + } + +private: + vector topo_sort(int k, vector>& g){ + + vector indegrees(k + 1, 0); + for(int u = 1; u <= k; u ++){ + for(int v: g[u]) indegrees[v] ++; + } + + queue q; + for(int u = 1; u <= k; u ++) + if(indegrees[u] == 0) q.push(u); + + vector res; + while(!q.empty()){ + int u = q.front(); q.pop(); + res.push_back(u); + + for(int v: g[u]){ + indegrees[v] --; + if(indegrees[v] == 0) q.push(v); + } + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2393-Count-Strictly-Increasing-Subarrays/cpp-2393/CMakeLists.txt b/2001-2500/2393-Count-Strictly-Increasing-Subarrays/cpp-2393/CMakeLists.txt new file mode 100644 index 00000000..c94958c9 --- /dev/null +++ b/2001-2500/2393-Count-Strictly-Increasing-Subarrays/cpp-2393/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_2393) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2393 main.cpp) diff --git a/2001-2500/2393-Count-Strictly-Increasing-Subarrays/cpp-2393/main.cpp b/2001-2500/2393-Count-Strictly-Increasing-Subarrays/cpp-2393/main.cpp new file mode 100644 index 00000000..f5bbb1b1 --- /dev/null +++ b/2001-2500/2393-Count-Strictly-Increasing-Subarrays/cpp-2393/main.cpp @@ -0,0 +1,45 @@ +/// Source : https://leetcode.com/problems/count-strictly-increasing-subarrays/ +/// Author : liuyubobobo +/// Time : 2022-09-03 + +#include +#include + +using namespace std; + + +/// Sliding Window +/// Time Complexity: O(n) +/// Space Compelxity: O(1) +class Solution { +public: + long long countSubarrays(vector& nums) { + + int n = nums.size(); + long long res = 0; + int l = 0, r = -1; + while(l < n){ + if(r + 1 < n && (r + 1 == l || nums[r] < nums[r + 1])) + r ++; + else{ + res += r - l + 1; + l ++; + } + } + return res; + } +}; + + +int main() { + + vector nums1 = {1,3,5,4,4,6}; + cout << Solution().countSubarrays(nums1) << '\n'; + // 10 + + vector nums2 = {1,2, 3,4,5}; + cout << Solution().countSubarrays(nums2) << '\n'; + // 15 + + return 0; +} diff --git a/2001-2500/2395-Find-Subarrays-With-Equal-Sum/cpp-2395/CMakeLists.txt b/2001-2500/2395-Find-Subarrays-With-Equal-Sum/cpp-2395/CMakeLists.txt new file mode 100644 index 00000000..e6db4427 --- /dev/null +++ b/2001-2500/2395-Find-Subarrays-With-Equal-Sum/cpp-2395/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_2395) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2395 main2.cpp) diff --git a/2001-2500/2395-Find-Subarrays-With-Equal-Sum/cpp-2395/main.cpp b/2001-2500/2395-Find-Subarrays-With-Equal-Sum/cpp-2395/main.cpp new file mode 100644 index 00000000..86869fb2 --- /dev/null +++ b/2001-2500/2395-Find-Subarrays-With-Equal-Sum/cpp-2395/main.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/find-subarrays-with-equal-sum/ +/// Author : liuyubobobo +/// Time : 2022-09-03 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n^2) +/// Space Complexity: O(1) +class Solution { +public: + bool findSubarrays(vector& nums) { + + int n = nums.size(); + for(int start = 0; start + 1 < n; start ++){ + int t = nums[start] + nums[start + 1]; + for(int i = start + 1; i + 1 < n; i ++) + if(t == nums[i] + nums[i + 1]) return true; + } + return false; + } +}; + + +int main() { + + + return 0; +} diff --git a/2001-2500/2395-Find-Subarrays-With-Equal-Sum/cpp-2395/main2.cpp b/2001-2500/2395-Find-Subarrays-With-Equal-Sum/cpp-2395/main2.cpp new file mode 100644 index 00000000..2662789c --- /dev/null +++ b/2001-2500/2395-Find-Subarrays-With-Equal-Sum/cpp-2395/main2.cpp @@ -0,0 +1,38 @@ +/// Source : https://leetcode.com/problems/find-subarrays-with-equal-sum/ +/// Author : liuyubobobo +/// Time : 2022-09-03 + +#include +#include +#include + +using namespace std; + + +/// Using MultiSet +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + bool findSubarrays(vector& nums) { + + int n = nums.size(); + multiset s; + for(int start = 0; start + 1 < n; start ++) + s.insert(nums[start] + nums[start + 1]); + + for(int start = 0; start + 1 < n; start ++){ + int t = nums[start] + nums[start + 1]; + s.erase(s.find(t)); + if(s.count(t)) return true; + } + return false; + } +}; + + +int main() { + + + return 0; +} diff --git a/2001-2500/2396-Strictly-Palindromic-Number/cpp-2396/CMakeLists.txt b/2001-2500/2396-Strictly-Palindromic-Number/cpp-2396/CMakeLists.txt new file mode 100644 index 00000000..f1976760 --- /dev/null +++ b/2001-2500/2396-Strictly-Palindromic-Number/cpp-2396/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_2396) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2396 main.cpp) diff --git a/2001-2500/2396-Strictly-Palindromic-Number/cpp-2396/main.cpp b/2001-2500/2396-Strictly-Palindromic-Number/cpp-2396/main.cpp new file mode 100644 index 00000000..5147583b --- /dev/null +++ b/2001-2500/2396-Strictly-Palindromic-Number/cpp-2396/main.cpp @@ -0,0 +1,38 @@ +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + bool isStrictlyPalindromic(int n) { + + bool ok = true; + for(int b = 2; b <= n - 2 && ok; b ++){ + vector res = get_base_number(n, b); + for(int i = 0, j = res.size() - 1; i < j && ok; i ++, j --) + if(res[i] != res[j]) ok = false; + } + return ok; + } + +private: + vector get_base_number(int n, int b){ + vector res; + while(n){ + res.push_back(n % b); + n /= b; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2397-Maximum-Rows-Covered-by-Columns/cpp-2397/CMakeLists.txt b/2001-2500/2397-Maximum-Rows-Covered-by-Columns/cpp-2397/CMakeLists.txt new file mode 100644 index 00000000..70195489 --- /dev/null +++ b/2001-2500/2397-Maximum-Rows-Covered-by-Columns/cpp-2397/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_2397) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2397 main.cpp) diff --git a/2001-2500/2397-Maximum-Rows-Covered-by-Columns/cpp-2397/main.cpp b/2001-2500/2397-Maximum-Rows-Covered-by-Columns/cpp-2397/main.cpp new file mode 100644 index 00000000..2d163ce0 --- /dev/null +++ b/2001-2500/2397-Maximum-Rows-Covered-by-Columns/cpp-2397/main.cpp @@ -0,0 +1,62 @@ +/// Source : https://leetcode.com/problems/maximum-rows-covered-by-columns/ +/// Author : liuyubobobo +/// Time : 2022-09-03 + +#include +#include + +using namespace std; + + +/// Backtrack +/// Time Complexity: O(C(C, cols) * R * C) +/// Space Complexity: O(C) +class Solution { + +public: + int maximumRows(vector>& mat, int cols) { + + int R = mat.size(), C = mat[0].size(); + + int res = 0; + vector v(C, 0); + dfs(R, C, mat, cols, 0, v, res); + return res; + } + +private: + void dfs(int R, int C, const vector>& mat, + int k, int start, vector& v, int& res){ + + if(k == 0){ + res = max(res, get_rows(R, C, mat, v)); + return; + } + + for(int i = start; i <= C - k; i ++){ + v[i] = 1; + dfs(R, C, mat, k - 1, i + 1, v, res); + v[i] = 0; + } + } + + int get_rows(int R, int C, const vector>& mat, const vector& col){ + + int res = 0; + for(int i = 0; i < R; i ++) + res += ok(C, mat[i], col); + return res; + } + + bool ok(int n, const vector& v1, const vector& v2){ + for(int i = 0; i < n; i ++) + if(v1[i] == 1 && v2[i] == 0) return false; + return true; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2398-Maximum-Number-of-Robots-Within-Budget/cpp-2398/CMakeLists.txt b/2001-2500/2398-Maximum-Number-of-Robots-Within-Budget/cpp-2398/CMakeLists.txt new file mode 100644 index 00000000..4a22ee63 --- /dev/null +++ b/2001-2500/2398-Maximum-Number-of-Robots-Within-Budget/cpp-2398/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_2398) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2398 main.cpp) diff --git a/2001-2500/2398-Maximum-Number-of-Robots-Within-Budget/cpp-2398/main.cpp b/2001-2500/2398-Maximum-Number-of-Robots-Within-Budget/cpp-2398/main.cpp new file mode 100644 index 00000000..40840cbe --- /dev/null +++ b/2001-2500/2398-Maximum-Number-of-Robots-Within-Budget/cpp-2398/main.cpp @@ -0,0 +1,93 @@ +/// Source : https://leetcode.com/problems/maximum-number-of-robots-within-budget/ +/// Author : liuyubobobo +/// Time : 2022-09-03 + +#include +#include +#include + +using namespace std; + + +/// ST(query range max) + Binary Seach +/// Time Complexity: O(n * logn * logn) +/// Space Complexity: O(nlogn) +template +class SparseTable{ + +private: + int n; + vector> table; + vector log2; + T (*combine)(T a, T b); + +public: + SparseTable(const vector& data, T (*combine)(T a, T b)): n(data.size()), log2(n + 1, 1){ + + this->combine = combine; + + int len = 2, k = 1; + for(int i = 1; i <= n; i ++){ + if(i >= len) len <<= 1, k ++; + log2[i] = k; + } + + int K = log2[n]; + table = vector>(K, vector(n)); + + for(int i = 0; i < n; i ++) + table[0][i] = data[i]; + + for(int k = 1; k < K; k ++) + for(int i = 0; i + (1 << (k - 1)) < n; i ++) + table[k][i] = combine(table[k - 1][i], table[k - 1][i + (1 << (k - 1))]); + } + + T query(int l, int r){ + + int k = log2[r - l + 1]; + return combine(table[k - 1][l], table[k - 1][r + 1 - (1 << (k - 1))]); + } +}; + +class Solution { +public: + int maximumRobots(vector& chargeTimes, vector& runningCosts, long long budget) { + + int n = chargeTimes.size(); + assert(runningCosts.size() == n); + + SparseTable st(chargeTimes, [](int a, int b){return max(a, b);}); + vector presum(n + 1, 0); + for(int i = 0; i < n; i ++) presum[i + 1] = presum[i] + runningCosts[i]; + + int res = 0; + for(int start = 0; start + res < n; start ++){ + + // check [start, start + res], len = res + 1 + // if not work, no need to search from start + if((presum[start + res + 1] - presum[start]) * (res + 1) + st.query(start, start + res) > budget) + continue; + + int end_l = start + res, end_r = n - 1; + while(end_l < end_r){ + int end_mid = (end_l + end_r + 1) / 2; + + // [start, end_mid] + long long t = (presum[end_mid + 1] - presum[start]) * (end_mid - start + 1) + st.query(start, end_mid); + if(t <= budget) + end_l = end_mid; + else + end_r = end_mid - 1; + } + res = max(res, end_l - start + 1); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2399-Check-Distances-Between-Same-Letters/cpp-2399/CMakeLists.txt b/2001-2500/2399-Check-Distances-Between-Same-Letters/cpp-2399/CMakeLists.txt new file mode 100644 index 00000000..415e0a92 --- /dev/null +++ b/2001-2500/2399-Check-Distances-Between-Same-Letters/cpp-2399/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/2001-2500/2399-Check-Distances-Between-Same-Letters/cpp-2399/main.cpp b/2001-2500/2399-Check-Distances-Between-Same-Letters/cpp-2399/main.cpp new file mode 100644 index 00000000..c9f16927 --- /dev/null +++ b/2001-2500/2399-Check-Distances-Between-Same-Letters/cpp-2399/main.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/check-distances-between-same-letters/ +/// Author : liuyubobobo +/// Time : 2022-09-03 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + bool checkDistances(string s, vector& distance) { + + vector first(26, -1); + for(int i = 0; i < s.size(); i ++){ + if(first[s[i] - 'a'] == -1) first[s[i] - 'a'] = i; + else{ + int d = i - first[s[i] - 'a'] - 1; + if(distance[s[i] - 'a'] != d) return false; + } + } + return true; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2400-Number-of-Ways-to-Reach-a-Position-After-Exactly-k-Steps/cpp-2400/CMakeLists.txt b/2001-2500/2400-Number-of-Ways-to-Reach-a-Position-After-Exactly-k-Steps/cpp-2400/CMakeLists.txt new file mode 100644 index 00000000..b1c82ab8 --- /dev/null +++ b/2001-2500/2400-Number-of-Ways-to-Reach-a-Position-After-Exactly-k-Steps/cpp-2400/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/2001-2500/2400-Number-of-Ways-to-Reach-a-Position-After-Exactly-k-Steps/cpp-2400/main.cpp b/2001-2500/2400-Number-of-Ways-to-Reach-a-Position-After-Exactly-k-Steps/cpp-2400/main.cpp new file mode 100644 index 00000000..02ab7241 --- /dev/null +++ b/2001-2500/2400-Number-of-Ways-to-Reach-a-Position-After-Exactly-k-Steps/cpp-2400/main.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/number-of-ways-to-reach-a-position-after-exactly-k-steps/ +/// Author : liuyubobobo +/// Time : 2022-09-03 + +#include +#include + +using namespace std; + + +/// Memoization +/// Time Complexity: O(k^2) +/// Space Complexity: O(k^2) +class Solution { + +private: + const long long MOD = 1e9 + 7; + int OFFSET = 1000; + +public: + int numberOfWays(int startPos, int endPos, int k) { + + OFFSET = -(startPos - k); + vector> dp(startPos + k + OFFSET, vector(k + 1, -1)); + return dfs(startPos, k, endPos, dp); + } + + long long dfs(int pos, int k, int target, vector>& dp){ + + if(k == 0) return pos == target; + if(dp[pos + OFFSET][k] != -1) return dp[pos + OFFSET][k]; + + long long res = 0; + res += dfs(pos + 1, k - 1, target, dp); + res += dfs(pos - 1, k - 1, target, dp); + return dp[pos + OFFSET][k] = res % MOD; + } +}; + + +int main() { + + cout << Solution().numberOfWays(1, 2, 3) << '\n'; + // 3 + + cout << Solution().numberOfWays(2, 5, 10) << '\n'; + // 0 + + cout << Solution().numberOfWays(921, 413, 716) << '\n'; + // 0 + + return 0; +} diff --git a/2001-2500/2401-Longest-Nice-Subarray/cpp-2401/CMakeLists.txt b/2001-2500/2401-Longest-Nice-Subarray/cpp-2401/CMakeLists.txt new file mode 100644 index 00000000..148bffbf --- /dev/null +++ b/2001-2500/2401-Longest-Nice-Subarray/cpp-2401/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main2.cpp) diff --git a/2001-2500/2401-Longest-Nice-Subarray/cpp-2401/main.cpp b/2001-2500/2401-Longest-Nice-Subarray/cpp-2401/main.cpp new file mode 100644 index 00000000..0656f599 --- /dev/null +++ b/2001-2500/2401-Longest-Nice-Subarray/cpp-2401/main.cpp @@ -0,0 +1,66 @@ +/// Source : https://leetcode.com/problems/longest-nice-subarray/ +/// Author : liuyubobobo +/// Time : 2022-09-03 + +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + int longestNiceSubarray(vector& nums) { + + int n = nums.size(); + vector> bits(30, vector(n, 0)); + for(int i = 0; i < n; i ++){ + for(int p = 0; p < 30; p ++) + bits[p][i] = ((nums[i] >> p) & 1); + } + + vector> presum(30, vector(n + 1, 0)); + for(int p = 0; p < 30; p ++) + for(int i = 0; i < n; i ++) + presum[p][i + 1] = presum[p][i] + bits[p][i]; + + int res = 0; + for(int start = 0; start < n; start ++){ + int end_l = start, end_r = n - 1; + while(end_l < end_r){ + int end_mid = (end_l + end_r + 1) / 2; + if(ok(presum, start, end_mid)) end_l = end_mid; + else end_r = end_mid - 1; + } + res = max(res, end_l - start + 1); + } + return res; + } + +private: + bool ok(const vector>& presum, int start, int end){ + + for(int p = 0; p < 30; p ++){ + int t = presum[p][end + 1] - presum[p][start]; + if(t > 1) return false; + } + return true; + } +}; + + +int main() { + + vector nums1 = {1, 3, 8, 48, 10}; + cout << Solution().longestNiceSubarray(nums1) << '\n'; + // 3 + + vector nums2 = {3, 1, 5, 11, 13}; + cout << Solution().longestNiceSubarray(nums2) << '\n'; + // 1 + + return 0; +} diff --git a/2001-2500/2401-Longest-Nice-Subarray/cpp-2401/main2.cpp b/2001-2500/2401-Longest-Nice-Subarray/cpp-2401/main2.cpp new file mode 100644 index 00000000..a36be6ea --- /dev/null +++ b/2001-2500/2401-Longest-Nice-Subarray/cpp-2401/main2.cpp @@ -0,0 +1,63 @@ +/// Source : https://leetcode.com/problems/longest-nice-subarray/ +/// Author : liuyubobobo +/// Time : 2022-09-03 + +#include +#include + +using namespace std; + + +/// Sliding Window +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int longestNiceSubarray(vector& nums) { + + int n = nums.size(); + + vector cur(30, 0); + int res = 0, l = 0, r = -1; + while(l < n){ + if(r + 1 < n && ok(cur, nums[r + 1])) + add(cur, nums[++r]); + else + remove(cur, nums[l ++]); + res = max(res, r - l + 1); + } + return res; + } + +private: + bool ok(const vector& bits, int x){ + + for(int p = 0; p < 30; p ++) + if(bits[p] + ((x >> p) & 1) > 1) return false; + return true; + } + + void add(vector& bits, int x){ + for(int p = 0; p < 30; p ++) + bits[p] += ((x >> p) & 1); + } + + void remove(vector& bits, int x){ + for(int p = 0; p < 30; p ++) + bits[p] -= ((x >> p) & 1); + } +}; + + +int main() { + + vector nums1 = {1, 3, 8, 48, 10}; + cout << Solution().longestNiceSubarray(nums1) << '\n'; + // 3 + + vector nums2 = {3, 1, 5, 11, 13}; + cout << Solution().longestNiceSubarray(nums2) << '\n'; + // 1 + + return 0; +} diff --git a/2001-2500/2402-Meeting-Rooms-III/cpp-2402/CMakeLists.txt b/2001-2500/2402-Meeting-Rooms-III/cpp-2402/CMakeLists.txt new file mode 100644 index 00000000..8148fadd --- /dev/null +++ b/2001-2500/2402-Meeting-Rooms-III/cpp-2402/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) diff --git a/2001-2500/2402-Meeting-Rooms-III/cpp-2402/main.cpp b/2001-2500/2402-Meeting-Rooms-III/cpp-2402/main.cpp new file mode 100644 index 00000000..9f686d26 --- /dev/null +++ b/2001-2500/2402-Meeting-Rooms-III/cpp-2402/main.cpp @@ -0,0 +1,91 @@ +/// Source : https://leetcode.com/problems/meeting-rooms-iii/ +/// Author : liuyubobobo +/// Time : 2022-09-03 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// PQ Events Simulation +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { + +private: + const int END_EVENT = 0, START_EVENT = 1; + +public: + int mostBooked(int n, vector>& meetings) { + + // event: + // start_time, + // 0 -end_meeting, 1 - start_meeting, + // end_meeting: room_number; start_meeting: end_time + priority_queue, long long>, vector, long long>>, greater, long long>>> events; + for(int i = 0; i < meetings.size(); i ++){ + long long start_time = meetings[i][0], end_time = meetings[i][1]; + events.push({{start_time, START_EVENT}, end_time}); + } + set availables; + set> waiting_list; // start, duration + for(int i = 0; i < n; i ++) availables.insert(i); + + vector cnt(n, 0); + while(!events.empty()){ + long long start_time = events.top().first.first; + int type = events.top().first.second; + long long x = events.top().second; + events.pop(); + + if(type == START_EVENT){ + long long end_time = x; + if(!availables.empty()){ + int room_id = *availables.begin(); + availables.erase(availables.begin()); + cnt[room_id] ++; + events.push({{end_time, END_EVENT}, room_id}); + } + else{ + waiting_list.insert({start_time, end_time - start_time}); + } + } + else{ + int room_id = x; + if(waiting_list.empty()){ + availables.insert(room_id); + continue; + } + + long long duration = waiting_list.begin()->second; + waiting_list.erase(waiting_list.begin()); + + cnt[room_id] ++; + events.push({{start_time + duration, END_EVENT}, room_id}); + } + } + + int best = -1, res = -1; + for(int i = 0; i < n; i ++) + if(cnt[i] > best) best = cnt[i], res = i; + return res; + } +}; + + +int main() { + + vector> meetings1 = {{0, 10}, {1, 5}, {2, 7}, {3, 4}}; + cout << Solution().mostBooked(2, meetings1) << '\n'; + // 0 + + vector> meetings2 = {{1, 20}, {2, 10}, {3, 5}, {4, 9}, {6, 8}}; + cout << Solution().mostBooked(3, meetings2) << '\n'; + // 1 + + return 0; +} diff --git a/2001-2500/2403-Minimum-Time-to-Kill-All-Monsters/cpp-2403/CMakeLists.txt b/2001-2500/2403-Minimum-Time-to-Kill-All-Monsters/cpp-2403/CMakeLists.txt new file mode 100644 index 00000000..d94035d7 --- /dev/null +++ b/2001-2500/2403-Minimum-Time-to-Kill-All-Monsters/cpp-2403/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_2403) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2403 main.cpp) diff --git a/2001-2500/2403-Minimum-Time-to-Kill-All-Monsters/cpp-2403/main.cpp b/2001-2500/2403-Minimum-Time-to-Kill-All-Monsters/cpp-2403/main.cpp new file mode 100644 index 00000000..a26248c3 --- /dev/null +++ b/2001-2500/2403-Minimum-Time-to-Kill-All-Monsters/cpp-2403/main.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/minimum-time-to-kill-all-monsters/ +/// Author : liuyubobobo +/// Time : 2022-09-07 + +#include +#include + +using namespace std; + + +/// Memoization +/// Time Complexity: O(2^n * n) +/// Space Complexity: O(2^n) +class Solution { +public: + long long minimumTime(vector& power) { + + int n = power.size(); + + vector dp(1 << n, -1); + return dfs(n, power, 0, dp); + } + +private: + long long dfs(int n, const vector& power, int state, + vector& dp){ + + if(state + 1 == (1 << n)) return 0; + if(dp[state] != -1) return dp[state]; + + long long gain = __builtin_popcount(state) + 1; + long long res = LONG_LONG_MAX; + for(int i = 0; i < n; i ++){ + if((state >> i) & 1) continue; + long long days = power[i] / gain + !!(power[i] % gain); + res = min(res, days + dfs(n, power, state | (1 << i), dp)); + } + return dp[state] = res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2404-Most-Frequent-Even-Element/cpp-2404/CMakeLists.txt b/2001-2500/2404-Most-Frequent-Even-Element/cpp-2404/CMakeLists.txt new file mode 100644 index 00000000..415e0a92 --- /dev/null +++ b/2001-2500/2404-Most-Frequent-Even-Element/cpp-2404/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/2001-2500/2404-Most-Frequent-Even-Element/cpp-2404/main.cpp b/2001-2500/2404-Most-Frequent-Even-Element/cpp-2404/main.cpp new file mode 100644 index 00000000..bd309f64 --- /dev/null +++ b/2001-2500/2404-Most-Frequent-Even-Element/cpp-2404/main.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/most-frequent-even-element/ +/// Author : liuyubobobo +/// Time : 2022-09-10 + +#include +#include +#include + +using namespace std; + + +/// Using Map +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int mostFrequentEven(vector& nums) { + + map f; + for(int e: nums) + if(e % 2 == 0) f[e] ++; + + int res = -1, best_f = 0; + for(const pair& p: f) + if(p.second > best_f) res = p.first, best_f = p.second; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2405-Optimal-Partition-of-String/cpp-2405/CMakeLists.txt b/2001-2500/2405-Optimal-Partition-of-String/cpp-2405/CMakeLists.txt new file mode 100644 index 00000000..b1c82ab8 --- /dev/null +++ b/2001-2500/2405-Optimal-Partition-of-String/cpp-2405/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/2001-2500/2405-Optimal-Partition-of-String/cpp-2405/main.cpp b/2001-2500/2405-Optimal-Partition-of-String/cpp-2405/main.cpp new file mode 100644 index 00000000..862e30ce --- /dev/null +++ b/2001-2500/2405-Optimal-Partition-of-String/cpp-2405/main.cpp @@ -0,0 +1,36 @@ +/// Source : https://leetcode.com/problems/optimal-partition-of-string/ +/// Author : liuyubobobo +/// Time : 2022-09-10 + +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int partitionString(string s) { + + vector used(26, false); + int res = 1; + for(char c: s){ + if(used[c - 'a']){ + res ++; + used.assign(26, false); + } + used[c - 'a'] = true; + } + return res; + } +}; + + +int main() { + + + return 0; +} diff --git a/2001-2500/2406-Divide-Intervals-Into-Minimum-Number-of-Groups/cpp-2406/CMakeLists.txt b/2001-2500/2406-Divide-Intervals-Into-Minimum-Number-of-Groups/cpp-2406/CMakeLists.txt new file mode 100644 index 00000000..148bffbf --- /dev/null +++ b/2001-2500/2406-Divide-Intervals-Into-Minimum-Number-of-Groups/cpp-2406/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main2.cpp) diff --git a/2001-2500/2406-Divide-Intervals-Into-Minimum-Number-of-Groups/cpp-2406/main.cpp b/2001-2500/2406-Divide-Intervals-Into-Minimum-Number-of-Groups/cpp-2406/main.cpp new file mode 100644 index 00000000..443a3834 --- /dev/null +++ b/2001-2500/2406-Divide-Intervals-Into-Minimum-Number-of-Groups/cpp-2406/main.cpp @@ -0,0 +1,45 @@ +/// Source : https://leetcode.com/problems/divide-intervals-into-minimum-number-of-groups/ +/// Author : liuyubobobo +/// Time : 2022-09-10 + +#include +#include +#include +#include + +using namespace std; + + +/// Greedy and Using Set +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + int minGroups(vector>& intervals) { + + sort(intervals.begin(), intervals.end()); + + multiset> ends; + for(const vector& interval: intervals){ + int a = interval[0], b = interval[1]; + auto iter = ends.upper_bound(a); + if(iter != ends.end()) ends.erase(iter); + ends.insert(b); + } + return ends.size(); + } +}; + + +int main() { + + vector> intervals1 = {{5, 10}, {6, 8}, {1, 5}, {2, 3}, {1, 10}}; + cout << Solution().minGroups(intervals1) << '\n'; + // 3 + + vector> intervals2 = {{1, 3}, {5, 6}, {8, 10}, {11, 13}}; + cout << Solution().minGroups(intervals2) << '\n'; + // 1 + + return 0; +} diff --git a/2001-2500/2406-Divide-Intervals-Into-Minimum-Number-of-Groups/cpp-2406/main2.cpp b/2001-2500/2406-Divide-Intervals-Into-Minimum-Number-of-Groups/cpp-2406/main2.cpp new file mode 100644 index 00000000..b613fcb5 --- /dev/null +++ b/2001-2500/2406-Divide-Intervals-Into-Minimum-Number-of-Groups/cpp-2406/main2.cpp @@ -0,0 +1,45 @@ +/// Source : https://leetcode.com/problems/divide-intervals-into-minimum-number-of-groups/ +/// Author : liuyubobobo +/// Time : 2022-09-12 + +#include +#include +#include +#include + +using namespace std; + + +/// Greedy and Using PQ +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + int minGroups(vector>& intervals) { + + sort(intervals.begin(), intervals.end()); + + priority_queue, greater> ends; + for(const vector& interval: intervals){ + int a = interval[0], b = interval[1]; + if(!ends.empty() && a > ends.top()) + ends.pop(); + ends.push(b); + } + return ends.size(); + } +}; + + +int main() { + + vector> intervals1 = {{5, 10}, {6, 8}, {1, 5}, {2, 3}, {1, 10}}; + cout << Solution().minGroups(intervals1) << '\n'; + // 3 + + vector> intervals2 = {{1, 3}, {5, 6}, {8, 10}, {11, 13}}; + cout << Solution().minGroups(intervals2) << '\n'; + // 1 + + return 0; +} diff --git a/2001-2500/2407-Longest-Increasing-Subsequence-II/cpp-2407/CMakeLists.txt b/2001-2500/2407-Longest-Increasing-Subsequence-II/cpp-2407/CMakeLists.txt new file mode 100644 index 00000000..8148fadd --- /dev/null +++ b/2001-2500/2407-Longest-Increasing-Subsequence-II/cpp-2407/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) diff --git a/2001-2500/2407-Longest-Increasing-Subsequence-II/cpp-2407/main.cpp b/2001-2500/2407-Longest-Increasing-Subsequence-II/cpp-2407/main.cpp new file mode 100644 index 00000000..dcd44ca2 --- /dev/null +++ b/2001-2500/2407-Longest-Increasing-Subsequence-II/cpp-2407/main.cpp @@ -0,0 +1,128 @@ +/// Source : https://leetcode.com/problems/divide-intervals-into-minimum-number-of-groups/ +/// Author : liuyubobobo +/// Time : 2022-09-10 + +#include +#include + +using namespace std; + + +/// DP + Segment Tree +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +template +class SegmentTree{ + +private: + int n; + vector data, tree; + T (*combine)(T a, T b); + +public: + SegmentTree(const vector& data, T (*combine)(T a, T b)): n(data.size()), data(data), tree(4 * n, 0){ + this->combine = combine; + buildSegTree(0, 0, n - 1); + } + + SegmentTree(int n, T (*combine)(T a, T b)): n(n), data(n, 0), tree(4 * n, 0){ + this->combine = combine; + } + + void update(int index, T value){ + if(data[index] == value) return; + data[index] = value; + update(0, 0, n - 1, index, value); + } + + T query(int index){ + assert(0 <= index && index < n); + return data[index]; + } + + T query(int l, int r){ + if(l > r) return 0; + return query(0, 0, n - 1, l, r); + } + +private: + void buildSegTree(int treeID, int l, int r){ + + if(l == r){ + tree[treeID] = data[l]; + return; + } + + int mid = (l + r) / 2; + buildSegTree(treeID * 2 + 1, l, mid); + buildSegTree(treeID * 2 + 2, mid + 1, r); + tree[treeID] = combine(tree[treeID * 2 + 1], tree[treeID * 2 + 2]); + return; + } + + void update(int treeID, int l, int r, int index, T value){ + + if(l == r){ + assert(l == index); + tree[treeID] = value; + return; + } + + int mid = (l + r) / 2; + if(index <= mid) update(treeID * 2 + 1, l, mid, index, value); + else update(treeID * 2 + 2, mid + 1, r, index, value); + + tree[treeID] = combine(tree[treeID * 2 + 1], tree[treeID * 2 + 2]); + return; + } + + T query(int treeID, int l, int r, int ql, int qr){ + + if(ql == l && qr == r) + return tree[treeID]; + + int mid = (l + r) / 2; + if(qr <= mid) return query(treeID * 2 + 1, l, mid, ql, qr); + else if(ql > mid) return query(treeID * 2 + 2, mid + 1, r, ql, qr); + + T resl = query(treeID * 2 + 1, l, mid, ql, mid); + T resr = query(treeID * 2 + 2, mid + 1, r, mid + 1, qr); + return combine(resl, resr); + } +}; + +class Solution { +public: + int lengthOfLIS(vector& nums, int k) { + + int maxv = *max_element(nums.begin(), nums.end()); + SegmentTree seg_tree(maxv + 1, [](int a, int b){return max(a, b);}); + + seg_tree.update(nums[0], 1); + for(int i = 1; i < nums.size(); i ++){ + int e = nums[i]; + int l = max(e - k, 0), r = e - 1; + int t = seg_tree.query(l, r); + seg_tree.update(e, max(seg_tree.query(e), t + 1)); + } + return seg_tree.query(0, maxv); + } +}; + + +int main() { + + vector nums1 = {4,2,1,4,3,4,5,8,15}; + cout << Solution().lengthOfLIS(nums1, 3) << '\n'; + // 5 + + vector nums2 = {7,4,5,1,8,12,4,7}; + cout << Solution().lengthOfLIS(nums2, 5) << '\n'; + // 4 + + vector nums3 = {1, 5}; + cout << Solution().lengthOfLIS(nums3, 1) << '\n'; + // 1 + + return 0; +} diff --git a/2001-2500/2408-Design-SQL/cpp-2408/CMakeLists.txt b/2001-2500/2408-Design-SQL/cpp-2408/CMakeLists.txt new file mode 100644 index 00000000..b299b759 --- /dev/null +++ b/2001-2500/2408-Design-SQL/cpp-2408/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_2408) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2408 main.cpp) diff --git a/2001-2500/2408-Design-SQL/cpp-2408/main.cpp b/2001-2500/2408-Design-SQL/cpp-2408/main.cpp new file mode 100644 index 00000000..39717891 --- /dev/null +++ b/2001-2500/2408-Design-SQL/cpp-2408/main.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/design-sql/ +/// Author : liuyubobobo +/// Time : 2022-09-20 + +#include +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: init: O(n) +/// query: O(logn) +/// Space Complexity: O(all rows) +class SQL { + +private: + map table_name_2_table_id; + const vector columns; + vector next_row_id; + vector>> tables; + +public: + SQL(vector& names, vector& columns) : + columns(columns), next_row_id(names.size(), 1), tables(names.size()) { + + for(int i = 0; i < names.size(); i ++) + table_name_2_table_id[names[i]] = i; + } + + void insertRow(string name, vector row) { + + int table_id = table_name_2_table_id[name]; + + tables[table_id].push_back(row); + next_row_id[table_id] ++; + } + + void deleteRow(string name, int rowId) { + + } + + string selectCell(string name, int rowId, int columnId) { + int table_id = table_name_2_table_id[name]; + return tables[table_id][rowId - 1][columnId - 1]; + } +}; + +int main() { + + return 0; +} diff --git a/2001-2500/2409-Count-Days-Spent-Together/cpp-2409/CMakeLists.txt b/2001-2500/2409-Count-Days-Spent-Together/cpp-2409/CMakeLists.txt new file mode 100644 index 00000000..415e0a92 --- /dev/null +++ b/2001-2500/2409-Count-Days-Spent-Together/cpp-2409/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/2001-2500/2409-Count-Days-Spent-Together/cpp-2409/main.cpp b/2001-2500/2409-Count-Days-Spent-Together/cpp-2409/main.cpp new file mode 100644 index 00000000..b099fe9b --- /dev/null +++ b/2001-2500/2409-Count-Days-Spent-Together/cpp-2409/main.cpp @@ -0,0 +1,55 @@ +/// Source : https://leetcode.com/problems/count-days-spent-together/ +/// Author : liuyubobobo +/// Time : 2022-09-17 + +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(1) +/// Space Complexity: O(1) +class Solution { + +private: + const vector months = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; + +public: + int countDaysTogether(string arriveAlice, string leaveAlice, string arriveBob, string leaveBob) { + + int a = get_day_index(arriveAlice); + int b = get_day_index(leaveAlice); + + int c = get_day_index(arriveBob); + int d = get_day_index(leaveBob); + + int x = max(a, c), y = min(b, d); + return max(0, y - x + 1); + } + +private: + int get_day_index(string date){ + + int month = atoi(date.substr(0, 2).c_str()); + int day = atoi(date.substr(3).c_str()); + + int res = 0; + for(int i = 1; i < month ; i ++) res += months[i]; + res += day; + return res; + } +}; + + +int main() { + + cout << Solution().countDaysTogether("08-15", "08-18", "08-16", "08-19") << '\n'; + // 3 + + cout << Solution().countDaysTogether("10-01", "10-31", "11-01", "12-31") << '\n'; + // 0 + + return 0; +} diff --git a/2001-2500/2410-Maximum-Matching-of-Players-With-Trainers/cpp-2410/CMakeLists.txt b/2001-2500/2410-Maximum-Matching-of-Players-With-Trainers/cpp-2410/CMakeLists.txt new file mode 100644 index 00000000..b1c82ab8 --- /dev/null +++ b/2001-2500/2410-Maximum-Matching-of-Players-With-Trainers/cpp-2410/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/2001-2500/2410-Maximum-Matching-of-Players-With-Trainers/cpp-2410/main.cpp b/2001-2500/2410-Maximum-Matching-of-Players-With-Trainers/cpp-2410/main.cpp new file mode 100644 index 00000000..1362009c --- /dev/null +++ b/2001-2500/2410-Maximum-Matching-of-Players-With-Trainers/cpp-2410/main.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/maximum-matching-of-players-with-trainers/ +/// Author : liuyubobobo +/// Time : 2022-09-17 + +#include +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + int matchPlayersAndTrainers(vector& players, vector& trainers) { + + sort(players.begin(), players.end(), greater()); + sort(trainers.begin(), trainers.end(), greater()); + + int res = 0, i = 0, j = 0; + for(i = 0; i < players.size() && j < trainers.size(); i ++) + if(players[i] <= trainers[j]) res ++, j ++; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2411-Smallest-Subarrays-With-Maximum-Bitwise-OR/cpp-2411/CMakeLists.txt b/2001-2500/2411-Smallest-Subarrays-With-Maximum-Bitwise-OR/cpp-2411/CMakeLists.txt new file mode 100644 index 00000000..d0dc1506 --- /dev/null +++ b/2001-2500/2411-Smallest-Subarrays-With-Maximum-Bitwise-OR/cpp-2411/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/2001-2500/2411-Smallest-Subarrays-With-Maximum-Bitwise-OR/cpp-2411/main.cpp b/2001-2500/2411-Smallest-Subarrays-With-Maximum-Bitwise-OR/cpp-2411/main.cpp new file mode 100644 index 00000000..9467affd --- /dev/null +++ b/2001-2500/2411-Smallest-Subarrays-With-Maximum-Bitwise-OR/cpp-2411/main.cpp @@ -0,0 +1,65 @@ +/// Source : https://leetcode.com/problems/smallest-subarrays-with-maximum-bitwise-or/ +/// Author : liuyubobobo +/// Time : 2022-09-17 + +#include +#include + +using namespace std; + + +/// Bitwise + Binary Search +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { + +private: + const int L = 30; + +public: + vector smallestSubarrays(vector& nums) { + + int n = nums.size(); + + vector> presum(L, vector(n + 1, 0)); + for(int i = 0; i < n; i ++){ + for(int p = 0; p < L; p ++) + presum[p][i + 1] = (nums[i] >> p) & 1; + } + + for(int p = 0; p < L; p ++) + for(int i = 0; i < n; i ++) presum[p][i + 1] += presum[p][i]; + + vector res(n, 1); + for(int i = 0; i < n; i ++){ + int t = 1; + for(int p = 0; p < L; p ++){ + if((nums[i] >> p) & 1) continue; + if(presum[p][i + 1] == presum[p].back()) continue; + auto iter = lower_bound(presum[p].begin() + (i + 1), presum[p].end(), presum[p][i + 1] + 1); + int index = iter - presum[p].begin(); + t = max(t, index - (i + 1) + 1); + } + res[i] = t; + } + return res; + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << ' '; cout << '\n'; +} + +int main() { + + vector nums1 = {1, 0, 2, 1, 3}; + print_vec(Solution().smallestSubarrays(nums1)); + // 3 3 2 2 1 + + vector nums2 = {1, 2}; + print_vec(Solution().smallestSubarrays(nums2)); + // 2 1 + + return 0; +} diff --git a/2001-2500/2412-Minimum-Money-Required-Before-Transactions/cpp-2412/CMakeLists.txt b/2001-2500/2412-Minimum-Money-Required-Before-Transactions/cpp-2412/CMakeLists.txt new file mode 100644 index 00000000..39417c0c --- /dev/null +++ b/2001-2500/2412-Minimum-Money-Required-Before-Transactions/cpp-2412/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2412) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2412 main.cpp) diff --git a/2001-2500/2412-Minimum-Money-Required-Before-Transactions/cpp-2412/main.cpp b/2001-2500/2412-Minimum-Money-Required-Before-Transactions/cpp-2412/main.cpp new file mode 100644 index 00000000..4b6f9205 --- /dev/null +++ b/2001-2500/2412-Minimum-Money-Required-Before-Transactions/cpp-2412/main.cpp @@ -0,0 +1,49 @@ +/// Source : https://leetcode.com/problems/minimum-money-required-before-transactions/description/ +/// Author : liuyubobobo +/// Time : 2023-01-09 + +#include +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + long long minimumMoney(vector>& transactions) { + + vector> neg, pos; + for(const vector& e: transactions) { + if (e[0] > e[1]) neg.push_back({e[0], e[1]}); + else pos.push_back({e[0], e[1]}); + } + + sort(neg.begin(), neg.end(), [](const pair& e1, const pair& e2){ + if(e1.second != e2.second) return e1.second < e2.second; + return e1.first > e2.first; + }); + + sort(pos.begin(), pos.end(), [](const pair& e1, const pair& e2){ + return e1.first > e2.first; + }); + + long long res = 0, cur = 0; + for(const pair& e: neg){ + cur -= e.first; + res = max(res, -cur); + cur += e.second; + } + if(!pos.empty()) cur -= pos[0].first; + return max(res, max(0ll, -cur)); + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2413-Smallest-Even-Multiple/cpp-2413/CMakeLists.txt b/2001-2500/2413-Smallest-Even-Multiple/cpp-2413/CMakeLists.txt new file mode 100644 index 00000000..daf73152 --- /dev/null +++ b/2001-2500/2413-Smallest-Even-Multiple/cpp-2413/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_2413) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2413 main.cpp) diff --git a/2001-2500/2413-Smallest-Even-Multiple/cpp-2413/main.cpp b/2001-2500/2413-Smallest-Even-Multiple/cpp-2413/main.cpp new file mode 100644 index 00000000..530da38d --- /dev/null +++ b/2001-2500/2413-Smallest-Even-Multiple/cpp-2413/main.cpp @@ -0,0 +1,26 @@ +/// Source : https://leetcode.com/problems/smallest-even-multiple/submissions/ +/// Author : liuyubobobo +/// Time : 2022-09-20 + +#include + +using namespace std; + + +/// Math +/// Time Complexity: O(1) +/// Space Complexity: O(1) +class Solution { +public: + int smallestEvenMultiple(int n) { + + if(n % 2 == 0) return n; + return n << 1; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2414-Length-of-the-Longest-Alphabetical-Continuous-Substring/cpp-2414/CMakeLists.txt b/2001-2500/2414-Length-of-the-Longest-Alphabetical-Continuous-Substring/cpp-2414/CMakeLists.txt new file mode 100644 index 00000000..8f903bf3 --- /dev/null +++ b/2001-2500/2414-Length-of-the-Longest-Alphabetical-Continuous-Substring/cpp-2414/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_2414) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2414 main.cpp) diff --git a/2001-2500/2414-Length-of-the-Longest-Alphabetical-Continuous-Substring/cpp-2414/main.cpp b/2001-2500/2414-Length-of-the-Longest-Alphabetical-Continuous-Substring/cpp-2414/main.cpp new file mode 100644 index 00000000..ff7b5e6a --- /dev/null +++ b/2001-2500/2414-Length-of-the-Longest-Alphabetical-Continuous-Substring/cpp-2414/main.cpp @@ -0,0 +1,30 @@ +/// Source : https://leetcode.com/problems/length-of-the-longest-alphabetical-continuous-substring/ +/// Author : liuyubobobo +/// Time : 2022-09-20 + +#include + +using namespace std; + + +/// String Split +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int longestContinuousSubstring(string s) { + + int n = s.size(), res = 0; + for(int start = 0, i = 1; i <= n; i ++) + if(i == n || s[i] - s[start] != i - start){ + res = max(res, i - start); + start = i; + } + return res; + } +}; + +int main() { + + return 0; +} diff --git a/2001-2500/2415-Reverse-Odd-Levels-of-Binary-Tree/cpp-2415/CMakeLists.txt b/2001-2500/2415-Reverse-Odd-Levels-of-Binary-Tree/cpp-2415/CMakeLists.txt new file mode 100644 index 00000000..ac6c4d31 --- /dev/null +++ b/2001-2500/2415-Reverse-Odd-Levels-of-Binary-Tree/cpp-2415/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_2415) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2415 main.cpp) diff --git a/2001-2500/2415-Reverse-Odd-Levels-of-Binary-Tree/cpp-2415/main.cpp b/2001-2500/2415-Reverse-Odd-Levels-of-Binary-Tree/cpp-2415/main.cpp new file mode 100644 index 00000000..4c3135fa --- /dev/null +++ b/2001-2500/2415-Reverse-Odd-Levels-of-Binary-Tree/cpp-2415/main.cpp @@ -0,0 +1,63 @@ +/// Source : https://leetcode.com/problems/reverse-odd-levels-of-binary-tree/ +/// Author : liuyubobobo +/// Time : 2022-09-20 + +#include +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +///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* reverseOddLevels(TreeNode* root) { + + vector> levels; + dfs(root, 0, levels); + + for(vector& level: levels){ + for(int i = 0, j = level.size() - 1; i < j; i ++, j --) + swap(level[i]->val, level[j]->val); + } + return root; + } + +private: + void dfs(TreeNode* node, int d, vector>& levels){ + + if(!node) return; + + if(d & 1){ + int index = (d - 1) / 2; + if(index >= levels.size()){ + assert(index == levels.size()); + levels.push_back({node}); + } + else levels[index].push_back(node); + } + + dfs(node->left, d + 1, levels); + dfs(node->right, d + 1, levels); + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2416-Sum-of-Prefix-Scores-of-Strings/cpp-2416/CMakeLists.txt b/2001-2500/2416-Sum-of-Prefix-Scores-of-Strings/cpp-2416/CMakeLists.txt new file mode 100644 index 00000000..f85f655f --- /dev/null +++ b/2001-2500/2416-Sum-of-Prefix-Scores-of-Strings/cpp-2416/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_2416) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2416 main.cpp) diff --git a/2001-2500/2416-Sum-of-Prefix-Scores-of-Strings/cpp-2416/main.cpp b/2001-2500/2416-Sum-of-Prefix-Scores-of-Strings/cpp-2416/main.cpp new file mode 100644 index 00000000..d052f2ef --- /dev/null +++ b/2001-2500/2416-Sum-of-Prefix-Scores-of-Strings/cpp-2416/main.cpp @@ -0,0 +1,75 @@ +/// Source : https://leetcode.com/problems/sum-of-prefix-scores-of-strings/ +/// Author : liuyubobobo +/// Time : 2022-09-20 + +#include +#include + +using namespace std; + + +/// Using Trie +/// Time Complexity: O(all_characters int words) +/// Space Complexity: O(all_characters int words) +class Trie { + +private: + class Node{ + + public: + vector next; + int sz; + + Node() : next(26, nullptr), sz(0) {}; + }; + + Node* root; + +public: + Trie() : root(new Node()) {} + + void insert(const string& word) { + + Node* cur = root; + root->sz ++; + for(char c: word){ + if(cur->next[c - 'a'] == nullptr) + cur->next[c - 'a'] = new Node(); + cur = cur->next[c - 'a']; + cur->sz ++; + } + } + + int query(const string& word) { + + Node* cur = root; + int res = 0; + for(char c: word){ + if(cur->next[c - 'a'] == nullptr) + return res; + cur = cur->next[c - 'a']; + res += cur->sz; + } + return res; + } +}; + +class Solution { +public: + vector sumPrefixScores(vector& words) { + + Trie trie; + for(const string& word: words) + trie.insert(word); + + vector res; + for(const string& word: words) + res.push_back(trie.query(word)); + return res; + } +}; + +int main() { + + return 0; +} diff --git a/2001-2500/2417-Closest-Fair-Integer/cpp-2417/CMakeLists.txt b/2001-2500/2417-Closest-Fair-Integer/cpp-2417/CMakeLists.txt new file mode 100644 index 00000000..66e0b340 --- /dev/null +++ b/2001-2500/2417-Closest-Fair-Integer/cpp-2417/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_2417) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2417 main.cpp) diff --git a/2001-2500/2417-Closest-Fair-Integer/cpp-2417/main.cpp b/2001-2500/2417-Closest-Fair-Integer/cpp-2417/main.cpp new file mode 100644 index 00000000..cb11dc1d --- /dev/null +++ b/2001-2500/2417-Closest-Fair-Integer/cpp-2417/main.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/closest-fair-integer/ +/// Author : liuyubobobo +/// Time : 2022-10-12 + +#include +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(logn) +/// Space Complexity: O(logn) +class Solution { +public: + int closestFair(int n) { + + string s = to_string(n); + int len = s.size(); + + int start = n; + if(len % 2) start = (int)pow(10, len); + + int i; + for(i = start; to_string(i).size() % 2 == 0; i ++) + if(good(i)) return i; + return closestFair(i); + } + +private: + bool good(int x){ + + vector f(2, 0); + while(x){ + int d = x % 10; + f[d & 1] ++; + x /= 10; + } + return f[0] == f[1]; + } +}; + + +int main() { + + cout << Solution().closestFair(2) << '\n'; + + return 0; +} diff --git a/2001-2500/2418-Sort-the-People/cpp-2418/CMakeLists.txt b/2001-2500/2418-Sort-the-People/cpp-2418/CMakeLists.txt new file mode 100644 index 00000000..ff24cc37 --- /dev/null +++ b/2001-2500/2418-Sort-the-People/cpp-2418/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_2418) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2418 main.cpp) diff --git a/2001-2500/2418-Sort-the-People/cpp-2418/main.cpp b/2001-2500/2418-Sort-the-People/cpp-2418/main.cpp new file mode 100644 index 00000000..0de539e0 --- /dev/null +++ b/2001-2500/2418-Sort-the-People/cpp-2418/main.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/sort-the-people/ +/// Author : liuyubobobo +/// Time : 2022-09-26 + +#include +#include +#include + +using namespace std; + + +/// Sorting +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + vector sortPeople(vector& names, vector& heights) { + + int n = names.size(); + + vector> data(n); + for(int i = 0; i < n; i ++) data[i] = {heights[i], names[i]}; + sort(data.begin(), data.end(), greater>()); + + vector res(n); + for(int i = 0; i < n; i ++) res[i] = data[i].second; + return res; + } +}; + +int main() { + + return 0; +} diff --git a/2001-2500/2419-Longest-Subarray-With-Maximum-Bitwise-AND/cpp-2419/CMakeLists.txt b/2001-2500/2419-Longest-Subarray-With-Maximum-Bitwise-AND/cpp-2419/CMakeLists.txt new file mode 100644 index 00000000..2571f75a --- /dev/null +++ b/2001-2500/2419-Longest-Subarray-With-Maximum-Bitwise-AND/cpp-2419/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_2419) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2419 main.cpp) diff --git a/2001-2500/2419-Longest-Subarray-With-Maximum-Bitwise-AND/cpp-2419/main.cpp b/2001-2500/2419-Longest-Subarray-With-Maximum-Bitwise-AND/cpp-2419/main.cpp new file mode 100644 index 00000000..fdf64a77 --- /dev/null +++ b/2001-2500/2419-Longest-Subarray-With-Maximum-Bitwise-AND/cpp-2419/main.cpp @@ -0,0 +1,36 @@ +/// Source : https://leetcode.com/problems/longest-subarray-with-maximum-bitwise-and/ +/// Author : liuyubobobo +/// Time : 2022-09-26 + +#include +#include +#include + +using namespace std; + + +/// Split +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int longestSubarray(vector& nums) { + + int target = *max_element(nums.begin(), nums.end()); + + int res = 1; + for(int start = 0, i = 1; i <= nums.size(); i ++){ + if(i == nums.size() || nums[i] != nums[start]){ + if(nums[start] == target) res = max(res, i - start); + start = i; + } + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2420-Find-All-Good-Indices/cpp-2420/CMakeLists.txt b/2001-2500/2420-Find-All-Good-Indices/cpp-2420/CMakeLists.txt new file mode 100644 index 00000000..5310359f --- /dev/null +++ b/2001-2500/2420-Find-All-Good-Indices/cpp-2420/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_2420) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2420 main.cpp) diff --git a/2001-2500/2420-Find-All-Good-Indices/cpp-2420/main.cpp b/2001-2500/2420-Find-All-Good-Indices/cpp-2420/main.cpp new file mode 100644 index 00000000..17ba665e --- /dev/null +++ b/2001-2500/2420-Find-All-Good-Indices/cpp-2420/main.cpp @@ -0,0 +1,36 @@ +/// Source : https://leetcode.com/problems/find-all-good-indices/ +/// Author : liuyubobobo +/// Time : 2022-09-26 + +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector goodIndices(vector& nums, int k) { + + int n = nums.size(); + vector dp1(n, 1), dp2(n, 1); + for(int i = 1; i < n; i ++) + if(nums[i] <= nums[i - 1]) dp1[i] = 1 + dp1[i - 1]; + for(int i = n - 2; i >= 0; i --) + if(nums[i] <= nums[i + 1]) dp2[i] = 1 + dp2[i + 1]; + + vector res; + for(int i = 1; i < n - 1; i ++) + if(dp1[i - 1] >= k && dp2[i + 1] >= k) res.push_back(i); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2421-Number-of-Good-Paths/cpp-2421/CMakeLists.txt b/2001-2500/2421-Number-of-Good-Paths/cpp-2421/CMakeLists.txt new file mode 100644 index 00000000..51dae3bd --- /dev/null +++ b/2001-2500/2421-Number-of-Good-Paths/cpp-2421/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_2421) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2421 main.cpp) diff --git a/2001-2500/2421-Number-of-Good-Paths/cpp-2421/main.cpp b/2001-2500/2421-Number-of-Good-Paths/cpp-2421/main.cpp new file mode 100644 index 00000000..e4a923ec --- /dev/null +++ b/2001-2500/2421-Number-of-Good-Paths/cpp-2421/main.cpp @@ -0,0 +1,92 @@ +/// Source : https://leetcode.com/problems/number-of-good-paths/ +/// Author : liuyubobobo +/// Time : 2022-10-12 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// Using UF +/// Time Complexity: O(max(vals) + |edges|) +/// Space Complexity: O(n) +class UF{ + +private: + vector parent; + +public: + UF(int n) : parent(n){ + for(int i = 0 ; i < n ; i ++) + parent[i] = i; + } + + int find(int p){ + if(p != parent[p]) + parent[p] = find(parent[p]); + return parent[p]; + } + + bool is_connected(int p, int q){ + return find(p) == find(q); + } + + void union_elements(int p, int q){ + + int p_root = find(p), q_root = find(q); + + if(p_root == q_root) return; + + parent[p_root] = q_root; + } +}; + +class Solution { +public: + int numberOfGoodPaths(vector& vals, vector>& edges) { + + int n = vals.size(); + int max_vals = *max_element(vals.begin(), vals.end()); + + vector>> data(max_vals + 1); + for(const vector& edge: edges){ + int a = edge[0], b = edge[1]; + data[max(vals[a], vals[b])].push_back({a, b}); + } + + UF uf(n); + int res = n; + for(int v = 0; v <= max_vals; v ++){ + list>& l = data[v]; + set vset; + for(const pair& p: l) { + uf.union_elements(p.first, p.second); + if(vals[p.first] == v) vset.insert(p.first); + if(vals[p.second] == v) vset.insert(p.second); + } + + map cc; + for(int u: vset) cc[uf.find(u)] ++; + + for(const pair& p: cc){ + int k = p.second; + res += k * (k - 1) / 2; + } + } + return res; + } +}; + + +int main() { + + vector vals1 = {1, 3, 2, 1, 3}; + vector> edges1 = {{0, 1}, {0, 2}, {2, 3}, {2, 4}}; + cout << Solution().numberOfGoodPaths(vals1, edges1) << '\n'; + + return 0; +} diff --git a/2001-2500/2422-Merge-Operations-to-Turn-Array-Into-a-Palindrome/cpp-2422/CMakeLists.txt b/2001-2500/2422-Merge-Operations-to-Turn-Array-Into-a-Palindrome/cpp-2422/CMakeLists.txt new file mode 100644 index 00000000..a25cd34d --- /dev/null +++ b/2001-2500/2422-Merge-Operations-to-Turn-Array-Into-a-Palindrome/cpp-2422/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_2422) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2422 main.cpp) diff --git a/2001-2500/2422-Merge-Operations-to-Turn-Array-Into-a-Palindrome/cpp-2422/main.cpp b/2001-2500/2422-Merge-Operations-to-Turn-Array-Into-a-Palindrome/cpp-2422/main.cpp new file mode 100644 index 00000000..590e6a7a --- /dev/null +++ b/2001-2500/2422-Merge-Operations-to-Turn-Array-Into-a-Palindrome/cpp-2422/main.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/merge-operations-to-turn-array-into-a-palindrome/ +/// Author : liuyubobobo +/// Time : 2022-09-30 + +#include +#include +#include + +using namespace std; + + +/// Greedy and using deque +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int minimumOperations(vector& nums) { + + deque q; + for(int e: nums) q.push_back(e); + + int res = 0; + while(q.size() > 1){ + long long front = q.front(), tail = q.back(); + if(front == tail) q.pop_front(), q.pop_back(); + else if(front < tail){ + q.pop_front(); + long long x = q.front(); q.pop_front(); + q.push_front(x + front); + res ++; + } + else{ + q.pop_back(); + long long x = q.back(); q.pop_back(); + q.push_back(x + tail); + res ++; + } + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2423-Remove-Letter-To-Equalize-Frequency/cpp-2423/CMakeLists.txt b/2001-2500/2423-Remove-Letter-To-Equalize-Frequency/cpp-2423/CMakeLists.txt new file mode 100644 index 00000000..28513559 --- /dev/null +++ b/2001-2500/2423-Remove-Letter-To-Equalize-Frequency/cpp-2423/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_2423) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2423 main.cpp) diff --git a/2001-2500/2423-Remove-Letter-To-Equalize-Frequency/cpp-2423/main.cpp b/2001-2500/2423-Remove-Letter-To-Equalize-Frequency/cpp-2423/main.cpp new file mode 100644 index 00000000..37c69071 --- /dev/null +++ b/2001-2500/2423-Remove-Letter-To-Equalize-Frequency/cpp-2423/main.cpp @@ -0,0 +1,48 @@ +/// Source : https://leetcode.com/problems/remove-letter-to-equalize-frequency/ +/// Author : liuyubobobo +/// Time : 2022-10-02 + +#include +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Compelxity: O(|word| + 26^2) +/// Space Complexity: O(26) +class Solution { +public: + bool equalFrequency(string word) { + + vector f(26, 0); + for(char c: word) f[c - 'a'] ++; + + for(int i = 0; i < 26; i ++) + if(f[i]){ + f[i] --; + if(ok(f)) return true; + f[i] ++; + } + return false; + } + +private: + bool ok(const vector& f){ + + int t = -1; + for(int i = 0; i < 26 && t == -1; i ++) + if(f[i]) t = f[i]; + + for(int i = 0; i < 26; i ++) + if(f[i] && f[i] != t) return false; + return true; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2424-Longest-Uploaded-Prefix/cpp-2424/CMakeLists.txt b/2001-2500/2424-Longest-Uploaded-Prefix/cpp-2424/CMakeLists.txt new file mode 100644 index 00000000..5fd22870 --- /dev/null +++ b/2001-2500/2424-Longest-Uploaded-Prefix/cpp-2424/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_2424) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2424 main.cpp) diff --git a/2001-2500/2424-Longest-Uploaded-Prefix/cpp-2424/main.cpp b/2001-2500/2424-Longest-Uploaded-Prefix/cpp-2424/main.cpp new file mode 100644 index 00000000..5bb656d9 --- /dev/null +++ b/2001-2500/2424-Longest-Uploaded-Prefix/cpp-2424/main.cpp @@ -0,0 +1,39 @@ +/// Source : https://leetcode.com/problems/longest-uploaded-prefix/ +/// Author : liuyubobobo +/// Time : 2022-10-02 + +#include +#include + +using namespace std; + + +/// Using TreeSet +/// Time Complexity: init: O(nlogn) +/// upload and longest: O(logn) +/// Space Complexity: O(n) +class LUPrefix { + +private: + set available; + +public: + LUPrefix(int n) { + for(int i = 1; i <= n + 1; i ++) available.insert(i); + } + + void upload(int video) { + available.erase(video); + } + + int longest() { + auto iter = available.lower_bound(1); + return *iter - 1; + } +}; + + +int main() { + std::cout << "Hello, World!" << std::endl; + return 0; +} diff --git a/2001-2500/2425-Bitwise-XOR-of-All-Pairings/cpp-2425/CMakeLists.txt b/2001-2500/2425-Bitwise-XOR-of-All-Pairings/cpp-2425/CMakeLists.txt new file mode 100644 index 00000000..58130ea2 --- /dev/null +++ b/2001-2500/2425-Bitwise-XOR-of-All-Pairings/cpp-2425/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_2425) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2425 main.cpp) diff --git a/2001-2500/2425-Bitwise-XOR-of-All-Pairings/cpp-2425/main.cpp b/2001-2500/2425-Bitwise-XOR-of-All-Pairings/cpp-2425/main.cpp new file mode 100644 index 00000000..2b109210 --- /dev/null +++ b/2001-2500/2425-Bitwise-XOR-of-All-Pairings/cpp-2425/main.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/bitwise-xor-of-all-pairings/ +/// Author : liuyubobobo +/// Time : 2022-10-03 + +#include +#include + +using namespace std; + + +/// Bitwise +/// Time Complexity: O(n + m) +/// Space Complexity: O(1) +class Solution { +public: + int xorAllNums(vector& nums1, vector& nums2) { + + int n = nums1.size(), m = nums2.size(); + + int res = 0; + for(int e: nums1) + if(m & 1) res ^= e; + for(int e: nums2) + if(n & 1) res ^= e; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2426-Number-of-Pairs-Satisfying-Inequality/cpp-2426/CMakeLists.txt b/2001-2500/2426-Number-of-Pairs-Satisfying-Inequality/cpp-2426/CMakeLists.txt new file mode 100644 index 00000000..93932f83 --- /dev/null +++ b/2001-2500/2426-Number-of-Pairs-Satisfying-Inequality/cpp-2426/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_2426) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2426 main.cpp) diff --git a/2001-2500/2426-Number-of-Pairs-Satisfying-Inequality/cpp-2426/main.cpp b/2001-2500/2426-Number-of-Pairs-Satisfying-Inequality/cpp-2426/main.cpp new file mode 100644 index 00000000..739b277f --- /dev/null +++ b/2001-2500/2426-Number-of-Pairs-Satisfying-Inequality/cpp-2426/main.cpp @@ -0,0 +1,327 @@ +/// Source : https://leetcode.com/problems/number-of-pairs-satisfying-inequality/ +/// Author : liuyubobobo +/// Time : 2022-10-03 + +#include +#include +#include + +using namespace std; + + +/// Using AVL Tree +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +template +class AVLTreeMultiSet{ + +private: + class Node{ + public: + Key key; + Node *left = nullptr, *right = nullptr; + int height = 1, size = 1; + + Node(const Key& key): key(key){} + }; + + Node* root = nullptr; + +public: + AVLTreeMultiSet(){} + + int size(){ + return size(root); + } + + void add(const Key& key){ + root = add(root, key); + } + + void remove(const Key& key){ + root = remove(root, key); + } + + bool contains(const Key& key){ + return get_node(root, key) != nullptr; + } + + // 0-based rank + int get_index(const Key& key){ + + Node* node = get_node(root, key); + assert(node); + + return size_less_than(key); + } + + // 0-based select + Key select(int index){ + + assert(index < size(root)); + return select(root, index); + } + + // < key 的元素有几个? + int size_less_than(const Key& key){ + return size_less_than(root, key); + } + + // <= key 的元素有几个? + int size_less_than_or_equal_to(const Key& key){ + return size_less_than_or_equal_to(root, key); + } + + // > key 的元素有几个? + int size_larger_than(const Key& key){ + return size_larger_than(root, key); + } + + // >= key 的元素有几个? + int size_larger_than_or_equal_to(const Key& key){ + return size_larger_than_or_equal_to(root, key); + } + +private: + int size(Node* node){ + return node ? node->size : 0; + } + + int height(Node* node){ + return node ? node->height : 0; + } + + int get_balance_factor(Node* node){ + return height(node->left) - height(node->right); + } + + Node* right_rotate(Node* y) { + Node* x = y->left; + Node* T3 = x->right; + + // 向右旋转过程 + x->right = y; + y->left = T3; + + // 更新 height 和 size + y->height = max(height(y->left), height(y->right)) + 1; + x->height = max(height(x->left), height(x->right)) + 1; + + y->size = size(y->left) + size(y->right) + 1; + x->size = size(x->left) + size(x->right) + 1; + + return x; + } + + Node* left_rotate(Node* y) { + Node* x = y->right; + Node* T2 = x->left; + + // 向左旋转过程 + x->left = y; + y->right = T2; + + // 更新 height 和 size + y->height = max(height(y->left), height(y->right)) + 1; + x->height = max(height(x->left), height(x->right)) + 1; + + y->size = size(y->left) + size(y->right) + 1; + x->size = size(x->left) + size(x->right) + 1; + + return x; + } + + // 向以node为根的二分搜索树中插入元素(key, value),递归算法 + // 返回插入新节点后二分搜索树的根 + Node* add(Node* node, const Key& key){ + + if(node == nullptr) + return new Node(key); + + if(key <= node->key) + node->left = add(node->left, key); + else if(key > node->key) + node->right = add(node->right, key); + + return keep_balance(node); + } + + Node* remove(Node* node, const Key& key){ + + if(node == nullptr) + return nullptr; + + Node* ret_node; + if(key < node->key){ + node->left = remove(node->left, key); + ret_node = node; + } + else if(key > node->key){ + node->right = remove(node->right, key); + ret_node = node; + } + else{ + + // 待删除节点左子树为空的情况 + if(node->left == nullptr){ + Node* right_node = node->right; + node->right = nullptr; + ret_node = right_node; + } + // 待删除节点右子树为空的情况 + else if(node->right == nullptr){ + Node* left_node = node->left; + node->left = nullptr; + ret_node = left_node; + } + // 待删除节点左右子树均不为空的情况 + else{ + // 找到比待删除节点大的最小节点, 即待删除节点右子树的最小节点 + // 用这个节点顶替待删除节点的位置 + Node* min_node = get_min_node(node->right); + assert(min_node); + node->key = min_node->key; + + node->right = remove_min(node->right); + ret_node = node; + } + } + + return keep_balance(ret_node); + } + + Node* remove_min(Node* node){ + + if(node == nullptr) + return nullptr; + + Node* ret_node; + if(node->left) { + node->left = remove_min(node->left); + ret_node = node; + } + else + ret_node = node->right; + + return keep_balance(ret_node); + } + + Node* get_min_node(Node* node){ + + if(!node) return nullptr; + + if(node->left) return get_min_node(node->left); + return node; + } + + Node* keep_balance(Node* node){ + + if(!node) return nullptr; + + // 更新 height 和 size + node->height = 1 + max(height(node->left), height(node->right)); + node->size = 1 + size(node->left) + size(node->right); + + // 计算平衡因子 + int balance_factor = get_balance_factor(node); + + // 平衡维护 + // LL + if (balance_factor > 1 && get_balance_factor(node->left) >= 0) + return right_rotate(node); + + // RR + if (balance_factor < -1 && get_balance_factor(node->right) <= 0) + return left_rotate(node); + + // LR + if (balance_factor > 1 && get_balance_factor(node->left) < 0) { + node->left = left_rotate(node->left); + return right_rotate(node); + } + + // RL + if (balance_factor < -1 && get_balance_factor(node->right) > 0) { + node->right = right_rotate(node->right); + return left_rotate(node); + } + + return node; + } + + Node* get_node(Node* node, const Key& key){ + + if(node == nullptr) + return nullptr; + + if(key == node->key) + return node; + else if(key < node->key) + return get_node(node->left, key); + else + return get_node(node->right, key); + } + + Key select(Node* node, int index){ + + if(index < size(node->left)) return select(node->left, index); + + if(index == size(node->left)) return node->key; + + return select(node->right, index - size(node->left) - 1); + } + + // < key 的元素有几个 + int size_less_than(Node* node, const Key& key){ + if(!node) return 0; + if(key <= node->key) return size_less_than(node->left, key); + return size(node->left) + 1 + size_less_than(node->right, key); + } + + // <= key 的元素有几个 + int size_less_than_or_equal_to(Node* node, const Key& key){ + if(!node) return 0; + if(key < node->key) return size_less_than_or_equal_to(node->left, key); + return size(node->left) + 1 + size_less_than_or_equal_to(node->right, key); + } + + // > key 的元素有几个 + int size_larger_than(Node* node, const Key& key){ + if(!node) return 0; + if(key >= node->key) return size_larger_than(node->right, key); + return size_larger_than(node->left, key) + 1 + size(node->right); + } + + // >= key 的元素有几个 + int size_larger_than_or_equal_to(Node* node, const Key& key){ + if(!node) return 0; + if(key > node->key) return size_larger_than_or_equal_to(node->right, key); + return size_larger_than_or_equal_to(node->left, key) + 1 + size(node->right); + } +}; + +class Solution { +public: + long long numberOfPairs(vector& nums1, vector& nums2, int diff) { + + int n = nums1.size(); + vector data(n); + for(int i = 0; i < n; i ++) data[i] = nums1[i] - nums2[i]; + + AVLTreeMultiSet tree; + for(int e: data) tree.add(e); + + long long res = 0; + for(int e: data){ + tree.remove(e); + res += tree.size_larger_than_or_equal_to(e - diff); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2427-Number-of-Common-Factors/cpp-2427/CMakeLists.txt b/2001-2500/2427-Number-of-Common-Factors/cpp-2427/CMakeLists.txt new file mode 100644 index 00000000..415e0a92 --- /dev/null +++ b/2001-2500/2427-Number-of-Common-Factors/cpp-2427/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/2001-2500/2427-Number-of-Common-Factors/cpp-2427/main.cpp b/2001-2500/2427-Number-of-Common-Factors/cpp-2427/main.cpp new file mode 100644 index 00000000..52ee93e1 --- /dev/null +++ b/2001-2500/2427-Number-of-Common-Factors/cpp-2427/main.cpp @@ -0,0 +1,30 @@ +/// Source : https://leetcode.com/problems/number-of-common-factors/ +/// Author : liuyubobobo +/// Time : 2022-10-01 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(min(a, b)) +/// Space Complexity: O(1) +class Solution { +public: + int commonFactors(int a, int b) { + + int res = 0; + int n = min(a, b); + for(int i = 1; i <= n; i ++) + if(a % i == 0 && b % i == 0) res ++; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2428-Maximum-Sum-of-an-Hourglass/cpp-2428/CMakeLists.txt b/2001-2500/2428-Maximum-Sum-of-an-Hourglass/cpp-2428/CMakeLists.txt new file mode 100644 index 00000000..b1c82ab8 --- /dev/null +++ b/2001-2500/2428-Maximum-Sum-of-an-Hourglass/cpp-2428/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/2001-2500/2428-Maximum-Sum-of-an-Hourglass/cpp-2428/main.cpp b/2001-2500/2428-Maximum-Sum-of-an-Hourglass/cpp-2428/main.cpp new file mode 100644 index 00000000..33dec21b --- /dev/null +++ b/2001-2500/2428-Maximum-Sum-of-an-Hourglass/cpp-2428/main.cpp @@ -0,0 +1,32 @@ +/// Source : https://leetcode.com/problems/maximum-sum-of-an-hourglass/ +/// Author : liuyubobobo +/// Time : 2022-10-01 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(R * C) +/// Space Complexity: O(1) +class Solution { +public: + int maxSum(vector>& g) { + + int R = g.size(), C = g[0].size(), res = 0; + for(int i = 0; i + 2 < R; i ++) + for(int j = 0; j + 2 < C; j ++){ + int t = g[i][j] + g[i][j + 1] + g[i][j + 2] + g[i + 1][j + 1] + g[i + 2][j] + g[i + 2][j + 1] + g[i + 2][j + 2]; + res = max(res, t); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2429-Minimize-XOR/cpp-2429/CMakeLists.txt b/2001-2500/2429-Minimize-XOR/cpp-2429/CMakeLists.txt new file mode 100644 index 00000000..d0dc1506 --- /dev/null +++ b/2001-2500/2429-Minimize-XOR/cpp-2429/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/2001-2500/2429-Minimize-XOR/cpp-2429/main.cpp b/2001-2500/2429-Minimize-XOR/cpp-2429/main.cpp new file mode 100644 index 00000000..b2d16528 --- /dev/null +++ b/2001-2500/2429-Minimize-XOR/cpp-2429/main.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/minimize-xor/ +/// Author : liuyubobobo +/// Time : 2022-10-01 + +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(log(num1) + log(num2)) +/// Space Complexity: O(1) +class Solution { +public: + int minimizeXor(int num1, int num2) { + + int one_cnt = __builtin_popcount(num2); + + int D = get_len(num1), res = 0; + for(int p = D - 1; p >= 0 && one_cnt; p --) + if((num1 >> p) & 1) one_cnt --, res += (1 << p); + + for(int p = 0; p <= 30 && one_cnt; p ++) + if(((num1 >> p) & 1) == 0) one_cnt --, res += (1 << p); + + return res; + } + +private: + int get_len(int x){ + int res = 0; + while(x){ + res ++, x >>= 1; + } + return res; + } +}; + + +int main() { + + cout << Solution().minimizeXor(3, 5) << '\n'; + // 3 + + cout << Solution().minimizeXor(1, 12) << '\n'; + // 3 + + cout << Solution().minimizeXor(91, 18) << '\n'; + // 80 + + return 0; +} diff --git a/2001-2500/2430-Maximum-Deletions-on-a-String/cpp-2430/CMakeLists.txt b/2001-2500/2430-Maximum-Deletions-on-a-String/cpp-2430/CMakeLists.txt new file mode 100644 index 00000000..541b2eff --- /dev/null +++ b/2001-2500/2430-Maximum-Deletions-on-a-String/cpp-2430/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main2.cpp) diff --git a/2001-2500/2430-Maximum-Deletions-on-a-String/cpp-2430/main.cpp b/2001-2500/2430-Maximum-Deletions-on-a-String/cpp-2430/main.cpp new file mode 100644 index 00000000..32b579a6 --- /dev/null +++ b/2001-2500/2430-Maximum-Deletions-on-a-String/cpp-2430/main.cpp @@ -0,0 +1,66 @@ +/// Source : https://leetcode.com/problems/maximum-deletions-on-a-string/ +/// Author : liuyubobobo +/// Time : 2022-10-01 + +#include +#include + +using namespace std; + + +/// RK + DP +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class StringHashU{ + +private: + int n; + unsigned long long B; + vector h, p; + +public: + StringHashU(const string& s, unsigned long long B = 13331) : + n(s.size()), h(n + 1, 0), p(n + 1, 1), B(B){ + + for(int i = 0; i < n; i ++){ + h[i + 1] = h[i] * B + s[i]; + p[i + 1] = p[i] * B; + } + } + + unsigned long long get_hash(int l, int r){ + assert(l >= 0 && l < n); + assert(r >= 0 && r < n); + return h[r + 1] - h[l] * p[r - l + 1]; + } +}; + +class Solution { +public: + int deleteString(string s) { + + StringHashU hash(s); + + int n = s.size(); + vector dp(n + 1, 0); + dp[n - 1] = 1; + for(int start = n - 2; start >= 0; start --){ + int len = n - start, tres = 1; + for(int i = 1; i <= len / 2; i ++) + if(hash.get_hash(start, start + i - 1) == hash.get_hash(start + i, start + 2 * i - 1)) + tres = max(tres, 1 + dp[start + i]); + dp[start] = tres; + } + return dp[0]; + } +}; + + +int main() { + + string s2 = "aaabaab"; + cout << Solution().deleteString(s2) << '\n'; + // 4 + + return 0; +} diff --git a/2001-2500/2430-Maximum-Deletions-on-a-String/cpp-2430/main2.cpp b/2001-2500/2430-Maximum-Deletions-on-a-String/cpp-2430/main2.cpp new file mode 100644 index 00000000..01d026e7 --- /dev/null +++ b/2001-2500/2430-Maximum-Deletions-on-a-String/cpp-2430/main2.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/maximum-deletions-on-a-string/ +/// Author : liuyubobobo +/// Time : 2022-10-02 + +#include +#include + +using namespace std; + + +/// Double DP +/// It's slower than using RK but this method is more standard. +/// Time Complexity: O(n^2) +/// Space Complexity: O(n^2) +class Solution { +public: + int deleteString(string s) { + + int n = s.size(); + + vector> lcs(n + 1, vector(n + 1, 0)); + for(int i = n - 1; i >= 0; i --) + for(int j = n - 1; j >= 0; j --) + if(s[i] == s[j]) lcs[i][j] = 1 + lcs[i + 1][j + 1]; + + vector dp(n + 1, 0); + dp[n - 1] = 1; + for(int start = n - 2; start >= 0; start --){ + int len = n - start, tres = 1; + for(int i = 1; i <= len / 2; i ++) + if(lcs[start][start + i] >= i) + tres = max(tres, 1 + dp[start + i]); + dp[start] = tres; + } + return dp[0]; + } +}; + + +int main() { + + string s2 = "aaabaab"; + cout << Solution().deleteString(s2) << '\n'; + // 4 + + return 0; +} diff --git a/2001-2500/2431-Maximize-Total-Tastiness-of-Purchased-Fruits/cpp-2431/CMakeLists.txt b/2001-2500/2431-Maximize-Total-Tastiness-of-Purchased-Fruits/cpp-2431/CMakeLists.txt new file mode 100644 index 00000000..6268af43 --- /dev/null +++ b/2001-2500/2431-Maximize-Total-Tastiness-of-Purchased-Fruits/cpp-2431/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_2431) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2431 main.cpp) diff --git a/2001-2500/2431-Maximize-Total-Tastiness-of-Purchased-Fruits/cpp-2431/main.cpp b/2001-2500/2431-Maximize-Total-Tastiness-of-Purchased-Fruits/cpp-2431/main.cpp new file mode 100644 index 00000000..971e79ec --- /dev/null +++ b/2001-2500/2431-Maximize-Total-Tastiness-of-Purchased-Fruits/cpp-2431/main.cpp @@ -0,0 +1,44 @@ +/// Source : https://leetcode.com/problems/maximize-total-tastiness-of-purchased-fruits/ +/// Author : liuyubobobo +/// Time : 2022-10-06 + +#include +#include + +using namespace std; + + +/// Memoization +/// Time Complexity: O(n * maxAmount * maxCoupons) +/// Space Complexity: O(n * maxAmount * maxCoupons) +class Solution { +public: + int maxTastiness(vector& price, vector& tastiness, int maxAmount, int maxCoupons) { + + int n = price.size(); + + vector>> dp(n, vector>(maxAmount + 1, vector(maxCoupons + 1, -1))); + return dfs(price, tastiness, n - 1, maxAmount, maxCoupons, dp); + } + +private: + int dfs(const vector& price, const vector& tastiness, + int index, int amount, int coupons, vector>>& dp){ + + if(index == -1) return 0; + if(dp[index][amount][coupons] != -1) return dp[index][amount][coupons]; + + int res = dfs(price, tastiness, index - 1, amount, coupons, dp); + if(price[index] <= amount) + res = max(res, tastiness[index] + dfs(price, tastiness, index - 1, amount - price[index], coupons, dp)); + if(coupons && price[index] / 2 <= amount) + res = max(res, tastiness[index] + dfs(price, tastiness, index - 1, amount - price[index] / 2, coupons - 1, dp)); + return dp[index][amount][coupons] = res; + } +}; + + +int main() { + std::cout << "Hello, World!" << std::endl; + return 0; +} diff --git a/2001-2500/2432-The-Employee-That-Worked-on-the-Longest-Task/cpp-2432/CMakeLists.txt b/2001-2500/2432-The-Employee-That-Worked-on-the-Longest-Task/cpp-2432/CMakeLists.txt new file mode 100644 index 00000000..415e0a92 --- /dev/null +++ b/2001-2500/2432-The-Employee-That-Worked-on-the-Longest-Task/cpp-2432/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/2001-2500/2432-The-Employee-That-Worked-on-the-Longest-Task/cpp-2432/main.cpp b/2001-2500/2432-The-Employee-That-Worked-on-the-Longest-Task/cpp-2432/main.cpp new file mode 100644 index 00000000..f48392c8 --- /dev/null +++ b/2001-2500/2432-The-Employee-That-Worked-on-the-Longest-Task/cpp-2432/main.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/the-employee-that-worked-on-the-longest-task/ +/// Author : liuyubobobo +/// Time : 2022-10-08 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int hardestWorker(int n, vector>& logs) { + + int max_t = -1, res = INT_MAX; + int cur = 0; + for(const vector& log: logs){ + int id = log[0], t = log[1]; + if(t - cur > max_t) + res = id, max_t = t - cur; + else if(t - cur == max_t) + res = min(res, id); + cur = t; + } + return res; + } +}; + + +int main() { + + vector> logs1 = {{0, 3}, {2, 5}, {0, 9}, {1, 15}}; + cout << Solution().hardestWorker(10, logs1) << '\n'; + // 1 + + return 0; +} diff --git a/2001-2500/2433-Find-The-Original-Array-of-Prefix-Xor/cpp-2433/CMakeLists.txt b/2001-2500/2433-Find-The-Original-Array-of-Prefix-Xor/cpp-2433/CMakeLists.txt new file mode 100644 index 00000000..b1c82ab8 --- /dev/null +++ b/2001-2500/2433-Find-The-Original-Array-of-Prefix-Xor/cpp-2433/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/2001-2500/2433-Find-The-Original-Array-of-Prefix-Xor/cpp-2433/main.cpp b/2001-2500/2433-Find-The-Original-Array-of-Prefix-Xor/cpp-2433/main.cpp new file mode 100644 index 00000000..b57ebb8f --- /dev/null +++ b/2001-2500/2433-Find-The-Original-Array-of-Prefix-Xor/cpp-2433/main.cpp @@ -0,0 +1,29 @@ +/// Source : https://leetcode.com/problems/find-the-original-array-of-prefix-xor/ +/// Author : liuyubobobo +/// Time : 2022-10-08 + +#include +#include + +using namespace std; + + +/// Bitwise +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + vector findArray(vector& pref) { + + int n = pref.size(); + vector res(n, pref[0]); + for(int i = 1; i < n; i ++) res[i] = pref[i] ^ pref[i - 1]; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2434-Using-a-Robot-to-Print-the-Lexicographically-Smallest-String/cpp-2434/CMakeLists.txt b/2001-2500/2434-Using-a-Robot-to-Print-the-Lexicographically-Smallest-String/cpp-2434/CMakeLists.txt new file mode 100644 index 00000000..d0dc1506 --- /dev/null +++ b/2001-2500/2434-Using-a-Robot-to-Print-the-Lexicographically-Smallest-String/cpp-2434/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/2001-2500/2434-Using-a-Robot-to-Print-the-Lexicographically-Smallest-String/cpp-2434/main.cpp b/2001-2500/2434-Using-a-Robot-to-Print-the-Lexicographically-Smallest-String/cpp-2434/main.cpp new file mode 100644 index 00000000..f274eb54 --- /dev/null +++ b/2001-2500/2434-Using-a-Robot-to-Print-the-Lexicographically-Smallest-String/cpp-2434/main.cpp @@ -0,0 +1,69 @@ +/// Source : https://leetcode.com/problems/using-a-robot-to-print-the-lexicographically-smallest-string/ +/// Author : liuyubobobo +/// Time : 2022-10-09 + +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + string robotWithString(string s) { + + vector f(26, 0); + for(char c: s) f[c - 'a'] ++; + + vector stack; + string res = ""; + for(char c: s){ + stack.push_back(c); + f[c - 'a'] --; + while(!stack.empty() && is_min(f, stack.back())){ + res += stack.back(); + stack.pop_back(); + } + + } + while(!stack.empty()) res += stack.back(), stack.pop_back(); + return res; + } + +private: + bool is_min(const vector& f, char c){ + + char min_c = 'z' + 1; + for(int i = 0; i < 26; i ++) + if(f[i]){ + min_c = (char)('a' + i); + break; + } + return c <= min_c; + } +}; + + +int main() { + + string s1 = "zza"; + cout << Solution().robotWithString(s1) << '\n'; + // azz + + string s2 = "bac"; + cout << Solution().robotWithString(s2) << '\n'; + // abc + + string s3 = "bdda"; + cout << Solution().robotWithString(s3) << '\n'; + // addb + + string s4 = "vzhofnpo"; + cout << Solution().robotWithString(s4) << '\n'; + // fnohopzv + + return 0; +} diff --git a/2001-2500/2435-Paths-in-Matrix-Whose-Sum-Is-Divisible-by-K/cpp-2435/CMakeLists.txt b/2001-2500/2435-Paths-in-Matrix-Whose-Sum-Is-Divisible-by-K/cpp-2435/CMakeLists.txt new file mode 100644 index 00000000..541b2eff --- /dev/null +++ b/2001-2500/2435-Paths-in-Matrix-Whose-Sum-Is-Divisible-by-K/cpp-2435/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main2.cpp) diff --git a/2001-2500/2435-Paths-in-Matrix-Whose-Sum-Is-Divisible-by-K/cpp-2435/main.cpp b/2001-2500/2435-Paths-in-Matrix-Whose-Sum-Is-Divisible-by-K/cpp-2435/main.cpp new file mode 100644 index 00000000..dd8589bc --- /dev/null +++ b/2001-2500/2435-Paths-in-Matrix-Whose-Sum-Is-Divisible-by-K/cpp-2435/main.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/paths-in-matrix-whose-sum-is-divisible-by-k/ +/// Author : liuyubobobo +/// Time : 2022-10-09 + +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(R * C * k) +/// Space Complexity: O(R * C * k) +class Solution { + +private: + const long long MOD = 1e9 + 7; + +public: + int numberOfPaths(vector>& grid, int k) { + + int R = grid.size(), C = grid[0].size(); + vector>> dp(R, vector>(C, vector(k, 0))); + dp[0][0][grid[0][0] % k] = 1; + + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++) { + if(i == 0 && j == 0) continue; + for (int m = 0; m < k; m++) { + long long t = 0; + + int a = m - grid[i][j]; + if (a < 0) + a = (a % k + k) % k; + + if(i - 1 >= 0) t += dp[i - 1][j][a]; + if(j - 1 >= 0) t += dp[i][j - 1][a]; + + dp[i][j][m] = t % MOD; + } + } + return dp[R - 1][C - 1][0]; + } +}; + + +int main() { + + vector> grid1 = {{5,2,4},{3,0,5},{0,7,2}}; + cout << Solution().numberOfPaths(grid1, 3) << '\n'; + // 2 + + return 0; +} diff --git a/2001-2500/2435-Paths-in-Matrix-Whose-Sum-Is-Divisible-by-K/cpp-2435/main2.cpp b/2001-2500/2435-Paths-in-Matrix-Whose-Sum-Is-Divisible-by-K/cpp-2435/main2.cpp new file mode 100644 index 00000000..7ad28ca1 --- /dev/null +++ b/2001-2500/2435-Paths-in-Matrix-Whose-Sum-Is-Divisible-by-K/cpp-2435/main2.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/paths-in-matrix-whose-sum-is-divisible-by-k/ +/// Author : liuyubobobo +/// Time : 2022-10-09 + +#include +#include + +using namespace std; + + +/// Memoization +/// Time Complexity: O(R * C * k) +/// Space Complexity: O(R * C * k) +class Solution { + +private: + const long long MOD = 1e9 + 7; + int R, C, k; + +public: + int numberOfPaths(vector>& grid, int k) { + + R = grid.size(), C = grid[0].size(); + this->k = k; + vector>> dp(R, vector>(C, vector(k, -1))); + + return dfs(grid, 0, 0, grid[0][0] % k, dp); + } + +private: + long long dfs(const vector>& grid, int x, int y, int m, + vector>>& dp){ + + if(x == R - 1 && y == C - 1) return m == 0; + if(dp[x][y][m] != -1) return dp[x][y][m]; + + long long res = 0; + if(x + 1 < R) res += dfs(grid, x + 1, y, (m + grid[x + 1][y]) % k, dp); + if(y + 1 < C) res += dfs(grid, x, y + 1, (m + grid[x][y + 1]) % k, dp); + return dp[x][y][m] = res % MOD; + } +}; + + +int main() { + + vector> grid1 = {{5,2,4},{3,0,5},{0,7,2}}; + cout << Solution().numberOfPaths(grid1, 3) << '\n'; + // 2 + + return 0; +} diff --git a/2001-2500/2436-Minimum-Split-Into-Subarrays-With-GCD-Greater-Than-One/cpp-2436/CMakeLists.txt b/2001-2500/2436-Minimum-Split-Into-Subarrays-With-GCD-Greater-Than-One/cpp-2436/CMakeLists.txt new file mode 100644 index 00000000..a784c2cf --- /dev/null +++ b/2001-2500/2436-Minimum-Split-Into-Subarrays-With-GCD-Greater-Than-One/cpp-2436/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_2436) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2436 main.cpp) diff --git a/2001-2500/2436-Minimum-Split-Into-Subarrays-With-GCD-Greater-Than-One/cpp-2436/main.cpp b/2001-2500/2436-Minimum-Split-Into-Subarrays-With-GCD-Greater-Than-One/cpp-2436/main.cpp new file mode 100644 index 00000000..286962f5 --- /dev/null +++ b/2001-2500/2436-Minimum-Split-Into-Subarrays-With-GCD-Greater-Than-One/cpp-2436/main.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/minimum-split-into-subarrays-with-gcd-greater-than-one/ +/// Author : liuyubobobo +/// Time : 2022-10-12 + +#include +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(n^2 * log(max(nums))) +/// Space Complexity: O(n) +class Solution { +public: + int minimumSplits(vector& nums) { + + int n = nums.size(); + + vector dp(n + 1, INT_MAX); + dp[n] = 0; + for(int i = n - 1; i >= 0; i --){ + dp[i] = 1 + dp[i + 1]; + int cur = nums[i]; + for(int j = i + 1; j < n && cur > 1; j ++){ + cur = gcd(cur,nums[j]); + if(cur > 1) dp[i] = min(dp[i], 1 + dp[j + 1]); + } + } + return dp[0]; + } + +private: + int gcd(int a, int b){ + if(a > b) swap(a, b); + if (a == 0) return b; + return gcd(b % a, a); + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2437-Number-of-Valid-Clock-Times/cpp-2437/CMakeLists.txt b/2001-2500/2437-Number-of-Valid-Clock-Times/cpp-2437/CMakeLists.txt new file mode 100644 index 00000000..36154dc8 --- /dev/null +++ b/2001-2500/2437-Number-of-Valid-Clock-Times/cpp-2437/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_2437) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2437 main.cpp) diff --git a/2001-2500/2437-Number-of-Valid-Clock-Times/cpp-2437/main.cpp b/2001-2500/2437-Number-of-Valid-Clock-Times/cpp-2437/main.cpp new file mode 100644 index 00000000..864a6f0d --- /dev/null +++ b/2001-2500/2437-Number-of-Valid-Clock-Times/cpp-2437/main.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/number-of-valid-clock-times/ +/// Author : liuyubobobo +/// Time : 2022-10-15 + +#include + +using namespace std; + + +/// Backtrack +/// Time Complexity: O(10^4) +/// Space Complexity: O(1) +class Solution { +public: + int countTime(string time) { + + return dfs(time, 0); + } + +private: + int dfs(string& time, int index){ + + if(index == 5){ + return is_valid_time(time); + } + + if(time[index] != '?') return dfs(time, index + 1); + + int res = 0; + for(char c = '0'; c <= '9'; c ++){ + time[index] = c; + res += dfs(time, index + 1); + time[index] = '?'; + } + return res; + } + + bool is_valid_time(const string& time){ + + int h = atoi(time.substr(0, 2).c_str()); + int m = atoi(time.substr(3).c_str()); + return 0 <= h && h <= 23 && 0 <= m && m <= 59; + } +}; + + +int main() { + + cout << Solution().countTime("0?:0?") << '\n'; + // 100 + + return 0; +} diff --git a/2001-2500/2438-Range-Product-Queries-of-Powers/cpp-2438/CMakeLists.txt b/2001-2500/2438-Range-Product-Queries-of-Powers/cpp-2438/CMakeLists.txt new file mode 100644 index 00000000..c7c49622 --- /dev/null +++ b/2001-2500/2438-Range-Product-Queries-of-Powers/cpp-2438/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_2438) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2438 main.cpp) diff --git a/2001-2500/2438-Range-Product-Queries-of-Powers/cpp-2438/main.cpp b/2001-2500/2438-Range-Product-Queries-of-Powers/cpp-2438/main.cpp new file mode 100644 index 00000000..001f7993 --- /dev/null +++ b/2001-2500/2438-Range-Product-Queries-of-Powers/cpp-2438/main.cpp @@ -0,0 +1,42 @@ +/// Source : https://leetcode.com/problems/range-product-queries-of-powers/ +/// Author : liuyubobobo +/// Time : 2022-10-15 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(logn + qlogn) +/// Space Complexity: O(logn) +class Solution { + +private: + long long MOD = 1e9 + 7; + +public: + vector productQueries(int n, vector>& queries) { + + vector powers; + for(int p = 0; p <= 30; p ++) + if((n >> p) & 1) powers.push_back(1 << p); + + int q = queries.size(); + vector res(q); + for(int i = 0; i < q; i ++){ + long long tres = 1; + for(int j = queries[i][0]; j <= queries[i][1]; j ++) + tres = tres * powers[j] % MOD; + res[i] = tres; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2439-Minimize-Maximum-of-Array/cpp-2439/CMakeLists.txt b/2001-2500/2439-Minimize-Maximum-of-Array/cpp-2439/CMakeLists.txt new file mode 100644 index 00000000..a8791ee1 --- /dev/null +++ b/2001-2500/2439-Minimize-Maximum-of-Array/cpp-2439/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_2439) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2439 main.cpp) diff --git a/2001-2500/2439-Minimize-Maximum-of-Array/cpp-2439/main.cpp b/2001-2500/2439-Minimize-Maximum-of-Array/cpp-2439/main.cpp new file mode 100644 index 00000000..1e12b95f --- /dev/null +++ b/2001-2500/2439-Minimize-Maximum-of-Array/cpp-2439/main.cpp @@ -0,0 +1,48 @@ +/// Source : https://leetcode.com/problems/minimize-maximum-of-array/ +/// Author : liuyubobobo +/// Time : 2022-10-15 + +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + int minimizeArrayValue(vector& nums) { + + int n = nums.size(); + vector data(n); + for(int i = 0; i < n; i ++) data[i] = nums[i]; + + int l = 0, r = 2e9; + while(l < r){ + int mid = l + (r - l) / 2; + if(ok(n, data, mid)) r = mid; + else l = mid + 1; + } + return l; + } + +private: + bool ok(int n, vector nums, long long x){ + + for(int i = n - 1; i > 0; i --) + if(nums[i] > x){ + long long t = nums[i] - x; + nums[i] -= t; + nums[i - 1] += t; + } + return nums[0] <= x; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2440-Create-Components-With-Same-Value/cpp-2440/CMakeLists.txt b/2001-2500/2440-Create-Components-With-Same-Value/cpp-2440/CMakeLists.txt new file mode 100644 index 00000000..10329b23 --- /dev/null +++ b/2001-2500/2440-Create-Components-With-Same-Value/cpp-2440/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_2440) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2440 main.cpp) diff --git a/2001-2500/2440-Create-Components-With-Same-Value/cpp-2440/main.cpp b/2001-2500/2440-Create-Components-With-Same-Value/cpp-2440/main.cpp new file mode 100644 index 00000000..274342e4 --- /dev/null +++ b/2001-2500/2440-Create-Components-With-Same-Value/cpp-2440/main.cpp @@ -0,0 +1,99 @@ +/// Source : https://leetcode.cn/problems/create-components-with-same-value/ +/// Author : liuyubobobo +/// Time : 2022-10-16 + +#include +#include +#include +#include +#include +#include +#include + +using namespace std; + + +/// Topological Sort +/// Time Complexity: O(sqrt(sum) * n) +/// Space Complexity: O(n) +class Solution { +public: + int componentValue(vector& nums, vector>& edges) { + + int sum = accumulate(nums.begin(), nums.end(), 0); + + vector D; + for(int i = 1; i * i <= sum; i ++) + if(sum % i == 0){ + D.push_back(i); + if(i * i < sum) D.push_back(sum / i); + } + sort(D.begin(), D.end()); + + int n = nums.size(); + vector> g(n); + vector degrees(n, 0); + for(const vector& edge: edges){ + int a = edge[0], b = edge[1]; + g[a].push_back(b), g[b].push_back(a); + degrees[a] ++, degrees[b] ++; + } + + for(int d: D){ + if(ok(n, g, degrees, nums, d)){ + return sum / d - 1; + } + } + assert(false); + return -1; + } + +private: + bool ok(int n, const vector>& g, + vector degrees, vector nums, int d){ + + if(n == 1) return nums[0] == d; + + queue q; + vector inqueue(n, false); + vector over(n, false); + for(int i = 0; i < n; i ++) + if(degrees[i] == 1) q.push(i), inqueue[i] = true; + + while(q.size() > 1){ + int cur = q.front(); q.pop(); + + if(nums[cur] > d) return false; + + for(int next: g[cur]){ + if(over[next]) continue; + degrees[next] --; + degrees[cur] --; + + if(nums[cur] < d) nums[next] += nums[cur]; + if(degrees[next] == 1 && !inqueue[next]){ + inqueue[next] = true; + q.push(next); + } + } + over[cur] = true; + } + return nums[q.front()] == d; + } +}; + + +int main() { + +// vector nums1 = {6,2,2,2,6}; +// vector> edges1 = {{0,1},{1,2},{1,3},{3,4}}; +// cout << Solution().componentValue(nums1, edges1) << '\n'; +// // 2 + + vector nums2 = {1}; + vector> edges2 = {}; + cout << Solution().componentValue(nums2, edges2) << '\n'; + // 2 + + return 0; +} diff --git a/2001-2500/2441-Largest-Positive-Integer-That-Exists-With-Its-Negative/cpp-2441/CMakeLists.txt b/2001-2500/2441-Largest-Positive-Integer-That-Exists-With-Its-Negative/cpp-2441/CMakeLists.txt new file mode 100644 index 00000000..11d7a27d --- /dev/null +++ b/2001-2500/2441-Largest-Positive-Integer-That-Exists-With-Its-Negative/cpp-2441/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_2441) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2441 main.cpp) diff --git a/2001-2500/2441-Largest-Positive-Integer-That-Exists-With-Its-Negative/cpp-2441/main.cpp b/2001-2500/2441-Largest-Positive-Integer-That-Exists-With-Its-Negative/cpp-2441/main.cpp new file mode 100644 index 00000000..bded374d --- /dev/null +++ b/2001-2500/2441-Largest-Positive-Integer-That-Exists-With-Its-Negative/cpp-2441/main.cpp @@ -0,0 +1,31 @@ +/// Source : https://leetcode.com/problems/largest-positive-integer-that-exists-with-its-negative/ +/// Author : liuyubobobo +/// Time : 2022-10-15 + +#include +#include +#include + +using namespace std; + + +/// Using Map +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int findMaxK(vector& nums) { + + set s(nums.begin(), nums.end()); + int res = -1; + for(int e: nums) + if(e > 0 && s.count(-e)) res = max(res, e); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2442-Count-Number-of-Distinct-Integers-After-Reverse-Operations/cpp-2442/CMakeLists.txt b/2001-2500/2442-Count-Number-of-Distinct-Integers-After-Reverse-Operations/cpp-2442/CMakeLists.txt new file mode 100644 index 00000000..ad4bbf22 --- /dev/null +++ b/2001-2500/2442-Count-Number-of-Distinct-Integers-After-Reverse-Operations/cpp-2442/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_2442) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2442 main.cpp) diff --git a/2001-2500/2442-Count-Number-of-Distinct-Integers-After-Reverse-Operations/cpp-2442/main.cpp b/2001-2500/2442-Count-Number-of-Distinct-Integers-After-Reverse-Operations/cpp-2442/main.cpp new file mode 100644 index 00000000..49c6e765 --- /dev/null +++ b/2001-2500/2442-Count-Number-of-Distinct-Integers-After-Reverse-Operations/cpp-2442/main.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/count-number-of-distinct-integers-after-reverse-operations/ +/// Author : liuyubobobo +/// Time : 2022-10-15 + +#include +#include +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(nlog(max_nums)) +/// Space Complexity: O(n) +class Solution { +public: + int countDistinctIntegers(vector& nums) { + + set s(nums.begin(), nums.end()); + for(int e: nums){ + string e_str = to_string(e); + reverse(e_str.begin(), e_str.end()); + s.insert(atoi(e_str.c_str())); + } + return s.size(); + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2443-Sum-of-Number-and-Its-Reverse/cpp-2443/CMakeLists.txt b/2001-2500/2443-Sum-of-Number-and-Its-Reverse/cpp-2443/CMakeLists.txt new file mode 100644 index 00000000..40b91463 --- /dev/null +++ b/2001-2500/2443-Sum-of-Number-and-Its-Reverse/cpp-2443/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_2443) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2443 main.cpp) diff --git a/2001-2500/2443-Sum-of-Number-and-Its-Reverse/cpp-2443/main.cpp b/2001-2500/2443-Sum-of-Number-and-Its-Reverse/cpp-2443/main.cpp new file mode 100644 index 00000000..2581059a --- /dev/null +++ b/2001-2500/2443-Sum-of-Number-and-Its-Reverse/cpp-2443/main.cpp @@ -0,0 +1,36 @@ +/// Source : https://leetcode.com/problems/sum-of-number-and-its-reverse/ +/// Author : liuyubobobo +/// Time : 2022-10-16 + +#include +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(num * log(num)) +/// Space Complexity: O(log(num)) +class Solution { +public: + bool sumOfNumberAndReverse(int num) { + + for(int a = num; a >= num - a; a --){ + string a_str = to_string(a); + reverse(a_str.begin(), a_str.end()); + int ra = atoi(a_str.c_str()); + if(ra == num - a) return true; + } + return false; + } +}; + + +int main() { + + cout << Solution().sumOfNumberAndReverse(181) << '\n'; + // 1 + + return 0; +} diff --git a/2001-2500/2444-Count-Subarrays-With-Fixed-Bounds/cpp-2444/CMakeLists.txt b/2001-2500/2444-Count-Subarrays-With-Fixed-Bounds/cpp-2444/CMakeLists.txt new file mode 100644 index 00000000..688c8248 --- /dev/null +++ b/2001-2500/2444-Count-Subarrays-With-Fixed-Bounds/cpp-2444/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_2444) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2444 main.cpp) diff --git a/2001-2500/2444-Count-Subarrays-With-Fixed-Bounds/cpp-2444/main.cpp b/2001-2500/2444-Count-Subarrays-With-Fixed-Bounds/cpp-2444/main.cpp new file mode 100644 index 00000000..30db351b --- /dev/null +++ b/2001-2500/2444-Count-Subarrays-With-Fixed-Bounds/cpp-2444/main.cpp @@ -0,0 +1,62 @@ +/// Source : https://leetcode.com/problems/count-subarrays-with-fixed-bounds/ +/// Author : liuyubobobo +/// Time : 2022-10-16 + +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + long long countSubarrays(vector& nums, int minK, int maxK) { + + int n = nums.size(); + + vector ok(n); + for(int i = 0; i < n; i ++) + ok[i] = (minK <= nums[i] && nums[i] <= maxK); + + long long res = 0; + for(int start = 0, i = 1; i <= n; i ++) + if(i == n || ok[i] != ok[start]){ + if(ok[start]) + res += solve(nums, start, i, minK, maxK); + start = i; + } + return res; + } + +private: + long long solve(const vector& nums, int l, int r, int minK, int maxK){ + + vector min_indices, max_indices; + for(int i = l; i < r; i ++){ + if(nums[i] == minK) min_indices.push_back(i); + if(nums[i] == maxK) max_indices.push_back(i); + } + + long long res = 0; + int i = l, min_i = 0, max_i = 0; + while(i < r && min_i < min_indices.size() && max_i < max_indices.size()){ + + int j = max(min_indices[min_i], max_indices[max_i]); + res += r - j; + + i ++; + if(min_indices[min_i] < i) min_i ++; + if(max_indices[max_i] < i) max_i ++; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2445-Number-of-Nodes-With-Value-One/cpp-2445/CMakeLists.txt b/2001-2500/2445-Number-of-Nodes-With-Value-One/cpp-2445/CMakeLists.txt new file mode 100644 index 00000000..d96ee76a --- /dev/null +++ b/2001-2500/2445-Number-of-Nodes-With-Value-One/cpp-2445/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_2445) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2445 main.cpp) diff --git a/2001-2500/2445-Number-of-Nodes-With-Value-One/cpp-2445/main.cpp b/2001-2500/2445-Number-of-Nodes-With-Value-One/cpp-2445/main.cpp new file mode 100644 index 00000000..cf1fd3ce --- /dev/null +++ b/2001-2500/2445-Number-of-Nodes-With-Value-One/cpp-2445/main.cpp @@ -0,0 +1,38 @@ +/// Source : https://leetcode.com/problems/number-of-nodes-with-value-one/ +/// Author : liuyubobobo +/// Time : 2022-10-20 + +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + int numberOfNodes(int n, vector& queries) { + + vector qtable(n + 1, 0); + for(int q: queries) qtable[q] ^= 1; + + int res = 0; + for(int i = 1; i <= n; i ++){ + int x = i, t = 0; + while(x){ + t ^= qtable[x]; + x >>= 1; + } + res += t; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2446-Determine-if-Two-Events-Have-Conflict/cpp-2446/CMakeLists.txt b/2001-2500/2446-Determine-if-Two-Events-Have-Conflict/cpp-2446/CMakeLists.txt new file mode 100644 index 00000000..415e0a92 --- /dev/null +++ b/2001-2500/2446-Determine-if-Two-Events-Have-Conflict/cpp-2446/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/2001-2500/2446-Determine-if-Two-Events-Have-Conflict/cpp-2446/main.cpp b/2001-2500/2446-Determine-if-Two-Events-Have-Conflict/cpp-2446/main.cpp new file mode 100644 index 00000000..b1f75d90 --- /dev/null +++ b/2001-2500/2446-Determine-if-Two-Events-Have-Conflict/cpp-2446/main.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/determine-if-two-events-have-conflict/ +/// Author : liuyubobobo +/// Time : 2022-10-22 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(1) +/// Space Complexity: O(1) +class Solution { +public: + bool haveConflict(vector& event1, vector& event2) { + + int s1 = get_time(event1[0]), e1 = get_time(event1[1]); + int s2 = get_time(event2[0]), e2 = get_time(event2[1]); + if(s1 > s2) swap(s1, s2), swap(e1, e2); + + return s2 <= e1; + } + +private: + int get_time(const string& s){ + int h = atoi(s.substr(0, 2).c_str()); + int m = atoi(s.substr(3).c_str()); + return h * 60 + m; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2447-Number-of-Subarrays-With-GCD-Equal-to-K/cpp-2447/CMakeLists.txt b/2001-2500/2447-Number-of-Subarrays-With-GCD-Equal-to-K/cpp-2447/CMakeLists.txt new file mode 100644 index 00000000..b1c82ab8 --- /dev/null +++ b/2001-2500/2447-Number-of-Subarrays-With-GCD-Equal-to-K/cpp-2447/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/2001-2500/2447-Number-of-Subarrays-With-GCD-Equal-to-K/cpp-2447/main.cpp b/2001-2500/2447-Number-of-Subarrays-With-GCD-Equal-to-K/cpp-2447/main.cpp new file mode 100644 index 00000000..cbab9ecf --- /dev/null +++ b/2001-2500/2447-Number-of-Subarrays-With-GCD-Equal-to-K/cpp-2447/main.cpp @@ -0,0 +1,55 @@ +/// Source : https://leetcode.com/problems/number-of-subarrays-with-gcd-equal-to-k/ +/// Author : liuyubobobo +/// Time : 2022-10-22 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n^2 * log(max_nums)) +/// Space Complexity: O(log(max_nums)) +class Solution { +public: + int subarrayGCD(vector& nums, int k) { + + int n = nums.size(); + int res = 0; + for(int l = 0; l < n; l ++){ + if(nums[l] == k) res ++; + int cur_g = nums[l]; + for(int r = l + 1; r < n; r ++){ + cur_g = gcd(cur_g, nums[r]); + if(cur_g == k) res ++; + } + } + return res; + } + +private: + int gcd(int a, int b){ + if(a > b) swap(a, b); + if (a == 0) return b; + return gcd(b % a, a); + } +}; + + +int main() { + + vector nums1 = {9, 3, 1, 2, 6, 3}; + cout << Solution().subarrayGCD(nums1, 3) << '\n'; + // 4 + + vector nums2 = {4}; + cout << Solution().subarrayGCD(nums2, 7) << '\n'; + // 0 + + vector nums3 = {3, 3, 4, 1, 2}; + cout << Solution().subarrayGCD(nums3, 1) << '\n'; + // 10 + + return 0; +} diff --git a/2001-2500/2448-Minimum-Cost-to-Make-Array-Equal/cpp-2448/CMakeLists.txt b/2001-2500/2448-Minimum-Cost-to-Make-Array-Equal/cpp-2448/CMakeLists.txt new file mode 100644 index 00000000..d0dc1506 --- /dev/null +++ b/2001-2500/2448-Minimum-Cost-to-Make-Array-Equal/cpp-2448/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/2001-2500/2448-Minimum-Cost-to-Make-Array-Equal/cpp-2448/main.cpp b/2001-2500/2448-Minimum-Cost-to-Make-Array-Equal/cpp-2448/main.cpp new file mode 100644 index 00000000..d71fe512 --- /dev/null +++ b/2001-2500/2448-Minimum-Cost-to-Make-Array-Equal/cpp-2448/main.cpp @@ -0,0 +1,59 @@ +/// Source : https://leetcode.com/problems/minimum-cost-to-make-array-equal/ +/// Author : liuyubobobo +/// Time : 2022-10-22 + +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(nlogn + max_nums) +/// Space Complexity: O(n) +class Solution { +public: + long long minCost(vector& nums, vector& cost) { + + int n = nums.size(); + + long long cur_cost = 0; + for(int i = 0; i < n; i ++) cur_cost += 1ll * nums[i] * cost[i]; + long long res_cost = cur_cost; + + vector> data(n); + for(int i = 0; i < n; i ++) data[i] = {nums[i], cost[i]}; + sort(data.begin(), data.end()); + int index = 0; + + long long above_cost_d = 0; + for(int i = 0; i < n; i ++) above_cost_d += cost[i]; + long long below_cost_d = 0; + + for(int cur_target = 1; cur_target <= data.back().first; cur_target ++){ + cur_cost = cur_cost - above_cost_d + below_cost_d; + res_cost = min(res_cost, cur_cost); + + while(index < n && data[index].first == cur_target){ + above_cost_d -= data[index].second; + below_cost_d += data[index].second; + index ++; + } + } + return res_cost; + } +}; + + +int main() { + + vector nums1 = {1, 3, 5, 2}, cost1 = {2, 3, 1, 14}; + cout << Solution().minCost(nums1, cost1) << '\n'; + // 8 + + vector nums2 = {2, 2, 2, 2, 2}, cost2 = {4, 2, 8, 1, 3}; + cout << Solution().minCost(nums2, cost2) << '\n'; + // 0 + + return 0; +} diff --git a/2001-2500/2449-Minimum-Number-of-Operations-to-Make-Arrays-Similar/cpp-2449/CMakeLists.txt b/2001-2500/2449-Minimum-Number-of-Operations-to-Make-Arrays-Similar/cpp-2449/CMakeLists.txt new file mode 100644 index 00000000..8148fadd --- /dev/null +++ b/2001-2500/2449-Minimum-Number-of-Operations-to-Make-Arrays-Similar/cpp-2449/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) diff --git a/2001-2500/2449-Minimum-Number-of-Operations-to-Make-Arrays-Similar/cpp-2449/main.cpp b/2001-2500/2449-Minimum-Number-of-Operations-to-Make-Arrays-Similar/cpp-2449/main.cpp new file mode 100644 index 00000000..3202299a --- /dev/null +++ b/2001-2500/2449-Minimum-Number-of-Operations-to-Make-Arrays-Similar/cpp-2449/main.cpp @@ -0,0 +1,59 @@ +/// Source : https://leetcode.com/problems/minimum-number-of-operations-to-make-arrays-similar/ +/// Author : liuyubobobo +/// Time : 2022-10-22 + +#include +#include +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + long long makeSimilar(vector& nums, vector& target) { + + vector even_s, odd_s; + for(int e: nums) if(e & 1) odd_s.push_back(e); else even_s.push_back(e); + + vector even_t, odd_t; + for(int e: target) if(e & 1) odd_t.push_back(e); else even_t.push_back(e); + + sort(even_s.begin(), even_s.end()); + sort(odd_s.begin(), odd_s.end()); + sort(even_t.begin(), even_t.end()); + sort(odd_t.begin(), odd_t.end()); + + assert(even_s.size() == even_t.size() && odd_s.size() == odd_t.size()); + + long long add = 0, sub = 0; + for(int i = 0; i < even_s.size(); i ++){ + if(even_s[i] < even_t[i]) add += (even_t[i] - even_s[i]) / 2; + else sub += (even_s[i] - even_t[i]) / 2; + } + for(int i = 0; i < odd_s.size(); i ++){ + if(odd_s[i] < odd_t[i]) add += (odd_t[i] - odd_s[i]) / 2; + else sub += (odd_s[i] - odd_t[i]) / 2; + } + assert(add == sub); + return add; + } +}; + + +int main() { + + vector nums1 = {8, 12, 6}, target1 = {2, 14, 10}; + cout << Solution().makeSimilar(nums1, target1) << '\n'; + // 2 + + vector nums2 = {1, 2, 5}, target2 = {4, 1, 3}; + cout << Solution().makeSimilar(nums2, target2) << '\n'; + // 1 + + return 0; +} diff --git a/2001-2500/2450-Number-of-Distinct-Binary-Strings-After-Applying-Operations/cpp-2450/CMakeLists.txt b/2001-2500/2450-Number-of-Distinct-Binary-Strings-After-Applying-Operations/cpp-2450/CMakeLists.txt new file mode 100644 index 00000000..9c060e2f --- /dev/null +++ b/2001-2500/2450-Number-of-Distinct-Binary-Strings-After-Applying-Operations/cpp-2450/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_2450) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2450 main.cpp) diff --git a/2001-2500/2450-Number-of-Distinct-Binary-Strings-After-Applying-Operations/cpp-2450/main.cpp b/2001-2500/2450-Number-of-Distinct-Binary-Strings-After-Applying-Operations/cpp-2450/main.cpp new file mode 100644 index 00000000..2bd8fcc1 --- /dev/null +++ b/2001-2500/2450-Number-of-Distinct-Binary-Strings-After-Applying-Operations/cpp-2450/main.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/number-of-distinct-binary-strings-after-applying-operations/ +/// Author : liuyubobobo +/// Time : 2022-10-30 + +#include + +using namespace std; + + +/// Math +/// Time Complexity: O(log(n - k + 1)) +/// Space Complexity: O(log(n - k + 1)) +class Solution { +public: + int countDistinctStrings(string s, int k) { + + int n = s.size(); + return quick_pow(2ll, n - k + 1, 1e9 + 7ll); + } + +private: + long long quick_pow(long long a, long long k, long long MOD) { + long long res = 1ll; + while (k) { + if (k & 1) res = res * a % MOD; + a = a * a % MOD; + k >>= 1; + } + return res % MOD; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2451-Odd-String-Difference/cpp-2451/CMakeLists.txt b/2001-2500/2451-Odd-String-Difference/cpp-2451/CMakeLists.txt new file mode 100644 index 00000000..fd13fd77 --- /dev/null +++ b/2001-2500/2451-Odd-String-Difference/cpp-2451/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_2451) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2451 main.cpp) diff --git a/2001-2500/2451-Odd-String-Difference/cpp-2451/main.cpp b/2001-2500/2451-Odd-String-Difference/cpp-2451/main.cpp new file mode 100644 index 00000000..c3a8ac8e --- /dev/null +++ b/2001-2500/2451-Odd-String-Difference/cpp-2451/main.cpp @@ -0,0 +1,38 @@ +/// Source : https://leetcode.com/problems/odd-string-difference/ +/// Author : liuyubobobo +/// Time : 2022-10-30 + +#include +#include +#include + +using namespace std; + + +/// Using Map +/// Time Complexity: O(|words| * len) +/// Space Compelxity: O(|words| * len) +class Solution { +public: + string oddString(vector& words) { + + map, vector> diff2str; + for(const string& word: words){ + int n = word.size(); + vector d(n - 1, 0); + for(int i = 1; i < n; i ++) + d[i - 1] = word[i] - word[i - 1]; + diff2str[d].push_back(word); + } + + for(const auto& p: diff2str) + if(p.second.size() == 1) return p.second[0]; + return ""; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2452-Words-Within-Two-Edits-of-Dictionary/cpp-2452/CMakeLists.txt b/2001-2500/2452-Words-Within-Two-Edits-of-Dictionary/cpp-2452/CMakeLists.txt new file mode 100644 index 00000000..cbb0a308 --- /dev/null +++ b/2001-2500/2452-Words-Within-Two-Edits-of-Dictionary/cpp-2452/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_2452) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2452 main.cpp) diff --git a/2001-2500/2452-Words-Within-Two-Edits-of-Dictionary/cpp-2452/main.cpp b/2001-2500/2452-Words-Within-Two-Edits-of-Dictionary/cpp-2452/main.cpp new file mode 100644 index 00000000..a4f14a86 --- /dev/null +++ b/2001-2500/2452-Words-Within-Two-Edits-of-Dictionary/cpp-2452/main.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/words-within-two-edits-of-dictionary/ +/// Author : liuyubobobo +/// Time : 2022-10-30 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(|queries| * |dict| * word_len) +/// Space Complexity: O(1) +class Solution { +public: + vector twoEditWords(vector& queries, vector& dictionary) { + + vector res; + for(const string& word: queries){ + if(ok(word, dictionary)) res.push_back(word); + } + return res; + } + +private: + bool ok(const string& word, const vector& dict){ + + for(const string& s: dict) + if(diff(word, s) <= 2) return true; + return false; + } + + int diff(const string& s1, const string& s2){ + + int n = s1.size(), res = 0; + for(int i = 0; i < n; i ++) + res += s1[i] != s2[i]; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2453-Destroy-Sequential-Targets/cpp-2453/CMakeLists.txt b/2001-2500/2453-Destroy-Sequential-Targets/cpp-2453/CMakeLists.txt new file mode 100644 index 00000000..b18366d3 --- /dev/null +++ b/2001-2500/2453-Destroy-Sequential-Targets/cpp-2453/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_2453) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2453 main.cpp) diff --git a/2001-2500/2453-Destroy-Sequential-Targets/cpp-2453/main.cpp b/2001-2500/2453-Destroy-Sequential-Targets/cpp-2453/main.cpp new file mode 100644 index 00000000..c60dedd2 --- /dev/null +++ b/2001-2500/2453-Destroy-Sequential-Targets/cpp-2453/main.cpp @@ -0,0 +1,48 @@ +/// Source : https://leetcode.com/problems/destroy-sequential-targets/ +/// Author : liuyubobobo +/// Time : 2022-10-30 + +#include +#include +#include + +using namespace std; + + +/// Using Map +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int destroyTargets(vector& nums, int space) { + + map f; + map min_res; + for(int e: nums){ + f[e % space] ++; + + if(min_res.count(e % space)) min_res[e % space] = min(min_res[e % space], e); + else min_res[e % space] = e; + } + + int maxf = 0; + for(const pair& p: f) + maxf = max(maxf, p.second); + + int res = INT_MAX; + for(const pair& p: f) + if(p.second == maxf) + res = min(res, min_res[p.first]); + + return res; + } +}; + + +int main() { + + vector nums1 = {3,7,8,1,1,5}; + cout << Solution().destroyTargets(nums1, 2) << '\n'; + + return 0; +} diff --git a/2001-2500/2454-Next-Greater-Element-IV/cpp-2454/CMakeLists.txt b/2001-2500/2454-Next-Greater-Element-IV/cpp-2454/CMakeLists.txt new file mode 100644 index 00000000..f2f8c98e --- /dev/null +++ b/2001-2500/2454-Next-Greater-Element-IV/cpp-2454/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_2454) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2454 main.cpp) diff --git a/2001-2500/2454-Next-Greater-Element-IV/cpp-2454/main.cpp b/2001-2500/2454-Next-Greater-Element-IV/cpp-2454/main.cpp new file mode 100644 index 00000000..3ec32836 --- /dev/null +++ b/2001-2500/2454-Next-Greater-Element-IV/cpp-2454/main.cpp @@ -0,0 +1,86 @@ +/// Source : https://leetcode.com/problems/next-greater-element-iv/ +/// Author : liuyubobobo +/// Time : 2022-10-30 + +#include +#include + +using namespace std; + + +/// Mono Stack + ST + Binary Search +/// Time Complexity: O(n(logn)^2) +/// Space Complexity: O(nlogn) +template +class SparseTable{ + +private: + int n; + vector> table; + vector log2; + T (*combine)(T a, T b); + +public: + SparseTable(const vector& data, T (*combine)(T a, T b)): n(data.size()), log2(n + 1, 1){ + + this->combine = combine; + + int len = 2, k = 1; + for(int i = 1; i <= n; i ++){ + if(i >= len) len <<= 1, k ++; + log2[i] = k; + } + + int K = log2[n]; + table = vector>(K, vector(n)); + + for(int i = 0; i < n; i ++) + table[0][i] = data[i]; + + for(int k = 1; k < K; k ++) + for(int i = 0; i + (1 << (k - 1)) < n; i ++) + table[k][i] = combine(table[k - 1][i], table[k - 1][i + (1 << (k - 1))]); + } + + T query(int l, int r){ + + int k = log2[r - l + 1]; + return combine(table[k - 1][l], table[k - 1][r + 1 - (1 << (k - 1))]); + } +}; + +class Solution { +public: + vector secondGreaterElement(vector& nums) { + + int n = nums.size(); + vector next(n, -1), s; + for(int i = 0; i < n; i ++){ + while(!s.empty() && nums[i] > nums[s.back()]) + next[s.back()] = i, s.pop_back(); + s.push_back(i); + } + + SparseTable st(nums, [](int a, int b){return max(a, b);}); + vector res(n, -1); + for(int i = 0; i < n; i ++){ + int a = next[i]; + if(a == -1) continue; + + int l = a + 1, r = n; + while(l < r){ + int mid = (l + r) / 2; + if(st.query(a + 1, mid) > nums[i]) r = mid; + else l = mid + 1; + } + res[i] = l == n ? -1 : nums[l]; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2455-Average-Value-of-Even-Numbers-That-Are-Divisible-by-Three/cpp-2455/CMakeLists.txt b/2001-2500/2455-Average-Value-of-Even-Numbers-That-Are-Divisible-by-Three/cpp-2455/CMakeLists.txt new file mode 100644 index 00000000..415e0a92 --- /dev/null +++ b/2001-2500/2455-Average-Value-of-Even-Numbers-That-Are-Divisible-by-Three/cpp-2455/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/2001-2500/2455-Average-Value-of-Even-Numbers-That-Are-Divisible-by-Three/cpp-2455/main.cpp b/2001-2500/2455-Average-Value-of-Even-Numbers-That-Are-Divisible-by-Three/cpp-2455/main.cpp new file mode 100644 index 00000000..143421ad --- /dev/null +++ b/2001-2500/2455-Average-Value-of-Even-Numbers-That-Are-Divisible-by-Three/cpp-2455/main.cpp @@ -0,0 +1,29 @@ +/// Source : https://leetcode.com/problems/average-value-of-even-numbers-that-are-divisible-by-three/ +/// Author : liuyubobobo +/// Time : 2022-10-29 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int averageValue(vector& nums) { + + int total = 0, cnt = 0; + for(int e: nums) + if(e % 6 == 0) total += e, cnt ++; + return cnt == 0 ? 0 : total / cnt; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2456-Most-Popular-Video-Creator/cpp-2456/CMakeLists.txt b/2001-2500/2456-Most-Popular-Video-Creator/cpp-2456/CMakeLists.txt new file mode 100644 index 00000000..b1c82ab8 --- /dev/null +++ b/2001-2500/2456-Most-Popular-Video-Creator/cpp-2456/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/2001-2500/2456-Most-Popular-Video-Creator/cpp-2456/main.cpp b/2001-2500/2456-Most-Popular-Video-Creator/cpp-2456/main.cpp new file mode 100644 index 00000000..31dcac60 --- /dev/null +++ b/2001-2500/2456-Most-Popular-Video-Creator/cpp-2456/main.cpp @@ -0,0 +1,55 @@ +/// Source : https://leetcode.com/problems/most-popular-video-creator/ +/// Author : liuyubobobo +/// Time : 2022-10-29 + +#include +#include +#include + +using namespace std; + + +/// Using Map +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector> mostPopularCreator(vector& creators, vector& ids, vector& views) { + + int n = creators.size(); + + map> best_video; + map total_views; + long long most_view = 0ll; + for(int i = 0; i < n; i ++){ + string creator = creators[i], id = ids[i]; + long long view = views[i]; + + total_views[creator] += view; + most_view = max(most_view, total_views[creator]); + + auto iter = best_video.find(creator); + if(iter == best_video.end()){ + best_video[creator] = {view, id}; + continue; + } + + if(view > iter->second.first || (view == iter->second.first && id < iter->second.second)) + best_video[creator] = {view, id}; + } + + vector> res; + for(const pair& p: total_views) + if(p.second == most_view){ + string creater = p.first; + res.push_back({creater, best_video[creater].second}); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2457-Minimum-Addition-to-Make-Integer-Beautiful/cpp-2457/CMakeLists.txt b/2001-2500/2457-Minimum-Addition-to-Make-Integer-Beautiful/cpp-2457/CMakeLists.txt new file mode 100644 index 00000000..d0dc1506 --- /dev/null +++ b/2001-2500/2457-Minimum-Addition-to-Make-Integer-Beautiful/cpp-2457/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/2001-2500/2457-Minimum-Addition-to-Make-Integer-Beautiful/cpp-2457/main.cpp b/2001-2500/2457-Minimum-Addition-to-Make-Integer-Beautiful/cpp-2457/main.cpp new file mode 100644 index 00000000..7f125912 --- /dev/null +++ b/2001-2500/2457-Minimum-Addition-to-Make-Integer-Beautiful/cpp-2457/main.cpp @@ -0,0 +1,62 @@ +/// Source : https://leetcode.com/problems/minimum-addition-to-make-integer-beautiful/ +/// Author : liuyubobobo +/// Time : 2022-10-29 + +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O((logn)^2) +/// Space Complexity: O(logn) +class Solution { +public: + long long makeIntegerBeautiful(long long n, int target) { + + vector pow10(18, 1ll); + for(int i = 1; i < 18; i ++) + pow10[i] = pow10[i - 1] * 10ll; + + long long res = 0; + while(true){ + string s = to_string(n); + int len = s.size(); + + if(digit_sum(len, s) <= target) break; + + int first_non_zero = len - 1; + for(first_non_zero = len - 1; first_non_zero >= 0; first_non_zero --) + if(s[first_non_zero] != '0') break; + + long long d = (10 - (s[first_non_zero] - '0')) * pow10[len - first_non_zero - 1]; + res += d; + n += d; + } + return res; + } + +private: + int digit_sum(int n, const string& s){ + int res = 0; + for(char d: s) + res += (d - '0'); + return res; + } +}; + + +int main() { + + cout << Solution().makeIntegerBeautiful(16, 6) << '\n'; + // 4 + + cout << Solution().makeIntegerBeautiful(467, 6) << '\n'; + // 33 + + cout << Solution().makeIntegerBeautiful(1, 1) << '\n'; + // 0 + + return 0; +} diff --git a/2001-2500/2458-Height-of-Binary-Tree-After-Subtree-Removal-Queries/cpp-2458/CMakeLists.txt b/2001-2500/2458-Height-of-Binary-Tree-After-Subtree-Removal-Queries/cpp-2458/CMakeLists.txt new file mode 100644 index 00000000..8148fadd --- /dev/null +++ b/2001-2500/2458-Height-of-Binary-Tree-After-Subtree-Removal-Queries/cpp-2458/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) diff --git a/2001-2500/2458-Height-of-Binary-Tree-After-Subtree-Removal-Queries/cpp-2458/main.cpp b/2001-2500/2458-Height-of-Binary-Tree-After-Subtree-Removal-Queries/cpp-2458/main.cpp new file mode 100644 index 00000000..88237b0e --- /dev/null +++ b/2001-2500/2458-Height-of-Binary-Tree-After-Subtree-Removal-Queries/cpp-2458/main.cpp @@ -0,0 +1,95 @@ +/// Source : https://leetcode.com/problems/height-of-binary-tree-after-subtree-removal-queries/ +/// Author : liuyubobobo +/// Time : 2022-10-29 + +#include +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n + q) +/// Space Complexity: O(n) + +/// 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 treeQueries(TreeNode* root, vector& queries) { + + int n = dfs_sz(root); + + vector depth(n + 1, -1), subtree_depth(n + 1, -1); + dfs_depth(root, 0, depth, subtree_depth); + + vector res_table(n + 1, 0); + dfs_res_table(root, depth, subtree_depth, 0, res_table); + + vector res(queries.size()); + for(int i = 0; i < queries.size(); i ++){ + int q = queries[i]; + res[i] = res_table[q]; + } + return res; + } + +private: + void dfs_res_table(TreeNode* node, const vector& depth, const vector& subtree_depth, + int pre_max, vector& res_table){ + + if(!node) return; + res_table[node->val] = pre_max; + + int right_max_depth = depth[node->val] + (node->right ? subtree_depth[node->right->val] : 0); + dfs_res_table(node->left, depth, subtree_depth, max(pre_max, right_max_depth), res_table); + + int left_max_depth = depth[node->val] + (node->left ? subtree_depth[node->left->val] : 0); + dfs_res_table(node->right, depth, subtree_depth, max(pre_max, left_max_depth), res_table); + } + + void dfs_depth(TreeNode* node, int d, vector& depth, vector& subtree_depth){ + + if(!node) return; + + depth[node->val] = d; + + dfs_depth(node->left, d + 1, depth, subtree_depth); + dfs_depth(node->right, d + 1, depth, subtree_depth); + + int t = 0; + if(node->left) t = max(t, subtree_depth[node->left->val]); + if(node->right) t = max(t, subtree_depth[node->right->val]); + subtree_depth[node->val] = 1 + t; + } + + int dfs_sz(TreeNode* node){ + + if(!node) return 0; + return 1 + dfs_sz(node->left) + dfs_sz(node->right); + } +}; + + +int main() { + + TreeNode* root1 = new TreeNode(1); + root1->left = new TreeNode(3, new TreeNode(2), nullptr); + root1->right = new TreeNode(4, new TreeNode(6), new TreeNode(5, nullptr, new TreeNode(7))); + + vector queries1 = {4}; + vector res1 = Solution().treeQueries(root1, queries1); + for(int e: res1) cout << e << ' '; cout << '\n'; + // 2 + + return 0; +} diff --git a/2001-2500/2459-Sort-Array-by-Moving-Items-to-Empty-Space/cpp-2459/CMakeLists.txt b/2001-2500/2459-Sort-Array-by-Moving-Items-to-Empty-Space/cpp-2459/CMakeLists.txt new file mode 100644 index 00000000..1d476010 --- /dev/null +++ b/2001-2500/2459-Sort-Array-by-Moving-Items-to-Empty-Space/cpp-2459/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2459) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2459 main.cpp) diff --git a/2001-2500/2459-Sort-Array-by-Moving-Items-to-Empty-Space/cpp-2459/main.cpp b/2001-2500/2459-Sort-Array-by-Moving-Items-to-Empty-Space/cpp-2459/main.cpp new file mode 100644 index 00000000..ccf15376 --- /dev/null +++ b/2001-2500/2459-Sort-Array-by-Moving-Items-to-Empty-Space/cpp-2459/main.cpp @@ -0,0 +1,66 @@ +/// Source : https://leetcode.com/problems/sort-array-by-moving-items-to-empty-space/description/ +/// Author : liuyubobobo +/// Time : 2023-01-09 + +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int sortArray(vector& nums) { + + int n = nums.size(); + + vector target(n); + for(int i = 0; i < n; i ++) target[i] = i; + + int res = solve(n, nums, target); + + for(int i = 0; i < n; i ++) target[i] = i + 1; + target.back() = 0; + res = min(res, solve(n, nums, target)); + + return res; + } + +private: + int solve(int n, const vector& nums, const vector& target){ + + vector pos(n); + for(int i = 0; i < n; i ++) pos[target[i]] = i; + + vector visited(n, false); + int res = 0; + for(int i = 0; i < n; i ++){ + if(visited[i]) continue; + + int cur = i, len = 0; + bool contain_zero = false; + while(!visited[cur]){ + len ++; + visited[cur] = true; + + if(nums[cur] == 0) contain_zero = true; + cur = pos[nums[cur]]; + } + + if(len == 1) continue; + + if(contain_zero) res += len - 1; + else res += len + 1; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2460-Apply-Operations-o an-Array/cpp-2460/CMakeLists.txt b/2001-2500/2460-Apply-Operations-o an-Array/cpp-2460/CMakeLists.txt new file mode 100644 index 00000000..415e0a92 --- /dev/null +++ b/2001-2500/2460-Apply-Operations-o an-Array/cpp-2460/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/2001-2500/2460-Apply-Operations-o an-Array/cpp-2460/main.cpp b/2001-2500/2460-Apply-Operations-o an-Array/cpp-2460/main.cpp new file mode 100644 index 00000000..8ee443ab --- /dev/null +++ b/2001-2500/2460-Apply-Operations-o an-Array/cpp-2460/main.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/apply-operations-to-an-array/ +/// Author : liuyubobobo +/// Time : 2022-11-05 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + vector applyOperations(vector& nums) { + + int n = nums.size(); + for(int i = 0; i + 1 < n; i ++) + if(nums[i] == nums[i + 1]) nums[i] *= 2, nums[i + 1] = 0; + + vector res(n, 0); + for(int i = 0, k = 0; i < n; i ++) + if(nums[i]) res[k ++] = nums[i]; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2461-Maximum-Sum-of-Distinct-Subarrays-With-Length-K/cpp-2461/CMakeLists.txt b/2001-2500/2461-Maximum-Sum-of-Distinct-Subarrays-With-Length-K/cpp-2461/CMakeLists.txt new file mode 100644 index 00000000..b1c82ab8 --- /dev/null +++ b/2001-2500/2461-Maximum-Sum-of-Distinct-Subarrays-With-Length-K/cpp-2461/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/2001-2500/2461-Maximum-Sum-of-Distinct-Subarrays-With-Length-K/cpp-2461/main.cpp b/2001-2500/2461-Maximum-Sum-of-Distinct-Subarrays-With-Length-K/cpp-2461/main.cpp new file mode 100644 index 00000000..aebd87fd --- /dev/null +++ b/2001-2500/2461-Maximum-Sum-of-Distinct-Subarrays-With-Length-K/cpp-2461/main.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/maximum-sum-of-distinct-subarrays-with-length-k/description/ +/// Author : liuyubobobo +/// Time : 2022-11-05 + +#include +#include +#include + +using namespace std; + + +/// Sliding Window +/// Time Complexity: O(n) +/// Space Complexity: O(max_nums) +class Solution { +public: + long long maximumSubarraySum(vector& nums, int k) { + + int n = nums.size(); + vector f(1e5 + 1); + int not_unique = 0; + long long sum = 0, res = 0; + + for(int i = 0; i < n; i ++){ + sum += nums[i]; + f[nums[i]] ++; + if(f[nums[i]] == 2) not_unique ++; + + if(i >= k - 1){ + if(not_unique == 0) res = max(res, sum); + + sum -= nums[i - (k - 1)]; + f[nums[i - (k - 1)]] --; + if(f[nums[i - (k - 1)]] == 1) not_unique --; + } + } + + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2462-Total-Cost-to-Hire-K-Workers/cpp-2462/CMakeLists.txt b/2001-2500/2462-Total-Cost-to-Hire-K-Workers/cpp-2462/CMakeLists.txt new file mode 100644 index 00000000..d0dc1506 --- /dev/null +++ b/2001-2500/2462-Total-Cost-to-Hire-K-Workers/cpp-2462/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/2001-2500/2462-Total-Cost-to-Hire-K-Workers/cpp-2462/main.cpp b/2001-2500/2462-Total-Cost-to-Hire-K-Workers/cpp-2462/main.cpp new file mode 100644 index 00000000..114831d3 --- /dev/null +++ b/2001-2500/2462-Total-Cost-to-Hire-K-Workers/cpp-2462/main.cpp @@ -0,0 +1,59 @@ +/// Source : https://leetcode.com/problems/total-cost-to-hire-k-workers/description/ +/// Author : liuyubobobo +/// Time : 2022-11-05 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// Using MinHeap +/// Time Complexity: O((candidates + k) * log(candidates)) +/// Space Complexity: O(candidates) +class Solution { +public: + long long totalCost(vector& costs, int k, int candidates) { + + int n = costs.size(); + + priority_queue, greater<>> front_pq, tail_pq; + for(int i = 0; i < candidates; i ++) front_pq.push(costs[i]); + for(int i = n - 1; i >= n - candidates && i >= candidates; i --) tail_pq.push(costs[i]); + + int front = candidates, tail = n - candidates - 1; + long long res = 0; + for(int i = 0; i < k; i ++){ + int front_min = front_pq.empty() ? INT_MAX : front_pq.top(); + int tail_min = tail_pq.empty() ? INT_MAX : tail_pq.top(); + if(front_min <= tail_min){ + res += front_min; + front_pq.pop(); + if(front <= tail) front_pq.push(costs[front ++]); + } + else{ + res += tail_min; + tail_pq.pop(); + if(front <= tail) tail_pq.push(costs[tail --]); + } + } + return res; + } +}; + + +int main() { + + vector costs1 = {17,12,10,2,7,2,11,20,8}; + cout << Solution().totalCost(costs1, 3, 4) << '\n'; + // 11 + + vector costs2 = {57,33,26,76,14,67,24,90,72,37,30}; + cout << Solution().totalCost(costs2, 11, 2) << '\n'; + // 526 + + return 0; +} diff --git a/2001-2500/2463-Minimum-Total-Distance-Traveled/cpp-2463/CMakeLists.txt b/2001-2500/2463-Minimum-Total-Distance-Traveled/cpp-2463/CMakeLists.txt new file mode 100644 index 00000000..8148fadd --- /dev/null +++ b/2001-2500/2463-Minimum-Total-Distance-Traveled/cpp-2463/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) diff --git a/2001-2500/2463-Minimum-Total-Distance-Traveled/cpp-2463/main.cpp b/2001-2500/2463-Minimum-Total-Distance-Traveled/cpp-2463/main.cpp new file mode 100644 index 00000000..3669388b --- /dev/null +++ b/2001-2500/2463-Minimum-Total-Distance-Traveled/cpp-2463/main.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/minimum-total-distance-traveled/ +/// Author : liuyubobobo +/// Time : 2022-11-05 + +#include +#include +#include +#include + +using namespace std; + + +/// Memoization +/// Time Complexity: O(|robot| * |factory| * |max_limit|) +/// Space Complexity: O(|robot| * |factory|) +class Solution { +public: + long long minimumTotalDistance(vector& robot, vector>& factory) { + + sort(robot.begin(), robot.end()); + sort(factory.begin(), factory.end()); + + int rn = robot.size(), fn = factory.size(); + vector> dp(rn, vector(fn, -1)); + return dfs(rn, robot, fn, factory, 0, 0, dp); + } + +private: + long long dfs(int rn, const vector& robot, int fn, const vector>& factory, + int rindex, int findex, vector>& dp){ + + if(rindex == rn) return 0; + if(findex == fn) return LONG_LONG_MAX / 2; + if(dp[rindex][findex] != -1) return dp[rindex][findex]; + + long long res = dfs(rn, robot, fn, factory, rindex, findex + 1, dp); + + int fpos = factory[findex][0], limit = factory[findex][1]; + long long cur = 0; + for(int i = 0; i < limit && rindex + i < rn; i ++){ + cur += abs(fpos - robot[rindex + i]); + res = min(res, cur + dfs(rn, robot, fn, factory, rindex + i + 1, findex + 1, dp)); + } + return dp[rindex][findex] = res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2464-Minimum-Subarrays-in-a-Valid-Split/cpp-2464/CMakeLists.txt b/2001-2500/2464-Minimum-Subarrays-in-a-Valid-Split/cpp-2464/CMakeLists.txt new file mode 100644 index 00000000..bf6e4681 --- /dev/null +++ b/2001-2500/2464-Minimum-Subarrays-in-a-Valid-Split/cpp-2464/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_2464) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2464 main.cpp) diff --git a/2001-2500/2464-Minimum-Subarrays-in-a-Valid-Split/cpp-2464/main.cpp b/2001-2500/2464-Minimum-Subarrays-in-a-Valid-Split/cpp-2464/main.cpp new file mode 100644 index 00000000..d0a84df4 --- /dev/null +++ b/2001-2500/2464-Minimum-Subarrays-in-a-Valid-Split/cpp-2464/main.cpp @@ -0,0 +1,42 @@ +/// Source : https://leetcode.com/problems/minimum-subarrays-in-a-valid-split/description/ +/// Author : liuyubobobo +/// Time : 2022-11-10 + +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(n^2 * log(max_num)) +/// Space Complexity: O(n) +class Solution { +public: + int validSubarraySplit(vector& nums) { + + int n = nums.size(); + + vector dp(n + 1, INT_MAX / 2); + dp[n] = 0; + for(int i = n - 1; i >= 0; i --){ + for(int j = i; j < n; j ++) + if(gcd(nums[i], nums[j]) > 1) + dp[i] = min(dp[i], 1 + dp[j + 1]); + } + return dp[0] >= INT_MAX / 2 ? -1 : dp[0]; + } + +private: + int gcd(int a, int b){ + if(a > b) swap(a, b); + if (a == 0) return b; + return gcd(b % a, a); + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2465-Number-of-Distinct-Averages/cpp-2465/CMakeLists.txt b/2001-2500/2465-Number-of-Distinct-Averages/cpp-2465/CMakeLists.txt new file mode 100644 index 00000000..3d4364fe --- /dev/null +++ b/2001-2500/2465-Number-of-Distinct-Averages/cpp-2465/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_2465) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2465 main.cpp) diff --git a/2001-2500/2465-Number-of-Distinct-Averages/cpp-2465/main.cpp b/2001-2500/2465-Number-of-Distinct-Averages/cpp-2465/main.cpp new file mode 100644 index 00000000..a89aab84 --- /dev/null +++ b/2001-2500/2465-Number-of-Distinct-Averages/cpp-2465/main.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/number-of-distinct-averages/description/ +/// Author : liuyubobobo +/// Time : 2022-11-27 + +#include +#include +#include +#include + +using namespace std; + + +/// Sorting and using set +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + int distinctAverages(vector& nums) { + + sort(nums.begin(), nums.end()); + + set res; + for(int i = 0, j = nums.size() - 1; i < j; i ++, j --) + res.insert(nums[i] + nums[j]); + return res.size(); + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2466-Count-Ways-To-Build-Good-Strings/cpp-2466/CMakeLists.txt b/2001-2500/2466-Count-Ways-To-Build-Good-Strings/cpp-2466/CMakeLists.txt new file mode 100644 index 00000000..6377af39 --- /dev/null +++ b/2001-2500/2466-Count-Ways-To-Build-Good-Strings/cpp-2466/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_2466) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2466 main.cpp) diff --git a/2001-2500/2466-Count-Ways-To-Build-Good-Strings/cpp-2466/main.cpp b/2001-2500/2466-Count-Ways-To-Build-Good-Strings/cpp-2466/main.cpp new file mode 100644 index 00000000..1ae9b515 --- /dev/null +++ b/2001-2500/2466-Count-Ways-To-Build-Good-Strings/cpp-2466/main.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/count-ways-to-build-good-strings/ +/// Author : liuyubobobo +/// Time : 2022-11-27 + +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +private: + const long long MOD = 1e9 + 7; + +public: + int countGoodStrings(int low, int high, int zero, int one) { + + vector dp(high + 1, 0); + dp[0] = 1; + for(int i = 1; i <= high; i ++){ + if(i - zero >= 0) dp[i] += dp[i - zero]; + if(i - one >= 0) dp[i] += dp[i - one]; + dp[i] %= MOD; + } + + long long res = 0; + for(int i = low; i <= high; i ++) res += dp[i]; + return res % MOD; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2467-Most-Profitable-Path-in-a-Tree/cpp-2467/CMakeLists.txt b/2001-2500/2467-Most-Profitable-Path-in-a-Tree/cpp-2467/CMakeLists.txt new file mode 100644 index 00000000..1c935fb3 --- /dev/null +++ b/2001-2500/2467-Most-Profitable-Path-in-a-Tree/cpp-2467/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_2467) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2467 main.cpp) diff --git a/2001-2500/2467-Most-Profitable-Path-in-a-Tree/cpp-2467/main.cpp b/2001-2500/2467-Most-Profitable-Path-in-a-Tree/cpp-2467/main.cpp new file mode 100644 index 00000000..01f29a9e --- /dev/null +++ b/2001-2500/2467-Most-Profitable-Path-in-a-Tree/cpp-2467/main.cpp @@ -0,0 +1,107 @@ +/// Source : https://leetcode.com/problems/most-profitable-path-in-a-tree/description/ +/// Author : liuyubobobo +/// Time : 2022-11-28 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +public: + int mostProfitablePath(vector>& edges, int bob, vector& amount) { + + int n = edges.size() + 1; + + vector> tree(n); + for(const vector& edge: edges){ + int a = edge[0], b = edge[1]; + tree[a].push_back(b), tree[b].push_back(a); + } + + vector parent(n, 0); + dfs_parent(tree, 0, 0, parent); + + vector bob_path = {bob}; + while(bob_path.back() != 0) bob_path.push_back(parent[bob_path.back()]); + + int res = INT_MIN, ares = 0, bres = 0; + vector visited(n, 0); + dfs(tree, 0, 0, 0, visited, bob_path, amount, ares, bres, res); + return res; + } + +private: + void dfs(const vector>& tree, int u, int p, int index, + vector& visited, const vector& bob_path, const vector& amount, + int& ares, int& bres, int& res){ + + if(index < bob_path.size()){ + if(u == bob_path[index]){ + ares += amount[u] / 2, bres += amount[u] / 2; + assert(visited[u] == 0); + visited[u] |= 3; + } + else{ + if(!visited[u]) + ares += amount[u], visited[u] |= 1; + if(!visited[bob_path[index]]) + bres += amount[bob_path[index]], visited[bob_path[index]] |= 2; + } + } + else{ + if(!visited[u]) ares += amount[u], visited[u] |= 1; + } + + if(tree[u].size() == 1 && u){ + res = max(res, ares); + } + + for(int v: tree[u]){ + if(v == p) continue; + dfs(tree, v, u, index + 1, visited, bob_path, amount, ares, bres, res); + } + + if(index < bob_path.size()){ + if(u == bob_path[index]){ + assert(visited[u] == 3); + ares -= amount[u] / 2, bres -= amount[u] / 2; + visited[u] = 0; + } + else{ + if(visited[u] & 1) ares -= amount[u], visited[u] -= 1; + if(visited[bob_path[index]] & 2) bres -= amount[bob_path[index]], visited[bob_path[index]] -= 2; + } + } + else{ + if(visited[u] & 1) ares -= amount[u], visited[u] -= 1; + } + } + + void dfs_parent(const vector>& tree, int u, int p, vector& parent){ + + parent[u] = p; + for(int v: tree[u]){ + if(v == p) continue; + dfs_parent(tree, v, u, parent); + } + } +}; + + +int main() { + + vector> edges1 = {{0, 1}, {1, 2}, {2, 3}}; + vector amount1 = {-5644,-6018,1188,-8502}; + cout << Solution().mostProfitablePath(edges1, 3, amount1) << '\n'; + + return 0; +} diff --git a/2001-2500/2468-Split-Message-Based-on-Limit/cpp-2468/CMakeLists.txt b/2001-2500/2468-Split-Message-Based-on-Limit/cpp-2468/CMakeLists.txt new file mode 100644 index 00000000..1ebd4187 --- /dev/null +++ b/2001-2500/2468-Split-Message-Based-on-Limit/cpp-2468/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_2468) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2468 main.cpp) diff --git a/2001-2500/2468-Split-Message-Based-on-Limit/cpp-2468/main.cpp b/2001-2500/2468-Split-Message-Based-on-Limit/cpp-2468/main.cpp new file mode 100644 index 00000000..3e2695b4 --- /dev/null +++ b/2001-2500/2468-Split-Message-Based-on-Limit/cpp-2468/main.cpp @@ -0,0 +1,61 @@ +/// Source : https://leetcode.com/problems/split-message-based-on-limit/description/ +/// Author : liuyubobobo +/// Time : 2022-11-28 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector splitMessage(string message, int limit) { + + int n = message.size(); + for(int part_len = 1;part_len + part_len + 3 < limit; part_len ++){ + vector res; + if(ok(n, message, part_len, limit, res)) return res; + } + return {}; + } + +private: + bool ok(int n, const string& message, int part_len, int limit, vector& res){ + + string part_num(part_len, '#'); + for(int i = 1, j = 0; j < n; i ++){ + string i_str = to_string(i); + if(i_str.size() > part_len) return false; + + string suf = "<" + i_str + "/" + part_num + ">"; + int content_len = limit - suf.size(); + string content = message.substr(j, content_len); + j += content_len; + + res.push_back(content + suf); + } + + string len = to_string(res.size()); + if(len.size() != part_len) return false; + + for(string& s: res) s.replace(s.find(part_num), part_len, len); + return true; + } +}; + + +void print_vec(const vector& v){ + for(const string& e: v) cout << e << '\n'; +} + +int main() { + + string message1 = "this is really a very awesome message"; + print_vec(Solution().splitMessage("this is really a very awesome message", 9)); + + return 0; +} diff --git a/2001-2500/2469-Convert-the-Temperature/cpp-2469/CMakeLists.txt b/2001-2500/2469-Convert-the-Temperature/cpp-2469/CMakeLists.txt new file mode 100644 index 00000000..415e0a92 --- /dev/null +++ b/2001-2500/2469-Convert-the-Temperature/cpp-2469/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/2001-2500/2469-Convert-the-Temperature/cpp-2469/main.cpp b/2001-2500/2469-Convert-the-Temperature/cpp-2469/main.cpp new file mode 100644 index 00000000..93e2851d --- /dev/null +++ b/2001-2500/2469-Convert-the-Temperature/cpp-2469/main.cpp @@ -0,0 +1,28 @@ +/// Source : https://leetcode.com/problems/convert-the-temperature/ +/// Author : liuyubobobo +/// Time : 2022-11-12 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(1) +/// Space Complexity: O(1) +class Solution { +public: + vector convertTemperature(double celsius) { + + double k = celsius + 273.15; + double f = celsius * 1.80 + 32.00; + return {k, f}; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2470-Number-of-Subarrays-With-LCM-Equal-to-K/cpp-2470/CMakeLists.txt b/2001-2500/2470-Number-of-Subarrays-With-LCM-Equal-to-K/cpp-2470/CMakeLists.txt new file mode 100644 index 00000000..b1c82ab8 --- /dev/null +++ b/2001-2500/2470-Number-of-Subarrays-With-LCM-Equal-to-K/cpp-2470/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/2001-2500/2470-Number-of-Subarrays-With-LCM-Equal-to-K/cpp-2470/main.cpp b/2001-2500/2470-Number-of-Subarrays-With-LCM-Equal-to-K/cpp-2470/main.cpp new file mode 100644 index 00000000..d7b52a57 --- /dev/null +++ b/2001-2500/2470-Number-of-Subarrays-With-LCM-Equal-to-K/cpp-2470/main.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/number-of-subarrays-with-lcm-equal-to-k/ +/// Author : liuyubobobo +/// Time : 2022-11-12 + +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(n^2 * logk) +/// Space Complexity: O(1) +class Solution { +public: + int subarrayLCM(vector& nums, int k) { + + int n = nums.size(), res = 0; + for(int l = 0; l < n; l ++){ + int lcm = nums[l]; + if(lcm == k) res ++; + else if(lcm > k) continue; + for(int r = l + 1; r < n && lcm <= k; r ++){ + lcm = lcm * nums[r] / gcd(lcm, nums[r]); + if(lcm == k) res ++; + } + } + return res; + } + +private: + int gcd(int a, int b){ + + if(a < b) swap(a, b); + int c; + while (b){ + c = a % b; + a = b; + b = c; + } + return a; + } +}; + + +int main() { + + vector nums1 = {3, 6, 2, 7, 1}; + cout << Solution().subarrayLCM(nums1, 6) << '\n'; + + return 0; +} diff --git a/2001-2500/2471-Minimum-Number-of-Operations-to-Sort-a-Binary-Tree-by-Level/cpp-2471/CMakeLists.txt b/2001-2500/2471-Minimum-Number-of-Operations-to-Sort-a-Binary-Tree-by-Level/cpp-2471/CMakeLists.txt new file mode 100644 index 00000000..d0dc1506 --- /dev/null +++ b/2001-2500/2471-Minimum-Number-of-Operations-to-Sort-a-Binary-Tree-by-Level/cpp-2471/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/2001-2500/2471-Minimum-Number-of-Operations-to-Sort-a-Binary-Tree-by-Level/cpp-2471/main.cpp b/2001-2500/2471-Minimum-Number-of-Operations-to-Sort-a-Binary-Tree-by-Level/cpp-2471/main.cpp new file mode 100644 index 00000000..35422c71 --- /dev/null +++ b/2001-2500/2471-Minimum-Number-of-Operations-to-Sort-a-Binary-Tree-by-Level/cpp-2471/main.cpp @@ -0,0 +1,84 @@ +/// Source : https://leetcode.com/problems/minimum-number-of-operations-to-sort-a-binary-tree-by-level/ +/// Author : liuyubobobo +/// Time : 2022-11-13 + +#include +#include +#include + +using namespace std; + + +/// BFS + Greedy +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) + +/// 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: + int minimumOperations(TreeNode* root) { + + queue q; + q.push(root); + int res = 0; + vector num2index(1e5 + 1, -1); + while(!q.empty()){ + + vector v; + while(!q.empty()) v.push_back(q.front()), q.pop(); + + vector data(v.size()); + for(int i = 0; i < v.size(); i ++) data[i] = v[i]->val; + + res += solve(data.size(), data, num2index); + + for(TreeNode* node: v){ + if(node->left) q.push(node->left); + if(node->right) q.push(node->right); + } + } + return res; + } + +private: + int solve(int n, vector& data, vector& num2index){ + + for(int i = 0; i < n; i ++) num2index[data[i]] = i; + + vector sorted_data = data; + sort(sorted_data.begin(), sorted_data.end()); + + int res = 0; + for(int i = 0; i < n; i ++){ + int j = num2index[sorted_data[i]]; + if(i != j){ + res ++; + swap(data[i], data[j]); + num2index[data[j]] = j; + } + } + return res; + } +}; + + +int main() { + + TreeNode* left = new TreeNode(4, new TreeNode(7), new TreeNode(6)); + TreeNode* right = new TreeNode(3, new TreeNode(8, new TreeNode(9), nullptr), new TreeNode(5, new TreeNode(10), + nullptr)); + TreeNode* root = new TreeNode(1, left, right); + cout << Solution().minimumOperations(root) << '\n'; + // 3 + + return 0; +} diff --git a/2001-2500/2472-Maximum-Number-of-Non-overlapping-Palindrome-Substrings/cpp-2472/CMakeLists.txt b/2001-2500/2472-Maximum-Number-of-Non-overlapping-Palindrome-Substrings/cpp-2472/CMakeLists.txt new file mode 100644 index 00000000..8148fadd --- /dev/null +++ b/2001-2500/2472-Maximum-Number-of-Non-overlapping-Palindrome-Substrings/cpp-2472/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) diff --git a/2001-2500/2472-Maximum-Number-of-Non-overlapping-Palindrome-Substrings/cpp-2472/main.cpp b/2001-2500/2472-Maximum-Number-of-Non-overlapping-Palindrome-Substrings/cpp-2472/main.cpp new file mode 100644 index 00000000..2b6896ae --- /dev/null +++ b/2001-2500/2472-Maximum-Number-of-Non-overlapping-Palindrome-Substrings/cpp-2472/main.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/maximum-number-of-non-overlapping-palindrome-substrings/description/ +/// Author : liuyubobobo +/// Time : 2022-11-12 + +#include +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(n^2 + nk) +/// Space Complexity: O(n^2) +class Solution { +public: + int maxPalindromes(string s, int k) { + + int n = s.size(); + + vector> is_palindrome(n, vector(n + 1, false)); // start, len + for(int i = 0; i < n; i ++) is_palindrome[i][1] = is_palindrome[i][0] = true; + for(int len = 2; len <= n; len ++) + for(int i = 0; i + len <= n; i ++) + if(s[i] == s[i + len - 1] && is_palindrome[i + 1][len - 2]) is_palindrome[i][len] = true; + + vector dp(n + 1, INT_MIN / 2); + dp[n] = 0; + dp[n - 1] = (k == 1); + for(int i = n - 2; i >= 0; i --){ + dp[i] = dp[i + 1]; + for(int len = k; i + len <= n; len ++) + if(is_palindrome[i][len]) dp[i] = max(dp[i], 1 + dp[i + len]); + } + return dp[0] >= 0 ? dp[0] : 0; + } +}; + + +int main() { + + cout << Solution().maxPalindromes("abaccdbbd", 3) << '\n'; + // 2 + + cout << Solution().maxPalindromes("adbcda", 2) << '\n'; + // 0 + + cout << Solution().maxPalindromes("fttfjofpnpfydwdwdnns", 2) << '\n'; + // 4 + + return 0; +} diff --git a/2001-2500/2473-Minimum-Cost-to-Buy-Apples/cpp-2473/CMakeLists.txt b/2001-2500/2473-Minimum-Cost-to-Buy-Apples/cpp-2473/CMakeLists.txt new file mode 100644 index 00000000..1c1b6186 --- /dev/null +++ b/2001-2500/2473-Minimum-Cost-to-Buy-Apples/cpp-2473/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_2473) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2473 main.cpp) diff --git a/2001-2500/2473-Minimum-Cost-to-Buy-Apples/cpp-2473/main.cpp b/2001-2500/2473-Minimum-Cost-to-Buy-Apples/cpp-2473/main.cpp new file mode 100644 index 00000000..01c41481 --- /dev/null +++ b/2001-2500/2473-Minimum-Cost-to-Buy-Apples/cpp-2473/main.cpp @@ -0,0 +1,82 @@ +/// Source : https://leetcode.com/problems/minimum-cost-to-buy-apples/description/ +/// Author : liuyubobobo +/// Time : 2022-11-28s + +#include +#include +#include +#include + +using namespace std; + + +/// Dij +/// Time Complexity: O(V^2*logE + V^2) +/// Space Complexity: O(V^2) +class Solution { +public: + vector minCost(int n, vector>& roads, vector& appleCost, int k) { + + vector>> g(n); + for(const vector& e: roads){ + int u = e[0], v = e[1], w = e[2]; + u --, v --; + g[u].push_back({v, w}); + g[v].push_back({u, w}); + } + + vector> dis(n); + for(int u = 0; u < n; u ++) dis[u] = dij(n, g, u); + + vector res(n, LONG_LONG_MAX); + for(int s = 0; s < n; s ++){ + for(int t = 0; t < n; t ++) + if(dis[s][t] != LONG_LONG_MAX / 2) + res[s] = min(res[s], dis[s][t] * (k + 1) + appleCost[t]); + } + return res; + } + +private: + vector dij(int n, const vector>>& g, int s){ + + priority_queue, vector>, greater<>> pq; + pq.push({0, s}); + vector dis(n, LONG_LONG_MAX / 2); + dis[s] = 0; + vector visited(n, false); + while(!pq.empty()){ + long long d = pq.top().first; + int u = pq.top().second; + pq.pop(); + + if(visited[u]) continue; + visited[u] = true; + + for(const pair& p: g[u]){ + int v = p.first; long long w = p.second; + if(!visited[v] && d + w < dis[v]){ + dis[v] = d + w; + pq.push({dis[v], v}); + } + } + } + return dis; + } +}; + + +void print_vec(const vector& v){ + for(long long e: v) cout << e << ' '; cout << '\n'; +} + +int main() { + + vector> roads1 = { + {1,2,4},{2,3,2},{2,4,5},{3,4,1},{1,3,4} + }; + vector appleCost1 = {56,42,102,301}; + print_vec(Solution().minCost(4, roads1, appleCost1, 2)); + + return 0; +} diff --git a/2001-2500/2475-Number-of-Unequal-Triplets-in-Array/cpp-2475/CMakeLists.txt b/2001-2500/2475-Number-of-Unequal-Triplets-in-Array/cpp-2475/CMakeLists.txt new file mode 100644 index 00000000..b7b6f031 --- /dev/null +++ b/2001-2500/2475-Number-of-Unequal-Triplets-in-Array/cpp-2475/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_2475) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2475 main.cpp) diff --git a/2001-2500/2475-Number-of-Unequal-Triplets-in-Array/cpp-2475/main.cpp b/2001-2500/2475-Number-of-Unequal-Triplets-in-Array/cpp-2475/main.cpp new file mode 100644 index 00000000..6cc3e925 --- /dev/null +++ b/2001-2500/2475-Number-of-Unequal-Triplets-in-Array/cpp-2475/main.cpp @@ -0,0 +1,31 @@ +/// Source : https://leetcode.com/problems/number-of-unequal-triplets-in-array/ +/// Author : liuyubobobo +/// Time : 2022-11-28 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n^3) +/// Space Complexity: O(1) +class Solution { +public: + int unequalTriplets(vector& nums) { + + int n = nums.size(), res = 0; + for(int i = 0; i < n; i ++) + for(int j = i + 1; j < n; j ++) + for(int k = j + 1; k < n; k ++) + res += (nums[i] != nums[j] && nums[j] != nums[k] && nums[i] != nums[k]); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2476-Closest-Nodes-Queries-in-a-Binary-Search-Tree/cpp-2476/CMakeLists.txt b/2001-2500/2476-Closest-Nodes-Queries-in-a-Binary-Search-Tree/cpp-2476/CMakeLists.txt new file mode 100644 index 00000000..a5f89477 --- /dev/null +++ b/2001-2500/2476-Closest-Nodes-Queries-in-a-Binary-Search-Tree/cpp-2476/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_2476) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2476 main.cpp) diff --git a/2001-2500/2476-Closest-Nodes-Queries-in-a-Binary-Search-Tree/cpp-2476/main.cpp b/2001-2500/2476-Closest-Nodes-Queries-in-a-Binary-Search-Tree/cpp-2476/main.cpp new file mode 100644 index 00000000..fab611bc --- /dev/null +++ b/2001-2500/2476-Closest-Nodes-Queries-in-a-Binary-Search-Tree/cpp-2476/main.cpp @@ -0,0 +1,64 @@ +/// Source : https://leetcode.com/problems/closest-nodes-queries-in-a-binary-search-tree/description/ +/// Author : liuyubobobo +/// Time : 2022-11-28 + +#include +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) + +/// 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> closestNodes(TreeNode* root, vector& queries) { + + vector data; + dfs(root, data); + + int q = queries.size(); + vector> res(q, {-1, -1}); + for(int i = 0; i < q; i ++){ + int e = queries[i]; + + auto iter = upper_bound(data.begin(), data.end(), e); + if(iter != data.begin()){ + iter --; + res[i][0] = *iter; + } + + iter = lower_bound(data.begin(), data.end(), e); + if(iter != data.end()) res[i][1] = *iter; + } + return res; + } + +private: + void dfs(TreeNode* node, vector& data){ + if(!node) return; + + dfs(node->left, data); + data.push_back(node->val); + dfs(node->right, data); + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2477-Minimum-Fuel-Cost-to-Report-to-the-Capital/cpp-2477/CMakeLists.txt b/2001-2500/2477-Minimum-Fuel-Cost-to-Report-to-the-Capital/cpp-2477/CMakeLists.txt new file mode 100644 index 00000000..343aa694 --- /dev/null +++ b/2001-2500/2477-Minimum-Fuel-Cost-to-Report-to-the-Capital/cpp-2477/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_2477) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2477 main.cpp) diff --git a/2001-2500/2477-Minimum-Fuel-Cost-to-Report-to-the-Capital/cpp-2477/main.cpp b/2001-2500/2477-Minimum-Fuel-Cost-to-Report-to-the-Capital/cpp-2477/main.cpp new file mode 100644 index 00000000..09bc5c0c --- /dev/null +++ b/2001-2500/2477-Minimum-Fuel-Cost-to-Report-to-the-Capital/cpp-2477/main.cpp @@ -0,0 +1,51 @@ +/// Source : https://leetcode.com/problems/minimum-fuel-cost-to-report-to-the-capital/description/ +/// Author : liuyubobobo +/// Time : 2022-11-29 + +#include +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + long long minimumFuelCost(vector>& roads, int seats) { + + int n = roads.size() + 1; + vector> tree(n); + for(const vector& road: roads){ + int a = road[0], b = road[1]; + tree[a].push_back(b), tree[b].push_back(a); + } + + vector sz(n, 0); + dfs_sz(tree, 0, 0, sz); + + long long res = 0; + for(int i = 1; i < n; i ++) + res += sz[i] / seats + !!(sz[i] % seats); + return res; + } + +private: + int dfs_sz(const vector>& tree, int u, int p, vector& sz){ + + int res = 1; + for(int v: tree[u]){ + if(v == p) continue; + res += dfs_sz(tree, v, u, sz); + } + return sz[u] = res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2478-Number-of-Beautiful-Partitions/cpp-2478/CMakeLists.txt b/2001-2500/2478-Number-of-Beautiful-Partitions/cpp-2478/CMakeLists.txt new file mode 100644 index 00000000..3bf294af --- /dev/null +++ b/2001-2500/2478-Number-of-Beautiful-Partitions/cpp-2478/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_2478) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_2478 main.cpp) diff --git a/2001-2500/2478-Number-of-Beautiful-Partitions/cpp-2478/main.cpp b/2001-2500/2478-Number-of-Beautiful-Partitions/cpp-2478/main.cpp new file mode 100644 index 00000000..39468d11 --- /dev/null +++ b/2001-2500/2478-Number-of-Beautiful-Partitions/cpp-2478/main.cpp @@ -0,0 +1,71 @@ +/// Source : https://leetcode.com/problems/number-of-beautiful-partitions/description/ +/// Author : liuyubobobo +/// Time : 2022-12-01 + +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { + +private: + const long long MOD = 1e9 + 7; + +public: + int beautifulPartitions(string s, int k, int minLength) { + + int n = s.size(); + + vector dp(n, 0), sufsum(n, 0); + for(int i = n - minLength; i >= 0; i --) + if(can_be_start(s, i) && !is_prime(s[n - 1])) dp[i] = 1; + + sufsum[n - 1] = dp[n - 1]; + for(int i = n - 2; i >= 0; i --) sufsum[i] = dp[i] + sufsum[i + 1]; + + for(int cnt = 2; cnt <= k; cnt ++){ + vector tdp(n, 0); + for(int i = n - cnt * minLength; i >= 0; i --){ + if(can_be_start(s, i)) tdp[i] = sufsum[i + minLength]; + } + + sufsum[n - 1]= tdp[n - 1]; + for(int i = n - 2; i >= 0; i --) + sufsum[i] = (tdp[i] + sufsum[i + 1]) % MOD; + dp = tdp; + } + return dp[0]; + } + +private: + bool can_be_start(const string& s, int index){ + return is_prime(s[index]) && (index == 0 || !is_prime(s[index - 1])); + } + + bool is_prime(char c){ + return c == '2' || c == '3' || c == '5' || c == '7'; + } +}; + + +int main() { + + string s1 = "23542185131"; + cout << Solution().beautifulPartitions(s1, 3, 2) << '\n'; + // 3 + + string s2 = "23542185131"; + cout << Solution().beautifulPartitions(s2, 3, 3) << '\n'; + // 1 + + string s3 = "3312958"; + cout << Solution().beautifulPartitions(s3, 3, 1) << '\n'; + // 1 + + return 0; +} diff --git a/2001-2500/2479-Maximum-XOR-of-Two-Non-Overlapping-Subtrees/cpp-2479/CMakeLists.txt b/2001-2500/2479-Maximum-XOR-of-Two-Non-Overlapping-Subtrees/cpp-2479/CMakeLists.txt new file mode 100644 index 00000000..f55bf4c6 --- /dev/null +++ b/2001-2500/2479-Maximum-XOR-of-Two-Non-Overlapping-Subtrees/cpp-2479/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2479) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2479 main.cpp) diff --git a/2001-2500/2479-Maximum-XOR-of-Two-Non-Overlapping-Subtrees/cpp-2479/main.cpp b/2001-2500/2479-Maximum-XOR-of-Two-Non-Overlapping-Subtrees/cpp-2479/main.cpp new file mode 100644 index 00000000..650b1083 --- /dev/null +++ b/2001-2500/2479-Maximum-XOR-of-Two-Non-Overlapping-Subtrees/cpp-2479/main.cpp @@ -0,0 +1,119 @@ +/// Source : https://leetcode.com/problems/maximum-xor-of-two-non-overlapping-subtrees/description/ +/// Author : liuyubobobo +/// Time : 2022-12-02 + +#include +#include +#include + +using namespace std; + + +/// DFS + Trie +/// Time Complexity: O(nlogn(LONG_LONG_MAX)) +/// Space Complexity: O(n * LONG_LONG_MAX) +class BinaryTrie { + +private: + class Node{ + + public: + Node* next[2]; + int sz; + + Node() : sz(0) { + next[0] = next[1] = nullptr; + }; + }; + + int L; + Node* root; + +public: + BinaryTrie(int L = 63) : root(new Node()), L(L){} + + void insert(long long x) { + + Node* cur = root; + cur->sz ++; + for(int i = L - 1; i >= 0; i --){ + int e = ((x >> i) & 1); + if(cur->next[e] == nullptr) + cur->next[e] = new Node(); + cur = cur->next[e]; + cur->sz ++; + } + } + + // 返回 Binary Trie 中存储的数字和 x 异或的最大值 + long long query(long long x){ + + Node* cur = root; + long long res = 0; + for(int i = L - 1; i >= 0; i --){ + int e = ((x >> i) & 1); + if(cur->next[1 - e] && cur->next[1 - e]->sz){ + res = res * 2 + 1; + cur = cur->next[1 - e]; + } + else if(cur->next[e]){ + res = res * 2; + cur = cur->next[e]; + } + else return 0; + } + return res; + } +}; + +class Solution { + +public: + long long maxXor(int n, vector>& edges, vector& values) { + + vector> tree(n); + for(const vector& e: edges){ + int a = e[0], b = e[1]; + tree[a].push_back(b), tree[b].push_back(a); + } + + vector sum(n, 0); + dfs_sum(tree, 0, 0, values, sum); + + long long res = 0; + BinaryTrie trie; + dfs(tree, 0, 0, sum, trie, res); + return res; + } + +private: + void dfs(const vector>& tree, int u, int p, + const vector& sum, BinaryTrie& trie, long long& res){ + + res = max(res, trie.query(sum[u])); + + for(int v: tree[u]){ + if(v == p) continue; + dfs(tree, v, u, sum, trie, res); + } + + trie.insert(sum[u]); + } + + long long dfs_sum(const vector>& tree, int u, int p, + const vector& values, vector& sum){ + + long long res = values[u]; + for(int v: tree[u]){ + if(v == p) continue; + res += dfs_sum(tree, v, u, values, sum); + } + return sum[u] = res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2481-Minimum-Cuts-to-Divide-a-Circle/cpp-2481/CMakeLists.txt b/2001-2500/2481-Minimum-Cuts-to-Divide-a-Circle/cpp-2481/CMakeLists.txt new file mode 100644 index 00000000..acad2941 --- /dev/null +++ b/2001-2500/2481-Minimum-Cuts-to-Divide-a-Circle/cpp-2481/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2481) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2481 main.cpp) diff --git a/2001-2500/2481-Minimum-Cuts-to-Divide-a-Circle/cpp-2481/main.cpp b/2001-2500/2481-Minimum-Cuts-to-Divide-a-Circle/cpp-2481/main.cpp new file mode 100644 index 00000000..4983215f --- /dev/null +++ b/2001-2500/2481-Minimum-Cuts-to-Divide-a-Circle/cpp-2481/main.cpp @@ -0,0 +1,29 @@ +/// Source : https://leetcode.com/problems/minimum-cuts-to-divide-a-circle/description/ +/// Author : liuyubobobo +/// Time : 2022-12-02 + +#include + +using namespace std; + + +/// Math +/// Time Complexity: O(logn) +/// Space Complexity: O(1) +class Solution { +public: + int numberOfCuts(int n) { + + if(n == 1) return 0; + + int k = 1; + while(n % 2 == 0) k <<= 1, n >>= 1; + return n * ((k + 1) / 2); + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2482-Difference-Between-Ones-and-Zeros-in-Row-and-Column/cpp-2482/CMakeLists.txt b/2001-2500/2482-Difference-Between-Ones-and-Zeros-in-Row-and-Column/cpp-2482/CMakeLists.txt new file mode 100644 index 00000000..89189094 --- /dev/null +++ b/2001-2500/2482-Difference-Between-Ones-and-Zeros-in-Row-and-Column/cpp-2482/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2482) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2482 main.cpp) diff --git a/2001-2500/2482-Difference-Between-Ones-and-Zeros-in-Row-and-Column/cpp-2482/main.cpp b/2001-2500/2482-Difference-Between-Ones-and-Zeros-in-Row-and-Column/cpp-2482/main.cpp new file mode 100644 index 00000000..6305e93d --- /dev/null +++ b/2001-2500/2482-Difference-Between-Ones-and-Zeros-in-Row-and-Column/cpp-2482/main.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/difference-between-ones-and-zeros-in-row-and-column/description/ +/// Author : liuyubobobo +/// Time : 2022-12-02 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(R * C) +/// Space Complexity: O(R + C) +class Solution { +public: + vector> onesMinusZeros(vector>& grid) { + + int R = grid.size(), C = grid[0].size(); + vector> res(R, vector(C)); + + vector onesRow(R, 0), zerosRow(R, 0); + vector onesCol(C, 0), zerosCol(C, 0); + for(int i = 0; i < R; i ++){ + for(int j = 0; j < C; j ++) + if(grid[i][j] == 0) zerosRow[i] ++, zerosCol[j] ++; + else onesRow[i] ++, onesCol[j] ++; + } + + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++) + res[i][j] = onesRow[i] + onesCol[j] - zerosRow[i] - zerosCol[j]; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2483-Minimum-Penalty-for-a-Shop/cpp-2483/CMakeLists.txt b/2001-2500/2483-Minimum-Penalty-for-a-Shop/cpp-2483/CMakeLists.txt new file mode 100644 index 00000000..d6f67351 --- /dev/null +++ b/2001-2500/2483-Minimum-Penalty-for-a-Shop/cpp-2483/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2483) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2483 main.cpp) diff --git a/2001-2500/2483-Minimum-Penalty-for-a-Shop/cpp-2483/main.cpp b/2001-2500/2483-Minimum-Penalty-for-a-Shop/cpp-2483/main.cpp new file mode 100644 index 00000000..9f3e3934 --- /dev/null +++ b/2001-2500/2483-Minimum-Penalty-for-a-Shop/cpp-2483/main.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/minimum-penalty-for-a-shop/description/ +/// Author : liuyubobobo +/// Time : 2022-12-02 + +#include + +using namespace std; + + +/// Linear Scan +/// Time Compelxity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int bestClosingTime(string customers) { + + int res = 0, p = 0; + for(char c: customers) p += c == 'Y'; + + int best = p; + for(int i = 0; i < customers.size(); i ++){ + char c = customers[i]; + if(c == 'Y') p --; + else p ++; + if(p < best) best = p, res = i + 1; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2484-Count-Palindromic-Subsequences/cpp-2484/CMakeLists.txt b/2001-2500/2484-Count-Palindromic-Subsequences/cpp-2484/CMakeLists.txt new file mode 100644 index 00000000..7a42a496 --- /dev/null +++ b/2001-2500/2484-Count-Palindromic-Subsequences/cpp-2484/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2484) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2484 main.cpp) diff --git a/2001-2500/2484-Count-Palindromic-Subsequences/cpp-2484/main.cpp b/2001-2500/2484-Count-Palindromic-Subsequences/cpp-2484/main.cpp new file mode 100644 index 00000000..e9a8140a --- /dev/null +++ b/2001-2500/2484-Count-Palindromic-Subsequences/cpp-2484/main.cpp @@ -0,0 +1,79 @@ +/// Source : https://leetcode.com/problems/count-palindromic-subsequences/description/ +/// Author : liuyubobobo +/// Time : 2022-12-15 + +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +private: + const int D = 10; + const long long MOD = 1e9 + 7; + +public: + int countPalindromes(string s) { + + int n = s.size(); + + vector> pre1(D, vector(n)), suf1(D, vector(n)); + for(char c = 0; c < D; c ++){ + pre1[c][0] = (s[0] - '0' == c); + for(int i = 1; i < n; i ++) + pre1[c][i] = pre1[c][i - 1] + (s[i] - '0' == c); + + suf1[c][n - 1] = (s[n - 1] - '0' == c); + for(int i = n - 2; i >= 0; i --) + suf1[c][i] = suf1[c][i + 1] + (s[i] - '0' == c); + } + + vector>> pre2(10, vector>(10, vector(n, 0))); + vector>> suf2(10, vector>(10, vector(n, 0))); + for(int i = 1; i < n; i ++){ + // c1, c2, x + for(char c1 = 0; c1 < D; c1 ++) + for(char c2 = 0; c2 < D; c2 ++){ + if(s[i] - '0' == c2) pre2[c2][c1][i] += pre1[c1][i - 1]; + pre2[c2][c1][i] += pre2[c2][c1][i - 1]; + } + } + for(int i = n - 2; i >= 0; i --){ + // x, c1, c2 + for(char c1 = 0; c1 <= 9; c1 ++) + for(char c2 = 0; c2 <= 9; c2 ++){ + if(s[i] - '0' == c1) suf2[c1][c2][i] += suf1[c2][i + 1]; + suf2[c1][c2][i] += suf2[c1][c2][i + 1]; + } + } + + long long res = 0, MOD = 1e9 + 7; + for(int i = 2; i < n - 2; i ++){ + // a, b, x, b, a + for(int a = 0; a < D; a ++) + for(int b = 0; b < D; b ++) + res += (1ll * pre2[b][a][i - 1] * suf2[b][a][i + 1]) % MOD, res %= MOD; + } + return res; + } +}; + + +int main() { + + cout << Solution().countPalindromes("103301") << '\n'; + // 2 + + cout << Solution().countPalindromes("0000000") << '\n'; + // 21 + + cout << Solution().countPalindromes("9999900000") << '\n'; + // 2 + + return 0; +} diff --git a/2001-2500/2485-Find-the-Pivot-Integer/cpp-2485/CMakeLists.txt b/2001-2500/2485-Find-the-Pivot-Integer/cpp-2485/CMakeLists.txt new file mode 100644 index 00000000..8c8003d2 --- /dev/null +++ b/2001-2500/2485-Find-the-Pivot-Integer/cpp-2485/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2485) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2485 main.cpp) diff --git a/2001-2500/2485-Find-the-Pivot-Integer/cpp-2485/main.cpp b/2001-2500/2485-Find-the-Pivot-Integer/cpp-2485/main.cpp new file mode 100644 index 00000000..8bf648d5 --- /dev/null +++ b/2001-2500/2485-Find-the-Pivot-Integer/cpp-2485/main.cpp @@ -0,0 +1,30 @@ +/// Source : https://leetcode.com/problems/find-the-pivot-integer/description/ +/// Author : liuyubobobo +/// Time : 2022-12-18 + +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int pivotInteger(int n) { + + // [1...x] and [x ... n] + for(int x = 1; x <= n; x ++){ + if((1 + x) * x / 2 == (x + n) * (n - x + 1) / 2) return x; + } + return -1; + } +}; + + +int main() { + + + return 0; +} diff --git a/2001-2500/2486-Append-Characters-to-String-to-Make-Subsequence/cpp-2486/CMakeLists.txt b/2001-2500/2486-Append-Characters-to-String-to-Make-Subsequence/cpp-2486/CMakeLists.txt new file mode 100644 index 00000000..95348428 --- /dev/null +++ b/2001-2500/2486-Append-Characters-to-String-to-Make-Subsequence/cpp-2486/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2486) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2486 main.cpp) diff --git a/2001-2500/2486-Append-Characters-to-String-to-Make-Subsequence/cpp-2486/main.cpp b/2001-2500/2486-Append-Characters-to-String-to-Make-Subsequence/cpp-2486/main.cpp new file mode 100644 index 00000000..230f3528 --- /dev/null +++ b/2001-2500/2486-Append-Characters-to-String-to-Make-Subsequence/cpp-2486/main.cpp @@ -0,0 +1,28 @@ +/// Source : https://leetcode.com/problems/append-characters-to-string-to-make-subsequence/description/ +/// Author : liuyubobobo +/// Time : 2022-12-18 + +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int appendCharacters(string s, string t) { + + int j = 0; + for(int i = 0; i < s.size(); i ++) + if(j < t.size() && s[i] == t[j]) j ++; + return t.size() - j; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2487-Remove-Nodes-From-Linked-List/cpp-2487/CMakeLists.txt b/2001-2500/2487-Remove-Nodes-From-Linked-List/cpp-2487/CMakeLists.txt new file mode 100644 index 00000000..2a40371c --- /dev/null +++ b/2001-2500/2487-Remove-Nodes-From-Linked-List/cpp-2487/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2487) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2487 main.cpp) diff --git a/2001-2500/2487-Remove-Nodes-From-Linked-List/cpp-2487/main.cpp b/2001-2500/2487-Remove-Nodes-From-Linked-List/cpp-2487/main.cpp new file mode 100644 index 00000000..23f6d690 --- /dev/null +++ b/2001-2500/2487-Remove-Nodes-From-Linked-List/cpp-2487/main.cpp @@ -0,0 +1,45 @@ +/// Source : https://leetcode.com/problems/remove-nodes-from-linked-list/description/ +/// Author : liuyubobobo +/// Time : 2022-12-18 + +#include +#include + +using namespace std; + + +/// Mono Stack +/// Time Complexity: O(n) +/// Space Compelxity: O(n) + +/// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode() : val(0), next(nullptr) {} + ListNode(int x) : val(x), next(nullptr) {} + ListNode(int x, ListNode *next) : val(x), next(next) {} +}; + +class Solution { +public: + ListNode* removeNodes(ListNode* head) { + + vector stack; + for(ListNode* node = head; node; node = node->next){ + while(!stack.empty() && stack.back()->val < node->val) stack.pop_back(); + stack.push_back(node); + } + + for(int i = 0; i + 1 < stack.size(); i ++) + stack[i]->next = stack[i + 1]; + stack.back()->next = nullptr; + return stack[0]; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2488-Count-Subarrays-With-Median-K/cpp-2488/CMakeLists.txt b/2001-2500/2488-Count-Subarrays-With-Median-K/cpp-2488/CMakeLists.txt new file mode 100644 index 00000000..2e2a145f --- /dev/null +++ b/2001-2500/2488-Count-Subarrays-With-Median-K/cpp-2488/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2488) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2488 main.cpp) diff --git a/2001-2500/2488-Count-Subarrays-With-Median-K/cpp-2488/main.cpp b/2001-2500/2488-Count-Subarrays-With-Median-K/cpp-2488/main.cpp new file mode 100644 index 00000000..cea29bf4 --- /dev/null +++ b/2001-2500/2488-Count-Subarrays-With-Median-K/cpp-2488/main.cpp @@ -0,0 +1,55 @@ +/// Source : https://leetcode.com/problems/count-subarrays-with-median-k/ +/// Author : liuyubobobo +/// Time : 2022-12-18 + +#include +#include +#include +#include + +using namespace std; + + +/// Median Classic +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int countSubarrays(vector& nums, int k) { + + int n = nums.size(); + + vector data(n, 0); + int kpos = -1; + for(int i = 0; i < n; i ++) { + if (nums[i] < k) data[i] = -1; + else if (nums[i] > k) data[i] = 1; + else kpos = i; + } + + map f; + f[0] = 1; + int cur = 0; + for(int i = kpos + 1; i < n; i ++){ + cur += data[i]; + f[cur] ++; + } + + int lsum = accumulate(data.begin(), data.begin() + kpos + 1, 0); + int res = 0; + for(int l = 0; l <= kpos; l ++){ + auto iter = f.find(-lsum); + if(iter != f.end()) res += iter->second; + iter = f.find(1-lsum); + if(iter != f.end()) res += iter->second; + lsum -= data[l]; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2489-Number-of-Substrings-With-Fixed-Ratio/cpp-2489/CMakeLists.txt b/2001-2500/2489-Number-of-Substrings-With-Fixed-Ratio/cpp-2489/CMakeLists.txt new file mode 100644 index 00000000..ab10eb3d --- /dev/null +++ b/2001-2500/2489-Number-of-Substrings-With-Fixed-Ratio/cpp-2489/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2489) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2489 main.cpp) diff --git a/2001-2500/2489-Number-of-Substrings-With-Fixed-Ratio/cpp-2489/main.cpp b/2001-2500/2489-Number-of-Substrings-With-Fixed-Ratio/cpp-2489/main.cpp new file mode 100644 index 00000000..d4c0334d --- /dev/null +++ b/2001-2500/2489-Number-of-Substrings-With-Fixed-Ratio/cpp-2489/main.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/number-of-substrings-with-fixed-ratio/description/ +/// Author : liuyubobobo +/// Time : 2022-12-19 + +#include +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + long long fixedRatio(string s, int num1, int num2) { + + int n = s.size(); + vector presum1(n + 1, 0); + for(int i = 0; i < n; i ++) presum1[i + 1] = presum1[i] + (s[i] == '1'); + + long long res = 0; + map table; + table[0] = 1; + for(int i = 0; i < n; i ++){ + int t = presum1[i + 1] * num1 - (i + 1 - presum1[i + 1]) * num2; + auto iter = table.find(t); + if(iter != table.end()) res += iter->second; + table[t] ++; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2490-Circular-Sentence/cpp-2490/CMakeLists.txt b/2001-2500/2490-Circular-Sentence/cpp-2490/CMakeLists.txt new file mode 100644 index 00000000..4673bfac --- /dev/null +++ b/2001-2500/2490-Circular-Sentence/cpp-2490/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2490) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2490 main.cpp) diff --git a/2001-2500/2490-Circular-Sentence/cpp-2490/main.cpp b/2001-2500/2490-Circular-Sentence/cpp-2490/main.cpp new file mode 100644 index 00000000..c7ed13d0 --- /dev/null +++ b/2001-2500/2490-Circular-Sentence/cpp-2490/main.cpp @@ -0,0 +1,38 @@ +/// Source : https://leetcode.com/problems/circular-sentence/description/ +/// Author : liuyubobobo +/// Time : 2022-12-19 + +#include +#include +#include + +using namespace std; + + +/// Simualtion +/// Time Complexity: O(|n|) +/// Space Complexity: O(|n|) +class Solution { +public: + bool isCircularSentence(string sentence) { + + vector words; + for(int start = 0, i = 1; i <= sentence.size(); i ++){ + if(i == sentence.size() || sentence[i] == ' '){ + words.push_back(sentence.substr(start, i - start)); + start = i + 1; + i = start; + } + } + + for(int i = 1; i < words.size(); i ++) + if(words[i - 1].back() != words[i][0]) return false; + return words.back().back() == words[0][0]; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2491-Divide-Players-Into-Teams-of-Equal-Skill/cpp-2491/CMakeLists.txt b/2001-2500/2491-Divide-Players-Into-Teams-of-Equal-Skill/cpp-2491/CMakeLists.txt new file mode 100644 index 00000000..8c7ca595 --- /dev/null +++ b/2001-2500/2491-Divide-Players-Into-Teams-of-Equal-Skill/cpp-2491/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2491) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2491 main.cpp) diff --git a/2001-2500/2491-Divide-Players-Into-Teams-of-Equal-Skill/cpp-2491/main.cpp b/2001-2500/2491-Divide-Players-Into-Teams-of-Equal-Skill/cpp-2491/main.cpp new file mode 100644 index 00000000..1e4b6bb4 --- /dev/null +++ b/2001-2500/2491-Divide-Players-Into-Teams-of-Equal-Skill/cpp-2491/main.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/divide-players-into-teams-of-equal-skill/description/ +/// Author : liuyubobobo +/// Time : 2022-12-19 + +#include +#include +#include + +using namespace std; + + +/// Using Set +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + long long dividePlayers(vector& skill) { + + int n = skill.size(); + + multiset s; + int sum = 0; + for(int e: skill) s.insert(e), sum += e; + + if(sum % (n / 2)) return -1; + int t = sum / (n / 2); + + long long res = 0; + while(!s.empty()){ + int a = *s.begin(); + s.erase(s.begin()); + int b = t - a; + auto iter = s.find(b); + if(iter == s.end()) return -1; + s.erase(iter); + res += a * b; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2492-Minimum-Score-of-a-Path-Between-Two-Cities/cpp-2492/CMakeLists.txt b/2001-2500/2492-Minimum-Score-of-a-Path-Between-Two-Cities/cpp-2492/CMakeLists.txt new file mode 100644 index 00000000..a31202df --- /dev/null +++ b/2001-2500/2492-Minimum-Score-of-a-Path-Between-Two-Cities/cpp-2492/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2492) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2492 main.cpp) diff --git a/2001-2500/2492-Minimum-Score-of-a-Path-Between-Two-Cities/cpp-2492/main.cpp b/2001-2500/2492-Minimum-Score-of-a-Path-Between-Two-Cities/cpp-2492/main.cpp new file mode 100644 index 00000000..2aa82c8f --- /dev/null +++ b/2001-2500/2492-Minimum-Score-of-a-Path-Between-Two-Cities/cpp-2492/main.cpp @@ -0,0 +1,60 @@ +/// Source : https://leetcode.com/problems/minimum-score-of-a-path-between-two-cities/description/ +/// Author : liuyubobobo +/// Time : 2022-12-19 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(eloge + (v + e) + e) +/// Space Complexity: O(v + e) +class Solution { +public: + int minScore(int n, vector>& roads) { + + sort(roads.begin(), roads.end(), + [](const vector& road1, const vector& road2){ + return road1[2] < road2[2]; + }); + + vector> g(n); + for(int i = 0; i < roads.size(); i ++){ + int u = roads[i][0] - 1, v = roads[i][1] - 1; + g[u].push_back(v), g[v].push_back(u); + } + + vector visited_s(n, false); + dfs(g, 0, 0, visited_s); + + vector visited_t(n, false); + dfs(g, n - 1, n - 1, visited_t); + + for(const vector& road: roads){ + int u = road[0] - 1, v = road[1] - 1, w = road[2]; + if(visited_s[u] && visited_t[v]) return w; + if(visited_s[v] && visited_t[u]) return w; + } + return -1; + } + +private: + void dfs(const vector>& g, int u, int p, vector& visited){ + visited[u] = true; + for(int v: g[u]){ + if(v == p || visited[v]) continue; + dfs(g, v, u, visited); + } + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2493-Divide-Nodes-Into-the-Maximum-Number-of-Groups/cpp-2493/CMakeLists.txt b/2001-2500/2493-Divide-Nodes-Into-the-Maximum-Number-of-Groups/cpp-2493/CMakeLists.txt new file mode 100644 index 00000000..c65d3701 --- /dev/null +++ b/2001-2500/2493-Divide-Nodes-Into-the-Maximum-Number-of-Groups/cpp-2493/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2493) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2493 main.cpp) diff --git a/2001-2500/2493-Divide-Nodes-Into-the-Maximum-Number-of-Groups/cpp-2493/main.cpp b/2001-2500/2493-Divide-Nodes-Into-the-Maximum-Number-of-Groups/cpp-2493/main.cpp new file mode 100644 index 00000000..2c70d63b --- /dev/null +++ b/2001-2500/2493-Divide-Nodes-Into-the-Maximum-Number-of-Groups/cpp-2493/main.cpp @@ -0,0 +1,95 @@ +/// Source : https://leetcode.com/problems/divide-nodes-into-the-maximum-number-of-groups/description/ +/// Author : liuyubobobo +/// Time : 2022-12-22 + +#include +#include +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(V * (V + E)) +/// Space Complexity: O(V + E) +class Solution { +public: + int magnificentSets(int n, vector>& edges) { + + vector> g(n); + for(const vector& e: edges){ + int a = e[0] - 1, b = e[1] - 1; + g[a].push_back(b), g[b].push_back(a); + } + + vector cc(n, -1); + int cc_index = 0, res = 0; + for(int u = 0; u < n; u ++){ + if(cc[u] != -1) continue; + dfs(g, u, cc_index, cc); + + int tres = solve(n, g, cc_index, cc); + if(tres == -1) return -1; + res += tres; + + cc_index ++; + } + return res; + } + +private: + int solve(int n, const vector>& g, int cc_index, const vector& cc){ + + int res = -1; + for(int s = 0; s < n; s ++){ + if(cc[s] != cc_index) continue; + res = max(res, solve(n, g, s)); + } + + return res; + } + + int solve(int n, const vector>& g, int s){ + + vector level(n, -1), pre(n, -1); + + queue q; + q.push(s); + level[s] = 1; + pre[s] = 0; + while(!q.empty()){ + int u = q.front(); q.pop(); + for(int v: g[u]){ + if(level[v] != -1){ + if(abs(level[v] - level[u]) == 1) continue; + else return -1; + } + level[v] = level[u] + 1; + pre[v] = u; + q.push(v); + } + } + return *max_element(level.begin(), level.end()); + } + + void dfs(const vector>& g, int u, int cc_index, vector& cc){ + + cc[u] = cc_index; + for(int v: g[u]){ + if(cc[v] == -1) dfs(g, v, cc_index, cc); + } + } +}; + + +int main() { + + vector> edges1 = { + {1,2},{1,4},{1,5},{2,6},{2,3},{4,6} + }; + cout << Solution().magnificentSets(6, edges1) << '\n'; + // 4 + + return 0; +} diff --git a/2001-2500/2495-Number-of-Subarrays-Having-Even-Product/cpp-2495/CMakeLists.txt b/2001-2500/2495-Number-of-Subarrays-Having-Even-Product/cpp-2495/CMakeLists.txt new file mode 100644 index 00000000..9ff5c9ce --- /dev/null +++ b/2001-2500/2495-Number-of-Subarrays-Having-Even-Product/cpp-2495/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2495) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2495 main.cpp) diff --git a/2001-2500/2495-Number-of-Subarrays-Having-Even-Product/cpp-2495/main.cpp b/2001-2500/2495-Number-of-Subarrays-Having-Even-Product/cpp-2495/main.cpp new file mode 100644 index 00000000..93b26744 --- /dev/null +++ b/2001-2500/2495-Number-of-Subarrays-Having-Even-Product/cpp-2495/main.cpp @@ -0,0 +1,42 @@ +/// Source : https://leetcode.com/problems/number-of-subarrays-having-even-product/description/ +/// Author : liuyubobobo +/// Time : 2022-12-22 + +#include +#include + +using namespace std; + + +/// Mono Stack +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + long long evenProduct(vector& nums) { + + int n = nums.size(); + vector next_even(n, n), stack; + + for(int i = 0; i < n; i ++){ + stack.push_back(i); + if(nums[i] % 2 == 0){ + while(!stack.empty()){ + next_even[stack.back()] = i; + stack.pop_back(); + } + } + } + + long long res = 0; + for(int l = 0; l < n; l ++) + res += n - next_even[l]; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2496-Maximum-Value-of-a-String-in-an-Array/cpp-2496/CMakeLists.txt b/2001-2500/2496-Maximum-Value-of-a-String-in-an-Array/cpp-2496/CMakeLists.txt new file mode 100644 index 00000000..ff1e9fd5 --- /dev/null +++ b/2001-2500/2496-Maximum-Value-of-a-String-in-an-Array/cpp-2496/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2496) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2496 main.cpp) diff --git a/2001-2500/2496-Maximum-Value-of-a-String-in-an-Array/cpp-2496/main.cpp b/2001-2500/2496-Maximum-Value-of-a-String-in-an-Array/cpp-2496/main.cpp new file mode 100644 index 00000000..723b6bbb --- /dev/null +++ b/2001-2500/2496-Maximum-Value-of-a-String-in-an-Array/cpp-2496/main.cpp @@ -0,0 +1,48 @@ +/// Source : https://leetcode.com/problems/frog-jump-ii/description/ +/// Author : liuyubobobo +/// Time : 2023-01-02 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n * |s|) +/// Space Complexity: O(1) +class Solution { +public: + int maximumValue(vector& strs) { + + int res = 0; + for(const string& s: strs) + res = max(res, get_value(s)); + return res; + } + +private: + int get_value(const string& s){ + + if(all_digits(s)){ + long long res = 0; + for(char c: s) + res = res * 10 + (c - '0'); + return res; + } + return s.size(); + } + + bool all_digits(const string& s){ + + for(char c: s) + if(!isdigit(c)) return false; + return true; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2497-Maximum-Star-Sum-of-a-Graph/cpp-2497/CMakeLists.txt b/2001-2500/2497-Maximum-Star-Sum-of-a-Graph/cpp-2497/CMakeLists.txt new file mode 100644 index 00000000..bfcd001f --- /dev/null +++ b/2001-2500/2497-Maximum-Star-Sum-of-a-Graph/cpp-2497/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2497) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2497 main.cpp) diff --git a/2001-2500/2497-Maximum-Star-Sum-of-a-Graph/cpp-2497/main.cpp b/2001-2500/2497-Maximum-Star-Sum-of-a-Graph/cpp-2497/main.cpp new file mode 100644 index 00000000..32bd1135 --- /dev/null +++ b/2001-2500/2497-Maximum-Star-Sum-of-a-Graph/cpp-2497/main.cpp @@ -0,0 +1,43 @@ +/// Source : https://leetcode.com/problems/maximum-star-sum-of-a-graph/description/ +/// Author : liuyubobobo +/// Time : 2022-12-31 + +#include +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(V + E) +/// Space Complexity: O(V + E) +class Solution { +public: + int maxStarSum(vector& vals, vector>& edges, int k) { + + int n = vals.size(); + vector> g(n); + for(const vector& e: edges){ + int a = e[0], b = e[1]; + g[a].push_back(vals[b]); + g[b].push_back(vals[a]); + } + + for(vector& v: g) sort(v.begin(), v.end(), greater()); + + int res = INT_MIN; + for(int u = 0; u < n; u ++){ + int sum = vals[u]; + for(int i = 0; i < g[u].size() && i < k && g[u][i] > 0; i ++) sum += g[u][i]; + res = max(res, sum); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2498-Frog-Jump-II/cpp-2498/CMakeLists.txt b/2001-2500/2498-Frog-Jump-II/cpp-2498/CMakeLists.txt new file mode 100644 index 00000000..7521f191 --- /dev/null +++ b/2001-2500/2498-Frog-Jump-II/cpp-2498/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2498) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2498 main.cpp) diff --git a/2001-2500/2498-Frog-Jump-II/cpp-2498/main.cpp b/2001-2500/2498-Frog-Jump-II/cpp-2498/main.cpp new file mode 100644 index 00000000..67f138f3 --- /dev/null +++ b/2001-2500/2498-Frog-Jump-II/cpp-2498/main.cpp @@ -0,0 +1,33 @@ +#include +#include +#include + +using namespace std; + + +class Solution { +public: + int maxJump(vector& stones) { + + stones.push_back(stones.back()); + + int n = stones.size(), res = 0; + for(int i = 2; i < n; i += 2) + res = max(res, stones[i] - stones[i - 2]); + + res = max(res, stones[1]); + for(int i = 3; i < n; i += 2) + res = max(res, stones[i] - stones[i - 2]); + return res; + } +}; + + +int main() { + + vector stones1 = {0, 3, 9}; + cout << Solution().maxJump(stones1) << '\n'; + // 9 + + return 0; +} diff --git a/2001-2500/2499-Minimum-Total-Cost-to-Make-Arrays-Unequal/cpp-2499/CMakeLists.txt b/2001-2500/2499-Minimum-Total-Cost-to-Make-Arrays-Unequal/cpp-2499/CMakeLists.txt new file mode 100644 index 00000000..33689c88 --- /dev/null +++ b/2001-2500/2499-Minimum-Total-Cost-to-Make-Arrays-Unequal/cpp-2499/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2499) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2499 main.cpp) diff --git a/2001-2500/2499-Minimum-Total-Cost-to-Make-Arrays-Unequal/cpp-2499/main.cpp b/2001-2500/2499-Minimum-Total-Cost-to-Make-Arrays-Unequal/cpp-2499/main.cpp new file mode 100644 index 00000000..9695c39f --- /dev/null +++ b/2001-2500/2499-Minimum-Total-Cost-to-Make-Arrays-Unequal/cpp-2499/main.cpp @@ -0,0 +1,43 @@ +/// Source : https://leetcode.com/problems/minimum-total-cost-to-make-arrays-unequal/description/ +/// Author : liuyubobobo +/// Time : 2023-01-09 + +#include +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + long long minimumTotalCost(vector& nums1, vector& nums2) { + + int n = nums1.size(); + + map f; + int total = 0; + long long res = 0; + for(int i = 0; i < n; i ++) + if(nums1[i] == nums2[i]) f[nums1[i]] ++, total ++, res += i; + + int maxf = 0, maxf_value; + for(const pair& p: f) + if(p.second > maxf) maxf = p.second, maxf_value = p.first; + + for(int i = 0; i < n && maxf > total / 2; i ++) + if(nums1[i] != nums2[i] && nums1[i] != maxf_value && nums2[i] != maxf_value) + res += i, total ++; + + return maxf > total / 2 ? -1 : res; + } +}; + + +int main() { + + return 0; +} diff --git a/2001-2500/2500-Delete-Greatest-Value-in-Each-Row/cpp-2500/CMakeLists.txt b/2001-2500/2500-Delete-Greatest-Value-in-Each-Row/cpp-2500/CMakeLists.txt new file mode 100644 index 00000000..2b9df6f0 --- /dev/null +++ b/2001-2500/2500-Delete-Greatest-Value-in-Each-Row/cpp-2500/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(A) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(A main.cpp) diff --git a/2001-2500/2500-Delete-Greatest-Value-in-Each-Row/cpp-2500/main.cpp b/2001-2500/2500-Delete-Greatest-Value-in-Each-Row/cpp-2500/main.cpp new file mode 100644 index 00000000..02c1ba57 --- /dev/null +++ b/2001-2500/2500-Delete-Greatest-Value-in-Each-Row/cpp-2500/main.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/delete-greatest-value-in-each-row/ +/// Author : liuyubobobo +/// Time : 2022-12-10 + +#include +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(R * ClogC) +/// Space Complexity: O(1) +class Solution { +public: + int deleteGreatestValue(vector>& grid) { + + for(vector& row: grid) sort(row.begin(), row.end()); + + int res = 0; + for(int j = grid[0].size() - 1; j >= 0; j --){ + int maxv = 0; + for(int i = 0; i < grid.size(); i ++) maxv = max(maxv, grid[i][j]); + res += maxv; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2501-Longest-Square-Streak-in-an-Array/cpp-2501/CMakeLists.txt b/2501-3000/2501-Longest-Square-Streak-in-an-Array/cpp-2501/CMakeLists.txt new file mode 100644 index 00000000..f9dab828 --- /dev/null +++ b/2501-3000/2501-Longest-Square-Streak-in-an-Array/cpp-2501/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(B) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(B main.cpp) diff --git a/2501-3000/2501-Longest-Square-Streak-in-an-Array/cpp-2501/main.cpp b/2501-3000/2501-Longest-Square-Streak-in-an-Array/cpp-2501/main.cpp new file mode 100644 index 00000000..b2d7753e --- /dev/null +++ b/2501-3000/2501-Longest-Square-Streak-in-an-Array/cpp-2501/main.cpp @@ -0,0 +1,49 @@ +/// Source : https://leetcode.com/problems/longest-square-streak-in-an-array/description/ +/// Author : liuyubobobo +/// Time : 2022-12-10 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(nlogn) +/// Space Compelxity: O(1) +class Solution { +public: + int longestSquareStreak(vector& nums) { + + int n = nums.size(); + vector v(n); + for(int i = 0; i < n; i ++) v[i] = nums[i]; + + sort(v.begin(), v.end()); + int res = 0; + for(int start = 0, i = 1; i <= n; i ++){ + if(i == n || v[i] != v[start]){ + int len = 1; + long long cur = v[start], cur_index = start; + while(true){ + auto iter = lower_bound(v.begin() + cur_index, v.end(), cur * cur); + if(iter == v.end() || *iter != cur * cur) break; + + len ++; + cur = cur * cur; + cur_index = iter - v.begin(); + } + res = max(res, len); + + start = i; + } + } + return res >= 2 ? res : -1; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2502-Design-Memory-Allocator/cpp-2502/CMakeLists.txt b/2501-3000/2502-Design-Memory-Allocator/cpp-2502/CMakeLists.txt new file mode 100644 index 00000000..e3dedae7 --- /dev/null +++ b/2501-3000/2502-Design-Memory-Allocator/cpp-2502/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(C) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(C main2.cpp) diff --git a/2501-3000/2502-Design-Memory-Allocator/cpp-2502/main.cpp b/2501-3000/2502-Design-Memory-Allocator/cpp-2502/main.cpp new file mode 100644 index 00000000..6dc76321 --- /dev/null +++ b/2501-3000/2502-Design-Memory-Allocator/cpp-2502/main.cpp @@ -0,0 +1,89 @@ +/// Source : https://leetcode.com/problems/design-memory-allocator/description/ +/// Author : liuyubobobo +/// Time : 2022-12-10 + +#include +#include +#include + +using namespace std; + + +/// Using TreeSet +/// Time Complexity: init: O(1) +/// allocate: O(n) +/// free: O(n) +/// Space Complexity: O(n) +class Allocator { + +private: + set> mem; + vector>> id2mem; + +public: + Allocator(int n) : id2mem(1001){ + mem.insert({0, n - 1}); + } + + int allocate(int size, int mID) { + + pair target = {-1, -1}; + for(const pair& block: mem){ + int l = block.first, r = block.second, len = r - l + 1; + if(len >= size){ + target = block; + break; + } + } + + if(target.first == -1) return -1; + + id2mem[mID].push_back({target.first, target.first + size - 1}); + mem.erase(target); + if(target.first + size <= target.second) + mem.insert({target.first + size, target.second}); + return target.first; + } + + int free(int mID) { + + int ret = 0; + for(const pair& p: id2mem[mID]) { + pair target = p; + ret += target.second - target.first + 1; + + auto iter = mem.upper_bound(target); + if (iter != mem.end() && iter->first == target.second + 1) { + target.second = iter->second; + mem.erase(iter); + } + + iter = mem.upper_bound(target); + if (iter != mem.begin()) { + iter--; + if (iter->second + 1 == target.first) { + target.first = iter->first; + mem.erase(iter); + } + } + + mem.insert(target); + } + id2mem[mID].clear(); + return ret; + } +}; + + +int main() { + + Allocator allocator(10); + cout << allocator.allocate(1, 1) << '\n'; // 0 + cout << allocator.allocate(1, 2) << '\n'; // 1 + cout << allocator.allocate(1, 3) << '\n'; // 2 + cout << allocator.free(2) << '\n'; // 1 + cout << allocator.allocate(3, 4) << '\n'; // 3 + cout << allocator.allocate(1, 3) << '\n'; // 2 + + return 0; +} diff --git a/2501-3000/2502-Design-Memory-Allocator/cpp-2502/main2.cpp b/2501-3000/2502-Design-Memory-Allocator/cpp-2502/main2.cpp new file mode 100644 index 00000000..5c8f8fe6 --- /dev/null +++ b/2501-3000/2502-Design-Memory-Allocator/cpp-2502/main2.cpp @@ -0,0 +1,104 @@ +/// Source : https://leetcode.com/problems/design-memory-allocator/description/ +/// Author : liuyubobobo +/// Time : 2022-12-15 + +#include +#include +#include + +using namespace std; + + +/// Using LinkedList +/// Time Complexity: init: O(1) +/// allocate: O(n) +/// free: O(n) +/// Space Complexity: O(n) +class Allocator { + +private: + list> available; // start, end + vector>> id2mem; + +public: + Allocator(int n) : id2mem(1001){ + available.push_back({0, n - 1}); + } + + int allocate(int size, int mID) { + + list>::iterator alloc_iter = available.end(); + for(auto iter = available.begin(); iter != available.end(); iter ++){ + int l = iter->first, r = iter->second, len = r - l + 1; + if(len >= size){ + alloc_iter = iter; + break; + } + } + + if(alloc_iter == available.end()) return -1; + + add(id2mem[mID], {alloc_iter->first, alloc_iter->first + size - 1}); + int ret = alloc_iter->first; + alloc_iter->first += size; + if(alloc_iter->first > alloc_iter->second) available.erase(alloc_iter); + return ret; + } + + int free(int mID) { + + int ret = 0; + for(const pair& p: id2mem[mID]) { + ret += p.second - p.first + 1; + add(available, p); + } + id2mem[mID].clear(); + return ret; + } + +private: + void add(list>& l, const pair& p){ + + auto insert_pos_iter = l.end(); + for(auto iter = l.begin(); iter != l.end(); iter ++){ + if(iter->second + 1 == p.first){ + iter->second = p.second; + insert_pos_iter = iter; + break; + } + else if(iter->first > p.second){ + insert_pos_iter = iter; +// insert_pos_iter --; + insert_pos_iter = l.insert(insert_pos_iter, p); + break; + } + } + + if(insert_pos_iter == l.end()){ + l.push_back(p); + return; + } + + auto next_iter = insert_pos_iter; + next_iter ++; + if(next_iter == l.end() || next_iter->first != insert_pos_iter->second + 1) return; + + insert_pos_iter->second = next_iter->second; + l.erase(next_iter); + return; + } +}; + + +int main() { + + Allocator allocator(10); + cout << allocator.allocate(1, 1) << '\n'; // 0 + cout << allocator.allocate(1, 2) << '\n'; // 1 + cout << allocator.allocate(1, 3) << '\n'; // 2 + cout << allocator.free(2) << '\n'; // 1 + cout << allocator.allocate(3, 4) << '\n'; // 3 + cout << allocator.allocate(1, 3) << '\n'; // 1 + + return 0; +} diff --git a/2501-3000/2503-Maximum-Number-of-Points-From-Grid-Queries/cpp-2503/CMakeLists.txt b/2501-3000/2503-Maximum-Number-of-Points-From-Grid-Queries/cpp-2503/CMakeLists.txt new file mode 100644 index 00000000..d2d08329 --- /dev/null +++ b/2501-3000/2503-Maximum-Number-of-Points-From-Grid-Queries/cpp-2503/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(D) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(D main.cpp) diff --git a/2501-3000/2503-Maximum-Number-of-Points-From-Grid-Queries/cpp-2503/main.cpp b/2501-3000/2503-Maximum-Number-of-Points-From-Grid-Queries/cpp-2503/main.cpp new file mode 100644 index 00000000..d2750c0a --- /dev/null +++ b/2501-3000/2503-Maximum-Number-of-Points-From-Grid-Queries/cpp-2503/main.cpp @@ -0,0 +1,106 @@ +/// Source : https://leetcode.com/problems/maximum-number-of-points-from-grid-queries/ +/// Author : liuyubobobo +/// Time : 2022-12-15 + +#include +#include +#include +#include + +using namespace std; + + +/// Offline query, using UF +/// Time Complexity: O(nlogn + qlogq + q) +/// Space Complexity: O(n) +class UF{ + +private: + vector parent, sz; + +public: + UF(int n) : parent(n), sz(n, 1){ + for(int i = 0 ; i < n ; i ++) + parent[i] = i; + } + + int find(int p){ + if(p != parent[p]) + parent[p] = find(parent[p]); + return parent[p]; + } + + bool is_connected(int p , int q){ + return find(p) == find(q); + } + + void union_elements(int p, int q){ + + int p_root = find(p), q_root = find(q); + + if(p_root == q_root) return; + + parent[p_root] = q_root; + sz[q_root] += sz[p_root]; + } + + int size(int p){ + return sz[find(p)]; + } +}; + +class Solution { + +private: + const int dirs[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; + int R, C; + +public: + vector maxPoints(vector>& grid, vector& q) { + + R = grid.size(), C = grid[0].size(); + int n = R * C; + vector> v(R * C); + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++){ + int index = i * C + j; + v[index] = {grid[i][j], index}; + } + sort(v.begin(), v.end()); + + vector> queries(q.size()); + for(int i = 0; i < q.size(); i ++) queries[i] = {q[i], i}; + sort(queries.begin(), queries.end()); + + vector res(q.size()); + + UF uf(n); + int i = 0; + for(const pair& p: queries){ + int t = p.first, q_index = p.second; + while(i < n && v[i].first < t){ + int cx = v[i].second / C, cy = v[i].second % C; + for(int d = 0; d < 4; d ++){ + int nx = cx + dirs[d][0], ny = cy + dirs[d][1]; + if(in_area(nx, ny) && grid[nx][ny] < t){ + uf.union_elements(v[i].second, nx * C + ny); + } + } + i ++; + } + res[q_index] = grid[0][0] < t ? uf.size(0) : 0; + } + return res; + } + +private: + bool in_area(int x, int y){ + return 0 <= x && x < R && 0 <= y && y < C; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2505-Bitwise-OR-of-All-Subsequence-Sums/cpp-2505/CMakeLists.txt b/2501-3000/2505-Bitwise-OR-of-All-Subsequence-Sums/cpp-2505/CMakeLists.txt new file mode 100644 index 00000000..e671836c --- /dev/null +++ b/2501-3000/2505-Bitwise-OR-of-All-Subsequence-Sums/cpp-2505/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2505) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2505 main.cpp) diff --git a/2501-3000/2505-Bitwise-OR-of-All-Subsequence-Sums/cpp-2505/main.cpp b/2501-3000/2505-Bitwise-OR-of-All-Subsequence-Sums/cpp-2505/main.cpp new file mode 100644 index 00000000..b643a94f --- /dev/null +++ b/2501-3000/2505-Bitwise-OR-of-All-Subsequence-Sums/cpp-2505/main.cpp @@ -0,0 +1,38 @@ +/// Source : https://leetcode.com/problems/bitwise-or-of-all-subsequence-sums/description/ +/// Author : liuyubobobo +/// Time : 2022-12-15 + +#include +#include + +using namespace std; + + +/// Bitwise +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + long long subsequenceSumOr(vector& nums) { + + long long res = 0; + + int cnt = 0; + for(int p = 0; p < 62; p ++){ + cnt /= 2; + if(p <= 31) + for(int num: nums) cnt += ((num >> p) & 1); + if(cnt) res += (1ll << p); + } + + cnt /= 2; + if(cnt) res += (1ll << 62); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2506-Count-Pairs-Of-Similar-Strings/cpp-2506/CMakeLists.txt b/2501-3000/2506-Count-Pairs-Of-Similar-Strings/cpp-2506/CMakeLists.txt new file mode 100644 index 00000000..41b4f523 --- /dev/null +++ b/2501-3000/2506-Count-Pairs-Of-Similar-Strings/cpp-2506/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2506) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2506 main.cpp) diff --git a/2501-3000/2506-Count-Pairs-Of-Similar-Strings/cpp-2506/main.cpp b/2501-3000/2506-Count-Pairs-Of-Similar-Strings/cpp-2506/main.cpp new file mode 100644 index 00000000..fcd3ace8 --- /dev/null +++ b/2501-3000/2506-Count-Pairs-Of-Similar-Strings/cpp-2506/main.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/count-pairs-of-similar-strings/description/ +/// Author : liuyubobobo +/// Time : 2022-12-18 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { +public: + int similarPairs(vector& words) { + + int n = words.size(); + vector> f(n, vector(26, false)); + for(int i = 0; i < n; i ++){ + const string& word = words[i]; + for(char c: word) f[i][c - 'a'] = true; + } + + int res = 0; + for(int i = 0; i < n; i ++) + for(int j = i + 1; j < n; j ++) + res += f[i] == f[j]; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2507-Smallest-Value-After-Replacing-With-Sum-of-Prime-Factors/cpp-2507/CMakeLists.txt b/2501-3000/2507-Smallest-Value-After-Replacing-With-Sum-of-Prime-Factors/cpp-2507/CMakeLists.txt new file mode 100644 index 00000000..aec8d639 --- /dev/null +++ b/2501-3000/2507-Smallest-Value-After-Replacing-With-Sum-of-Prime-Factors/cpp-2507/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2507) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2507 main.cpp) diff --git a/2501-3000/2507-Smallest-Value-After-Replacing-With-Sum-of-Prime-Factors/cpp-2507/main.cpp b/2501-3000/2507-Smallest-Value-After-Replacing-With-Sum-of-Prime-Factors/cpp-2507/main.cpp new file mode 100644 index 00000000..ff82cbf0 --- /dev/null +++ b/2501-3000/2507-Smallest-Value-After-Replacing-With-Sum-of-Prime-Factors/cpp-2507/main.cpp @@ -0,0 +1,69 @@ +/// Source : https://leetcode.com/problems/smallest-value-after-replacing-with-sum-of-prime-factors/description/ +/// Author : liuyubobobo +/// Time : 2022-12-18 + +#include +#include + +using namespace std; + + +/// Sieve + Simulation +/// Time Complexity: O(MAXN * logMAXN) +/// Space Compelxity: O(MAXN) +class Solution { + +private: + const int MAXN = 1e5; + +public: + int smallestValue(int n) { + + vector sieve_table = sieve(MAXN); + vector visited(MAXN + 1, false); + while(!visited[n]){ + visited[n] = true; + n = calc(n, sieve_table); + } + + for(int i = 0; i <= MAXN; i ++) + if(visited[i]) return i; + return -1; + } + +private: + int calc(int x, const vector& sieve_table){ + + int res = 0; + while(x != 1){ + int p = sieve_table[x]; + res += p; + x /= p; + } + return res; + } + + vector sieve(int n){ + + vector table(n + 1, 0); + vector primes; + table[0] = table[1] = 1; + for(int i = 2; i <= n; i ++){ + if(table[i] == 0) { + primes.push_back(i); + table[i] = i; + } + for(int j = 0; j < primes.size() && primes[j] <= table[i] && i * primes[j] <= n; j ++) + table[i * primes[j]] = primes[j]; + } + return table; + } +}; + + +int main() { + + cout << Solution().smallestValue(64) << '\n'; + + return 0; +} diff --git a/2501-3000/2508-Add-Edges-to-Make-Degrees-of-All-Nodes-Even/cpp-2508/CMakeLists.txt b/2501-3000/2508-Add-Edges-to-Make-Degrees-of-All-Nodes-Even/cpp-2508/CMakeLists.txt new file mode 100644 index 00000000..452024e8 --- /dev/null +++ b/2501-3000/2508-Add-Edges-to-Make-Degrees-of-All-Nodes-Even/cpp-2508/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2508) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2508 main.cpp) diff --git a/2501-3000/2508-Add-Edges-to-Make-Degrees-of-All-Nodes-Even/cpp-2508/main.cpp b/2501-3000/2508-Add-Edges-to-Make-Degrees-of-All-Nodes-Even/cpp-2508/main.cpp new file mode 100644 index 00000000..704b72a1 --- /dev/null +++ b/2501-3000/2508-Add-Edges-to-Make-Degrees-of-All-Nodes-Even/cpp-2508/main.cpp @@ -0,0 +1,126 @@ +/// Source : https://leetcode.com/problems/add-edges-to-make-degrees-of-all-nodes-even/ +/// Author : liuyubobobo +/// Time : 2022-12-18 + +#include +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(V + E) +/// Space Complexity: O(V + E) +class Solution { +public: + bool isPossible(int n, vector>& edges) { + + vector> g(n); + for(const vector& e: edges){ + int u = e[0] - 1, v = e[1] - 1; + g[u].insert(v), g[v].insert(u); + } + + int is_full = 0; + vector oddv; + for(int i = 0; i < n; i ++){ + if(g[i].size() == n - 1) is_full ++; + else if(g[i].size() % 2 == 1) oddv.push_back(i); + } + +// cout << "is_full : " << is_full << '\n'; +// for(int e: oddv) cout << e << ' '; cout << '\n'; +// cout << g[1].count(2) << ' ' << g[2].count(1) << '\n'; + if(is_full && (n - 1) % 2) return false; + + if(oddv.empty()) return true; + if(oddv.size() == 2) { + if(ok_to_connect(g, oddv[0], oddv[1])) return true; + for(int i = 0; i < n; i ++) + if(g[i].size() + 2 <= n - 1 && ok_to_connect(g, i, oddv[0]) && ok_to_connect(g, i, oddv[1])) + return true; + return false; + } + + if(oddv.size() != 4) return false; + + do{ + if(ok_to_connect(g, oddv[0], oddv[1]) && ok_to_connect(g, oddv[2], oddv[3])) + return true; + }while(next_permutation(oddv.begin(), oddv.end())); + return false; + } + +private: + static bool ok_to_connect(const vector>& g, int u, int v){ + return g[u].count(v) == 0 && g[v].count(u) == 0; + } +}; + + +int main() { + + vector> edges1 = {{1, 2}, {3, 4}}; + cout << Solution().isPossible(4, edges1) << '\n'; + // 1 + + vector> edges2 = { + {5, 9}, + {8, 1}, + {2, 3}, + {7, 10}, + {3, 6}, + {6, 7}, + {7, 8}, + {5, 1}, + {5, 7}, + {10, 11}, + {3, 7}, + {6, 11}, + {8, 11}, + {3, 4}, + {8, 9}, + {9, 1}, + {2, 10}, + {9, 11}, + {5, 11}, + {2, 5}, + {8, 10}, + {2, 7}, + {4, 1}, + {3, 10}, + {6, 1}, + {4, 9}, + {4, 6}, + {4, 5}, + {2, 4}, + {2, 11}, + {5, 8}, + {6, 9}, + {4, 10}, + {3, 11}, + {4, 7}, + {3, 5}, + {7, 1}, + {2, 9}, + {6, 10}, + {10, 1}, + {5, 6}, + {3, 9}, + {2, 6}, + {7, 9}, + {4, 11}, + {4, 8}, + {6, 8}, + {3, 8}, + {9, 10}, + {5, 10}, + {2, 8}, + {7, 11} + }; + cout << Solution().isPossible(11, edges2) << '\n'; + // 0 + + return 0; +} diff --git a/2501-3000/2509-Cycle-Length-Queries-in-a-Tree/cpp-2509/CMakeLists.txt b/2501-3000/2509-Cycle-Length-Queries-in-a-Tree/cpp-2509/CMakeLists.txt new file mode 100644 index 00000000..1afa23dd --- /dev/null +++ b/2501-3000/2509-Cycle-Length-Queries-in-a-Tree/cpp-2509/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2509) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2509 main.cpp) diff --git a/2501-3000/2509-Cycle-Length-Queries-in-a-Tree/cpp-2509/main.cpp b/2501-3000/2509-Cycle-Length-Queries-in-a-Tree/cpp-2509/main.cpp new file mode 100644 index 00000000..92405cab --- /dev/null +++ b/2501-3000/2509-Cycle-Length-Queries-in-a-Tree/cpp-2509/main.cpp @@ -0,0 +1,59 @@ +/// Source : https://leetcode.com/problems/cycle-length-queries-in-a-tree/ +/// Author : liuyubobobo +/// Time : 2022-12-18 + +#include +#include +#include + +using namespace std; + + +/// Math +/// Time Complexity: O(qlogn) +/// Space Complexity: O(logn) +class Solution { +public: + vector cycleLengthQueries(int n, vector>& queries) { + + int m = queries.size(); + + vector res(m); + for(int qindex = 0; qindex < m; qindex ++){ + int u = queries[qindex][0], v = queries[qindex][1]; + + vector upath, vpath; + while(u) upath.push_back(u), u /= 2; + while(v) vpath.push_back(v), v /= 2; + + reverse(upath.begin(), upath.end()); + reverse(vpath.begin(), vpath.end()); + + int lca_pos = -1; + for(int i = 0; i < upath.size() && i < vpath.size(); i ++) + if(upath[i] != vpath[i]){ + lca_pos = i; break; + } + + if(lca_pos == -1) lca_pos = min(upath.size(), vpath.size()); + int tres = 0; + tres += (int)upath.size() - lca_pos; + tres += (int)vpath.size() - lca_pos; + tres ++; + res[qindex] = tres; + } + return res; + } +}; + + +int main() { + + vector> queries1 = {{5, 3}, {4, 7}, {2, 3}}; + Solution().cycleLengthQueries(3, queries1); + + vector> queries2 = {{1, 2}}; + Solution().cycleLengthQueries(2, queries2); + + return 0; +} diff --git a/2501-3000/2510-Check-if-There-is-a-Path-With-Equal-Number-of-0s-And-1s/cpp-2510/CMakeLists.txt b/2501-3000/2510-Check-if-There-is-a-Path-With-Equal-Number-of-0s-And-1s/cpp-2510/CMakeLists.txt new file mode 100644 index 00000000..b317dc14 --- /dev/null +++ b/2501-3000/2510-Check-if-There-is-a-Path-With-Equal-Number-of-0s-And-1s/cpp-2510/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2510) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2510 main.cpp) diff --git a/2501-3000/2510-Check-if-There-is-a-Path-With-Equal-Number-of-0s-And-1s/cpp-2510/main.cpp b/2501-3000/2510-Check-if-There-is-a-Path-With-Equal-Number-of-0s-And-1s/cpp-2510/main.cpp new file mode 100644 index 00000000..e29004b1 --- /dev/null +++ b/2501-3000/2510-Check-if-There-is-a-Path-With-Equal-Number-of-0s-And-1s/cpp-2510/main.cpp @@ -0,0 +1,44 @@ +/// Source : https://leetcode.com/problems/check-if-there-is-a-path-with-equal-number-of-0s-and-1s/description/ +/// Author : liuyubobobo +/// Time : 2022-12-22 + +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(n * m * (n + m)) +/// Space Complexity: O(n * m * (n + m)) +class Solution { +public: + bool isThereAPath(vector>& grid) { + + int n = grid.size(), m = grid[0].size(); + + if((n + m - 1) & 1) return false; + + const int OFFSET = n + m - 1; + vector>> dp(n, vector>(m, vector(2 * OFFSET + 1, false))); + + // zero - one + dp[0][0][(grid[0][0] == 0 ? 1 : -1) + OFFSET] = true; + for(int i = 0; i < n; i ++) + for(int j = 0; j < m; j ++) + for(int value = -OFFSET; value <= OFFSET; value ++){ + if(!dp[i][j][ value + OFFSET]) continue; + if(i + 1 < n && value + (grid[i + 1][j] ? -1 : 1) <= OFFSET) + dp[i + 1][j][value + (grid[i + 1][j] ? -1 : 1) + OFFSET] = true; + if(j + 1 < m && value + (grid[i][j + 1] ? -1 : 1) <= OFFSET) + dp[i][j + 1][value + (grid[i][j + 1] ? -1 : 1) + OFFSET] = true; + } + return dp[n - 1][m - 1][OFFSET]; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2511-Maximum-Enemy-Forts-That-Can-Be-Captured/cpp-2511/CMakeLists.txt b/2501-3000/2511-Maximum-Enemy-Forts-That-Can-Be-Captured/cpp-2511/CMakeLists.txt new file mode 100644 index 00000000..7d43c2ef --- /dev/null +++ b/2501-3000/2511-Maximum-Enemy-Forts-That-Can-Be-Captured/cpp-2511/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2511) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2511 main.cpp) diff --git a/2501-3000/2511-Maximum-Enemy-Forts-That-Can-Be-Captured/cpp-2511/main.cpp b/2501-3000/2511-Maximum-Enemy-Forts-That-Can-Be-Captured/cpp-2511/main.cpp new file mode 100644 index 00000000..9c305c66 --- /dev/null +++ b/2501-3000/2511-Maximum-Enemy-Forts-That-Can-Be-Captured/cpp-2511/main.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/maximum-enemy-forts-that-can-be-captured/description/ +/// Author : liuyubobobo +/// Time : 2022-12-28 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { +public: + int captureForts(vector& forts) { + + int n = forts.size(), res = 0; + for(int i = 0; i < n; i ++){ + if(forts[i] != 1) continue; + + int j; + for(j = i - 1; j >= 0 && forts[j] == 0; j --); + if(j >= 0 && forts[j] == -1) res = max(res, i - j - 1); + + for(j = i + 1; j < n && forts[j] == 0; j ++); + if(j < n && forts[j] == -1) res = max(res, j - i - 1); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2512-Reward-Top-K-Students/cpp-2512/CMakeLists.txt b/2501-3000/2512-Reward-Top-K-Students/cpp-2512/CMakeLists.txt new file mode 100644 index 00000000..615ae582 --- /dev/null +++ b/2501-3000/2512-Reward-Top-K-Students/cpp-2512/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2512) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2512 main.cpp) diff --git a/2501-3000/2512-Reward-Top-K-Students/cpp-2512/main.cpp b/2501-3000/2512-Reward-Top-K-Students/cpp-2512/main.cpp new file mode 100644 index 00000000..d8d68ad0 --- /dev/null +++ b/2501-3000/2512-Reward-Top-K-Students/cpp-2512/main.cpp @@ -0,0 +1,60 @@ +/// Source : https://leetcode.com/problems/reward-top-k-students/description/ +/// Author : liuyubobobo +/// Time : 2022-10-28 + +#include +#include +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(nlogn) +/// Space Complexity: O(|pset| + |nset| + n) +class Solution { +public: + vector topStudents(vector& positive_feedback, vector& negative_feedback, vector& report, vector& student_id, int k) { + + set pset(positive_feedback.begin(), positive_feedback.end()); + set nset(negative_feedback.begin(), negative_feedback.end()); + + int n = report.size(); + vector> v(n); // score, id; + for(int i = 0; i < n; i ++) + v[i] = {get_score(report[i], pset, nset), student_id[i]}; + + sort(v.begin(), v.end(), [](const pair& p1, const pair& p2){ + if(p1.first != p2.first) return p1.first > p2.first; + return p1.second < p2.second; + }); + + vector res(k); + for(int i = 0; i < k; i ++) res[i] = v[i].second; + return res; + } + +private: + int get_score(const string& s, const set& pset, const set& nset){ + + int res = 0, n = s.size(); + for(int start = 0, i = 1; i <= n; i ++){ + if(i == n || s[i] == ' '){ + string word = s.substr(start, i - start); + if(pset.count(word)) res += 3; + if(nset.count(word)) res -= 1; + + start = i + 1; + i = start; + } + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2513-Minimize-the-Maximum-of-Two-Arrays/cpp-2513/CMakeLists.txt b/2501-3000/2513-Minimize-the-Maximum-of-Two-Arrays/cpp-2513/CMakeLists.txt new file mode 100644 index 00000000..1d5ee00d --- /dev/null +++ b/2501-3000/2513-Minimize-the-Maximum-of-Two-Arrays/cpp-2513/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2513) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2513 main.cpp) diff --git a/2501-3000/2513-Minimize-the-Maximum-of-Two-Arrays/cpp-2513/main.cpp b/2501-3000/2513-Minimize-the-Maximum-of-Two-Arrays/cpp-2513/main.cpp new file mode 100644 index 00000000..8b9fb370 --- /dev/null +++ b/2501-3000/2513-Minimize-the-Maximum-of-Two-Arrays/cpp-2513/main.cpp @@ -0,0 +1,59 @@ +/// Source : https://leetcode.com/problems/minimize-the-maximum-of-two-arrays/description/ +/// Author : liuyubobobo +/// Time : 2022-12-28 + +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(log(MAX_LONG_LONG)) +/// Space Complexity: O(1) +class Solution { +public: + int minimizeSet(int divisor1, int divisor2, int uniqueCnt1, int uniqueCnt2) { + + long long l = 1, r = 1000000000000000000ll; + while(l < r){ + long long mid = (l + r) / 2; + if(ok(mid, divisor1, divisor2, uniqueCnt1, uniqueCnt2)) r = mid; + else l = mid + 1; + } + return l; + } + +private: + bool ok(long long n, long long d1, long long d2, long long n1, long long n2){ + + long long only1 = n / d1; + long long only2 = n / d2; + long long both12 = n / ((d1 * d2) / gcd(min(d1, d2), max(d1, d2))); + + long long left = n - only1 - only2 + both12; + only1 -= both12, only2 -= both12; + + long long cnt1 = 0, cnt2 = 0; + cnt1 += only2; + if(cnt1 < n1) left -= (n1 - cnt1); + + if(left < 0) return false; + + cnt2 += only1 + left; + return cnt2 >= n2; + } + + long long gcd(long long a, long long b){ + if (a == 0) return b; + return gcd(b % a, a); + } +}; + + +int main() { + + cout << Solution().minimizeSet(2, 4, 8, 2) << '\n'; + + return 0; +} diff --git a/2501-3000/2514-Count-Anagrams/cpp-2514/CMakeLists.txt b/2501-3000/2514-Count-Anagrams/cpp-2514/CMakeLists.txt new file mode 100644 index 00000000..0bcd1108 --- /dev/null +++ b/2501-3000/2514-Count-Anagrams/cpp-2514/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2514) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2514 main.cpp) diff --git a/2501-3000/2514-Count-Anagrams/cpp-2514/main.cpp b/2501-3000/2514-Count-Anagrams/cpp-2514/main.cpp new file mode 100644 index 00000000..10955d46 --- /dev/null +++ b/2501-3000/2514-Count-Anagrams/cpp-2514/main.cpp @@ -0,0 +1,75 @@ +/// Source : https://leetcode.com/problems/count-anagrams/ +/// Author : liuyubobobo +/// Time : 2022-12-28 + +#include +#include + +using namespace std; + + +/// Math +/// Time Complexity: O(n) +/// Space Compelxity: O(n) +class Solution { + +private: + long long MOD = 1e9 + 7; + +public: + int countAnagrams(string s) { + + int n = s.size(); + vector fac(n + 1, 1); + for(int i = 2; i <= n; i ++) fac[i] = fac[i - 1] * i % MOD; + + vector ifac(n + 1); + for(int i = 0; i <= n; i ++) ifac[i] = quick_pow(fac[i], MOD - 2); + + long long res = 1; + for(int start = 0, i = 1; i <= n; i ++){ + if(i == n || s[i] == ' '){ + string word = s.substr(start, i - start); + res *= get_cnt(word, fac, ifac); + res %= MOD; + + start = i + 1; + i = start; + } + } + return res; + } + +private: + long long get_cnt(const string& word, + const vector& fac, const vector& ifac){ + + vector f(26, 0); + for(char c: word) f[c - 'a'] ++; + + int n = word.size(); + long long res = fac[n]; + for(int i = 0; i < 26; i ++) + res = res * ifac[f[i]] % MOD; + return res; + } + + long long quick_pow(long long a, long long k) { + long long res = 1ll; + while (k) { + if (k & 1) res = res * a % MOD; + a = a * a % MOD; + k >>= 1; + } + return res % MOD; + } +}; + + +int main() { + + string s1 = "aa"; + cout << Solution().countAnagrams(s1) << '\n'; + + return 0; +} diff --git a/2501-3000/2515-Shortest-Distance-to-Target-String-in-a-Circular-Array/cpp-2515/CMakeLists.txt b/2501-3000/2515-Shortest-Distance-to-Target-String-in-a-Circular-Array/cpp-2515/CMakeLists.txt new file mode 100644 index 00000000..4263d09b --- /dev/null +++ b/2501-3000/2515-Shortest-Distance-to-Target-String-in-a-Circular-Array/cpp-2515/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2515) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2515 main.cpp) diff --git a/2501-3000/2515-Shortest-Distance-to-Target-String-in-a-Circular-Array/cpp-2515/main.cpp b/2501-3000/2515-Shortest-Distance-to-Target-String-in-a-Circular-Array/cpp-2515/main.cpp new file mode 100644 index 00000000..3dfcced9 --- /dev/null +++ b/2501-3000/2515-Shortest-Distance-to-Target-String-in-a-Circular-Array/cpp-2515/main.cpp @@ -0,0 +1,43 @@ +/// Source : https://leetcode.com/problems/shortest-distance-to-target-string-in-a-circular-array/description/ +/// Author : liuyubobobo +/// Time : 2022-12-26 + +#include +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int closetTarget(vector& words, string target, int startIndex) { + + auto iter = find(words.begin(), words.end(), target); + if(iter == words.end()) return -1; + + vector v; + while(iter != words.end()) { + int targetIndex = iter - words.begin(); + v.push_back(targetIndex); + iter = find(words.begin() + targetIndex + 1, words.end(), target); + } + + int n = words.size(), res = INT_MAX; + for(int targetIndex: v){ + int a = (targetIndex - startIndex + n) % n; + int b = (startIndex - targetIndex + n) % n; + res = min(res, min(a, b)); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2516-Take-K-of-Each-Character-From-Left-and-Right/cpp-2516/CMakeLists.txt b/2501-3000/2516-Take-K-of-Each-Character-From-Left-and-Right/cpp-2516/CMakeLists.txt new file mode 100644 index 00000000..a00c5b49 --- /dev/null +++ b/2501-3000/2516-Take-K-of-Each-Character-From-Left-and-Right/cpp-2516/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2516) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2516 main.cpp) diff --git a/2501-3000/2516-Take-K-of-Each-Character-From-Left-and-Right/cpp-2516/main.cpp b/2501-3000/2516-Take-K-of-Each-Character-From-Left-and-Right/cpp-2516/main.cpp new file mode 100644 index 00000000..ae976a9f --- /dev/null +++ b/2501-3000/2516-Take-K-of-Each-Character-From-Left-and-Right/cpp-2516/main.cpp @@ -0,0 +1,64 @@ +/// Source : https://leetcode.com/problems/take-k-of-each-character-from-left-and-right/ +/// Author : liuyubobobo +/// Time : 2022-12-26 + +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { + +public: + int takeCharacters(string s, int k) { + + int n = s.size(); + + vector prea(n + 1, 0), preb(n + 1, 0), prec(n + 1, 0); + for(int i = 0; i < n; i ++){ + prea[i + 1] = prea[i] + (s[i] == 'a'); + preb[i + 1] = preb[i] + (s[i] == 'b'); + prec[i + 1] = prec[i] + (s[i] == 'c'); + } + + if(prea.back() < k || preb.back() < k || prec.back() < k) return -1; + + int res = max3(get(prea, k), get(preb, k), get(prec, k)); + + int a = 0, b = 0, c = 0; + for(int i = n - 1; i >= 0; i --){ + a += s[i] == 'a'; + b += s[i] == 'b'; + c += s[i] == 'c'; + + int t = max3(get(prea, max(k - a, 0)), get(preb, max(k - b, 0)), get(prec, max(k - c, 0))); + res = min(res, t + n - i); + } + return res; + } + +private: + int max3(int a, int b, int c){ + return max(a, max(b, c)); + } + + int get(const vector& v, int k){ + auto iter = lower_bound(v.begin(), v.end(), k); + assert(iter != v.end()); + return iter - v.begin(); + } +}; + + +int main() { + + string s = "aabaaaacaabc"; + cout << Solution().takeCharacters(s, 2) << '\n'; + // 8 + + return 0; +} diff --git a/2501-3000/2517-Maximum-Tastiness-of-Candy-Basket/cpp-2517/CMakeLists.txt b/2501-3000/2517-Maximum-Tastiness-of-Candy-Basket/cpp-2517/CMakeLists.txt new file mode 100644 index 00000000..d2460ca5 --- /dev/null +++ b/2501-3000/2517-Maximum-Tastiness-of-Candy-Basket/cpp-2517/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2517) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2517 main.cpp) diff --git a/2501-3000/2517-Maximum-Tastiness-of-Candy-Basket/cpp-2517/main.cpp b/2501-3000/2517-Maximum-Tastiness-of-Candy-Basket/cpp-2517/main.cpp new file mode 100644 index 00000000..7ac1220d --- /dev/null +++ b/2501-3000/2517-Maximum-Tastiness-of-Candy-Basket/cpp-2517/main.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/maximum-tastiness-of-candy-basket/description/ +/// Author : liuyubobobo +/// Time : 2022-12-26 + +#include +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(nlogn + nlong(max_price - min_price)) +/// Space Complexity: O(1) +class Solution { +public: + int maximumTastiness(vector& price, int k) { + + sort(price.begin(), price.end()); + + int n = price.size(); + int l = 0, r = price.back() - price[0]; + while(l < r){ + int mid = (l + r + 1) / 2; + if(ok(price, mid, k)) l = mid; + else r = mid - 1; + } + return l; + } + +private: + bool ok(const vector& v, int t, int k){ + + int cnt = 1, cur = v[0]; + while(cnt < k){ + cur += t; + auto iter = lower_bound(v.begin(), v.end(), cur); + if(iter == v.end()) return false; + cur = *iter; + cnt ++; + } + return true; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2518-Number-of-Great-Partitions/cpp-2518/CMakeLists.txt b/2501-3000/2518-Number-of-Great-Partitions/cpp-2518/CMakeLists.txt new file mode 100644 index 00000000..2ab5083e --- /dev/null +++ b/2501-3000/2518-Number-of-Great-Partitions/cpp-2518/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2518) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2518 main.cpp) diff --git a/2501-3000/2518-Number-of-Great-Partitions/cpp-2518/main.cpp b/2501-3000/2518-Number-of-Great-Partitions/cpp-2518/main.cpp new file mode 100644 index 00000000..09a2f984 --- /dev/null +++ b/2501-3000/2518-Number-of-Great-Partitions/cpp-2518/main.cpp @@ -0,0 +1,74 @@ +/// Source : https://leetcode.com/problems/number-of-great-partitions/description/ +/// Author : liuyubobobo +/// Time : 2022-12-28 + +#include +#include + +using namespace std; + + +/// Knapback +/// Time Complexity: O(nk) +/// Space Complexity: O(nk) +class Solution { + +private: + long long MOD = 1e9 + 7; + +public: + int countPartitions(vector& nums, int k) { + + int n = nums.size(); + vector> dp(n + 1, vector(k, 0)); + + dp[0][0] = 1; + for(int i = 0; i < n; i ++){ + for(int C = 0; C < k; C ++){ + dp[i + 1][C] = dp[i][C]; + if(C - nums[i] >= 0) + dp[i + 1][C] += dp[i][C - nums[i]], + dp[i + 1][C] %= MOD; + } + } + + long long sum = 0; + for(int e: nums) sum += e; + + long long t = 0; + for(int C = 0; C < k; C ++){ + t += dp[n][C]; + if(sum - C >= k) t += dp[n][C]; + t %= MOD; + } +// cout << t << '\n'; + + long long res = 1; + for(int i = 0; i < n; i ++) res = res * 2 % MOD; + + res = (res - t + MOD) % MOD; + return res; + } +}; + + +int main() { + + vector nums1 = {1, 2, 3, 4}; + cout << Solution().countPartitions(nums1, 4) << '\n'; + // 6 + + vector nums2 = {3, 3, 3}; + cout << Solution().countPartitions(nums2, 4) << '\n'; + // 0 + + vector nums3 = {6, 6}; + cout << Solution().countPartitions(nums3, 2) << '\n'; + // 2 + + vector nums4 = {96,40,22,98,9,97,45,22,79,57,95,62}; + cout << Solution().countPartitions(nums4, 505) << '\n'; + // 0 + + return 0; +} diff --git a/2501-3000/2519-Count-the-Number-of-K-Big-Indices/cpp-2519/CMakeLists.txt b/2501-3000/2519-Count-the-Number-of-K-Big-Indices/cpp-2519/CMakeLists.txt new file mode 100644 index 00000000..bd78dc34 --- /dev/null +++ b/2501-3000/2519-Count-the-Number-of-K-Big-Indices/cpp-2519/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2519) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2519 main.cpp) diff --git a/2501-3000/2519-Count-the-Number-of-K-Big-Indices/cpp-2519/main.cpp b/2501-3000/2519-Count-the-Number-of-K-Big-Indices/cpp-2519/main.cpp new file mode 100644 index 00000000..e8fbdfd2 --- /dev/null +++ b/2501-3000/2519-Count-the-Number-of-K-Big-Indices/cpp-2519/main.cpp @@ -0,0 +1,99 @@ +/// Source : https://leetcode.com/problems/count-the-number-of-k-big-indices/ +/// Author : liuyubobobo +/// Time : 2022-12-28 + +#include +#include +#include + +using namespace std; + + +/// Using BIT +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +template +class BIT{ + +private: + int n; + vector data; + vector tree; + +public: + BIT(const vector& arr) : n(arr.size()), data(arr.begin(), arr.end()), tree(n + 1){ + + for(int i = 0; i < n; i ++) + tree[i + 1]= data[i]; + + for(int i = 1; i <= n; i ++){ + int parent = i + (i & -i); + if(parent <= n) tree[parent] += tree[i]; + } + } + + void add(int index, T v){ + assert(0 <= index && index < n); + + data[index] += v; + + index ++; + for(;index <= n; index += (index & -index)) + tree[index] += v; + } + + T query(int l, int r){ + if(!(0 <= l && l < n) || !(0 <= r && r < n) || !(l <= r)) return 0; + return prefix_sum(r + 1) - prefix_sum(l); + } + + void set(int index, T v){ + assert(0 <= index && index < n); + add(index, v - data[index]); + } + +private: + // r is 1-based + T prefix_sum(int r){ + + T res = 0; + for(; r; r -= (r & -r)) + res += tree[r]; + return res; + } +}; + + +class Solution { +public: + int kBigIndices(vector& nums, int k) { + + int maxv = *max_element(nums.begin(), nums.end()); + int n = nums.size(); + + BIT bit1(vector(maxv + 1, 0)); + vector left(n, 0); + for(int i = 0; i < n; i ++){ + left[i] = bit1.query(0, nums[i] - 1); + bit1.add(nums[i], 1); + } + + BIT bit2(vector(maxv + 1, 0)); + vector right(n, 0); + for(int i = n - 1; i >= 0; i --){ + right[i] = bit2.query(0, nums[i] - 1); + bit2.add(nums[i], 1); + } + + int res = 0; + for(int i = 0; i < n; i ++) + res += (left[i] >= k && right[i] >= k); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2520-Count-the-Digits-That-Divide-a-Number/cpp-2520/CMakeLists.txt b/2501-3000/2520-Count-the-Digits-That-Divide-a-Number/cpp-2520/CMakeLists.txt new file mode 100644 index 00000000..27018f78 --- /dev/null +++ b/2501-3000/2520-Count-the-Digits-That-Divide-a-Number/cpp-2520/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2520) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2520 main.cpp) diff --git a/2501-3000/2520-Count-the-Digits-That-Divide-a-Number/cpp-2520/main.cpp b/2501-3000/2520-Count-the-Digits-That-Divide-a-Number/cpp-2520/main.cpp new file mode 100644 index 00000000..974cb288 --- /dev/null +++ b/2501-3000/2520-Count-the-Digits-That-Divide-a-Number/cpp-2520/main.cpp @@ -0,0 +1,30 @@ +/// Source : https://leetcode.com/problems/count-the-digits-that-divide-a-number/description/ +/// Author : liuyubobobo +/// Time : 2022-12-31 + +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(log(num)) +/// Space Complexity: O(log(num)) +class Solution { +public: + int countDigits(int num) { + + int res = 0; + + string num_str = to_string(num); + for(char c: num_str) + res += num % (c - '0') == 0; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2521-Distinct-Prime-Factors-of-Product-of-Array/cpp-2521/CMakeLists.txt b/2501-3000/2521-Distinct-Prime-Factors-of-Product-of-Array/cpp-2521/CMakeLists.txt new file mode 100644 index 00000000..3be708aa --- /dev/null +++ b/2501-3000/2521-Distinct-Prime-Factors-of-Product-of-Array/cpp-2521/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2521) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2521 main.cpp) diff --git a/2501-3000/2521-Distinct-Prime-Factors-of-Product-of-Array/cpp-2521/main.cpp b/2501-3000/2521-Distinct-Prime-Factors-of-Product-of-Array/cpp-2521/main.cpp new file mode 100644 index 00000000..3cdeb763 --- /dev/null +++ b/2501-3000/2521-Distinct-Prime-Factors-of-Product-of-Array/cpp-2521/main.cpp @@ -0,0 +1,53 @@ +/// Source : https://leetcode.com/problems/distinct-prime-factors-of-product-of-array/description/ +/// Author : liuyubobobo +/// Time : 2022-12-31 + +#include +#include +#include + +using namespace std; + + +/// Sieve +/// Time Complexity: O(MAX_NUM*log(MAX_NUM) + nlog(MAX_NUM)) +/// Space Compelxity: O(MAX_NUM) +class Solution { +public: + int distinctPrimeFactors(vector& nums) { + + vector sieve_table = sieve(1000); + set res; + for(int num: nums){ + + while(num != 1){ + res.insert(sieve_table[num]); + num /= sieve_table[num]; + } + } + return res.size(); + } + +private: + vector sieve(int n){ + + vector table(n + 1, 0); + vector primes; + table[0] = table[1] = 1; + for(int i = 2; i <= n; i ++){ + if(table[i] == 0) { + primes.push_back(i); + table[i] = i; + } + for(int j = 0; j < primes.size() && primes[j] <= table[i] && i * primes[j] <= n; j ++) + table[i * primes[j]] = primes[j]; + } + return table; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2522-Partition-String-Into-Substrings-With-Values-at-Most-K/cpp-2522/CMakeLists.txt b/2501-3000/2522-Partition-String-Into-Substrings-With-Values-at-Most-K/cpp-2522/CMakeLists.txt new file mode 100644 index 00000000..b702502d --- /dev/null +++ b/2501-3000/2522-Partition-String-Into-Substrings-With-Values-at-Most-K/cpp-2522/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2522) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2522 main.cpp) diff --git a/2501-3000/2522-Partition-String-Into-Substrings-With-Values-at-Most-K/cpp-2522/main.cpp b/2501-3000/2522-Partition-String-Into-Substrings-With-Values-at-Most-K/cpp-2522/main.cpp new file mode 100644 index 00000000..6e55ce40 --- /dev/null +++ b/2501-3000/2522-Partition-String-Into-Substrings-With-Values-at-Most-K/cpp-2522/main.cpp @@ -0,0 +1,49 @@ +/// Source : https://leetcode.com/problems/partition-string-into-substrings-with-values-at-most-k/description/ +/// Author : liuyubobobo +/// Time : 2022-12-31 + +#include +#include +#include + +using namespace std; + + +/// Memoization +/// Time Complexity: O(nlogk) +/// Space Complexity: O(n) +class Solution { + +private: + const int INF = INT_MAX / 2; +public: + int minimumPartition(string s, int k) { + + int n = s.size(); + vector dp(n, -1); + dfs(n, s, 0, k, dp); + return dp[0] == INF ? -1 : dp[0]; + } + +private: + int dfs(int n, const string& s, int index, long long k, vector& dp){ + + if(index == n) return 0; + if(dp[index] != -1) return dp[index]; + + long long cur = 0; + int res = INF; + for(int i = index; i < n && cur * 10 + (s[i] - '0') <= k; i ++){ + cur = cur * 10 + (s[i] - '0'); + res = min(res, 1 + dfs(n, s, i + 1, k, dp)); + } + return dp[index] = res; + } +}; + + +int main() { + + + return 0; +} diff --git a/2501-3000/2523-Closest-Prime-Numbers-in-Range/cpp-2523/CMakeLists.txt b/2501-3000/2523-Closest-Prime-Numbers-in-Range/cpp-2523/CMakeLists.txt new file mode 100644 index 00000000..339a9757 --- /dev/null +++ b/2501-3000/2523-Closest-Prime-Numbers-in-Range/cpp-2523/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2523) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2523 main.cpp) diff --git a/2501-3000/2523-Closest-Prime-Numbers-in-Range/cpp-2523/main.cpp b/2501-3000/2523-Closest-Prime-Numbers-in-Range/cpp-2523/main.cpp new file mode 100644 index 00000000..725f5901 --- /dev/null +++ b/2501-3000/2523-Closest-Prime-Numbers-in-Range/cpp-2523/main.cpp @@ -0,0 +1,55 @@ +/// Source : https://leetcode.com/problems/closest-prime-numbers-in-range/description/ +/// Author : liuyubobobo +/// Time : 2022-12-31 + +#include +#include + +using namespace std; + + +/// Sieve +/// Time Compelxity: O(right * log(right) + (right - left) +/// Space Compelxity: O(right) +class Solution { + +public: + vector closestPrimes(int left, int right) { + + vector sieve_table = sieve(right); + vector v; + for(int i = left; i <= right; i ++) + if(sieve_table[i] == i && i != 1) v.push_back(i); + + if(v.size() <= 1) return {-1, -1}; + + int min_interval = v[1] - v[0], l = v[0]; + for(int i = 2; i < (int)v.size(); i ++) + if(v[i] - v[i - 1] < min_interval) + min_interval = v[i] - v[i - 1], l = v[i - 1]; + return {l, l + min_interval}; + } + +private: + vector sieve(int n){ + + vector table(n + 1, 0); + vector primes; + table[0] = table[1] = 1; + for(int i = 2; i <= n; i ++){ + if(table[i] == 0) { + primes.push_back(i); + table[i] = i; + } + for(int j = 0; j < primes.size() && primes[j] <= table[i] && i * primes[j] <= n; j ++) + table[i * primes[j]] = primes[j]; + } + return table; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2524-Maximum-Frequency-Score-of-a-Subarray/cpp-2524/CMakeLists.txt b/2501-3000/2524-Maximum-Frequency-Score-of-a-Subarray/cpp-2524/CMakeLists.txt new file mode 100644 index 00000000..2270b059 --- /dev/null +++ b/2501-3000/2524-Maximum-Frequency-Score-of-a-Subarray/cpp-2524/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2524) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2524 main.cpp) diff --git a/2501-3000/2524-Maximum-Frequency-Score-of-a-Subarray/cpp-2524/main.cpp b/2501-3000/2524-Maximum-Frequency-Score-of-a-Subarray/cpp-2524/main.cpp new file mode 100644 index 00000000..544c1d03 --- /dev/null +++ b/2501-3000/2524-Maximum-Frequency-Score-of-a-Subarray/cpp-2524/main.cpp @@ -0,0 +1,62 @@ +/// Source : https://leetcode.com/problems/maximum-frequency-score-of-a-subarray/description/ +/// Author : liuyubobobo +/// Time : 2022-01-06 + +#include +#include + +using namespace std; + + +/// Sliding Window +/// Time Complexity: O(maxv + nlog(maxv)) +/// Space Compelxity: O(maxv) +class Solution { + +private: + const long long MOD = 1e9 + 7; + +public: + int maxFrequencyScore(vector& nums, int k) { + + int maxv = *max_element(nums.begin(), nums.end()); + vector f(maxv + 1, 0); + for(int i = 0; i + 1 < k; i ++) f[nums[i]] ++; + + long long cur = 0; + for(int i = 0; i <= maxv; i ++) + if(f[i]) cur += quick_pow(i, f[i]), cur %= MOD; + + long long res = 0; + for(int i = k - 1; i < nums.size(); i ++){ + int num = nums[i]; + if(f[num]){cur -= quick_pow(num, f[num]); cur = (cur + MOD) % MOD;} + f[num] ++; + cur += quick_pow(num, f[num]); cur %= MOD; + + res = max(res, cur); + + num = nums[i - (k - 1)]; + cur -= quick_pow(num, f[num]); cur = (cur + MOD) % MOD; + f[num] --; + if(f[num]){cur += quick_pow(num, f[num]); cur %= MOD;} + } + return res; + } + +private: + long long quick_pow(long long a, long long k) { + long long res = 1ll; + while (k) { + if (k & 1) res = res * a % MOD; + a = a * a % MOD; + k >>= 1; + } + return res % MOD; + } +}; + +int main() { + + return 0; +} diff --git a/2501-3000/2525-Categorize-Box-According-to-Criteria/cpp-2525/CMakeLists.txt b/2501-3000/2525-Categorize-Box-According-to-Criteria/cpp-2525/CMakeLists.txt new file mode 100644 index 00000000..e91fd64a --- /dev/null +++ b/2501-3000/2525-Categorize-Box-According-to-Criteria/cpp-2525/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2525) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2525 main.cpp) diff --git a/2501-3000/2525-Categorize-Box-According-to-Criteria/cpp-2525/main.cpp b/2501-3000/2525-Categorize-Box-According-to-Criteria/cpp-2525/main.cpp new file mode 100644 index 00000000..d55e03ac --- /dev/null +++ b/2501-3000/2525-Categorize-Box-According-to-Criteria/cpp-2525/main.cpp @@ -0,0 +1,36 @@ +/// Source : https://leetcode.com/problems/categorize-box-according-to-criteria/description/ +/// Author : liuyubobobo +/// Time : 2023-01-07 + +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(1) +/// Space Complexity: O(1) +class Solution { +public: + string categorizeBox(long long length, long long width, long long height, long long mass) { + + bool is_bulky = false; + if(length >= 10000 || width >= 10000 || height >= 10000 || mass >= 10000) + is_bulky = true; + + long long volume = length * width * height; + if(volume >= 1000000000) is_bulky = true; + + bool is_heavy = mass >= 100; + + if(is_bulky && is_heavy) return "Both"; + if(!is_bulky && !is_heavy) return "Neither"; + return is_bulky ? "Bulky" : "Heavy"; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2526-Find-Consecutive-Integers-from-a-Data-Stream/cpp-2526/CMakeLists.txt b/2501-3000/2526-Find-Consecutive-Integers-from-a-Data-Stream/cpp-2526/CMakeLists.txt new file mode 100644 index 00000000..0beb385b --- /dev/null +++ b/2501-3000/2526-Find-Consecutive-Integers-from-a-Data-Stream/cpp-2526/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2526) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2526 main.cpp) diff --git a/2501-3000/2526-Find-Consecutive-Integers-from-a-Data-Stream/cpp-2526/main.cpp b/2501-3000/2526-Find-Consecutive-Integers-from-a-Data-Stream/cpp-2526/main.cpp new file mode 100644 index 00000000..ad6e835f --- /dev/null +++ b/2501-3000/2526-Find-Consecutive-Integers-from-a-Data-Stream/cpp-2526/main.cpp @@ -0,0 +1,43 @@ +/// Source : https://leetcode.com/problems/find-consecutive-integers-from-a-data-stream/description/ +/// Author : liuyubobobo +/// Time : 2023-01-07 + +#include +#include + +using namespace std; + + +/// Using Deque +/// Time Complexity: O(n) +/// Space Complexity: O(k) +class DataStream { + +private: + int value, k; + deque q; + int equal_value = 0; + +public: + DataStream(int value, int k) : value(value), k(k) { + } + + bool consec(int num) { + q.push_back(num); + equal_value += (num == value); + + if(q.size() > k){ + int front = q.front(); + q.pop_front(); + equal_value -= (front == value); + } + + return equal_value == k; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2527-Find-Xor-Beauty-of-Array/cpp-2527/CMakeLists.txt b/2501-3000/2527-Find-Xor-Beauty-of-Array/cpp-2527/CMakeLists.txt new file mode 100644 index 00000000..4bd25232 --- /dev/null +++ b/2501-3000/2527-Find-Xor-Beauty-of-Array/cpp-2527/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2527) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2527 main.cpp) diff --git a/2501-3000/2527-Find-Xor-Beauty-of-Array/cpp-2527/main.cpp b/2501-3000/2527-Find-Xor-Beauty-of-Array/cpp-2527/main.cpp new file mode 100644 index 00000000..bacfd456 --- /dev/null +++ b/2501-3000/2527-Find-Xor-Beauty-of-Array/cpp-2527/main.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/find-xor-beauty-of-array/description/ +/// Author : liuyubobobo +/// Time : 2023-01-07 + +#include +#include + +using namespace std; + + +/// Bitwise +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int xorBeauty(vector& nums) { + + long long n = nums.size(); + + int res = 0; + for(int p = 0; p < 30; p ++){ + vector cnt(2, 0); + for(int num: nums) cnt[(num >> p) & 1] ++; + + long long a = n * n - cnt[0] * cnt[0]; + long long b = a * cnt[1]; + if(b & 1) res += (1 << p); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2528-Maximize-the-Minimum-Powered-City/cpp-2528/CMakeLists.txt b/2501-3000/2528-Maximize-the-Minimum-Powered-City/cpp-2528/CMakeLists.txt new file mode 100644 index 00000000..e9658cae --- /dev/null +++ b/2501-3000/2528-Maximize-the-Minimum-Powered-City/cpp-2528/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2528) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2528 main.cpp) diff --git a/2501-3000/2528-Maximize-the-Minimum-Powered-City/cpp-2528/main.cpp b/2501-3000/2528-Maximize-the-Minimum-Powered-City/cpp-2528/main.cpp new file mode 100644 index 00000000..7e68eda1 --- /dev/null +++ b/2501-3000/2528-Maximize-the-Minimum-Powered-City/cpp-2528/main.cpp @@ -0,0 +1,56 @@ +/// Source : https://leetcode.com/problems/maximize-the-minimum-powered-city/description/ +/// Author : liuyubobobo +/// Time : 2023-01-07 + +#include +#include + +using namespace std; + + +/// Binary Search + Diff Array +/// Time Complexity: O(n * log(max)) +/// Space Complexity: O(n) +class Solution { +public: + long long maxPower(vector& stations, int radius, int k) { + + long long l = 0, r = 1e11; + while(l < r){ + long long mid = (l + r + 1) / 2; + if(ok(stations.size(), stations, radius, k, mid)) + l = mid; + else + r = mid - 1; + } + return l; + } + +private: + bool ok(int n, const vector& stations, int radius, int k, long long min_power){ + + vector diff_arr(n + 1, 0); + for(int i = 0; i < n; i ++){ + int l = max(0, i - radius), r = min(n - 1, i + radius); + diff_arr[l] += stations[i], diff_arr[r + 1] -= stations[i]; + } + + long long cur = 0, need = 0; + for(int i = 0; i < n; i ++){ + cur += diff_arr[i]; + if(cur < min_power){ + long long d = min_power - cur, l = i, r = min(i + radius + radius, n - 1); + diff_arr[l] += d, diff_arr[r + 1] -= d; + cur = min_power; + need += d; + } + } + return need <= k; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2529-Maximum-Count-of-Positive-Integer-and-Negative-Integer/cpp-2529/CMakeLists.txt b/2501-3000/2529-Maximum-Count-of-Positive-Integer-and-Negative-Integer/cpp-2529/CMakeLists.txt new file mode 100644 index 00000000..0585437f --- /dev/null +++ b/2501-3000/2529-Maximum-Count-of-Positive-Integer-and-Negative-Integer/cpp-2529/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2529) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2529 main.cpp) diff --git a/2501-3000/2529-Maximum-Count-of-Positive-Integer-and-Negative-Integer/cpp-2529/main.cpp b/2501-3000/2529-Maximum-Count-of-Positive-Integer-and-Negative-Integer/cpp-2529/main.cpp new file mode 100644 index 00000000..be662ed1 --- /dev/null +++ b/2501-3000/2529-Maximum-Count-of-Positive-Integer-and-Negative-Integer/cpp-2529/main.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/maximum-count-of-positive-integer-and-negative-integer/description/ +/// Author : liuyubobobo +/// Time : 2023-01-08 + +#include +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(logn) +/// Space Complexity: O(1) +class Solution { +public: + int maximumCount(vector& nums) { + + auto iter = lower_bound(nums.begin(), nums.end(), 0); + int neg = iter - nums.begin(); + + iter = lower_bound(nums.begin(), nums.end(), 1); + int pos = nums.end() - iter; + + return max(neg, pos); + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2530-Maximal-Score-After-Applying-K-Operations/cpp-2530/CMakeLists.txt b/2501-3000/2530-Maximal-Score-After-Applying-K-Operations/cpp-2530/CMakeLists.txt new file mode 100644 index 00000000..fecf5aa6 --- /dev/null +++ b/2501-3000/2530-Maximal-Score-After-Applying-K-Operations/cpp-2530/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2530) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2530 main.cpp) diff --git a/2501-3000/2530-Maximal-Score-After-Applying-K-Operations/cpp-2530/main.cpp b/2501-3000/2530-Maximal-Score-After-Applying-K-Operations/cpp-2530/main.cpp new file mode 100644 index 00000000..f7d5f0c0 --- /dev/null +++ b/2501-3000/2530-Maximal-Score-After-Applying-K-Operations/cpp-2530/main.cpp @@ -0,0 +1,38 @@ +/// Source : https://leetcode.com/problems/maximal-score-after-applying-k-operations/description/ +/// Author : liuyubobobo +/// Time : 2023-01-08 + +#include +#include +#include + +using namespace std; + + +/// PQ +/// Time Complexity: O(klogn) +/// Space Complexity: O(n) +class Solution { +public: + long long maxKelements(vector& nums, int k) { + + priority_queue pq; + for(int e: nums) pq.push(e); + + long long res = 0; + for(int i = 0; i < k && !pq.empty(); i ++){ + int e = pq.top(); pq.pop(); + res += e; + + e = e / 3 + !!(e % 3); + if(e) pq.push(e); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2531-Make-Number-of-Distinct-Characters-Equal/cpp-2531/CMakeLists.txt b/2501-3000/2531-Make-Number-of-Distinct-Characters-Equal/cpp-2531/CMakeLists.txt new file mode 100644 index 00000000..e062bdc9 --- /dev/null +++ b/2501-3000/2531-Make-Number-of-Distinct-Characters-Equal/cpp-2531/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2531) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2531 main.cpp) diff --git a/2501-3000/2531-Make-Number-of-Distinct-Characters-Equal/cpp-2531/main.cpp b/2501-3000/2531-Make-Number-of-Distinct-Characters-Equal/cpp-2531/main.cpp new file mode 100644 index 00000000..715a8d69 --- /dev/null +++ b/2501-3000/2531-Make-Number-of-Distinct-Characters-Equal/cpp-2531/main.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/make-number-of-distinct-characters-equal/description/ +/// Author : liuyubobobo +/// Time : 2023-01-08 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(|word1| + |word2| + CHAR_SET^3) +/// Space Complexity: O(1) +class Solution { +public: + bool isItPossible(string word1, string word2) { + + vector f1(26, 0), f2(26, 0); + for(char c: word1) f1[c - 'a'] ++; + for(char c: word2) f2[c - 'a'] ++; + + for(int i = 0; i < 26; i ++) if(f1[i]) + for(int j = 0; j < 26; j ++) if(f2[j]){ + f1[i] --, f2[j] --; + f1[j] ++, f2[i] ++; + + if(get_unique(f1) == get_unique(f2)) return true; + + f1[j] --, f2[i] --; + f1[i] ++, f2[j] ++; + } + return false; + } + +private: + int get_unique(const vector& f){ + + int res = 0; + for(int e: f) res += !!e; + return res; + } +}; + +int main() { + + return 0; +} diff --git a/2501-3000/2532-Time-to-Cross-a-Bridge/cpp-2532/CMakeLists.txt b/2501-3000/2532-Time-to-Cross-a-Bridge/cpp-2532/CMakeLists.txt new file mode 100644 index 00000000..522a4447 --- /dev/null +++ b/2501-3000/2532-Time-to-Cross-a-Bridge/cpp-2532/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2532) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2532 main.cpp) diff --git a/2501-3000/2532-Time-to-Cross-a-Bridge/cpp-2532/main.cpp b/2501-3000/2532-Time-to-Cross-a-Bridge/cpp-2532/main.cpp new file mode 100644 index 00000000..62be1ebc --- /dev/null +++ b/2501-3000/2532-Time-to-Cross-a-Bridge/cpp-2532/main.cpp @@ -0,0 +1,84 @@ +/// Source : https://leetcode.com/problems/time-to-cross-a-bridge/description/s +/// Author : liuyubobobo +/// Time : 2023-01-09 + +#include +#include +#include +#include +#include +#include +#include + +using namespace std; + + +/// Event Simulation, Using PQ +/// Time Complexity: O(nlogk) +/// Space Complexity: O(k) +class Solution { +public: + int findCrossingTime(int n, int k, vector>& time) { + + priority_queue, vector>, greater>> left_ready_q, right_ready_q; // ready_time, index + priority_queue> bridge_left_q, bridge_right_q; // efficient, index + for(int i = 0; i < k; i ++) + bridge_left_q.push({time[i][0] + time[i][2], i}); + + int cur_time = 0, left = n, complete = 0; + while(true){ + + while(!left_ready_q.empty() && cur_time >= left_ready_q.top().first){ + int index = left_ready_q.top().second; + left_ready_q.pop(); + bridge_left_q.push({time[index][0] + time[index][2], index}); + } + + while(!right_ready_q.empty() && cur_time >= right_ready_q.top().first){ + int index = right_ready_q.top().second; + right_ready_q.pop(); + bridge_right_q.push({time[index][0] + time[index][2], index}); + } + + if(!bridge_right_q.empty()){ + int index = bridge_right_q.top().second; + bridge_right_q.pop(); + + cur_time += time[index][2]; + + left_ready_q.push({cur_time + time[index][3], index}); + + complete ++; + if(complete == n) return cur_time; + } + else if(left && !bridge_left_q.empty()){ + int index = bridge_left_q.top().second; + bridge_left_q.pop(); + + cur_time += time[index][0]; + + right_ready_q.push({cur_time + time[index][1], index}); + + left --; + } + else{ + int next_time = INT_MAX; + if(!left_ready_q.empty()) next_time = min(next_time, left_ready_q.top().first); + if(!right_ready_q.empty()) next_time = min(next_time, right_ready_q.top().first); + assert(next_time != INT_MAX); + cur_time = next_time; + } + } + return -1; + } +}; + + +int main() { + + vector> time1 = {{1, 1, 2, 1}, {1, 1, 3, 1}, {1, 1, 4, 1}}; + cout << Solution().findCrossingTime(1, 3, time1) << '\n'; + // 6 + + return 0; +} diff --git a/2501-3000/2533-Number-of-Good-Binary-Strings/cpp-2533/CMakeLists.txt b/2501-3000/2533-Number-of-Good-Binary-Strings/cpp-2533/CMakeLists.txt new file mode 100644 index 00000000..cac4ab16 --- /dev/null +++ b/2501-3000/2533-Number-of-Good-Binary-Strings/cpp-2533/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2533) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2533 main.cpp) diff --git a/2501-3000/2533-Number-of-Good-Binary-Strings/cpp-2533/main.cpp b/2501-3000/2533-Number-of-Good-Binary-Strings/cpp-2533/main.cpp new file mode 100644 index 00000000..03f64446 --- /dev/null +++ b/2501-3000/2533-Number-of-Good-Binary-Strings/cpp-2533/main.cpp @@ -0,0 +1,49 @@ +/// Source : https://leetcode.com/problems/number-of-good-binary-strings/ +/// Author : liuyubobobo +/// Time : 2023-01-14 + +#include +#include + +using namespace std; + + +/// Memoization +/// Time Complexity: O(maxLength) +/// Space Complexity: O(maxLength) +class Solution { + +private: + const long long MOD = 1e9 + 7; + +public: + int goodBinaryStrings(int minLength, int maxLength, int oneGroup, int zeroGroup) { + + vector dp(maxLength + 1, -1); + long long res = 0; + for(int len = minLength; len <= maxLength; len ++) + res += solve(len, oneGroup, zeroGroup, dp), res %= MOD; + return res; + } + +private: + long long solve(int len, int one, int zero, vector& dp){ + + if(len < 0) return 0; + if(len == 0) return 1; + if(dp[len] != -1) return dp[len]; + + long long res = solve(len - one, one, zero, dp); + res += solve(len - zero, one, zero, dp); + return dp[len] = res % MOD; + } +}; + + +int main() { + + cout << Solution().goodBinaryStrings(2, 3, 1, 2) << '\n'; + // 5 + + return 0; +} diff --git a/2501-3000/2534-Time-Taken-to-Cross-the-Door/cpp-2534/CMakeLists.txt b/2501-3000/2534-Time-Taken-to-Cross-the-Door/cpp-2534/CMakeLists.txt new file mode 100644 index 00000000..8dfa2c4e --- /dev/null +++ b/2501-3000/2534-Time-Taken-to-Cross-the-Door/cpp-2534/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2534) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2534 main.cpp) diff --git a/2501-3000/2534-Time-Taken-to-Cross-the-Door/cpp-2534/main.cpp b/2501-3000/2534-Time-Taken-to-Cross-the-Door/cpp-2534/main.cpp new file mode 100644 index 00000000..aa68e311 --- /dev/null +++ b/2501-3000/2534-Time-Taken-to-Cross-the-Door/cpp-2534/main.cpp @@ -0,0 +1,81 @@ +/// Source : https://leetcode.com/problems/time-taken-to-cross-the-door/description/ +/// Author : liuyubobobo +/// Time : 2023-01-14 + +#include +#include +#include + +using namespace std; + + +/// Event Simulation +/// Time Compelxity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector timeTaken(vector& arrival, vector& state) { + + int n = arrival.size(); + + vector res(n, -1); + queue enter_list, leave_list; + int arrival_index = 0, t = 0, pre_state = -1; + while(arrival_index < n || !enter_list.empty() || !leave_list.empty()){ + while(arrival_index < n && arrival[arrival_index] <= t){ + if(state[arrival_index] == 0) enter_list.push(arrival_index); + else leave_list.push(arrival_index); + arrival_index ++; + } + + if(pre_state == -1 || pre_state == 1){ + if(!leave_list.empty()){ + int index = leave_list.front(); leave_list.pop(); + res[index] = t; + pre_state = 1; + } + else if(!enter_list.empty()){ + int index = enter_list.front(); enter_list.pop(); + res[index] = t; + pre_state = 0; + } + else pre_state = -1; + } + else{ + if(!enter_list.empty()){ + int index = enter_list.front(); enter_list.pop(); + res[index] = t; + pre_state = 0; + } + else if(!leave_list.empty()){ + int index = leave_list.front(); leave_list.pop(); + res[index] = t; + pre_state = 1; + } + else pre_state = -1; + } + t ++; + } + + return res; + } +}; + + +void print_vec(const vector& res){ + for(int e: res) cout << e << ' '; cout << '\n'; +} + +int main() { + + vector arrival1 = {0, 1, 1, 2, 4}, state1 = {0, 1, 0, 0, 1}; + print_vec(Solution().timeTaken(arrival1, state1)); + // 0 3 1 2 4 + + vector arrival2 = {0,0,6,9,10,10,11,11,11,12,14,14,15,15,15,15,15,16,18,18}, + state2 = {0,0,0,0,0,0,1,1,1,1,0,1,1,1,0,1,0,1,0,0}; + print_vec(Solution().timeTaken(arrival2, state2)); + // 0 3 1 2 4 + + return 0; +} diff --git a/2501-3000/2535-Difference-Between-Element-Sum-and-Digit-Sum-of-an-Array/cpp-2535/CMakeLists.txt b/2501-3000/2535-Difference-Between-Element-Sum-and-Digit-Sum-of-an-Array/cpp-2535/CMakeLists.txt new file mode 100644 index 00000000..4b2bfe28 --- /dev/null +++ b/2501-3000/2535-Difference-Between-Element-Sum-and-Digit-Sum-of-an-Array/cpp-2535/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2535) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2535 main.cpp) diff --git a/2501-3000/2535-Difference-Between-Element-Sum-and-Digit-Sum-of-an-Array/cpp-2535/main.cpp b/2501-3000/2535-Difference-Between-Element-Sum-and-Digit-Sum-of-an-Array/cpp-2535/main.cpp new file mode 100644 index 00000000..9a89b7fe --- /dev/null +++ b/2501-3000/2535-Difference-Between-Element-Sum-and-Digit-Sum-of-an-Array/cpp-2535/main.cpp @@ -0,0 +1,31 @@ +/// Source : https://leetcode.com/problems/difference-between-element-sum-and-digit-sum-of-an-array/description/ +/// Author : liuyubobobo +/// Time : 2023-01-14 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Compelxity: O(nlog(max_num)) +/// Space Complexity: O(1) +class Solution { +public: + int differenceOfSum(vector& nums) { + + int sum1 = 0, sum2 = 0; + for(int num: nums){ + sum1 += num; + while(num) sum2 += num % 10, num /= 10; + } + return abs(sum1 - sum2); + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2536-Increment-Submatrices-by-One/cpp-2536/CMakeLists.txt b/2501-3000/2536-Increment-Submatrices-by-One/cpp-2536/CMakeLists.txt new file mode 100644 index 00000000..dc6f5345 --- /dev/null +++ b/2501-3000/2536-Increment-Submatrices-by-One/cpp-2536/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2536) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2536 main.cpp) diff --git a/2501-3000/2536-Increment-Submatrices-by-One/cpp-2536/main.cpp b/2501-3000/2536-Increment-Submatrices-by-One/cpp-2536/main.cpp new file mode 100644 index 00000000..6127abba --- /dev/null +++ b/2501-3000/2536-Increment-Submatrices-by-One/cpp-2536/main.cpp @@ -0,0 +1,41 @@ +/// Source : https://leetcode.com/problems/increment-submatrices-by-one/description/ +/// Author : liuyubobobo +/// Time : 2023-01-14 + +#include +#include + +using namespace std; + + +/// Diff Array +/// Time Complexity: O(|q| * n) +/// Space Complexity: O(n^2) +class Solution { +public: + vector> rangeAddQueries(int n, vector>& queries) { + + vector> diff(n, vector(n + 1, 0)); + for(const vector& q: queries){ + int a = q[0], b = q[2], l = q[1], r = q[3]; + for(int i = a; i <= b; i ++) + diff[i][l] += 1, diff[i][r + 1] -= 1; + } + + vector> res(n, vector(n)); + for(int i = 0; i < n; i ++){ + int presum = 0; + for(int j = 0; j < n; j ++){ + presum += diff[i][j]; + res[i][j] = presum; + } + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2537-Count-the-Number-of-Good-Subarrays/cpp-2537/CMakeLists.txt b/2501-3000/2537-Count-the-Number-of-Good-Subarrays/cpp-2537/CMakeLists.txt new file mode 100644 index 00000000..266c11b5 --- /dev/null +++ b/2501-3000/2537-Count-the-Number-of-Good-Subarrays/cpp-2537/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2537) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2537 main.cpp) diff --git a/2501-3000/2537-Count-the-Number-of-Good-Subarrays/cpp-2537/main.cpp b/2501-3000/2537-Count-the-Number-of-Good-Subarrays/cpp-2537/main.cpp new file mode 100644 index 00000000..d286e5f4 --- /dev/null +++ b/2501-3000/2537-Count-the-Number-of-Good-Subarrays/cpp-2537/main.cpp @@ -0,0 +1,43 @@ +/// Source : https://leetcode.com/problems/count-the-number-of-good-subarrays/description/ +/// Author : liuyubobobo +/// Time : 2023-01-14 + +#include +#include +#include + +using namespace std; + + +/// Sliding Window +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + long long countGood(vector& nums, int k) { + + map f; + long long cur = 0, res = 0; + int n = nums.size(), l = 0, r = -1; + while(l < n){ + if(r + 1 < n && cur < k){ + cur += f[nums[r + 1]]; + f[nums[r + 1]] ++; + r ++; + } + else{ + f[nums[l]] --; + cur -= f[nums[l]]; + l ++; + } + if(cur >= k) res += n - r; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2539-Count-the-Number-of-Good-Subsequences/cpp-2539/CMakeLists.txt b/2501-3000/2539-Count-the-Number-of-Good-Subsequences/cpp-2539/CMakeLists.txt new file mode 100644 index 00000000..17f76ecb --- /dev/null +++ b/2501-3000/2539-Count-the-Number-of-Good-Subsequences/cpp-2539/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2539) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2539 main.cpp) diff --git a/2501-3000/2539-Count-the-Number-of-Good-Subsequences/cpp-2539/main.cpp b/2501-3000/2539-Count-the-Number-of-Good-Subsequences/cpp-2539/main.cpp new file mode 100644 index 00000000..9e08f006 --- /dev/null +++ b/2501-3000/2539-Count-the-Number-of-Good-Subsequences/cpp-2539/main.cpp @@ -0,0 +1,80 @@ +/// Source : https://leetcode.com/problems/count-the-number-of-good-subsequences/description/ +/// Author : liuyubobobo +/// Time : 2023-01-19 + +#include +#include +#include +#include + +using namespace std; + + +/// Math +/// Time Complexity: O(n) +/// Space Complexity: O(maxn) +class Solution { + +private: + const int MAXN = 1e4; + const long long MOD = 1e9 + 7; + vector fac, ifac; + +public: + Solution() : fac(MAXN + 1, 1), ifac(MAXN + 1){ + for(int i = 2; i <= MAXN; i ++) fac[i] = fac[i - 1] * i % MOD; + for(int i = 0; i <= MAXN; i ++) ifac[i] = quick_pow(fac[i], MOD - 2); + } + + int countGoodSubsequences(string s) { + + int n = s.size(); + + vector f(26, 0); + for(char c: s) f[c - 'a'] ++; + + vector a; + for(int e: f) if(e) a.push_back(e); + int maxf = *max_element(a.begin(), a.end()); + + long long total = 0; + for(int i = 1; i <= maxf; i ++){ + long long tres = 1; + for(int e: a) tres = tres * (C(e, i) + C(e, 0)) % MOD; + tres = (tres - 1 + MOD) % MOD; + total += tres; + } + return total % MOD; + } + +private: + long long C(int n, int r){ + if(r > n) return 0; + return fac[n] * ifac[r] % MOD * ifac[n - r] % MOD; + } + + long long quick_pow(long long a, long long k) { + long long res = 1ll; + while (k) { + if (k & 1) res = res * a % MOD; + a = a * a % MOD; + k >>= 1; + } + return res % MOD; + } +}; + + +int main() { + + cout << Solution().countGoodSubsequences("aabb") << '\n'; + // 11 + + cout << Solution().countGoodSubsequences("leet") << '\n'; + // 12 + + cout << Solution().countGoodSubsequences("abcd") << '\n'; + // 15 + + return 0; +} diff --git a/2501-3000/2540-Minimum-Common-Value/cpp-2540/CMakeLists.txt b/2501-3000/2540-Minimum-Common-Value/cpp-2540/CMakeLists.txt new file mode 100644 index 00000000..c8903efb --- /dev/null +++ b/2501-3000/2540-Minimum-Common-Value/cpp-2540/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2540) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2540 main.cpp) diff --git a/2501-3000/2540-Minimum-Common-Value/cpp-2540/main.cpp b/2501-3000/2540-Minimum-Common-Value/cpp-2540/main.cpp new file mode 100644 index 00000000..ea4a5035 --- /dev/null +++ b/2501-3000/2540-Minimum-Common-Value/cpp-2540/main.cpp @@ -0,0 +1,32 @@ +/// Source : https://leetcode.com/problems/minimum-common-value/description/ +/// Author : liuyubobobo +/// Time : 2023-01-21 + +#include +#include + +using namespace std; + + +/// Two Pointers +/// Time Complexity: O(|nums1| + |nums2|) +/// Space Complexity: O(1) +class Solution { +public: + int getCommon(vector& nums1, vector& nums2) { + + int i = 0, j = 0; + while(i < nums1.size() && j < nums2.size()){ + if(nums1[i] == nums2[j]) return nums1[i]; + else if(nums1[i] < nums2[j]) i ++; + else j ++; + } + return -1; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2541-Minimum-Operations-to-Make-Array-Equal-II/cpp-2541/CMakeLists.txt b/2501-3000/2541-Minimum-Operations-to-Make-Array-Equal-II/cpp-2541/CMakeLists.txt new file mode 100644 index 00000000..189c45e8 --- /dev/null +++ b/2501-3000/2541-Minimum-Operations-to-Make-Array-Equal-II/cpp-2541/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2541) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2541 main.cpp) diff --git a/2501-3000/2541-Minimum-Operations-to-Make-Array-Equal-II/cpp-2541/main.cpp b/2501-3000/2541-Minimum-Operations-to-Make-Array-Equal-II/cpp-2541/main.cpp new file mode 100644 index 00000000..95e40d1f --- /dev/null +++ b/2501-3000/2541-Minimum-Operations-to-Make-Array-Equal-II/cpp-2541/main.cpp @@ -0,0 +1,48 @@ +/// Source : https://leetcode.com/problems/minimum-operations-to-make-array-equal-ii/description/ +/// Author : liuyubobobo +/// Time : 2023-01-21 + +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + long long minOperations(vector& nums1, vector& nums2, int k) { + + int n = nums1.size(); + if(k == 0){ + for(int i = 0; i < n; i ++) + if(nums1[i] != nums2[i]) return -1; + return 0; + } + + long long a = 0, b = 0; + for(int i = 0; i < n; i ++){ + if(nums1[i] > nums2[i]){ + long long d = nums1[i] - nums2[i]; + if(d % k != 0) return -1; + a += d / k; + } + else if(nums1[i] < nums2[i]){ + long long d = nums2[i] - nums1[i]; + if(d % k != 0) return -1; + b += d / k; + } + } + + return a == b ? a : -1; + } +}; + + +int main() { + + + return 0; +} diff --git a/2501-3000/2542-Maximum-Subsequence-Score/cpp-2542/CMakeLists.txt b/2501-3000/2542-Maximum-Subsequence-Score/cpp-2542/CMakeLists.txt new file mode 100644 index 00000000..c62f244f --- /dev/null +++ b/2501-3000/2542-Maximum-Subsequence-Score/cpp-2542/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2542) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2542 main.cpp) diff --git a/2501-3000/2542-Maximum-Subsequence-Score/cpp-2542/main.cpp b/2501-3000/2542-Maximum-Subsequence-Score/cpp-2542/main.cpp new file mode 100644 index 00000000..eca07bae --- /dev/null +++ b/2501-3000/2542-Maximum-Subsequence-Score/cpp-2542/main.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.com/problems/maximum-subsequence-score/description/ +/// Author : liuyubobobo +/// Time : 2023-01-21 + +#include +#include +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + long long maxScore(vector& nums1, vector& nums2, int k) { + + int n = nums1.size(); + + vector> v(n); + for(int i = 0; i < n; i ++) v[i] = {nums1[i], nums2[i]}; + + sort(v.begin(), v.end(), + [](const pair& p1, const pair& p2){ + return p1.second < p2.second; + }); + + priority_queue, greater<>> pq; + long long sum = 0; + for(int i = n - 1; i >= n - k; i --) + pq.push(v[i].first), sum += v[i].first; + + long long res = v[n - k].second * sum; + for(int i = n - k - 1; i >= 0; i --){ + long long t = pq.top(); + pq.pop(); + sum -= t; + pq.push(v[i].first); + sum += v[i].first; + res = max(res, v[i].second * sum); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2543-Check-if-Point-Is-Reachable/cpp-2543/CMakeLists.txt b/2501-3000/2543-Check-if-Point-Is-Reachable/cpp-2543/CMakeLists.txt new file mode 100644 index 00000000..4db2fffb --- /dev/null +++ b/2501-3000/2543-Check-if-Point-Is-Reachable/cpp-2543/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2543) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2543 main.cpp) diff --git a/2501-3000/2543-Check-if-Point-Is-Reachable/cpp-2543/main.cpp b/2501-3000/2543-Check-if-Point-Is-Reachable/cpp-2543/main.cpp new file mode 100644 index 00000000..6732efdb --- /dev/null +++ b/2501-3000/2543-Check-if-Point-Is-Reachable/cpp-2543/main.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/check-if-point-is-reachable/description/ +/// Author : liuyubobobo +/// Time : 2023-01-24 + +#include +#include + +using namespace std; + + +/// Math +/// Time Complexity: O(log(max(targetX, targetY))) +/// Space Complexity: O(log(max(targetX, targetY))) +class Solution { +public: + bool isReachable(int targetX, int targetY) { + + int g = gcd(targetX, targetY); + return (g & (g - 1)) == 0; + } + +private: + int gcd(int a, int b){ + if(a > b) swap(a, b); + if (a == 0) return b; + return gcd(b % a, a); + } +}; + + +int main() { + + cout << Solution().isReachable(6, 9) << '\n'; + return 0; +} diff --git a/2501-3000/2544-Alternating-Digit-Sum/cpp-2544/CMakeLists.txt b/2501-3000/2544-Alternating-Digit-Sum/cpp-2544/CMakeLists.txt new file mode 100644 index 00000000..4a2a5823 --- /dev/null +++ b/2501-3000/2544-Alternating-Digit-Sum/cpp-2544/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2544) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2544 main.cpp) diff --git a/2501-3000/2544-Alternating-Digit-Sum/cpp-2544/main.cpp b/2501-3000/2544-Alternating-Digit-Sum/cpp-2544/main.cpp new file mode 100644 index 00000000..10e9fb6e --- /dev/null +++ b/2501-3000/2544-Alternating-Digit-Sum/cpp-2544/main.cpp @@ -0,0 +1,29 @@ +/// Source : https://leetcode.com/problems/alternating-digit-sum/description/ +/// Author : liuyubobobo +/// Time : 2023-01-21 + +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(logn) +/// Space Complexity: O(logn) +class Solution { +public: + int alternateDigitSum(int n) { + + string s = to_string(n); + int res = 0; + for(int i = 0; i < s.size(); i ++) + res += (i % 2 ? -1 : 1) * (s[i] - '0'); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2545-Sort-the-Students-by-Their-Kth-Score/cpp-2545/CMakeLists.txt b/2501-3000/2545-Sort-the-Students-by-Their-Kth-Score/cpp-2545/CMakeLists.txt new file mode 100644 index 00000000..95c038f1 --- /dev/null +++ b/2501-3000/2545-Sort-the-Students-by-Their-Kth-Score/cpp-2545/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2545) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2545 main.cpp) diff --git a/2501-3000/2545-Sort-the-Students-by-Their-Kth-Score/cpp-2545/main.cpp b/2501-3000/2545-Sort-the-Students-by-Their-Kth-Score/cpp-2545/main.cpp new file mode 100644 index 00000000..c4faa74b --- /dev/null +++ b/2501-3000/2545-Sort-the-Students-by-Their-Kth-Score/cpp-2545/main.cpp @@ -0,0 +1,31 @@ +/// Source : https://leetcode.com/problems/sort-the-students-by-their-kth-score/description/ +/// Author : liuyubobobo +/// Time : 2023-01-21 + +#include +#include +#include + +using namespace std; + + +/// Sorting +/// Time Complexity: O(mlogm * n) +/// Space Cpomplexity: O(n) +class Solution { +public: + vector> sortTheStudents(vector>& score, int k) { + + sort(score.begin(), score.end(), + [k](const vector& s1, const vector& s2){ + return s1[k] > s2[k]; + }); + return score; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2546-Apply-Bitwise-Operations-to-Make-Strings-Equal/cpp-2546/CMakeLists.txt b/2501-3000/2546-Apply-Bitwise-Operations-to-Make-Strings-Equal/cpp-2546/CMakeLists.txt new file mode 100644 index 00000000..35963fd1 --- /dev/null +++ b/2501-3000/2546-Apply-Bitwise-Operations-to-Make-Strings-Equal/cpp-2546/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2546) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2546 main.cpp) diff --git a/2501-3000/2546-Apply-Bitwise-Operations-to-Make-Strings-Equal/cpp-2546/main.cpp b/2501-3000/2546-Apply-Bitwise-Operations-to-Make-Strings-Equal/cpp-2546/main.cpp new file mode 100644 index 00000000..19dd9be4 --- /dev/null +++ b/2501-3000/2546-Apply-Bitwise-Operations-to-Make-Strings-Equal/cpp-2546/main.cpp @@ -0,0 +1,38 @@ +/// Source : https://leetcode.com/problems/apply-bitwise-operations-to-make-strings-equal/description/ +/// Author : liuyubobobo +/// Time : 2023-01-22 + +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + bool makeStringsEqual(string s, string target) { + + int n = s.size() - 1; + if(s == target) return true; + + bool s_has1 = false, s_all0 = true; + for(char c: s) if(c == '1') s_has1 = true; + for(char c: s) if(c == '1') s_all0 = false; + + bool t_has1 = false, t_all0 = true; + for(char c: target) if(c == '1') t_has1 = true; + for(char c: target) if(c == '1') t_all0 = false; + + if(s_has1 && t_all0) return false; + if(t_has1 && s_all0) return false; + return true; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2547-Minimum-Cost-to-Split-an-Array/cpp-2547/CMakeLists.txt b/2501-3000/2547-Minimum-Cost-to-Split-an-Array/cpp-2547/CMakeLists.txt new file mode 100644 index 00000000..48bbea51 --- /dev/null +++ b/2501-3000/2547-Minimum-Cost-to-Split-an-Array/cpp-2547/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2547) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2547 main.cpp) diff --git a/2501-3000/2547-Minimum-Cost-to-Split-an-Array/cpp-2547/main.cpp b/2501-3000/2547-Minimum-Cost-to-Split-an-Array/cpp-2547/main.cpp new file mode 100644 index 00000000..f98e2983 --- /dev/null +++ b/2501-3000/2547-Minimum-Cost-to-Split-an-Array/cpp-2547/main.cpp @@ -0,0 +1,44 @@ +/// Source : https://leetcode.com/problems/minimum-cost-to-split-an-array/description/ +/// Author : liuyubobobo +/// Time : 2023-01-22 + +#include +#include +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { +public: + int minCost(vector& nums, int k) { + + int n = nums.size(); + vector f(n, 0); + + vector dp(n + 1, INT_MAX / 2); + dp[n] = 0; + for(int i = n - 1; i >= 0; i --){ + f.assign(n, 0); + int trim_value = 0; + for(int j = i; j >= 0; j --){ + f[nums[j]] ++; + int len = f[nums[j]]; + if(len == 2) trim_value += 2; + else if(len > 2) trim_value ++; + dp[j] = min(dp[j], trim_value + k + dp[i + 1]); + } + } + return dp[0]; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2548-Maximum-Price-to-Fill-a-Bag/cpp-2548/CMakeLists.txt b/2501-3000/2548-Maximum-Price-to-Fill-a-Bag/cpp-2548/CMakeLists.txt new file mode 100644 index 00000000..5fcd588b --- /dev/null +++ b/2501-3000/2548-Maximum-Price-to-Fill-a-Bag/cpp-2548/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2548) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2548 main.cpp) diff --git a/2501-3000/2548-Maximum-Price-to-Fill-a-Bag/cpp-2548/main.cpp b/2501-3000/2548-Maximum-Price-to-Fill-a-Bag/cpp-2548/main.cpp new file mode 100644 index 00000000..b302f6dd --- /dev/null +++ b/2501-3000/2548-Maximum-Price-to-Fill-a-Bag/cpp-2548/main.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/maximum-price-to-fill-a-bag/description/ +/// Author : liuyubobobo +/// Time : 2023-01-28 + +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + double maxPrice(vector>& items, int capacity) { + + int total_weight = 0; + for(const vector& item: items) total_weight += item[1]; + if(total_weight < capacity) return -1; + + sort(items.begin(), items.end(), + [](const vector& item1, const vector& item2){ + double p1 = item1[0], w1 = item1[1]; + double p2 = item2[0], w2 = item2[1]; + return p1 / w1 > p2 / w2; + }); + + double price = 0; + for(const vector& item: items){ + double p = item[0]; int w = item[1]; + if(w <= capacity) price += p, capacity -= w; + else{ + price += capacity / (double)w * p; + break; + } + } + return price; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2549-Count-Distinct-Numbers-on-Board/cpp-2549/CMakeLists.txt b/2501-3000/2549-Count-Distinct-Numbers-on-Board/cpp-2549/CMakeLists.txt new file mode 100644 index 00000000..af4c5c79 --- /dev/null +++ b/2501-3000/2549-Count-Distinct-Numbers-on-Board/cpp-2549/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2549) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2549 main.cpp) diff --git a/2501-3000/2549-Count-Distinct-Numbers-on-Board/cpp-2549/main.cpp b/2501-3000/2549-Count-Distinct-Numbers-on-Board/cpp-2549/main.cpp new file mode 100644 index 00000000..dd7e64e0 --- /dev/null +++ b/2501-3000/2549-Count-Distinct-Numbers-on-Board/cpp-2549/main.cpp @@ -0,0 +1,25 @@ +/// Source : https://leetcode.com/problems/count-distinct-numbers-on-board/description/ +/// Author : liuyubobobo +/// Time : 2023-01-28 + +#include +#include + +using namespace std; + + +/// Math +/// Time Complexity: O(1) +/// Space Complexity: O(1) +class Solution { +public: + int distinctIntegers(int n) { + return n == 1 ? 1 : n - 1; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2550-Count-Collisions-of-Monkeys-on-a-Polygon/cpp-2550/CMakeLists.txt b/2501-3000/2550-Count-Collisions-of-Monkeys-on-a-Polygon/cpp-2550/CMakeLists.txt new file mode 100644 index 00000000..ba55a941 --- /dev/null +++ b/2501-3000/2550-Count-Collisions-of-Monkeys-on-a-Polygon/cpp-2550/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2550) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2550 main.cpp) diff --git a/2501-3000/2550-Count-Collisions-of-Monkeys-on-a-Polygon/cpp-2550/main.cpp b/2501-3000/2550-Count-Collisions-of-Monkeys-on-a-Polygon/cpp-2550/main.cpp new file mode 100644 index 00000000..f67abb2f --- /dev/null +++ b/2501-3000/2550-Count-Collisions-of-Monkeys-on-a-Polygon/cpp-2550/main.cpp @@ -0,0 +1,39 @@ +/// Source : https://leetcode.com/problems/count-collisions-of-monkeys-on-a-polygon/description/ +/// Author : liuyubobobo +/// Time : 2023-01-28 + +#include + +using namespace std; + + +/// Math +/// Time Complexity: O(logn) +/// Space Complexity: O(1) +class Solution { + +private: + const long long MOD = 1e9 + 7; + +public: + int monkeyMove(int n) { + return (quick_pow(2, n) - 2 + MOD) % MOD; + } + +private: + long long quick_pow(long long a, long long k) { + long long res = 1ll; + while (k) { + if (k & 1) res = res * a % MOD; + a = a * a % MOD; + k >>= 1; + } + return res % MOD; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2551-Put-Marbles-in-Bags/cpp-2551/CMakeLists.txt b/2501-3000/2551-Put-Marbles-in-Bags/cpp-2551/CMakeLists.txt new file mode 100644 index 00000000..0a4259ea --- /dev/null +++ b/2501-3000/2551-Put-Marbles-in-Bags/cpp-2551/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2551) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2551 main.cpp) diff --git a/2501-3000/2551-Put-Marbles-in-Bags/cpp-2551/main.cpp b/2501-3000/2551-Put-Marbles-in-Bags/cpp-2551/main.cpp new file mode 100644 index 00000000..5b315e00 --- /dev/null +++ b/2501-3000/2551-Put-Marbles-in-Bags/cpp-2551/main.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/put-marbles-in-bags/description/ +/// Author : liuyubobobo +/// Time : 2023-01-29 + +#include +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + long long putMarbles(vector& weights, int k) { + + int n = weights.size(); + + vector v; + for(int i = 0; i + 1 < n; i ++) v.push_back(weights[i] + weights[i + 1]); + sort(v.begin(), v.end()); + + long long maxv = 0, minv = 0; + for(int i = (int)v.size() - 1, j = 0; j < k - 1; j ++, i --) maxv += v[i]; + for(int i = 0, j = 0; j < k - 1; j ++, i ++) minv += v[i]; + + return maxv - minv; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2553-Separate-the-Digits-in-an-Array/cpp-2553/CMakeLists.txt b/2501-3000/2553-Separate-the-Digits-in-an-Array/cpp-2553/CMakeLists.txt new file mode 100644 index 00000000..25110586 --- /dev/null +++ b/2501-3000/2553-Separate-the-Digits-in-an-Array/cpp-2553/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2553) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2553 main.cpp) diff --git a/2501-3000/2553-Separate-the-Digits-in-an-Array/cpp-2553/main.cpp b/2501-3000/2553-Separate-the-Digits-in-an-Array/cpp-2553/main.cpp new file mode 100644 index 00000000..7a6acf3c --- /dev/null +++ b/2501-3000/2553-Separate-the-Digits-in-an-Array/cpp-2553/main.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/separate-the-digits-in-an-array/ +/// Author : liuyubobobo +/// Time : 2023-02-04 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(nlog(MAX_NUM)) +/// Space Complexity: O(1) +class Solution { +public: + vector separateDigits(vector& nums) { + + vector res; + for(int num: nums){ + vector digits = get_digits(num); + for(int e: digits) res.push_back(e); + } + return res; + } + +private: + vector get_digits(int x){ + vector res; + while(x) res.push_back(x % 10), x /= 10; + if(res.empty()) res.push_back(0); + reverse(res.begin(), res.end()); + return res; + } +}; + + +int main() { + std::cout << "Hello, World!" << std::endl; + return 0; +} diff --git a/2501-3000/2554-Maximum-Number-of-Integers-to-Choose-From-a-Range-I/cpp-2554/CMakeLists.txt b/2501-3000/2554-Maximum-Number-of-Integers-to-Choose-From-a-Range-I/cpp-2554/CMakeLists.txt new file mode 100644 index 00000000..932c1463 --- /dev/null +++ b/2501-3000/2554-Maximum-Number-of-Integers-to-Choose-From-a-Range-I/cpp-2554/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2554) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2554 main.cpp) diff --git a/2501-3000/2554-Maximum-Number-of-Integers-to-Choose-From-a-Range-I/cpp-2554/main.cpp b/2501-3000/2554-Maximum-Number-of-Integers-to-Choose-From-a-Range-I/cpp-2554/main.cpp new file mode 100644 index 00000000..b16c0b36 --- /dev/null +++ b/2501-3000/2554-Maximum-Number-of-Integers-to-Choose-From-a-Range-I/cpp-2554/main.cpp @@ -0,0 +1,41 @@ +/// Source : https://leetcode.com/problems/maximum-number-of-integers-to-choose-from-a-range-i/description/ +/// Author : liuyubobobo +/// Time : 2023-02-04 + +#include +#include +#include + +using namespace std; + + +/// Two Pointers +/// Time Complexity: O(|banned| * log|banned| + n + |banned|) +/// Space Complexity: O(1) +class Solution { +public: + int maxCount(vector& banned, int n, int maxSum) { + + sort(banned.begin(), banned.end()); + + int banned_index = 0, res = 0, sum = 0; + for(int i = 1; i <= n; i ++){ + if(banned_index < banned.size() && i == banned[banned_index]){ + while(banned_index < banned.size() && i == banned[banned_index]) + banned_index ++; + } + else if(sum + i > maxSum) break; + else{ + res ++; + sum += i; + } + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2555-Maximize-Win-From-Two-Segments/cpp-2555/CMakeLists.txt b/2501-3000/2555-Maximize-Win-From-Two-Segments/cpp-2555/CMakeLists.txt new file mode 100644 index 00000000..6fbe7afc --- /dev/null +++ b/2501-3000/2555-Maximize-Win-From-Two-Segments/cpp-2555/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2555) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2555 main.cpp) diff --git a/2501-3000/2555-Maximize-Win-From-Two-Segments/cpp-2555/main.cpp b/2501-3000/2555-Maximize-Win-From-Two-Segments/cpp-2555/main.cpp new file mode 100644 index 00000000..f9e8c47a --- /dev/null +++ b/2501-3000/2555-Maximize-Win-From-Two-Segments/cpp-2555/main.cpp @@ -0,0 +1,39 @@ +/// Source : https://leetcode.com/problems/maximize-win-from-two-segments/description/ +/// Author : liuyubobobo +/// Time : 2023-02-04 + +#include +#include +#include + +using namespace std; + + +/// DP + Binary Search +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + int maximizeWin(vector& pos, int k) { + + int n = pos.size(); + + vector dp(n + 1, 0); + int res = 0; + for(int i = n - 1; i >= 0; i --){ + auto iter = upper_bound(pos.begin() + i, pos.end(), pos[i] + k); + int r = (iter - pos.begin()); + int tres = r - i; + res = max(res, tres + dp[r]); + dp[i] = max(tres, dp[i + 1]); + } + return res; + } +}; + + +int main() { + + + return 0; +} diff --git a/2501-3000/2556-Disconnect-Path-in-a-Binary-Matrix-by-at-Most-One-Flip/cpp-2556/CMakeLists.txt b/2501-3000/2556-Disconnect-Path-in-a-Binary-Matrix-by-at-Most-One-Flip/cpp-2556/CMakeLists.txt new file mode 100644 index 00000000..fbad678b --- /dev/null +++ b/2501-3000/2556-Disconnect-Path-in-a-Binary-Matrix-by-at-Most-One-Flip/cpp-2556/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2556) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2556 main.cpp) diff --git a/2501-3000/2556-Disconnect-Path-in-a-Binary-Matrix-by-at-Most-One-Flip/cpp-2556/main.cpp b/2501-3000/2556-Disconnect-Path-in-a-Binary-Matrix-by-at-Most-One-Flip/cpp-2556/main.cpp new file mode 100644 index 00000000..fad86949 --- /dev/null +++ b/2501-3000/2556-Disconnect-Path-in-a-Binary-Matrix-by-at-Most-One-Flip/cpp-2556/main.cpp @@ -0,0 +1,93 @@ +/// Source : https://leetcode.com/problems/disconnect-path-in-a-binary-matrix-by-at-most-one-flip/description/ +/// Author : liuyubobobo +/// Time : 2023-02-05 + +#include +#include +#include + +using namespace std; + + +/// Tarjan critical points +/// Time Complexity: O(R * C) +/// Space Complexity: O(R * C) +class TarjanCriticalPoint{ + +private: + int n; + vector> g; + set critical_points; + +public: + TarjanCriticalPoint(int n): n(n), g(n){} + + void add_edge(int u, int v){ + g[u].insert(v); + g[v].insert(u); + } + + vector get_critical_points(){ + return vector(critical_points.begin(), critical_points.end()); + } + + bool solve(){ + + critical_points.clear(); + + vector ids(n, -1), low(n, -1); + int id = 0; + return dfs(0, -1, id, ids, low); + } + + bool dfs(int u, int p, int& id, vector& ids, vector& low){ + + bool ret = (u == n - 1); + ids[u] = low[u] = id ++; + + int children = 0; + for(int v: g[u]){ + if(v == p) continue; + if(ids[v] == -1){ + if(dfs(v, u, id, ids, low)) ret = true; + low[u] = min(low[u], low[v]); + children ++; + + if(low[v] >= ids[u] && p != -1) + critical_points.insert(u); + } + else + low[u] = min(low[u], ids[v]); + } + + if(p == -1 && children > 1) + critical_points.insert(u); + return ret; + } +}; + +class Solution { +public: + bool isPossibleToCutPath(vector>& grid) { + + int R = grid.size(), C = grid[0].size(); + + TarjanCriticalPoint cp(R * C); + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++){ + if(!grid[i][j]) continue; + int u = i * C + j; + + if(j + 1 < C && grid[i][j + 1]) cp.add_edge(u, i * C + j + 1); + if(i + 1 < R && grid[i + 1][j]) cp.add_edge(u, (i + 1) * C + j); + } + + return !cp.solve() || !cp.get_critical_points().empty(); + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2557-Maximum-Number-of-Integers-to-Choose-From-a-Range-II/cpp-2557/CMakeLists.txt b/2501-3000/2557-Maximum-Number-of-Integers-to-Choose-From-a-Range-II/cpp-2557/CMakeLists.txt new file mode 100644 index 00000000..365f4d94 --- /dev/null +++ b/2501-3000/2557-Maximum-Number-of-Integers-to-Choose-From-a-Range-II/cpp-2557/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2557) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2557 main.cpp) diff --git a/2501-3000/2557-Maximum-Number-of-Integers-to-Choose-From-a-Range-II/cpp-2557/main.cpp b/2501-3000/2557-Maximum-Number-of-Integers-to-Choose-From-a-Range-II/cpp-2557/main.cpp new file mode 100644 index 00000000..b03cad5a --- /dev/null +++ b/2501-3000/2557-Maximum-Number-of-Integers-to-Choose-From-a-Range-II/cpp-2557/main.cpp @@ -0,0 +1,41 @@ +/// Source : https://leetcode.com/problems/maximum-number-of-integers-to-choose-from-a-range-ii/description/ +/// Author : liuyubobobo +/// Time : 2023-02-05 + +#include +#include + +using namespace std; + + +/// Two Pointers +/// Time Complexity: O(|banned| * log|banned| + n + |banned|) +/// Space Complexity: O(1) +class Solution { +public: + int maxCount(vector& banned, int n, long long maxSum) { + + sort(banned.begin(), banned.end()); + + int banned_index = 0, res = 0; + long long sum = 0; + for(int i = 1; i <= n; i ++){ + if(banned_index < banned.size() && i == banned[banned_index]){ + while(banned_index < banned.size() && i == banned[banned_index]) + banned_index ++; + } + else if(sum + i > maxSum) break; + else{ + res ++; + sum += i; + } + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2558-Take-Gifts-From-the-Richest-Pile/cpp-2558/CMakeLists.txt b/2501-3000/2558-Take-Gifts-From-the-Richest-Pile/cpp-2558/CMakeLists.txt new file mode 100644 index 00000000..f864e0a0 --- /dev/null +++ b/2501-3000/2558-Take-Gifts-From-the-Richest-Pile/cpp-2558/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2558) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2558 main.cpp) diff --git a/2501-3000/2558-Take-Gifts-From-the-Richest-Pile/cpp-2558/main.cpp b/2501-3000/2558-Take-Gifts-From-the-Richest-Pile/cpp-2558/main.cpp new file mode 100644 index 00000000..b1c9f9f3 --- /dev/null +++ b/2501-3000/2558-Take-Gifts-From-the-Richest-Pile/cpp-2558/main.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/take-gifts-from-the-richest-pile/description/ +/// Author : liuyubobobo +/// Time : 2023-02-05 + +#include +#include +#include + +using namespace std; + + +/// Using PQ +/// Time Complexity: O(klogn + nlogn) +/// Space Complexity: O(n) +class Solution { +public: + long long pickGifts(vector& gifts, int k) { + + priority_queue pq; + for(int e: gifts) pq.push(e); + for(int i = 0; i < k; i ++){ + int e = pq.top(); pq.pop(); + int x = sqrt(e); + pq.push(x); + } + + long long res = 0; + while(!pq.empty()){ + int e = pq.top(); pq.pop(); + res += e; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2559-Count-Vowel-Strings-in-Ranges/cpp-2559/CMakeLists.txt b/2501-3000/2559-Count-Vowel-Strings-in-Ranges/cpp-2559/CMakeLists.txt new file mode 100644 index 00000000..fe7a7609 --- /dev/null +++ b/2501-3000/2559-Count-Vowel-Strings-in-Ranges/cpp-2559/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2559) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2559 main.cpp) diff --git a/2501-3000/2559-Count-Vowel-Strings-in-Ranges/cpp-2559/main.cpp b/2501-3000/2559-Count-Vowel-Strings-in-Ranges/cpp-2559/main.cpp new file mode 100644 index 00000000..8ce01190 --- /dev/null +++ b/2501-3000/2559-Count-Vowel-Strings-in-Ranges/cpp-2559/main.cpp @@ -0,0 +1,45 @@ +/// Source : https://leetcode.com/problems/count-vowel-strings-in-ranges/description/ +/// Author : liuyubobobo +/// Time : 2023-02-05 + +#include +#include + +using namespace std; + + +/// Presum +/// Time Complexity: O(n + q) +/// Space Complexity: O(n) +class Solution { +public: + vector vowelStrings(vector& words, vector>& queries) { + + int n = words.size(); + vector v(n, 0); + for(int i = 0; i < n; i ++) + v[i] = is_vowel(words[i][0]) && is_vowel(words[i].back()); + + vector presum(n + 1, 0); + for(int i = 0; i < n; i ++) + presum[i + 1] = presum[i] + v[i]; + + vector res(queries.size()); + for(int i = 0; i < queries.size(); i ++){ + int l = queries[i][0], r = queries[i][1]; + res[i] = presum[r + 1] - presum[l]; + } + return res; + } + +private: + bool is_vowel(char c){ + return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2560-House-Robber-IV/cpp-2560/CMakeLists.txt b/2501-3000/2560-House-Robber-IV/cpp-2560/CMakeLists.txt new file mode 100644 index 00000000..decd4afc --- /dev/null +++ b/2501-3000/2560-House-Robber-IV/cpp-2560/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2560) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2560 main.cpp) diff --git a/2501-3000/2560-House-Robber-IV/cpp-2560/main.cpp b/2501-3000/2560-House-Robber-IV/cpp-2560/main.cpp new file mode 100644 index 00000000..accee50f --- /dev/null +++ b/2501-3000/2560-House-Robber-IV/cpp-2560/main.cpp @@ -0,0 +1,44 @@ +/// Source : https://leetcode.com/problems/house-robber-iv/description/ +/// Author : liuyubobobo +/// Time : 2023-02-05 + +#include +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(nlog(max_num)) +/// Space Complexity: O(1) +class Solution { +public: + int minCapability(vector& nums, int k) { + + int n = nums.size(); + int l = 0, r = *max_element(nums.begin(), nums.end()); + while(l < r){ + int mid = (l + r) / 2; + if(ok(n, nums, mid, k)) r = mid; + else l = mid + 1; + } + return l; + } + +private: + bool ok(int n, const vector& nums, int v, int k){ + + int cnt = 0; + for(int i = 0; i < n; i ++) + if(nums[i] <= v) cnt ++, i ++; + return cnt >= k; + } +}; + + +int main() { + + + return 0; +} diff --git a/2501-3000/2561-Rearranging-Fruits/cpp-2561/CMakeLists.txt b/2501-3000/2561-Rearranging-Fruits/cpp-2561/CMakeLists.txt new file mode 100644 index 00000000..74465431 --- /dev/null +++ b/2501-3000/2561-Rearranging-Fruits/cpp-2561/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2561) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2561 main.cpp) diff --git a/2501-3000/2561-Rearranging-Fruits/cpp-2561/main.cpp b/2501-3000/2561-Rearranging-Fruits/cpp-2561/main.cpp new file mode 100644 index 00000000..429c95e3 --- /dev/null +++ b/2501-3000/2561-Rearranging-Fruits/cpp-2561/main.cpp @@ -0,0 +1,94 @@ +/// Source : https://leetcode.com/problems/rearranging-fruits/description/ +/// Author : liuyubobobo +/// Time : 2023-02-05 + +#include +#include +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(n1logn1 + n2logn2) +/// Space Complexity: O(n1 + n2) +class Solution { +public: + long long minCost(vector& basket1, vector& basket2) { + + int n = basket1.size(); + sort(basket1.begin(), basket1.end()); + sort(basket2.begin(), basket2.end()); + + priority_queue, greater> pq; + for(int e: basket1) pq.push(e); + for(int e: basket2) pq.push(e); + + vector target; + while(!pq.empty()){ + int a = pq.top(); pq.pop(); + int b = pq.top(); pq.pop(); + if(a != b) return -1; + target.push_back(a); + } + + deque change1 = get_change(n, basket1, target); + deque change2 = get_change(n, basket2, target); + + if(change1.size() != change2.size()) return -1; + int len = change1.size(); + if(len == 0) return 0; + + long long res = 0, min_cost = min(basket1[0], basket2[0]); + while(!change1.empty()){ + if(min_cost * 2ll < min(change1.front(), change2.front())){ + res += min_cost * 2ll; + change1.pop_back(), change2.pop_back(); + } + else if(change1.front() <= change2.front()){ + res += change1.front(); + change1.pop_front(), change2.pop_back(); + } + else{ + res += change2.front(); + change2.pop_front(), change1.pop_back(); + } + } + return res; + } + +private: + deque get_change(int n, const vector& a, const vector& b){ + + deque res; + for(int i = 0, j = 0; i < n;){ + if(j == n) res.push_back(a[i ++]); + else if(a[i] < b[j]) res.push_back(a[i ++]); + else if(a[i] == b[j]) i ++, j ++; + else if(a[i] > b[j]) j ++; + } + return res; + } +}; + + +int main() { + + vector basket1_1 = {4, 4, 4, 4, 3}; + vector basket1_2 = {5, 5, 5, 5, 3}; + cout << Solution().minCost(basket1_1, basket1_2) << '\n'; + // 8 + + vector basket2_1 = {84,80,43,8,80,88,43,14,100,88}; + vector basket2_2 = {32,32,42,68,68,100,42,84,14,8}; + cout << Solution().minCost(basket2_1, basket2_2) << '\n'; + // 48 + + vector basket3_1 = {3350,1104,2004,1577,1365,2088,2249,1948,2621,750,31,2004,1749,3365,3350,3843,3365,1656,3168,3106,2820,3557,1095,2446,573,2464,2172,1326,2712,467,1104,1446,1577,53,2492,2638,1200,2997,3454,2492,1926,1452,2712,446,2997,2820,750,2529,3847,656,272,3873,530,1749,1743,251,3847,31,251,515,2858,126,2491}; + vector basket3_2 = {530,1920,2529,2317,1969,2317,1095,2249,2858,2636,3772,53,3106,2638,1267,1926,2882,515,3772,1969,3454,2446,656,2621,1365,1743,3557,1656,3447,446,1098,1446,467,2636,1088,1098,2882,1088,1326,644,3873,3843,3926,1920,2464,2088,205,1200,1267,272,925,925,2172,2491,3168,644,1452,573,1948,3926,205,126,3447}; + cout << Solution().minCost(basket3_1, basket3_2) << '\n'; + // 837 + + return 0; +} diff --git a/2501-3000/2562-Find-the-Array-Concatenation-Value/cpp-2562/CMakeLists.txt b/2501-3000/2562-Find-the-Array-Concatenation-Value/cpp-2562/CMakeLists.txt new file mode 100644 index 00000000..13f9654c --- /dev/null +++ b/2501-3000/2562-Find-the-Array-Concatenation-Value/cpp-2562/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2562) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2562 main.cpp) diff --git a/2501-3000/2562-Find-the-Array-Concatenation-Value/cpp-2562/main.cpp b/2501-3000/2562-Find-the-Array-Concatenation-Value/cpp-2562/main.cpp new file mode 100644 index 00000000..17839784 --- /dev/null +++ b/2501-3000/2562-Find-the-Array-Concatenation-Value/cpp-2562/main.cpp @@ -0,0 +1,36 @@ +/// Source : https://leetcode.com/problems/find-the-array-concatenation-value/description/ +/// Author : liuyubobobo +/// Time : 2023-02-11 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(nlog(MAX_NUMS)) +/// Space Complexity: O(log(MAX_NUMS)) +class Solution { +public: + long long findTheArrayConcVal(vector& nums) { + + int n = nums.size(); + long long res = 0; + for(int i = 0, j = n - 1; i <= j; i ++, j --){ + if(i == j) res += nums[i]; + else{ + long long a = nums[i], b = nums[j]; + string a_str = to_string(a), b_str = to_string(b); + res += atoll((a_str + b_str).c_str()); + } + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2563-Count-the-Number-of-Fair-Pairs/cpp-2563/CMakeLists.txt b/2501-3000/2563-Count-the-Number-of-Fair-Pairs/cpp-2563/CMakeLists.txt new file mode 100644 index 00000000..c49b6754 --- /dev/null +++ b/2501-3000/2563-Count-the-Number-of-Fair-Pairs/cpp-2563/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2563) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2563 main.cpp) diff --git a/2501-3000/2563-Count-the-Number-of-Fair-Pairs/cpp-2563/main.cpp b/2501-3000/2563-Count-the-Number-of-Fair-Pairs/cpp-2563/main.cpp new file mode 100644 index 00000000..6d488e01 --- /dev/null +++ b/2501-3000/2563-Count-the-Number-of-Fair-Pairs/cpp-2563/main.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/count-the-number-of-fair-pairs/description/ +/// Author : liuyubobobo +/// Time : 2023-02-11 + +#include +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + long long countFairPairs(vector& nums, int lower, int upper) { + + sort(nums.begin(), nums.end()); + long long res = 0; + for(int i = 0; i < nums.size(); i ++){ + auto iter1 = lower_bound(nums.begin() + (i + 1), nums.end(), lower - nums[i]); + auto iter2 = upper_bound(nums.begin() + (i + 1), nums.end(), upper - nums[i]); + res += iter2 - iter1; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2564-Substring-XOR-Queries/cpp-2564/CMakeLists.txt b/2501-3000/2564-Substring-XOR-Queries/cpp-2564/CMakeLists.txt new file mode 100644 index 00000000..f388d47a --- /dev/null +++ b/2501-3000/2564-Substring-XOR-Queries/cpp-2564/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2564) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2564 main.cpp) diff --git a/2501-3000/2564-Substring-XOR-Queries/cpp-2564/main.cpp b/2501-3000/2564-Substring-XOR-Queries/cpp-2564/main.cpp new file mode 100644 index 00000000..b1952538 --- /dev/null +++ b/2501-3000/2564-Substring-XOR-Queries/cpp-2564/main.cpp @@ -0,0 +1,56 @@ +/// Source : https://leetcode.com/problems/substring-xor-queries/description/ +/// Author : liuyubobobo +/// Time : 2023-02-11 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector> substringXorQueries(string s, vector>& queries) { + + int n = s.size(), q = queries.size(); + vector> res(q, {-1, -1}); + map> res2index; + for(int i = 0; i < q; i ++){ + int first = queries[i][0], second = queries[i][1]; + int val = second ^ first; + + res2index[val].push_back(i); + } + + for(int len = 1; len <= min(31, n); len ++){ + long long cur = 0; + for(int i = 0; i < len - 1; i ++) cur = cur * 2 + (s[i] - '0'); + for(int i = len - 1; i < n; i ++){ + cur = cur * 2 + (s[i] - '0'); + auto iter = res2index.find(cur); + if(iter != res2index.end()){ + for(int index: iter->second) res[index] = {i - (len - 1), i}; + res2index.erase(iter); + } + + if(s[i - (len - 1)] == '1') cur -= (1ll << (len - 1)); + } + } + return res; + } +}; + +int main() { + + string s1 = "101101"; + vector> queries1 = {{0, 5}, {1, 2}}; + Solution().substringXorQueries(s1, queries1); + + return 0; +} diff --git a/2501-3000/2565-Subsequence-With-the-Minimum-Score/cpp-2565/CMakeLists.txt b/2501-3000/2565-Subsequence-With-the-Minimum-Score/cpp-2565/CMakeLists.txt new file mode 100644 index 00000000..d87fa24d --- /dev/null +++ b/2501-3000/2565-Subsequence-With-the-Minimum-Score/cpp-2565/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2565) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2565 main.cpp) diff --git a/2501-3000/2565-Subsequence-With-the-Minimum-Score/cpp-2565/main.cpp b/2501-3000/2565-Subsequence-With-the-Minimum-Score/cpp-2565/main.cpp new file mode 100644 index 00000000..22dc670a --- /dev/null +++ b/2501-3000/2565-Subsequence-With-the-Minimum-Score/cpp-2565/main.cpp @@ -0,0 +1,41 @@ +/// Source : https://leetcode.com/problems/subsequence-with-the-minimum-score/description/ +/// Author : liuyubobobo +/// Time : 2023-02-12 + +#include +#include + +using namespace std; + + +/// Pre and Suf +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int minimumScore(string s, string t) { + + int sn = s.size(), tn = t.size(); + + vector pre(sn, 0), suf(sn, 0); + for(int i = 0, j = 0; i < sn; i ++){ + if(j < tn && s[i] == t[j]) pre[i] = ++j; + else if(i > 0) pre[i] = pre[i - 1]; + } + for(int i = sn - 1, j = tn - 1; i >= 0; i --){ + if(j >= 0 && s[i] == t[j]) suf[i] = tn - (j --); + else if(i + 1 < sn) suf[i] = suf[i + 1]; + } + + int res = min(tn - suf[0], tn - pre.back()); + for(int i = 0; i + 1 < sn; i ++) + res = min(res, tn - pre[i] - suf[i + 1]); + return max(res, 0); + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2566-Maximum-Difference-by-Remapping-a-Digit/cpp-2566/CMakeLists.txt b/2501-3000/2566-Maximum-Difference-by-Remapping-a-Digit/cpp-2566/CMakeLists.txt new file mode 100644 index 00000000..957e935e --- /dev/null +++ b/2501-3000/2566-Maximum-Difference-by-Remapping-a-Digit/cpp-2566/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2566) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2566 main.cpp) diff --git a/2501-3000/2566-Maximum-Difference-by-Remapping-a-Digit/cpp-2566/main.cpp b/2501-3000/2566-Maximum-Difference-by-Remapping-a-Digit/cpp-2566/main.cpp new file mode 100644 index 00000000..7bc05ece --- /dev/null +++ b/2501-3000/2566-Maximum-Difference-by-Remapping-a-Digit/cpp-2566/main.cpp @@ -0,0 +1,43 @@ +/// Source : https://leetcode.com/problems/maximum-difference-by-remapping-a-digit/description/ +/// Author : liuyubobobo +/// Time : 2023-02-19 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(10 * 10 * log(num)) +/// Space Complexity: O(log(num)) +class Solution { +public: + int minMaxDifference(int num) { + + int maxv = INT_MIN, minv = INT_MAX; + for(int from = 0; from <= 9; from ++) + for(int to = 0; to <= 9; to ++){ + int new_num = replace(num, from, to); + maxv = max(maxv, new_num); + minv = min(minv, new_num); + } + return maxv - minv; + } + +private: + int replace(int num, int from, int to) { + + string num_str = to_string(num); + for(char& c: num_str) + if(c == (char)(from + '0')) + c = (char)(to + '0'); + return atoi(num_str.c_str()); + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2567-Minimum-Score-by-Changing-Two-Elements/cpp-2567/CMakeLists.txt b/2501-3000/2567-Minimum-Score-by-Changing-Two-Elements/cpp-2567/CMakeLists.txt new file mode 100644 index 00000000..902dee05 --- /dev/null +++ b/2501-3000/2567-Minimum-Score-by-Changing-Two-Elements/cpp-2567/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2567) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2567 main.cpp) diff --git a/2501-3000/2567-Minimum-Score-by-Changing-Two-Elements/cpp-2567/main.cpp b/2501-3000/2567-Minimum-Score-by-Changing-Two-Elements/cpp-2567/main.cpp new file mode 100644 index 00000000..3cd462d7 --- /dev/null +++ b/2501-3000/2567-Minimum-Score-by-Changing-Two-Elements/cpp-2567/main.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/minimum-score-by-changing-two-elements/description/ +/// Author : liuyubobobo +/// Time : 2023-02-20 + +#include +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + int minimizeSum(vector& nums) { + + sort(nums.begin(), nums.end()); + + int n = nums.size(); + return min3(nums[n - 2] - nums[1], nums[n - 1] - nums[2], nums[n - 3] - nums[0]); + } + +private: + int min3(int a, int b, int c) { + return min(a, min(b, c)); + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2568-Minimum-Impossible-OR/cpp-2568/CMakeLists.txt b/2501-3000/2568-Minimum-Impossible-OR/cpp-2568/CMakeLists.txt new file mode 100644 index 00000000..6a782e74 --- /dev/null +++ b/2501-3000/2568-Minimum-Impossible-OR/cpp-2568/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2568) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2568 main.cpp) diff --git a/2501-3000/2568-Minimum-Impossible-OR/cpp-2568/main.cpp b/2501-3000/2568-Minimum-Impossible-OR/cpp-2568/main.cpp new file mode 100644 index 00000000..15418261 --- /dev/null +++ b/2501-3000/2568-Minimum-Impossible-OR/cpp-2568/main.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/minimum-impossible-or/description/ +/// Author : liuyubobobo +/// Time : 2023-02-20 + +#include +#include +#include + +using namespace std; + + +/// Math +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + int minImpossibleOR(vector& nums) { + + sort(nums.begin(), nums.end()); + for(int i = 0;;i ++){ + auto iter = lower_bound(nums.begin(), nums.end(), 1 << i); + if(iter == nums.end() || *iter != (1 << i)) + return 1 < +#include +#include + +using namespace std; + + +/// Segment Tree +/// Time Complexity: O(nlogn + qlogn) +/// Space Complexity: O(n) +template +class SegmentTree{ + +private: + int n; + vector tree, lazy; + T (*combine)(T a, T b); + +public: + SegmentTree(const vector& data, T (*combine)(T a, T b)): + n(data.size()), tree(4 * n, 0), lazy(4 * n, 0){ + this->combine = combine; + buildSegTree(0, 0, n - 1, data); + } + + SegmentTree(int n, T (*combine)(T a, T b)): n(n), tree(4 * n, 0), lazy(4 * n, 0){ + this->combine = combine; + } + + void flip(int uL, int uR){ + assert(0 <= uL && uL < n); + assert(0 <= uR && uR < n); + assert(uL <= uR); + flip(0, 0, n-1, uL, uR); + } + + T query(int qL, int qR){ + assert(0 <= qL && qL < n); + assert(0 <= qR && qR < n); + assert(qL <= qR); + return query(0, 0, n - 1, qL, qR); + } + +private: + void buildSegTree(int treeID, int l, int r, const vector& data){ + + if(l == r){ + tree[treeID] = data[l]; + return; + } + + int mid = (l + r) / 2; + buildSegTree(treeID * 2 + 1, l, mid, data); + buildSegTree(treeID * 2 + 2, mid + 1, r, data); + tree[treeID] = combine(tree[treeID * 2 + 1], tree[treeID * 2 + 2]); + return; + } + + void flip(int treeID, int treeL, int treeR, int uL, int uR){ + + if(uL > treeR || uR < treeL) return; + + if(uL <= treeL && treeR <= uR){ + + int len = treeR - treeL + 1; + tree[treeID] = len - tree[treeID]; + lazy[treeID] ++; + + return; + } + + if(lazy[treeID]) + push(treeID, treeL, treeR); + + int mid = (treeL + treeR) / 2; + flip(2 * treeID + 1, treeL, mid, uL, uR); + flip(2 * treeID + 2, mid + 1, treeR, uL, uR); + tree[treeID] = combine(tree[treeID * 2 + 1], tree[treeID * 2 + 2]); + return; + } + + T query(int treeID, int treeL, int treeR, int qL, int qR){ + + if(qL <= treeL && treeR <= qR) + return tree[treeID]; + + if(lazy[treeID]) + push(treeID, treeL, treeR); + + int mid = (treeL + treeR) / 2; + if(qR <= mid) return query(2 * treeID + 1, treeL, mid, qL, qR); + if(qL >= mid + 1) return query(2 * treeID + 2, mid + 1, treeR, qL, qR); + + T resl = query(2 * treeID + 1, treeL, mid, qL, qR); + T resr = query(2 * treeID + 2, mid + 1, treeR, qL, qR); + T res = combine(resl, resr); + return res; + } + +private: + void push(int treeID, int treeL, int treeR){ + + if(treeL == treeR) return; + + T v = lazy[treeID]; + + int mid = (treeL + treeR) / 2; + int tn = treeR - treeL + 1, tnl = mid - treeL + 1, tnr = tn - tnl; + + if(v & 1) { + tree[treeID * 2 + 1] = tnl - tree[treeID * 2 + 1]; + tree[treeID * 2 + 2] = tnr - tree[treeID * 2 + 2]; + } + + lazy[treeID * 2 + 1] += v; + lazy[treeID * 2 + 2] += v; + + lazy[treeID] = 0; + } +}; + +class Solution { +public: + vector handleQuery(vector& nums1, vector& nums2, vector>& queries) { + + int n = nums1.size(); + + SegmentTree seg_tree(nums1, [](int a, int b){return a + b;}); + + long long sum = 0; + for(int e: nums2) sum += e; + + vector res; + for(const vector& query: queries){ +// for(int i = 0; i < n; i ++) cout << seg_tree.query(i, i) << " "; cout << '\n'; + int type = query[0]; + if(type == 1){ + int l = query[1], r = query[2]; + seg_tree.flip(l, r); + } + else if(type == 2){ + long long p = query[1]; + sum += p * seg_tree.query(0, n - 1); + } + else res.push_back(sum); + } + return res; + } +}; + + +void print_vec(const vector& res){ + for(long long e: res) cout << e << " "; cout << '\n'; +} + +int main() { + + vector nums1_1 = {1, 0, 1}, nums1_2 = {0, 0, 0}; + vector>queries1 = {{1, 1, 1}, {2, 1, 0}, {3, 0, 0}}; + print_vec(Solution().handleQuery(nums1_1, nums1_2, queries1)); + // 3 + + vector nums2_1 = {0, 1, 0, 0, 0, 0}, nums2_2 = {14, 4, 13, 13, 47, 18}; + vector>queries2 = {{3,0,0},{1,4,4},{1,1,4},{1,3,4},{3,0,0},{2,5,0},{1,1,3},{2,16,0},{2,10,0},{3,0,0},{3,0,0},{2,6,0}}; + print_vec(Solution().handleQuery(nums2_1, nums2_2, queries2)); + // 109,109,197,197 + + return 0; +} diff --git a/2501-3000/2570-Merge-Two-2D-Arrays-by-Summing-Values/cpp-2570/CMakeLists.txt b/2501-3000/2570-Merge-Two-2D-Arrays-by-Summing-Values/cpp-2570/CMakeLists.txt new file mode 100644 index 00000000..5fcbddbf --- /dev/null +++ b/2501-3000/2570-Merge-Two-2D-Arrays-by-Summing-Values/cpp-2570/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2570) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2570 main.cpp) diff --git a/2501-3000/2570-Merge-Two-2D-Arrays-by-Summing-Values/cpp-2570/main.cpp b/2501-3000/2570-Merge-Two-2D-Arrays-by-Summing-Values/cpp-2570/main.cpp new file mode 100644 index 00000000..b512af34 --- /dev/null +++ b/2501-3000/2570-Merge-Two-2D-Arrays-by-Summing-Values/cpp-2570/main.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/merge-two-2d-arrays-by-summing-values/description/ +/// Author : liuyubobobo +/// Time : 2023-02-20 + +#include +#include + +using namespace std; + + +/// Merge +/// Time Complexity: O(n1 + n2) +/// Space Complexity: O(1) +class Solution { +public: + vector> mergeArrays(vector>& nums1, vector>& nums2) { + + vector> res; + int n1 = nums1.size(), n2 = nums2.size(); + for(int i = 0, j = 0; i < n1 || j < n2;){ + if(i == n1) res.push_back(nums2[j++]); + else if(j == n2) res.push_back(nums1[i++]); + else if(nums1[i][0] < nums2[j][0]) res.push_back(nums1[i++]); + else if(nums1[i][0] > nums2[j][0]) res.push_back(nums2[j++]); + else res.push_back({nums1[i][0], nums1[i ++][1] + nums2[j ++][1]}); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2571-Minimum-Operations-to-Reduce-an-Integer-to-0/cpp-2571/CMakeLists.txt b/2501-3000/2571-Minimum-Operations-to-Reduce-an-Integer-to-0/cpp-2571/CMakeLists.txt new file mode 100644 index 00000000..f51708f0 --- /dev/null +++ b/2501-3000/2571-Minimum-Operations-to-Reduce-an-Integer-to-0/cpp-2571/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2571) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2571 main.cpp) diff --git a/2501-3000/2571-Minimum-Operations-to-Reduce-an-Integer-to-0/cpp-2571/main.cpp b/2501-3000/2571-Minimum-Operations-to-Reduce-an-Integer-to-0/cpp-2571/main.cpp new file mode 100644 index 00000000..24ee4844 --- /dev/null +++ b/2501-3000/2571-Minimum-Operations-to-Reduce-an-Integer-to-0/cpp-2571/main.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/minimum-operations-to-reduce-an-integer-to-0/description/ +/// Author : liuyubobobo +/// Time : 2023-02-20 + +#include +#include + +using namespace std; + + +/// Memoization +/// Time Complexity: O(logn) +/// Space Complexity: O(logn) +class Solution { +public: + int minOperations(int n) { + + vector v; + while(n) v.push_back(n & 1), n >>= 1; + + vector> dp(v.size(), vector(2, 0)); + return dfs(v, 0, 0, dp); + } + +private: + int dfs(const vector& v, int index, int last, vector>& dp){ + + if(index == v.size()) return last == 1 ? 2 : 0; + + if(dp[index][last] != 0) return dp[index][last]; + + int res = INT_MAX; + if(last == 0){ + if(v[index] == 0) res = min(res, dfs(v, index + 1, 0, dp)); + else{ + res = min(res, dfs(v, index + 1, 1, dp)); + res = min(res, dfs(v, index + 1, 0, dp) + 1); + } + } + else{ + if(v[index] == 0){ + res = min(res, dfs(v, index + 1, 0, dp) + 2); + res = min(res, dfs(v, index + 1, 1, dp) + 1); + } + else res = min(res, dfs(v, index + 1, 1, dp)); + } + return dp[index][last] = res; + } +}; + +int main() { + std::cout << "Hello, World!" << std::endl; + return 0; +} diff --git a/2501-3000/2572-Count-the-Number-of-Square-Free-Subsets/cpp-2572/CMakeLists.txt b/2501-3000/2572-Count-the-Number-of-Square-Free-Subsets/cpp-2572/CMakeLists.txt new file mode 100644 index 00000000..6c6290a0 --- /dev/null +++ b/2501-3000/2572-Count-the-Number-of-Square-Free-Subsets/cpp-2572/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2572) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2572 main.cpp) diff --git a/2501-3000/2572-Count-the-Number-of-Square-Free-Subsets/cpp-2572/main.cpp b/2501-3000/2572-Count-the-Number-of-Square-Free-Subsets/cpp-2572/main.cpp new file mode 100644 index 00000000..a778d533 --- /dev/null +++ b/2501-3000/2572-Count-the-Number-of-Square-Free-Subsets/cpp-2572/main.cpp @@ -0,0 +1,68 @@ +/// Source : https://leetcode.com/problems/count-the-number-of-square-free-subsets/description/ +/// Author : liuyubobobo +/// Time : 2023-02-22 + +#include +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(n * 2^10 + 2^20) +/// Space Complexity: O(2^10) +class Solution { + +private: + const vector primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29}; + const int prime_sz = primes.size(); + const long long MOD = 1e9 + 7; + +public: + int squareFreeSubsets(vector& nums) { + + int n = nums.size(), ones = 0; + vector cnt(1 << prime_sz, 0); + for(int num: nums){ + if(contain_square_factor(num)) continue; + if(num == 1){ ones ++; continue;} + int mask = 0; + for(int i = 0; i < prime_sz; i ++) + if(num % primes[i] == 0) + mask |= (1 << i); + cnt[mask] ++; + } + + vector dp(1 << prime_sz, 0); + dp[0] = 1; + for(int mask = 1; mask < (1 << prime_sz); mask ++) { + for(int submask = mask; submask >= 1; submask --) + if((submask & mask) == submask && __builtin_ffs(submask) == __builtin_ffs(mask)) + dp[mask] += dp[mask - submask] * cnt[submask]; + dp[mask] %= MOD; + } + long long res = accumulate(dp.begin(), dp.end(), 0LL) % MOD; + + long long ones_res = 1; + for(int i = 0; i < ones; i ++) ones_res = ones_res * 2 % MOD; + return (res * ones_res % MOD - 1 + MOD) % MOD; + } + +private: + bool contain_square_factor(int num){ + for(int prime: primes) + if(num % (prime * prime) == 0) return true; + return false; + } +}; + + +int main() { + + vector nums1 = {3, 4, 4, 5}; + cout << Solution().squareFreeSubsets(nums1) << endl; + // 3 + + return 0; +} diff --git a/2501-3000/2573-Find-the-String-with-LCP/cpp-2573/CMakeLists.txt b/2501-3000/2573-Find-the-String-with-LCP/cpp-2573/CMakeLists.txt new file mode 100644 index 00000000..d080518b --- /dev/null +++ b/2501-3000/2573-Find-the-String-with-LCP/cpp-2573/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2573) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2573 main.cpp) diff --git a/2501-3000/2573-Find-the-String-with-LCP/cpp-2573/main.cpp b/2501-3000/2573-Find-the-String-with-LCP/cpp-2573/main.cpp new file mode 100644 index 00000000..d6a704c9 --- /dev/null +++ b/2501-3000/2573-Find-the-String-with-LCP/cpp-2573/main.cpp @@ -0,0 +1,96 @@ +/// Source : https://leetcode.com/problems/find-the-string-with-lcp/description/ +/// Author : liuyubobobo +/// Time : 2023-02-22 + +#include +#include + +using namespace std; + + +/// Construction and LCP +/// Time Complexity: O(n^2) +/// Space Complexity: O(n^2) +class UF{ + +private: + vector parent; + +public: + UF(int n) : parent(n){ + for(int i = 0 ; i < n ; i ++) + parent[i] = i; + } + + int find(int p){ + if(p != parent[p]) + parent[p] = find(parent[p]); + return parent[p]; + } + + bool is_connected(int p, int q){ + return find(p) == find(q); + } + + void union_elements(int p, int q){ + + int p_root = find(p), q_root = find(q); + + if(p_root == q_root) return; + + parent[p_root] = q_root; + } +}; + +class Solution { +public: + string findTheString(vector>& lcp) { + + int n = lcp.size(); + UF uf(n); + for(int i = 0 ; i < n; i ++) + for(int j = 0 ; j < n; j ++) + if(lcp[i][j] >= 1) + uf.union_elements(i, j); + + vector parent2char(n, ' '); + char next_char = 'a'; + string res(n, ' '); + bool ok = true; + for(int i = 0 ; i < n && ok; i ++){ + int p = uf.find(i); + if(parent2char[p] == ' '){ + if(next_char > 'z') ok = false; + else parent2char[p] = next_char ++; + } + res[i] = parent2char[p]; + } + if(!ok) return ""; + + if(check(n, res, lcp)) return res; + return ""; + } + +private: + bool check(int n, const string& s, const vector>& A){ + vector> lcp(n, vector(n, 0)); + for(int i = n - 1 ; i >= 0 ; i --) + for(int j = n - 1 ; j >= 0 ; j --) + if(s[i] == s[j]){ + lcp[i][j] = 1 + ((i + 1 < n && j + 1 < n) ? lcp[i + 1][j + 1] : 0); + } + return lcp == A; + } +}; + + +int main() { + + vector> lcp2 = {{4,3,2,1}, + {3,3,2,1}, + {2,2,2,1}, + {1,1,1,1}}; + cout << Solution().findTheString(lcp2) << endl; + + return 0; +} diff --git a/2501-3000/2574-Left-and-Right-Sum-Differences/cpp-2574/CMakeLists.txt b/2501-3000/2574-Left-and-Right-Sum-Differences/cpp-2574/CMakeLists.txt new file mode 100644 index 00000000..feee6947 --- /dev/null +++ b/2501-3000/2574-Left-and-Right-Sum-Differences/cpp-2574/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2574) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2574 main.cpp) diff --git a/2501-3000/2574-Left-and-Right-Sum-Differences/cpp-2574/main.cpp b/2501-3000/2574-Left-and-Right-Sum-Differences/cpp-2574/main.cpp new file mode 100644 index 00000000..525c41cc --- /dev/null +++ b/2501-3000/2574-Left-and-Right-Sum-Differences/cpp-2574/main.cpp @@ -0,0 +1,36 @@ +/// Source : https://leetcode.com/problems/left-and-right-sum-differences/description/ +/// Author : liuyubobobo +/// Time : 2023-02-27 + +#include +#include + +using namespace std; + + +/// Presum +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector leftRigthDifference(vector& nums) { + + int n = nums.size(); + vector presum(n + 1, 0); + for(int i = 0; i < n; i ++) presum[i + 1] = presum[i] + nums[i]; + + vector res(n, 0); + for(int i = 0; i < n; i ++){ + int left = presum[i]; + int right = presum[n] - presum[i + 1]; + res[i] = abs(right - left); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2575-Find-the-Divisibility-Array-of-a-String/cpp-2575/CMakeLists.txt b/2501-3000/2575-Find-the-Divisibility-Array-of-a-String/cpp-2575/CMakeLists.txt new file mode 100644 index 00000000..5fa22d76 --- /dev/null +++ b/2501-3000/2575-Find-the-Divisibility-Array-of-a-String/cpp-2575/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2575) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2575 main.cpp) diff --git a/2501-3000/2575-Find-the-Divisibility-Array-of-a-String/cpp-2575/main.cpp b/2501-3000/2575-Find-the-Divisibility-Array-of-a-String/cpp-2575/main.cpp new file mode 100644 index 00000000..1e1d99fb --- /dev/null +++ b/2501-3000/2575-Find-the-Divisibility-Array-of-a-String/cpp-2575/main.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/find-the-divisibility-array-of-a-string/description/ +/// Author : liuyubobobo +/// Time : 2023-02-27 + +#include +#include + +using namespace std; + + +/// Math +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + vector divisibilityArray(string word, long long m) { + + int n = word.size(); + vector res(n, 0); + long long cur = 0ll; + for(int i = 0; i < n; i++){ + cur = (cur * 10 + word[i] - '0') % m; + res[i] = cur == 0; + } + return res; + } +}; + + +int main() { + std::cout << "Hello, World!" << std::endl; + return 0; +} diff --git a/2501-3000/2576-Find-the-Maximum-Number-of-Marked-Indices/cpp-2576/CMakeLists.txt b/2501-3000/2576-Find-the-Maximum-Number-of-Marked-Indices/cpp-2576/CMakeLists.txt new file mode 100644 index 00000000..5e5be77e --- /dev/null +++ b/2501-3000/2576-Find-the-Maximum-Number-of-Marked-Indices/cpp-2576/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2576) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2576 main.cpp) diff --git a/2501-3000/2576-Find-the-Maximum-Number-of-Marked-Indices/cpp-2576/main.cpp b/2501-3000/2576-Find-the-Maximum-Number-of-Marked-Indices/cpp-2576/main.cpp new file mode 100644 index 00000000..7c2864cb --- /dev/null +++ b/2501-3000/2576-Find-the-Maximum-Number-of-Marked-Indices/cpp-2576/main.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/find-the-maximum-number-of-marked-indices/description/ +/// Author : liuyubobobo +/// Time : 2023-02-27 + +#include +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + int maxNumOfMarkedIndices(vector& nums) { + + sort(nums.begin(), nums.end()); + int n = nums.size(), res = 0; + for(int i = 0, j = n / 2; i < n / 2 && j < n; i ++){ + while(j < n && nums[i] * 2 > nums[j]) j ++; + if(j < n) res += 2, j ++; + } + return res; + } +}; + + +int main() { + + vector nums1 = {42,83,48,10,24,55,9,100,10,17,17,99,51,32,16,98,99,31,28,68,71,14,64,29,15,40}; + cout << Solution().maxNumOfMarkedIndices(nums1) << '\n'; + // 26 + + return 0; +} diff --git a/2501-3000/2577-Minimum-Time-to-Visit-a-Cell-In-a-Grid/cpp-2577/CMakeLists.txt b/2501-3000/2577-Minimum-Time-to-Visit-a-Cell-In-a-Grid/cpp-2577/CMakeLists.txt new file mode 100644 index 00000000..cd668e00 --- /dev/null +++ b/2501-3000/2577-Minimum-Time-to-Visit-a-Cell-In-a-Grid/cpp-2577/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2577) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2577 main.cpp) diff --git a/2501-3000/2577-Minimum-Time-to-Visit-a-Cell-In-a-Grid/cpp-2577/main.cpp b/2501-3000/2577-Minimum-Time-to-Visit-a-Cell-In-a-Grid/cpp-2577/main.cpp new file mode 100644 index 00000000..a4677608 --- /dev/null +++ b/2501-3000/2577-Minimum-Time-to-Visit-a-Cell-In-a-Grid/cpp-2577/main.cpp @@ -0,0 +1,78 @@ +/// Source : https://leetcode.com/problems/minimum-time-to-visit-a-cell-in-a-grid/description/ +/// Author : liuyubobobo +/// Time : 2023-04-03 + +#include +#include +#include +#include + +using namespace std; + + +/// Dij +/// Time Complexity: O(R * C * log(R * C)) +/// Space Complexity: O(R * C) +class Solution { + +private: + const int dirs[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; + const int INF = INT_MAX / 2; + int R, C; + +public: + int minimumTime(vector>& grid) { + + R = grid.size(), C = grid[0].size(); + + bool can_loop = false; + if(grid[0][1] <= 1 || grid[1][0] <= 1) can_loop = true; + + vector> dis(R, vector(C, INF)); + vector> visited(R, vector(C, false)); + + priority_queue, vector>, greater>> pq; + dis[0][0] = 0; + pq.push({0, 0}); + while(!pq.empty()){ + int d = pq.top().first, cx = pq.top().second / C, cy = pq.top().second % C; + pq.pop(); + + if(visited[cx][cy]) continue; + visited[cx][cy] = true; + + for(int i = 0; i < 4; i ++){ + int nx = cx + dirs[i][0], ny = cy + dirs[i][1]; + if(in_area(nx, ny) && !visited[nx][ny]){ + int nd = d + 1; + if(can_loop && nd < grid[nx][ny]) nd = grid[nx][ny] + (grid[nx][ny] % 2 != nd % 2); + if(nd < grid[nx][ny]) continue; + if(nd < dis[nx][ny]){ + dis[nx][ny] = nd; + pq.push({nd, nx * C + ny}); + } + } + } + } + return dis[R - 1][C - 1] == INF ? -1 : dis[R - 1][C - 1]; + } + +private: + bool in_area(int x, int y){ + return 0 <= x && x < R && 0 <= y && y < C; + } +}; + + +int main() { + + vector> grid1 = { + {0, 1, 3, 2}, + {5, 1, 2, 5}, + {4, 3, 8, 6} + }; + cout << Solution().minimumTime(grid1) << '\n'; + // 7 + + return 0; +} diff --git a/2501-3000/2578-Split-With-Minimum-Sum/cpp-2578/CMakeLists.txt b/2501-3000/2578-Split-With-Minimum-Sum/cpp-2578/CMakeLists.txt new file mode 100644 index 00000000..2d383c52 --- /dev/null +++ b/2501-3000/2578-Split-With-Minimum-Sum/cpp-2578/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2578) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2578 main.cpp) diff --git a/2501-3000/2578-Split-With-Minimum-Sum/cpp-2578/main.cpp b/2501-3000/2578-Split-With-Minimum-Sum/cpp-2578/main.cpp new file mode 100644 index 00000000..0b06e6f3 --- /dev/null +++ b/2501-3000/2578-Split-With-Minimum-Sum/cpp-2578/main.cpp @@ -0,0 +1,38 @@ +/// Source : https://leetcode.com/problems/split-with-minimum-sum/ +/// Author : liuyubobobo +/// Time : 2023-03-04 + +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(log(num)) +/// Space Complexity: O(log(num)) +class Solution { +public: + int splitNum(int num) { + + vector f(10, 0); + while(num) f[num % 10] ++, num /= 10; + + vector res(2, ""); + for(int e = 1, index = 0; e <= 9; e ++){ + while(f[e] --) res[index] += to_string(e), index ^= 1; + } + + for(int index = 0; index < 2; index ++) + if(res[index] == "") res[index] = "0"; + + int a = stoi(res[0]), b = stoi(res[1]); + return a + b; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2579-Count-Total-Number-of-Colored-Cells/cpp-2579/CMakeLists.txt b/2501-3000/2579-Count-Total-Number-of-Colored-Cells/cpp-2579/CMakeLists.txt new file mode 100644 index 00000000..deb7ada6 --- /dev/null +++ b/2501-3000/2579-Count-Total-Number-of-Colored-Cells/cpp-2579/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2579) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2579 main.cpp) diff --git a/2501-3000/2579-Count-Total-Number-of-Colored-Cells/cpp-2579/main.cpp b/2501-3000/2579-Count-Total-Number-of-Colored-Cells/cpp-2579/main.cpp new file mode 100644 index 00000000..f331780c --- /dev/null +++ b/2501-3000/2579-Count-Total-Number-of-Colored-Cells/cpp-2579/main.cpp @@ -0,0 +1,31 @@ +/// Source : https://leetcode.com/problems/count-total-number-of-colored-cells/description/ +/// Author : liuyubobobo +/// Time : 2023-03-04 + +#include + +using namespace std; + + +/// Math +/// Time Complexity: O(1) +/// Space Complexity: O(1) +class Solution { +public: + long long coloredCells(long long n) { + + return n * n * 2 - (n * 2 - 1); + } +}; + + +int main() { + + cout << Solution().coloredCells(1) << '\n'; + // 1 + + cout << Solution().coloredCells(2) << '\n'; + // 5 + + return 0; +} diff --git a/2501-3000/2580-Count-Ways-to-Group-Overlapping-Ranges/cpp-2580/CMakeLists.txt b/2501-3000/2580-Count-Ways-to-Group-Overlapping-Ranges/cpp-2580/CMakeLists.txt new file mode 100644 index 00000000..763f119e --- /dev/null +++ b/2501-3000/2580-Count-Ways-to-Group-Overlapping-Ranges/cpp-2580/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2580) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2580 main.cpp) diff --git a/2501-3000/2580-Count-Ways-to-Group-Overlapping-Ranges/cpp-2580/main.cpp b/2501-3000/2580-Count-Ways-to-Group-Overlapping-Ranges/cpp-2580/main.cpp new file mode 100644 index 00000000..72396faa --- /dev/null +++ b/2501-3000/2580-Count-Ways-to-Group-Overlapping-Ranges/cpp-2580/main.cpp @@ -0,0 +1,55 @@ +/// Source : https://leetcode.com/problems/count-ways-to-group-overlapping-ranges/description/ +/// Author : liuyubobobo +/// Time : 2023-03-04 + +#include +#include +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { + +private: + const long long MOD = 1e9 + 7; + +public: + int countWays(vector>& ranges) { + + int n = ranges.size(); + sort(ranges.begin(), ranges.end()); + + int cnt = 0, l = ranges[0][0], r = ranges[0][1]; + for(int i = 1; i <= n; i ++){ + if(i < n && overlapped(l, r, ranges[i][0], ranges[i][1])){ + l = min(l, ranges[i][0]); + r = max(r, ranges[i][1]); + } + else{ + cnt ++; + if(i < n) l = ranges[i][0], r = ranges[i][1]; + } + } + + long long res = 1; + for(int i = 0; i < cnt; i ++) res = res * 2ll % MOD; + return res; + } + +private: + bool overlapped(int l1, int r1, int l2, int r2){ + assert(l2 >= l1); + return l1 <= l2 && l2 <= r1; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2581-Count-Number-of-Possible-Root-Nodes/cpp-2581/CMakeLists.txt b/2501-3000/2581-Count-Number-of-Possible-Root-Nodes/cpp-2581/CMakeLists.txt new file mode 100644 index 00000000..d52cbfc9 --- /dev/null +++ b/2501-3000/2581-Count-Number-of-Possible-Root-Nodes/cpp-2581/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2581) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2581 main.cpp) diff --git a/2501-3000/2581-Count-Number-of-Possible-Root-Nodes/cpp-2581/main.cpp b/2501-3000/2581-Count-Number-of-Possible-Root-Nodes/cpp-2581/main.cpp new file mode 100644 index 00000000..e469d275 --- /dev/null +++ b/2501-3000/2581-Count-Number-of-Possible-Root-Nodes/cpp-2581/main.cpp @@ -0,0 +1,74 @@ +/// Source : https://leetcode.com/problems/count-number-of-possible-root-nodes/description/ +/// Author : liuyubobobo +/// Time : 2023-03-04 + +#include +#include +#include +#include + +using namespace std; + + +/// Rerooting +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int rootCount(vector>& edges, vector>& guesses, int k) { + + int n = edges.size() + 1; + vector> tree(n); + for(const vector& edge: edges){ + int u = edge[0], v = edge[1]; + tree[u].push_back(v), tree[v].push_back(u); + } + + set> guess_set; + for(const vector& guess: guesses){ + int u = guess[0], v = guess[1]; + guess_set.insert({u, v}); + } + + set> correct_guesses; + dfs(tree, 0, -1, guess_set, correct_guesses); + + int res = 0; + dfs_reroot(tree, 0, -1, guess_set, correct_guesses, k, res); + return res; + } + +private: + void dfs_reroot(const vector>& tree, int u, int p, + const set>& guess_set, set>& correct_guesses, + const int k, int& res){ + + if(correct_guesses.size() >= k) res ++; + + for(int v: tree[u]){ + if(v == p) continue; + + correct_guesses.erase({u, v}); + if(guess_set.count({v, u})) correct_guesses.insert({v, u}); + dfs_reroot(tree, v, u, guess_set, correct_guesses, k, res); + correct_guesses.erase({v, u}); + if(guess_set.count({u, v})) correct_guesses.insert({u, v}); + } + } + + void dfs(const vector>& tree, int u, int p, + const set>& guess_set, set>& correct_guesses){ + + for(int v: tree[u]){ + if(v == p) continue; + if(guess_set.count({u, v})) + correct_guesses.insert({u, v}); + dfs(tree, v, u, guess_set, correct_guesses); + } + } +}; + +int main() { + + return 0; +} diff --git a/2501-3000/2582-Pass-the-Pillow/cpp-2582/CMakeLists.txt b/2501-3000/2582-Pass-the-Pillow/cpp-2582/CMakeLists.txt new file mode 100644 index 00000000..bccbfed5 --- /dev/null +++ b/2501-3000/2582-Pass-the-Pillow/cpp-2582/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2582) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2582 main.cpp) diff --git a/2501-3000/2582-Pass-the-Pillow/cpp-2582/main.cpp b/2501-3000/2582-Pass-the-Pillow/cpp-2582/main.cpp new file mode 100644 index 00000000..367d6477 --- /dev/null +++ b/2501-3000/2582-Pass-the-Pillow/cpp-2582/main.cpp @@ -0,0 +1,31 @@ +/// Source : https://leetcode.com/problems/pass-the-pillow/description/ +/// Author : liuyubobobo +/// Time : 2023-03-04 + +#include + +using namespace std; + + +/// Math +/// Time Complexity: O(1) +/// Space Complexity: O(1) +class Solution { +public: + int passThePillow(int n, int time) { + + int k = 2 * (n - 1); + time %= k; + + if(time <= n - 1) return time + 1; + + time -= (n - 1); + return n - time; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2583-Kth-Largest-Sum-in-a-Binary-Tree/cpp-2583/CMakeLists.txt b/2501-3000/2583-Kth-Largest-Sum-in-a-Binary-Tree/cpp-2583/CMakeLists.txt new file mode 100644 index 00000000..f41f268e --- /dev/null +++ b/2501-3000/2583-Kth-Largest-Sum-in-a-Binary-Tree/cpp-2583/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2583) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2583 main.cpp) diff --git a/2501-3000/2583-Kth-Largest-Sum-in-a-Binary-Tree/cpp-2583/main.cpp b/2501-3000/2583-Kth-Largest-Sum-in-a-Binary-Tree/cpp-2583/main.cpp new file mode 100644 index 00000000..60b0df7f --- /dev/null +++ b/2501-3000/2583-Kth-Largest-Sum-in-a-Binary-Tree/cpp-2583/main.cpp @@ -0,0 +1,55 @@ +/// Source : https://leetcode.com/problems/kth-largest-sum-in-a-binary-tree/description/ +/// Author : liuyubobobo +/// Time : 2023-03-04 + +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// 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: + long long kthLargestLevelSum(TreeNode* root, int k) { + + vector sums; + dfs(root, 0, sums); + sort(sums.begin(), sums.end(), greater<>()); + return k - 1 < sums.size() ? sums[k - 1] : -1; + } + +private: + void dfs(TreeNode* root, int level, vector& sums) { + + if (!root) return; + + if (level >= sums.size()){ + assert(level == sums.size()); + sums.push_back(root->val); + } + else sums[level] += root->val; + + dfs(root->left, level + 1, sums); + dfs(root->right, level + 1, sums); + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2584-Split-the-Array-to-Make-Coprime-Products/cpp-2584/CMakeLists.txt b/2501-3000/2584-Split-the-Array-to-Make-Coprime-Products/cpp-2584/CMakeLists.txt new file mode 100644 index 00000000..7d06d034 --- /dev/null +++ b/2501-3000/2584-Split-the-Array-to-Make-Coprime-Products/cpp-2584/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2584) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2584 main.cpp) diff --git a/2501-3000/2584-Split-the-Array-to-Make-Coprime-Products/cpp-2584/main.cpp b/2501-3000/2584-Split-the-Array-to-Make-Coprime-Products/cpp-2584/main.cpp new file mode 100644 index 00000000..bcfa71be --- /dev/null +++ b/2501-3000/2584-Split-the-Array-to-Make-Coprime-Products/cpp-2584/main.cpp @@ -0,0 +1,76 @@ +/// Source : https://leetcode.com/problems/split-the-array-to-make-coprime-products/description/ +/// Author : liuyubobobo +/// Time : 2023-03-13 + +#include +#include +#include +#include + +using namespace std; + + +/// Sieve + Map +/// Time Complexity: O(max_num * log(max_num) + n * log(max_num)) +/// Space Complexity: O(max_num) +class Solution { +public: + int findValidSplit(vector& nums) { + + int n = nums.size(); + int max_num = *max_element(nums.begin(), nums.end()); + + vector sieve_table = sieve(max_num); + + vector f1(max_num + 1, 0), f2(max_num + 1, 0); + for(int i = 0; i < n; i ++){ + int x = nums[i]; + while(x > 1){ + int p = sieve_table[x]; + f2[p] ++; + while(x % p == 0) x /= p; + } + } + + int both = 0; + for(int i = 0; i < n; i ++){ + int x = nums[i]; + while(x > 1){ + int p = sieve_table[x]; + both -= (f1[p] && f2[p]); + + f2[p] --; + f1[p] ++; + while(x % p == 0) x /= p; + + both += (f1[p] && f2[p]); + } + if(both == 0 && i < n - 1) return i; + } + + return -1; + } + +private: + vector sieve(int n){ + + vector table(n + 1, 0); + vector primes; + table[0] = table[1] = 1; + for(int i = 2; i <= n; i ++){ + if(table[i] == 0) { + primes.push_back(i); + table[i] = i; + } + for(int j = 0; j < primes.size() && primes[j] <= table[i] && i * primes[j] <= n; j ++) + table[i * primes[j]] = primes[j]; + } + return table; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2585-Number-of-Ways-to-Earn-Points/cpp-2585/CMakeLists.txt b/2501-3000/2585-Number-of-Ways-to-Earn-Points/cpp-2585/CMakeLists.txt new file mode 100644 index 00000000..57bb80ca --- /dev/null +++ b/2501-3000/2585-Number-of-Ways-to-Earn-Points/cpp-2585/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2585) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2585 main.cpp) diff --git a/2501-3000/2585-Number-of-Ways-to-Earn-Points/cpp-2585/main.cpp b/2501-3000/2585-Number-of-Ways-to-Earn-Points/cpp-2585/main.cpp new file mode 100644 index 00000000..f83a8ae4 --- /dev/null +++ b/2501-3000/2585-Number-of-Ways-to-Earn-Points/cpp-2585/main.cpp @@ -0,0 +1,42 @@ +/// Source : https://leetcode.com/problems/number-of-ways-to-earn-points/description/ +/// Author : liuyubobobo +/// Time : 2023-03-13 + +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(n * target * max_count) +/// Space Complexity: O(n * target) +class Solution { + +private: + const long long MOD = 1e9 + 7; + +public: + int waysToReachTarget(int target, vector>& types) { + + int n = types.size(); + vector> dp(n + 1, vector(target + 1, 0)); + dp[0][0] = 1; + for(int i = 0; i < n; i ++){ + int count = types[i][0], mark = types[i][1]; + for(int j = 0; j <= count; j ++){ + for(int t = mark * j; t <= target; t ++){ + dp[i + 1][t] += dp[i][t - mark * j]; + dp[i + 1][t] %= MOD; + } + } + } + return dp[n][target]; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2586-Count-the-Number-of-Vowel-Strings-in-Range/cpp-2586/CMakeLists.txt b/2501-3000/2586-Count-the-Number-of-Vowel-Strings-in-Range/cpp-2586/CMakeLists.txt new file mode 100644 index 00000000..b61aa603 --- /dev/null +++ b/2501-3000/2586-Count-the-Number-of-Vowel-Strings-in-Range/cpp-2586/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2586) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2586 main.cpp) diff --git a/2501-3000/2586-Count-the-Number-of-Vowel-Strings-in-Range/cpp-2586/main.cpp b/2501-3000/2586-Count-the-Number-of-Vowel-Strings-in-Range/cpp-2586/main.cpp new file mode 100644 index 00000000..a5bce452 --- /dev/null +++ b/2501-3000/2586-Count-the-Number-of-Vowel-Strings-in-Range/cpp-2586/main.cpp @@ -0,0 +1,38 @@ +/// Source : https://leetcode.com/problems/count-the-number-of-vowel-strings-in-range/description/ +/// Author : liuyubobobo +/// Time : 2023-03-13 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int vowelStrings(vector& words, int left, int right) { + + int res = 0; + for(int i = left; i <= right; i ++) + res += check(words[i]); + return res; + } + +private: + bool check(const string& s){ + return is_vowel(s[0]) && is_vowel(s.back()); + } + + bool is_vowel(char c){ + return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2587-Rearrange-Array-to-Maximize-Prefix-Score/cpp-2587/CMakeLists.txt b/2501-3000/2587-Rearrange-Array-to-Maximize-Prefix-Score/cpp-2587/CMakeLists.txt new file mode 100644 index 00000000..5588fb09 --- /dev/null +++ b/2501-3000/2587-Rearrange-Array-to-Maximize-Prefix-Score/cpp-2587/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2587) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2587 main.cpp) diff --git a/2501-3000/2587-Rearrange-Array-to-Maximize-Prefix-Score/cpp-2587/main.cpp b/2501-3000/2587-Rearrange-Array-to-Maximize-Prefix-Score/cpp-2587/main.cpp new file mode 100644 index 00000000..247cf30e --- /dev/null +++ b/2501-3000/2587-Rearrange-Array-to-Maximize-Prefix-Score/cpp-2587/main.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/rearrange-array-to-maximize-prefix-score/description/ +/// Author : liuyubobobo +/// Time : 2023-03-13 + +#include +#include +#include + +using namespace std; + + +/// Presum +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + int maxScore(vector& nums) { + + sort(nums.begin(), nums.end(), greater()); + + int n = nums.size(); + vector presum(n + 1, 0ll); + for(int i = 0; i < n; i ++) presum[i + 1] = presum[i] + nums[i]; + + int res = 0; + for(int i = 1; i <= n; i ++) res += presum[i] > 0; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2588-Count-the-Number-of-Beautiful-Subarrays/cpp-2588/CMakeLists.txt b/2501-3000/2588-Count-the-Number-of-Beautiful-Subarrays/cpp-2588/CMakeLists.txt new file mode 100644 index 00000000..cf7187b8 --- /dev/null +++ b/2501-3000/2588-Count-the-Number-of-Beautiful-Subarrays/cpp-2588/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2588) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2588 main.cpp) diff --git a/2501-3000/2588-Count-the-Number-of-Beautiful-Subarrays/cpp-2588/main.cpp b/2501-3000/2588-Count-the-Number-of-Beautiful-Subarrays/cpp-2588/main.cpp new file mode 100644 index 00000000..ee634780 --- /dev/null +++ b/2501-3000/2588-Count-the-Number-of-Beautiful-Subarrays/cpp-2588/main.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/count-the-number-of-beautiful-subarrays/description/ +/// Author : liuyubobobo +/// Time : 2023-03-13 + +#include +#include + +using namespace std; + + +/// Using Map +/// Time Complexity: O(n) +/// Space Complexity: O(max_num) +class Solution { +public: + long long beautifulSubarrays(vector& nums) { + + vector records(1 << 20, 0); + records[0] ++; + long long res = 0; + int x = 0; + for(int e: nums){ + for(int p = 0; p < 20; p++){ + if((e >> p) & 1) x ^= (1 << p); + } + res += records[x]; + records[x] ++; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2589-Minimum-Time-to-Complete-All-Tasks/cpp-2589/CMakeLists.txt b/2501-3000/2589-Minimum-Time-to-Complete-All-Tasks/cpp-2589/CMakeLists.txt new file mode 100644 index 00000000..f584459c --- /dev/null +++ b/2501-3000/2589-Minimum-Time-to-Complete-All-Tasks/cpp-2589/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2589) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2589 main.cpp) diff --git a/2501-3000/2589-Minimum-Time-to-Complete-All-Tasks/cpp-2589/main.cpp b/2501-3000/2589-Minimum-Time-to-Complete-All-Tasks/cpp-2589/main.cpp new file mode 100644 index 00000000..3f26ae7b --- /dev/null +++ b/2501-3000/2589-Minimum-Time-to-Complete-All-Tasks/cpp-2589/main.cpp @@ -0,0 +1,41 @@ +/// Source : https://leetcode.com/problems/minimum-time-to-complete-all-tasks/description/ +/// Author : liuyubobobo +/// Time : 2023-03-13 + +#include +#include +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(nlogn + n * max_time) +/// Space Complexity: O(max_time) +class Solution { +public: + int findMinimumTime(vector>& tasks) { + + sort(tasks.begin(), tasks.end(), [](vector& a, vector& b) { + if(a[1] != b[1]) return a[1] < b[1]; + return a[0] < b[0]; + }); + + vector used(2001, 0); + for(const vector& task: tasks){ + int start = task[0], end = task[1], duration = task[2]; + int cur = accumulate(used.begin() + start, used.begin() + (end + 1), 0); + for(int i = end; i >= start && cur < duration; i --) + if(!used[i]) used[i] = 1, cur ++; + } + + return accumulate(used.begin(), used.end(), 0); + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2590-Design-a-Todo-List/cpp-2590/CMakeLists.txt b/2501-3000/2590-Design-a-Todo-List/cpp-2590/CMakeLists.txt new file mode 100644 index 00000000..88d68a11 --- /dev/null +++ b/2501-3000/2590-Design-a-Todo-List/cpp-2590/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2590) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2590 main.cpp) diff --git a/2501-3000/2590-Design-a-Todo-List/cpp-2590/main.cpp b/2501-3000/2590-Design-a-Todo-List/cpp-2590/main.cpp new file mode 100644 index 00000000..fd7138ec --- /dev/null +++ b/2501-3000/2590-Design-a-Todo-List/cpp-2590/main.cpp @@ -0,0 +1,98 @@ +/// Source : https://leetcode.com/problems/design-a-todo-list/description/ +/// Author : liuyubobobo +/// Time : 2023-03-24 + +#include +#include +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class TodoList { + +private: + class Task { + public: + string description; + int dueDate; + vector tags; + bool completed; + + Task(const string& description, int dueDate, const vector& tags, bool completed) + : description(description), dueDate(dueDate), tags(tags.begin(), tags.end()), completed(completed) {} + }; + + vector> user_tasks; + vector task_list; + +public: + TodoList() : user_tasks(101){} + + int addTask(int userId, const string& taskDescription, int dueDate, const vector& tags) { + task_list.push_back(Task(taskDescription, dueDate, tags, false)); + + int task_id = task_list.size(); + user_tasks[userId].push_back(task_id - 1); + return task_id; + } + + vector getAllTasks(int userId) { + vector> result; + for (int task_id : user_tasks[userId]) + if(!task_list[task_id].completed) + result.push_back({task_list[task_id].description, task_list[task_id].dueDate}); + return get_tasks_sorted_by_due_date(result); + } + + vector getTasksForTag(int userId, string tag) { + vector> result; + for (int task_id : user_tasks[userId]) { + if (find(task_list[task_id].tags.begin(), task_list[task_id].tags.end(), tag) != task_list[task_id].tags.end() && !task_list[task_id].completed) + result.push_back({task_list[task_id].description, task_list[task_id].dueDate}); + } + return get_tasks_sorted_by_due_date(result); + } + + void completeTask(int userId, int taskId) { + if(find(user_tasks[userId].begin(), user_tasks[userId].end(), taskId - 1) != user_tasks[userId].end()) + task_list[taskId - 1].completed = true; + } + +private: + vector get_tasks_sorted_by_due_date(vector>& v) { + sort(v.begin(), v.end(), [](pair a, pair b) { + return a.second < b.second; + }); + + vector ret; + for(auto task : v) + ret.push_back(task.first); + return ret; + } +}; + + +int main() { + + TodoList todoList; + cout << todoList.addTask(1, "Task1", 50, {}) << '\n'; // 1 + cout << todoList.addTask(1, "Task2", 100, {"P1"}) << '\n'; // 2 + + vector res = todoList.getAllTasks(1); + for(const string& e: res) cout << e << ' '; cout << '\n'; // Task1, Task2 + + res = todoList.getAllTasks(5); + for(const string& e: res) cout << e << ' '; cout << '\n'; // empty + + cout << todoList.addTask(1, "Task3", 30, {"P1"}) << '\n'; // 3 + + res = todoList.getTasksForTag(1, "P1"); + for(const string& e: res) cout << e << ' '; cout << '\n'; // Task3, Task2 + + return 0; +} diff --git a/2501-3000/2591-Distribute-Money-to-Maximum-Children/cpp-2591/CMakeLists.txt b/2501-3000/2591-Distribute-Money-to-Maximum-Children/cpp-2591/CMakeLists.txt new file mode 100644 index 00000000..7e294415 --- /dev/null +++ b/2501-3000/2591-Distribute-Money-to-Maximum-Children/cpp-2591/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2591) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2591 main.cpp) diff --git a/2501-3000/2591-Distribute-Money-to-Maximum-Children/cpp-2591/main.cpp b/2501-3000/2591-Distribute-Money-to-Maximum-Children/cpp-2591/main.cpp new file mode 100644 index 00000000..fb21aa61 --- /dev/null +++ b/2501-3000/2591-Distribute-Money-to-Maximum-Children/cpp-2591/main.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/distribute-money-to-maximum-children/description/ +/// Author : liuyubobobo +/// Time : 2023-03-25 + +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(min(money / 8, children)) +/// Space Complexity: O(1) +class Solution { +public: + int distMoney(int money, int children) { + + for(int res = min(money / 8, children); res >= 0; res --){ + + int left_money = money - res * 8; + int left_children = children - res; + if(left_money && !left_children) continue; + if(left_children == 1 && left_money == 4) continue; + if(left_money < left_children) continue; + return res; + } + return -1; + } +}; + +int main() { + + return 0; +} diff --git a/2501-3000/2592-Maximize-Greatness-of-an-Array/cpp-2592/CMakeLists.txt b/2501-3000/2592-Maximize-Greatness-of-an-Array/cpp-2592/CMakeLists.txt new file mode 100644 index 00000000..b2be2054 --- /dev/null +++ b/2501-3000/2592-Maximize-Greatness-of-an-Array/cpp-2592/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2592) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2592 main.cpp) diff --git a/2501-3000/2592-Maximize-Greatness-of-an-Array/cpp-2592/main.cpp b/2501-3000/2592-Maximize-Greatness-of-an-Array/cpp-2592/main.cpp new file mode 100644 index 00000000..5f8a952f --- /dev/null +++ b/2501-3000/2592-Maximize-Greatness-of-an-Array/cpp-2592/main.cpp @@ -0,0 +1,36 @@ +/// Source : https://leetcode.com/problems/maximize-greatness-of-an-array/description/ +/// Author : liuyubobobo +/// Time : 2023-03-25 + +#include +#include +#include + +using namespace std; + + +/// Greedy +/// Time Compelxity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + int maximizeGreatness(vector& nums) { + + multiset s(nums.begin(), nums.end()); + + int res = 0; + for(int e: nums){ + auto iter = s.upper_bound(e); + if(iter != s.end()){ + res ++; s.erase(iter); + } + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2593-Find-Score-of-an-Array-After-Marking-All-Elements/cpp-2593/CMakeLists.txt b/2501-3000/2593-Find-Score-of-an-Array-After-Marking-All-Elements/cpp-2593/CMakeLists.txt new file mode 100644 index 00000000..12acc0a5 --- /dev/null +++ b/2501-3000/2593-Find-Score-of-an-Array-After-Marking-All-Elements/cpp-2593/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2593) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2593 main.cpp) diff --git a/2501-3000/2593-Find-Score-of-an-Array-After-Marking-All-Elements/cpp-2593/main.cpp b/2501-3000/2593-Find-Score-of-an-Array-After-Marking-All-Elements/cpp-2593/main.cpp new file mode 100644 index 00000000..f354bba2 --- /dev/null +++ b/2501-3000/2593-Find-Score-of-an-Array-After-Marking-All-Elements/cpp-2593/main.cpp @@ -0,0 +1,45 @@ +/// Source : https://leetcode.com/problems/find-score-of-an-array-after-marking-all-elements/description/ +/// Author : liuyubobobo +/// Time : 2023-03-25 + +#include +#include +#include + +using namespace std; + + +/// Using PQ +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + long long findScore(vector& nums) { + + int n = nums.size(); + vector visited(n, false); + + long long score = 0; + priority_queue, vector>, greater<>> pq; + for(int i = 0; i < n; i++) pq.push({nums[i], i}); + + while(!pq.empty()) { + auto [val, idx] = pq.top(); + pq.pop(); + + if(visited[idx]) continue; + visited[idx] = true; + if(idx > 0) visited[idx - 1] = true; + if(idx + 1 < n) visited[idx + 1] = true; + + score += val; + } + return score; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2594-Minimum-Time-to-Repair-Cars/cpp-2594/CMakeLists.txt b/2501-3000/2594-Minimum-Time-to-Repair-Cars/cpp-2594/CMakeLists.txt new file mode 100644 index 00000000..5f796857 --- /dev/null +++ b/2501-3000/2594-Minimum-Time-to-Repair-Cars/cpp-2594/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2594) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2594 main.cpp) diff --git a/2501-3000/2594-Minimum-Time-to-Repair-Cars/cpp-2594/main.cpp b/2501-3000/2594-Minimum-Time-to-Repair-Cars/cpp-2594/main.cpp new file mode 100644 index 00000000..30fa0536 --- /dev/null +++ b/2501-3000/2594-Minimum-Time-to-Repair-Cars/cpp-2594/main.cpp @@ -0,0 +1,44 @@ +/// Source : https://leetcode.com/problems/minimum-time-to-repair-cars/description/ +/// Author : liuyubobobo +/// Time : 2023-03-25 + +#include +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(nlog(LONG_LONG_MAX)) +/// Space Complexity: O(1) +class Solution { +public: + long long repairCars(vector& ranks, int cars) { + + long long l = 0, r = LONG_LONG_MAX; + while(l < r){ + long long mid = l + (r - l) / 2; + if(check(ranks, cars, mid)) r = mid; + else l = mid + 1; + } + return l; + } + +private: + bool check(vector& ranks, int cars, long long time){ + + long long max_cars = 0; + for(int r: ranks){ + long long x = (long long)sqrt((long double)time / r); + max_cars += x; + } + return max_cars >= cars; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2595-Number-of-Even-and-Odd-Bits/cpp-2595/CMakeLists.txt b/2501-3000/2595-Number-of-Even-and-Odd-Bits/cpp-2595/CMakeLists.txt new file mode 100644 index 00000000..ba302f4d --- /dev/null +++ b/2501-3000/2595-Number-of-Even-and-Odd-Bits/cpp-2595/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2595) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2595 main.cpp) diff --git a/2501-3000/2595-Number-of-Even-and-Odd-Bits/cpp-2595/main.cpp b/2501-3000/2595-Number-of-Even-and-Odd-Bits/cpp-2595/main.cpp new file mode 100644 index 00000000..0f4ee993 --- /dev/null +++ b/2501-3000/2595-Number-of-Even-and-Odd-Bits/cpp-2595/main.cpp @@ -0,0 +1,32 @@ +/// Source : https://leetcode.com/problems/number-of-even-and-odd-bits/description/ +/// Author : liuyubobobo +/// Time : 2023-03-25 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(log(n)) +/// Space Complexity: O(1) +class Solution { +public: + vector evenOddBit(int n) { + + int even = 0, odd = 0; + for(int p = 0; p < 10; p ++){ + if((n >> p) & 1){ + if(p & 1) odd ++; else even ++; + } + } + return {even, odd}; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2596-Check-Knight-Tour-Configuration/cpp-2596/CMakeLists.txt b/2501-3000/2596-Check-Knight-Tour-Configuration/cpp-2596/CMakeLists.txt new file mode 100644 index 00000000..28665a8b --- /dev/null +++ b/2501-3000/2596-Check-Knight-Tour-Configuration/cpp-2596/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2596) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2596 main.cpp) diff --git a/2501-3000/2596-Check-Knight-Tour-Configuration/cpp-2596/main.cpp b/2501-3000/2596-Check-Knight-Tour-Configuration/cpp-2596/main.cpp new file mode 100644 index 00000000..ffe425f4 --- /dev/null +++ b/2501-3000/2596-Check-Knight-Tour-Configuration/cpp-2596/main.cpp @@ -0,0 +1,44 @@ +/// Source : https://leetcode.com/problems/check-knight-tour-configuration/description/ +/// Author : liuyubobobo +/// Time : 2023-03-25 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n^2) +/// Space Complexity: O(n^2) +class Solution { +public: + bool checkValidGrid(vector>& grid) { + + int n = grid.size(); + + vector x(n * n, -1), y(n * n, -1); + for(int i = 0; i < n; i ++) + for(int j = 0; j < n; j ++) x[grid[i][j]] = i, y[grid[i][j]] = j; + + if(x.back() == -1) return false; + if(x[0] || y[0]) return false; + + for(int i = 1; i < n * n; i ++) + if(!check(x[i - 1], y[i - 1], x[i], y[i])) return false; + return true; + } + +private: + bool check(int x1, int y1, int x2, int y2){ + int dx = abs(x1 - x2), dy = abs(y1 - y2); + return (dx == 1 && dy == 2) || (dx == 2 && dy == 1); + } +}; + + +int main() { + + + return 0; +} diff --git a/2501-3000/2597-The-Number-of-Beautiful-Subsets/cpp-2597/CMakeLists.txt b/2501-3000/2597-The-Number-of-Beautiful-Subsets/cpp-2597/CMakeLists.txt new file mode 100644 index 00000000..b148dea0 --- /dev/null +++ b/2501-3000/2597-The-Number-of-Beautiful-Subsets/cpp-2597/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2597) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2597 main.cpp) diff --git a/2501-3000/2597-The-Number-of-Beautiful-Subsets/cpp-2597/main.cpp b/2501-3000/2597-The-Number-of-Beautiful-Subsets/cpp-2597/main.cpp new file mode 100644 index 00000000..d142307d --- /dev/null +++ b/2501-3000/2597-The-Number-of-Beautiful-Subsets/cpp-2597/main.cpp @@ -0,0 +1,55 @@ +/// Source : https://leetcode.com/problems/the-number-of-beautiful-subsets/description/ +/// Author : liuyubobobo +/// Time : 2023-03-26 + +#include +#include +#include +#include + +using namespace std; + + +/// Bitwise +/// Time Complexity: O(nlogn + n^2 + 2^n * n) +/// Space Complexity: O(n^2) +class Solution { +public: + int beautifulSubsets(vector& nums, int k) { + + int n = nums.size(); + sort(nums.begin(), nums.end()); + + vector> check(n); + for(int i = 0; i < n; i ++){ + for(int j = i + 1; j < n; j ++){ + if(nums[i] + k == nums[j]){ + check[i].push_back(j); + } + } + } + + int res = 0; + for(int state = 1; state < (1 << n); state ++){ + bool ok = true; + for(int i = 0; i < n && ok; i ++){ + if(((state >> i) & 1) && !check[i].empty()){ + for(int j: check[i]){ + if((state >> j) & 1){ + ok = false; + break; + } + } + } + } + res += ok; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2598-Smallest-Missing-Non-negative-Integer-After-Operations/cpp-2598/CMakeLists.txt b/2501-3000/2598-Smallest-Missing-Non-negative-Integer-After-Operations/cpp-2598/CMakeLists.txt new file mode 100644 index 00000000..38379239 --- /dev/null +++ b/2501-3000/2598-Smallest-Missing-Non-negative-Integer-After-Operations/cpp-2598/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2598) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2598 main.cpp) diff --git a/2501-3000/2598-Smallest-Missing-Non-negative-Integer-After-Operations/cpp-2598/main.cpp b/2501-3000/2598-Smallest-Missing-Non-negative-Integer-After-Operations/cpp-2598/main.cpp new file mode 100644 index 00000000..fff1fc14 --- /dev/null +++ b/2501-3000/2598-Smallest-Missing-Non-negative-Integer-After-Operations/cpp-2598/main.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/smallest-missing-non-negative-integer-after-operations/description/ +/// Author : liuyubobobo +/// Time : 2023-03-27 + +#include +#include +#include + +using namespace std; + + +/// Using Hash Table +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int findSmallestInteger(vector& nums, int value) { + + vector f(2e5, 0); + for(int e: nums){ + if(e >= 0){ + int k = e / value; f[e - k * value] ++; + } + else{ + int k = (-e) / value + !!((-e) % value); f[e + k * value] ++; + } + } + + for(int res = 0;; res ++){ + int k = res / value, t = res - k * value; + if(f[t]) f[t] --; + else return res; + } + return -1; + } +}; + + +int main() { + + vector nums1 = {1, -10, 7, 13, 6, 8}; + cout << Solution().findSmallestInteger(nums1, 5) << '\n'; + // 4 + + vector nums2 = {1, -10, 7, 13, 6, 8}; + cout << Solution().findSmallestInteger(nums2, 7) << '\n'; + // 2 + + return 0; +} diff --git a/2501-3000/2599-Make-the-Prefix-Sum-Non-negative/cpp-2599/CMakeLists.txt b/2501-3000/2599-Make-the-Prefix-Sum-Non-negative/cpp-2599/CMakeLists.txt new file mode 100644 index 00000000..c5f0b184 --- /dev/null +++ b/2501-3000/2599-Make-the-Prefix-Sum-Non-negative/cpp-2599/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2599) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2599 main.cpp) diff --git a/2501-3000/2599-Make-the-Prefix-Sum-Non-negative/cpp-2599/main.cpp b/2501-3000/2599-Make-the-Prefix-Sum-Non-negative/cpp-2599/main.cpp new file mode 100644 index 00000000..57e584a6 --- /dev/null +++ b/2501-3000/2599-Make-the-Prefix-Sum-Non-negative/cpp-2599/main.cpp @@ -0,0 +1,45 @@ +/// Source : https://leetcode.com/problems/make-the-prefix-sum-non-negative/description/ +/// Author : liuyubobobo +/// Time : 2023-03-24 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + int makePrefSumNonNegative(vector& nums) { + + int n = nums.size(); + + vector last; + priority_queue, greater<>> pq; + long long cur_presum = 0; + for(int i = 0; i < n; i ++){ + + cur_presum += nums[i]; + if(nums[i] < 0) pq.push(nums[i]); + + while(cur_presum < 0){ + long long t = pq.top(); pq.pop(); + last.push_back(t), cur_presum -= t; + } + + } + return last.size(); + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2600-K-Items-With-the-Maximum-Sum/cpp-2600/CMakeLists.txt b/2501-3000/2600-K-Items-With-the-Maximum-Sum/cpp-2600/CMakeLists.txt new file mode 100644 index 00000000..2b9df6f0 --- /dev/null +++ b/2501-3000/2600-K-Items-With-the-Maximum-Sum/cpp-2600/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(A) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(A main.cpp) diff --git a/2501-3000/2600-K-Items-With-the-Maximum-Sum/cpp-2600/main.cpp b/2501-3000/2600-K-Items-With-the-Maximum-Sum/cpp-2600/main.cpp new file mode 100644 index 00000000..fe485d87 --- /dev/null +++ b/2501-3000/2600-K-Items-With-the-Maximum-Sum/cpp-2600/main.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/smallest-missing-non-negative-integer-after-operations/ +/// Author : liuyubobobo +/// Time : 2023-03-26 + +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(1) +/// Space Complexity: O(1) +class Solution { +public: + int kItemsWithMaximumSum(int numOnes, int numZeros, int numNegOnes, int k) { + + int res = 0; + + int t = min(numOnes, k); + res += t, k -= t; + + t = min(numZeros, k); + k -= t; + + t = min(numNegOnes, k); + k -= t, res -= t; + + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2601-Prime-Subtraction-Operation/cpp-2601/CMakeLists.txt b/2501-3000/2601-Prime-Subtraction-Operation/cpp-2601/CMakeLists.txt new file mode 100644 index 00000000..f9dab828 --- /dev/null +++ b/2501-3000/2601-Prime-Subtraction-Operation/cpp-2601/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(B) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(B main.cpp) diff --git a/2501-3000/2601-Prime-Subtraction-Operation/cpp-2601/main.cpp b/2501-3000/2601-Prime-Subtraction-Operation/cpp-2601/main.cpp new file mode 100644 index 00000000..47ca6df5 --- /dev/null +++ b/2501-3000/2601-Prime-Subtraction-Operation/cpp-2601/main.cpp @@ -0,0 +1,66 @@ +/// Source : https://leetcode.com/problems/prime-subtraction-operation/ +/// Author : liuyubobobo +/// Time : 2023-03-26 + +#include +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(max_num * log(max_num) + n * log(max_num)) +/// Space Complexity: O(max_num) +class Solution { +public: + bool primeSubOperation(vector& nums) { + + vector primes = sieve(*max_element(nums.begin(), nums.end())); + sort(primes.begin(), primes.end(), greater()); + for(int prime: primes){ + if(prime < nums[0]){ + nums[0] -= prime; + break; + } + } + + for(int i = 1; i < nums.size(); i ++){ + for(int prime: primes){ + if(prime < nums[i] && nums[i] - prime > nums[i - 1]){ + nums[i] -= prime; + break; + } + } + if(nums[i] <= nums[i - 1]) return false; + } + return true; + } + +private: + vector sieve(int n){ + + vector table(n + 1, 0); + vector primes; + table[0] = table[1] = 1; + for(int i = 2; i <= n; i ++){ + if(table[i] == 0) { + primes.push_back(i); + table[i] = i; + } + for(int j = 0; j < primes.size() && primes[j] <= table[i] && i * primes[j] <= n; j ++) + table[i * primes[j]] = primes[j]; + } + return primes; + } +}; + + +int main() { + + vector nums1 = {998, 2}; + cout << Solution().primeSubOperation(nums1) << '\n'; + // 1 + + return 0; +} diff --git a/2501-3000/2602-Minimum-Operations-to-Make-All-Array-Elements-Equal/cpp-2602/CMakeLists.txt b/2501-3000/2602-Minimum-Operations-to-Make-All-Array-Elements-Equal/cpp-2602/CMakeLists.txt new file mode 100644 index 00000000..8b7526c5 --- /dev/null +++ b/2501-3000/2602-Minimum-Operations-to-Make-All-Array-Elements-Equal/cpp-2602/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(C) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(C main.cpp) diff --git a/2501-3000/2602-Minimum-Operations-to-Make-All-Array-Elements-Equal/cpp-2602/main.cpp b/2501-3000/2602-Minimum-Operations-to-Make-All-Array-Elements-Equal/cpp-2602/main.cpp new file mode 100644 index 00000000..cf814d21 --- /dev/null +++ b/2501-3000/2602-Minimum-Operations-to-Make-All-Array-Elements-Equal/cpp-2602/main.cpp @@ -0,0 +1,48 @@ +/// Source : https://leetcode.com/problems/minimum-operations-to-make-all-array-elements-equal/description/ +/// Author : liuyubobobo +/// Time : 2023-03-26 + +#include +#include +#include + +using namespace std; + + +/// Presum + Binary Search +/// Time Complexity: O(nlogn + qlogn) +/// Space Complexity: O(n) +class Solution { +public: + vector minOperations(vector& nums, vector& queries) { + + sort(nums.begin(), nums.end()); + + int n = nums.size(); + vector presum(n + 1, 0); + for(int i = 1; i <= n; i++) + presum[i] = presum[i - 1] + nums[i - 1]; + + vector res(queries.size()); + for(int i = 0; i < queries.size(); i++){ + int q = queries[i]; + + auto iter = lower_bound(nums.begin(), nums.end(), q); + int index = iter - nums.begin(); + + // [0... index - 1] < q; [index ... n - 1] >= q; + + long long tres = 0; + tres += (long long)q * index - presum[index]; + tres += presum[n] - presum[index] - (long long)q * (n - index); + res[i] = tres; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2603-Collect-Coins-in-a-Tree/cpp-2603/CMakeLists.txt b/2501-3000/2603-Collect-Coins-in-a-Tree/cpp-2603/CMakeLists.txt new file mode 100644 index 00000000..d2d08329 --- /dev/null +++ b/2501-3000/2603-Collect-Coins-in-a-Tree/cpp-2603/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(D) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(D main.cpp) diff --git a/2501-3000/2603-Collect-Coins-in-a-Tree/cpp-2603/main.cpp b/2501-3000/2603-Collect-Coins-in-a-Tree/cpp-2603/main.cpp new file mode 100644 index 00000000..675d51da --- /dev/null +++ b/2501-3000/2603-Collect-Coins-in-a-Tree/cpp-2603/main.cpp @@ -0,0 +1,114 @@ +/// Source : https://leetcode.com/problems/collect-coins-in-a-tree/description/ +/// Author : liuyubobobo +/// Time : 2023-03-26 + +#include +#include +#include +#include + +using namespace std; + + +/// BFS +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int collectTheCoins(vector& coins, vector>& edges) { + + int n = coins.size(); + vector> tree(n); + + for(const vector& edge : edges){ + int u = edge[0], v = edge[1]; + tree[u].push_back(v), tree[v].push_back(u); + } + + vector mask = prune(n, tree, coins); + + vector d(n, 0); + for(const vector& edge : edges){ + int u = edge[0], v = edge[1]; + if(mask[u] && mask[v]) d[u] ++, d[v] ++; + } + + queue q; + vector visited(n, false); + for(int i = 0; i < n; i++) + if(d[i] == 1) q.push(i), visited[i] = true; + + vector dis(n, 0); + while(!q.empty()){ + int u = q.front(); q.pop(); + for(int v: tree[u]){ + if(visited[v] || !mask[v]) continue; + if(coins[u] || dis[u]) dis[v] = max(dis[v], dis[u] + 1); + d[v] --; + if(d[v] == 1) q.push(v), visited[v] = true; + } + } + + int root = -1; + for(int i = 0; i < n; i++) + if(dis[i] >= 2){root = i; break;} + + return root == -1 ? 0 : dfs(tree, root, -1, dis); + } + +private: + int dfs(const vector>& tree, int u, int p, const vector& value){ + + int res = 0; + for(int v: tree[u]){ + if(v == p || value[v] < 2) continue; + res += 2 + dfs(tree, v, u, value); + } + + return res; + } + + vector prune(int n, vector>& tree, const vector& coins){ + + vector d(n, 0); + for(int i = 0; i < n; i++) d[i] = tree[i].size(); + + queue q; + for(int i = 0; i < n; i++) + if(d[i] == 1 && coins[i] == 0) q.push(i); + + vector mask(n, true); + while(!q.empty()){ + int u = q.front(); q.pop(); + mask[u] = false; + + for(int v: tree[u]){ + if(!mask[v] || coins[v]) continue; + d[v] --; + if(d[v] == 1) q.push(v); + } + } + return mask; + } +}; + + +int main() { + + vectorcoins1 = {1,0,0,0,0,1}; + vector> edges1 = {{0,1},{1,2},{2,3},{3,4},{4,5}}; + cout << Solution().collectTheCoins(coins1, edges1) << endl; + // 2 + + vector coins2 = {0,0,0,1,1,0,0,1}; + vector> edges2 = {{0,1},{0,2},{1,3},{1,4},{2,5},{5,6},{5,7}}; + cout << Solution().collectTheCoins(coins2, edges2) << endl; + // 2 + + vector coins3 = {1,0,0,1,0,0,1,0,0}; + vector> edges3 = {{0,1},{0,2},{0,3},{1,4},{2,5},{4,6},{2,7},{5,8}}; + cout << Solution().collectTheCoins(coins3, edges3) << endl; + // 0 + + return 0; +} diff --git a/2501-3000/2604-Minimum-Time-to-Eat-All-Grains/cpp-2604/CMakeLists.txt b/2501-3000/2604-Minimum-Time-to-Eat-All-Grains/cpp-2604/CMakeLists.txt new file mode 100644 index 00000000..f327652d --- /dev/null +++ b/2501-3000/2604-Minimum-Time-to-Eat-All-Grains/cpp-2604/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2604) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2604 main.cpp) diff --git a/2501-3000/2604-Minimum-Time-to-Eat-All-Grains/cpp-2604/main.cpp b/2501-3000/2604-Minimum-Time-to-Eat-All-Grains/cpp-2604/main.cpp new file mode 100644 index 00000000..082c78de --- /dev/null +++ b/2501-3000/2604-Minimum-Time-to-Eat-All-Grains/cpp-2604/main.cpp @@ -0,0 +1,67 @@ +/// Source : https://leetcode.com/problems/minimum-time-to-eat-all-grains/description/ +/// Author : liuyubobobo +/// Time : 2023-04-03 + +#include +#include +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(nlogmlog(INT_MAX)) +/// Space Complexity: O(n + m) +class Solution { +public: + int minimumTime(vector& hens, vector& grains) { + + sort(hens.begin(), hens.end()); + sort(grains.begin(), grains.end()); + + int l = 0, r = INT_MAX; + while(l < r){ + int mid = l + (r - l) / 2; + if(check(hens, grains, mid)) r = mid; + else l = mid + 1; + } + return l; + } + +private: + bool check(const vector& hens, const vector& grains, int k){ + + int gi = 0; + for(int hen: hens){ + + if(grains[gi] < hen){ + if(hen - grains[gi] > k) return false; + gi = get_max_gi(grains, gi, hen, k); + } + else{ + gi = upper_bound(grains.begin(), grains.end(), hen + k) - grains.begin(); + } + + if(gi >= grains.size()) break; + } + return gi == grains.size(); + } + + int get_max_gi(const vector& grains, int gi, int hen, int k){ + + assert(hen > grains[gi]); + int gi1 = upper_bound(grains.begin(), grains.end(), hen + (k - 2 * (hen - grains[gi]))) - grains.begin(); + int gi2 = upper_bound(grains.begin(), grains.end(), hen + (k - (hen - grains[gi])) / 2) - grains.begin(); + return max(gi1, gi2); + } +}; + + +int main() { + + vector hen1 = {0}, grain1 = {1000000000}; + cout << Solution().minimumTime(hen1, grain1) << '\n'; + + return 0; +} diff --git a/2501-3000/2605-Form-Smallest-Number-From-Two-Digit-Arrays/cpp-2605/CMakeLists.txt b/2501-3000/2605-Form-Smallest-Number-From-Two-Digit-Arrays/cpp-2605/CMakeLists.txt new file mode 100644 index 00000000..9c829faa --- /dev/null +++ b/2501-3000/2605-Form-Smallest-Number-From-Two-Digit-Arrays/cpp-2605/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2605) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2605 main.cpp) diff --git a/2501-3000/2605-Form-Smallest-Number-From-Two-Digit-Arrays/cpp-2605/main.cpp b/2501-3000/2605-Form-Smallest-Number-From-Two-Digit-Arrays/cpp-2605/main.cpp new file mode 100644 index 00000000..e11a4950 --- /dev/null +++ b/2501-3000/2605-Form-Smallest-Number-From-Two-Digit-Arrays/cpp-2605/main.cpp @@ -0,0 +1,39 @@ +/// Source : https://leetcode.com/problems/form-smallest-number-from-two-digit-arrays/description/ +/// Author : liuyubobobo +/// Time : 2023-04-02 + +#include +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(100) +/// Space Complexity: O(1) +class Solution { +public: + int minNumber(vector& nums1, vector& nums2) { + + for(int i = 1; i < 100; i ++){ + int x = i, state = 0; + while(x){ + int d = x % 10; + if(find(nums1.begin(), nums1.end(),d) != nums1.end()) + state |= 1; + if(find(nums2.begin(), nums2.end(),d) != nums2.end()) + state |= 2; + x /= 10; + } + if(state == 3) + return i; + } + return -1; + } +}; + +int main() { + + return 0; +} diff --git a/2501-3000/2606-Find-the-Substring-With-Maximum-Cost/cpp-2606/CMakeLists.txt b/2501-3000/2606-Find-the-Substring-With-Maximum-Cost/cpp-2606/CMakeLists.txt new file mode 100644 index 00000000..6b8391c1 --- /dev/null +++ b/2501-3000/2606-Find-the-Substring-With-Maximum-Cost/cpp-2606/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2606) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2606 main.cpp) diff --git a/2501-3000/2606-Find-the-Substring-With-Maximum-Cost/cpp-2606/main.cpp b/2501-3000/2606-Find-the-Substring-With-Maximum-Cost/cpp-2606/main.cpp new file mode 100644 index 00000000..409d3d48 --- /dev/null +++ b/2501-3000/2606-Find-the-Substring-With-Maximum-Cost/cpp-2606/main.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/find-the-substring-with-maximum-cost/description/ +/// Author : liuyubobobo +/// Time : 2023-04-02 + +#include +#include +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int maximumCostSubstring(string s, string chars, vector& vals) { + + vector costs(26, 0); + for (int i = 0; i < 26; i ++) costs[i] = i + 1; + for(int i = 0; i < chars.size(); i ++) costs[chars[i] - 'a'] = vals[i]; + + int res = 0, min_pre = 0, pre = 0; + for(int i = 0; i < s.size(); i ++) { + pre += costs[s[i] - 'a']; + min_pre = min(min_pre, pre); + res = max(res, pre - min_pre); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2607-Make-K-Subarray-Sums-Equal/cpp-2607/CMakeLists.txt b/2501-3000/2607-Make-K-Subarray-Sums-Equal/cpp-2607/CMakeLists.txt new file mode 100644 index 00000000..7f1340cc --- /dev/null +++ b/2501-3000/2607-Make-K-Subarray-Sums-Equal/cpp-2607/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2607) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2607 main.cpp) diff --git a/2501-3000/2607-Make-K-Subarray-Sums-Equal/cpp-2607/main.cpp b/2501-3000/2607-Make-K-Subarray-Sums-Equal/cpp-2607/main.cpp new file mode 100644 index 00000000..d06aac51 --- /dev/null +++ b/2501-3000/2607-Make-K-Subarray-Sums-Equal/cpp-2607/main.cpp @@ -0,0 +1,43 @@ +/// Source : https://leetcode.com/problems/make-k-subarray-sums-equal/description/ +/// Author : liuyubobobo +/// Time : 2023-04-02 + +#include +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + long long makeSubKSumEqual(vector& arr, int k) { + + int n = arr.size(); + + vector visited(n, false); + long long res = 0; + for(int i = 0; i < n; i ++){ + if(visited[i]) continue; + + vector v; + for(int j = i; !visited[j]; j = (j + k) % n) + v.push_back(arr[j]), visited[j] = true; + + sort(v.begin(), v.end()); + int t = v[v.size() / 2]; + for(int j = 0; j < v.size(); j ++) + res += abs(v[j] - t); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2608-Shortest-Cycle-in-a-Graph/cpp-2608/CMakeLists.txt b/2501-3000/2608-Shortest-Cycle-in-a-Graph/cpp-2608/CMakeLists.txt new file mode 100644 index 00000000..ec49765a --- /dev/null +++ b/2501-3000/2608-Shortest-Cycle-in-a-Graph/cpp-2608/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2608) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2608 main.cpp) diff --git a/2501-3000/2608-Shortest-Cycle-in-a-Graph/cpp-2608/main.cpp b/2501-3000/2608-Shortest-Cycle-in-a-Graph/cpp-2608/main.cpp new file mode 100644 index 00000000..6506d0b0 --- /dev/null +++ b/2501-3000/2608-Shortest-Cycle-in-a-Graph/cpp-2608/main.cpp @@ -0,0 +1,66 @@ +/// Source : https://leetcode.com/problems/shortest-cycle-in-a-graph/description/ +/// Author : liuyubobobo +/// Time : 2023-04-02 + +#include +#include +#include +#include + +using namespace std; + + +/// BFS +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { +public: + int findShortestCycle(int n, vector>& edges) { + + vector> g(n); + for(const vector& e : edges){ + int u = e[0], v = e[1]; + g[u].push_back(v), g[v].push_back(u); + } + + int res = INT_MAX; + for(const vector& e: edges){ + int u = e[0], v = e[1]; + g[u].remove(v), g[v].remove(u); + + vector dis = bfs(n, g, u); + if(dis[v] != INT_MAX) res = min(res, dis[v] + 1); + + g[u].push_back(v), g[v].push_back(u); + } + return res == INT_MAX ? -1 : res; + } + +private: + vector bfs(int n, const vector>& g, int s){ + + vector dis(n, INT_MAX); + queue q; + q.push(s), dis[s] = 0; + + while(!q.empty()){ + int u = q.front(), d = dis[u]; q.pop(); + for(int v: g[u]){ + if(dis[v] != INT_MAX) continue; + dis[v] = dis[u] + 1; + q.push(v); + } + } + return dis; + } +}; + + +int main() { + + vector> edges1 = {{2,1},{0,1},{4,1},{3,0},{1,3}}; + cout << Solution().findShortestCycle(5, edges1) << '\n'; + // 3 + + return 0; +} diff --git a/2501-3000/2609-Find-the-Longest-Balanced-Substring-of-a-Binary-String/cpp-2609/CMakeLists.txt b/2501-3000/2609-Find-the-Longest-Balanced-Substring-of-a-Binary-String/cpp-2609/CMakeLists.txt new file mode 100644 index 00000000..233d8d7b --- /dev/null +++ b/2501-3000/2609-Find-the-Longest-Balanced-Substring-of-a-Binary-String/cpp-2609/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2609) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2609 main.cpp) diff --git a/2501-3000/2609-Find-the-Longest-Balanced-Substring-of-a-Binary-String/cpp-2609/main.cpp b/2501-3000/2609-Find-the-Longest-Balanced-Substring-of-a-Binary-String/cpp-2609/main.cpp new file mode 100644 index 00000000..d6bed278 --- /dev/null +++ b/2501-3000/2609-Find-the-Longest-Balanced-Substring-of-a-Binary-String/cpp-2609/main.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/find-the-longest-balanced-substring-of-a-binary-string/description/ +/// Author : liuyubobobo +/// Time : 2023-04-02 + +#include +#include + +using namespace std; + + +/// String split +/// Time Complexity: O(n) +/// Space Compelxity: O(n) +class Solution { +public: + int findTheLongestBalancedSubstring(string s) { + + int n = s.size(); + + vector> segs; + for(int start = 0, i = 1; i <= n; i ++){ + if(i == n || s[i] != s[start]){ + segs.push_back({s[start] - '0', i - start}); + start = i; + } + } + + int res = 0; + for(int i = 0; i + 1 < (int)segs.size(); i ++) + if(segs[i].first == 0 && segs[i + 1].first == 1) + res = max(res, 2 * min(segs[i].second, segs[i + 1].second)); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2610-Convert-an-Array-Into-a-2D-Array-With-Conditions/cpp-2610/CMakeLists.txt b/2501-3000/2610-Convert-an-Array-Into-a-2D-Array-With-Conditions/cpp-2610/CMakeLists.txt new file mode 100644 index 00000000..621f8ed3 --- /dev/null +++ b/2501-3000/2610-Convert-an-Array-Into-a-2D-Array-With-Conditions/cpp-2610/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2610) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2610 main.cpp) diff --git a/2501-3000/2610-Convert-an-Array-Into-a-2D-Array-With-Conditions/cpp-2610/main.cpp b/2501-3000/2610-Convert-an-Array-Into-a-2D-Array-With-Conditions/cpp-2610/main.cpp new file mode 100644 index 00000000..76f3660a --- /dev/null +++ b/2501-3000/2610-Convert-an-Array-Into-a-2D-Array-With-Conditions/cpp-2610/main.cpp @@ -0,0 +1,39 @@ +/// Source : https://leetcode.com/problems/convert-an-array-into-a-2d-array-with-conditions/description/ +/// Author : liuyubobobo +/// Time : 2023-04-02 + +#include +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(n) +/// Space Complexity: O(max_num + max_f) +class Solution { +public: + vector> findMatrix(vector& nums) { + + int max_num = *max_element(nums.begin(), nums.end()); + + vector f(max_num + 1, 0); + for(int e: nums) f[e] ++; + + int maxf = *max_element(f.begin(), f.end()); + + vector> res(maxf); + for(int e = 0; e <= max_num; e ++){ + if(!f[e]) continue; + for(int i = 0; i < f[e]; i ++) res[i].push_back(e); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2611-Mice-and-Cheese/cpp-2611/CMakeLists.txt b/2501-3000/2611-Mice-and-Cheese/cpp-2611/CMakeLists.txt new file mode 100644 index 00000000..eb6c2351 --- /dev/null +++ b/2501-3000/2611-Mice-and-Cheese/cpp-2611/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2611) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2611 main.cpp) diff --git a/2501-3000/2611-Mice-and-Cheese/cpp-2611/main.cpp b/2501-3000/2611-Mice-and-Cheese/cpp-2611/main.cpp new file mode 100644 index 00000000..e27355b5 --- /dev/null +++ b/2501-3000/2611-Mice-and-Cheese/cpp-2611/main.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/mice-and-cheese/description/ +/// Author : liuyubobobo +/// Time : 2023-04-02 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// Using PQ +/// Time Complexity: O(nlogn + klogn) +/// Space Complexity: O(n) +class Solution { +public: + int miceAndCheese(vector& reward1, vector& reward2, int k) { + + int res = accumulate(reward2.begin(), reward2.end(), 0); + + int n = reward1.size(); + priority_queue pq; + for(int i = 0; i < n; i++) + pq.push(reward1[i] - reward2[i]); + + for(int i = 0; i < k; i++) { + int t = pq.top(); pq.pop(); + res += t; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2612-Minimum-Reverse-Operations/cpp-2612/CMakeLists.txt b/2501-3000/2612-Minimum-Reverse-Operations/cpp-2612/CMakeLists.txt new file mode 100644 index 00000000..4cb2739b --- /dev/null +++ b/2501-3000/2612-Minimum-Reverse-Operations/cpp-2612/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_2612) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2612 main.cpp) diff --git a/2501-3000/2612-Minimum-Reverse-Operations/cpp-2612/main.cpp b/2501-3000/2612-Minimum-Reverse-Operations/cpp-2612/main.cpp new file mode 100644 index 00000000..9a982231 --- /dev/null +++ b/2501-3000/2612-Minimum-Reverse-Operations/cpp-2612/main.cpp @@ -0,0 +1,69 @@ +/// Source : https://leetcode.com/problems/minimum-reverse-operations/description/ +/// Author : liuyubobobo +/// Time : 2023-04-02 + +#include +#include +#include +#include + +using namespace std; + + +/// BFS +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + vector minReverseOperations(int n, int p, const vector& banned, int k) { + + vector ok(n, true); + for(int ban: banned) ok[ban] = false; + + set available[2]; + for(int i = 0; i < n; ++i) if(ok[i]) available[i & 1].insert(i); + vector res(n, -1); + + queue> q; + q.push({p, 0}); + res[p] = 0; + available[p & 1].erase(p); + while(!q.empty()){ + int pos = q.front().first, step = q.front().second; + q.pop(); + + int start = max(pos - k + 1, k - pos - 1); + int end = min(pos + k - 1, 2 * n - k -pos - 1); + set& s = available[start & 1]; + for(auto iter = s.lower_bound(start); iter != s.end() && *iter <= end; iter = s.erase(iter)){ + res[*iter] = step + 1; + q.push({*iter, step + 1}); + } + } + + return res; + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << ' '; + cout << '\n'; +} + +int main() { + + vector banned1 = {}; + print_vec(Solution().minReverseOperations(4, 2, banned1, 4)); + // -1 1 0 1 + + vector banned2 = {}; + print_vec(Solution().minReverseOperations(5, 0, banned2, 4)); + // 0 3 2 1 4 + + vector banned3 = {}; + print_vec(Solution().minReverseOperations(3, 2, banned3, 1)); + // -1 -1 0 + + return 0; +} diff --git a/2501-3000/2613-Beautiful-Pairs/cpp-2613/CMakeLists.txt b/2501-3000/2613-Beautiful-Pairs/cpp-2613/CMakeLists.txt new file mode 100644 index 00000000..762e3614 --- /dev/null +++ b/2501-3000/2613-Beautiful-Pairs/cpp-2613/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2613) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2613 main.cpp) diff --git a/2501-3000/2613-Beautiful-Pairs/cpp-2613/main.cpp b/2501-3000/2613-Beautiful-Pairs/cpp-2613/main.cpp new file mode 100644 index 00000000..f96cc72f --- /dev/null +++ b/2501-3000/2613-Beautiful-Pairs/cpp-2613/main.cpp @@ -0,0 +1,25 @@ +#include +#include + +using namespace std; + + +class Solution { +public: + vector beautifulPair(vector& nums1, vector& nums2) { + + int n = nums1.size(); + + vector> points(n); + for(int i = 0; i < n; i ++) + points[i] = {nums1[i] + nums2[i], nums1[i] - nums2[i], i}; + + + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2614-Prime-In-Diagonal/cpp-2614/CMakeLists.txt b/2501-3000/2614-Prime-In-Diagonal/cpp-2614/CMakeLists.txt new file mode 100644 index 00000000..727628de --- /dev/null +++ b/2501-3000/2614-Prime-In-Diagonal/cpp-2614/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2614) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2614 main.cpp) diff --git a/2501-3000/2614-Prime-In-Diagonal/cpp-2614/main.cpp b/2501-3000/2614-Prime-In-Diagonal/cpp-2614/main.cpp new file mode 100644 index 00000000..b15e7e00 --- /dev/null +++ b/2501-3000/2614-Prime-In-Diagonal/cpp-2614/main.cpp @@ -0,0 +1,43 @@ +/// Source : https://leetcode.com/problems/prime-in-diagonal/description/ +/// Author : liuyubobobo +/// Time : 2023-04-09 + +#include +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(nlogn + n * sqrt(max_num)) +/// Space Complexity: O(n) +class Solution { +public: + int diagonalPrime(vector>& nums) { + + int n = nums.size(); + + vector v; + for(int i = 0; i < n; i ++) + v.push_back(nums[i][i]), v.push_back(nums[i][n - i - 1]); + sort(v.begin(), v.end(), greater<>()); + + for(int e: v) if(is_prime(e)) return e; + return 0; + } + +private: + bool is_prime(int x){ + if(x < 2) return false; + for(int i = 2; i * i <= x; i ++) + if(x % i == 0) return false; + return true; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2615-Sum-of-Distances/cpp-2615/CMakeLists.txt b/2501-3000/2615-Sum-of-Distances/cpp-2615/CMakeLists.txt new file mode 100644 index 00000000..1079ec86 --- /dev/null +++ b/2501-3000/2615-Sum-of-Distances/cpp-2615/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2615) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2615 main.cpp) diff --git a/2501-3000/2615-Sum-of-Distances/cpp-2615/main.cpp b/2501-3000/2615-Sum-of-Distances/cpp-2615/main.cpp new file mode 100644 index 00000000..370d8937 --- /dev/null +++ b/2501-3000/2615-Sum-of-Distances/cpp-2615/main.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/sum-of-distances/description/ +/// Author : liuyubobobo +/// Time : 2023-04-09 + +#include +#include +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector distance(vector& nums) { + + map> m; + for (int i = 0; i < nums.size(); ++i) m[nums[i]].push_back(i); + + int n = nums.size(); + vector res(n); + for(const pair>& p: m){ + const vector& index_v = p.second; + + long long left_sum = 0, right_sum = 0, left_cnt = 0, right_cnt = index_v.size() - 1; + for(int i = 1; i < (int)index_v.size(); i ++) right_sum += index_v[i] - index_v[0]; + res[index_v[0]] = left_sum + right_sum; + + for(int i = 1; i < (int)index_v.size(); i ++){ + long long d = index_v[i] - index_v[i - 1]; + left_sum += ++ left_cnt * d; + right_sum -= right_cnt -- * d; + res[index_v[i]] = left_sum + right_sum; + } + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2616-Minimize-the-Maximum-Difference-of-Pairs/cpp-2616/CMakeLists.txt b/2501-3000/2616-Minimize-the-Maximum-Difference-of-Pairs/cpp-2616/CMakeLists.txt new file mode 100644 index 00000000..ef2f7cec --- /dev/null +++ b/2501-3000/2616-Minimize-the-Maximum-Difference-of-Pairs/cpp-2616/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2616) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2616 main.cpp) diff --git a/2501-3000/2616-Minimize-the-Maximum-Difference-of-Pairs/cpp-2616/main.cpp b/2501-3000/2616-Minimize-the-Maximum-Difference-of-Pairs/cpp-2616/main.cpp new file mode 100644 index 00000000..82efbaee --- /dev/null +++ b/2501-3000/2616-Minimize-the-Maximum-Difference-of-Pairs/cpp-2616/main.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/minimize-the-maximum-difference-of-pairs/description/ +/// Author : liuyubobobo +/// Time : 2023-04-09 + +#include +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + int minimizeMax(vector& nums, int p) { + + int n = nums.size(); + sort(nums.begin(), nums.end()); + + int l = 0, r = nums.back() - nums.front(); + while(l < r){ + int mid = (l + r) / 2; + if(ok(n, nums, p, mid)) r = mid; + else l = mid + 1; + } + return l; + } + +private: + bool ok(int n, const vector& nums, int p, int d){ + + int i = 0, cnt = 0; + while(i + 1 < n){ + if(nums[i + 1] - nums[i] <= d) cnt ++, i += 2; + else i ++; + } + return cnt >= p; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2638-Count-the-Number-of-K-Free-Subsets/cpp-2638/CMakeLists.txt b/2501-3000/2638-Count-the-Number-of-K-Free-Subsets/cpp-2638/CMakeLists.txt new file mode 100644 index 00000000..37e9dd45 --- /dev/null +++ b/2501-3000/2638-Count-the-Number-of-K-Free-Subsets/cpp-2638/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2638) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2638 main.cpp) diff --git a/2501-3000/2638-Count-the-Number-of-K-Free-Subsets/cpp-2638/main.cpp b/2501-3000/2638-Count-the-Number-of-K-Free-Subsets/cpp-2638/main.cpp new file mode 100644 index 00000000..bbeb403a --- /dev/null +++ b/2501-3000/2638-Count-the-Number-of-K-Free-Subsets/cpp-2638/main.cpp @@ -0,0 +1,63 @@ +/// Source : https://leetcode.com/problems/count-the-number-of-k-free-subsets/description/ +/// Author : liuyubobobo +/// Time : 2023-04-15 + +#include +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + long long countTheNumOfKFreeSubsets(vector& nums, int k) { + + int n = nums.size(); + vector> dp(2, vector(n + 1, 0)); + dp[0][1] = dp[1][1] = 1; + for(int len = 2; len <= n; len ++){ + dp[0][len] = dp[0][len - 1] + dp[1][len - 1]; + dp[1][len] = dp[0][len - 1]; + } + + sort(nums.begin(), nums.end()); + + long long res = 1; + vector visited(n, false); + + for(int i = 0; i < n; i ++){ + if(visited[i]) continue; + + int chain_len = get_chain_len(nums, i, k, visited); + res *= (dp[0][chain_len] + dp[1][chain_len]); + } + return res; + } + +private: + int get_chain_len(const vector& nums, int s, int k, vector& visited){ + + int cur = nums[s], res = 1; + while(true){ + auto iter = lower_bound(nums.begin(), nums.end(), cur + k); + if(iter != nums.end() && *iter == cur + k){ + int index = iter - nums.begin(); + visited[index] = true; + cur = nums[index]; + res ++; + } + else break; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2639-Find-the-Width-of-Columns-of-a-Grid/cpp-2639/CMakeLists.txt b/2501-3000/2639-Find-the-Width-of-Columns-of-a-Grid/cpp-2639/CMakeLists.txt new file mode 100644 index 00000000..f5ef912d --- /dev/null +++ b/2501-3000/2639-Find-the-Width-of-Columns-of-a-Grid/cpp-2639/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2639) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2639 main.cpp) diff --git a/2501-3000/2639-Find-the-Width-of-Columns-of-a-Grid/cpp-2639/main.cpp b/2501-3000/2639-Find-the-Width-of-Columns-of-a-Grid/cpp-2639/main.cpp new file mode 100644 index 00000000..5125548b --- /dev/null +++ b/2501-3000/2639-Find-the-Width-of-Columns-of-a-Grid/cpp-2639/main.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/find-the-width-of-columns-of-a-grid/description/ +/// Author : liuyubobobo +/// Time : 2023-04-15 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(R * C * log(max(grid[i][j]))) +/// Space Complexity: O(C) +class Solution { +public: + vector findColumnWidth(vector>& grid) { + + int R = grid.size(), C = grid[0].size(); + + vector res(C, 0); + for(int j = 0; j < C; j ++){ + for(int i = 0; i < R; i ++){ + string s = to_string(grid[i][j]); + res[j] = max(res[j], (int)s.size()); + } + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2640-Find-the-Score-of-All-Prefixes-of-an-Array/cpp-2640/CMakeLists.txt b/2501-3000/2640-Find-the-Score-of-All-Prefixes-of-an-Array/cpp-2640/CMakeLists.txt new file mode 100644 index 00000000..6550ad14 --- /dev/null +++ b/2501-3000/2640-Find-the-Score-of-All-Prefixes-of-an-Array/cpp-2640/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2640) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2640 main.cpp) diff --git a/2501-3000/2640-Find-the-Score-of-All-Prefixes-of-an-Array/cpp-2640/main.cpp b/2501-3000/2640-Find-the-Score-of-All-Prefixes-of-an-Array/cpp-2640/main.cpp new file mode 100644 index 00000000..cb97380e --- /dev/null +++ b/2501-3000/2640-Find-the-Score-of-All-Prefixes-of-an-Array/cpp-2640/main.cpp @@ -0,0 +1,36 @@ +/// Source : https://leetcode.com/problems/find-the-score-of-all-prefixes-of-an-array/description/ +/// Author : liuyubobobo +/// Time : 2023-04-15 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector findPrefixScore(vector& nums) { + + int n = nums.size(); + + vector pre_max(n, nums[0]); + for(int i = 1; i < n; i ++) pre_max[i] = max(pre_max[i - 1], 0ll + nums[i]); + + vector conver(n); + for(int i = 0; i < n; i ++) conver[i] = nums[i] + pre_max[i]; + + vector res(n, conver[0]); + for(int i = 1; i < n; i ++) res[i] = res[i - 1] + conver[i]; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2641-Cousins-in-Binary-Tree-II/cpp-2641/CMakeLists.txt b/2501-3000/2641-Cousins-in-Binary-Tree-II/cpp-2641/CMakeLists.txt new file mode 100644 index 00000000..28c05001 --- /dev/null +++ b/2501-3000/2641-Cousins-in-Binary-Tree-II/cpp-2641/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2641) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2641 main.cpp) diff --git a/2501-3000/2641-Cousins-in-Binary-Tree-II/cpp-2641/main.cpp b/2501-3000/2641-Cousins-in-Binary-Tree-II/cpp-2641/main.cpp new file mode 100644 index 00000000..589f0b83 --- /dev/null +++ b/2501-3000/2641-Cousins-in-Binary-Tree-II/cpp-2641/main.cpp @@ -0,0 +1,65 @@ +/// Source : https://leetcode.com/problems/cousins-in-binary-tree-ii/description/ +/// Author : liuyubobobo +/// Time : 2023-04-15 + +#include +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// 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* replaceValueInTree(TreeNode* root) { + + vector depth_sum; + dfs(root, nullptr, 0, depth_sum); + + return dfs_replace(root, nullptr, 0, depth_sum); + } + +private: + TreeNode* dfs_replace(TreeNode* node, TreeNode* parent, int depth, const vector& depth_sum){ + + if(node == nullptr) return nullptr; + + TreeNode* left = dfs_replace(node->left, node, depth + 1, depth_sum); + TreeNode* right = dfs_replace(node->right, node, depth + 1, depth_sum); + TreeNode* ret = new TreeNode(0, left, right); + if(parent != nullptr) + ret->val = depth_sum[depth] - (parent->left ? parent->left->val : 0) - (parent->right ? parent->right->val : 0); + return ret; + } + + void dfs(TreeNode* node, TreeNode* parent, int depth, vector& depth_sum){ + + if (node == nullptr) return; + + while(depth >= depth_sum.size()) depth_sum.push_back(0); + depth_sum[depth] += node->val; + + dfs(node->left, node, depth + 1, depth_sum); + dfs(node->right, node, depth + 1, depth_sum); + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2642-Design-Graph-With-Shortest-Path-Calculator/cpp-2642/CMakeLists.txt b/2501-3000/2642-Design-Graph-With-Shortest-Path-Calculator/cpp-2642/CMakeLists.txt new file mode 100644 index 00000000..f1455aa5 --- /dev/null +++ b/2501-3000/2642-Design-Graph-With-Shortest-Path-Calculator/cpp-2642/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2642) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2642 main.cpp) diff --git a/2501-3000/2642-Design-Graph-With-Shortest-Path-Calculator/cpp-2642/main.cpp b/2501-3000/2642-Design-Graph-With-Shortest-Path-Calculator/cpp-2642/main.cpp new file mode 100644 index 00000000..141e7d45 --- /dev/null +++ b/2501-3000/2642-Design-Graph-With-Shortest-Path-Calculator/cpp-2642/main.cpp @@ -0,0 +1,62 @@ +/// Source : https://leetcode.com/problems/the-most-similar-path-in-a-graph/description/ +/// Author : liuyubobobo +/// Time : 2023-04-15 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// dij +/// Time Complexity: init: O(|edges|) +/// addEdge: O(1) +/// query: O(|E|log|E|) +/// Space Complexity: O(|V| + |E|) +class Graph { + +private: + const int INF = INT_MAX / 2; + int n; + vector>> g; + +public: + Graph(int n, vector>& edges) : n(n), g(n) { + for(const vector& e: edges){ + int u = e[0], v = e[1], w = e[2]; + g[u].push_back({v, w}); + } + } + + void addEdge(vector edge) { + int u = edge[0], v = edge[1], w = edge[2]; + g[u].push_back({v, w}); + } + + int shortestPath(int s, int t) { + + vector visited(n, false); + vector dis(n, INF); + priority_queue, vector>, greater>> pq; + pq.push({0, s}); + while(!pq.empty()){ + int d = pq.top().first, u = pq.top().second; pq.pop(); + + if(visited[u]) continue; + visited[u] = true; + if(u == t) return d; + + for(const auto& [v, w]: g[u]) + if(d + w < dis[v]) dis[v] = d + w, pq.push({dis[v], v}); + } + return -1; + } +}; + +int main() { + + return 0; +} diff --git a/2501-3000/2643-Row-With-Maximum-Ones/cpp-2643/CMakeLists.txt b/2501-3000/2643-Row-With-Maximum-Ones/cpp-2643/CMakeLists.txt new file mode 100644 index 00000000..7ac1f0d1 --- /dev/null +++ b/2501-3000/2643-Row-With-Maximum-Ones/cpp-2643/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2643) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2643 main.cpp) diff --git a/2501-3000/2643-Row-With-Maximum-Ones/cpp-2643/main.cpp b/2501-3000/2643-Row-With-Maximum-Ones/cpp-2643/main.cpp new file mode 100644 index 00000000..c07642b4 --- /dev/null +++ b/2501-3000/2643-Row-With-Maximum-Ones/cpp-2643/main.cpp @@ -0,0 +1,32 @@ +/// Source : https://leetcode.com/problems/row-with-maximum-ones/description/ +/// Author : liuyubobobo +/// Time : 2023-04-15 + +#include +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n^2) +/// Space Complexity: O(1) +class Solution { +public: + vector rowAndMaximumOnes(vector>& mat) { + + int max_ones = -1, res = -1; + for(int i = 0; i < mat.size(); i ++){ + int ones = count(mat[i].begin(), mat[i].end(), 1); + if(ones > max_ones) max_ones = ones, res = i; + } + return {res, max_ones}; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2644-Find-the-Maximum-Divisibility-Score/cpp-2644/CMakeLists.txt b/2501-3000/2644-Find-the-Maximum-Divisibility-Score/cpp-2644/CMakeLists.txt new file mode 100644 index 00000000..71e97fa2 --- /dev/null +++ b/2501-3000/2644-Find-the-Maximum-Divisibility-Score/cpp-2644/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2644) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2644 main.cpp) diff --git a/2501-3000/2644-Find-the-Maximum-Divisibility-Score/cpp-2644/main.cpp b/2501-3000/2644-Find-the-Maximum-Divisibility-Score/cpp-2644/main.cpp new file mode 100644 index 00000000..680b9e52 --- /dev/null +++ b/2501-3000/2644-Find-the-Maximum-Divisibility-Score/cpp-2644/main.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/find-the-maximum-divisibility-score/description/ +/// Author : liuyubobobo +/// Time : 2023-04-15 + +#include +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(|divisors| * log|divisors| + |nums| * |divisors|) +/// Space Complexity: O(1) +class Solution { +public: + int maxDivScore(vector& nums, vector& divisors) { + + sort(divisors.begin(), divisors.end()); + int best = -1, res = -1; + + for(int d: divisors){ + int cnt = 0; + for(int e: nums) cnt += (e % d == 0); + if(cnt > best) best = cnt, res = d; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2645-Minimum-Additions-to-Make-Valid-String/cpp-2645/CMakeLists.txt b/2501-3000/2645-Minimum-Additions-to-Make-Valid-String/cpp-2645/CMakeLists.txt new file mode 100644 index 00000000..4668e873 --- /dev/null +++ b/2501-3000/2645-Minimum-Additions-to-Make-Valid-String/cpp-2645/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2645) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2645 main.cpp) diff --git a/2501-3000/2645-Minimum-Additions-to-Make-Valid-String/cpp-2645/main.cpp b/2501-3000/2645-Minimum-Additions-to-Make-Valid-String/cpp-2645/main.cpp new file mode 100644 index 00000000..be505075 --- /dev/null +++ b/2501-3000/2645-Minimum-Additions-to-Make-Valid-String/cpp-2645/main.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/minimum-additions-to-make-valid-string/description/ +/// Author : liuyubobobo +/// Time : 2023-04-15 + +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int addMinimum(string word) { + + int n = word.size(), next = 0, index = 0, res = 0; + while(index < n) { + int cur = word[index] - 'a'; + if(next == cur) + index ++; + else res ++; + next = (next + 1) % 3; + } + + while(next != 0) res ++, next = (next + 1) % 3; + return res; + } +}; + +int main() { + + return 0; +} diff --git a/2501-3000/2646-Minimize-the-Total-Price-of-the-Trips/cpp-2646/CMakeLists.txt b/2501-3000/2646-Minimize-the-Total-Price-of-the-Trips/cpp-2646/CMakeLists.txt new file mode 100644 index 00000000..b1d70828 --- /dev/null +++ b/2501-3000/2646-Minimize-the-Total-Price-of-the-Trips/cpp-2646/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2646) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2646 main.cpp) diff --git a/2501-3000/2646-Minimize-the-Total-Price-of-the-Trips/cpp-2646/main.cpp b/2501-3000/2646-Minimize-the-Total-Price-of-the-Trips/cpp-2646/main.cpp new file mode 100644 index 00000000..8a424921 --- /dev/null +++ b/2501-3000/2646-Minimize-the-Total-Price-of-the-Trips/cpp-2646/main.cpp @@ -0,0 +1,103 @@ +/// Source : https://leetcode.com/problems/minimize-the-total-price-of-the-trips/description/ +/// Author : liuyubobobo +/// Time : 2023-04-15 + +#include +#include +#include +#include +#include +#include +#include + +using namespace std; + + +/// Tree DP +/// Time Complexity: O(|trip| * n) +/// Space Complexity: O(n) +class Solution { +public: + int minimumTotalPrice(int n, vector>& edges, vector& price, vector>& trips) { + + vector> g(n); + for(const vector& e: edges) { + int u = e[0], v = e[1]; + g[u].push_back(v), g[v].push_back(u); + } + + vector f(n, 0); + for(const vector& trip: trips) { + int s = trip[0], t = trip[1]; + + vector path = get_path(n, g, s, t); + assert(path[0] == s && path.back() == t); + for(int e: path) f[e] ++; + } + + vector> dp(n, vector(2, -1)); + return dfs(g, 0, -1, true, f, price, dp); + } + +private: + int dfs(const vector>& g, int u, int p, bool can_halve, + const vector& f, const vector& price, vector>& dp) { + + if(dp[u][can_halve] != -1) return dp[u][can_halve]; + + int res = INT_MAX; + if(can_halve){ + int tres = price[u] / 2 * f[u]; + for(int v: g[u]) { + if(v == p) continue; + tres += dfs(g, v, u, false, f, price, dp); + } + res = min(res, tres); + } + + int tres = price[u] * f[u]; + for(int v: g[u]) { + if(v == p) continue; + tres += dfs(g, v, u, true, f, price, dp); + } + res = min(res, tres); + + return dp[u][can_halve] = res; + } + + vector get_path(int n, const vector>& g, int s, int t){ + + vector pre(n, -1); + vector visited(n, false); + queue q; + q.push(s); + visited[s] = true; + while(!q.empty()) { + int u = q.front(); q.pop(); + for(int v: g[u]) { + if(visited[v]) continue; + pre[v] = u; + q.push(v); + visited[v] = true; + } + } + + vector path = {t}; + while(path.back() != s) + path.push_back(pre[path.back()]); + reverse(path.begin(), path.end()); + return path; + } +}; + + +int main() { + + vector> edges1 = {{0,1},{1,2},{1,3}}; + vector price1 = {2,2,10,6}; + vector> trips1 = {{0,3},{2,1},{2,3}}; + cout << Solution().minimumTotalPrice(4, edges1, price1, trips1) << '\n'; + // 23 + + return 0; +} diff --git a/2501-3000/2647-Color-the-Triangle-Red/cpp-2647/CMakeLists.txt b/2501-3000/2647-Color-the-Triangle-Red/cpp-2647/CMakeLists.txt new file mode 100644 index 00000000..82688815 --- /dev/null +++ b/2501-3000/2647-Color-the-Triangle-Red/cpp-2647/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2647) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2647 main.cpp) diff --git a/2501-3000/2647-Color-the-Triangle-Red/cpp-2647/main.cpp b/2501-3000/2647-Color-the-Triangle-Red/cpp-2647/main.cpp new file mode 100644 index 00000000..5c752e2f --- /dev/null +++ b/2501-3000/2647-Color-the-Triangle-Red/cpp-2647/main.cpp @@ -0,0 +1,39 @@ +/// Source : https://leetcode.com/problems/color-the-triangle-red/description/ +/// Author : liuyubobobo +/// Time : 2023-05-02 + +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(n^2) +/// Space Complexity: O(1) +class Solution { +public: + vector> colorRed(int n) { + + vector> res; + for(int i = n; i >= 1; i -= 4){ + if(i < 4){ + res.push_back({1, 1}); + for(int j = 2; j <= i; j ++) res.push_back({j, 1}), res.push_back({j, 2 * j - 1}); + } + else{ + for(int j = 1; j <= 2 * i - 1; j += 2) res.push_back({i, j}); + res.push_back({i - 1, 2}); + for(int j = 3; j <= 2 * (i - 2) - 1; j += 2) res.push_back({i - 2, j}); + res.push_back({i - 3, 1}); + } + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2651-Calculate-Delayed-Arrival-Time/cpp-2651/CMakeLists.txt b/2501-3000/2651-Calculate-Delayed-Arrival-Time/cpp-2651/CMakeLists.txt new file mode 100644 index 00000000..6b632806 --- /dev/null +++ b/2501-3000/2651-Calculate-Delayed-Arrival-Time/cpp-2651/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2651) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2651 main.cpp) diff --git a/2501-3000/2651-Calculate-Delayed-Arrival-Time/cpp-2651/main.cpp b/2501-3000/2651-Calculate-Delayed-Arrival-Time/cpp-2651/main.cpp new file mode 100644 index 00000000..c4cb9790 --- /dev/null +++ b/2501-3000/2651-Calculate-Delayed-Arrival-Time/cpp-2651/main.cpp @@ -0,0 +1,24 @@ +/// Source : https://leetcode.com/problems/calculate-delayed-arrival-time/description/ +/// Author : liuyubobobo +/// Time : 2023-04-23 + +#include + +using namespace std; + + +/// Math +/// Time Complexity: O(1) +/// Space Complexity: O(1) +class Solution { +public: + int findDelayedArrivalTime(int arrivalTime, int delayedTime) { + return (arrivalTime + delayedTime) % 24; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2652-Sum-Multiples/cpp-2652/CMakeLists.txt b/2501-3000/2652-Sum-Multiples/cpp-2652/CMakeLists.txt new file mode 100644 index 00000000..cbe90ee9 --- /dev/null +++ b/2501-3000/2652-Sum-Multiples/cpp-2652/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2652) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2652 main.cpp) diff --git a/2501-3000/2652-Sum-Multiples/cpp-2652/main.cpp b/2501-3000/2652-Sum-Multiples/cpp-2652/main.cpp new file mode 100644 index 00000000..c91b1f5d --- /dev/null +++ b/2501-3000/2652-Sum-Multiples/cpp-2652/main.cpp @@ -0,0 +1,30 @@ +/// Source : https://leetcode.com/problems/sum-multiples/description/ +/// Author : liuyubobobo +/// Time : 2023-04-23 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int sumOfMultiples(int n) { + + int sum = 0; + for(int i = 1; i <= n; i ++) + if(i % 3 == 0 || i % 5 == 0 || i % 7 == 0) + sum += i; + return sum; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2653-Sliding-Subarray-Beauty/cpp-2653/CMakeLists.txt b/2501-3000/2653-Sliding-Subarray-Beauty/cpp-2653/CMakeLists.txt new file mode 100644 index 00000000..38d019a2 --- /dev/null +++ b/2501-3000/2653-Sliding-Subarray-Beauty/cpp-2653/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2653) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2653 main.cpp) diff --git a/2501-3000/2653-Sliding-Subarray-Beauty/cpp-2653/main.cpp b/2501-3000/2653-Sliding-Subarray-Beauty/cpp-2653/main.cpp new file mode 100644 index 00000000..a2ad8248 --- /dev/null +++ b/2501-3000/2653-Sliding-Subarray-Beauty/cpp-2653/main.cpp @@ -0,0 +1,51 @@ +/// Source : https://leetcode.com/problems/sliding-subarray-beauty/description/ +/// Author : liuyubobobo +/// Time : 2023-04-23 + +#include +#include + +using namespace std; + + +/// Sliding Window +/// Time Complexity: O(n * |max_num - min_num|) +/// Space Complexity: O(|max_num - min_num|) +class Solution { + +private: + const int OFFSET = 50; + +public: + vector getSubarrayBeauty(vector& nums, int k, int x) { + + vector f(101, 0); + + for(int i = 0; i < k - 1; i ++) f[nums[i] + OFFSET] ++; + + vector res; + for(int i = k - 1; i < nums.size(); i ++){ + f[nums[i] + OFFSET] ++; + + res.push_back(min(0, get_kth(f, x))); + f[nums[i - (k - 1)] + OFFSET] --; + } + return res; + } + +private: + int get_kth(vector& f, int k){ + int sum = 0; + for(int i = 0; i <= 100; i ++){ + sum += f[i]; + if(sum >= k) return i - OFFSET; + } + return -1; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2654-Minimum-Number-of-Operations-to-Make-All-Array-Elements-Equal-to-1/cpp-2654/CMakeLists.txt b/2501-3000/2654-Minimum-Number-of-Operations-to-Make-All-Array-Elements-Equal-to-1/cpp-2654/CMakeLists.txt new file mode 100644 index 00000000..1ae9fdf6 --- /dev/null +++ b/2501-3000/2654-Minimum-Number-of-Operations-to-Make-All-Array-Elements-Equal-to-1/cpp-2654/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2654) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2654 main.cpp) diff --git a/2501-3000/2654-Minimum-Number-of-Operations-to-Make-All-Array-Elements-Equal-to-1/cpp-2654/main.cpp b/2501-3000/2654-Minimum-Number-of-Operations-to-Make-All-Array-Elements-Equal-to-1/cpp-2654/main.cpp new file mode 100644 index 00000000..9ce97ccb --- /dev/null +++ b/2501-3000/2654-Minimum-Number-of-Operations-to-Make-All-Array-Elements-Equal-to-1/cpp-2654/main.cpp @@ -0,0 +1,71 @@ +/// Source : https://leetcode.com/problems/minimum-number-of-operations-to-make-all-array-elements-equal-to-1/ +/// Author : liuyubobobo +/// Time : 2023-04-30 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(n^3) +/// Space Complexity: O(1) +class Solution { +public: + int minOperations(vector& nums) { + + int n = nums.size(), g = gcd(nums, 0, n - 1); + if(g > 1) return -1; + + int one_cnt = count(nums.begin(), nums.end(), 1); + if(one_cnt) return n - one_cnt; + + int min_len = n; + for(int s = 0; s < n; s ++) + for(int t = s + 1; t < n; t ++){ + int g = gcd(nums, s, t); + if(g == 1) min_len = min(min_len, t - s + 1); + } + return min_len - 1 + n - 1; + } + +private: + int gcd(vector& nums, int s, int t){ + int g = nums[s]; + for(int i = s + 1; i <= t; i ++) g = gcd(g, nums[i]); + return g; + } + + template + T gcd(T a, T b){ + if(a < b) swap(a, b); + while(b){ + int t = a % b; + a = b; + b = t; + } + return a; + } +}; + + +int main() { + + vector nums1 = {2, 6, 3, 4}; + cout << Solution().minOperations(nums1) << '\n'; + // 4 + + vector nums2 = {2, 10, 6, 14}; + cout << Solution().minOperations(nums2) << '\n'; + // -1 + + vector nums3 = {6, 10, 15}; + cout << Solution().minOperations(nums3) << '\n'; + // 4 + + return 0; +} diff --git a/2501-3000/2655-Find-Maximal-Uncovered-Ranges/cpp-2655/CMakeLists.txt b/2501-3000/2655-Find-Maximal-Uncovered-Ranges/cpp-2655/CMakeLists.txt new file mode 100644 index 00000000..20493d62 --- /dev/null +++ b/2501-3000/2655-Find-Maximal-Uncovered-Ranges/cpp-2655/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2655) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2655 main.cpp) diff --git a/2501-3000/2655-Find-Maximal-Uncovered-Ranges/cpp-2655/main.cpp b/2501-3000/2655-Find-Maximal-Uncovered-Ranges/cpp-2655/main.cpp new file mode 100644 index 00000000..652bd8e3 --- /dev/null +++ b/2501-3000/2655-Find-Maximal-Uncovered-Ranges/cpp-2655/main.cpp @@ -0,0 +1,45 @@ +/// Source : https://leetcode.com/problems/find-maximal-uncovered-ranges/description/ +/// Author : liuyubobobo +/// Time : 2023-04-30 + +#include +#include +#include + +using namespace std; + + +/// Sorting +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + vector> findMaximalUncoveredRanges(int n, vector>& ranges) { + + sort(ranges.begin(), ranges.end()); + + vector> segs; + for(const vector& range: ranges){ + int a = range[0], b = range[1]; + if(segs.empty() || segs.back().second + 1 < a) + segs.push_back({a, b}); + else segs.back().second = max(segs.back().second, b); + } + + if(segs.empty()) return vector>(1, {0, n - 1}); + + vector> res; + if(segs[0].first) res.push_back({0, segs[0].first - 1}); + for(int i = 1; i < segs.size(); i++) + res.push_back({segs[i - 1].second + 1, segs[i].first - 1}); + if(segs.back().second + 1 < n) + res.push_back({segs.back().second + 1, n - 1}); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2656-Maximum-Sum-With-Exactly-K-Elements/cpp-2656/CMakeLists.txt b/2501-3000/2656-Maximum-Sum-With-Exactly-K-Elements/cpp-2656/CMakeLists.txt new file mode 100644 index 00000000..7386ba30 --- /dev/null +++ b/2501-3000/2656-Maximum-Sum-With-Exactly-K-Elements/cpp-2656/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2656) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2656 main.cpp) diff --git a/2501-3000/2656-Maximum-Sum-With-Exactly-K-Elements/cpp-2656/main.cpp b/2501-3000/2656-Maximum-Sum-With-Exactly-K-Elements/cpp-2656/main.cpp new file mode 100644 index 00000000..5c937436 --- /dev/null +++ b/2501-3000/2656-Maximum-Sum-With-Exactly-K-Elements/cpp-2656/main.cpp @@ -0,0 +1,28 @@ +/// Source : https://leetcode.com/problems/maximum-sum-with-exactly-k-elements/description/ +/// Author : liuyubobobo +/// Time : 2023-04-30 + +#include +#include +#include + +using namespace std; + + +/// Math +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int maximizeSum(vector& nums, int k) { + + int start = *max_element(nums.begin(), nums.end()); + return (start + start + k - 1) * k / 2; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2657-Find-the-Prefix-Common-Array-of-Two-Arrays/cpp-2657/CMakeLists.txt b/2501-3000/2657-Find-the-Prefix-Common-Array-of-Two-Arrays/cpp-2657/CMakeLists.txt new file mode 100644 index 00000000..56486179 --- /dev/null +++ b/2501-3000/2657-Find-the-Prefix-Common-Array-of-Two-Arrays/cpp-2657/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2657) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2657 main.cpp) diff --git a/2501-3000/2657-Find-the-Prefix-Common-Array-of-Two-Arrays/cpp-2657/main.cpp b/2501-3000/2657-Find-the-Prefix-Common-Array-of-Two-Arrays/cpp-2657/main.cpp new file mode 100644 index 00000000..8a919aa0 --- /dev/null +++ b/2501-3000/2657-Find-the-Prefix-Common-Array-of-Two-Arrays/cpp-2657/main.cpp @@ -0,0 +1,36 @@ +/// Source : https://leetcode.com/problems/find-the-prefix-common-array-of-two-arrays/description/ +/// Author : liuyubobobo +/// Time : 2023-04-30 + +#include +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { +public: + vector findThePrefixCommonArray(vector& A, vector& B) { + + set Aset; + vector res(A.size()); + for (int i = 0; i < A.size(); i++) { + Aset.insert(A[i]); + int cnt = 0; + for(int j = 0; j <= i; j ++) + cnt += Aset.count(B[j]); + res[i] = cnt; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2658-Maximum-Number-of-Fish-in-a-Grid/cpp-2658/CMakeLists.txt b/2501-3000/2658-Maximum-Number-of-Fish-in-a-Grid/cpp-2658/CMakeLists.txt new file mode 100644 index 00000000..ab98fcd4 --- /dev/null +++ b/2501-3000/2658-Maximum-Number-of-Fish-in-a-Grid/cpp-2658/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2658) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2658 main.cpp) diff --git a/2501-3000/2658-Maximum-Number-of-Fish-in-a-Grid/cpp-2658/main.cpp b/2501-3000/2658-Maximum-Number-of-Fish-in-a-Grid/cpp-2658/main.cpp new file mode 100644 index 00000000..68f25292 --- /dev/null +++ b/2501-3000/2658-Maximum-Number-of-Fish-in-a-Grid/cpp-2658/main.cpp @@ -0,0 +1,56 @@ +/// Source : https://leetcode.com/problems/maximum-number-of-fish-in-a-grid/description/ +/// Author : liuyubobobo +/// Time : 2023-04-30 + +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(R * C) +/// Space Complexity: O(R * C) +class Solution { + +private: + const int dirs[4][2] = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}}; + int R, C; + +public: + int findMaxFish(vector>& grid) { + + R = grid.size(), C = grid[0].size(); + vector> visited(R, vector(C, false)); + int res = 0; + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++){ + if(grid[i][j] == 0 || visited[i][j]) continue; + res = max(res, dfs(grid, i, j, visited)); + } + return res; + } + +private: + int dfs(const vector>& grid, int cx, int cy, vector>& visited){ + + int res = grid[cx][cy]; + visited[cx][cy] = true; + for(int d = 0; d < 4; d ++){ + int nx = cx + dirs[d][0], ny = cy + dirs[d][1]; + if(in_area(nx, ny) && grid[nx][ny] && !visited[nx][ny]) + res += dfs(grid, nx, ny, visited); + } + return res; + } + + bool in_area(int x, int y){ + return 0 <= x && x < R && 0 <= y && y < C; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2659-Make-Array-Empty/cpp-2659/CMakeLists.txt b/2501-3000/2659-Make-Array-Empty/cpp-2659/CMakeLists.txt new file mode 100644 index 00000000..ba6a80a8 --- /dev/null +++ b/2501-3000/2659-Make-Array-Empty/cpp-2659/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2659) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2659 main.cpp) diff --git a/2501-3000/2659-Make-Array-Empty/cpp-2659/main.cpp b/2501-3000/2659-Make-Array-Empty/cpp-2659/main.cpp new file mode 100644 index 00000000..10f4bd1d --- /dev/null +++ b/2501-3000/2659-Make-Array-Empty/cpp-2659/main.cpp @@ -0,0 +1,118 @@ +/// Source : https://leetcode.com/problems/make-array-empty/description/ +/// Author : liuyubobobo +/// Time : 2023-04-30 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// Using BIT +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +template +class BIT{ + +private: + int n; + vector data; + vector tree; + +public: + BIT(const vector& arr) : n(arr.size()), data(arr.begin(), arr.end()), tree(n + 1){ + + for(int i = 0; i < n; i ++) + tree[i + 1]= data[i]; + + for(int i = 1; i <= n; i ++){ + int parent = i + (i & -i); + if(parent <= n) tree[parent] += tree[i]; + } + } + + BIT(int n): n(n), data(n, 0), tree(n + 1, 0){} + + void add(int index, T v){ + assert(0 <= index && index < n); + + data[index] += v; + + index ++; + for(;index <= n; index += (index & -index)) + tree[index] += v; + } + + T query(int l, int r){ + if(!(0 <= l && l < n) || !(0 <= r && r < n)) return 0; + if(l > r) return 0; + return prefix_sum(r + 1) - prefix_sum(l); + } + + void set(int index, T v){ + assert(0 <= index && index < n); + add(index, v - data[index]); + } + +private: + // r is 1-based + T prefix_sum(int r){ + + T res = 0; + for(; r; r -= (r & -r)) + res += tree[r]; + return res; + } +}; + +class Solution { +public: + long long countOperationsToEmptyArray(vector& nums) { + + int n = nums.size(); + vector> order(n); + for(int i = 0; i < n; i ++) order[i] = {nums[i], i}; + sort(order.begin(), order.end()); + + BIT bit(vector(n, 1)); + + int front = 0; + long long res = 0; + for(const pair& p: order){ + int index = p.second; + if(index > front){ + res += bit.query(front, index - 1); + bit.set(index, 0); + res ++; + front = (index + 1) % n; + } + else if(index < front){ + res += bit.query(front, n - 1); + res += bit.query(0, index - 1); + bit.set(index, 0); + res ++; + front = (index + 1) % n; + } + else{ + bit.set(index, 0); + res ++; + front = (index + 1) % n; + } + } + return res; + + } +}; + + +int main() { + + vector nums1 = {-15, -19, 5}; + cout << Solution().countOperationsToEmptyArray(nums1) << endl; + // 5 + + return 0; +} diff --git a/2501-3000/2660-Determine-the-Winner-of-a-Bowling-Game/cpp-2660/CMakeLists.txt b/2501-3000/2660-Determine-the-Winner-of-a-Bowling-Game/cpp-2660/CMakeLists.txt new file mode 100644 index 00000000..b69c4cdd --- /dev/null +++ b/2501-3000/2660-Determine-the-Winner-of-a-Bowling-Game/cpp-2660/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2660) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2660 main.cpp) diff --git a/2501-3000/2660-Determine-the-Winner-of-a-Bowling-Game/cpp-2660/main.cpp b/2501-3000/2660-Determine-the-Winner-of-a-Bowling-Game/cpp-2660/main.cpp new file mode 100644 index 00000000..fb1c9282 --- /dev/null +++ b/2501-3000/2660-Determine-the-Winner-of-a-Bowling-Game/cpp-2660/main.cpp @@ -0,0 +1,39 @@ +/// Source : https://leetcode.com/problems/determine-the-winner-of-a-bowling-game/description/ +/// Author : liuyubobobo +/// Time : 2023-04-30 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int isWinner(vector& player1, vector& player2) { + + int a = get_score(player1), b = get_score(player2); + return (a == b ? 0 : (a > b ? 1 : 2)); + } + +private: + int get_score(const vector& v){ + int res = 0; + for(int i = 0; i < v.size(); i ++){ + bool double_score = false; + if(i - 1 >= 0 && v[i - 1] == 10) double_score = true; + if(i - 2 >= 0 && v[i - 2] == 10) double_score = true; + res += (double_score ? 2 : 1) * v[i]; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2661-First-Completely-Painted-Row-or-Column/cpp-2661/CMakeLists.txt b/2501-3000/2661-First-Completely-Painted-Row-or-Column/cpp-2661/CMakeLists.txt new file mode 100644 index 00000000..29110081 --- /dev/null +++ b/2501-3000/2661-First-Completely-Painted-Row-or-Column/cpp-2661/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2661) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2661 main.cpp) diff --git a/2501-3000/2661-First-Completely-Painted-Row-or-Column/cpp-2661/main.cpp b/2501-3000/2661-First-Completely-Painted-Row-or-Column/cpp-2661/main.cpp new file mode 100644 index 00000000..0a19ac9d --- /dev/null +++ b/2501-3000/2661-First-Completely-Painted-Row-or-Column/cpp-2661/main.cpp @@ -0,0 +1,41 @@ +/// Source : https://leetcode.com/problems/first-completely-painted-row-or-column/description/ +/// Author : liuyubobobo +/// Time : 2023-04-30 + +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(R * C) +/// Space Complexity: O(R * C) +class Solution { +public: + int firstCompleteIndex(vector& arr, vector>& mat) { + + int R = mat.size(), C = mat[0].size(); + vector> pos(R * C + 1); + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++) + pos[mat[i][j]] = {i, j}; + + vector rows(R, C), cols(C, R); + for(int i = 0; i < arr.size(); i ++){ + int r = pos[arr[i]].first, c = pos[arr[i]].second; + rows[r] --, cols[c] --; + if(rows[r] == 0 || cols[c] == 0) return i; + } + return -1; + } +}; + + +int main() { + + + + + return 0; +} diff --git a/2501-3000/2662-Minimum-Cost-of-a-Path-With-Special-Roads/cpp-2662/CMakeLists.txt b/2501-3000/2662-Minimum-Cost-of-a-Path-With-Special-Roads/cpp-2662/CMakeLists.txt new file mode 100644 index 00000000..31ec1a99 --- /dev/null +++ b/2501-3000/2662-Minimum-Cost-of-a-Path-With-Special-Roads/cpp-2662/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2662) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2662 main.cpp) diff --git a/2501-3000/2662-Minimum-Cost-of-a-Path-With-Special-Roads/cpp-2662/main.cpp b/2501-3000/2662-Minimum-Cost-of-a-Path-With-Special-Roads/cpp-2662/main.cpp new file mode 100644 index 00000000..5905d18b --- /dev/null +++ b/2501-3000/2662-Minimum-Cost-of-a-Path-With-Special-Roads/cpp-2662/main.cpp @@ -0,0 +1,91 @@ +/// Source : https://leetcode.com/problems/minimum-cost-of-a-path-with-special-roads/description/ +/// Author : liuyubobobo +/// Time : 2023-04-30 + +#include +#include +#include +#include +#include +#include + +using namespace std; + + +/// Dijkstra +/// Time Complexity: O(n^2 * logn) +/// Space Complexity: O(n^2) +class Solution { +public: + int minimumCost(vector& start, vector& target, vector>& specialRoads) { + + set> vertexs; + vertexs.insert({start[0], start[1]}); + vertexs.insert({target[0], target[1]}); + for(const vector& v: specialRoads) { + vertexs.insert({v[0], v[1]}); + vertexs.insert({v[2], v[3]}); + } + + vector> index2v(vertexs.begin(), vertexs.end()); + map, int> v2index; + for(int i = 0; i < index2v.size(); i++) v2index[index2v[i]] = i; + + int n = index2v.size(); + int s = v2index[{start[0], start[1]}], t = v2index[{target[0], target[1]}]; + + vector> g(n, vector(n, INT_MAX / 2)); + for(int i = 0; i < n; i ++) + for(int j = i + 1; j < n; j ++) + g[i][j] = g[j][i] = get_dis(index2v[i], index2v[j]); + + for(const vector& v: specialRoads) { + int a = v2index[{v[0], v[1]}], b = v2index[{v[2], v[3]}], w = v[4]; + if(w < g[a][b]) g[a][b] = w; + } + + + return dij(n, g, s, t); + } + +private: + int dij(int n, const vector>& g, int s, int t){ + + vector visited(n, false); + vector dis(n, INT_MAX / 2); + priority_queue, vector>, greater<>> pq; + pq.push({0, s}); + dis[s] = 0; + while(!pq.empty()){ + auto [d, u] = pq.top(); pq.pop(); + + if(visited[u]) continue; + visited[u] = true; + + dis[u] = d; + for(int v = 0; v < n; v ++){ + int w = g[u][v]; + if(!visited[v] && dis[v] > dis[u] + w){ + dis[v] = dis[u] + w; + pq.push({dis[v], v}); + } + } + } + return dis[t]; + } + + int get_dis(const pair& p1, const pair& p2){ + return abs(p1.first - p2.first) + abs(p1.second - p2.second); + } +}; + + +int main() { + + vector start1 = {1, 1}, target1 = {4, 5}; + vector> specialRoads1 = {{1, 2, 3, 3, 2}, {3, 4, 4, 5, 1}}; + cout << Solution().minimumCost(start1, target1, specialRoads1) << endl; + // 5 + + return 0; +} diff --git a/2501-3000/2663-Lexicographically-Smallest-Beautiful-String/cpp-2663/CMakeLists.txt b/2501-3000/2663-Lexicographically-Smallest-Beautiful-String/cpp-2663/CMakeLists.txt new file mode 100644 index 00000000..a20c2964 --- /dev/null +++ b/2501-3000/2663-Lexicographically-Smallest-Beautiful-String/cpp-2663/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2663) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2663 main.cpp) diff --git a/2501-3000/2663-Lexicographically-Smallest-Beautiful-String/cpp-2663/main.cpp b/2501-3000/2663-Lexicographically-Smallest-Beautiful-String/cpp-2663/main.cpp new file mode 100644 index 00000000..333acab6 --- /dev/null +++ b/2501-3000/2663-Lexicographically-Smallest-Beautiful-String/cpp-2663/main.cpp @@ -0,0 +1,69 @@ +/// Source : https://leetcode.com/problems/lexicographically-smallest-beautiful-string/description/ +/// Author : liuyubobobo +/// Time : 2023-04-30 + +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + string smallestBeautifulString(string s, int k) { + + int n = s.size(), pos = n - 1; + while(add1(n, s, k, pos)){ + int pre = pos; + pos = check(pos, s); + if(pos == -1){ + for(int i = pre + 1; i < n; i ++){ + for(char c = 'a'; c < 'a' + k; c ++){ + if(i - 1 >= 0 && s[i - 1] == c) continue; + if(i - 2 >= 0 && s[i - 2] == c) continue; + s[i] = c; + break; + } + } + return s; + } + } + return ""; + } + +private: + int check(int pos, const string& s){ + + for(int i = pos; i > 0; i --){ + if(s[i] == s[i - 1]) return i; + if(i - 2 >= 0 && s[i] == s[i - 2]) return i; + } + return -1; + } + + bool add1(int n, string& s, int k, int pos){ + s[pos] += 1; + for(int i = pos; i > 0; i --) + if(s[i] == 'a' + k){ + s[i - 1] += 1; + s[i] = 'a'; + } + else break; + if(s[0] == 'a' + k) return false; + + return true; + } +}; + +int main() { + +// cout << Solution().smallestBeautifulString("abcz", 26) << endl; +// // abda + + cout << Solution().smallestBeautifulString("ponponp", 16) << endl; + + return 0; +} diff --git a/2501-3000/2664-The-Knights-Tour/cpp-2664/CMakeLists.txt b/2501-3000/2664-The-Knights-Tour/cpp-2664/CMakeLists.txt new file mode 100644 index 00000000..ac8ea56b --- /dev/null +++ b/2501-3000/2664-The-Knights-Tour/cpp-2664/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2664) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2664 main.cpp) diff --git a/2501-3000/2664-The-Knights-Tour/cpp-2664/main.cpp b/2501-3000/2664-The-Knights-Tour/cpp-2664/main.cpp new file mode 100644 index 00000000..5493c5bc --- /dev/null +++ b/2501-3000/2664-The-Knights-Tour/cpp-2664/main.cpp @@ -0,0 +1,56 @@ +/// Source : https://leetcode.com/problems/the-knights-tour/description/ +/// Author : liuyubobobo +/// Time : 2023-05-06 + +#include +#include + +using namespace std; + + +/// Backtrack +/// Time Complexity: O(exp) +/// Space Complexity: O(R * C) +class Solution { + +private: + const int dirs[8][2] = { + {-2, -1}, + {-2, 1}, + {-1, -2}, + {-1, 2}, + {1, -2}, + {1, 2}, + {2, -1}, + {2, 1} + }; + +public: + vector> tourOfKnight(int R, int C, int r, int c) { + + vector> res(R, vector(C, -1)); + dfs(R, C, r, c, 0, res); + return res; + } + + bool dfs(int R, int C, int x, int y, int step, vector>& res) { + + res[x][y] = step; + if(step == R * C - 1) return true; + for (int i = 0; i < 8; ++i) { + int nx = x + dirs[i][0]; + int ny = y + dirs[i][1]; + if (nx >= 0 && nx < R && ny >= 0 && ny < C && res[nx][ny] == -1) { + if(dfs(R, C, nx, ny, step + 1, res)) return true; + } + } + res[x][y] = -1; + return false; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2670-Find-the-Distinct-Difference-Array/cpp-2670/CMakeLists.txt b/2501-3000/2670-Find-the-Distinct-Difference-Array/cpp-2670/CMakeLists.txt new file mode 100644 index 00000000..8a306afe --- /dev/null +++ b/2501-3000/2670-Find-the-Distinct-Difference-Array/cpp-2670/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(A) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(A main.cpp) diff --git a/2501-3000/2670-Find-the-Distinct-Difference-Array/cpp-2670/main.cpp b/2501-3000/2670-Find-the-Distinct-Difference-Array/cpp-2670/main.cpp new file mode 100644 index 00000000..1e6a8032 --- /dev/null +++ b/2501-3000/2670-Find-the-Distinct-Difference-Array/cpp-2670/main.cpp @@ -0,0 +1,44 @@ +/// Source : https://leetcode.com/problems/find-the-distinct-difference-array/ +/// Author : liuyubobobo +/// Time : 2023-05-06 + +#include +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector distinctDifferenceArray(vector& nums) { + + int n = nums.size(); + + vector pre(n), suf(n + 1, 0); + set s; + for(int i = 0; i < n; i ++){ + s.insert(nums[i]); + pre[i] = s.size(); + } + + s.clear(); + for(int i = n - 1; i >= 0; i --){ + s.insert(nums[i]); + suf[i] = s.size(); + } + + vector res(n); + for(int i = 0; i < n; i ++) res[i] = pre[i] - suf[i + 1]; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2671-Frequency-Tracker/cpp-2671/CMakeLists.txt b/2501-3000/2671-Frequency-Tracker/cpp-2671/CMakeLists.txt new file mode 100644 index 00000000..3e27b177 --- /dev/null +++ b/2501-3000/2671-Frequency-Tracker/cpp-2671/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(B) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(B main.cpp) diff --git a/2501-3000/2671-Frequency-Tracker/cpp-2671/main.cpp b/2501-3000/2671-Frequency-Tracker/cpp-2671/main.cpp new file mode 100644 index 00000000..522da15e --- /dev/null +++ b/2501-3000/2671-Frequency-Tracker/cpp-2671/main.cpp @@ -0,0 +1,69 @@ +/// Source : https://leetcode.com/problems/frequency-tracker/ +/// Author : liuyubobobo +/// Time : 2023-05-06 + +#include +#include +#include + +using namespace std; + + +/// Using Map and Set +/// Time Complexity: O(logn) for each operation +/// Space Complexity: O(n) +class FrequencyTracker { + +private: + map numberToFrequency; + multiset f; + +public: + FrequencyTracker() { + + } + + void add(int number) { + numberToFrequency[number] ++; + int new_f = numberToFrequency[number]; + int old_f = new_f - 1; + if(old_f) f.erase(f.find(old_f)); + f.insert(new_f); + } + + void deleteOne(int number) { + if(numberToFrequency.find(number) == numberToFrequency.end()) return; + + numberToFrequency[number] --; + int new_f = numberToFrequency[number]; + int old_f = new_f + 1; + f.erase(f.find(old_f)); + if(new_f) f.insert(new_f); + + if(new_f == 0) numberToFrequency.erase(number); + } + + bool hasFrequency(int frequency) { + return f.find(frequency) != f.end(); + } +}; + + +int main() { + +// ["FrequencyTracker","deleteOne","hasFrequency","hasFrequency","deleteOne","hasFrequency","hasFrequency","add","deleteOne","deleteOne"] +// [[],[5],[1],[1],[3],[1],[1],[7],[7],[7]] + + FrequencyTracker ft; + ft.deleteOne(5); + cout << ft.hasFrequency(1) << endl; + cout << ft.hasFrequency(1) << endl; + ft.deleteOne(3); + cout << ft.hasFrequency(1) << endl; + cout << ft.hasFrequency(1) << endl; + ft.add(7); + ft.deleteOne(7); + ft.deleteOne(7); + + return 0; +} diff --git a/2501-3000/2672-Number-of-Adjacent-Elements-With-the-Same-Color/cpp-2672/CMakeLists.txt b/2501-3000/2672-Number-of-Adjacent-Elements-With-the-Same-Color/cpp-2672/CMakeLists.txt new file mode 100644 index 00000000..6d269de2 --- /dev/null +++ b/2501-3000/2672-Number-of-Adjacent-Elements-With-the-Same-Color/cpp-2672/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(C) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(C main.cpp) diff --git a/2501-3000/2672-Number-of-Adjacent-Elements-With-the-Same-Color/cpp-2672/main.cpp b/2501-3000/2672-Number-of-Adjacent-Elements-With-the-Same-Color/cpp-2672/main.cpp new file mode 100644 index 00000000..5924d873 --- /dev/null +++ b/2501-3000/2672-Number-of-Adjacent-Elements-With-the-Same-Color/cpp-2672/main.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/number-of-adjacent-elements-with-the-same-color/description/ +/// Author : liuyubobobo +/// Time : 2023-05-06 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(q) +/// Space Complexity: O(n) +class Solution { +public: + vector colorTheArray(int n, vector>& queries) { + + vector nums(n, 0); + int cur = 0; + vector res(queries.size()); + for(int i = 0; i < queries.size(); i++) { + int index = queries[i][0], c = queries[i][1]; + int old_color = nums[index]; + if(c == old_color){ + res[i] = cur; continue; + } + + nums[index] = c; + if(old_color){ + if(index - 1 >= 0 && nums[index - 1] == old_color) cur --; + if(index + 1 < n && nums[index + 1] == old_color) cur --; + } + + if(index - 1 >= 0 && nums[index - 1] == c) cur ++; + if(index + 1 < n && nums[index + 1] == c) cur ++; + + res[i] = cur; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2673-Make-Costs-of-Paths-Equal-in-a-Binary-Tree/cpp-2673/CMakeLists.txt b/2501-3000/2673-Make-Costs-of-Paths-Equal-in-a-Binary-Tree/cpp-2673/CMakeLists.txt new file mode 100644 index 00000000..6a6bdfdb --- /dev/null +++ b/2501-3000/2673-Make-Costs-of-Paths-Equal-in-a-Binary-Tree/cpp-2673/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(D) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(D main.cpp) diff --git a/2501-3000/2673-Make-Costs-of-Paths-Equal-in-a-Binary-Tree/cpp-2673/main.cpp b/2501-3000/2673-Make-Costs-of-Paths-Equal-in-a-Binary-Tree/cpp-2673/main.cpp new file mode 100644 index 00000000..987b996a --- /dev/null +++ b/2501-3000/2673-Make-Costs-of-Paths-Equal-in-a-Binary-Tree/cpp-2673/main.cpp @@ -0,0 +1,39 @@ +/// Source : https://leetcode.com/problems/make-costs-of-paths-equal-in-a-binary-tree/ +/// Author : liuyubobobo +/// Time : 2023-05-06 + +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(h) +class Solution { +public: + int minIncrements(int n, vector& cost) { + + int res = 0; + dfs(n, 0, cost, res); + return res; + } + +private: + int dfs(int n, int cur, const vector& cost, int& res){ + + if(2 * cur + 1 >= n) return cost[cur]; + + int l = dfs(n, 2 * cur + 1, cost, res); + int r = dfs(n, 2 * cur + 2, cost, res); + res += abs(l - r); + return max(l, r) + cost[cur]; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2674-Split-a-Circular-Linked-List/cpp-2674/CMakeLists.txt b/2501-3000/2674-Split-a-Circular-Linked-List/cpp-2674/CMakeLists.txt new file mode 100644 index 00000000..8c6143e7 --- /dev/null +++ b/2501-3000/2674-Split-a-Circular-Linked-List/cpp-2674/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2674) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2674 main.cpp) diff --git a/2501-3000/2674-Split-a-Circular-Linked-List/cpp-2674/main.cpp b/2501-3000/2674-Split-a-Circular-Linked-List/cpp-2674/main.cpp new file mode 100644 index 00000000..acba402f --- /dev/null +++ b/2501-3000/2674-Split-a-Circular-Linked-List/cpp-2674/main.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.com/problems/split-a-circular-linked-list/description/ +/// Author : liuyubobobo +/// Time : 2023-05-12 + +#include +#include + +using namespace std; + + +/// Slow and Fast Pointer +/// Time Complexity: O(n) +/// Space Complexity: O(1) + +/// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode() : val(0), next(nullptr) {} + ListNode(int x) : val(x), next(nullptr) {} + ListNode(int x, ListNode *next) : val(x), next(next) {} +}; + +class Solution { +public: + vector splitCircularLinkedList(ListNode* list) { + + ListNode *slow = list, *fast = list->next; + while(fast->next != list){ + slow = slow->next; + fast = fast->next; + if(fast->next == list) break; + else fast = fast->next; + } + + ListNode *first = list, *second = slow->next; + slow->next = first; + fast->next = second; + return {first, second}; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2678-Number-of-Senior-Citizens/cpp-2678/CMakeLists.txt b/2501-3000/2678-Number-of-Senior-Citizens/cpp-2678/CMakeLists.txt new file mode 100644 index 00000000..8e117464 --- /dev/null +++ b/2501-3000/2678-Number-of-Senior-Citizens/cpp-2678/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2678) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2678 main.cpp) diff --git a/2501-3000/2678-Number-of-Senior-Citizens/cpp-2678/main.cpp b/2501-3000/2678-Number-of-Senior-Citizens/cpp-2678/main.cpp new file mode 100644 index 00000000..2a5d73e4 --- /dev/null +++ b/2501-3000/2678-Number-of-Senior-Citizens/cpp-2678/main.cpp @@ -0,0 +1,31 @@ +/// Source : https://leetcode.com/problems/number-of-senior-citizens/description/ +/// Author : liuyubobobo +/// Time : 2023-05-13 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int countSeniors(vector& details) { + + int res = 0; + for(const string& s: details){ + int age = stoi(s.substr(11, 2)); + res += age > 60; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2679-Sum-in-a-Matrix/cpp-2679/CMakeLists.txt b/2501-3000/2679-Sum-in-a-Matrix/cpp-2679/CMakeLists.txt new file mode 100644 index 00000000..5ba116ef --- /dev/null +++ b/2501-3000/2679-Sum-in-a-Matrix/cpp-2679/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2679) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2679 main.cpp) diff --git a/2501-3000/2679-Sum-in-a-Matrix/cpp-2679/main.cpp b/2501-3000/2679-Sum-in-a-Matrix/cpp-2679/main.cpp new file mode 100644 index 00000000..12b4cb2f --- /dev/null +++ b/2501-3000/2679-Sum-in-a-Matrix/cpp-2679/main.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/sum-in-a-matrix/description/ +/// Author : liuyubobobo +/// Time : 2023-05-13 + +#include +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(R * ClogC) +/// Space Complexity: O(1) +class Solution { +public: + int matrixSum(vector>& nums) { + + for(vector& v: nums) sort(v.begin(), v.end()); + + int res = 0; + for(int c = 0; c < nums[0].size(); c++) { + int maxv = 0; + for(int r = 0; r < nums.size(); r++) maxv = max(maxv, nums[r][c]); + res += maxv; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2680-Maximum-OR/cpp-2680/CMakeLists.txt b/2501-3000/2680-Maximum-OR/cpp-2680/CMakeLists.txt new file mode 100644 index 00000000..b57b907e --- /dev/null +++ b/2501-3000/2680-Maximum-OR/cpp-2680/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2680) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2680 main.cpp) diff --git a/2501-3000/2680-Maximum-OR/cpp-2680/main.cpp b/2501-3000/2680-Maximum-OR/cpp-2680/main.cpp new file mode 100644 index 00000000..cb345c92 --- /dev/null +++ b/2501-3000/2680-Maximum-OR/cpp-2680/main.cpp @@ -0,0 +1,42 @@ +/// Source : https://leetcode.com/problems/maximum-or/description/ +/// Author : liuyubobobo +/// Time : 2023-05-13 + +#include +#include + +using namespace std; + + +/// Bitwise +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + long long maximumOr(vector& nums, int k) { + + vector f(30, 0); + for(int e: nums){ + for(int p = 0; p < 30; p ++) if(e & (1 << p)) f[p] ++; + } + + long long res = 0; + for(int e: nums){ + for(int p = 0; p < 30; p ++) if(e & (1 << p)) f[p] --; + + long long tres = e; + tres <<= k; + for(int p = 0; p < 30; p ++) if(f[p]) tres |= (1ll << p); + res = max(res, tres); + + for(int p = 0; p < 30; p ++) if(e & (1 << p)) f[p] ++; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2681-Power-of-Heroes/cpp-2681/CMakeLists.txt b/2501-3000/2681-Power-of-Heroes/cpp-2681/CMakeLists.txt new file mode 100644 index 00000000..0cae5c55 --- /dev/null +++ b/2501-3000/2681-Power-of-Heroes/cpp-2681/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2681) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2681 main.cpp) diff --git a/2501-3000/2681-Power-of-Heroes/cpp-2681/main.cpp b/2501-3000/2681-Power-of-Heroes/cpp-2681/main.cpp new file mode 100644 index 00000000..62241147 --- /dev/null +++ b/2501-3000/2681-Power-of-Heroes/cpp-2681/main.cpp @@ -0,0 +1,41 @@ +/// Source : https://leetcode.com/problems/power-of-heroes/description/ +/// Author : liuyubobobo +/// Time : 2023-05-13 + +#include +#include +#include + +using namespace std; + + +/// Math +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { + +private: + const long long MOD = 1e9 + 7; + +public: + int sumOfPower(vector& nums) { + + sort(nums.begin(), nums.end()); + + long long min_part = 0, res = 0; + for(long long e: nums){ + res += e * e % MOD * min_part % MOD; + res += e * e % MOD * e % MOD; + res %= MOD; + + min_part = (min_part * 2 + e) % MOD; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2682-Find-the-Losers-of-the-Circular-Game/cpp-2682/CMakeLists.txt b/2501-3000/2682-Find-the-Losers-of-the-Circular-Game/cpp-2682/CMakeLists.txt new file mode 100644 index 00000000..debb2188 --- /dev/null +++ b/2501-3000/2682-Find-the-Losers-of-the-Circular-Game/cpp-2682/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2682) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2682 main.cpp) diff --git a/2501-3000/2682-Find-the-Losers-of-the-Circular-Game/cpp-2682/main.cpp b/2501-3000/2682-Find-the-Losers-of-the-Circular-Game/cpp-2682/main.cpp new file mode 100644 index 00000000..010436bf --- /dev/null +++ b/2501-3000/2682-Find-the-Losers-of-the-Circular-Game/cpp-2682/main.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/find-the-losers-of-the-circular-game/description/ +/// Author : liuyubobobo +/// Time : 2023-05-13 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { +public: + vector circularGameLosers(int n, int k) { + + vector visited(n, false); + for(int i = 1, cur = 0; !visited[cur];i ++){ + visited[cur] = true; + cur = (cur + i * k) % n; + } + + vector res; + for(int i = 0; i < n; i ++) if(!visited[i]) res.push_back(i + 1); + return res; + } +}; + + +int main() { + + + return 0; +} diff --git a/2501-3000/2683-Neighboring-Bitwise-XOR/cpp-2683/CMakeLists.txt b/2501-3000/2683-Neighboring-Bitwise-XOR/cpp-2683/CMakeLists.txt new file mode 100644 index 00000000..5b5e0a19 --- /dev/null +++ b/2501-3000/2683-Neighboring-Bitwise-XOR/cpp-2683/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2683) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2683 main.cpp) diff --git a/2501-3000/2683-Neighboring-Bitwise-XOR/cpp-2683/main.cpp b/2501-3000/2683-Neighboring-Bitwise-XOR/cpp-2683/main.cpp new file mode 100644 index 00000000..e37f63dc --- /dev/null +++ b/2501-3000/2683-Neighboring-Bitwise-XOR/cpp-2683/main.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/neighboring-bitwise-xor/description/ +/// Author : liuyubobobo +/// Time : 2023-05-13 + +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + bool doesValidArrayExist(vector& derived) { + + int n = derived.size(); + return check(n, 0, derived) || check(n, 1, derived); + } + +private: + bool check(int n, int first, const vector& derived){ + + vector v(n, first); + for(int i = 1; i < n; i ++) v[i] = v[i - 1] ^ derived[i - 1]; + return v.back() ^ v[0] == derived.back(); + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2684-Maximum-Number-of-Moves-in-a-Grid/cpp-2684/CMakeLists.txt b/2501-3000/2684-Maximum-Number-of-Moves-in-a-Grid/cpp-2684/CMakeLists.txt new file mode 100644 index 00000000..2edd12ea --- /dev/null +++ b/2501-3000/2684-Maximum-Number-of-Moves-in-a-Grid/cpp-2684/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2684) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2684 main.cpp) diff --git a/2501-3000/2684-Maximum-Number-of-Moves-in-a-Grid/cpp-2684/main.cpp b/2501-3000/2684-Maximum-Number-of-Moves-in-a-Grid/cpp-2684/main.cpp new file mode 100644 index 00000000..4aa9416b --- /dev/null +++ b/2501-3000/2684-Maximum-Number-of-Moves-in-a-Grid/cpp-2684/main.cpp @@ -0,0 +1,45 @@ +/// Source : https://leetcode.com/problems/maximum-number-of-moves-in-a-grid/description/ +/// Author : liuyubobobo +/// Time : 2023-05-13 + +#include +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(R * C) +/// Space Complexity: O(R * C) +class Solution { +public: + int maxMoves(vector>& grid) { + + int R = grid.size(), C = grid[0].size(); + vector> dp(R, vector(C, -1)); + for(int i = 0; i < R; i ++) dp[i][0] = 0; + + for(int j = 0; j + 1 < C; j ++){ + for(int i = 0; i < R; i ++){ + if(dp[i][j] == -1) continue; + for(int d = -1; d <= 1; d ++){ + if(i + d < 0 || i + d >= R) continue; + if(grid[i + d][j + 1] <= grid[i][j]) continue; + dp[i + d][j + 1] = max(dp[i + d][j + 1], dp[i][j] + 1); + } + } + } + + int res = 0; + for(int i = 0; i < R; i ++) res = max(res, *max_element(dp[i].begin(), dp[i].end())); + return res; + } +}; + + +int main() { + + + return 0; +} diff --git a/2501-3000/2685-Count-the-Number-of-Complete-Components/cpp-2685/CMakeLists.txt b/2501-3000/2685-Count-the-Number-of-Complete-Components/cpp-2685/CMakeLists.txt new file mode 100644 index 00000000..281ba124 --- /dev/null +++ b/2501-3000/2685-Count-the-Number-of-Complete-Components/cpp-2685/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2685) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2685 main.cpp) diff --git a/2501-3000/2685-Count-the-Number-of-Complete-Components/cpp-2685/main.cpp b/2501-3000/2685-Count-the-Number-of-Complete-Components/cpp-2685/main.cpp new file mode 100644 index 00000000..3ab0bafd --- /dev/null +++ b/2501-3000/2685-Count-the-Number-of-Complete-Components/cpp-2685/main.cpp @@ -0,0 +1,59 @@ +/// Source : https://leetcode.com/problems/count-the-number-of-complete-components/description/ +/// Author : liuyubobobo +/// Time : 2023-05-13 + +#include +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n + m) +/// Space Complexity: O(n + m) +class Solution { +public: + int countCompleteComponents(int n, vector>& edges) { + + vector> g(n); + for(auto& e : edges) + g[e[0]].push_back(e[1]), g[e[1]].push_back(e[0]); + + vector visited(n, false); + int res = 0; + for(int i = 0; i < n; i++){ + if(visited[i]) continue; + + vector cc; + dfs(g, i, visited, cc); + res += ok(g, cc); + } + return res; + } + +private: + bool ok(const vector>& g, const vector& cc){ + + int d = cc.size() - 1; + for(int u: cc) + if(g[u].size() != d) + return false; + return true; + } + + void dfs(const vector>& g, int u, vector& visited, vector& cc){ + + visited[u] = true; + cc.push_back(u); + for(int v: g[u]) + if(!visited[v]) + dfs(g, v, visited, cc); + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2689-Extract-Kth-Character-From-The-Rope-Tree/cpp-2689/CMakeLists.txt b/2501-3000/2689-Extract-Kth-Character-From-The-Rope-Tree/cpp-2689/CMakeLists.txt new file mode 100644 index 00000000..e9e891ad --- /dev/null +++ b/2501-3000/2689-Extract-Kth-Character-From-The-Rope-Tree/cpp-2689/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2689) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2689 main.cpp) diff --git a/2501-3000/2689-Extract-Kth-Character-From-The-Rope-Tree/cpp-2689/main.cpp b/2501-3000/2689-Extract-Kth-Character-From-The-Rope-Tree/cpp-2689/main.cpp new file mode 100644 index 00000000..b9277536 --- /dev/null +++ b/2501-3000/2689-Extract-Kth-Character-From-The-Rope-Tree/cpp-2689/main.cpp @@ -0,0 +1,49 @@ +/// Source : https://leetcode.com/problems/extract-kth-character-from-the-rope-tree/description/ +/// Author : liuyubobobo +/// Time : 2023-05-17 + +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// Definition for a rope tree node. +struct RopeTreeNode { + int len; + string val; + RopeTreeNode *left; + RopeTreeNode *right; + RopeTreeNode() : len(0), val(""), left(nullptr), right(nullptr) {} + RopeTreeNode(string s) : len(0), val(std::move(s)), left(nullptr), right(nullptr) {} + RopeTreeNode(int x) : len(x), val(""), left(nullptr), right(nullptr) {} + RopeTreeNode(int x, RopeTreeNode *left, RopeTreeNode *right) : len(x), val(""), left(left), right(right) {} +}; + +class Solution { +public: + char getKthCharacter(RopeTreeNode* root, int k) { + + return dfs(root, k); + } + +private: + char dfs(RopeTreeNode* node, int k) { + + if(node->len == 0) return node->val[k - 1]; + + int left_len = node->left ? (node->left->len ? node->left->len : node->left->val.size()) : 0; + if(k <= left_len) return dfs(node->left, k); + return dfs(node->right, k - left_len); + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2696-Minimum-String-Length-After-Removing-Substrings/cpp-2696/CMakeLists.txt b/2501-3000/2696-Minimum-String-Length-After-Removing-Substrings/cpp-2696/CMakeLists.txt new file mode 100644 index 00000000..c566a118 --- /dev/null +++ b/2501-3000/2696-Minimum-String-Length-After-Removing-Substrings/cpp-2696/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2696) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2696 main.cpp) diff --git a/2501-3000/2696-Minimum-String-Length-After-Removing-Substrings/cpp-2696/main.cpp b/2501-3000/2696-Minimum-String-Length-After-Removing-Substrings/cpp-2696/main.cpp new file mode 100644 index 00000000..9b44c506 --- /dev/null +++ b/2501-3000/2696-Minimum-String-Length-After-Removing-Substrings/cpp-2696/main.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/minimum-string-length-after-removing-substrings/description/ +/// Author : liuyubobobo +/// Time : 2023-05-21 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(|s|^2) +/// Space Complexity: O(|s|) +class Solution { +public: + int minLength(string s) { + + while(true){ + bool flag = false; + if(s.find("AB") != string::npos) + s.replace(s.find("AB"), 2, ""), flag = true; + if(s.find("CD") != string::npos) + s.replace(s.find("CD"), 2, ""), flag = true; + if(!flag) break; + } + return s.size(); + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2697-Lexicographically-Smallest-Palindrome/cpp-2697/CMakeLists.txt b/2501-3000/2697-Lexicographically-Smallest-Palindrome/cpp-2697/CMakeLists.txt new file mode 100644 index 00000000..0c627a93 --- /dev/null +++ b/2501-3000/2697-Lexicographically-Smallest-Palindrome/cpp-2697/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2697) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2697 main.cpp) diff --git a/2501-3000/2697-Lexicographically-Smallest-Palindrome/cpp-2697/main.cpp b/2501-3000/2697-Lexicographically-Smallest-Palindrome/cpp-2697/main.cpp new file mode 100644 index 00000000..48f3ca61 --- /dev/null +++ b/2501-3000/2697-Lexicographically-Smallest-Palindrome/cpp-2697/main.cpp @@ -0,0 +1,30 @@ +/// Source : https://leetcode.com/problems/lexicographically-smallest-palindrome/description/ +/// Author : liuyubobobo +/// Time : 2023-05-21 + +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + string makeSmallestPalindrome(string s) { + + int n = s.size(); + for(int i = 0, j = n - 1; i < j; i ++, j --){ + char min_char = min(s[i], s[j]); + s[i] = s[j] = min_char; + } + return s; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2698-Find-the-Punishment-Number-of-an-Integer/cpp-2698/CMakeLists.txt b/2501-3000/2698-Find-the-Punishment-Number-of-an-Integer/cpp-2698/CMakeLists.txt new file mode 100644 index 00000000..2b1f2172 --- /dev/null +++ b/2501-3000/2698-Find-the-Punishment-Number-of-an-Integer/cpp-2698/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2698) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2698 main.cpp) diff --git a/2501-3000/2698-Find-the-Punishment-Number-of-an-Integer/cpp-2698/main.cpp b/2501-3000/2698-Find-the-Punishment-Number-of-an-Integer/cpp-2698/main.cpp new file mode 100644 index 00000000..eeb0e32d --- /dev/null +++ b/2501-3000/2698-Find-the-Punishment-Number-of-an-Integer/cpp-2698/main.cpp @@ -0,0 +1,51 @@ +/// Source : https://leetcode.com/problems/find-the-punishment-number-of-an-integer/description/ +/// Author : liuyubobobo +/// Time : 2023-05-21 + +#include +#include + +using namespace std; + + +/// Memoization +/// Time Complexity: O(n * n * logn) +/// Space Complexity: O(nlogn) +class Solution { +public: + int punishmentNumber(int n) { + + int res = 0; + for(int i = 1; i <= n; i ++){ + int num = i * i; + if(check(num, i)) res += num; + } + return res; + } + +private: + bool check(int num, int sum){ + string num_str = to_string(num); + vector> dp(num_str.size(), vector(sum + 1, -1)); + return dfs(num_str, 0, sum, dp); + } + + int dfs(const string& s, int index, int sum, vector>& dp){ + + if(index == s.size()) return sum == 0; + if(sum < 0) return 0; + if(dp[index][sum] != -1) return dp[index][sum]; + + int cur = 0; + for(int i = index; i < s.size(); i ++){ + cur = cur * 10 + (s[i] - '0'); + if(dfs(s, i + 1, sum - cur, dp)) return dp[index][sum] = 1; + } + return dp[index][sum] = 0; + } +}; + +int main() { + + return 0; +} diff --git a/2501-3000/2699-Modify-Graph-Edge-Weights/cpp-2699/CMakeLists.txt b/2501-3000/2699-Modify-Graph-Edge-Weights/cpp-2699/CMakeLists.txt new file mode 100644 index 00000000..8efe1dc4 --- /dev/null +++ b/2501-3000/2699-Modify-Graph-Edge-Weights/cpp-2699/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2699) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2699 main.cpp) diff --git a/2501-3000/2699-Modify-Graph-Edge-Weights/cpp-2699/main.cpp b/2501-3000/2699-Modify-Graph-Edge-Weights/cpp-2699/main.cpp new file mode 100644 index 00000000..8996841d --- /dev/null +++ b/2501-3000/2699-Modify-Graph-Edge-Weights/cpp-2699/main.cpp @@ -0,0 +1,102 @@ +/// Source : https://leetcode.com/problems/modify-graph-edge-weights/description/ +/// Author : liuyubobobo +/// Time : 2023-05-21 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(n^2 * log(target) * n^2 * logn) +/// Space Complexity: O(n^2) +class Solution { + +private: + const long long INF = LONG_LONG_MAX / 2; + long long MAXW = 1000000000ll; + +public: + vector> modifiedGraphEdges(int n, vector>& edges, int source, int destination, int target) { + + MAXW = target; + + vector> g(n, vector(n, INF)); + for(const vector& edge: edges) { + int u = edge[0], v = edge[1], w = edge[2]; + if(w == -1) w = MAXW; + g[u][v] = g[v][u] = w; + } + + long long dis = dij(n, g, source, destination); + if(dis < target) return {}; + if(dis == target){ + for(vector& edge: edges) if(edge[2] == -1) edge[2] = MAXW; + return edges; + } + + for(vector& edge: edges){ + if(edge[2] == -1){ + int u = edge[0], v = edge[1]; + long long l = 1, r = MAXW; + while(l < r){ + long long mid = (l + r) / 2; + g[u][v] = g[v][u] = mid; + long long tdis = dij(n, g, source, destination); + if(tdis < target) l = mid + 1; + else r = mid; + } + g[u][v] = g[v][u] = l; + } + } + + if(dij(n, g, source, destination) != target) return {}; + for(vector& edge: edges) edge[2] = g[edge[0]][edge[1]]; + return edges; + } + +private: + long long dij(int n, const vector>& g, int s, int t){ + + vector dis(n, INF); + vector visited(n, false); + + priority_queue, vector>, greater<>> pq; + pq.push({0, s}); + dis[s] = 0; + while(!pq.empty()){ + long long d = pq.top().first; int u = pq.top().second; pq.pop(); + if(visited[u]) continue; + visited[u] = true; + + for(int v = 0; v < n; v ++){ + if(visited[v]) continue; + long long w = g[u][v]; + if(d + w < dis[v]){ + dis[v] = d + w; + pq.push({dis[v], v}); + } + } + } + return dis[t]; + } +}; + + +void print_vec(const vector>& v){ + for(const vector& e: v){ + for(int x: e) cout << x << ' '; cout << '\n'; + } +} + +int main() { + + vector> edges1 = {{4, 1, -1}, {2, 0, -1}, {0, 3, -1}, {4, 3, -1}}; + print_vec(Solution().modifiedGraphEdges(5, edges1, 0, 1, 5)); + + return 0; +} diff --git a/2501-3000/2702-Minimum-Operations-to-Make-Numbers-Non-positive/cpp-2702/CMakeLists.txt b/2501-3000/2702-Minimum-Operations-to-Make-Numbers-Non-positive/cpp-2702/CMakeLists.txt new file mode 100644 index 00000000..019579d7 --- /dev/null +++ b/2501-3000/2702-Minimum-Operations-to-Make-Numbers-Non-positive/cpp-2702/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2702) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2702 main.cpp) diff --git a/2501-3000/2702-Minimum-Operations-to-Make-Numbers-Non-positive/cpp-2702/main.cpp b/2501-3000/2702-Minimum-Operations-to-Make-Numbers-Non-positive/cpp-2702/main.cpp new file mode 100644 index 00000000..0180d347 --- /dev/null +++ b/2501-3000/2702-Minimum-Operations-to-Make-Numbers-Non-positive/cpp-2702/main.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode.com/problems/minimum-operations-to-make-numbers-non-positive/description/ +/// Author : liuyubobobo +/// Time : 2023-05-26 + +#include +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(nlog(max(nums))) +/// Space Complexity: O(1) +class Solution { +public: + int minOperations(vector& nums, int x, int y) { + + long long l = 0, r = *max_element(nums.begin(), nums.end()); + while(l < r){ + long long mid = (l + r) / 2; + if(ok(nums, x, y, mid)) r = mid; + else l = mid + 1; + } + return l; + } + +private: + bool ok(vector& nums, long long x, long long y, long long k) { + + long long cnt = 0; + for (long long e: nums) { + e -= k * y; + if (e <= 0) continue; + cnt += e / (x - y) + !!(e % (x - y)); + } + return cnt <= k; + } +}; + + +int main() { + + vector nums1 = {3, 4, 1, 7, 6}; + cout << Solution().minOperations(nums1, 4, 2) << '\n'; + // 3 + + vector nums2 = {1, 2, 1}; + cout << Solution().minOperations(nums2, 2, 1) << '\n'; + // 1 + + vector nums3 = {74, 92, 25, 65, 77, 1, 73}; + cout << Solution().minOperations(nums3, 10, 4) << '\n'; + // 16 + + return 0; +} diff --git a/2501-3000/2706-Buy-Two-Chocolates/cpp-2706/CMakeLists.txt b/2501-3000/2706-Buy-Two-Chocolates/cpp-2706/CMakeLists.txt new file mode 100644 index 00000000..8a306afe --- /dev/null +++ b/2501-3000/2706-Buy-Two-Chocolates/cpp-2706/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(A) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(A main.cpp) diff --git a/2501-3000/2706-Buy-Two-Chocolates/cpp-2706/main.cpp b/2501-3000/2706-Buy-Two-Chocolates/cpp-2706/main.cpp new file mode 100644 index 00000000..f52cd2ce --- /dev/null +++ b/2501-3000/2706-Buy-Two-Chocolates/cpp-2706/main.cpp @@ -0,0 +1,29 @@ +/// Source : https://leetcode.com/problems/buy-two-chocolates/ +/// Author : liuyubobobo +/// Time : 2023-05-27 + +#include +#include +#include + +using namespace std; + + +/// Sorting +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + int buyChoco(vector& prices, int money) { + + sort(prices.begin(), prices.end()); + int left = money - prices[0] - prices[1]; + return left >= 0 ? left : money; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2707-Extra-Characters-in-a-String/cpp-2707/CMakeLists.txt b/2501-3000/2707-Extra-Characters-in-a-String/cpp-2707/CMakeLists.txt new file mode 100644 index 00000000..3e27b177 --- /dev/null +++ b/2501-3000/2707-Extra-Characters-in-a-String/cpp-2707/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(B) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(B main.cpp) diff --git a/2501-3000/2707-Extra-Characters-in-a-String/cpp-2707/main.cpp b/2501-3000/2707-Extra-Characters-in-a-String/cpp-2707/main.cpp new file mode 100644 index 00000000..733abfe4 --- /dev/null +++ b/2501-3000/2707-Extra-Characters-in-a-String/cpp-2707/main.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.com/problems/extra-characters-in-a-string/ +/// Author : liuyubobobo +/// Time : 2023-05-27 + +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(n * all_word_length) +/// Space Complexity: O(n) +class Solution { +public: + int minExtraChar(string s, vector& dictionary) { + + int n = s.size(); + vector dp(n + 1, 0); + for(int i = n - 1; i >= 0; i --){ + dp[i] = dp[i + 1]; + for(const string& word: dictionary) + if(s.find(word, i) == i) + dp[i] = max(dp[i], (int)word.size() + dp[i + word.size()]); + } + + return n - *max_element(dp.begin(), dp.end()); + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2708-Maximum-Strength-of-a-Group/cpp-2708/CMakeLists.txt b/2501-3000/2708-Maximum-Strength-of-a-Group/cpp-2708/CMakeLists.txt new file mode 100644 index 00000000..6d269de2 --- /dev/null +++ b/2501-3000/2708-Maximum-Strength-of-a-Group/cpp-2708/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(C) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(C main.cpp) diff --git a/2501-3000/2708-Maximum-Strength-of-a-Group/cpp-2708/main.cpp b/2501-3000/2708-Maximum-Strength-of-a-Group/cpp-2708/main.cpp new file mode 100644 index 00000000..75eab927 --- /dev/null +++ b/2501-3000/2708-Maximum-Strength-of-a-Group/cpp-2708/main.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/maximum-strength-of-a-group/ +/// Author : liuyubobobo +/// Time : 2023-05-27 + +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(2^n) +/// Space Complexity: O(2^n) +class Solution { +public: + long long maxStrength(vector& nums) { + + int n = nums.size(); + + vector dp(1 << n, 1); + for(int state = 1; state < (1 << n); state ++){ + int p = __builtin_ffs(state) - 1; + dp[state] = dp[state ^ (1 << p)] * nums[p]; + } + return *max_element(dp.begin() + 1, dp.end()); + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2709-Greatest-Common-Divisor-Traversal/cpp-2709/CMakeLists.txt b/2501-3000/2709-Greatest-Common-Divisor-Traversal/cpp-2709/CMakeLists.txt new file mode 100644 index 00000000..6a6bdfdb --- /dev/null +++ b/2501-3000/2709-Greatest-Common-Divisor-Traversal/cpp-2709/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(D) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(D main.cpp) diff --git a/2501-3000/2709-Greatest-Common-Divisor-Traversal/cpp-2709/main.cpp b/2501-3000/2709-Greatest-Common-Divisor-Traversal/cpp-2709/main.cpp new file mode 100644 index 00000000..150c92e2 --- /dev/null +++ b/2501-3000/2709-Greatest-Common-Divisor-Traversal/cpp-2709/main.cpp @@ -0,0 +1,99 @@ +/// Source : https://leetcode.com/problems/greatest-common-divisor-traversal/description/ +/// Author : liuyubobobo +/// Time : 2023-05-27 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// Sieve Table + UF +/// Time Complexity: O(n * log(max(nums[i]))) +/// Space Complexity: O(n * log(max(nums[i]))) +class UF{ + +private: + vector parent; + int total; + +public: + UF(int n) : parent(n), total(n){ + for(int i = 0 ; i < n ; i ++) + parent[i] = i; + } + + int find(int p){ + if(p != parent[p]) + parent[p] = find(parent[p]); + return parent[p]; + } + + bool is_connected(int p, int q){ + return find(p) == find(q); + } + + void union_elements(int p, int q){ + + int p_root = find(p), q_root = find(q); + + if(p_root == q_root) return; + + parent[p_root] = q_root; + total --; + } + + int get_total(){ + return total; + } +}; + +class Solution { +public: + bool canTraverseAllPairs(vector& nums) { + + vector sieve_table = sieve(*max_element(nums.begin(), nums.end())); + map> table; // d -> index list + for(int i = 0; i < nums.size(); i ++){ + int e = nums[i]; + while(e > 1){ + int p = sieve_table[e]; + table[p].push_back(i); + while(e % p == 0) e /= p; + } + } + + UF uf(nums.size()); + for(const pair>& row: table){ + for(int i = 1; i < row.second.size(); i ++) + uf.union_elements(row.second[i - 1], row.second[i]); + } + return uf.get_total() == 1; + } + +private: + vector sieve(int n){ + + vector table(n + 1, 0); + vector primes; + table[0] = table[1] = 1; + for(int i = 2; i <= n; i ++){ + if(table[i] == 0) { + primes.push_back(i); + table[i] = i; + } + for(int j = 0; j < primes.size() && primes[j] <= table[i] && i * primes[j] <= n; j ++) + table[i * primes[j]] = primes[j]; + } + return table; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2710-Remove-Trailing-Zeros-From-a-String/cpp-2710/CMakeLists.txt b/2501-3000/2710-Remove-Trailing-Zeros-From-a-String/cpp-2710/CMakeLists.txt new file mode 100644 index 00000000..8a306afe --- /dev/null +++ b/2501-3000/2710-Remove-Trailing-Zeros-From-a-String/cpp-2710/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(A) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(A main.cpp) diff --git a/2501-3000/2710-Remove-Trailing-Zeros-From-a-String/cpp-2710/main.cpp b/2501-3000/2710-Remove-Trailing-Zeros-From-a-String/cpp-2710/main.cpp new file mode 100644 index 00000000..bc8b7ac3 --- /dev/null +++ b/2501-3000/2710-Remove-Trailing-Zeros-From-a-String/cpp-2710/main.cpp @@ -0,0 +1,26 @@ +/// Source : https://leetcode.com/problems/remove-trailing-zeros-from-a-string/description/ +/// Author : liuyubobobo +/// Time : 2023-05-27 + +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(|num|) +/// Space Complexity: O(|num|) +class Solution { +public: + string removeTrailingZeros(string num) { + + while(!num.empty() && num.back() == '0') num.pop_back(); + return num; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2711-Difference-of-Number-of-Distinct-Values-on-Diagonals/cpp-2711/CMakeLists.txt b/2501-3000/2711-Difference-of-Number-of-Distinct-Values-on-Diagonals/cpp-2711/CMakeLists.txt new file mode 100644 index 00000000..3e27b177 --- /dev/null +++ b/2501-3000/2711-Difference-of-Number-of-Distinct-Values-on-Diagonals/cpp-2711/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(B) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(B main.cpp) diff --git a/2501-3000/2711-Difference-of-Number-of-Distinct-Values-on-Diagonals/cpp-2711/main.cpp b/2501-3000/2711-Difference-of-Number-of-Distinct-Values-on-Diagonals/cpp-2711/main.cpp new file mode 100644 index 00000000..486196bc --- /dev/null +++ b/2501-3000/2711-Difference-of-Number-of-Distinct-Values-on-Diagonals/cpp-2711/main.cpp @@ -0,0 +1,51 @@ +/// Source : https://leetcode.com/problems/difference-of-number-of-distinct-values-on-diagonals/ +/// Author : liuyubobobo +/// Time : 2023-05-27 + +#include +#include +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(R * C * max(R, C)) +/// Space Complexity: O(1) +class Solution { +public: + vector> differenceOfDistinctValues(vector>& grid) { + + int R = grid.size(), C = grid[0].size(); + + vector> res(R, vector(C)); + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++) + res[i][j] = solve(R, C, grid, i, j); + return res; + } + +private: + int solve(int R, int C, vector>& grid, int x, int y){ + + int cx = x, cy = y; + set s1; + while(-- cx >= 0 && -- cy >= 0) + s1.insert(grid[cx][cy]); + + cx = x, cy = y; + set s2; + while(++ cx < R && ++ cy < C) + s2.insert(grid[cx][cy]); + + int t = (int)s1.size() - (int)s2.size(); + return abs(t); + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2712-Minimum-Cost-to-Make-All-Characters-Equal/cpp-2712/CMakeLists.txt b/2501-3000/2712-Minimum-Cost-to-Make-All-Characters-Equal/cpp-2712/CMakeLists.txt new file mode 100644 index 00000000..6d269de2 --- /dev/null +++ b/2501-3000/2712-Minimum-Cost-to-Make-All-Characters-Equal/cpp-2712/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(C) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(C main.cpp) diff --git a/2501-3000/2712-Minimum-Cost-to-Make-All-Characters-Equal/cpp-2712/main.cpp b/2501-3000/2712-Minimum-Cost-to-Make-All-Characters-Equal/cpp-2712/main.cpp new file mode 100644 index 00000000..d10b39a9 --- /dev/null +++ b/2501-3000/2712-Minimum-Cost-to-Make-All-Characters-Equal/cpp-2712/main.cpp @@ -0,0 +1,56 @@ +/// Source : https://leetcode.com/problems/minimum-cost-to-make-all-characters-equal/description/ +/// Author : liuyubobobo +/// Time : 2023-05-27 + +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + long long minimumCost(string s) { + + int n = s.size(); + deque> pos0, pos1; + for(int start = 0, i = 1; i <= n; i ++){ + if(i == n || s[i] != s[start]){ + int a = start, b = i - 1; + if(s[start] == '0') pos0.push_back({a, b}); + else pos1.push_back({a, b}); + start = i; + } + } + return min(solve(n, pos0), solve(n, pos1)); + } + +private: + long long solve(int n, deque>& pos){ + + long long res = 0; + while(!pos.empty()){ + int tres1 = pos.front().second + 1 + pos.front().first; + int tres2 = (n - pos.back().first) + (n - (pos.back().second + 1)); + + if(tres1 < tres2) res += tres1, pos.pop_front(); + else res += tres2, pos.pop_back(); + } + return res; + } +}; + + +int main() { + + cout << Solution().minimumCost("0011") << '\n'; + // 2 + + cout << Solution().minimumCost("010101") << '\n'; + // 9 + + return 0; +} diff --git a/2501-3000/2713-Maximum-Strictly-Increasing-Cells-in-a-Matrix/cpp-2713/CMakeLists.txt b/2501-3000/2713-Maximum-Strictly-Increasing-Cells-in-a-Matrix/cpp-2713/CMakeLists.txt new file mode 100644 index 00000000..5a9eabe1 --- /dev/null +++ b/2501-3000/2713-Maximum-Strictly-Increasing-Cells-in-a-Matrix/cpp-2713/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(D) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(D main2.cpp) diff --git a/2501-3000/2713-Maximum-Strictly-Increasing-Cells-in-a-Matrix/cpp-2713/main.cpp b/2501-3000/2713-Maximum-Strictly-Increasing-Cells-in-a-Matrix/cpp-2713/main.cpp new file mode 100644 index 00000000..e4fb785e --- /dev/null +++ b/2501-3000/2713-Maximum-Strictly-Increasing-Cells-in-a-Matrix/cpp-2713/main.cpp @@ -0,0 +1,66 @@ +#include +#include +#include +#include + +using namespace std; + + +class Solution { +public: + int maxIncreasingCells(vector>& mat) { + + int R = mat.size(), C = mat[0].size(); + + priority_queue, vector>, greater<>> pq; + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++) pq.push({mat[i][j], i * C + j}); + + vector row(R, 0), col(C, 0); + vector rowv(R, INT_MIN), colv(C, INT_MIN); + vector> dp(R, vector(C, 0)); + int res = 0; + while(!pq.empty()){ + int v = pq.top().first, pos = pq.top().second; + pq.pop(); + int r = pos / C, c = pos % C; + + if(v > rowv[r]) dp[r][c] = max(dp[r][c], row[r] + 1); + else dp[r][c] = max(dp[r][c], row[r]); + if(v > colv[c]) dp[r][c] = max(dp[r][c], col[c] + 1); + else dp[r][c] = max(dp[r][c], col[c]); + + if(dp[r][c] > row[r]) row[r] = dp[r][c], rowv[r] = v; + if(dp[r][c] > col[c]) col[c] = dp[r][c], colv[c] = v; + + res = max(res, dp[r][c]); + } + return res; + } +}; + + +int main() { + +// vector> mat1 = {{3, 1}, {3, 4}}; +// cout << Solution().maxIncreasingCells(mat1) << '\n'; +// // 2 +// +// vector> mat2 = {{1, 1}, {1, 1}}; +// cout << Solution().maxIncreasingCells(mat2) << '\n'; +// // 1 +// +// vector> mat3 = {{3, 1, 6}, {-9, 5, 7}}; +// cout << Solution().maxIncreasingCells(mat3) << '\n'; +// // 4 +// +// vector> mat4 = {{7, 6, 3}, {-7, -5, 6}, {-7, 0, -4}, {6, 6, 0}, {-8, 6, 0}}; +// cout << Solution().maxIncreasingCells(mat4) << '\n'; +// // 7 + + vector> mat5 = {{3, 1}, {3, 4}}; + cout << Solution().maxIncreasingCells(mat5) << '\n'; + // 2 + + return 0; +} diff --git a/2501-3000/2713-Maximum-Strictly-Increasing-Cells-in-a-Matrix/cpp-2713/main2.cpp b/2501-3000/2713-Maximum-Strictly-Increasing-Cells-in-a-Matrix/cpp-2713/main2.cpp new file mode 100644 index 00000000..c3b083d7 --- /dev/null +++ b/2501-3000/2713-Maximum-Strictly-Increasing-Cells-in-a-Matrix/cpp-2713/main2.cpp @@ -0,0 +1,83 @@ +/// Source : https://leetcode.com/problems/maximum-strictly-increasing-cells-in-a-matrix/description/ +/// Author : liuyubobobo +/// Time : 2023-05-27 + +#include +#include +#include +#include + +using namespace std; + + +/// DAG DP +/// Time Complexity: O(R * C * log(R * C)) +/// Space Complexity: O(R + C) +class Solution { +public: + int maxIncreasingCells(vector>& mat) { + + int R = mat.size(), C = mat[0].size(); + + priority_queue, vector>, greater<>> pq; + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++) pq.push({mat[i][j], i * C + j}); + + vector row1(R, 0), col1(C, 0), row2(R, 0), col2(C, 0); + vector rowv1(R, INT_MIN), colv1(C, INT_MIN), rowv2(R, INT_MIN), colv2(C, INT_MIN); + vector> dp(R, vector(C, 0)); + int res = 0; + while(!pq.empty()){ + int v = pq.top().first, pos = pq.top().second; + pq.pop(); + int r = pos / C, c = pos % C; + + if(v > rowv1[r]) dp[r][c] = max(dp[r][c], row1[r] + 1); + else dp[r][c] = max(dp[r][c], row2[r] + 1); + + if(v > colv1[c]) dp[r][c] = max(dp[r][c], col1[c] + 1); + else dp[r][c] = max(dp[r][c], col2[c] + 1); + + if(v > rowv1[r] && dp[r][c] > row1[r]){ + row2[r] = row1[r], rowv2[r] = rowv1[r]; + row1[r] = dp[r][c], rowv1[r] = v; + } + else if(v == rowv1[r] && dp[r][c] > row1[r]) row1[r] = dp[r][c]; + + if(v > colv1[c] && dp[r][c] > col1[c]){ + col2[c] = col1[c], colv2[c] = colv1[c]; + col1[c] = dp[r][c], colv1[c] = v; + } + else if(v == colv1[c] && dp[r][c] > col1[c]) col1[c] = dp[r][c]; + + res = max(res, dp[r][c]); + } + return res; + } +}; + + +int main() { + + vector> mat1 = {{3, 1}, {3, 4}}; + cout << Solution().maxIncreasingCells(mat1) << '\n'; + // 2 + + vector> mat2 = {{1, 1}, {1, 1}}; + cout << Solution().maxIncreasingCells(mat2) << '\n'; + // 1 + + vector> mat3 = {{3, 1, 6}, {-9, 5, 7}}; + cout << Solution().maxIncreasingCells(mat3) << '\n'; + // 4 + + vector> mat4 = {{7, 6, 3}, {-7, -5, 6}, {-7, 0, -4}, {6, 6, 0}, {-8, 6, 0}}; + cout << Solution().maxIncreasingCells(mat4) << '\n'; + // 7 + + vector> mat5 = {{3, 1}, {3, 4}}; + cout << Solution().maxIncreasingCells(mat5) << '\n'; + // 2 + + return 0; +} diff --git a/2501-3000/2714-Find-Shortest-Path-with-K-Hops/cpp-2714/CMakeLists.txt b/2501-3000/2714-Find-Shortest-Path-with-K-Hops/cpp-2714/CMakeLists.txt new file mode 100644 index 00000000..e497d7db --- /dev/null +++ b/2501-3000/2714-Find-Shortest-Path-with-K-Hops/cpp-2714/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2714) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2714 main.cpp) diff --git a/2501-3000/2714-Find-Shortest-Path-with-K-Hops/cpp-2714/main.cpp b/2501-3000/2714-Find-Shortest-Path-with-K-Hops/cpp-2714/main.cpp new file mode 100644 index 00000000..089f4031 --- /dev/null +++ b/2501-3000/2714-Find-Shortest-Path-with-K-Hops/cpp-2714/main.cpp @@ -0,0 +1,73 @@ +/// Source : https://leetcode.com/problems/find-shortest-path-with-k-hops/description/ +/// Author : liuyubobobo +/// Time : 2023-06-03 + +#include +#include +#include +#include + +using namespace std; + + +/// Dijkstra +/// Time Complexity: O(nk * log(n * k)) +/// Space Complexity: O(n * k) +class Solution { + +private: + const int INF = INT_MAX / 2; + +public: + int shortestPathWithHops(int n, vector>& edges, int s, int t, int k) { + + vector>> g(n); + for(auto& e : edges) { + int u = e[0], v = e[1], w = e[2]; + g[u].push_back({v, w}), g[v].push_back({u, w}); + } + + priority_queue>, vector>>, greater<>> pq; + vector> dis(n, vector(k + 1, INF)); + vector> visited(n, vector(k + 1, false)); + pq.push({0, {s, k}}); + dis[s][k] = 0; + + while(!pq.empty()) { + const pair> p = pq.top(); pq.pop(); + int d = p.first, u = p.second.first, h = p.second.second; + + if(visited[u][h]) continue; + visited[u][h] = true; +// cout << u << " " << h << " " << d << endl; + + if(h){ + for(const pair& e : g[u]) { + int v = e.first, w = e.second; + if(!visited[v][h - 1] && dis[v][h - 1] > d) { + dis[v][h - 1] = d; + pq.push({d, {v, h - 1}}); + } + } + } + + for(const pair& e : g[u]) { + int v = e.first, w = e.second; + if(!visited[v][h] && dis[v][h] > d + w) { + dis[v][h] = d + w; + pq.push({d + w, {v, h}}); + } + } + } + return *min_element(dis[t].begin(), dis[t].end()); + } +}; + + +int main() { + + vector> edges1 = {{0,1,4},{0,2,2},{2,3,6}}; + cout << Solution().shortestPathWithHops(4, edges1, 1, 3, 2) << endl; + + return 0; +} diff --git a/2501-3000/2716-Minimize-String-Length/cpp-2716/CMakeLists.txt b/2501-3000/2716-Minimize-String-Length/cpp-2716/CMakeLists.txt new file mode 100644 index 00000000..de76dea0 --- /dev/null +++ b/2501-3000/2716-Minimize-String-Length/cpp-2716/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2716) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2716 main.cpp) diff --git a/2501-3000/2716-Minimize-String-Length/cpp-2716/main.cpp b/2501-3000/2716-Minimize-String-Length/cpp-2716/main.cpp new file mode 100644 index 00000000..2625e792 --- /dev/null +++ b/2501-3000/2716-Minimize-String-Length/cpp-2716/main.cpp @@ -0,0 +1,29 @@ +/// Source : https://leetcode.com/problems/minimize-string-length/description/ +/// Author : liuyubobobo +/// Time : 2023-06-04 + +#include +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int minimizedStringLength(string s) { + + vector visited(26, false); + for(char c: s) visited[c - 'a'] = true; + return accumulate(visited.begin(), visited.end(), 0); + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2717-Semi-Ordered-Permutation/cpp-2717/CMakeLists.txt b/2501-3000/2717-Semi-Ordered-Permutation/cpp-2717/CMakeLists.txt new file mode 100644 index 00000000..04397242 --- /dev/null +++ b/2501-3000/2717-Semi-Ordered-Permutation/cpp-2717/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2717) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2717 main.cpp) diff --git a/2501-3000/2717-Semi-Ordered-Permutation/cpp-2717/main.cpp b/2501-3000/2717-Semi-Ordered-Permutation/cpp-2717/main.cpp new file mode 100644 index 00000000..5787ff57 --- /dev/null +++ b/2501-3000/2717-Semi-Ordered-Permutation/cpp-2717/main.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/semi-ordered-permutation/description/ +/// Author : liuyubobobo +/// Time : 2023-06-04 + +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int semiOrderedPermutation(vector& nums) { + + int n = nums.size(); + + int pos_1 = find(nums.begin(), nums.end(), 1) - nums.begin(); + int pos_n = find(nums.begin(), nums.end(), n) - nums.begin(); + + int res = pos_1 + n - 1 - pos_n; + if(pos_1 > pos_n) res--; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2718-Sum-of-Matrix-After-Queries/cpp-2718/CMakeLists.txt b/2501-3000/2718-Sum-of-Matrix-After-Queries/cpp-2718/CMakeLists.txt new file mode 100644 index 00000000..72d0e064 --- /dev/null +++ b/2501-3000/2718-Sum-of-Matrix-After-Queries/cpp-2718/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2718) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2718 main.cpp) diff --git a/2501-3000/2718-Sum-of-Matrix-After-Queries/cpp-2718/main.cpp b/2501-3000/2718-Sum-of-Matrix-After-Queries/cpp-2718/main.cpp new file mode 100644 index 00000000..82dbc157 --- /dev/null +++ b/2501-3000/2718-Sum-of-Matrix-After-Queries/cpp-2718/main.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/sum-of-matrix-after-queries/description/ +/// Author : liuyubobobo +/// Time : 2023-06-04 + +#include +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(|queries|) +/// Space Complexity: O(n) +class Solution { +public: + long long matrixSumQueries(int n, vector>& queries) { + + long long res = 0; + + vector row_visited(n, false), col_visited(n, false); + int row_left = n, col_left = n; + + for(int i = queries.size() - 1; i >= 0; i --){ + int type = queries[i][0], index = queries[i][1], val = queries[i][2]; + + if(type == 0){ + if(row_visited[index]) continue; + + res += (long long)val * col_left; + row_visited[index] = true; + row_left --; + } + else{ + if(col_visited[index]) continue; + + res += (long long)val * row_left; + col_visited[index] = true; + col_left --; + } + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2719-Count-of-Integers/cpp-2719/CMakeLists.txt b/2501-3000/2719-Count-of-Integers/cpp-2719/CMakeLists.txt new file mode 100644 index 00000000..dec1b17c --- /dev/null +++ b/2501-3000/2719-Count-of-Integers/cpp-2719/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2719) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2719 main.cpp) diff --git a/2501-3000/2719-Count-of-Integers/cpp-2719/main.cpp b/2501-3000/2719-Count-of-Integers/cpp-2719/main.cpp new file mode 100644 index 00000000..0dcc4c99 --- /dev/null +++ b/2501-3000/2719-Count-of-Integers/cpp-2719/main.cpp @@ -0,0 +1,73 @@ +/// Source : https://leetcode.com/problems/count-of-integers/description/ +/// Author : liuyubobobo +/// Time : 2023-06-04 + +#include +#include + +using namespace std; + + +/// Digital DP +/// Time Complexity: O(len(num2) * max_sum) +/// Space Complexity: O(len(num2) * max_sum) +class Solution { + +private: + const long long MOD = 1e9 + 7; + +public: + int count(string num1, string num2, int min_sum, int max_sum) { + num1 = sub1(num1); + long long res = solve(num2, min_sum, max_sum) - solve(num1, min_sum, max_sum); + return (res + MOD) % MOD; + } + +private: + long long solve(const string& s, int min_sum, int max_sum){ + + int len = s.size(); + vector> dp(len << 1, vector(max_sum + 1, -1)); + return dfs(len, s, 0, 0, 0, min_sum, max_sum, dp); + } + + long long dfs(int len, const string& s, int index, int can_over, int cur_sum, + const int min_sum, const int max_sum, vector>& dp){ + + if(index == len) return min_sum <= cur_sum && cur_sum <= max_sum; + if(cur_sum > max_sum) return 0; + if(dp[index * 2 + can_over][cur_sum] != -1) return dp[index * 2 + can_over][cur_sum]; + + long long res = 0; + for(int i = 0; i <= (can_over ? 9 : s[index] - '0'); i ++){ + res += dfs(len, s, index + 1, can_over || i < s[index] - '0', cur_sum + i, min_sum, max_sum, dp); + res %= MOD; + } + return dp[index * 2 + can_over][cur_sum] = res; + } + + string sub1(const string& s){ + string res = s; + for(int i = res.size() - 1; i >= 0; i --){ + if(res[i] == '0'){ + res[i] = '9'; + }else{ + res[i] -= 1; + break; + } + } + + reverse(res.begin(), res.end()); + while(res.back() == '0') res.pop_back(); + reverse(res.begin(), res.end()); + return res.size() == 0 ? "0" : res; + } +}; + + +int main() { + + cout << Solution().count("1", "12", 1, 8) << '\n'; + + return 0; +} diff --git a/2501-3000/2728-Count-Houses-in-a-Circular-Street/cpp-2728/CMakeLists.txt b/2501-3000/2728-Count-Houses-in-a-Circular-Street/cpp-2728/CMakeLists.txt new file mode 100644 index 00000000..9ba5342d --- /dev/null +++ b/2501-3000/2728-Count-Houses-in-a-Circular-Street/cpp-2728/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2728) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2728 main.cpp) diff --git a/2501-3000/2728-Count-Houses-in-a-Circular-Street/cpp-2728/main.cpp b/2501-3000/2728-Count-Houses-in-a-Circular-Street/cpp-2728/main.cpp new file mode 100644 index 00000000..cb78e219 --- /dev/null +++ b/2501-3000/2728-Count-Houses-in-a-Circular-Street/cpp-2728/main.cpp @@ -0,0 +1,49 @@ +/// Source : https://leetcode.com/problems/count-houses-in-a-circular-street/description/ +/// Author : liuyubobobo +/// Time : 2023-06-08 + +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(k) +/// Space Complexity: O(1) + +/// Definition for a street. +class Street { +public: + Street(vector doors); + void openDoor(); + void closeDoor(); + bool isDoorOpen(); + void moveRight(); + void moveLeft(); +}; + +class Solution { +public: + int houseCount(Street* street, int k) { + + for(int i = 0; i < k; i ++, street->moveRight()) + if(street->isDoorOpen()) + street->closeDoor(); + + street->openDoor(); + street->moveRight(); + + int res = 1; + while(!street->isDoorOpen()){ + res ++; + street->moveRight(); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2729-Check-if-The-Number-is-Fascinating/cpp-2729/CMakeLists.txt b/2501-3000/2729-Check-if-The-Number-is-Fascinating/cpp-2729/CMakeLists.txt new file mode 100644 index 00000000..91d92404 --- /dev/null +++ b/2501-3000/2729-Check-if-The-Number-is-Fascinating/cpp-2729/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2729) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2729 main.cpp) diff --git a/2501-3000/2729-Check-if-The-Number-is-Fascinating/cpp-2729/main.cpp b/2501-3000/2729-Check-if-The-Number-is-Fascinating/cpp-2729/main.cpp new file mode 100644 index 00000000..c8934730 --- /dev/null +++ b/2501-3000/2729-Check-if-The-Number-is-Fascinating/cpp-2729/main.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.com/problems/check-if-the-number-is-fascinating/description/ +/// Author : liuyubobobo +/// Time : 2023-06-13 + +#include +#include +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(logn) +/// Space Complexity: O(1) +class Solution { +public: + bool isFascinating(int n) { + + int a = n, b = 2 * n, c = 3 * n; + string s = to_string(a) + to_string(b) + to_string(c); + + vector f(10, 0); + for(char c: s) f[c - '0'] ++; + return count_if(f.begin() + 1, f.end(), [](int e){return e == 1;}) == 9; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2730-Find-the-Longest-Semi-Repetitive-Substring/cpp-2730/CMakeLists.txt b/2501-3000/2730-Find-the-Longest-Semi-Repetitive-Substring/cpp-2730/CMakeLists.txt new file mode 100644 index 00000000..02d93698 --- /dev/null +++ b/2501-3000/2730-Find-the-Longest-Semi-Repetitive-Substring/cpp-2730/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2730) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2730 main.cpp) diff --git a/2501-3000/2730-Find-the-Longest-Semi-Repetitive-Substring/cpp-2730/main.cpp b/2501-3000/2730-Find-the-Longest-Semi-Repetitive-Substring/cpp-2730/main.cpp new file mode 100644 index 00000000..8159a67c --- /dev/null +++ b/2501-3000/2730-Find-the-Longest-Semi-Repetitive-Substring/cpp-2730/main.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/find-the-longest-semi-repetitive-substring/description/ +/// Author : liuyubobobo +/// Time : 2023-06-13 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n^2) +/// Space Complexity: O(1) +class Solution { +public: + int longestSemiRepetitiveSubstring(string s) { + + int res = 1; + for(int i = 0; i + 1 < s.size(); i ++) + res = max(res, solve(s, i, i + 1)); + return res; + } + +private: + int solve(const string& s, int a, int b){ + int res = 2; + for(int i = a - 1; i >= 0 && s[i] != s[i + 1]; i --) res ++; + for(int i = b + 1; i < s.size() && s[i] != s[i - 1]; i ++) res ++; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2731-Movement-of-Robots/cpp-2731/CMakeLists.txt b/2501-3000/2731-Movement-of-Robots/cpp-2731/CMakeLists.txt new file mode 100644 index 00000000..153e6c90 --- /dev/null +++ b/2501-3000/2731-Movement-of-Robots/cpp-2731/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2731) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2731 main.cpp) diff --git a/2501-3000/2731-Movement-of-Robots/cpp-2731/main.cpp b/2501-3000/2731-Movement-of-Robots/cpp-2731/main.cpp new file mode 100644 index 00000000..500402e1 --- /dev/null +++ b/2501-3000/2731-Movement-of-Robots/cpp-2731/main.cpp @@ -0,0 +1,49 @@ +/// Source : https://leetcode.com/problems/movement-of-robots/description/ +/// Author : liuyubobobo +/// Time : 2023-06-13 + +#include +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { + +private: + const long long MOD = 1e9 + 7; + +public: + int sumDistance(vector& nums, string s, int d) { + + int n = nums.size(); + for(int i = 0; i < n; i ++) + if(s[i] == 'R') nums[i] += d; else nums[i] -= d; + sort(nums.begin(), nums.end()); + + long long right_dis = 0, right_cnt = n - 1; + for(int i = 1; i < n; i ++) right_dis += 0ll + nums[i] - nums[0]; + + long long res = right_dis % MOD; + for(int i = 1; i < n; i ++){ + long long cur = 0ll + nums[i] - nums[i - 1]; + + right_dis = (right_dis - right_cnt * cur % MOD + MOD) % MOD; + right_cnt --; + + res = (res + right_dis) % MOD; + res %= MOD; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2732-Find-a-Good-Subset-of-the-Matrix/cpp-2732/CMakeLists.txt b/2501-3000/2732-Find-a-Good-Subset-of-the-Matrix/cpp-2732/CMakeLists.txt new file mode 100644 index 00000000..bb21c839 --- /dev/null +++ b/2501-3000/2732-Find-a-Good-Subset-of-the-Matrix/cpp-2732/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2732) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2732 main.cpp) diff --git a/2501-3000/2732-Find-a-Good-Subset-of-the-Matrix/cpp-2732/main.cpp b/2501-3000/2732-Find-a-Good-Subset-of-the-Matrix/cpp-2732/main.cpp new file mode 100644 index 00000000..ac1f2f08 --- /dev/null +++ b/2501-3000/2732-Find-a-Good-Subset-of-the-Matrix/cpp-2732/main.cpp @@ -0,0 +1,44 @@ +/// Source : https://leetcode.com/problems/find-a-good-subset-of-the-matrix/description/ +/// Author : liuyubobobo +/// Time : 2023-06-19 + +#include +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(n * 2^b) +/// Space Complexity: O(2^b) +class Solution { +public: + vector goodSubsetofBinaryMatrix(vector>& grid) { + + int n = grid.size(), b = grid[0].size(); + + map pattern2index; + for(int i = 0; i < n; i ++){ + + int value = 0; + for(int j = 0; j < b; j ++) + if(grid[i][j]) value += (1 << j); + + if(value == 0) return {{i}}; + + auto iter = pattern2index.find(value); + if(iter != pattern2index.end()) return {iter->second, i}; + + for(int s = 0; s < (1 << b); s ++) + if((s & value) == 0) pattern2index[s] = i; + } + return {}; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2733-Neither-Minimum-nor-Maximum/cpp-2733/CMakeLists.txt b/2501-3000/2733-Neither-Minimum-nor-Maximum/cpp-2733/CMakeLists.txt new file mode 100644 index 00000000..9498c170 --- /dev/null +++ b/2501-3000/2733-Neither-Minimum-nor-Maximum/cpp-2733/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2733) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2733 main.cpp) diff --git a/2501-3000/2733-Neither-Minimum-nor-Maximum/cpp-2733/main.cpp b/2501-3000/2733-Neither-Minimum-nor-Maximum/cpp-2733/main.cpp new file mode 100644 index 00000000..be466ab5 --- /dev/null +++ b/2501-3000/2733-Neither-Minimum-nor-Maximum/cpp-2733/main.cpp @@ -0,0 +1,32 @@ +/// Source : https://leetcode.com/problems/neither-minimum-nor-maximum/description/ +/// Author : liuyubobobo +/// Time : 2023-06-19 + +#include +#include +#include + +using namespace std; + + +/// Set +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + int findNonMinOrMax(vector& nums) { + + set s(nums.begin(), nums.end()); + if(s.size() <= 2) return -1; + + auto iter = s.begin(); + iter ++; + return *iter; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2734-Lexicographically-Smallest-String-After-Substring-Operation/cpp-2734/CMakeLists.txt b/2501-3000/2734-Lexicographically-Smallest-String-After-Substring-Operation/cpp-2734/CMakeLists.txt new file mode 100644 index 00000000..0de9cf14 --- /dev/null +++ b/2501-3000/2734-Lexicographically-Smallest-String-After-Substring-Operation/cpp-2734/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2734) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2734 main.cpp) diff --git a/2501-3000/2734-Lexicographically-Smallest-String-After-Substring-Operation/cpp-2734/main.cpp b/2501-3000/2734-Lexicographically-Smallest-String-After-Substring-Operation/cpp-2734/main.cpp new file mode 100644 index 00000000..6164a2cc --- /dev/null +++ b/2501-3000/2734-Lexicographically-Smallest-String-After-Substring-Operation/cpp-2734/main.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.com/problems/lexicographically-smallest-string-after-substring-operation/description/ +/// Author : liuyubobobo +/// Time : 2023-06-19 + +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + string smallestString(string s) { + + int start = 0; + for(; start < s.size(); start ++) if(s[start] != 'a') break; + if(start == s.size()) { + s[s.size() - 1] = 'z'; + return s; + } + + int end; + for(end = start; end < s.size(); end ++) if(s[end] == 'a') break; + + for(int i = start; i < end; i ++) s[i] --; + return s; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2735-Collecting-Chocolates/cpp-2735/CMakeLists.txt b/2501-3000/2735-Collecting-Chocolates/cpp-2735/CMakeLists.txt new file mode 100644 index 00000000..38970f9d --- /dev/null +++ b/2501-3000/2735-Collecting-Chocolates/cpp-2735/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2735) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2735 main.cpp) diff --git a/2501-3000/2735-Collecting-Chocolates/cpp-2735/main.cpp b/2501-3000/2735-Collecting-Chocolates/cpp-2735/main.cpp new file mode 100644 index 00000000..68c7e02b --- /dev/null +++ b/2501-3000/2735-Collecting-Chocolates/cpp-2735/main.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/collecting-chocolates/description/ +/// Author : liuyubobobo +/// Time : 2023-06-19 + +#include +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n^2) +/// Space Complexity: O(n^2) +class Solution { +public: + long long minCost(vector& nums, int x) { + + int n = nums.size(); + + vector> min_table(n, vector(n, LONG_LONG_MAX)); + for(int start = 0; start < n; start ++){ + min_table[start][start] = nums[start]; + for(int i= start + 1; i < n; i ++) + min_table[start][i] = min(min_table[start][i - 1], 0ll + nums[i]); + } + + long long res = LONG_LONG_MAX; + for(int offset = 0; offset < n; offset ++){ + res = min(res, solve(n, x, offset, min_table)); + } + return res; + } + +private: + long long solve(int n, long long x, int offset, + const vector>& min_table){ + + long long res = x * offset; + for(int start = 0; start < n; start ++){ + int end = (start + offset) % n; + + if(start <= end) res += min_table[start][end]; + else res += min(min_table[start][n - 1], min_table[0][end]); + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2736-Maximum-Sum-Queries/cpp-2736/CMakeLists.txt b/2501-3000/2736-Maximum-Sum-Queries/cpp-2736/CMakeLists.txt new file mode 100644 index 00000000..b364367f --- /dev/null +++ b/2501-3000/2736-Maximum-Sum-Queries/cpp-2736/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2736) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2736 main.cpp) diff --git a/2501-3000/2736-Maximum-Sum-Queries/cpp-2736/main.cpp b/2501-3000/2736-Maximum-Sum-Queries/cpp-2736/main.cpp new file mode 100644 index 00000000..33ea6f8f --- /dev/null +++ b/2501-3000/2736-Maximum-Sum-Queries/cpp-2736/main.cpp @@ -0,0 +1,135 @@ +/// Source : https://leetcode.com/problems/maximum-sum-queries/description/ +/// Author : liuyubobobo +/// Time : 2023-06-19 + +#include +#include +#include +#include + +using namespace std; + + +/// Segment Tree + Offline Queries +/// Time Complexity: O(nlogn + qlogn) +/// Space Complexity: O(n) +template +class SegmentTree{ + +private: + int n; + vector data, tree; + T (*combine)(T a, T b); + +public: + + SegmentTree(int n, T (*combine)(T a, T b)): n(n), data(n, -1), tree(4 * n, -1){ + this->combine = combine; + } + + void update(int index, T value){ + if(data[index] == value) return; + data[index] = value; + update(0, 0, n - 1, index, value); + } + + T query(int index){ + assert(0 <= index && index < n); + return data[index]; + } + + T query(int l, int r){ + assert(l <= r); + assert(0 <= l && l < n); + assert(0 <= r && r < n); + return query(0, 0, n - 1, l, r); + } + +private: + void buildSegTree(int treeID, int l, int r){ + + if(l == r){ + tree[treeID] = data[l]; + return; + } + + int mid = (l + r) / 2; + buildSegTree(treeID * 2 + 1, l, mid); + buildSegTree(treeID * 2 + 2, mid + 1, r); + tree[treeID] = combine(tree[treeID * 2 + 1], tree[treeID * 2 + 2]); + return; + } + + void update(int treeID, int l, int r, int index, T value){ + + if(l == r){ + assert(l == index); + tree[treeID] = value; + return; + } + + int mid = (l + r) / 2; + if(index <= mid) update(treeID * 2 + 1, l, mid, index, value); + else update(treeID * 2 + 2, mid + 1, r, index, value); + + tree[treeID] = combine(tree[treeID * 2 + 1], tree[treeID * 2 + 2]); + return; + } + + T query(int treeID, int l, int r, int ql, int qr){ + + if(ql == l && qr == r) + return tree[treeID]; + + int mid = (l + r) / 2; + if(qr <= mid) return query(treeID * 2 + 1, l, mid, ql, qr); + else if(ql > mid) return query(treeID * 2 + 2, mid + 1, r, ql, qr); + + T resl = query(treeID * 2 + 1, l, mid, ql, mid); + T resr = query(treeID * 2 + 2, mid + 1, r, mid + 1, qr); + return combine(resl, resr); + } +}; + +class Solution { +public: + vector maximumSumQueries(vector& nums1, vector& nums2, vector>& queries) { + + vector> v; + for(int i = 0; i < nums1.size(); i ++) v.push_back({nums1[i], nums2[i]}); + sort(v.begin(), v.end(), greater<>()); + + for(int i = 0; i < queries.size(); i ++) + queries[i].push_back(i); + sort(queries.begin(), queries.end(), greater<>()); + + map value2index; + for(const pair& p: v) value2index[p.second] = 0; + for(const vector& p: queries) value2index[p[1]] = 0; + + int sz = 0; + for(auto iter = value2index.begin(); iter != value2index.end(); iter ++) + iter->second = sz ++; + + vector res(queries.size()); + SegmentTree segTree(sz, [](int a, int b){return max(a, b);}); + for(int i = 0, j = 0; i < queries.size(); i ++){ + while(j < v.size() && v[j].first >= queries[i][0]){ + int index = value2index[v[j].second]; + segTree.update(index, max(segTree.query(index), v[j].first + v[j].second)); + j ++; + } + + int index = value2index[queries[i][1]]; + int tres = segTree.query(index, sz - 1); + res[queries[i][2]] = tres; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2737-Find-the-Closest-Marked-Node/cpp-2737/CMakeLists.txt b/2501-3000/2737-Find-the-Closest-Marked-Node/cpp-2737/CMakeLists.txt new file mode 100644 index 00000000..d0cc5d1f --- /dev/null +++ b/2501-3000/2737-Find-the-Closest-Marked-Node/cpp-2737/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2737) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2737 main.cpp) diff --git a/2501-3000/2737-Find-the-Closest-Marked-Node/cpp-2737/main.cpp b/2501-3000/2737-Find-the-Closest-Marked-Node/cpp-2737/main.cpp new file mode 100644 index 00000000..2b5d73dc --- /dev/null +++ b/2501-3000/2737-Find-the-Closest-Marked-Node/cpp-2737/main.cpp @@ -0,0 +1,59 @@ +/// Source : https://leetcode.cn/problems/find-the-closest-marked-node/ +/// Author : liuyubobobo +/// Time : 2023-06-16 + +#include +#include +#include +#include + +using namespace std; + + +/// Dijkstra +/// Time Complexity: O(ElogE) +/// Space Complexity: O(V) +class Solution { + +private: + const int INF = INT_MAX / 2; + +public: + int minimumDistance(int n, vector>& edges, int s, vector& marked) { + + vector>> g(n); + for(const vector& edge: edges){ + int u = edge[0], v = edge[1], w = edge[2]; + g[u].push_back({v, w}); + } + + vector dis(n, INF); + dis[s] = 0; + vector visited(n, false); + priority_queue, vector>, greater<>> pq; + pq.push({0, s}); + while(!pq.empty()){ + int d = pq.top().first, u = pq.top().second; pq.pop(); + if(visited[u]) continue; + visited[u] = true; + + for(const pair& p: g[u]){ + int v = p.first, w = p.second; + if(!visited[v] && dis[v] > dis[u] + w){ + dis[v] = dis[u] + w; + pq.push({dis[v], v}); + } + } + } + + int res = INF; + for(int u: marked) res = min(res, dis[u]); + return res == INF ? -1 : res; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2739-Total-Distance-Traveled/cpp-2739/CMakeLists.txt b/2501-3000/2739-Total-Distance-Traveled/cpp-2739/CMakeLists.txt new file mode 100644 index 00000000..1813dd45 --- /dev/null +++ b/2501-3000/2739-Total-Distance-Traveled/cpp-2739/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2739) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2739 main.cpp) diff --git a/2501-3000/2739-Total-Distance-Traveled/cpp-2739/main.cpp b/2501-3000/2739-Total-Distance-Traveled/cpp-2739/main.cpp new file mode 100644 index 00000000..cd73cef2 --- /dev/null +++ b/2501-3000/2739-Total-Distance-Traveled/cpp-2739/main.cpp @@ -0,0 +1,32 @@ +/// Source : https://leetcode.com/problems/total-distance-traveled/description/ +/// Author : liuyubobobo +/// Time : 2023-06-18 + +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(mainTank) +/// Space Complexity: O(1) +class Solution { +public: + int distanceTraveled(int mainTank, int additionalTank) { + + int res = 0; + while(mainTank >= 5 && additionalTank) { + res += 50; + + mainTank = mainTank - 5 + 1; + additionalTank --; + } + return res + mainTank * 10; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2740-Find-the-Value-of-the-Partition/cpp-2740/CMakeLists.txt b/2501-3000/2740-Find-the-Value-of-the-Partition/cpp-2740/CMakeLists.txt new file mode 100644 index 00000000..a4f995d0 --- /dev/null +++ b/2501-3000/2740-Find-the-Value-of-the-Partition/cpp-2740/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2740) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2740 main.cpp) diff --git a/2501-3000/2740-Find-the-Value-of-the-Partition/cpp-2740/main.cpp b/2501-3000/2740-Find-the-Value-of-the-Partition/cpp-2740/main.cpp new file mode 100644 index 00000000..a7b5bf5e --- /dev/null +++ b/2501-3000/2740-Find-the-Value-of-the-Partition/cpp-2740/main.cpp @@ -0,0 +1,31 @@ +/// Source : https://leetcode.com/problems/find-the-value-of-the-partition/description/ +/// Author : liuyubobobo +/// Time : 2023-06-18 + +#include +#include + +using namespace std; + + +/// Sorting +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + int findValueOfPartition(vector& nums) { + + sort(nums.begin(), nums.end()); + + int res = INT_MAX; + for(int i = 1; i < nums.size(); i ++) + res = min(res, nums[i] - nums[i - 1]); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2741-Special-Permutations/cpp-2741/CMakeLists.txt b/2501-3000/2741-Special-Permutations/cpp-2741/CMakeLists.txt new file mode 100644 index 00000000..95adda90 --- /dev/null +++ b/2501-3000/2741-Special-Permutations/cpp-2741/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2741) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2741 main.cpp) diff --git a/2501-3000/2741-Special-Permutations/cpp-2741/main.cpp b/2501-3000/2741-Special-Permutations/cpp-2741/main.cpp new file mode 100644 index 00000000..bdbb5099 --- /dev/null +++ b/2501-3000/2741-Special-Permutations/cpp-2741/main.cpp @@ -0,0 +1,48 @@ +/// Source : https://leetcode.com/problems/special-permutations/description/ +/// Author : liuyubobobo +/// Time : 2023-06-18 + +#include +#include + +using namespace std; + + +/// Bitmask + Memoization +/// Time Complexity: O(n^2 * 2^n) +/// Space Complexity: O(n * 2^n) +class Solution { + +private: + const long long MOD = 1e9 + 7; + +public: + int specialPerm(vector& nums) { + + int n = nums.size(); + vector> dp(n + 1, vector(1 << n, -1)); + return dfs(nums, 0, (1 << n) - 1, dp); + } + +private: + long long dfs(const vector& nums, int last_index, int state, vector>& dp) { + + if(state == 0) return 1; + if(dp[last_index][state] != -1) return dp[last_index][state]; + + long long res = 0; + for(int i = 0; i < nums.size(); i ++) { + if((state & (1 << i)) == 0) continue; + if(last_index == 0) res += dfs(nums, i + 1, state ^ (1 << i), dp); + else if(nums[i] % nums[last_index - 1] == 0 || nums[last_index - 1] % nums[i] == 0) + res += dfs(nums, i + 1, state ^ (1 << i), dp); + } + return dp[last_index][state] = res % MOD; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2742-Painting-the-Walls/cpp-2742/CMakeLists.txt b/2501-3000/2742-Painting-the-Walls/cpp-2742/CMakeLists.txt new file mode 100644 index 00000000..e4c7628e --- /dev/null +++ b/2501-3000/2742-Painting-the-Walls/cpp-2742/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2742) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2742 main.cpp) diff --git a/2501-3000/2742-Painting-the-Walls/cpp-2742/main.cpp b/2501-3000/2742-Painting-the-Walls/cpp-2742/main.cpp new file mode 100644 index 00000000..9cf0788b --- /dev/null +++ b/2501-3000/2742-Painting-the-Walls/cpp-2742/main.cpp @@ -0,0 +1,48 @@ +/// Source : https://leetcode.com/problems/painting-the-walls/description/ +/// Author : liuyubobobo +/// Time : 2023-06-18 + +#include +#include +#include + +using namespace std; + + +/// Memoization +/// Time Complexity: O(n * (total_time + n)) +/// Space Complexity: O(n * (total_time + n)) +class Solution { + +private: + const int INF = INT_MAX / 2; + +public: + int paintWalls(vector& cost, vector& time) { + + int n = cost.size(); + int total_time = accumulate(time.begin(), time.end(), 0); + + vector> dp(n, vector(total_time + n + 1, -1)); + return dfs(n, cost, time, 0, 0, n, dp); + } + +private: + int dfs(int n, const vector& cost, const vector& time, + int index, int can_be_free_time, int offset, vector>& dp) { + + if(index == n) return can_be_free_time >= 0 ? 0 : INF; + if(dp[index][can_be_free_time + offset] != -1) return dp[index][can_be_free_time + offset]; + + int res = INF; + res = min(res, cost[index] + dfs(n, cost, time, index + 1, can_be_free_time + time[index], offset, dp)); + res = min(res, dfs(n, cost, time, index + 1, can_be_free_time - 1, offset, dp)); + return dp[index][can_be_free_time + offset] = res; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2743-Count-Substrings-Without-Repeating-Character/cpp-2743/CMakeLists.txt b/2501-3000/2743-Count-Substrings-Without-Repeating-Character/cpp-2743/CMakeLists.txt new file mode 100644 index 00000000..31ac4a90 --- /dev/null +++ b/2501-3000/2743-Count-Substrings-Without-Repeating-Character/cpp-2743/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2743) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2743 main.cpp) diff --git a/2501-3000/2743-Count-Substrings-Without-Repeating-Character/cpp-2743/main.cpp b/2501-3000/2743-Count-Substrings-Without-Repeating-Character/cpp-2743/main.cpp new file mode 100644 index 00000000..3ba7521d --- /dev/null +++ b/2501-3000/2743-Count-Substrings-Without-Repeating-Character/cpp-2743/main.cpp @@ -0,0 +1,36 @@ +/// Source : https://leetcode.com/problems/count-substrings-without-repeating-character/description/ +/// Author : liuyubobobo +/// Time : 2023-06-22 + +#include +#include + +using namespace std; + + +/// Sliding Window +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int numberOfSpecialSubstrings(string s) { + + vector f(26, 0); + int l = 0, r = -1, res = 0; + while(l < s.size()){ + if(r + 1 < s.size() && f[s[r + 1] - 'a'] == 0){ + f[s[++ r] - 'a'] ++; + res += r - l + 1; + } + else{ + f[s[l ++] - 'a'] --; + } + } + return res; + } +}; + +int main() { + + return 0; +} diff --git a/2501-3000/2744-Find-Maximum-Number-of-String-Pairs/cpp-2744/CMakeLists.txt b/2501-3000/2744-Find-Maximum-Number-of-String-Pairs/cpp-2744/CMakeLists.txt new file mode 100644 index 00000000..d021c502 --- /dev/null +++ b/2501-3000/2744-Find-Maximum-Number-of-String-Pairs/cpp-2744/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2744) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2744 main.cpp) diff --git a/2501-3000/2744-Find-Maximum-Number-of-String-Pairs/cpp-2744/main.cpp b/2501-3000/2744-Find-Maximum-Number-of-String-Pairs/cpp-2744/main.cpp new file mode 100644 index 00000000..78dfcadb --- /dev/null +++ b/2501-3000/2744-Find-Maximum-Number-of-String-Pairs/cpp-2744/main.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.com/problems/find-maximum-number-of-string-pairs/description/ +/// Author : liuyubobobo +/// Time : 2023-06-25 + +#include +#include + +using namespace std; + + +/// Using Hash Table +/// Time Complexity: O(n + 26 * 26) +/// Space Complexity: O(26 * 26) +class Solution { +public: + int maximumNumberOfStringPairs(vector& words) { + + vector> f(26, vector(26, 0)); + for(const string& word: words) { + f[word[0] - 'a'][word[1] - 'a'] ++; + } + + int res = 0; + for(int i = 0; i < 26; i ++) + for(int j = i + 1; j < 26; j ++) res += min(f[i][j], f[j][i]); + for(int i = 0; i < 26; i ++) res += f[i][i] / 2; + return res; + } +}; + +int main() { + + return 0; +} diff --git a/2501-3000/2745-Construct-the-Longest-New-String/cpp-2745/CMakeLists.txt b/2501-3000/2745-Construct-the-Longest-New-String/cpp-2745/CMakeLists.txt new file mode 100644 index 00000000..baab7f00 --- /dev/null +++ b/2501-3000/2745-Construct-the-Longest-New-String/cpp-2745/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2745) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2745 main.cpp) diff --git a/2501-3000/2745-Construct-the-Longest-New-String/cpp-2745/main.cpp b/2501-3000/2745-Construct-the-Longest-New-String/cpp-2745/main.cpp new file mode 100644 index 00000000..84c8d84f --- /dev/null +++ b/2501-3000/2745-Construct-the-Longest-New-String/cpp-2745/main.cpp @@ -0,0 +1,38 @@ +/// Source : https://leetcode.com/problems/construct-the-longest-new-string/description/ +/// Author : liuyubobobo +/// Time : 2023-06-25 + +#include +#include + +using namespace std; + + +/// Memoization +/// Time Complexity: O(x * y * z) +/// Space Complexity: O(x * y * z) +class Solution { +public: + int longestString(int x, int y, int z) { + + vector>>> dp(3, vector>>(x + 1, vector>(y + 1, vector(z + 1, -1)))); + return dfs(0, x, y, z, dp); + } + +private: + int dfs(int pre, int x, int y, int z, vector>>>& dp){ + + if(dp[pre][x][y][z] != -1) return dp[pre][x][y][z]; + int res = 0; + if(x && pre != 1) res = max(res, 2 + dfs(1, x - 1, y, z, dp)); + if(y && pre != 2) res = max(res, 2 + dfs(2, x, y - 1, z, dp)); + if(z && pre != 1) res = max(res, 2 + dfs(2, x, y, z - 1, dp)); + return dp[pre][x][y][z] = res; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2746-Decremental-String-Concatenation/cpp-2746/CMakeLists.txt b/2501-3000/2746-Decremental-String-Concatenation/cpp-2746/CMakeLists.txt new file mode 100644 index 00000000..80edf606 --- /dev/null +++ b/2501-3000/2746-Decremental-String-Concatenation/cpp-2746/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2746) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2746 main.cpp) diff --git a/2501-3000/2746-Decremental-String-Concatenation/cpp-2746/main.cpp b/2501-3000/2746-Decremental-String-Concatenation/cpp-2746/main.cpp new file mode 100644 index 00000000..8169cc90 --- /dev/null +++ b/2501-3000/2746-Decremental-String-Concatenation/cpp-2746/main.cpp @@ -0,0 +1,51 @@ +/// Source : https://leetcode.com/problems/decremental-string-concatenation/description/ +/// Author : liuyubobobo +/// Time : 2023-06-25 + +#include +#include +#include + +using namespace std; + + +/// Memoization +/// Time Complexity: O(n * 26^2) +/// Space Complexity: O(n * 26^2) +class Solution { +public: + int minimizeConcatenatedLength(vector& words) { + + int n = words.size(); + + vector>> dp(n, vector>(26, vector(26, -1))); + return (int)words[0].size() + dfs(words, 1, words[0][0] - 'a', words[0].back() - 'a', dp); + } + +private: + int dfs(const vector& words, int index, int front, int tail, + vector>>& dp){ + + if(index == words.size()) return 0; + if(dp[index][front][tail] != -1) return dp[index][front][tail]; + + int res = INT_MAX; + if(words[index].back() - 'a' == front) + res = min(res, (int)words[index].size() - 1 + dfs(words, index + 1, words[index][0] - 'a', tail, dp)); + else + res = min(res, (int)words[index].size() + dfs(words, index + 1, words[index][0] - 'a', tail, dp)); + + if(words[index][0] - 'a' == tail) + res = min(res, (int)words[index].size() - 1 + dfs(words, index + 1, front, words[index].back() - 'a', dp)); + else + res = min(res, (int)words[index].size() + dfs(words, index + 1, front, words[index].back() - 'a', dp)); + + return dp[index][front][tail] = res; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2747-Count-Zero-Request-Servers/cpp-2747/CMakeLists.txt b/2501-3000/2747-Count-Zero-Request-Servers/cpp-2747/CMakeLists.txt new file mode 100644 index 00000000..7affa925 --- /dev/null +++ b/2501-3000/2747-Count-Zero-Request-Servers/cpp-2747/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2747) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2747 main.cpp) diff --git a/2501-3000/2747-Count-Zero-Request-Servers/cpp-2747/main.cpp b/2501-3000/2747-Count-Zero-Request-Servers/cpp-2747/main.cpp new file mode 100644 index 00000000..9da23b17 --- /dev/null +++ b/2501-3000/2747-Count-Zero-Request-Servers/cpp-2747/main.cpp @@ -0,0 +1,70 @@ +/// Source : https://leetcode.com/problems/count-zero-request-servers/description/ +/// Author : liuyubobobo +/// Time : 2023-06-25 + +#include +#include +#include +#include + +using namespace std; + + +/// Sliding Window +/// Time Complexity: O(nlogn + qlogq) +/// Space Complexity: O(n) +class Solution { +public: + vector countServers(int n, vector>& logs, int x, vector& queries) { + + sort(logs.begin(), logs.end(), + [](const vector& a, const vector& b) { + return a[1] < b[1]; + }); + + vector> queries_pair; + for(int i = 0; i < queries.size(); i ++) queries_pair.push_back({queries[i], i}); + sort(queries_pair.begin(), queries_pair.end()); + + map f; + int l = 0, r = -1, index = 0; + vector res(queries.size(), n); + while(l < logs.size() && index < queries_pair.size()){ + if(r + 1 < logs.size() && queries_pair[index].first - x <= logs[r + 1][1] && logs[r + 1][1] <= queries_pair[index].first){ + r ++, f[logs[r][0]] ++; + } + else{ + if(queries_pair[index].first - x <= logs[l][1] && (l == 0 || queries_pair[index].first - x > logs[l - 1][1])){ + res[queries_pair[index].second] -= f.size(); + index ++; + continue; + } + + if(l <= r){ + f[logs[l][0]] --; + if(f[logs[l][0]] == 0) f.erase(logs[l][0]); + } + + l ++; + r = max(r, l - 1); + } + } + + return res; + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << ' '; cout << '\n'; +} + +int main() { + + vector> logs1 = {{2,30},{2,5},{3,9},{4,21}}; + vector queries1 = {11, 28, 16, 18}; + print_vec(Solution().countServers(4, logs1, 9, queries1)); + // 2 3 3 3 + + return 0; +} diff --git a/2501-3000/2748-Number-of-Beautiful-Pairs/cpp-2748/CMakeLists.txt b/2501-3000/2748-Number-of-Beautiful-Pairs/cpp-2748/CMakeLists.txt new file mode 100644 index 00000000..e5f23f16 --- /dev/null +++ b/2501-3000/2748-Number-of-Beautiful-Pairs/cpp-2748/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2748) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2748 main.cpp) diff --git a/2501-3000/2748-Number-of-Beautiful-Pairs/cpp-2748/main.cpp b/2501-3000/2748-Number-of-Beautiful-Pairs/cpp-2748/main.cpp new file mode 100644 index 00000000..adae7380 --- /dev/null +++ b/2501-3000/2748-Number-of-Beautiful-Pairs/cpp-2748/main.cpp @@ -0,0 +1,45 @@ +/// Source : https://leetcode.com/problems/number-of-beautiful-pairs/description/ +/// Author : liuyubobobo +/// Time : 2023-06-25 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n^2) +/// Space Complexity: O(1) +class Solution { +public: + int countBeautifulPairs(vector& nums) { + + int n = nums.size(), res = 0; + for(int i = 0; i < n; i ++) + for(int j = i + 1; j < n; j ++){ + int a = to_string(nums[i])[0] - '0'; + int b = to_string(nums[j]).back() - '0'; + res += gcd(a, b) == 1; + } + return res; + } + +private: + template + T gcd(T a, T b){ + if(a < b) swap(a, b); + while(b){ + int t = a % b; + a = b; + b = t; + } + return a; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2749-Minimum-Operations-to-Make-the-Integer-Zero/cpp-2749/CMakeLists.txt b/2501-3000/2749-Minimum-Operations-to-Make-the-Integer-Zero/cpp-2749/CMakeLists.txt new file mode 100644 index 00000000..18f3da21 --- /dev/null +++ b/2501-3000/2749-Minimum-Operations-to-Make-the-Integer-Zero/cpp-2749/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2749) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2749 main.cpp) diff --git a/2501-3000/2749-Minimum-Operations-to-Make-the-Integer-Zero/cpp-2749/main.cpp b/2501-3000/2749-Minimum-Operations-to-Make-the-Integer-Zero/cpp-2749/main.cpp new file mode 100644 index 00000000..2317dc4e --- /dev/null +++ b/2501-3000/2749-Minimum-Operations-to-Make-the-Integer-Zero/cpp-2749/main.cpp @@ -0,0 +1,30 @@ +/// Source : https://leetcode.com/problems/minimum-operations-to-make-the-integer-zero/description/ +/// Author : liuyubobobo +/// Time : 2023-06-25 + +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(1) +/// Space Complexity: O(1) +class Solution { +public: + int makeTheIntegerZero(long long num1, long long num2) { + + for(int k = 1; k <= 60; k ++){ + long long x = num1 - k * num2; + if(x <= 0) break; + if(__builtin_popcountll(x) <= k && x >= k) return k; + } + return -1; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2750-Ways-to-Split-Array-Into-Good-Subarrays/cpp-2750/CMakeLists.txt b/2501-3000/2750-Ways-to-Split-Array-Into-Good-Subarrays/cpp-2750/CMakeLists.txt new file mode 100644 index 00000000..7ba102a7 --- /dev/null +++ b/2501-3000/2750-Ways-to-Split-Array-Into-Good-Subarrays/cpp-2750/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2750) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2750 main.cpp) diff --git a/2501-3000/2750-Ways-to-Split-Array-Into-Good-Subarrays/cpp-2750/main.cpp b/2501-3000/2750-Ways-to-Split-Array-Into-Good-Subarrays/cpp-2750/main.cpp new file mode 100644 index 00000000..b2c8c41c --- /dev/null +++ b/2501-3000/2750-Ways-to-Split-Array-Into-Good-Subarrays/cpp-2750/main.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode.com/problems/ways-to-split-array-into-good-subarrays/description/ +/// Author : liuyubobobo +/// Time : 2023-06-25 + +#include +#include + +using namespace std; + + +/// Math +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +private: + long long MOD = 1e9 + 7; + +public: + int numberOfGoodSubarraySplits(vector& nums) { + + vector pos; + for(int i = 0; i < nums.size(); i ++) if(nums[i] == 1) pos.push_back(i); + + if(pos.empty()) return 0; + + long long res = 1; + for(int i = 0; i + 1 < pos.size(); i ++){ + long long t = pos[i + 1] - pos[i]; + res = res * t % MOD; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2751-Robot-Collisions/cpp-2751/CMakeLists.txt b/2501-3000/2751-Robot-Collisions/cpp-2751/CMakeLists.txt new file mode 100644 index 00000000..d0f532c7 --- /dev/null +++ b/2501-3000/2751-Robot-Collisions/cpp-2751/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2751) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2751 main.cpp) diff --git a/2501-3000/2751-Robot-Collisions/cpp-2751/main.cpp b/2501-3000/2751-Robot-Collisions/cpp-2751/main.cpp new file mode 100644 index 00000000..b23e89b4 --- /dev/null +++ b/2501-3000/2751-Robot-Collisions/cpp-2751/main.cpp @@ -0,0 +1,106 @@ +/// Source : https://leetcode.com/problems/robot-collisions/description/ +/// Author : liuyubobobo +/// Time : 2023-06-26 + +#include +#include +#include + +using namespace std; + + +/// Stack +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + vector survivedRobotsHealths(vector& positions, vector& healths, string directions) { + + int n = positions.size(); + + vector> robots; // pos, health, dir, index + for(int i = 0; i < n; i ++) robots.push_back({positions[i], healths[i], directions[i], i}); + + sort(robots.begin(), robots.end()); + + vector> res; // health, index + vector> stack; + for(int i = 0; i < n;) { + if(!stack.empty() && get<2>(stack.back()) == 'L'){ + res.push_back({get<1>(stack.back()), get<3>(stack.back())}); + stack.pop_back(); + } + else if(stack.empty() || get<2>(robots[i]) == get<2>(stack.back())){ + stack.push_back(robots[i]); i ++; + } + else{ + int& stack_health = get<1>(stack.back()); + int& cur_health = get<1>(robots[i]); + if(stack_health == cur_health){ + stack.pop_back(); i ++; + } + else if(stack_health < cur_health){ + stack.pop_back(); + cur_health --; + } + else{ + stack_health --; + i ++; + } + } + } + + while(!stack.empty()){ + res.push_back({get<1>(stack.back()), get<3>(stack.back())}); + stack.pop_back(); + } + + sort(res.begin(), res.end(), [](pair& a, pair& b){ + return a.second < b.second; + }); + + vector ret; + for(const auto& p: res) ret.push_back(p.first); + return ret; + } +}; + + +void print_vec(const vector& v){ + + if(v.empty()){ + cout << "empty\n"; + return; + } + + for(int e: v) cout << e << ' '; cout << '\n'; +} + +int main() { + + vector pos1 = {5, 4, 3, 2, 1}; + vector health1 = {2, 17, 9, 15, 10}; + string dir1 = "RRRRR"; + print_vec(Solution().survivedRobotsHealths(pos1, health1, dir1)); + // 2 17 9 15 10 + + vector pos2 = {3, 5, 2, 6}; + vector health2 = {10, 10, 15, 12}; + string dir2 = "RLRL"; + print_vec(Solution().survivedRobotsHealths(pos2, health2, dir2)); + // 14 + + vector pos3 = {1, 2, 5, 6}; + vector health3 = {10, 10, 11, 11}; + string dir3 = "RLRL"; + print_vec(Solution().survivedRobotsHealths(pos3, health3, dir3)); + // empty + + vector pos4 = {3, 40}; + vector health4 = {49, 11}; + string dir4 = "LL"; + print_vec(Solution().survivedRobotsHealths(pos4, health4, dir4)); + // 49 11 + + return 0; +} diff --git a/2501-3000/2760-Longest-Even-Odd-Subarray-With-Threshold/cpp-2760/CMakeLists.txt b/2501-3000/2760-Longest-Even-Odd-Subarray-With-Threshold/cpp-2760/CMakeLists.txt new file mode 100644 index 00000000..09927f63 --- /dev/null +++ b/2501-3000/2760-Longest-Even-Odd-Subarray-With-Threshold/cpp-2760/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2760) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2760 main.cpp) diff --git a/2501-3000/2760-Longest-Even-Odd-Subarray-With-Threshold/cpp-2760/main.cpp b/2501-3000/2760-Longest-Even-Odd-Subarray-With-Threshold/cpp-2760/main.cpp new file mode 100644 index 00000000..1e036f39 --- /dev/null +++ b/2501-3000/2760-Longest-Even-Odd-Subarray-With-Threshold/cpp-2760/main.cpp @@ -0,0 +1,38 @@ +/// Source : https://leetcode.com/problems/longest-even-odd-subarray-with-threshold/description/ +/// Author : liuyubobobo +/// Time : 2023-07-10 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n^3) +/// Space Complexity: O(1) +class Solution { +public: + int longestAlternatingSubarray(vector& nums, int threshold) { + + int n = nums.size(), res = 0; + for(int l = 0; l < n; l ++){ + if(nums[l] % 2 || nums[l] > threshold) continue; + + bool ok = true; + for(int r = l; r < n && ok; r ++){ + for(int i = l + 1; i <= r && ok; i ++) + if(nums[i] % 2 == nums[i - 1] % 2 || nums[i] > threshold) + ok = false; + if(ok) res = max(res, r - l + 1); + } + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2761-Prime-Pairs-With-Target-Sum/cpp-2761/CMakeLists.txt b/2501-3000/2761-Prime-Pairs-With-Target-Sum/cpp-2761/CMakeLists.txt new file mode 100644 index 00000000..68991160 --- /dev/null +++ b/2501-3000/2761-Prime-Pairs-With-Target-Sum/cpp-2761/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2761) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2761 main.cpp) diff --git a/2501-3000/2761-Prime-Pairs-With-Target-Sum/cpp-2761/main.cpp b/2501-3000/2761-Prime-Pairs-With-Target-Sum/cpp-2761/main.cpp new file mode 100644 index 00000000..3566096d --- /dev/null +++ b/2501-3000/2761-Prime-Pairs-With-Target-Sum/cpp-2761/main.cpp @@ -0,0 +1,49 @@ +/// Source : https://leetcode.com/problems/prime-pairs-with-target-sum/description/ +/// Author : liuyubobobo +/// Time : 2023-07-10 + +#include +#include + +using namespace std; + + +/// Sieve +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + vector> findPrimePairs(int n) { + + vector sieve_table = sieve(n); + + vector> res; + for(int x = 2; x + x <= n; x ++) + if(sieve_table[x] == x && sieve_table[n - x] == n - x) + res.push_back({x, n - x}); + return res; + } + +private: + vector sieve(int n){ + + vector table(n + 1, 0); + vector primes; + table[0] = table[1] = 1; + for(int i = 2; i <= n; i ++){ + if(table[i] == 0) { + primes.push_back(i); + table[i] = i; + } + for(int j = 0; j < primes.size() && primes[j] <= table[i] && i * primes[j] <= n; j ++) + table[i * primes[j]] = primes[j]; + } + return table; + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2762-Continuous-Subarrays/cpp-2762/CMakeLists.txt b/2501-3000/2762-Continuous-Subarrays/cpp-2762/CMakeLists.txt new file mode 100644 index 00000000..920ababa --- /dev/null +++ b/2501-3000/2762-Continuous-Subarrays/cpp-2762/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2762) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2762 main.cpp) diff --git a/2501-3000/2762-Continuous-Subarrays/cpp-2762/main.cpp b/2501-3000/2762-Continuous-Subarrays/cpp-2762/main.cpp new file mode 100644 index 00000000..70e2d9d9 --- /dev/null +++ b/2501-3000/2762-Continuous-Subarrays/cpp-2762/main.cpp @@ -0,0 +1,48 @@ +/// Source : https://leetcode.com/problems/continuous-subarrays/description/ +/// Author : liuyubobobo +/// Time : 2023-07-10 + +#include +#include +#include + +using namespace std; + + +/// Sliding Window +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + long long continuousSubarrays(vector& nums) { + + int n = nums.size(); + int l = 0, r = -1; + map f; + long long res = 0; + while(l < n){ + if(r + 1 < n && (f.empty() || max_diff(nums[r + 1], f) <= 2)) + f[nums[++ r]] ++, res += (r - l + 1); + else{ + f[nums[l]] --; + if(f[nums[l]] == 0) + f.erase(nums[l]); + l ++; + } + } + return res; + } + +private: + int max_diff(int e, const map& f){ + int a = abs(e - f.begin()->first); + int b = abs(e - f.rbegin()->first); + return max(a, b); + } +}; + + +int main() { + + return 0; +} diff --git a/2501-3000/2763-Sum-of-Imbalance-Numbers-of-All-Subarrays/cpp-2763/CMakeLists.txt b/2501-3000/2763-Sum-of-Imbalance-Numbers-of-All-Subarrays/cpp-2763/CMakeLists.txt new file mode 100644 index 00000000..efbbff6d --- /dev/null +++ b/2501-3000/2763-Sum-of-Imbalance-Numbers-of-All-Subarrays/cpp-2763/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_2763) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2763 main.cpp) diff --git a/2501-3000/2763-Sum-of-Imbalance-Numbers-of-All-Subarrays/cpp-2763/main.cpp b/2501-3000/2763-Sum-of-Imbalance-Numbers-of-All-Subarrays/cpp-2763/main.cpp new file mode 100644 index 00000000..fcfbe8d9 --- /dev/null +++ b/2501-3000/2763-Sum-of-Imbalance-Numbers-of-All-Subarrays/cpp-2763/main.cpp @@ -0,0 +1,65 @@ +/// Source : https://leetcode.com/problems/sum-of-imbalance-numbers-of-all-subarrays/description/ +/// Author : liuyubobobo +/// Time : 2023-07-19 + +#include +#include +#include + +using namespace std; + + +/// Using Map +/// Time Complexity: O(n^2 * logn) +/// Space Complexity: O(n) +class Solution { +public: + int sumImbalanceNumbers(vector& nums) { + + + int n = nums.size(); + int res = 0; + for(int l = 0; l < n; l ++){ + map f; + int cnt = 0; + for(int r = l; r < n; r ++){ + f[nums[r]] ++; + if(r == l) continue; + + auto cur_iter = f.find(nums[r]); + if(cur_iter->second > 1){ + res += cnt; continue; + } + auto next_iter = cur_iter; next_iter ++; + + if(cur_iter == f.begin()){ + int next_value = next_iter->first; + if(next_value - nums[r] > 1) cnt ++; + } + else if(next_iter == f.end()){ + auto pre_iter = cur_iter; pre_iter --; + int pre_value = pre_iter->first; + if(nums[r] - pre_value > 1) cnt ++; + } + else{ + auto pre_iter = cur_iter; pre_iter --; + int pre_value = pre_iter->first, next_value = next_iter->first; + if(next_value - pre_value > 1) cnt --; + if(nums[r] - pre_value > 1) cnt ++; + if(next_value - nums[r] > 1) cnt ++; + } + res += cnt; + } + } + return res; + } +}; + +int main() { + + vector nums2 = {1, 3, 3, 3, 5}; + cout << Solution().sumImbalanceNumbers(nums2) << '\n'; + // 8 + + return 0; +} diff --git a/2501-3000/2849-Determine-if-a-Cell-Is-Reachable-at-a-Given-Time/cpp-2849/CMakeLists.txt b/2501-3000/2849-Determine-if-a-Cell-Is-Reachable-at-a-Given-Time/cpp-2849/CMakeLists.txt new file mode 100644 index 00000000..d510b2ba --- /dev/null +++ b/2501-3000/2849-Determine-if-a-Cell-Is-Reachable-at-a-Given-Time/cpp-2849/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.26) +project(cpp_2849) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_2849 main.cpp) diff --git a/2501-3000/2849-Determine-if-a-Cell-Is-Reachable-at-a-Given-Time/cpp-2849/main.cpp b/2501-3000/2849-Determine-if-a-Cell-Is-Reachable-at-a-Given-Time/cpp-2849/main.cpp new file mode 100644 index 00000000..8ce52a2e --- /dev/null +++ b/2501-3000/2849-Determine-if-a-Cell-Is-Reachable-at-a-Given-Time/cpp-2849/main.cpp @@ -0,0 +1,28 @@ +/// Source : https://leetcode.com/problems/determine-if-a-cell-is-reachable-at-a-given-time/description/ +/// Author : liuyubobobo +/// Time : 2023-11-09 + +#include + +using namespace std; + + +/// Math +/// Time Complexity: O(1) +/// Space Complexity: O(1) +class Solution { +public: + bool isReachableAtTime(int sx, int sy, int fx, int fy, int t) { + + int a = abs(sx - fx), b = abs(sy - fy); + int d = max(a, b); + if(d == 0) return t != 1; + return t >= d; + } +}; + + +int main() { + + return 0; +} diff --git a/Coding-Interviews/010-1/cpp-010-01/CMakeLists.txt b/Coding-Interviews/010-1/cpp-010-01/CMakeLists.txt new file mode 100644 index 00000000..0e0f43f1 --- /dev/null +++ b/Coding-Interviews/010-1/cpp-010-01/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_010_01) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_010_01 main.cpp) diff --git a/Coding-Interviews/010-1/cpp-010-01/main.cpp b/Coding-Interviews/010-1/cpp-010-01/main.cpp new file mode 100644 index 00000000..df05fb6a --- /dev/null +++ b/Coding-Interviews/010-1/cpp-010-01/main.cpp @@ -0,0 +1,43 @@ +/// Source : https://leetcode-cn.com/problems/fei-bo-na-qi-shu-lie-lcof/ +/// Author : liuyubobobo +/// Time : 2021-09-03 + +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { + +private: + int MOD = 1e9 + 7; + +public: + int fib(int n) { + + if(n == 0) return 0; + if(n == 1) return 1; + + int a = 0, b = 1, c; + for(int i = 2; i <= n; i ++){ + c = (a + b) % MOD; + a = b; + b = c; + } + return c; + } +}; + + +int main() { + + cout << Solution().fib(2) << endl; + cout << Solution().fib(3) << endl; + cout << Solution().fib(4) << endl; + cout << Solution().fib(5) << endl; + + return 0; +} diff --git a/Coding-Interviews/015/cpp-015/CMakeLists.txt b/Coding-Interviews/015/cpp-015/CMakeLists.txt new file mode 100644 index 00000000..f1d87a3a --- /dev/null +++ b/Coding-Interviews/015/cpp-015/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(015) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(015 main.cpp) \ No newline at end of file diff --git a/Coding-Interviews/015/cpp-015/main.cpp b/Coding-Interviews/015/cpp-015/main.cpp new file mode 100644 index 00000000..134ad06d --- /dev/null +++ b/Coding-Interviews/015/cpp-015/main.cpp @@ -0,0 +1,30 @@ +/// Source : https://leetcode-cn.com/problems/er-jin-zhi-zhong-1de-ge-shu-lcof/ +/// Author : liuyubobobo +/// Time : 2021-06-23 + +#include + +using namespace std; + + +/// Bitwise +/// Time Complexity: O(logn) +/// Space Complexity: O(1) +class Solution { +public: + int hammingWeight(uint32_t n) { + + int res = 0; + while(n){ + n &= (n - 1); + res ++; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/Coding-Interviews/022/cpp-022/CMakeLists.txt b/Coding-Interviews/022/cpp-022/CMakeLists.txt new file mode 100644 index 00000000..4f8f6349 --- /dev/null +++ b/Coding-Interviews/022/cpp-022/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(cpp_022) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_022 main.cpp) diff --git a/Coding-Interviews/022/cpp-022/main.cpp b/Coding-Interviews/022/cpp-022/main.cpp new file mode 100644 index 00000000..bc32472f --- /dev/null +++ b/Coding-Interviews/022/cpp-022/main.cpp @@ -0,0 +1,38 @@ +/// Source : https://leetcode-cn.com/problems/lian-biao-zhong-dao-shu-di-kge-jie-dian-lcof/ +/// Author : liuyubobobo +/// Time : 2021-09-01 + +#include + +using namespace std; + + +/// Two Pointers +/// Time Complexity: O(n) +/// Space Complexity: O(1) + +/// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} +}; + +class Solution { +public: + ListNode* getKthFromEnd(ListNode* head, int k) { + + ListNode* b = head; + for(int i = 0; i < k; i ++) b = b->next; + + ListNode* a = head; + while(b) a = a->next, b = b->next; + return a; + } +}; + + +int main() { + + return 0; +} diff --git a/Coding-Interviews/026/cpp-026/CMakeLists.txt b/Coding-Interviews/026/cpp-026/CMakeLists.txt new file mode 100644 index 00000000..e255bfaf --- /dev/null +++ b/Coding-Interviews/026/cpp-026/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(026) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(026 main.cpp) diff --git a/Coding-Interviews/026/cpp-026/main.cpp b/Coding-Interviews/026/cpp-026/main.cpp new file mode 100644 index 00000000..fc7f0624 --- /dev/null +++ b/Coding-Interviews/026/cpp-026/main.cpp @@ -0,0 +1,65 @@ +/// Source : https://leetcode-cn.com/problems/shu-de-zi-jie-gou-lcof/ +/// Author : liuyubobobo +/// Time : 2022-01-01 + +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(|A| * |B|) +/// Space Complexity: O(h) + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} + TreeNode(int x, TreeNode* l, TreeNode* r): val(x), left(l), right(r){} +}; + +class Solution { +public: + bool isSubStructure(TreeNode* A, TreeNode* B) { + if (!B) return false; + return is_contain(A, B); + } + +private: + bool is_contain(TreeNode* A, TreeNode* B){ + + if (!A) return false; + + if (A->val == B->val && is_equal(A->left, B->left) && is_equal(A->right, B->right)) + return true; + + return is_contain(A->left, B) || is_contain (A->right, B); + } + + bool is_equal(TreeNode* A, TreeNode* B) { + + if(!B) return true; + if(!A) return false; + return A->val == B->val && is_equal(A->left, B->left) && is_equal(A->right, B->right); + } +}; + + +int main() { + + TreeNode* left_node1 = new TreeNode(0, new TreeNode(-4), new TreeNode(-3)); + TreeNode* right_node1 = new TreeNode(1); + TreeNode* B1 = new TreeNode(1, new TreeNode(-4), nullptr); + cout << Solution().isSubStructure(new TreeNode(1, left_node1, right_node1), B1) << endl; + // false + + TreeNode* left_node2 = new TreeNode(12, new TreeNode(8), new TreeNode(3)); + TreeNode* right_node2 = new TreeNode(6, new TreeNode(11), nullptr); + TreeNode* B2 = new TreeNode(10, new TreeNode(12, new TreeNode(8), nullptr), new TreeNode(6)); + cout << Solution().isSubStructure(new TreeNode(10, left_node2, right_node2), B2) << endl; + // true + + return 0; +} diff --git a/Coding-Interviews/028/cpp-028/CMakeLists.txt b/Coding-Interviews/028/cpp-028/CMakeLists.txt new file mode 100644 index 00000000..4fb18793 --- /dev/null +++ b/Coding-Interviews/028/cpp-028/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0101) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0101 ${SOURCE_FILES}) \ No newline at end of file diff --git a/Coding-Interviews/028/cpp-028/main.cpp b/Coding-Interviews/028/cpp-028/main.cpp new file mode 100644 index 00000000..1da4c446 --- /dev/null +++ b/Coding-Interviews/028/cpp-028/main.cpp @@ -0,0 +1,67 @@ +/// Source : https://leetcode.com/problems/symmetric-tree/description/ +/// Author : liuyubobobo +/// Time : 2018-06-02 + +#include + +using namespace std; + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +/// Recursive +/// Revert one child tree and see if the two child trees of the root are identical +/// +/// Time Complexity: O(n) +/// Space Complexity: O(h) +class Solution { +public: + bool isSymmetric(TreeNode* root) { + + if(root == NULL) + return true; + + TreeNode* left = root->left; + TreeNode* right = root->right; + right = revert(right); + + return is_identical(left, right); + } + +private: + TreeNode* revert(TreeNode* root){ + if(root == NULL) + return NULL; + + swap(root->left, root->right); + revert(root->left); + revert(root->right); + return root; + } + + bool is_identical(TreeNode* root1, TreeNode* root2){ + + if(root1 == NULL && root2 == NULL) + return true; + + if(root1 == NULL || root2 == NULL) + return false; + + if(root1->val != root2->val) + return false; + + return is_identical(root1->left, root2->left) && + is_identical(root1->right, root2->right); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/Coding-Interviews/028/cpp-028/main2.cpp b/Coding-Interviews/028/cpp-028/main2.cpp new file mode 100644 index 00000000..6ffa603b --- /dev/null +++ b/Coding-Interviews/028/cpp-028/main2.cpp @@ -0,0 +1,54 @@ +/// Source : https://leetcode.com/problems/symmetric-tree/description/ +/// Author : liuyubobobo +/// Time : 2018-06-02 + +#include + +using namespace std; + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +/// Recursive +/// No need to revert one child tree +/// See if the two child trees of the root are mirror directly +/// +/// Time Complexity: O(n) +/// Space Complexity: O(h) +class Solution { +public: + bool isSymmetric(TreeNode* root) { + + if(root == NULL) + return true; + + return is_mirror(root, root); + } + +private: + bool is_mirror(TreeNode* root1, TreeNode* root2){ + + if(root1 == NULL && root2 == NULL) + return true; + + if(root1 == NULL || root2 == NULL) + return false; + + if(root1->val != root2->val) + return false; + + return is_mirror(root1->left, root2->right) && + is_mirror(root1->right, root2->left); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/Coding-Interviews/028/cpp-028/main3.cpp b/Coding-Interviews/028/cpp-028/main3.cpp new file mode 100644 index 00000000..a6de98a0 --- /dev/null +++ b/Coding-Interviews/028/cpp-028/main3.cpp @@ -0,0 +1,64 @@ +/// Source : https://leetcode.com/problems/symmetric-tree/description/ +/// Author : liuyubobobo +/// Time : 2018-06-02 + +#include +#include + +using namespace std; + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +/// Non-Recursive +/// Using two queues to level traverse the root in different directions +/// +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + bool isSymmetric(TreeNode* root) { + + if(root == NULL) + return true; + + queue q1, q2; + q1.push(root); + q2.push(root); + while(!q1.empty() && !q2.empty()){ + TreeNode* node1 = q1.front(); + q1.pop(); + + TreeNode* node2 = q2.front(); + q2.pop(); + + if(node1 == NULL && node2 == NULL) + continue; + + if(node1 == NULL || node2 == NULL) + return false; + + if(node1->val != node2->val) + return false; + + q1.push(node1->left); + q1.push(node1->right); + + q2.push(node2->right); + q2.push(node2->left); + } + + return q1.empty() && q2.empty(); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/Coding-Interviews/028/cpp-028/main4.cpp b/Coding-Interviews/028/cpp-028/main4.cpp new file mode 100644 index 00000000..92f563f9 --- /dev/null +++ b/Coding-Interviews/028/cpp-028/main4.cpp @@ -0,0 +1,63 @@ +/// Source : https://leetcode.com/problems/symmetric-tree/description/ +/// Author : liuyubobobo +/// Time : 2018-06-02 + +#include +#include + +using namespace std; + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +/// Non-Recursive +/// Using one queues to level traverse the root in different directions +/// +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + bool isSymmetric(TreeNode* root) { + + if(root == NULL) + return true; + + queue q; + q.push(root); + q.push(root); + while(!q.empty()){ + TreeNode* node1 = q.front(); + q.pop(); + + TreeNode* node2 = q.front(); + q.pop(); + + if(node1 == NULL && node2 == NULL) + continue; + + if(node1 == NULL || node2 == NULL) + return false; + + if(node1->val != node2->val) + return false; + + q.push(node1->left); + q.push(node2->right); + q.push(node1->right); + q.push(node2->left); + } + + return true; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/Coding-Interviews/037/cpp-037/CMakeLists.txt b/Coding-Interviews/037/cpp-037/CMakeLists.txt new file mode 100644 index 00000000..bbadc14a --- /dev/null +++ b/Coding-Interviews/037/cpp-037/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(cpp_037) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_037 main.cpp) \ No newline at end of file diff --git a/Coding-Interviews/037/cpp-037/main.cpp b/Coding-Interviews/037/cpp-037/main.cpp new file mode 100644 index 00000000..17959955 --- /dev/null +++ b/Coding-Interviews/037/cpp-037/main.cpp @@ -0,0 +1,101 @@ +/// Source : https://leetcode-cn.com/problems/xu-lie-hua-er-cha-shu-lcof/ +/// Author : liuyubobobo +/// Time : 2021-06-30 + +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(n) +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +class Codec { +public: + + // Encodes a tree to a single string. + string serialize(TreeNode* root) { + + if(!root) + return "[null]"; + + string ret = "["; + dfs(root, ret); + ret.pop_back(); + return ret + "]"; + } + + // Decodes your encoded data to tree. + TreeNode* deserialize(string data) { + vector vec = get_vector(data); + + if(vec.size() == 0 || (vec.size() == 1 && vec[0] == "null")) + return NULL; + +// for(const string& s: vec) +// cout << s << " "; +// cout << endl; + + int index = 0; + return dfs(vec, index); + } + +private: + TreeNode* dfs(const vector& vec, int& index){ + + if(index == vec.size() || vec[index] == "null") + return NULL; + + TreeNode* node = new TreeNode(atoi(vec[index].c_str())); + index ++; + node->left = dfs(vec, index); + + index ++; + node->right = dfs(vec, index); + + return node; + } + + void dfs(TreeNode* node, string& ret){ + + ret += to_string(node->val) + ","; + + if(node->left) + dfs(node->left, ret); + else + ret += "null,"; + + if(node->right) + dfs(node->right, ret); + else + ret += "null,"; + } + + vector get_vector(const string& data){ + + string s = data.substr(1, data.size() - 2) + ","; + + vector res; + int i = 0; + while(i < s.size()){ + int comma = s.find(',', i); + res.push_back(s.substr(i, comma - i)); + i = comma + 1; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/Coding-Interviews/038/cpp-038/CMakeLists.txt b/Coding-Interviews/038/cpp-038/CMakeLists.txt new file mode 100644 index 00000000..5c47fc8b --- /dev/null +++ b/Coding-Interviews/038/cpp-038/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(038) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(038 main.cpp) \ No newline at end of file diff --git a/Coding-Interviews/038/cpp-038/main.cpp b/Coding-Interviews/038/cpp-038/main.cpp new file mode 100644 index 00000000..3821c11b --- /dev/null +++ b/Coding-Interviews/038/cpp-038/main.cpp @@ -0,0 +1,32 @@ +/// Source : https://leetcode-cn.com/problems/zi-fu-chuan-de-pai-lie-lcof/ +/// Author : liuyubobobo +/// Time : 2021-06-21 + +#include +#include + +using namespace std; + + +/// Permutation +/// Time Complexity: O(n!) +/// Space Complexity(n) +class Solution { +public: + vector permutation(string s) { + + sort(s.begin(), s.end()); + vector res; + do{ + res.push_back(s); + }while(next_permutation(s.begin(), s.end())); + return res; + } + +}; + + +int main() { + + return 0; +} diff --git a/Coding-Interviews/047/cpp-047/CMakeLists.txt b/Coding-Interviews/047/cpp-047/CMakeLists.txt new file mode 100644 index 00000000..30a85b8a --- /dev/null +++ b/Coding-Interviews/047/cpp-047/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_047) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_047 main.cpp) diff --git a/Coding-Interviews/047/cpp-047/main.cpp b/Coding-Interviews/047/cpp-047/main.cpp new file mode 100644 index 00000000..a294b567 --- /dev/null +++ b/Coding-Interviews/047/cpp-047/main.cpp @@ -0,0 +1,32 @@ +/// Source : https://leetcode.cn/problems/li-wu-de-zui-da-jie-zhi-lcof/ +/// Author : liuyubobobo +/// Time : 2023-03-07 + +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(R * C) +/// Space Complexity: O(R * C) +class Solution { +public: + int maxValue(vector>& grid) { + + int R = grid.size(), C = grid[0].size(); + + vector> dp(R + 1, vector(C + 1, 0)); + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++) + dp[i + 1][j + 1] = max(dp[i][j + 1], dp[i + 1][j]) + grid[i][j]; + return dp[R][C]; + } +}; + + +int main() { + + return 0; +} diff --git a/Cracking-The-Coding-Interview/01-05/cpp-01-05/CMakeLists.txt b/Cracking-The-Coding-Interview/01-05/cpp-01-05/CMakeLists.txt new file mode 100644 index 00000000..5741689d --- /dev/null +++ b/Cracking-The-Coding-Interview/01-05/cpp-01-05/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_01_05) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_01_05 main.cpp) diff --git a/Cracking-The-Coding-Interview/01-05/cpp-01-05/main.cpp b/Cracking-The-Coding-Interview/01-05/cpp-01-05/main.cpp new file mode 100644 index 00000000..dbdace88 --- /dev/null +++ b/Cracking-The-Coding-Interview/01-05/cpp-01-05/main.cpp @@ -0,0 +1,42 @@ +/// Source : https://leetcode.cn/problems/one-away-lcci/ +/// Author : liuyubobobo +/// Time : 2022-05-12 + +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + bool oneEditAway(string first, string second) { + + int n1 = first.size(), n2 = second.size(); + if(n1 == n2){ + + int change = 0; + for(int i = 0; i < n1; i ++) + change += (first[i] != second[i]); + return change <= 1; + } + + if(abs(n1 - n2) > 1) return false; + + if(n1 > n2) swap(n1, n2), swap(first, second); + + // n1 < n2; + for(int len = 0; len <= n1; len ++) + if(first.substr(0, len) == second.substr(0, len) && first.substr(len) == second.substr(len + 1)) + return true; + return false; + } +}; + + +int main() { + + return 0; +} diff --git a/Cracking-The-Coding-Interview/01-07/cpp-01-07/CMakeLists.txt b/Cracking-The-Coding-Interview/01-07/cpp-01-07/CMakeLists.txt new file mode 100644 index 00000000..14977dce --- /dev/null +++ b/Cracking-The-Coding-Interview/01-07/cpp-01-07/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0048) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main2.cpp) +add_executable(cpp_0048 ${SOURCE_FILES}) \ No newline at end of file diff --git a/Cracking-The-Coding-Interview/01-07/cpp-01-07/main.cpp b/Cracking-The-Coding-Interview/01-07/cpp-01-07/main.cpp new file mode 100644 index 00000000..77e7ceab --- /dev/null +++ b/Cracking-The-Coding-Interview/01-07/cpp-01-07/main.cpp @@ -0,0 +1,61 @@ +/// Source : https://leetcode.com/problems/rotate-image/description/ +/// Author : liuyubobobo +/// Time : 2018-09-13 + +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(n^2) +/// Space Complexity: O(1) +class Solution { +public: + void rotate(vector>& matrix) { + + int n = matrix.size(); + for(int i = 0; i <= n / 2; i ++) + for(int j = i; j < n - 1 - i; j ++){ + int t = matrix[i][j]; + matrix[i][j] = matrix[n - 1 - j][i]; + matrix[n - 1 - j][i] = matrix[n - 1 - i][n - 1 - j]; + matrix[n - 1 - i][n - 1 - j] = matrix[j][n - 1 - i]; + matrix[j][n - 1 - i] = t; + Solution::print_matrix(matrix); + } + } + + static void print_matrix(const vector>& m){ + for(int i = 0; i < m.size(); i ++){ + for(int j = 0; j < m[i].size(); j ++) + cout << m[i][j] << " "; + cout << endl; + } + cout << endl; + } +}; + + +int main() { + + vector> matrix1 = { + {1, 2, 3}, + {4, 5, 6}, + {7, 8, 9} + }; + Solution().rotate(matrix1); + Solution::print_matrix(matrix1); + + vector> matrix2 = { + {1, 2, 3, 4}, + {5, 6, 7, 8}, + {9, 10, 11, 12}, + {13, 14, 15, 16} + }; + Solution().rotate(matrix2); + Solution::print_matrix(matrix2); + + return 0; +} \ No newline at end of file diff --git a/Cracking-The-Coding-Interview/01-07/cpp-01-07/main2.cpp b/Cracking-The-Coding-Interview/01-07/cpp-01-07/main2.cpp new file mode 100644 index 00000000..9b200068 --- /dev/null +++ b/Cracking-The-Coding-Interview/01-07/cpp-01-07/main2.cpp @@ -0,0 +1,59 @@ +/// Source : https://leetcode.com/problems/rotate-image/description/ +/// Author : liuyubobobo +/// Time : 2018-12-16 + +#include +#include + +using namespace std; + + +/// Reverse diagonally and then reverse row +/// Time Complexity: O(n^2) +/// Space Complexity: O(1) +class Solution { +public: + void rotate(vector>& matrix) { + + int n = matrix.size(); + for(int i = 0; i < n; i ++) + for(int j = 0; j < n - i; j ++) + swap(matrix[i][j], matrix[n - j - 1][n - i - 1]); + + for(int i = 0; i < n / 2; i ++) + for(int j = 0; j < n; j ++) + swap(matrix[i][j], matrix[n - i - 1][j]); + } +}; + + +void print_matrix(const vector>& m){ + for(int i = 0; i < m.size(); i ++){ + for(int j = 0; j < m[i].size(); j ++) + cout << m[i][j] << " "; + cout << endl; + } + cout << endl; +} + +int main() { + + vector> matrix1 = { + {1, 2, 3}, + {4, 5, 6}, + {7, 8, 9} + }; + Solution().rotate(matrix1); + print_matrix(matrix1); + + vector> matrix2 = { + {1, 2, 3, 4}, + {5, 6, 7, 8}, + {9, 10, 11, 12}, + {13, 14, 15, 16} + }; + Solution().rotate(matrix2); + print_matrix(matrix2); + + return 0; +} \ No newline at end of file diff --git a/Cracking-The-Coding-Interview/01-08/cpp-01-08/CMakeLists.txt b/Cracking-The-Coding-Interview/01-08/cpp-01-08/CMakeLists.txt new file mode 100644 index 00000000..c942613d --- /dev/null +++ b/Cracking-The-Coding-Interview/01-08/cpp-01-08/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0073) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main4.cpp) +add_executable(cpp_0073 ${SOURCE_FILES}) \ No newline at end of file diff --git a/Cracking-The-Coding-Interview/01-08/cpp-01-08/main.cpp b/Cracking-The-Coding-Interview/01-08/cpp-01-08/main.cpp new file mode 100644 index 00000000..1f44d97d --- /dev/null +++ b/Cracking-The-Coding-Interview/01-08/cpp-01-08/main.cpp @@ -0,0 +1,45 @@ +/// Source : https://leetcode.com/problems/set-matrix-zeroes/description/ +/// Author : liuyubobobo +/// Time : 2018-10-05 + +#include +#include + +using namespace std; + + +/// Using another matrix to record zero place +/// Time Complexity: O(m * n * (m + n)) +/// Space Complexity: O(m * n) +class Solution { +public: + void setZeroes(vector>& matrix) { + + int m = matrix.size(); + if(!m) return; + + int n = matrix[0].size(); + if(!n) return; + + vector> isZero(m, vector(n, false)); + for(int i = 0; i < m; i ++) + for(int j = 0; j < n; j ++) + if(!matrix[i][j]){ + for(int k = 0; k < n; k ++) + isZero[i][k] = true; + for(int k = 0; k < m; k ++) + isZero[k][j] = true; + } + + for(int i = 0; i < m; i ++) + for(int j = 0; j < n; j ++) + if(isZero[i][j]) + matrix[i][j] = 0; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/Cracking-The-Coding-Interview/01-08/cpp-01-08/main2.cpp b/Cracking-The-Coding-Interview/01-08/cpp-01-08/main2.cpp new file mode 100644 index 00000000..1ca5fa18 --- /dev/null +++ b/Cracking-The-Coding-Interview/01-08/cpp-01-08/main2.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.com/problems/set-matrix-zeroes/description/ +/// Author : liuyubobobo +/// Time : 2018-10-05 + +#include +#include + +using namespace std; + + +/// Only record the zero row index and col index +/// Time Complexity: O(m * n) +/// Space Complexity: O(m + n) +class Solution { +public: + void setZeroes(vector>& matrix) { + + int m = matrix.size(); + if(!m) return; + + int n = matrix[0].size(); + if(!n) return; + + vector zeroRows, zeroCols; + for(int i = 0; i < m; i ++) + for(int j = 0; j < n; j ++) + if(!matrix[i][j]){ + zeroRows.push_back(i); + zeroCols.push_back(j); + } + + for(int r: zeroRows) + for(int j = 0; j < n; j ++) + matrix[r][j] = 0; + + for(int c: zeroCols) + for(int i = 0; i < m; i ++) + matrix[i][c] = 0; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/Cracking-The-Coding-Interview/01-08/cpp-01-08/main3.cpp b/Cracking-The-Coding-Interview/01-08/cpp-01-08/main3.cpp new file mode 100644 index 00000000..0f3edc3f --- /dev/null +++ b/Cracking-The-Coding-Interview/01-08/cpp-01-08/main3.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.com/problems/set-matrix-zeroes/description/ +/// Author : liuyubobobo +/// Time : 2018-10-05 + +#include +#include + +using namespace std; + + +/// Using an sentinel value to mark zero in place +/// Attention: this method is actually wrong since we can not guarantee that +/// the sentinel value can not occur in the matrix +/// +/// Time Complexity: O(m * n * (m + n)) +/// Space Complexity: O(1) +class Solution { +public: + void setZeroes(vector>& matrix) { + + int m = matrix.size(); + if(!m) return; + + int n = matrix[0].size(); + if(!n) return; + + int sentinel = 2e9; + for(int i = 0; i < m; i ++) + for(int j = 0; j < n; j ++) + if(matrix[i][j] == 0){ + for(int k = 0; k < n; k ++) + if(matrix[i][k] != 0) + matrix[i][k] = sentinel; + for(int k = 0; k < m; k ++) + if(matrix[k][j] != 0) + matrix[k][j] = sentinel; + } + + for(int i = 0; i < m; i ++) + for(int j = 0; j < n; j ++) + if(matrix[i][j] == sentinel) + matrix[i][j] = 0; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/Cracking-The-Coding-Interview/01-08/cpp-01-08/main4.cpp b/Cracking-The-Coding-Interview/01-08/cpp-01-08/main4.cpp new file mode 100644 index 00000000..5e062b33 --- /dev/null +++ b/Cracking-The-Coding-Interview/01-08/cpp-01-08/main4.cpp @@ -0,0 +1,81 @@ +/// Source : https://leetcode.com/problems/set-matrix-zeroes/description/ +/// Author : liuyubobobo +/// Time : 2018-10-05 + +#include +#include + +using namespace std; + + +/// Make a marker in the first element of every row and column +/// Time Complexity: O(m * n) +/// Space Complexity: O(1) +class Solution { +public: + void setZeroes(vector>& matrix) { + + int m = matrix.size(); + if(!m) return; + + int n = matrix[0].size(); + if(!n) return; + + bool zeroIndexColZero = false; + for(int i = 0; i < m; i ++) + for(int j = 0; j < n; j ++) + if(!matrix[i][j]){ + matrix[i][0] = 0; + if(j == 0) + zeroIndexColZero = true; + else + matrix[0][j] = 0; + } + + for(int i = 1; i < m; i ++) + if(!matrix[i][0]) + for(int j = 0; j < n; j ++) + matrix[i][j] = 0; + + for(int j = 1; j < n; j ++) + if(!matrix[0][j]) + for(int i = 0; i < m; i ++) + matrix[i][j] = 0; + + if(!matrix[0][0]) + for(int j = 0; j < n; j ++) + matrix[0][j] = 0; + + if(zeroIndexColZero) + for(int i = 0; i < m; i ++) + matrix[i][0] = 0; + } +}; + + +void print_matrix(const vector>& matrix){ + + for(const vector& row: matrix){ + for(int e: row) + cout << e << " "; + cout << endl; + } + cout << endl; +} + +int main() { + + vector> matrix1 = { + {1,1,1},{1,0,1},{1,1,1} + }; + Solution().setZeroes(matrix1); + print_matrix(matrix1); + + vector> matrix2 = { + {0,1,2,0},{3,4,5,2},{1,3,1,5} + }; + Solution().setZeroes(matrix2); + print_matrix(matrix2); + + return 0; +} \ No newline at end of file diff --git a/Cracking-The-Coding-Interview/04-06/cpp-04-06/CMakeLists.txt b/Cracking-The-Coding-Interview/04-06/cpp-04-06/CMakeLists.txt new file mode 100644 index 00000000..b344d38e --- /dev/null +++ b/Cracking-The-Coding-Interview/04-06/cpp-04-06/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_04_06) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_04_06 main.cpp) diff --git a/Cracking-The-Coding-Interview/04-06/cpp-04-06/main.cpp b/Cracking-The-Coding-Interview/04-06/cpp-04-06/main.cpp new file mode 100644 index 00000000..21a82de1 --- /dev/null +++ b/Cracking-The-Coding-Interview/04-06/cpp-04-06/main.cpp @@ -0,0 +1,55 @@ +/// Source : https://leetcode.cn/problems/successor-lcci/ +/// Author : liuyubobobo +/// Time : 2022-05-15 + +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// 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* inorderSuccessor(TreeNode* root, TreeNode* p) { + + bool next = false; + return dfs(root, p, next); + } + +private: + TreeNode* dfs(TreeNode* node, TreeNode* target, bool& next){ + + if(node->left){ + TreeNode* ret = dfs(node->left, target, next); + if(ret != nullptr) return ret; + } + + if(next) return node; + if(node == target) next = true; + + if(node->right){ + TreeNode* ret = dfs(node->right, target, next); + if(ret != nullptr) return ret; + } + + return nullptr; + } +}; + + +int main() { + + return 0; +} diff --git a/Cracking-The-Coding-Interview/05-02/cpp-05-02/CMakeLists.txt b/Cracking-The-Coding-Interview/05-02/cpp-05-02/CMakeLists.txt new file mode 100644 index 00000000..94d41a68 --- /dev/null +++ b/Cracking-The-Coding-Interview/05-02/cpp-05-02/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_05_02) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_05_02 main.cpp) diff --git a/Cracking-The-Coding-Interview/05-02/cpp-05-02/main.cpp b/Cracking-The-Coding-Interview/05-02/cpp-05-02/main.cpp new file mode 100644 index 00000000..89a0dedb --- /dev/null +++ b/Cracking-The-Coding-Interview/05-02/cpp-05-02/main.cpp @@ -0,0 +1,36 @@ +/// Source : https://leetcode.cn/problems/bianry-number-to-string-lcci/ +/// Author : liuyubobobo +/// Time : 2023-03-01 + +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(1) +/// Space Complexity: O(1) +class Solution { +public: + string printBin(double num) { + + string res = "0."; + double x = 0.5; + for (int k = 0; k < 7 && num != 0; k ++) { + if (num >= x) { + res += '1'; + num -= x; + } else { + res += '0'; + } + x /= 2; + } + return num == 0.0 ? res : "ERROR"; + } +}; + + +int main() { + + return 0; +} diff --git a/Cracking-The-Coding-Interview/16-19/cpp-16-19/CMakeLists.txt b/Cracking-The-Coding-Interview/16-19/cpp-16-19/CMakeLists.txt new file mode 100644 index 00000000..8312a6ab --- /dev/null +++ b/Cracking-The-Coding-Interview/16-19/cpp-16-19/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(cpp_16_19) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_16_19 main.cpp) diff --git a/Cracking-The-Coding-Interview/16-19/cpp-16-19/main.cpp b/Cracking-The-Coding-Interview/16-19/cpp-16-19/main.cpp new file mode 100644 index 00000000..8d22e9c4 --- /dev/null +++ b/Cracking-The-Coding-Interview/16-19/cpp-16-19/main.cpp @@ -0,0 +1,59 @@ +/// Source : https://leetcode.cn/problems/pond-sizes-lcci/ +/// Author : liuyubobobo +/// Time : 2023-06-22 + +#include +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(R * C) +/// Space Complexity: O(R * C) +class Solution { + +private: + int R, C; + const int dirs[8][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}, + {-1, -1}, {-1, 1}, {1, -1}, {1, 1}}; + +public: + vector pondSizes(vector>& land) { + + R = land.size(); C = land[0].size(); + vector> visited(R, vector(C, false)); + vector res; + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++){ + if(visited[i][j] || land[i][j]) continue; + res.push_back(dfs(land, i, j, visited)); + } + sort(res.begin(), res.end()); + return res; + } + +private: + int dfs(const vector>& land, int cx, int cy, vector>& visited){ + + visited[cx][cy] = true; + int res = 1; + for(int d = 0; d < 8; d ++){ + int nx = cx + dirs[d][0], ny = cy + dirs[d][1]; + if(in_area(nx, ny) && !visited[nx][ny] && !land[nx][ny]) + res += dfs(land, nx, ny, visited); + } + return res; + } + + bool in_area(int x, int y){ + return 0 <= x && x < R && 0 <= y && y < C; + } +}; + + +int main() { + + return 0; +} diff --git a/Cracking-The-Coding-Interview/17-05/cpp-17-05/CMakeLists.txt b/Cracking-The-Coding-Interview/17-05/cpp-17-05/CMakeLists.txt new file mode 100644 index 00000000..2ca9c494 --- /dev/null +++ b/Cracking-The-Coding-Interview/17-05/cpp-17-05/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.24) +project(cpp_17_05) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(cpp_17_05 main.cpp) diff --git a/Cracking-The-Coding-Interview/17-05/cpp-17-05/main.cpp b/Cracking-The-Coding-Interview/17-05/cpp-17-05/main.cpp new file mode 100644 index 00000000..c1b73aba --- /dev/null +++ b/Cracking-The-Coding-Interview/17-05/cpp-17-05/main.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode.cn/problems/find-longest-subarray-lcci/ +/// Author : liuyubobobo +/// Time : 2023-03-10 + +#include +#include +#include + +using namespace std; + + +/// Using Map +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + vector findLongestSubarray(vector& array) { + + int n = array.size(); + vector v(n, 0); + for (int i = 0; i < n; i++) + v[i] = (isdigit(array[i][0]) ? 1 : -1); + + map m; + m[0] = -1; + int cur = 0, best = 0, resl = -1, resr = -1; + for(int i = 0; i < n; i ++) { + cur += v[i]; + + auto iter = m.find(-cur); + if(iter != m.end()){ + int len = i - iter->second; + if(len > best){ + best = len; + resl = iter->second + 1; + resr = i; + } + } + else m[-cur] = i; + } + + return best == 0 ? vector() : vector(array.begin() + resl, array.begin() + resr + 1); + } +}; + + +int main() { + + return 0; +} diff --git a/Cracking-The-Coding-Interview/17-09/cpp-17-09/CMakeLists.txt b/Cracking-The-Coding-Interview/17-09/cpp-17-09/CMakeLists.txt new file mode 100644 index 00000000..bc8175f7 --- /dev/null +++ b/Cracking-The-Coding-Interview/17-09/cpp-17-09/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(cpp_17_09) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_17_09 main.cpp) diff --git a/Cracking-The-Coding-Interview/17-09/cpp-17-09/main.cpp b/Cracking-The-Coding-Interview/17-09/cpp-17-09/main.cpp new file mode 100644 index 00000000..4c03f80d --- /dev/null +++ b/Cracking-The-Coding-Interview/17-09/cpp-17-09/main.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.cn/problems/get-kth-magic-number-lcci/ +/// Author : liuyubobobo +/// Time : 2022-09-27 + +#include +#include +#include + +using namespace std; + + +/// Using PQ +/// Time Complexity: O(klogk) +/// Space Complexity: O(k) +class Solution { +public: + int getKthMagicNumber(int k) { + + priority_queue, greater> pq; + pq.push(1); + + set visited; + + long long res = -1; + while(k){ + res = pq.top(); pq.pop(); + if(visited.count(res)) continue; + + visited.insert(res); + + k --; + pq.push(res * 3); + pq.push(res * 5); + pq.push(res * 7); + } + return res; + } +}; + + +int main() { + + cout << Solution().getKthMagicNumber(2) << '\n'; + // 3 + + return 0; +} diff --git a/Cracking-The-Coding-Interview/17-10/cpp-17-10/CMakeLists.txt b/Cracking-The-Coding-Interview/17-10/cpp-17-10/CMakeLists.txt new file mode 100644 index 00000000..4baa8c84 --- /dev/null +++ b/Cracking-The-Coding-Interview/17-10/cpp-17-10/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.5) +project(cpp_0169) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(SOURCE_FILES main.cpp) +add_executable(cpp_0169 ${SOURCE_FILES}) \ No newline at end of file diff --git a/Cracking-The-Coding-Interview/17-10/cpp-17-10/main.cpp b/Cracking-The-Coding-Interview/17-10/cpp-17-10/main.cpp new file mode 100644 index 00000000..465cf949 --- /dev/null +++ b/Cracking-The-Coding-Interview/17-10/cpp-17-10/main.cpp @@ -0,0 +1,42 @@ +/// Source : https://leetcode-cn.com/problems/find-majority-element-lcci/ +/// Author : liuyubobobo +/// Time : 2021-07-08 + +#include +#include +#include + +using namespace std; + + +/// Boyer-Moore Voting Algorithm +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { + +public: + int majorityElement(vector& nums) { + + assert(nums.size() > 0); + + int count = 0; + int res = -1; + for(int num: nums){ + if(count == 0) + res = num; + + count += (res == num) ? 1 : -1; + } + + count = 0; + for(int num: nums) count += (num == res); + + return count > nums.size() / 2 ? res : -1; + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/Cracking-The-Coding-Interview/17-11/cpp-17-11/CMakeLists.txt b/Cracking-The-Coding-Interview/17-11/cpp-17-11/CMakeLists.txt new file mode 100644 index 00000000..7be0d539 --- /dev/null +++ b/Cracking-The-Coding-Interview/17-11/cpp-17-11/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(cpp_17_11) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_17_11 main.cpp) diff --git a/Cracking-The-Coding-Interview/17-11/cpp-17-11/main.cpp b/Cracking-The-Coding-Interview/17-11/cpp-17-11/main.cpp new file mode 100644 index 00000000..bf070010 --- /dev/null +++ b/Cracking-The-Coding-Interview/17-11/cpp-17-11/main.cpp @@ -0,0 +1,44 @@ +/// Source : https://leetcode.cn/problems/find-closest-lcci/ +/// Author : liuyubobobo +/// Time : 2022-05-26 + +#include +#include +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + int findClosest(vector& words, string word1, string word2) { + + vector pos1, pos2; + for(int i = 0; i < words.size(); i ++) + if(words[i] == word1) pos1.push_back(i); + else if(words[i] == word2) pos2.push_back(i); + + if(pos2.size() > pos1.size()) swap(pos1, pos2); + + int res = INT_MAX; + for(int p: pos2){ + auto iter = lower_bound(pos1.begin(), pos1.end(), p); + if(iter != pos1.end()) res = min(res, *iter - p); + if(iter != pos1.begin()){ + iter --; + res = min(res, p - *iter); + } + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/Cracking-The-Coding-Interview/17-21/cpp-17-21/CMakeLists.txt b/Cracking-The-Coding-Interview/17-21/cpp-17-21/CMakeLists.txt new file mode 100644 index 00000000..63d58210 --- /dev/null +++ b/Cracking-The-Coding-Interview/17-21/cpp-17-21/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(17_21) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(17_21 main.cpp) \ No newline at end of file diff --git a/Cracking-The-Coding-Interview/17-21/cpp-17-21/main.cpp b/Cracking-The-Coding-Interview/17-21/cpp-17-21/main.cpp new file mode 100644 index 00000000..9cde4154 --- /dev/null +++ b/Cracking-The-Coding-Interview/17-21/cpp-17-21/main.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode-cn.com/problems/volume-of-histogram-lcci/ +/// Author : liuyubobobo +/// Time : 2021-04-02 + +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int trap(vector& height) { + + int n = height.size(); + if(!n) return 0; + + vector leftmax(n, height[0]), rightmax(n, height.back()); + for(int i = 1; i < n; i ++) + leftmax[i] = max(leftmax[i - 1], height[i]); + for(int i = n - 2; i >= 0; i --) + rightmax[i] = max(rightmax[i + 1], height[i]); + + int res = 0; + for(int i = 0; i < height.size(); i ++){ + int bound = min(leftmax[i], rightmax[i]); + if(bound > height[i]) res += bound - height[i]; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/LC/LCP001/cpp-LCP001/CMakeLists.txt b/LC/LCP001/cpp-LCP001/CMakeLists.txt new file mode 100644 index 00000000..a7a348e1 --- /dev/null +++ b/LC/LCP001/cpp-LCP001/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(cpp_LCP01) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_LCP01 main.cpp) \ No newline at end of file diff --git a/LC/LCP001/cpp-LCP001/main.cpp b/LC/LCP001/cpp-LCP001/main.cpp new file mode 100644 index 00000000..0765c1d6 --- /dev/null +++ b/LC/LCP001/cpp-LCP001/main.cpp @@ -0,0 +1,29 @@ +/// Source : https://leetcode-cn.com/problems/guess-numbers/ +/// Author : liuyubobobo +/// Time : 2020-04-30 + +#include +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int game(vector& guess, vector& answer) { + + int res = 0; + for(int i = 0; i < guess.size(); i ++) + res += guess[i] == answer[i]; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/LC/LCP002/cpp-LCP002/CMakeLists.txt b/LC/LCP002/cpp-LCP002/CMakeLists.txt new file mode 100644 index 00000000..b1976006 --- /dev/null +++ b/LC/LCP002/cpp-LCP002/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main2.cpp) \ No newline at end of file diff --git a/LC/LCP002/cpp-LCP002/main.cpp b/LC/LCP002/cpp-LCP002/main.cpp new file mode 100644 index 00000000..3a5679cd --- /dev/null +++ b/LC/LCP002/cpp-LCP002/main.cpp @@ -0,0 +1,59 @@ +/// Source : https://leetcode-cn.com/problems/deep-dark-fraction/ +/// Author : liuyubobobo +/// Time : 2020-04-30 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(nlog(num)) +/// Space Complexity: O(1) +class Solution { +public: + vector fraction(vector& cont) { + + int n = cont.size(); + if(n == 1 || cont[n - 1] == 0) return {cont[0], 1}; + + vector res = {cont[n - 1], 1}; + for(int i = n - 2; i >= 0; i --){ + swap(res[0], res[1]); + res[0] += cont[i] * res[1]; + int g = gcd(res[0], res[1]); + res[0] /= g, res[1] /= g; + } + return res; + } + +private: + int gcd(int a, int b){ + if(a < b) swap(a, b); + if(a % b == 0) return b; + return gcd(b, a % b); + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << " "; cout << endl; +} + +int main() { + + vector cont1 = {3, 2, 0, 2}; + print_vec(Solution().fraction(cont1)); + // 13 4 + + vector cont2 = {0, 0, 3}; + print_vec(Solution().fraction(cont2)); + // 3 1 + + vector cont3 = {6, 1, 4, 7, 6, 2, 1, 4, 8, 0}; + print_vec(Solution().fraction(cont3)); + // 3 1 + + return 0; +} \ No newline at end of file diff --git a/LC/LCP002/cpp-LCP002/main2.cpp b/LC/LCP002/cpp-LCP002/main2.cpp new file mode 100644 index 00000000..bd876ccb --- /dev/null +++ b/LC/LCP002/cpp-LCP002/main2.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode-cn.com/problems/deep-dark-fraction/ +/// Author : liuyubobobo +/// Time : 2020-04-30 + +#include +#include + +using namespace std; + + +/// Simulation +/// Actually, it's no need to run gcd for this problem +/// Here's a goog explanation: https://leetcode-cn.com/problems/deep-dark-fraction/solution/bu-yong-yue-fen-by-jriver/ +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + vector fraction(vector& cont) { + + int n = cont.size(); + if(n == 1 || cont[n - 1] == 0) return {cont[0], 1}; + + vector res = {cont[n - 1], 1}; + for(int i = n - 2; i >= 0; i --){ + swap(res[0], res[1]); + res[0] += cont[i] * res[1]; + } + return res; + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << " "; cout << endl; +} + +int main() { + + vector cont1 = {3, 2, 0, 2}; + print_vec(Solution().fraction(cont1)); + // 13 4 + + vector cont2 = {0, 0, 3}; + print_vec(Solution().fraction(cont2)); + // 3 1 + + vector cont3 = {6, 1, 4, 7, 6, 2, 1, 4, 8, 0}; + print_vec(Solution().fraction(cont3)); + // 3 1 + + return 0; +} \ No newline at end of file diff --git a/LC/LCP003/cpp-LCP003/CMakeLists.txt b/LC/LCP003/cpp-LCP003/CMakeLists.txt new file mode 100644 index 00000000..3c6ea462 --- /dev/null +++ b/LC/LCP003/cpp-LCP003/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/LC/LCP003/cpp-LCP003/main.cpp b/LC/LCP003/cpp-LCP003/main.cpp new file mode 100644 index 00000000..0ddabf26 --- /dev/null +++ b/LC/LCP003/cpp-LCP003/main.cpp @@ -0,0 +1,72 @@ +/// Source : https://leetcode-cn.com/problems/programmable-robot/ +/// Author : liuyubobobo +/// Time : 2020-04-30 + +#include +#include +#include +#include + +using namespace std; + + +/// Mathematics +/// Time Complexity: O(m + n) +/// Space Complexity: O(m + n) +class Solution { +public: + bool robot(string command, vector>& obstacles, int x, int y) { + + unordered_map> map; + int cx = 0, cy = 0; + map[0].insert(0); + for(char c: command){ + if(c == 'U') cy += 1; + else cx += 1; + if(c) + map[cx].insert(cy); + } + + for(const vector obstacle: obstacles){ + int a = obstacle[0], b = obstacle[1]; + if(a > x || b > y || (a >= x && b >= y)) continue; + + int m = a / cx; + a %= cx; + b -= cy * m; + if(map.count(a) && map[a].count(b)) return false; + } + + int m = x / cx; + x %= cx; + y -= cy * m; + if(map.count(x) && map[x].count(y)) return true; + return false; + } +}; + + +int main() { + + string command1 = "URR"; + vector> obstacles1 = {}; + cout << Solution().robot(command1, obstacles1, 3, 2) << endl; + // 1 + + string command2 = "URR"; + vector> obstacles2 = {{2, 2}}; + cout << Solution().robot(command2, obstacles2, 3, 2) << endl; + // 0 + + string command3 = "URR"; + vector> obstacles3 = {{4, 2}}; + cout << Solution().robot(command3, obstacles3, 3, 2) << endl; + // 1 + + string command4 = "UUR"; + vector> obstacles4 = {}; + cout << Solution().robot(command4, obstacles4, 3, 4) << endl; + // 0 + + return 0; +} \ No newline at end of file diff --git a/LC/LCP004/cpp-LCP004/CMakeLists.txt b/LC/LCP004/cpp-LCP004/CMakeLists.txt new file mode 100644 index 00000000..70268b97 --- /dev/null +++ b/LC/LCP004/cpp-LCP004/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main2.cpp) \ No newline at end of file diff --git a/LC/LCP004/cpp-LCP004/main.cpp b/LC/LCP004/cpp-LCP004/main.cpp new file mode 100644 index 00000000..0f26f567 --- /dev/null +++ b/LC/LCP004/cpp-LCP004/main.cpp @@ -0,0 +1,71 @@ +/// Source : https://leetcode-cn.com/problems/broken-board-dominoes/ +/// Author : liuyubobobo +/// Time : 2020-04-22 + +#include +#include + +using namespace std; + + +/// State Compression DP +/// Time Complexity: O(n * m * 2^m) +/// Space Complexity: O(n * m * 2^m) +class Solution { + +private: + int n, m; + vector board; + +public: + int domino(int n, int m, vector>& broken) { + + this->n = n; + this->m = m; + + board.resize(n, 0); + for(const vector& p: broken) + board[p[0]] |= (1 << p[1]); + + vector>>> dp(n, vector>>(m, + vector>(1<(1<>>>& dp){ + + if(x == n - 1 && y >= m) return 0; + if(y >= m) return go(x + 1, 0, next, x + 1 == n - 1 ? (1 << m) - 1 : board[x + 2], dp); + if(dp[x][y][cur][next] != -1) return dp[x][y][cur][next]; + + int res = go(x, y + 1, cur, next, dp); + + if((cur & (1 << y)) == 0 && y + 1 < m && (cur & (1 << (y + 1))) == 0){ + int next_cur = cur; + next_cur |= (1 << y); + next_cur |= (1 << (y + 1)); + res = max(res, 1 + go(x, y + 2, next_cur, next, dp)); + } + + if((cur & (1 << y)) == 0 && x + 1 < n && (next & (1 << y)) == 0) + res = max(res, 1 + go(x, y + 1, cur | (1 << y), next | (1 << y), dp)); + +// cout << x << " " << y << " " << cur << " " << next << " : " << res << endl; + return dp[x][y][cur][next] = res; + } +}; + + +int main() { + + vector> broken1 = {{1, 0}, {1, 1}}; + cout << Solution().domino(2, 3, broken1) << endl; + // 2 + + vector> broken2 = {}; + cout << Solution().domino(3, 3, broken2) << endl; + // 4 + + return 0; +} \ No newline at end of file diff --git a/LC/LCP004/cpp-LCP004/main2.cpp b/LC/LCP004/cpp-LCP004/main2.cpp new file mode 100644 index 00000000..29b27f05 --- /dev/null +++ b/LC/LCP004/cpp-LCP004/main2.cpp @@ -0,0 +1,102 @@ +/// Source : https://leetcode-cn.com/problems/broken-board-dominoes/ +/// Author : liuyubobobo +/// Time : 2020-04-22 + +#include +#include +#include + +using namespace std; + + +/// Bipartition Match +/// Time Complexity: O(n * m * n * m) +/// Space Complexity: O(n * m) +class Solution { + +private: + int n, m; + const int dirs[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; + +public: + int domino(int n, int m, vector>& broken) { + + this->n = n, this->m = m; + vector> board(n, vector(m, 0)); + for(const vector& p: broken) + board[p[0]][p[1]] = 1; + + vector> g(n * m); + for(int i = 0; i < n; i ++) + for(int j = 0; j < m; j ++) + if(!board[i][j]) + for(int d = 0; d < 4; d ++){ + int nexti = i + dirs[d][0], nextj = j + dirs[d][1]; + if(in_area(nexti, nextj) && !board[nexti][nextj]) + g[i * m + j].insert(nexti * m + nextj), + g[nexti * m + nextj].insert(i * m + j); + } + + vector colors(n * m, -1); + for(int i = 0; i < n * m; i ++) + if(colors[i] == -1) + fillcolor(g, i, 0, colors); + + return max_match(g, colors); + } + +private: + int max_match(const vector>& g, const vector& colors){ + + vector matching(g.size(), -1); + + int res = 0; + for(int i = 0; i < g.size(); i ++) + if(colors[i] == 0 && matching[i] == -1){ + vector visited(g.size(), false); + if(dfs(g, i, visited, matching)) res ++; + } + return res; + } + + bool dfs(const vector>& g, int v, vector& visited, vector& matching){ + + visited[v] = true; + for(int u: g[v]) + if(!visited[u]){ + visited[u] = true; + if(matching[u] == -1 || dfs(g, matching[u], visited, matching)){ + matching[u] = v; + matching[v] = u; + return true; + } + } + return false; + } + + void fillcolor(const vector>& g, int v, int color, vector& colors){ + + colors[v] = color; + for(int next: g[v]) + if(colors[next] == -1) + fillcolor(g, next, 1 - color, colors); + } + + bool in_area(int x, int y){ + return x >= 0 && x < n && y >= 0 && y < m; + } +}; + + +int main() { + + vector> broken1 = {{1, 0}, {1, 1}}; + cout << Solution().domino(2, 3, broken1) << endl; + // 2 + + vector> broken2 = {}; + cout << Solution().domino(3, 3, broken2) << endl; + // 4 + + return 0; +} \ No newline at end of file diff --git a/LC/LCP005/cpp-LCP005/CMakeLists.txt b/LC/LCP005/cpp-LCP005/CMakeLists.txt new file mode 100644 index 00000000..2f230c23 --- /dev/null +++ b/LC/LCP005/cpp-LCP005/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(cpp_LCP05) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_LCP05 main.cpp) \ No newline at end of file diff --git a/LC/LCP005/cpp-LCP005/main.cpp b/LC/LCP005/cpp-LCP005/main.cpp new file mode 100644 index 00000000..ce8abeec --- /dev/null +++ b/LC/LCP005/cpp-LCP005/main.cpp @@ -0,0 +1,152 @@ +/// Source : https://leetcode-cn.com/problems/coin-bonus/ +/// Author : liuyubobobo +/// Time : 2020-04-22 + +#include +#include +#include + +using namespace std; + + +/// DFS Order + Segment Tree +/// Time Complexity: O(n + nlogn) +/// Space Complexity: O(n) +class SegmentTree{ + +private: + int n; + vector tree, lazy; + int MOD = 1e9 + 7; + +public: + SegmentTree(int n): n(n), tree(4 * n, 0), lazy(4 * n, 0){} + + void add(int index, int val){ + update(0, 0, n - 1, index, index, val); + } + + void add(int uL, int uR, int val){ + update(0, 0, n-1, uL, uR, val); + } + + int query(int index){ + return query(0, 0, n-1, index, index); + } + + int query(int qL, int qR){ + return query(0, 0, n-1, qL, qR); + } + +private: + void update(int treeID, int treeL, int treeR, int uL, int uR, int val){ + + if(lazy[treeID]){ + tree[treeID] = (tree[treeID] + (long long)(treeR - treeL + 1) * lazy[treeID]) % MOD; + if(treeL != treeR){ + lazy[2 * treeID + 1] += lazy[treeID]; + lazy[2 * treeID + 2] += lazy[treeID]; + } + lazy[treeID] = 0; + } + + if (treeL > uR || treeR < uL) return; + + if(uL <= treeL && uR >= treeR){ + tree[treeID] = (tree[treeID] + (long long)(treeR - treeL + 1) * val) % MOD; + if(treeL != treeR){ + lazy[2 * treeID + 1] += val; + lazy[2 * treeID + 2] += val; + } + return; + } + + int mid = (treeL + treeR) / 2; + update(2 * treeID + 1, treeL, mid, uL, uR, val); + update(2 * treeID + 2, mid + 1, treeR, uL, uR, val); + tree[treeID] = (tree[treeID * 2 + 1] + tree[treeID * 2 + 2]) % MOD; + return; + } + + int query(int treeID, int treeL, int treeR, int qL, int qR){ + + if(lazy[treeID]){ + tree[treeID] = (tree[treeID] + (long long)(treeR - treeL + 1) * lazy[treeID]) % MOD; + if(treeL != treeR){ + lazy[2 * treeID + 1] += lazy[treeID]; + lazy[2 * treeID + 2] += lazy[treeID]; + } + lazy[treeID] = 0; + } + + if(treeL > qR || treeR < qL) return 0; + + if(qL <= treeL && qR >= treeR) + return tree[treeID]; + + int mid = (treeL + treeR) / 2; + int leftRes = query(2 * treeID + 1, treeL, mid, qL, qR); + int rightRes = query(2 * treeID + 2, mid + 1, treeR, qL, qR); + return (leftRes + rightRes) % MOD; + } +}; + +class Solution { +public: + vector bonus(int n, vector>& leadership, vector>& operations) { + + vector> g(n); + for(vector& v: leadership) + g[v[0] - 1].insert(v[1] - 1); +// for(int i = 0; i < n; i ++){ +// cout << i << " : "; for(int x: g[i]) cout << x << " "; cout << endl; +// } + + vector> vToRange(n); + int index = 0; + dfs(g, 0, index, vToRange); +// for(int i = 0; i < vToRange.size(); i ++) +// cout << i << " : [" << vToRange[i].first << " , " << vToRange[i].second << "]" << endl; + + SegmentTree tree(n); + vector res; + for(const vector&op: operations) { + int x = op[1] - 1; + switch(op[0]) { + case 1: + tree.add(vToRange[x].first, op[2]); + break; + case 2: + tree.add(vToRange[x].first, vToRange[x].second, op[2]); + break; + case 3: + res.push_back(tree.query(vToRange[x].first, vToRange[x].second)); + break; + } + } + return res; + } + +private: + void dfs(const vector>& g, int v, int& index, vector>& vToRange){ + + vToRange[v].first = index ++; + for(int next: g[v]) + dfs(g, next, index, vToRange); + vToRange[v].second = index - 1; + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << " "; cout << endl; +} + +int main() { + + vector> leadership = {{1, 2}, {1, 6}, {2, 3}, {2, 5}, {1, 4}}; + vector> operations = {{1, 1, 500}, {2, 2, 50}, {3, 1}, {2, 6, 15}, {3, 1}}; + print_vec(Solution().bonus(6, leadership, operations)); + + return 0; +} diff --git a/LC/LCP006/cpp-LCP006/CMakeLists.txt b/LC/LCP006/cpp-LCP006/CMakeLists.txt new file mode 100644 index 00000000..cb89cda6 --- /dev/null +++ b/LC/LCP006/cpp-LCP006/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/LC/LCP006/cpp-LCP006/main.cpp b/LC/LCP006/cpp-LCP006/main.cpp new file mode 100644 index 00000000..c4e9ee3d --- /dev/null +++ b/LC/LCP006/cpp-LCP006/main.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode-cn.com/problems/na-ying-bi/solution/ +/// Author : liuyubobobo +/// Time : 2020-04-17 + +#include +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int minCount(vector& coins) { + + int res = 0; + for(int e: coins) + res += e / 2 + e % 2; + return res; + } +}; + + +int main() { + + vector coins1 = {4, 2, 1}; + cout << Solution().minCount(coins1) << endl; + // 4 + + vector coins2 = {2, 3, 10}; + cout << Solution().minCount(coins2) << endl; + // 8 + + return 0; +} \ No newline at end of file diff --git a/LC/LCP007/cpp-LCP007/CMakeLists.txt b/LC/LCP007/cpp-LCP007/CMakeLists.txt new file mode 100644 index 00000000..ec91efec --- /dev/null +++ b/LC/LCP007/cpp-LCP007/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main4.cpp) \ No newline at end of file diff --git a/LC/LCP007/cpp-LCP007/main.cpp b/LC/LCP007/cpp-LCP007/main.cpp new file mode 100644 index 00000000..7f08a950 --- /dev/null +++ b/LC/LCP007/cpp-LCP007/main.cpp @@ -0,0 +1,43 @@ +/// Source : https://leetcode-cn.com/problems/chuan-di-xin-xi/ +/// Author : liuyubobobo +/// Time : 2020-04-17 + +#include +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n^k) +/// Space Complexity: O(n + |relation| + k) +class Solution { + +public: + int numWays(int n, vector>& relation, int k) { + + vector> g(n); + for(const vector& arc: relation) + g[arc[0]].insert(arc[1]); + + return dfs(g, 0, n - 1, k); + } + +private: + int dfs(const vector>& g, int start, int end, int step){ + + if(step == 0) return start == end; + + int res = 0; + for(int next: g[start]) + res += dfs(g, next, end, step - 1); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/LC/LCP007/cpp-LCP007/main2.cpp b/LC/LCP007/cpp-LCP007/main2.cpp new file mode 100644 index 00000000..094fb9b8 --- /dev/null +++ b/LC/LCP007/cpp-LCP007/main2.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode-cn.com/problems/chuan-di-xin-xi/ +/// Author : liuyubobobo +/// Time : 2020-04-18 + +#include +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(n*n*k) +/// Space Complexity: O(n*k) +class Solution { + +public: + int numWays(int n, vector>& relation, int k) { + + vector> g(n); + for(const vector& arc: relation) + g[arc[0]].insert(arc[1]); + + vector> dp(n, vector(k + 1, -1)); + return dfs(g, 0, n - 1, k, dp); + } + +private: + int dfs(const vector>& g, int start, int end, int step, + vector>& dp){ + + if(step == 0) return start == end; + if(dp[start][step] != -1) return dp[start][step]; + + int res = 0; + for(int next: g[start]) + res += dfs(g, next, end, step - 1, dp); + return dp[start][step] = res; + } +}; + + +int main() { + + return 0; +} diff --git a/LC/LCP007/cpp-LCP007/main3.cpp b/LC/LCP007/cpp-LCP007/main3.cpp new file mode 100644 index 00000000..7fb4f7f7 --- /dev/null +++ b/LC/LCP007/cpp-LCP007/main3.cpp @@ -0,0 +1,40 @@ +/// Source : https://leetcode-cn.com/problems/chuan-di-xin-xi/ +/// Author : liuyubobobo +/// Time : 2020-04-18 + +#include +#include +#include + +using namespace std; + + +/// Dynamic Preogramming +/// Time Complexity: O(k*(n + |relation|)) +/// Space Complexity: O(n + |relation|) +class Solution { + +public: + int numWays(int n, vector>& relation, int k) { + + vector> g(n); + for(const vector& arc: relation) + g[arc[0]].insert(arc[1]); + + vector> dp(n, vector(k + 1, 0)); + for(int i = 0; i < n; i ++) + if(g[i].count(n - 1)) dp[i][1] = 1; + + for(int j = 2; j <= k; j ++) + for(int i = 0; i < n; i ++) + for(int next: g[i]) + dp[i][j] += dp[next][j - 1]; + return dp[0][k]; + } +}; + + +int main() { + + return 0; +} diff --git a/LC/LCP007/cpp-LCP007/main4.cpp b/LC/LCP007/cpp-LCP007/main4.cpp new file mode 100644 index 00000000..e462f72b --- /dev/null +++ b/LC/LCP007/cpp-LCP007/main4.cpp @@ -0,0 +1,45 @@ +/// Source : https://leetcode-cn.com/problems/chuan-di-xin-xi/ +/// Author : liuyubobobo +/// Time : 2020-04-18 + +#include +#include + +using namespace std; + + +/// Methematics: Matrix Multiplication +/// Time Complexity: O(k * n^3) +/// Space Complexity: O(n^2) +class Solution { + +public: + int numWays(int n, vector>& relation, int k) { + + vector> A(n, vector(n, 0)); + for(const vector& arc: relation) + A[arc[0]][arc[1]] = 1; + + vector> res = A; + for(int i = 1; i < k; i ++) res = mul(res, A, n); + return res[0][n - 1]; + } + +private: + vector> mul(const vector>& A, + const vector>& B,int n){ + + vector> res(n, vector(n, 0)); + for(int i = 0; i < n; i ++) + for(int j = 0; j < n; j ++) + for(int k = 0; k < n; k ++) + res[i][j] += A[i][k] * B[k][j]; + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/LC/LCP008/cpp-LCP008/CMakeLists.txt b/LC/LCP008/cpp-LCP008/CMakeLists.txt new file mode 100644 index 00000000..26e63018 --- /dev/null +++ b/LC/LCP008/cpp-LCP008/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main2.cpp) \ No newline at end of file diff --git a/LC/LCP008/cpp-LCP008/main.cpp b/LC/LCP008/cpp-LCP008/main.cpp new file mode 100644 index 00000000..24f6f6c2 --- /dev/null +++ b/LC/LCP008/cpp-LCP008/main.cpp @@ -0,0 +1,78 @@ +/// Source : https://leetcode-cn.com/problems/ju-qing-hong-fa-shi-jian/ +/// Author : liuyubobobo +/// Time : 2020-04-17 + +#include +#include +#include +#include + +using namespace std; + + +/// Using tree structure +/// Time Complexity: O(|inc| * |r|) +/// Space Complexity: O(|r|) +class Solution { +public: + vector getTriggerTime(vector>& inc, vector>& r) { + + map, set>> tree; + + vector res(r.size(), -1); + for(int i = 0; i < r.size(); i ++) + if(!r[i][0] && !r[i][1] && !r[i][2]) res[i] = 0; + else tree[r[i][0]][make_pair(r[i][1],r[i][2])].insert(i); + + int a = 0, b = 0, c = 0; + for(int i = 0; i < inc.size(); i ++){ + a += inc[i][0], b += inc[i][1], c += inc[i][2]; + + vector delv1; + for(const pair, set>>& p: tree){ + if(p.first > a) break; + + vector> delv2; + for(const pair, set>& p2: p.second){ + if(p2.first.first <= b && p2.first.second <= c){ + for(int index: p2.second) res[index] = i + 1; + delv2.push_back(p2.first); + } + else if(p2.first.first > b) break; + } + + for(const pair& delp: delv2) + tree[p.first].erase(delp); + if(tree[p.first].size() == 0) delv1.push_back(p.first); + } + + for(int delkey: delv1) tree.erase(delkey); + } + return res; + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << " "; cout << endl; +} + +int main() { + + vector> inc1 = {{2,8,4},{2,5,0},{10,9,8}}; + vector> r1 = {{2,11,3},{15,10,7},{9,17,12},{8,1,14}}; + print_vec(Solution().getTriggerTime(inc1, r1)); + // 2,-1,3,-1 + + vector> inc2 = {{0,4,5}, {4,8,8},{8,6,1},{10,10,0}}; + vector> r2 = {{12,11,16},{20,2,6},{9,2,6},{10,18,3},{8,14,9}}; + print_vec(Solution().getTriggerTime(inc2, r2)); + // -1 4 3 3 3 + + vector> inc3 = {{1,1,1}}; + vector> r3 = {{0,0,0}}; + print_vec(Solution().getTriggerTime(inc3, r3)); + // 0 + + return 0; +} diff --git a/LC/LCP008/cpp-LCP008/main2.cpp b/LC/LCP008/cpp-LCP008/main2.cpp new file mode 100644 index 00000000..45948e15 --- /dev/null +++ b/LC/LCP008/cpp-LCP008/main2.cpp @@ -0,0 +1,71 @@ +/// Source : https://leetcode-cn.com/problems/ju-qing-hong-fa-shi-jian/ +/// Author : liuyubobobo +/// Time : 2020-04-18 + +#include +#include +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(|r| * log(|inc|)) +/// Space Complexity: O(|inc|) +class Solution { +public: + vector getTriggerTime(vector>& inc, vector>& r) { + + vector> v = {{0, 0, 0}}; + for(const vector& e: inc){ + vector newe = v.back(); + newe[0] += e[0], newe[1] += e[1], newe[2] += e[2]; + v.push_back(newe); + } + + vector res; + for(const vector& e: r) + res.push_back(binary_search(v, e)); + return res; + } + +private: + int binary_search(const vector>& v, const vector& e){ + + int l = 0, r = v.size(); + while(l != r){ + int mid = (l + r) / 2; + if(v[mid][0] >= e[0] && v[mid][1] >= e[1] && v[mid][2] >= e[2]) + r = mid; + else + l = mid + 1; + } + return l == v.size() ? -1 : l; + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << " "; cout << endl; +} + +int main() { + + vector> inc1 = {{2,8,4},{2,5,0},{10,9,8}}; + vector> r1 = {{2,11,3},{15,10,7},{9,17,12},{8,1,14}}; + print_vec(Solution().getTriggerTime(inc1, r1)); + // 2,-1,3,-1 + + vector> inc2 = {{0,4,5}, {4,8,8},{8,6,1},{10,10,0}}; + vector> r2 = {{12,11,16},{20,2,6},{9,2,6},{10,18,3},{8,14,9}}; + print_vec(Solution().getTriggerTime(inc2, r2)); + // -1 4 3 3 3 + + vector> inc3 = {{1,1,1}}; + vector> r3 = {{0,0,0}}; + print_vec(Solution().getTriggerTime(inc3, r3)); + // 0 + + return 0; +} diff --git a/LC/LCP009/cpp-LCP009/CMakeLists.txt b/LC/LCP009/cpp-LCP009/CMakeLists.txt new file mode 100644 index 00000000..ffce3872 --- /dev/null +++ b/LC/LCP009/cpp-LCP009/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main2.cpp) \ No newline at end of file diff --git a/LC/LCP009/cpp-LCP009/main.cpp b/LC/LCP009/cpp-LCP009/main.cpp new file mode 100644 index 00000000..2d87271f --- /dev/null +++ b/LC/LCP009/cpp-LCP009/main.cpp @@ -0,0 +1,42 @@ +/// Source : https://leetcode-cn.com/problems/zui-xiao-tiao-yue-ci-shu/ +/// Author : liuyubobobo +/// Time : 2020-04-18 + +#include +#include +#include + +using namespace std; + + +/// Dynamic Programming +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { + +public: + int minJump(vector& jump) { + + int n = jump.size(); + vector dp(n, 1); + for(int i = n - 2; i >= 0; i --){ + + if(i + jump[i] < n) dp[i] = dp[i + jump[i]] + 1; + + for(int j = i + 1; j < n; j ++) + if(1 + dp[i] <= dp[j]) dp[j] = 1 + dp[i]; + else break; + } + return dp[0]; + } +}; + + +int main() { + + vector jump1 = {2, 5, 1, 1, 1, 1}; + cout << Solution().minJump(jump1) << endl; + // 3 + + return 0; +} diff --git a/LC/LCP009/cpp-LCP009/main2.cpp b/LC/LCP009/cpp-LCP009/main2.cpp new file mode 100644 index 00000000..bda7aa2f --- /dev/null +++ b/LC/LCP009/cpp-LCP009/main2.cpp @@ -0,0 +1,61 @@ +/// Source : https://leetcode-cn.com/problems/zui-xiao-tiao-yue-ci-shu/ +/// Author : liuyubobobo +/// Time : 2020-04-19 + +#include +#include +#include +#include + +using namespace std; + + +/// BFS +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +public: + int minJump(vector& jump) { + + int n = jump.size(); + vector step(n + 1, -1); + step[0] = 0; + queue q; + q.push(0); + int max_left = -1; + while(!q.empty()){ + int cur = q.front(); + q.pop(); + + int right = cur + jump[cur]; + if(right >= n) return 1 + step[cur]; + if(step[right] == -1){ + step[right] = 1 + step[cur]; + q.push(right); + } + + for(int left = cur - 1; left > max_left; left --){ + step[left] = 1 + step[cur]; + q.push(left); + } + max_left = max(max_left, cur); + } + assert(false); + return -1; + } +}; + + +int main() { + + vector jump1 = {2, 5, 1, 1, 1, 1}; + cout << Solution().minJump(jump1) << endl; + // 3 + + vector jump2 = {2, 1, 2, 100, 2, 1, 1, 1, 1}; + cout << Solution().minJump(jump2) << endl; + // 4 + + return 0; +} diff --git a/LC/LCP010/cpp-LCP010/CMakeLists.txt b/LC/LCP010/cpp-LCP010/CMakeLists.txt new file mode 100644 index 00000000..d9b75544 --- /dev/null +++ b/LC/LCP010/cpp-LCP010/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(cpp_LCP10) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_LCP10 main.cpp) \ No newline at end of file diff --git a/LC/LCP010/cpp-LCP010/main.cpp b/LC/LCP010/cpp-LCP010/main.cpp new file mode 100644 index 00000000..8597bb16 --- /dev/null +++ b/LC/LCP010/cpp-LCP010/main.cpp @@ -0,0 +1,65 @@ +/// Source : https://leetcode-cn.com/problems/er-cha-shu-ren-wu-diao-du/ +/// Author : liuyubobobo +/// Time : 2020-04-20 + +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(h) + +/// 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: + double minimalExecTime(TreeNode* root) { + + pair res = dfs(root); + return res.first + res.second / 2.0; + } + +private: + pair dfs(TreeNode* node){ + + if(!node) return {0, 0}; + + pair t1 = dfs(node->left); + pair t2 = dfs(node->right); +// cout << node->val << endl; +// cout << "t1 : s = " << t1.first << " p = " << t1.second << endl; +// cout << "t2 : s = " << t2.first << " p = " << t2.second << endl; + + int s = node->val, p = 0; + + if(t1.first < t2.first) swap(t1, t2); + int newp = min(t1.first, t2.first); + p += 2 * newp; + t1.first -= newp, t2.first -= newp; + + if(t1.first && t2.second){ + newp = min(t1.first, t2.second); + p += 2 * newp; + t1.first -= newp, t2.second -= newp; + } + + s += t1.first; + p += t1.second + t2.second; + + return {s, p}; + } +}; + + +int main() { + + return 0; +} diff --git a/LC/LCP011/cpp-LCP011/CMakeLists.txt b/LC/LCP011/cpp-LCP011/CMakeLists.txt new file mode 100644 index 00000000..446d8265 --- /dev/null +++ b/LC/LCP011/cpp-LCP011/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main2.cpp) \ No newline at end of file diff --git a/LC/LCP011/cpp-LCP011/main.cpp b/LC/LCP011/cpp-LCP011/main.cpp new file mode 100644 index 00000000..442f18fd --- /dev/null +++ b/LC/LCP011/cpp-LCP011/main.cpp @@ -0,0 +1,50 @@ +/// Source : https://leetcode-cn.com/problems/qi-wang-ge-shu-tong-ji/ +/// Author : liuyubobobo +/// Time : 2020-04-25 + +#include +#include + +using namespace std; + + +/// Sorting and Linear remove duplicates +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + int expectNumber(vector& scores) { + + sort(scores.begin(), scores.end()); + + int res = 0; + for(int start = 0, i = 1; i <= scores.size(); ) + if(i == scores.size() || scores[i] != scores[start]){ + int x = i - start; + if(x) res ++; + start = i; + i = start + 1; + } + else i ++; + + return res; + } +}; + + +int main() { + + vector scores1 = {1, 2, 3}; + cout << Solution().expectNumber(scores1) << endl; + // 3 + + vector scores2 = {1, 1}; + cout << Solution().expectNumber(scores2) << endl; + // 1 + + vector scores3 = {1, 1, 2}; + cout << Solution().expectNumber(scores3) << endl; + // 2 + + return 0; +} diff --git a/LC/LCP011/cpp-LCP011/main2.cpp b/LC/LCP011/cpp-LCP011/main2.cpp new file mode 100644 index 00000000..d198d8fe --- /dev/null +++ b/LC/LCP011/cpp-LCP011/main2.cpp @@ -0,0 +1,41 @@ +/// Source : https://leetcode-cn.com/problems/qi-wang-ge-shu-tong-ji/ +/// Author : liuyubobobo +/// Time : 2020-04-29 + +#include +#include +#include + +using namespace std; + + +/// Using Hash Set +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int expectNumber(vector& scores) { + + unordered_set set; + for(int e: scores) set.insert(e); + return set.size(); + } +}; + + +int main() { + + vector scores1 = {1, 2, 3}; + cout << Solution().expectNumber(scores1) << endl; + // 3 + + vector scores2 = {1, 1}; + cout << Solution().expectNumber(scores2) << endl; + // 1 + + vector scores3 = {1, 1, 2}; + cout << Solution().expectNumber(scores3) << endl; + // 2 + + return 0; +} diff --git a/LC/LCP012/cpp-LCP012/CMakeLists.txt b/LC/LCP012/cpp-LCP012/CMakeLists.txt new file mode 100644 index 00000000..545e47b8 --- /dev/null +++ b/LC/LCP012/cpp-LCP012/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/LC/LCP012/cpp-LCP012/main.cpp b/LC/LCP012/cpp-LCP012/main.cpp new file mode 100644 index 00000000..fc85f08c --- /dev/null +++ b/LC/LCP012/cpp-LCP012/main.cpp @@ -0,0 +1,59 @@ +/// Source : https://leetcode-cn.com/problems/xiao-zhang-shua-ti-ji-hua/solution/xiao-zhang-shua-ti-ji-hua-er-fen-cha-zhao-by-leetc/ +/// Author : liuyubobobo +/// Time : 2020-04-25 + +#include +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(nlogn(sum)) +/// Space Complexity: O(1) +class Solution { +public: + int minTime(vector& time, int m) { + + if(time.size() <= m) return 0; + + int l = 0, r = accumulate(time.begin(), time.end(), 0); + while(l < r){ + int mid = (l + r) / 2; + if(ok(time, m, mid)) r = mid; + else l = mid + 1; + } + assert(l != 0); + return l; + } + +private: + int ok(const vector& time, int m, int T){ + + int sum = 0, maxt = 0, days = 0; + for(int i = 0; i < time.size();){ + sum += time[i]; + maxt = max(maxt, time[i]); + if(sum - maxt > T) + sum = 0, maxt = 0, days ++; + else i ++; + } + if(sum) days ++; + return days <= m; + } +}; + + +int main() { + + vector time1 = {1, 2, 3, 3}; + cout << Solution().minTime(time1, 2) << endl; + // 3 + + vector time2 = {999, 999, 999}; + cout << Solution().minTime(time2, 4) << endl; + // 0 + + return 0; +} diff --git a/LC/LCP013/cpp-LCP013/CMakeLists.txt b/LC/LCP013/cpp-LCP013/CMakeLists.txt new file mode 100644 index 00000000..26e63018 --- /dev/null +++ b/LC/LCP013/cpp-LCP013/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main2.cpp) \ No newline at end of file diff --git a/LC/LCP013/cpp-LCP013/main.cpp b/LC/LCP013/cpp-LCP013/main.cpp new file mode 100644 index 00000000..da48c083 --- /dev/null +++ b/LC/LCP013/cpp-LCP013/main.cpp @@ -0,0 +1,145 @@ +/// Source : https://leetcode-cn.com/problems/xun-bao/ +/// Author : liuyubobobo +/// Time : 2020-04-29 + +#include +#include +#include +#include + +using namespace std; + + +/// TSP : Memory Search +/// Time Complexity: O(M * M * (1 << M)) +/// Time Complexity: O(M * (1 << M)) +class Solution { + +private: + const int dirs[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; + const int INF = 1e9; + + int m, n; + vector Os, Ms; + int start, end; + +public: + int minimalSteps(vector& maze) { + + m = maze.size(), n = maze[0].size(); + + for(int i = 0; i < m; i ++) + for(int j = 0; j < n; j ++){ + int index = i * n + j; + if(maze[i][j] == 'S') start = index; + else if(maze[i][j] == 'T') end = index; + else if(maze[i][j] == 'O') Os.push_back(index); + else if(maze[i][j] == 'M') Ms.push_back(index); + } + + vector steps; + + + /// Corner Cases + if(Ms.size() == 0){ + steps = bfs(maze, start); + return steps[end] == INF ? -1 : steps[end]; + } + if(Os.size() == 0) return -1; + + + /// Pre Calculation + vector> MO(Ms.size(), vector(Os.size())); + for(int i = 0; i < Ms.size(); i ++){ + steps = bfs(maze, Ms[i]); + for(int j = 0; j < Os.size(); j ++) + MO[i][j] = steps[Os[j]]; + } + + vector> MM(Ms.size(), vector(Ms.size(), INF)); + for(int i = 0; i < Ms.size(); i ++) + for(int j = i + 1; j < Ms.size(); j ++) + for(int k = 0; k < Os.size(); k ++) + MM[i][j] = MM[j][i] = min(MM[i][j], MO[i][k] + MO[j][k]); + + steps = bfs(maze, end); + vector ME(Ms.size()); + for(int i = 0; i < Ms.size(); i ++) ME[i] = steps[Ms[i]]; + + steps = bfs(maze, start); + vector SO(Os.size()); + for(int i = 0; i < Os.size(); i ++) SO[i] = steps[Os[i]]; + + + /// TSP - Memory Search + int res = INF; + vector> dp(Ms.size(), vector(1 << Ms.size(), -1)); + for(int i = 0; i < Ms.size(); i ++){ + int sdis = INF; + for(int j = 0; j < Os.size(); j ++) + sdis = min(sdis, SO[j] + MO[i][j]); + + res = min(res, sdis + dfs(MM, ME, 1 << i, i, dp)); + } + return res >= INF ? -1 : res; + } + +private: + int dfs(const vector>& MM, const vector& ME, + int mstate, int mcur, vector>& dp){ + + if(dp[mcur][mstate] != -1) return dp[mcur][mstate]; + if(mstate == (1 << Ms.size()) - 1) return dp[mcur][mstate] = ME[mcur]; + + int res = INF; + for(int i = 0; i < Ms.size(); i ++) + if((mstate & (1 << i)) == 0 && MM[mcur][i] != INF) + res = min(res, MM[mcur][i] + dfs(MM, ME, mstate | (1 << i), i, dp)); + return dp[mcur][mstate] = res; + } + + vector bfs(const vector& maze, int s){ + + vector step(m * n, INF); + + queue q; + q.push(s); + step[s] = 0; + while(!q.empty()){ + int cur = q.front(); + q.pop(); + + int curx = cur / n, cury = cur % n; + for(int d = 0; d < 4; d ++){ + int nextx = curx + dirs[d][0], nexty = cury + dirs[d][1], next = nextx * n + nexty; + if(in_area(nextx, nexty) && maze[nextx][nexty] != '#' && step[next] == INF){ + step[next] = step[cur] + 1; + q.push(next); + } + } + } + return step; + } + + bool in_area(int x, int y){ + return x >= 0 && x < m && y >= 0 && y < n; + } +}; + + +int main() { + + vector maze1 = {"S#O", "M..", "M.T"}; + cout << Solution().minimalSteps(maze1) << endl; + // 16 + + vector maze2 = {"S#O", "M.#", "M.T"}; + cout << Solution().minimalSteps(maze2) << endl; + // -1 + + vector maze3 = {"S#O", "M.T", "M.."}; + cout << Solution().minimalSteps(maze3) << endl; + // 17 + + return 0; +} diff --git a/LC/LCP013/cpp-LCP013/main2.cpp b/LC/LCP013/cpp-LCP013/main2.cpp new file mode 100644 index 00000000..eabb4686 --- /dev/null +++ b/LC/LCP013/cpp-LCP013/main2.cpp @@ -0,0 +1,148 @@ +/// Source : https://leetcode-cn.com/problems/xun-bao/ +/// Author : liuyubobobo +/// Time : 2020-04-29 + +#include +#include +#include +#include + +using namespace std; + + +/// TSP : Dynamic Programming +/// Time Complexity: O(M * M * (1 << M)) +/// Time Complexity: O(M * (1 << M)) +class Solution { + +private: + const int dirs[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; + const int INF = 1e9; + + int m, n; + vector Os, Ms; + int start, end; + +public: + int minimalSteps(vector& maze) { + + m = maze.size(), n = maze[0].size(); + + for(int i = 0; i < m; i ++) + for(int j = 0; j < n; j ++){ + int index = i * n + j; + if(maze[i][j] == 'S') start = index; + else if(maze[i][j] == 'T') end = index; + else if(maze[i][j] == 'O') Os.push_back(index); + else if(maze[i][j] == 'M') Ms.push_back(index); + } + + vector steps; + + + /// Corner Cases + if(Ms.size() == 0){ + steps = bfs(maze, start); + return steps[end] == INF ? -1 : steps[end]; + } + if(Os.size() == 0) return -1; + + + /// Pre Calculation + vector> MO(Ms.size(), vector(Os.size())); + for(int i = 0; i < Ms.size(); i ++){ + steps = bfs(maze, Ms[i]); + for(int j = 0; j < Os.size(); j ++) + MO[i][j] = steps[Os[j]]; + } + + vector> MM(Ms.size(), vector(Ms.size(), INF)); + for(int i = 0; i < Ms.size(); i ++) + for(int j = i + 1; j < Ms.size(); j ++) + for(int k = 0; k < Os.size(); k ++) + MM[i][j] = MM[j][i] = min(MM[i][j], MO[i][k] + MO[j][k]); + + steps = bfs(maze, end); + vector ME(Ms.size()); + for(int i = 0; i < Ms.size(); i ++) ME[i] = steps[Ms[i]]; + + steps = bfs(maze, start); + vector SO(Os.size()); + for(int i = 0; i < Os.size(); i ++) SO[i] = steps[Os[i]]; + + + /// TSP - DP + int res = INF; + vector> dp(Ms.size(), vector(1 << Ms.size(), INF)); + for(int start = 0; start < Ms.size(); start ++) { + int sdis = INF; + for (int i = 0; i < Os.size(); i++) + sdis = min(sdis, SO[i] + MO[start][i]); + dp[start][1 << start] = sdis; + } + + for(int state = 1; state < (1 << Ms.size()); state ++) + for(int i = 0; i < Ms.size(); i ++) + if(dp[i][state] != INF) + for(int j = 0; j < Ms.size(); j ++) + if(j != i && (state & (1 << j)) == 0) + dp[j][state | (1 << j)] = min(dp[j][state | (1 << j)], dp[i][state] + MM[i][j]); + + for(int i = 0; i < Ms.size(); i ++) + if(dp[i][(1 << Ms.size()) - 1] != INF) { + dp[i][(1 << Ms.size()) - 1] += ME[i]; + res = min(res, dp[i][(1 << Ms.size()) - 1]); + } + return res >= INF ? -1 : res; + } + +private: + vector bfs(const vector& maze, int s){ + + vector step(m * n, INF); + + queue q; + q.push(s); + step[s] = 0; + while(!q.empty()){ + int cur = q.front(); + q.pop(); + + int curx = cur / n, cury = cur % n; + for(int d = 0; d < 4; d ++){ + int nextx = curx + dirs[d][0], nexty = cury + dirs[d][1], next = nextx * n + nexty; + if(in_area(nextx, nexty) && maze[nextx][nexty] != '#' && step[next] == INF){ + step[next] = step[cur] + 1; + q.push(next); + } + } + } + return step; + } + + bool in_area(int x, int y){ + return x >= 0 && x < m && y >= 0 && y < n; + } +}; + + +int main() { + + vector maze1 = {"S#O", "M..", "M.T"}; + cout << Solution().minimalSteps(maze1) << endl; + // 16 + + vector maze2 = {"S#O", "M.#", "M.T"}; + cout << Solution().minimalSteps(maze2) << endl; + // -1 + + vector maze3 = {"S#O", "M.T", "M.."}; + cout << Solution().minimalSteps(maze3) << endl; + // 17 + + vector maze4 = {"...O.",".S#M.","..#T.","....."}; + cout << Solution().minimalSteps(maze4) << endl; + // 5 + + return 0; +} diff --git a/LC/LCP014/cpp-LCP014/CMakeLists.txt b/LC/LCP014/cpp-LCP014/CMakeLists.txt new file mode 100644 index 00000000..ffce3872 --- /dev/null +++ b/LC/LCP014/cpp-LCP014/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main2.cpp) \ No newline at end of file diff --git a/LC/LCP014/cpp-LCP014/main.cpp b/LC/LCP014/cpp-LCP014/main.cpp new file mode 100644 index 00000000..9e9325d7 --- /dev/null +++ b/LC/LCP014/cpp-LCP014/main.cpp @@ -0,0 +1,73 @@ +/// Source : https://leetcode-cn.com/problems/qie-fen-shu-zu/ +/// Author : liuyubobobo +/// Time : 2020-04-30 + +#include +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(nlog(maxnum)) +/// Space Complexity: O(n) +class Solution { +public: + int splitArray(vector& nums) { + + if(nums.size() == 1) return 1; + + vector dp(nums.size(), 1); + unordered_map best; + vector d = get_divisors(nums[0]); + for(int e: d) best[e] = 0; + + for(int i = 1; i < nums.size(); i ++){ + dp[i] = dp[i - 1] + 1; + d = get_divisors(nums[i]); + for(int e: d) + if(best.count(e)) dp[i] = min(dp[i], best[e] + 1); + for(int e: d) + best[e] = best.count(e) ? min(best[e], dp[i - 1]) : dp[i - 1]; + } + return dp[nums.size() - 1]; + } + +private: + vector get_divisors(int num){ + + vector res; + if(!(num & 1)){ + res.push_back(2); + while(!(num & 1)) num >>= 1; + } + + for(int d = 3; d * d <= num; d += 2) + if(num % d == 0){ + res.push_back(d); + while(num % d == 0) num /= d; + } + + if(num != 1) res.push_back(num); + return res; + } +}; + + +int main() { + + vector nums1 = {2,3,3,2,3,3}; + cout << Solution().splitArray(nums1) << endl; + // 2 + + vector nums2 = {2,3,5,7}; + cout << Solution().splitArray(nums2) << endl; + // 4 + + vector nums3 = {2,4,6,8,10}; + cout << Solution().splitArray(nums3) << endl; + // 1 + + return 0; +} diff --git a/LC/LCP014/cpp-LCP014/main2.cpp b/LC/LCP014/cpp-LCP014/main2.cpp new file mode 100644 index 00000000..c6499127 --- /dev/null +++ b/LC/LCP014/cpp-LCP014/main2.cpp @@ -0,0 +1,73 @@ +/// Source : https://leetcode-cn.com/problems/qie-fen-shu-zu/ +/// Author : liuyubobobo +/// Time : 2020-04-30 + +#include +#include +#include + +using namespace std; + + +/// DP +/// Using p[x] to record the min prime factor of x +/// Time Complexity: O(maxnum*log(maxnum) + nlog(maxnum)) +/// Space Complexity: O(maxnum) +class Solution { + +public: + int splitArray(vector& nums) { + + if(nums.size() == 1) return 1; + + int maxnum = *max_element(nums.begin(), nums.end()); + vector p(maxnum + 1, 0); + for(int i = 2; i <= maxnum; i ++) + if(!p[i]) + for(int j = i; j <= maxnum; j += i) + if(!p[j]) p[j] = i; + + vector best(maxnum + 1, -1); + + int x = nums[0]; + while(x != 1) best[p[x]] = 0, x /= p[x]; + + int prev = 1, cur; + for(int i = 1; i < nums.size(); i ++){ + + cur = prev + 1; + + int x = nums[i]; + while(x != 1){ + if(best[p[x]] != -1) cur = min(cur, best[p[x]] + 1); + x /= p[x]; + } + + x = nums[i]; + while(x != 1){ + best[p[x]] = (best[p[x]] != -1 ? min(best[p[x]], prev) : prev); + x /= p[x]; + } + prev = cur; + } + return cur; + } +}; + + +int main() { + + vector nums1 = {2,3,3,2,3,3}; + cout << Solution().splitArray(nums1) << endl; + // 2 + + vector nums2 = {2,3,5,7}; + cout << Solution().splitArray(nums2) << endl; + // 4 + + vector nums3 = {2,4,6,8,10}; + cout << Solution().splitArray(nums3) << endl; + // 1 + + return 0; +} diff --git a/LC/LCP015/cpp-LCP015/CMakeLists.txt b/LC/LCP015/cpp-LCP015/CMakeLists.txt new file mode 100644 index 00000000..79dd908c --- /dev/null +++ b/LC/LCP015/cpp-LCP015/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(cpp_LCP15) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_LCP15 main3.cpp) \ No newline at end of file diff --git a/LC/LCP015/cpp-LCP015/main.cpp b/LC/LCP015/cpp-LCP015/main.cpp new file mode 100644 index 00000000..1a812fb5 --- /dev/null +++ b/LC/LCP015/cpp-LCP015/main.cpp @@ -0,0 +1,89 @@ +/// Source : https://leetcode-cn.com/problems/you-le-yuan-de-mi-gong/ +/// Author : liuyubobobo +/// Time : 2020-05-01 + +#include +#include +#include + +using namespace std; + + +/// Using Convex Hull +/// Time Complexity: O(n^2*logn) +/// Space Complexity: O(n) +class Solution { +public: + vector visitOrder(vector>& points, string direction) { + + int n = points.size(); + + map, int> pointsToIndex; + for(const vector& p: points) pointsToIndex[p] = pointsToIndex.size(); + + vector res = {pointsToIndex.begin()->second}; + int cur = res[0]; + for(char c: direction){ + vector hull = convex_hull(pointsToIndex, points); + pointsToIndex.erase(points[cur]); +// cout << "hull "; for(int i: hull) cout << i << " "; cout << endl; + int curpos; + for(curpos = 0; curpos < n; curpos ++) if(hull[curpos] == cur) break; + + if(c == 'L') cur = hull[(curpos + 1) % n]; + else cur = hull[(curpos - 1 + hull.size()) % hull.size()]; + + res.push_back(cur); + } + pointsToIndex.erase(points[cur]); + res.push_back(pointsToIndex.begin()->second); +// for(int i: res) cout << i << " "; cout << endl; + return res; + } + +private: + vector convex_hull(map, int>& pointsToIndex, const vector>& points){ + + vector res; + for(map, int>::iterator iter = pointsToIndex.begin(); + iter != pointsToIndex.end(); iter ++){ + + while(res.size() >= 2 && cross(points[res[res.size() - 2]], points[res.back()], iter->first) < 0) + res.pop_back(); + res.push_back(iter->second); + } + + map, int>::reverse_iterator riter = pointsToIndex.rbegin(); + for(riter ++; riter != pointsToIndex.rend(); riter ++){ + while(res.size() >= 2 && cross(points[res[res.size() - 2]], points[res.back()], riter->first) < 0) + res.pop_back(); + res.push_back(riter->second); + } + + res.pop_back(); + return res; + } + + int cross(const vector& p1, const vector& p2, const vector& p3){ + return (p2[0] - p1[0]) * (p3[1] - p2[1]) - (p3[0] - p2[0]) * (p2[1] - p1[1]); + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << " "; cout << endl; +} + +int main() { + + vector> points1 = {{1,1},{1,4},{3,2},{2,1}}; + print_vec(Solution().visitOrder(points1, "LL")); + + vector> points2 = {{1,3},{2,4},{3,3},{2,1}}; + print_vec(Solution().visitOrder(points2, "LR")); + + vector> points3 = {{3,5},{4,5},{9,1},{5,6}, {4, 2}}; + print_vec(Solution().visitOrder(points3, "RLR")); + + return 0; +} diff --git a/LC/LCP015/cpp-LCP015/main2.cpp b/LC/LCP015/cpp-LCP015/main2.cpp new file mode 100644 index 00000000..32b355de --- /dev/null +++ b/LC/LCP015/cpp-LCP015/main2.cpp @@ -0,0 +1,69 @@ +/// Source : https://leetcode-cn.com/problems/you-le-yuan-de-mi-gong/ +/// Author : liuyubobobo +/// Time : 2020-05-01 + +#include +#include +#include +#include + +using namespace std; + + +/// Polar Angle Sorting +/// Actucally same thoughts to Graham Scan +/// Time Complexity: O(n^2*logn) +/// Space Complexity: O(n) +class Solution { +public: + vector visitOrder(vector>& points, string direction) { + + map, int> pointsToIndex; + for(const vector& p: points) pointsToIndex[p] = pointsToIndex.size(); + + set> left(points.begin(), points.end()); + vector res; + int cur = pointsToIndex.begin()->second; + res.push_back(cur); + left.erase(points[cur]); + for(char c: direction){ + + vector> vec; + for(const vector& p: left) vec.push_back(p); + for(vector& p: vec) p[0] -= points[cur][0], p[1] -= points[cur][1]; + sort(vec.begin(), vec.end(), [](const vector& p1, const vector& p2){ + return p1[0] * (p2[1] - p1[1]) - p1[1] * (p2[0] - p1[0]) > 0; + }); + + if(c == 'L') + cur = pointsToIndex[{vec[0][0] + points[cur][0], vec[0][1] + points[cur][1]}]; + else + cur = pointsToIndex[{vec.back()[0] + points[cur][0], vec.back()[1] + points[cur][1]}]; + + res.push_back(cur); + left.erase(points[cur]); + } + res.push_back(pointsToIndex[*left.begin()]); +// for(int i: res) cout << i << " "; cout << endl; + return res; + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << " "; cout << endl; +} + +int main() { + + vector> points1 = {{1,1},{1,4},{3,2},{2,1}}; + print_vec(Solution().visitOrder(points1, "LL")); + + vector> points2 = {{1,3},{2,4},{3,3},{2,1}}; + print_vec(Solution().visitOrder(points2, "LR")); + + vector> points3 = {{3,5},{4,5},{9,1},{5,6}, {4, 2}}; + print_vec(Solution().visitOrder(points3, "RLR")); + + return 0; +} diff --git a/LC/LCP015/cpp-LCP015/main3.cpp b/LC/LCP015/cpp-LCP015/main3.cpp new file mode 100644 index 00000000..b3075df0 --- /dev/null +++ b/LC/LCP015/cpp-LCP015/main3.cpp @@ -0,0 +1,67 @@ +/// Source : https://leetcode-cn.com/problems/you-le-yuan-de-mi-gong/ +/// Author : liuyubobobo +/// Time : 2020-05-01 + +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { +public: + vector visitOrder(vector>& points, string direction) { + + int n = points.size(); + + int leftmost = 0; + for(int i = 0; i < n; i ++) + if(points[i][0] < points[leftmost][0] || + (points[i][0] == points[leftmost][0] && points[i][1] < points[leftmost][1])) + leftmost = i; + + vector res = {leftmost}; + vector used(n, false); + used[leftmost] = true; + + for(char c: direction){ + int p; + for(p = 0; p < n; p ++) if(!used[p]) break; + if(c == 'L'){ + for(int i = p + 1; i < n; i ++) + if(!used[i] && cross(points[res.back()], points[p], points[i]) < 0) + p = i; + } + else{ + for(int i = p + 1; i < n; i ++) + if(!used[i] && cross(points[res.back()], points[p], points[i]) > 0) + p = i; + } + res.push_back(p); + used[p] = true; + } + for(int i = 0; i < n; i ++) if(!used[i]){res.push_back(i); break;} + return res; + } + +private: + int cross(const vector& p1, const vector& p2, const vector& p3){ + return (p2[0] - p1[0]) * (p3[1] - p2[1]) - (p3[0] - p2[0]) * (p2[1] - p1[1]); + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << " "; cout << endl; +} + +int main() { + + vector> points1 = {{1,1},{1,4},{3,2},{2,1}}; + print_vec(Solution().visitOrder(points1, "LL")); + + return 0; +} diff --git a/LC/LCP016/cpp-LCP016/CMakeLists.txt b/LC/LCP016/cpp-LCP016/CMakeLists.txt new file mode 100644 index 00000000..015a1e0b --- /dev/null +++ b/LC/LCP016/cpp-LCP016/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) +project(cpp_LCP16) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_LCP16 main.cpp) \ No newline at end of file diff --git a/LC/LCP016/cpp-LCP016/main.cpp b/LC/LCP016/cpp-LCP016/main.cpp new file mode 100644 index 00000000..d4fcee11 --- /dev/null +++ b/LC/LCP016/cpp-LCP016/main.cpp @@ -0,0 +1,113 @@ +/// Source : https://leetcode-cn.com/problems/you-le-yuan-de-you-lan-ji-hua/ +/// Author : liuyubobobo +/// Time : 2020-05-04 + +#include +#include +#include + +using namespace std; + + +/// Greedy + Combining Algorithms +/// Time Complexity: O(V * E) +/// Space Complexity: O(V + E) +class Solution { + +private: + const int BACKUP_SZ = 3; + +public: + int maxWeight(vector>& edges, vector& value) { + + int n = value.size(); + int LIMIT = sqrt(n); + + vector> g(n); + for(const vector& e: edges) + g[e[0]].insert(e[1]), g[e[1]].insert(e[0]); + + sort(edges.begin(), edges.end(), [value](const vector& e1, const vector& e2){ + return value[e1[0]] + value[e1[1]] > value[e2[0]] + value[e2[1]]; + }); + + int res = 0; + for(int v = 0; v < n; v ++){ + + if(g[v].size() <= LIMIT){ + + vector> tedges; + for(int x: g[v]) + for(int y: g[v]) + if(x < y && g[x].count(y)) tedges.push_back({x, y}); + sort(tedges.begin(), tedges.end(), [value](const vector& e1, const vector& e2){ + return value[e1[0]] + value[e1[1]] > value[e2[0]] + value[e2[1]]; + }); + res = max(res, test(g, v, tedges, value)); + } + else{ + res = max(res, test(g, v, edges, value)); + } + } + return res; + } + +private: + int test(vector>& g, + int v, const vector>& edges, const vector& value){ + + vector> backup; + int res = 0, minIndex = -1; + for(const vector& e: edges) + if(g[v].count(e[0]) && g[v].count(e[1])){ + + res = max(res, value[v] + value[e[0]] + value[e[1]]); + + for(const vector& backupe: backup) + res = max(res, value[v] + calc(value, e[0], e[1], backupe[0], backupe[1])); + + if(backup.size() < BACKUP_SZ) backup.push_back(e); + else backup[minIndex] = e; + + minIndex = 0; + for(int i = 1; i < backup.size(); i ++) + if(value[backup[i][0]] + value[backup[i][1]] < value[backup[minIndex][0]] + value[backup[minIndex][1]]) + minIndex = i; + } + return res; + } + + int calc(const vector& value, int a, int b, int c, int d){ + + int res = value[a] + value[b]; + if(c != a && c != b) res += value[c]; + if(d != a && d != b) res += value[d]; + return res; + } +}; + + +int main() { + + vector> edges1 = {{0,1},{1,2},{0,2}}; + vector value1 = {1, 2, 3}; + cout << Solution().maxWeight(edges1, value1) << endl; + // 6 + + vector> edges2 = {{0,2},{2,1}}; + vector value2 = {1, 2, 5}; + cout << Solution().maxWeight(edges2, value2) << endl; + // 0 + + vector> edges3 = {{0,1},{0,2},{0,3},{0,4},{0,5},{1,3},{2,4},{2,5},{3,4},{3,5},{4,5}}; + vector value3 = {7,8,6,8,9,7}; + cout << Solution().maxWeight(edges3, value3) << endl; + // 39 + + vector> edges4 = {{0,1},{0,2},{0,3},{0,4},{0,5},{0,6},{0,7},{0,8},{0,9}}; + vector value4 = {4441,8166,4493,3043,7988,2504,2328,1730,8841,2613}; + cout << Solution().maxWeight(edges4, value4) << endl; + // 0 + + return 0; +} \ No newline at end of file diff --git a/LC/LCP017/cpp-LCP017/CMakeLists.txt b/LC/LCP017/cpp-LCP017/CMakeLists.txt new file mode 100644 index 00000000..d5d5e4ff --- /dev/null +++ b/LC/LCP017/cpp-LCP017/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/LC/LCP017/cpp-LCP017/main.cpp b/LC/LCP017/cpp-LCP017/main.cpp new file mode 100644 index 00000000..ccab67c0 --- /dev/null +++ b/LC/LCP017/cpp-LCP017/main.cpp @@ -0,0 +1,32 @@ +/// Source : https://leetcode-cn.com/problems/nGK0Fy/ +/// Author : liuyubobobo +/// Time : 2020-09-12 + +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int calculate(string s) { + + int x = 1, y = 0; + for(char c: s) + if(c == 'A') x = 2 * x + y; + else y = 2 * y + x; + return x + y; + } +}; + + +int main() { + + cout << Solution().calculate("AB") << endl; + // 4 + + return 0; +} diff --git a/LC/LCP018/cpp-LCP018/CMakeLists.txt b/LC/LCP018/cpp-LCP018/CMakeLists.txt new file mode 100644 index 00000000..81ad8b42 --- /dev/null +++ b/LC/LCP018/cpp-LCP018/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/LC/LCP018/cpp-LCP018/main.cpp b/LC/LCP018/cpp-LCP018/main.cpp new file mode 100644 index 00000000..f724f50a --- /dev/null +++ b/LC/LCP018/cpp-LCP018/main.cpp @@ -0,0 +1,49 @@ +/// Source : https://leetcode-cn.com/problems/2vYnGI/ +/// Author : liuyubobobo +/// Time : 2020-09-12 + +#include +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { + +private: + const int MOD = 1e9 + 7; +public: + int breakfastNumber(vector& staple, vector& drinks, int x) { + + sort(staple.begin(), staple.end()); + sort(drinks.begin(), drinks.end()); + + int res = 0; + for(int e: staple){ + vector::iterator iter = upper_bound(drinks.begin(), drinks.end(), x - e); + res += iter - drinks.begin(); + res %= MOD; + } + return res; + } +}; + + +int main() { + + vector staple1 = {10,20,5}; + vector drinks1 = {5, 5, 2}; + cout << Solution().breakfastNumber(staple1, drinks1, 15) << endl; + // 6 + + vector staple2 = {2, 1, 1}; + vector drinks2 = {8,9,5,1}; + cout << Solution().breakfastNumber(staple2, drinks2, 9) << endl; + // 8 + + return 0; +} diff --git a/LC/LCP019/cpp-LCP019/CMakeLists.txt b/LC/LCP019/cpp-LCP019/CMakeLists.txt new file mode 100644 index 00000000..80fb8c61 --- /dev/null +++ b/LC/LCP019/cpp-LCP019/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main2.cpp) \ No newline at end of file diff --git a/LC/LCP019/cpp-LCP019/main.cpp b/LC/LCP019/cpp-LCP019/main.cpp new file mode 100644 index 00000000..cbd7a46a --- /dev/null +++ b/LC/LCP019/cpp-LCP019/main.cpp @@ -0,0 +1,66 @@ +/// Source : https://leetcode-cn.com/problems/UlBDOe/ +/// Author : liuyubobobo +/// Time : 2020-09-12 + +#include +#include + +using namespace std; + + +/// DP - Memory Search +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +private: + int n; + const int INF = 1e9; + +public: + int minimumOperations(string leaves) { + + n = leaves.size(); + vector> dp(3, vector(n, -1)); + // 0: ryr, 1: yr, 2: r + return dfs(leaves, 0, 0, dp); + } + +private: + int dfs(const string& s, int mod, int index, vector>& dp){ + + if(index == n - 1){ + if(mod != 2) return INF; + return s[index] == 'r' ? 0 : 1; + } + if(dp[mod][index] != -1) return dp[mod][index]; + + int res = 0; + if(mod == 0){ + int op = s[index] == 'r' ? 0 : 1; + res = op + dfs(s, 0, index + 1, dp); + res = min(res, op + dfs(s, 1, index + 1, dp)); + } + else if(mod == 1){ + int op = s[index] == 'r' ? 1 : 0; + res = op + dfs(s, 1, index + 1, dp); + res = min(res, op + dfs(s, 2, index + 1, dp)); + } + else{ + int op = s[index] == 'r' ? 0 : 1; + res = op + dfs(s, 2, index + 1, dp); + } + return dp[mod][index] = res; + } +}; + +int main() { + + cout << Solution().minimumOperations("rrryyyrryyyrr") << endl; + // 2 + + cout << Solution().minimumOperations("ryr") << endl; + // 0 + + return 0; +} diff --git a/LC/LCP019/cpp-LCP019/main2.cpp b/LC/LCP019/cpp-LCP019/main2.cpp new file mode 100644 index 00000000..1755ba16 --- /dev/null +++ b/LC/LCP019/cpp-LCP019/main2.cpp @@ -0,0 +1,51 @@ +/// Source : https://leetcode-cn.com/problems/UlBDOe/ +/// Author : liuyubobobo +/// Time : 2021-02-05 + +#include +#include + +using namespace std; + + +/// DP +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +public: + int minimumOperations(string leaves) { + + int n = leaves.size(); + vector> dp(3, vector(n)); + + // r + dp[0][0] = (leaves[0] != 'r'); + for(int i = 1; i < n; i ++) + dp[0][i] = dp[0][i - 1] + (leaves[i] != 'r'); + + // ry + dp[1][1] = (leaves[1] != 'y') + dp[0][0]; + for(int i = 2; i < n; i ++) + dp[1][i] = (leaves[i] != 'y') + min(dp[1][i - 1], dp[0][i - 1]); + + // ryr + dp[2][2] = (leaves[2] != 'r') + dp[1][1]; + for(int i = 3; i < n; i ++) + dp[2][i] = (leaves[i] != 'r') + min(dp[2][i - 1], dp[1][i - 1]); + + return dp[2].back(); + } +}; + + +int main() { + + cout << Solution().minimumOperations("rrryyyrryyyrr") << endl; + // 2 + + cout << Solution().minimumOperations("ryr") << endl; + // 0 + + return 0; +} diff --git a/LC/LCP020/cpp-LCP020/CMakeLists.txt b/LC/LCP020/cpp-LCP020/CMakeLists.txt new file mode 100644 index 00000000..74cc3ee6 --- /dev/null +++ b/LC/LCP020/cpp-LCP020/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) \ No newline at end of file diff --git a/LC/LCP020/cpp-LCP020/main.cpp b/LC/LCP020/cpp-LCP020/main.cpp new file mode 100644 index 00000000..57a8160e --- /dev/null +++ b/LC/LCP020/cpp-LCP020/main.cpp @@ -0,0 +1,65 @@ +/// Source : https://leetcode-cn.com/problems/meChtZ/ +/// Author : liuyubobobo +/// Time : 2020-09-12 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// Memory Search +/// Time Complexity: O(target) +/// Space Complexity: O(target) +class Solution { + +private: + long long MOD = 1e9 + 7; + +public: + int busRapidTransit(int target, int inc, int dec, vector& jump, vector& cost) { + + unordered_map dp; + return dfs(target, inc, dec, jump, cost, dp) % MOD; + } + +private: + long long dfs(int target, int inc, int dec, const vector& jump, const vector& cost, + unordered_map& dp){ + +// cout << target << endl; + if(dp.count(target)) return dp[target]; + + if(target == 0) return dp[target] = 0ll; + if(target == 1) return dp[target] = (long long)inc; + + long long res = (long long)target * inc; + for(int i = 0; i < jump.size(); i ++){ + res = min(res, dfs(target / jump[i], inc, dec, jump, cost, dp) + (long long)cost[i] + (long long)(target % jump[i]) * inc); + if(target > 1 && target % jump[i]) + res = min(res, dfs(target / jump[i] + 1, inc, dec, jump, cost, dp) + (long long)cost[i] + ((long long)(target / jump[i] + 1) * jump[i] - target) * dec); + } + return dp[target] = res; + } +}; + + +int main() { + + vector jump1 = {6}, cost1 = {10}; + cout << Solution().busRapidTransit(31, 5, 3, jump1, cost1) << endl; + // 33 + + vector jump2 = {3,6,8,11,5,10,4}, cost2 = {4,7,6,3,7,6,4}; + cout << Solution().busRapidTransit(612, 4, 5, jump2, cost2) << endl; + // 26 + + vector jump3 = {2}, cost3 = {1000000}; + cout << Solution().busRapidTransit(1000000000, 1, 1, jump3, cost3) << endl; + // 10953125 + + return 0; +} diff --git a/LC/LCP021/cpp-LCP021/CMakeLists.txt b/LC/LCP021/cpp-LCP021/CMakeLists.txt new file mode 100644 index 00000000..c56d6298 --- /dev/null +++ b/LC/LCP021/cpp-LCP021/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(cpp_LCP21) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(cpp_LCP21 main.cpp) \ No newline at end of file diff --git a/LC/LCP021/cpp-LCP021/main.cpp b/LC/LCP021/cpp-LCP021/main.cpp new file mode 100644 index 00000000..1a4e8432 --- /dev/null +++ b/LC/LCP021/cpp-LCP021/main.cpp @@ -0,0 +1,156 @@ +/// Source : https://leetcode-cn.com/problems/Za25hA/ +/// Author : liuyubobobo +/// Time : 2021-02-06 + +#include +#include +#include +#include + +using namespace std; + + +/// Loop finding and BFS +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +public: + int chaseGame(vector>& edges, int startA, int startB) { + + int n = edges.size(); + vector> g(n); + for(vector& e: edges){ + e[0] --, e[1] --; + g[e[0]].insert(e[1]); + g[e[1]].insert(e[0]); + } + startA --, startB --; + + for(int next: g[startA]) + if(next == startB) return 1; + + int circle_len = 0; + vector in_circle = get_circle(g, circle_len); +// for(int e: in_circle) cout << e << " "; cout << endl; + assert(circle_len >= 3); + if(circle_len >= 4 & in_circle[startB]) return -1; + + int bestInCircleB = -1, bestInCircleBDis = -1; + bfs(g, in_circle, startB, bestInCircleB, bestInCircleBDis); + assert(bestInCircleB != -1 && bestInCircleBDis != -1); + + vector disA = bfs(g, startA); + if(circle_len >= 4 && disA[bestInCircleB] > bestInCircleBDis + 1) return -1; + + vector disB = bfs(g, startB); + int res = INT_MIN; + for(int end = 0; end < g.size(); end ++) + if(g[end].size() == 1 && disA[end] > disB[end] + 1) + res = max(res, disA[end]); + return res; + } + +private: + vector bfs(const vector>& g, int s){ + + vector dis(g.size(), -1); + dis[s] = 0; + queue q; + q.push(s); + while(!q.empty()){ + int u = q.front(); + q.pop(); + + for(int v: g.at(u)) + if(dis[v] == -1){ + dis[v] = dis[u] + 1; + q.push(v); + } + } + return dis; + } + + void bfs(const vector>& g, const vector& in_circle, int s, + int& t, int& d){ + + vector dis(g.size(), -1); + dis[s] = 0; + queue q; + q.push(s); + while(!q.empty()){ + int u = q.front(); + q.pop(); + + if(in_circle[u]){ + t = u, d = dis[u]; + return; + } + + for(int v: g.at(u)) + if(dis[v] == -1){ + dis[v] = dis[u] + 1; + q.push(v); + } + } + assert(false); + return; + } + + vector get_circle(const vector>& g, int& circle_len){ + + vector pre(g.size(), -1); + int start = -1; + assert(dfs(g, 0, 0, pre, start)); + + vector in_circle(g.size(), false); + in_circle[start] = true; + int cur = pre[start]; + circle_len ++; + while(cur != start){ + in_circle[cur] = true; + cur = pre[cur]; + circle_len ++; + } + return in_circle; + } + + bool dfs(const vector>& g, int u, int p, vector& pre, int& start){ + + pre[u] = p; + for(int v: g.at(u)) + if(v != p){ + if(pre[v] == -1){ + if(dfs(g, v, u, pre, start)) return true; + } + else{ + pre[v] = u; + start = v; + return true; + } + } + return false; + } +}; + + +int main() { + + vector> edges1 = {{1,2},{2,3},{3,4},{4,1},{2,5},{5,6}}; + cout << Solution().chaseGame(edges1, 3, 5) << endl; + // 3 + + vector> edges2 = {{1,2},{2,3},{3,4},{4,1}}; + cout << Solution().chaseGame(edges2, 1, 3) << endl; + // -1 + + vector> edges3 = {{1,2},{2,3},{3,1},{3,6},{2,4},{4,5},{5,8},{4,7}}; + cout << Solution().chaseGame(edges3, 8, 7) << endl; + // 3 + + vector> edges4 = {{1,2},{2,3},{3,1},{3,6},{2,4},{4,5},{5,8},{4,7},{8,9}}; + cout << Solution().chaseGame(edges4, 9, 7) << endl; + // 6 + + return 0; +} diff --git a/LC/LCP022/cpp-LCP022/CMakeLists.txt b/LC/LCP022/cpp-LCP022/CMakeLists.txt new file mode 100644 index 00000000..ec9e7c4c --- /dev/null +++ b/LC/LCP022/cpp-LCP022/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main2.cpp) \ No newline at end of file diff --git a/LC/LCP022/cpp-LCP022/main.cpp b/LC/LCP022/cpp-LCP022/main.cpp new file mode 100644 index 00000000..f6149221 --- /dev/null +++ b/LC/LCP022/cpp-LCP022/main.cpp @@ -0,0 +1,76 @@ +/// Source : https://leetcode-cn.com/problems/ccw6C7/ +/// Author : liuyubobobo +/// Time : 2020-09-13 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(4^n * n^2) +/// Space Complexity: O(n^2) +class Solution { +public: + int paintingPlan(int n, int k) { + + if(n * n == k || n * n == 0) return 1; + + int res = 0; + for(int x = 0; x < (1 << n); x ++) + for(int y = 0; y < (1 << n); y ++) + if(paint(n, x, y) == k){ +// cout << x << " " << y << endl; + res ++; + } + return res; + } + +private: + int paint(int n, int x, int y){ + + vector> g(n, vector(n, 0)); + + int r = 0; + while(x){ + if(x & 1){ + for(int j = 0; j < n; j ++) + g[r][j] = 1; + } + x >>= 1; + r ++; + } + + int c = 0; + while(y){ + if(y & 1){ + for(int i = 0; i < n; i ++) + g[i][c] = 1; + } + y >>= 1; + c ++; + } + + int res = 0; + for(int i = 0; i < n; i ++) + for(int j = 0; j < n; j ++) + res += g[i][j]; + return res; + } +}; + + +int main() { + + cout << Solution().paintingPlan(2, 2) << endl; + // 4 + + cout << Solution().paintingPlan(2, 1) << endl; + // 0 + + cout << Solution().paintingPlan(2, 4) << endl; + // 1 + + return 0; +} diff --git a/LC/LCP022/cpp-LCP022/main2.cpp b/LC/LCP022/cpp-LCP022/main2.cpp new file mode 100644 index 00000000..21f2800d --- /dev/null +++ b/LC/LCP022/cpp-LCP022/main2.cpp @@ -0,0 +1,58 @@ +/// Source : https://leetcode-cn.com/problems/ccw6C7/ +/// Author : liuyubobobo +/// Time : 2020-09-20 + +#include +#include + +using namespace std; + + +/// Brute Force and Combination +/// Time Complexity: O(n^2) +/// Space Complexity: O(n^2) +class Solution { + +private: + vector> c; + +public: + int paintingPlan(int n, int k) { + + if(n * n == k) return 1; + + c = vector>(7, vector(7, -1)); + + int res = 0; + for(int i = 0; i <= n; i ++) + for(int j = 0; j <= n; j ++){ + int cnt = i * n + j * n - i * j; + if(cnt == k) + res += C(n, i) * C(n, j); + } + return res; + } + +private: + int C(int n, int k){ + + if(k == 0 || n == k) return 1; + if(c[n][k] != -1) return c[n][k]; + return c[n][k] = C(n - 1, k - 1) + C(n - 1, k); + } +}; + + +int main() { + + cout << Solution().paintingPlan(2, 2) << endl; + // 4 + + cout << Solution().paintingPlan(2, 1) << endl; + // 0 + + cout << Solution().paintingPlan(2, 4) << endl; + // 1 + + return 0; +} diff --git a/LC/LCP023/cpp-LCP023/CMakeLists.txt b/LC/LCP023/cpp-LCP023/CMakeLists.txt new file mode 100644 index 00000000..81ad8b42 --- /dev/null +++ b/LC/LCP023/cpp-LCP023/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/LC/LCP023/cpp-LCP023/main.cpp b/LC/LCP023/cpp-LCP023/main.cpp new file mode 100644 index 00000000..b94a3b58 --- /dev/null +++ b/LC/LCP023/cpp-LCP023/main.cpp @@ -0,0 +1,67 @@ +/// Source : https://leetcode.com/problems/two-sum/description/ +/// Author : liuyubobobo +/// Time : 2020-09-21 + +#include +#include + +using namespace std; + + +/// Greedy + Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + bool isMagic(vector& target) { + + int n = target.size(); + + vector data; + for(int i = 2; i <= n; i += 2) data.push_back(i); + for(int i = 1; i <= n; i += 2) data.push_back(i); + + int k = 0; + for(int i = 0; i < target.size() && target[i] == data[i]; i ++) k ++; + if(k == 0) return false; + + data = shuffle(target.size(), k); + return data == target; + } + +private: + vector shuffle(int n, int k){ + + vector data(n); + for(int i = 1; i <= n; i ++) data[i - 1] = i; + + vector res; + while(data.size()){ + vector t; + for(int i = 1; i < data.size(); i += 2) t.push_back(data[i]); + for(int i = 0; i < data.size(); i += 2) t.push_back(data[i]); + + reverse(t.begin(), t.end()); + for(int i = 0; i < k && t.size(); i ++) + res.push_back(t.back()), t.pop_back(); + reverse(t.begin(), t.end()); + + data = t; + } + return res; + } +}; + + +int main() { + + vector target1 = {2, 4, 3, 1, 5}; + cout << Solution().isMagic(target1) << endl; + // 1 + + vector target2 = {5, 4, 3, 2, 1}; + cout << Solution().isMagic(target2) << endl; + // 0 + + return 0; +} diff --git a/LC/LCP024/cpp-LCP024/CMakeLists.txt b/LC/LCP024/cpp-LCP024/CMakeLists.txt new file mode 100644 index 00000000..ce73aee9 --- /dev/null +++ b/LC/LCP024/cpp-LCP024/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/LC/LCP024/cpp-LCP024/main.cpp b/LC/LCP024/cpp-LCP024/main.cpp new file mode 100644 index 00000000..05ed4300 --- /dev/null +++ b/LC/LCP024/cpp-LCP024/main.cpp @@ -0,0 +1,76 @@ +/// Source : https://leetcode-cn.com/problems/5TxKeK/ +/// Author : liuyubobobo +/// Time : 2020-09-21 + +#include +#include +#include + +using namespace std; + + +/// Two heaps to maintain the median +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { + +private: + long long MOD = 1e9 + 7; + +public: + vector numsGame(vector& nums) { + + for(int i = 0; i < nums.size(); i ++) nums[i] -= i; + vector res = {0}; + + priority_queue leftheap; // left is max heap + priority_queue, greater> rightheap; // right is min heap + leftheap.push(nums[0]); + + long long leftsum = nums[0], rightsum = 0; + for(int i = 1; i < nums.size(); i ++){ + + leftheap.push(nums[i]); leftsum += nums[i]; + if(leftheap.size() - rightheap.size() == 2){ + int x = leftheap.top(); + leftheap.pop(); leftsum -= x; + rightheap.push(x); rightsum += x; + } + if(leftheap.top() > rightheap.top()){ + int x = leftheap.top(); leftheap.pop(); leftsum -= x; + int y = rightheap.top(); rightheap.pop(); rightsum -= y; + leftheap.push(y); leftsum += y; + rightheap.push(x); rightsum += x; + } + + long long cur_m = leftheap.top(); + long long op = 0ll; + op += cur_m * leftheap.size() - leftsum; + op += rightsum - cur_m * rightheap.size(); + res.push_back(op % MOD); + } + return res; + } +}; + + +void print_vec(const vector& vec){ + for(int e: vec) cout << e << " "; cout << endl; +} + +int main() { + + vector nums1 = {3,4,5,1,6,7}; + print_vec(Solution().numsGame(nums1)); + // 0 0 0 5 6 7 + + vector nums2 = {1,2,3,4,5}; + print_vec(Solution().numsGame(nums2)); + // 0 0 0 0 0 + + vector nums3 = {1,1,1,2,3,4}; + print_vec(Solution().numsGame(nums3)); + // 0 1 2 3 3 3 + + return 0; +} diff --git a/LC/LCP025/cpp-LCP025/CMakeLists.txt b/LC/LCP025/cpp-LCP025/CMakeLists.txt new file mode 100644 index 00000000..a373769d --- /dev/null +++ b/LC/LCP025/cpp-LCP025/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main2.cpp) \ No newline at end of file diff --git a/LC/LCP025/cpp-LCP025/main.cpp b/LC/LCP025/cpp-LCP025/main.cpp new file mode 100644 index 00000000..dfaf4bd8 --- /dev/null +++ b/LC/LCP025/cpp-LCP025/main.cpp @@ -0,0 +1,73 @@ +/// Source : https://leetcode-cn.com/problems/Uh984O/ +/// Author : liuyubobobo +/// Time : 2020-09-21 + +#include +#include +#include + +using namespace std; + + +/// Memory Search +/// State: dp[27][27][27][27][27] +/// Time Complexity: O(27**k) +/// Space Complexity: O(27**k) +class Solution { + +private: + long long MOD = 1e9 + 7; + +public: + int keyboard(int k, int n) { + + vector cnt(5, 0); + cnt[k - 1] = 26; + + unordered_map dp; + return dfs(n, cnt[0], cnt[1], cnt[2], cnt[3], cnt[4], dp); + } + + long long dfs(int n, int p1, int p2, int p3, int p4, int p5, + unordered_map& dp){ + + if(n == 0) return 1; + + int hash = (((p1 * 27 + p2) * 27 + p3) * 27 + p4) * 27 + p5; + if(dp.count(hash)) return dp[hash]; + +// cout << n << " " << p1 << " " << p2 << " " << p3 << " " << p4 << " " << p5 << endl; + + long long res = 0ll; + if(p1) res += dfs(n - 1, p1 - 1, p2, p3, p4, p5, dp) * p1, res %= MOD; + if(p2) res += dfs(n - 1, p1 + 1, p2 - 1, p3, p4, p5, dp) * p2, res %= MOD; + if(p3) res += dfs(n - 1, p1, p2 + 1, p3 - 1, p4, p5, dp) * p3, res %= MOD; + if(p4) res += dfs(n - 1, p1, p2, p3 + 1, p4 - 1, p5, dp) * p4, res %= MOD; + if(p5) res += dfs(n - 1, p1, p2, p3, p4 + 1, p5 - 1, dp) * p5, res %= MOD; + return dp[hash] = res; + } +}; + + +int main() { + + cout << Solution().keyboard(1, 1) << endl; + // 26 + + cout << Solution().keyboard(1, 2) << endl; + // 650 + + cout << Solution().keyboard(1, 26) << endl; + // 459042011 + + cout << Solution().keyboard(2, 1) << endl; + // 26 + + cout << Solution().keyboard(2, 2) << endl; + // 676 + + cout << Solution().keyboard(5, 50) << endl; + // 363766962 + + return 0; +} diff --git a/LC/LCP025/cpp-LCP025/main2.cpp b/LC/LCP025/cpp-LCP025/main2.cpp new file mode 100644 index 00000000..c910df04 --- /dev/null +++ b/LC/LCP025/cpp-LCP025/main2.cpp @@ -0,0 +1,73 @@ +/// Source : https://leetcode-cn.com/problems/Uh984O/ +/// Author : liuyubobobo +/// Time : 2020-09-21 + +#include +#include + +using namespace std; + + +/// Memory Search +/// State: dp[27][n] +/// Time Complexity: O(27kn) +/// Space Complexity: O(27n) +class Solution { + +private: + long long MOD = 1e9 + 7; + vector> comb; + +public: + int keyboard(int k, int n) { + + comb = vector>(200, vector(200, -1)); + + vector> dp(27, vector(n + 1, -1)); + return dfs(26, n, k, dp); + } + + long long dfs(int index, int n, int k, vector>& dp){ + + if(index == 0) return n == 0 ? 1 : 0; + if(n == 0) return 1; + if(dp[index][n] != -1) return dp[index][n]; + + long long res = 0ll; + for(int p = 0; p <= k && p <= n; p ++) + res += dfs(index - 1, n - p, k, dp) * C(n, p), res %= MOD; + return dp[index][n] = res; + } + + long long C(int n, int k){ + + if(n == k || k == 0) return 1ll; + if(comb[n][k] != -1) return comb[n][k]; + + return comb[n][k] = (C(n - 1, k) + C(n - 1, k - 1)) % MOD; + } +}; + + +int main() { + + cout << Solution().keyboard(1, 1) << endl; + // 26 + + cout << Solution().keyboard(1, 2) << endl; + // 650 + + cout << Solution().keyboard(1, 26) << endl; + // 459042011 + + cout << Solution().keyboard(2, 1) << endl; + // 26 + + cout << Solution().keyboard(2, 2) << endl; + // 676 + + cout << Solution().keyboard(5, 50) << endl; + // 363766962 + + return 0; +} diff --git a/LC/LCP028/cpp-LCP028/CMakeLists.txt b/LC/LCP028/cpp-LCP028/CMakeLists.txt new file mode 100644 index 00000000..d5d5e4ff --- /dev/null +++ b/LC/LCP028/cpp-LCP028/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/LC/LCP028/cpp-LCP028/main.cpp b/LC/LCP028/cpp-LCP028/main.cpp new file mode 100644 index 00000000..78c49120 --- /dev/null +++ b/LC/LCP028/cpp-LCP028/main.cpp @@ -0,0 +1,49 @@ +/// Source : https://leetcode-cn.com/problems/4xy4Wx/ +/// Author : liuyubobobo +/// Time : 2021-04-04 + +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { + +private: + const long long MOD = 1e9 + 7; + +public: + int purchasePlans(vector& nums, int target) { + + sort(nums.begin(), nums.end()); + long long res = 0ll; + for(int i = 0; i < nums.size(); i ++){ + + vector::iterator iter = upper_bound(nums.begin(), nums.end(), target - nums[i]); + if(iter == nums.begin()) continue; + + iter --; + if(iter - nums.begin() > i) + res += (iter - nums.begin()) - i; + } + return res % MOD; + } +}; + + +int main() { + + vector nums1 = {2, 5, 3, 5}; + cout << Solution().purchasePlans(nums1, 6) << endl; + // 1 + + vector nums2 = {2, 2, 1, 9}; + cout << Solution().purchasePlans(nums2, 10) << endl; + // 4 + + return 0; +} diff --git a/LC/LCP029/cpp-LCP029/CMakeLists.txt b/LC/LCP029/cpp-LCP029/CMakeLists.txt new file mode 100644 index 00000000..81ad8b42 --- /dev/null +++ b/LC/LCP029/cpp-LCP029/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/LC/LCP029/cpp-LCP029/main.cpp b/LC/LCP029/cpp-LCP029/main.cpp new file mode 100644 index 00000000..8f4e9fab --- /dev/null +++ b/LC/LCP029/cpp-LCP029/main.cpp @@ -0,0 +1,82 @@ +/// Source : https://leetcode-cn.com/problems/SNJvJP/ +/// Author : liuyubobobo +/// Time : 2021-04-04 + +#include +#include +#include + +using namespace std; + + +/// Mathematics +/// Time Complexity: O(1) +/// Space Complexity: O(1) +class Solution { +public: + int orchestraLayout(int num, int xPos, int yPos) { + + if(num % 2 && xPos == num / 2 && yPos == num / 2){ + int res = num % 9 * num % 9 % 9; + if(res == 0) res = 9; + return res; + } + + int top = xPos, bottom = num - xPos - 1, left = yPos, right = num - yPos - 1; + int side = min(min(top, bottom), min(left, right)); + + int total = (long long)(num - side) * 4ll * (long long)side % 9ll; + + xPos -= side, yPos -= side; + int edge = num - side * 2; + + if(xPos == 0){ + int res = (total + yPos + 1) % 9; + if(res == 0) res = 9; + return res; + } + + if(yPos == num - 2 * side - 1){ + int res = ((total + edge) % 9 + xPos) % 9; + if(res == 0) res = 9; + return res; + } + + if(xPos == num - 2 * side - 1){ + int res = (total + edge) % 9; + res = (res + edge - 1) % 9; + res = (res + edge - 1 - yPos) % 9; + if(res == 0) res = 9; + return res; + } + + assert(yPos == 0); + int res = (total + edge) % 9; + res = (res + edge - 1) % 9; + res = (res + edge - 1) % 9; + res = (res + edge - 1 - xPos) % 9; + if(res == 0) res = 9; + return res; + } +}; + + +int main() { + + cout << Solution().orchestraLayout(3, 0, 2) << endl; + // 3 + + cout << Solution().orchestraLayout(4, 1, 2) << endl; + // 5 + + cout << Solution().orchestraLayout(7, 1, 1) << endl; + // 7 + + int side = 7; + for(int i = 0; i < side; i ++){ + for(int j = 0; j < side; j ++) + cout << Solution().orchestraLayout(side, i, j) << " "; + cout << endl; + } + return 0; +} diff --git a/LC/LCP039/cpp-LCP039/CMakeLists.txt b/LC/LCP039/cpp-LCP039/CMakeLists.txt new file mode 100644 index 00000000..2ae8397c --- /dev/null +++ b/LC/LCP039/cpp-LCP039/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/LC/LCP039/cpp-LCP039/main.cpp b/LC/LCP039/cpp-LCP039/main.cpp new file mode 100644 index 00000000..e047f1d5 --- /dev/null +++ b/LC/LCP039/cpp-LCP039/main.cpp @@ -0,0 +1,44 @@ +/// Source : https://leetcode-cn.com/problems/0jQkd0/ +/// Author : liuyubobobo +/// Time : 2021-09-10 + +#include +#include + +using namespace std; + + +/// Using Hash Map +/// Time Complexity: O(n) +/// Space Complexity: O(max_num) +class Solution { +public: + int minimumSwitchingTimes(vector>& source, vector>& target) { + + vector f1(10001, 0), f2(10001, 0); + for(int i = 0; i < source.size(); i ++) + for(int j = 0; j < source[i].size(); j ++){ + f1[source[i][j]] ++; + f2[target[i][j]] ++; + } + + int res = 0; + for(int i = 0; i < f1.size(); i ++) + res += abs(f1[i] - f2[i]); + return res / 2 + res % 2; + } +}; + + +int main() { + + vector> source1 = {{1, 3}, {5, 4}}, target1 = {{3, 1}, {6, 5}}; + cout << Solution().minimumSwitchingTimes(source1, target1) << endl; + // 1 + + vector> source2 = {{1, 2, 3}, {3, 4, 5}}, target2 = {{1, 3, 5}, {2, 3, 4}}; + cout << Solution().minimumSwitchingTimes(source2, target2) << endl; + // 0 + + return 0; +} diff --git a/LC/LCP040/cpp-LCP040/CMakeLists.txt b/LC/LCP040/cpp-LCP040/CMakeLists.txt new file mode 100644 index 00000000..3f98647f --- /dev/null +++ b/LC/LCP040/cpp-LCP040/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/LC/LCP040/cpp-LCP040/main.cpp b/LC/LCP040/cpp-LCP040/main.cpp new file mode 100644 index 00000000..ca0ed8b6 --- /dev/null +++ b/LC/LCP040/cpp-LCP040/main.cpp @@ -0,0 +1,57 @@ +/// Source : https://leetcode-cn.com/problems/uOAnQW/ +/// Author : liuyubobobo +/// Time : 2021-09-10 + +#include +#include + +using namespace std; + + +/// Greedy + Presum +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + int maxmiumScore(vector& cards, int cnt) { + + vector odd, even; + for(int e: cards) + if(e % 2) odd.push_back(e); + else even.push_back(e); + + sort(odd.begin(), odd.end(), greater()); + sort(even.begin(), even.end(), greater()); + + int oddn = odd.size(); + vector presum1(oddn + 1, 0); + for(int i = 0; i < oddn; i ++) presum1[i + 1] = presum1[i] + odd[i]; + + int evenn = even.size(); + vector presum2(evenn + 1, 0); + for(int i = 0; i < evenn; i ++) presum2[i + 1] = presum2[i] + even[i]; + + int res = 0; + for(int oddnum = 0; oddnum <= oddn && oddnum <= cnt; oddnum += 2){ + int evennum = cnt - oddnum; + if(evennum > evenn) continue; + + res = max(res, presum1[oddnum] + presum2[evennum]); + } + return res; + } +}; + + +int main() { + + vector cards1 = {1, 2, 8, 9}; + cout << Solution().maxmiumScore(cards1, 3) << endl; + // 18 + + vector cards2 = {3, 3, 1}; + cout << Solution().maxmiumScore(cards2, 1) << endl; + // 0 + + return 0; +} diff --git a/LC/LCP041/cpp-LCP041/CMakeLists.txt b/LC/LCP041/cpp-LCP041/CMakeLists.txt new file mode 100644 index 00000000..cad75f71 --- /dev/null +++ b/LC/LCP041/cpp-LCP041/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/LC/LCP041/cpp-LCP041/main.cpp b/LC/LCP041/cpp-LCP041/main.cpp new file mode 100644 index 00000000..ee3796c5 --- /dev/null +++ b/LC/LCP041/cpp-LCP041/main.cpp @@ -0,0 +1,97 @@ +/// Source : https://leetcode-cn.com/problems/fHi6rV/ +/// Author : liuyubobobo +/// Time : 2021-09-10 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O((R * C)^3) +/// Space Complexity: O(R * C) +class Solution { + +private: + int R, C; + const int dirs[8][2] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}, {1, 1}, {-1, -1}, {1, -1}, {-1, 1}}; + +public: + int flipChess(vector& chessboard) { + + R = chessboard.size(), C = chessboard[0].size(); + + int res = 0; + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++) + if(chessboard[i][j] == '.'){ + vector t = chessboard; + t[i][j] = 'X'; + vector> visited(R, vector(C, false)); + visited[i][j] = true; + res = max(res, check(t, i, j, visited)); + } + return res; + } + +private: + int check(vector& board, int x, int y, vector>& visited){ + + vector> next; + + int res = 0; + for(int d = 0; d < 8; d ++){ + + int cx = x + dirs[d][0], cy = y + dirs[d][1], t = 0; + while(in_area(cx, cy) && board[cx][cy] != 'X') + cx += dirs[d][0], cy += dirs[d][1], t ++; + + if(in_area(cx, cy) && board[cx][cy] == 'X'){ + int tx = x + dirs[d][0], ty = y + dirs[d][1]; + vector> tnext; + while(tx != cx || ty != cy){ + if(board[tx][ty] != 'O') break; + tnext.push_back({tx, ty}); + tx += dirs[d][0], ty += dirs[d][1]; + } + if(tx == cx && ty == cy){ + res += t; + for(const pair& p: tnext){ + if(!visited[p.first][p.second]){ + visited[p.first][p.second] = true; + next.push_back(p); + } + board[p.first][p.second] = 'X'; + } + } + } + } + + for(const pair& p: next) + res += check(board, p.first, p.second, visited); + return res; + } + + bool in_area(int x, int y){ + return 0 <= x && x < R && 0 <= y && y < C; + } +}; + + +int main() { + + vector chessboard1 = {"....X.","....X.","XOOO..","......","......"}; + cout << Solution().flipChess(chessboard1) << endl; + // 3 + + vector chessboard2 = {".X.",".O.","XO."}; + cout << Solution().flipChess(chessboard2) << endl; + // 2 + + vector chessboard3 = {".......",".......",".......","X......",".O.....","..O....","....OOX"}; + cout << Solution().flipChess(chessboard3) << endl; + // 4 + + return 0; +} diff --git a/LC/LCP042/cpp-LCP042/CMakeLists.txt b/LC/LCP042/cpp-LCP042/CMakeLists.txt new file mode 100644 index 00000000..a0d16fe6 --- /dev/null +++ b/LC/LCP042/cpp-LCP042/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) diff --git a/LC/LCP042/cpp-LCP042/main.cpp b/LC/LCP042/cpp-LCP042/main.cpp new file mode 100644 index 00000000..399c90a7 --- /dev/null +++ b/LC/LCP042/cpp-LCP042/main.cpp @@ -0,0 +1,118 @@ +/// Source : https://leetcode-cn.com/problems/vFjcfV/ +/// Author : liuyubobobo +/// Time : 2021-09-10 + +#include +#include +#include + +using namespace std; + + +/// KDTree +/// Time Complexity: O((n + m) logn) +/// Space Complexity: O(n) +class KDTree{ + +private: + class Node{ + public: + vector v; + int k; + Node *left, *right; + + Node(const vector& v, int k): v(v), k(k), left(nullptr), right(nullptr){} + }; + + const int K; + Node* root; + +public: + KDTree(int K) : K(K), root(nullptr){}; + + void add(const vector& data){ + assert(data.size() == K); + root = add(root, data, 0); + } + + bool query(const vector& l, const vector& r, + long long x, long long y, long long w){ + assert(l.size() == K); + assert(r.size() == K); + + return query(root, 0, l, r, x, y, w); + } + +private: + bool query(Node* node, int k, const vector& l, const vector& r, + long long x, long long y, long long w){ + + if(node == nullptr) return false; + + int in = in_range(node->v, l, r); + if(in == K && (node->v[0] - x) * (node->v[0] - x) + (node->v[1] - y) * (node->v[1] - y) <= w * w) + return true; + + long long p = node->v[k]; + if(r[k] <= p) return query(node->left, (k + 1) % K, l, r, x, y, w); + else if(l[k] > p) return query(node->right, (k + 1) % K, l, r, x, y, w); + else{ + return query(node->left, (k + 1) % K, l, r, x, y, w) || + query(node->right, (k + 1) % K, l, r, x, y, w); + } + } + + int in_range(const vector& data, const vector& l, const vector& r){ + + int in = 0; + for(int i = 0; i < K; i ++) + in += l[i] <= data[i] && data[i] <= r[i]; + return in; + } + + Node* add(Node* node, const vector& data, int k){ + + if(node == nullptr) return new Node(data, k); + + long long p = node->v[k]; + if(data[k] <= p) node->left = add(node->left, data, (k + 1) % K); + else node->right = add(node->right, data, (k + 1) % K); + return node; + } +}; + +class Solution { +public: + int circleGame(vector>& toys, vector>& circles, int r) { + + shuffle(circles.begin(), circles.end(), default_random_engine()); + + KDTree kdtree(2); + for(const vector& point: circles) + kdtree.add({point[0], point[1]}); + + int res = 0; + for(const vector& toy: toys){ + long long x = toy[0], y = toy[1], w = r - toy[2]; + if(w < 0) continue; + + if(kdtree.query({x - w, y - w}, {x + w, y + w}, x, y, w)) + res ++; + } + return res; + } +}; + + +int main() { + + vector> toys1 = {{3, 3, 1}, {3, 2, 1}}, circles1 = {{4, 3}}; + cout << Solution().circleGame(toys1, circles1, 2) << endl; + // 1 + + vector> toys2 = {{1, 3, 2}, {4, 3, 1}, {7, 1, 2}}, circles2 = {{1, 0}, {3, 3}}; + cout << Solution().circleGame(toys2, circles2, 4) << endl; + // 2 + + return 0; +} diff --git a/LC/LCP043/cpp-LCP043/CMakeLists.txt b/LC/LCP043/cpp-LCP043/CMakeLists.txt new file mode 100644 index 00000000..9175cd40 --- /dev/null +++ b/LC/LCP043/cpp-LCP043/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(E) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(E main.cpp) diff --git a/LC/LCP043/cpp-LCP043/main.cpp b/LC/LCP043/cpp-LCP043/main.cpp new file mode 100644 index 00000000..811dbe64 --- /dev/null +++ b/LC/LCP043/cpp-LCP043/main.cpp @@ -0,0 +1,82 @@ +/// Source : https://leetcode-cn.com/problems/Y1VbOX/ +/// Author : liuyubobobo +/// Time : 2021-09-10 + +#include +#include +#include + +using namespace std; + + +/// Memoization +/// Time Complexity: O(20^4 * 2^4) +/// Space Complexity: O(20^4) +class Solution { +public: + int trafficCommand(vector& directions) { + + vector>>> dp(21, vector>>(21, vector>(21, vector(21, -1)))); + return dfs(directions, 0, 0, 0, 0, dp); + } + +private: + int dfs(const vector& directions, int a, int b, int c, int d, + vector>>>& dp){ + + if(a == directions[0].size() && b == directions[1].size() && c == directions[2].size() && d == directions[3].size()) + return 0; + if(dp[a][b][c][d] != -1) return dp[a][b][c][d]; + + int res = INT_MAX; + for(int state = 1; state < 16; state ++){ + + if((state & (1 << 0)) && a == directions[0].size()) continue; + if((state & (1 << 1)) && b == directions[1].size()) continue; + if((state & (1 << 2)) && c == directions[2].size()) continue; + if((state & (1 << 3)) && d == directions[3].size()) continue; + + if(ok(state & (1 << 0) ? directions[0][a] : ' ', + state & (1 << 1) ? directions[1][b] : ' ', + state & (1 << 2) ? directions[2][c] : ' ', + state & (1 << 3) ? directions[3][d] : ' ')) + res = min(res, 1 + dfs(directions, a + !!(state & (1 << 0)), b + !!(state & (1 << 1)), c + !!(state & (1 << 2)), d + !!(state & (1 << 3)), dp)); + } + return dp[a][b][c][d] = res; + } + + bool ok(char a, char b, char c, char d){ + + if(a == 'W' && (b == 'N' || b == 'W' || c == 'N' || d != ' ')) return false; + if(a == 'N' && (b == 'N' || c == 'N')) return false; + if(a == 'S' && (b == 'N' || b == 'W' || c == 'S' || c == 'E' || d == 'S' || d == 'E')) return false; + + if(b == 'N' && (c == 'E' || c == 'N' || d == 'E' || a != ' ')) return false; + if(b == 'E' && (c == 'E' || d == 'E')) return false; + if(b == 'W' && (c == 'E' || c == 'N' || d == 'W' || d == 'S' || a == 'W' || a == 'S')) return false; + + if(c == 'E' && (d == 'S' || d == 'E' || a == 'S' || b != ' ')) return false; + if(c == 'S' && (d == 'S' || a == 'S')) return false; + if(c == 'N' && (d == 'S' || d == 'E' || a == 'N' || a == 'W' || b == 'N' || b == 'W')) return false; + + if(d == 'S' && (a == 'W' || a == 'S' || b == 'W' || c != ' ')) return false; + if(d == 'W' && (a == 'W' || b == 'W')) return false; + if(d == 'E' && (a == 'W' || a == 'S' || b == 'E' || b == 'N' || c == 'E' || c == 'N')) return false; + + return true; + } +}; + + +int main() { + + vector directions1 = {"W","N","ES","W"}; + cout << Solution().trafficCommand(directions1) << endl; + // 2 + + vector directions2 = {"NS","WE","SE","EW"}; + cout << Solution().trafficCommand(directions2) << endl; + // 3 + + return 0; +} diff --git a/LC/LCP044/cpp-LCP044/CMakeLists.txt b/LC/LCP044/cpp-LCP044/CMakeLists.txt new file mode 100644 index 00000000..2ae8397c --- /dev/null +++ b/LC/LCP044/cpp-LCP044/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/LC/LCP044/cpp-LCP044/main.cpp b/LC/LCP044/cpp-LCP044/main.cpp new file mode 100644 index 00000000..17f8cd0c --- /dev/null +++ b/LC/LCP044/cpp-LCP044/main.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode-cn.com/problems/sZ59z6/ +/// Author : liuyubobobo +/// Time : 2021-09-25 + +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// 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: + int numColor(TreeNode* root) { + + set colors; + dfs(root, colors); + return colors.size(); + } + +private: + void dfs(TreeNode* node, set& colors){ + + if(!node) return; + + colors.insert(node->val); + dfs(node->left, colors); + dfs(node->right, colors); + } +}; + + +int main() { + + return 0; +} diff --git a/LC/LCP045/cpp-LCP045/CMakeLists.txt b/LC/LCP045/cpp-LCP045/CMakeLists.txt new file mode 100644 index 00000000..3f98647f --- /dev/null +++ b/LC/LCP045/cpp-LCP045/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/LC/LCP045/cpp-LCP045/main.cpp b/LC/LCP045/cpp-LCP045/main.cpp new file mode 100644 index 00000000..59cd765c --- /dev/null +++ b/LC/LCP045/cpp-LCP045/main.cpp @@ -0,0 +1,87 @@ +/// Source : https://leetcode-cn.com/problems/kplEvH/ +/// Author : liuyubobobo +/// Time : 2021-09-25 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// BFS +/// Time Complexity: O(R * C * max_terrain) +/// Space Complexity: O(R * C * max_terrain) +class Solution { + +private: + const int dirs[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; + int R, C; + +public: + vector> bicycleYard(vector& position, vector>& terrain, vector>& obstacle) { + + R = terrain.size(), C = terrain[0].size(); + + set> visited; + queue> q; // pos, speed + q.push({position[0] * C + position[1], 1}); + visited.insert({position[0] * C + position[1], 1}); + set> res; + while(!q.empty()){ + int cx = q.front().first / C, cy = q.front().first % C, speed = q.front().second; + q.pop(); + + for(int d = 0; d < 4; d ++){ + int nx = cx + dirs[d][0], ny = cy + dirs[d][1]; + if(!in_area(nx, ny)) continue; + + int npos = nx * C + ny, new_speed = speed + terrain[cx][cy] - terrain[nx][ny] - obstacle[nx][ny]; + if(new_speed <= 0) continue; + if(visited.count({npos, new_speed})) continue; + + visited.insert({npos, new_speed}); + if(new_speed == 1) res.insert({nx, ny}); + q.push({npos, new_speed}); + } + } + + vector> resv; + for(const pair& p: res) + resv.push_back({p.first, p.second}); + return resv; + } + +private: + bool in_area(int x, int y){ + return 0 <= x && x < R && 0 <= y && y < C; + } +}; + + +void print_vec(const vector>& v){ + + for(const vector& row: v){ + cout << '('; + for(int e: row) cout << e << ' '; + cout << ')'; + } + cout << endl; +} + +int main() { + + vector pos1 = {0, 0}; + vector> terrain1 = {{0, 0}, {0, 0}}, o1 = {{0, 0}, {0, 0}}; + print_vec(Solution().bicycleYard(pos1, terrain1, o1)); + // [[0,1],[1,0],[1,1]] + + vector pos2 = {1, 1}; + vector> terrain2 = {{5, 0}, {0, 6}}, o2 = {{0, 6}, {7, 0}}; + print_vec(Solution().bicycleYard(pos2, terrain2, o2)); + // 0 1 + + return 0; +} diff --git a/LC/LCP046/cpp-LCP046/CMakeLists.txt b/LC/LCP046/cpp-LCP046/CMakeLists.txt new file mode 100644 index 00000000..cad75f71 --- /dev/null +++ b/LC/LCP046/cpp-LCP046/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/LC/LCP046/cpp-LCP046/main.cpp b/LC/LCP046/cpp-LCP046/main.cpp new file mode 100644 index 00000000..0eada7da --- /dev/null +++ b/LC/LCP046/cpp-LCP046/main.cpp @@ -0,0 +1,92 @@ +/// Source : https://leetcode-cn.com/problems/05ZEDJ/ +/// Author : liuyubobobo +/// Time : 2021-09-25 + +#include +#include + +using namespace std; + + +/// Reverse +/// Time Complexity: O(|plan| * n) +/// Space Complexity: O(n) +class Solution { +public: + vector volunteerDeployment(vector& finalCnt, long long totalNum, vector>& edges, vector>& plans) { + + int n = finalCnt.size() + 1; + vector> g(n); + for(const vector& edge: edges){ + int a = edge[0], b = edge[1]; + g[a].push_back(b), g[b].push_back(a); + } + + vector> coef(n); + coef[0].first = 1, coef[0].second = 0ll; + for(int i = 0; i < finalCnt.size(); i ++){ + coef[i + 1].first = 0ll; + coef[i + 1].second = finalCnt[i]; + } + + for(int i = (int)plans.size() - 1; i >= 0; i --){ + int type = plans[i][0], id = plans[i][1]; + + if(type == 1){ + coef[id].first *= 2; + coef[id].second *= 2; + } + else if(type == 2){ + for(int i: g[id]) + coef[i] = minus(coef[i], coef[id]); + } + else{ + assert(type == 3); + for(int i: g[id]) + coef[i] = add(coef[i], coef[id]); + } + } + + pair res = {0, 0}; + for(const pair& p: coef) + res.first += p.first, res.second += p.second; + long long x = (totalNum - res.second) / res.first; + + vector ret(n); + for(int i = 0; i < n; i ++) + ret[i] = coef[i].first * x + coef[i].second; + return ret; + } + +private: + pair minus(pair a, pair b){ + return {a.first - b.first, a.second - b.second}; + } + + pair add(pair a, pair b){ + return {a.first + b.first, a.second + b.second}; + } +}; + + +void print_vec(const vector& v){ + for(int e: v) cout << e << ' '; + cout << '\n'; +} + +int main() { + + vector finalCut1 = {1, 16}; long long totalNum1 = 21; + vector> edges1 = {{0, 1}, {1, 2}}; + vector> plan1 = {{2, 1}, {1, 0}, {3, 0}}; + print_vec(Solution().volunteerDeployment(finalCut1, totalNum1, edges1, plan1)); + // 5 7 9 + + vector finalCut2 = {4,13,4,3,8}; long long totalNum2 = 54; + vector> edges2 = {{0, 3}, {1, 3}, {4, 3}, {2, 3}, {2, 5}}; + vector> plan2 = {{1, 1}, {3, 3}, {2, 5}, {1, 0}}; + print_vec(Solution().volunteerDeployment(finalCut2, totalNum2, edges2, plan2)); + // 10 16 9 4 7 8 + + return 0; +} diff --git a/LC/LCP047/cpp-LCP047/CMakeLists.txt b/LC/LCP047/cpp-LCP047/CMakeLists.txt new file mode 100644 index 00000000..2a7f1f76 --- /dev/null +++ b/LC/LCP047/cpp-LCP047/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main2.cpp) diff --git a/LC/LCP047/cpp-LCP047/main.cpp b/LC/LCP047/cpp-LCP047/main.cpp new file mode 100644 index 00000000..13010bb1 --- /dev/null +++ b/LC/LCP047/cpp-LCP047/main.cpp @@ -0,0 +1,77 @@ +/// Source : https://leetcode-cn.com/problems/oPs9Bm/ +/// Author : liuyubobobo +/// Time : 2021-09-25 + +#include +#include +#include + +using namespace std; + + +/// Memoization +/// Time Complexity: O(n * k) +/// Space Complexity: O(n * k) +class Solution { + +private: + const int MOD = 1e9 + 7; + +public: + int securityCheck(vector& capacities, int k) { + + int n = capacities.size(); + int sum = accumulate(capacities.begin(), capacities.end(), 0); + + // 0 - queue, 1 - stack + // room, k-th to go out + vector>> dp(2, vector>(n, vector(sum + 1, -1))); + int res = dfs(capacities, k, sum, 0, n - 1, 0, dp); + res += dfs(capacities, k, sum, 1, n - 1, 0, dp); + return res % MOD; + } + +private: + int dfs(const vector& capacities, const int k, const int sum, + int is_stack, int index, int go_out, + vector>>& dp){ + + if(index == -1){ + if(is_stack) return k == capacities[0] - 1 + go_out; + return k == go_out; + } + assert(go_out <= sum); + if(dp[is_stack][index][go_out] != -1) return dp[is_stack][index][go_out]; + + int res = 0; + if(is_stack){ + res += dfs(capacities, k, sum, 1, index - 1, capacities[index] - 1 + go_out, dp); + res += dfs(capacities, k, sum, 0, index - 1, capacities[index] - 1 + go_out, dp); + res %= MOD; + } + else{ + res += dfs(capacities, k, sum, 1, index - 1, go_out, dp); + res += dfs(capacities, k, sum, 0, index - 1, go_out, dp); + res %= MOD; + } + return dp[is_stack][index][go_out] = res; + } +}; + + +int main() { + + vector cap1 = {2, 2, 3}; + cout << Solution().securityCheck(cap1, 2) << endl; + // 2 + + vector cap2 = {3, 3}; + cout << Solution().securityCheck(cap2, 3) << endl; + // 0 + + vector cap3 = {4, 3, 2, 2}; + cout << Solution().securityCheck(cap3, 6) << endl; + // 2 + + return 0; +} diff --git a/LC/LCP047/cpp-LCP047/main2.cpp b/LC/LCP047/cpp-LCP047/main2.cpp new file mode 100644 index 00000000..44a86c71 --- /dev/null +++ b/LC/LCP047/cpp-LCP047/main2.cpp @@ -0,0 +1,51 @@ +/// Source : https://leetcode-cn.com/problems/oPs9Bm/ +/// Author : liuyubobobo +/// Time : 2021-09-25 + +#include +#include +#include + +using namespace std; + + +/// Backpack +/// Time Complexity: O(n * k) +/// Space Complexity: O(n * k) +class Solution { + +private: + const int MOD = 1e9 + 7; + +public: + int securityCheck(vector& capacities, int k) { + + int n = capacities.size(); + vector dp(k + 1, 0); + dp[0] = 1; + for(int item: capacities){ + item --; + for(int c = k; c >= item; c --) + dp[c] += dp[c - item], dp[c] %= MOD; + } + return dp[k]; + } +}; + + +int main() { + + vector cap1 = {2, 2, 3}; + cout << Solution().securityCheck(cap1, 2) << endl; + // 2 + + vector cap2 = {3, 3}; + cout << Solution().securityCheck(cap2, 3) << endl; + // 0 + + vector cap3 = {4, 3, 2, 2}; + cout << Solution().securityCheck(cap3, 6) << endl; + // 2 + + return 0; +} diff --git a/LC/LCP048/cpp-LCP048/CMakeLists.txt b/LC/LCP048/cpp-LCP048/CMakeLists.txt new file mode 100644 index 00000000..9175cd40 --- /dev/null +++ b/LC/LCP048/cpp-LCP048/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) +project(E) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(E main.cpp) diff --git a/LC/LCP048/cpp-LCP048/main.cpp b/LC/LCP048/cpp-LCP048/main.cpp new file mode 100644 index 00000000..97ebe6b7 --- /dev/null +++ b/LC/LCP048/cpp-LCP048/main.cpp @@ -0,0 +1,107 @@ +/// Source : https://leetcode-cn.com/problems/fsa7oZ/ +/// Author : liuyubobobo +/// Time : 2021-09-25 + +#include +#include +#include +#include + +using namespace std; + + +/// Ad-Hoc, Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +private: + const int dirs[8][2] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}, {1, 1}, {1, -1}, {-1, 1}, {-1, -1}}; + +public: + string gobang(vector>& pieces) { + + map, int> board; + for(const vector& piece: pieces) + board[{piece[0], piece[1]}] = piece[2]; + + // black - 0, white - 1 + set> black_win_pos = get_win_pos(board, 0); + set> white_win_pos = get_win_pos(board, 1); + + if(black_win_pos.size()) return "Black"; + if(white_win_pos.size() >= 2) return "White"; + + if(white_win_pos.size() == 1){ + board[*white_win_pos.begin()] = 0; + black_win_pos = get_win_pos(board, 0); + if(black_win_pos.size() >= 2) return "Black"; + return "None"; + } + + return have_black_4(board) ? "Black" : "None"; + } + +private: + bool have_black_4(const map, int>& board){ + + for(const pair, int>& p: board) + if(p.second == 0){ + int x = p.first.first, y = p.first.second; + for(int d = 0; d < 8; d ++){ + int color_cnt = 0, op_cnt = 0, empty_cnt = 0; + for(int l = 0; l < 4 && op_cnt == 0; l ++){ + pair np = {x + l * dirs[d][0], y + l * dirs[d][1]}; + if(!board.count(np)) empty_cnt ++; + else if(board.find(np)->second == 0) color_cnt ++; + else op_cnt ++; + } + if(color_cnt == 3 && op_cnt == 0){ + assert(empty_cnt == 1); + pair np1 = {x + 4 * dirs[d][0], y + 4 * dirs[d][1]}; + pair np2 = {x - dirs[d][0], y - dirs[d][1]}; + if(!board.count(np1) && !board.count(np2)) return true; + } + } + } + return false; + } + + set> get_win_pos(const map, int>& board, int color){ + + set> res; + for(const pair, int>& p: board) + if(p.second == color){ + int x = p.first.first, y = p.first.second; + for(int d = 0; d < 8; d ++){ + int color_cnt = 0, op_cnt = 0, empty_cnt = 0; + pair pos; + for(int l = 0; l < 5 && op_cnt == 0; l ++){ + pair np = {x + l * dirs[d][0], y + l * dirs[d][1]}; + if(!board.count(np)) empty_cnt ++, pos = np; + else if(board.find(np)->second == color) color_cnt ++; + else op_cnt ++; + } + if(color_cnt == 4 && op_cnt == 0){ + assert(empty_cnt == 1); + res.insert(pos); + } + } + } + return res; + } +}; + + +int main() { + + vector> pieces1 = {{0, 0, 1}, {1, 1, 1}, {2, 2, 0}}; + cout << Solution().gobang(pieces1) << endl; + // None + + vector> pieces2 = {{1,2,1},{1,4,1},{1,5,1},{2,1,0},{2,3,0},{2,4,0},{3,2,1},{3,4,0},{4,2,1},{5,2,1}}; + cout << Solution().gobang(pieces2) << endl; + // Black + + return 0; +} diff --git a/LC/LCP050/cpp-LCP050/CMakeLists.txt b/LC/LCP050/cpp-LCP050/CMakeLists.txt new file mode 100644 index 00000000..a3422f8f --- /dev/null +++ b/LC/LCP050/cpp-LCP050/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/LC/LCP050/cpp-LCP050/main.cpp b/LC/LCP050/cpp-LCP050/main.cpp new file mode 100644 index 00000000..e819803b --- /dev/null +++ b/LC/LCP050/cpp-LCP050/main.cpp @@ -0,0 +1,31 @@ +/// Source : https://leetcode-cn.com/problems/WHnhjV/ +/// Author : liuyubobobo +/// Time : 2022-04-16 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(|gem| + |op|) +/// Space Complexity: O(1) +class Solution { +public: + int giveGem(vector& gem, vector>& operations) { + + for(const vector& op: operations){ + int x = op[0], y = op[1]; + int t = gem[x] / 2; + gem[x] -= t, gem[y] += t; + } + return *max_element(gem.begin(), gem.end()) - *min_element(gem.begin(), gem.end()); + } +}; + + +int main() { + + return 0; +} diff --git a/LC/LCP051/cpp-LCP051/CMakeLists.txt b/LC/LCP051/cpp-LCP051/CMakeLists.txt new file mode 100644 index 00000000..0700646a --- /dev/null +++ b/LC/LCP051/cpp-LCP051/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/LC/LCP051/cpp-LCP051/main.cpp b/LC/LCP051/cpp-LCP051/main.cpp new file mode 100644 index 00000000..e8156683 --- /dev/null +++ b/LC/LCP051/cpp-LCP051/main.cpp @@ -0,0 +1,61 @@ +/// Source : https://leetcode-cn.com/problems/UEcfPD/ +/// Author : liuyubobobo +/// Time : 2022-04-16 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(2^|cookbooks| * |cookbooks|) +/// Space Complexity: O(1) +class Solution { +public: + int perfectMenu(vector& materials, vector>& cookbooks, + vector>& attribute, int limit) { + + int n = cookbooks.size(); + int best_x = -1; + for(int state = 1; state < (1 << n); state ++){ + + int total_x = 0, total_y = 0; + vector total_m(5, 0); + for(int i = 0; i < n; i ++) + if(state & (1 << i)){ + total_x += attribute[i][0]; + total_y += attribute[i][1]; + add(total_m, cookbooks[i]); + } + if(total_y >= limit && greater_or_equal(materials, total_m)) + best_x = max(best_x, total_x); + } + return best_x; + } + +private: + // v += a + void add(vector& v, const vector& a){ + for(int i = 0; i < v.size(); i ++) v[i] += a[i]; + } + + bool greater_or_equal(const vector& a, const vector& b){ + for(int i = 0; i < a.size(); i ++) + if(a[i] < b[i]) return false; + return true; + } +}; + + +int main() { + + vector materials1 = {3,2,4,1,2}; + vector> cookbooks1 = {{1,1,0,1,2},{2,1,4,0,0},{3,2,4,1,0}}; + vector> attribute1 = {{3,2},{2,4},{7,6}}; + int limit1 = 5; + cout << Solution().perfectMenu(materials1, cookbooks1, attribute1, limit1) << '\n'; + // 7 + + return 0; +} diff --git a/LC/LCP052/cpp-LCP052/CMakeLists.txt b/LC/LCP052/cpp-LCP052/CMakeLists.txt new file mode 100644 index 00000000..8accde5b --- /dev/null +++ b/LC/LCP052/cpp-LCP052/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/LC/LCP052/cpp-LCP052/main.cpp b/LC/LCP052/cpp-LCP052/main.cpp new file mode 100644 index 00000000..39162dce --- /dev/null +++ b/LC/LCP052/cpp-LCP052/main.cpp @@ -0,0 +1,145 @@ +/// Source : https://leetcode-cn.com/problems/QO5KpG/ +/// Author : liuyubobobo +/// Time : 2022-04-17 + +#include +#include +#include + +using namespace std; + + +/// Using Segment Tree +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) + +/// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +template +class SegmentTree{ + +private: + int n; + vector tree, lazy; + T (*combine)(T a, T b); + +public: + SegmentTree(int n, T (*combine)(T a, T b)): n(n), tree(4 * n, 0), lazy(4 * n, -1){ + this->combine = combine; + } + + void set(int uL, int uR, T v){ + if(uL > uR) return; + set(0, 0, n - 1, uL, uR, v); + } + + T query(int qL, int qR){ + if(qL > qR) return 0; + return query(0, 0, n - 1, qL, qR); + } + +private: + void set(int treeID, int treeL, int treeR, int uL, int uR, T v){ + + if(uL > treeR || uR < treeL) return; + + if(uL <= treeL && treeR <= uR){ + tree[treeID] = (treeR - treeL + 1) * v; + lazy[treeID] = v; + return; + } + + if(lazy[treeID] != -1) + push(treeID, treeL, treeR); + + int mid = (treeL + treeR) / 2; + set(2 * treeID + 1, treeL, mid, uL, uR, v); + set(2 * treeID + 2, mid + 1, treeR, uL, uR, v); + tree[treeID] = combine(tree[treeID * 2 + 1], tree[treeID * 2 + 2]); + return; + } + + T query(int treeID, int treeL, int treeR, int qL, int qR){ + + if(qL <= treeL && treeR <= qR) + return tree[treeID]; + + if(lazy[treeID] != -1) + push(treeID, treeL, treeR); + + int mid = (treeL + treeR) / 2; + if(qR <= mid) return query(2 * treeID + 1, treeL, mid, qL, qR); + if(qL >= mid + 1) return query(2 * treeID + 2, mid + 1, treeR, qL, qR); + + T resl = query(2 * treeID + 1, treeL, mid, qL, qR); + T resr = query(2 * treeID + 2, mid + 1, treeR, qL, qR); + T res = combine(resl, resr); + return res; + } + +private: + void push(int treeID, int treeL, int treeR){ + + if(treeL == treeR) return; + + T v = lazy[treeID]; + + int mid = (treeL + treeR) / 2; + int tn = treeR - treeL + 1, tnl = mid - treeL + 1, tnr = tn - tnl; + + tree[treeID * 2 + 1] = v * tnl; + tree[treeID * 2 + 2] = v * tnr; + + lazy[treeID * 2 + 1] = v; + lazy[treeID * 2 + 2] = v; + + lazy[treeID] = -1; + } +}; + +class Solution { + +public: + int getNumber(TreeNode* root, vector>& ops) { + + vector index2value; + init(root, index2value); + + int n = index2value.size(); +// for(int e: index2value) cout << e << ' '; cout << '\n'; + + SegmentTree seg_tree(n, [](int a, int b){return a + b;}); + + for(const vector& op: ops){ + int color = op[0], l_value = op[0], r_value = op[1]; + int l = lower_bound(index2value.begin(), index2value.end(), l_value) - index2value.begin(); + int r = (upper_bound(index2value.begin(), index2value.end(), r_value) - index2value.begin()) - 1; + +// cout << l << ' ' << r << ' ' << color << '\n'; + seg_tree.set(l, r, color); + } + return seg_tree.query(0, n - 1); + } + +private: + void init(TreeNode* node, vector& index2value){ + + if(!node) return; + + init(node->left, index2value); + index2value.push_back(node->val); + init(node->right, index2value); + } +}; + + +int main() { + + return 0; +} diff --git a/LC/LCP055/cpp-LCP055/CMakeLists.txt b/LC/LCP055/cpp-LCP055/CMakeLists.txt new file mode 100644 index 00000000..a3422f8f --- /dev/null +++ b/LC/LCP055/cpp-LCP055/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/LC/LCP055/cpp-LCP055/main.cpp b/LC/LCP055/cpp-LCP055/main.cpp new file mode 100644 index 00000000..e78090e6 --- /dev/null +++ b/LC/LCP055/cpp-LCP055/main.cpp @@ -0,0 +1,31 @@ +/// Source : https://leetcode-cn.com/problems/PTXy4P/ +/// Author : liuyubobobo +/// Time : 2022-04-23 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(|fruits|) +/// Space Complexity: O(1) +class Solution { +public: + int getMinimumTime(vector& time, vector>& fruits, int limit) { + + int res = 0; + for(const vector& fruit: fruits){ + int type = fruit[0], num = fruit[1]; + res += (num / limit + !!(num % limit)) * time[type]; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/LC/LCP056/cpp-LCP056/CMakeLists.txt b/LC/LCP056/cpp-LCP056/CMakeLists.txt new file mode 100644 index 00000000..0700646a --- /dev/null +++ b/LC/LCP056/cpp-LCP056/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/LC/LCP056/cpp-LCP056/main.cpp b/LC/LCP056/cpp-LCP056/main.cpp new file mode 100644 index 00000000..3cb2ed35 --- /dev/null +++ b/LC/LCP056/cpp-LCP056/main.cpp @@ -0,0 +1,77 @@ +/// Source : https://leetcode-cn.com/problems/6UEx57/ +/// Author : liuyubobobo +/// Time : 2022-04-23 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// 0-1 BFS +/// Time Complexity: O(R * C) +/// Space Complexity: O(R * C) +class Solution { + +private: + const int dirs[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; + const string ds = "^v<>"; + int R, C; + +public: + int conveyorBelt(vector& matrix, vector& start, vector& end) { + + R = matrix.size(), C = matrix[0].size(); + + vector>> g(R * C); + for(int cx = 0; cx < R; cx ++) + for(int cy = 0; cy < C; cy ++){ + int od = ds.find(matrix[cx][cy]), cur = cx * C + cy; + assert(od != string::npos); + + for(int d = 0; d < 4; d ++){ + int nx = cx + dirs[d][0], ny = cy + dirs[d][1], next = nx * C + ny; + if(in_area(nx, ny)) g[cur].push_back({next, (d == od ? 0 : 1)}); + } + } + return bfs(R * C, g, start[0] * C + start[1], end[0] * C + end[1]); + } + +private: + int bfs(int n, const vector>>& g, int s, int t){ + + vector dis(n, INT_MAX / 2); + vector visited(n, false); + deque q; + q.push_front(s); + dis[s] = 0; + while(!q.empty()){ + int u = q.front(); q.pop_front(); + if(visited[u]) continue; + visited[u] = true; + + for(const pair& p: g[u]){ + int v = p.first, w = p.second; + if(!visited[v] && w + dis[u] < dis[v]){ + dis[v] = dis[u] + w; + if(w) q.push_back(v); + else q.push_front(v); + } + } + } + return dis[t]; + } + + bool in_area(int x, int y){ + return 0 <= x && x < R && 0 <= y && y < C; + } +}; + + +int main() { + + return 0; +} diff --git a/LC/LCP057/cpp-LCP057/CMakeLists.txt b/LC/LCP057/cpp-LCP057/CMakeLists.txt new file mode 100644 index 00000000..8accde5b --- /dev/null +++ b/LC/LCP057/cpp-LCP057/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/LC/LCP057/cpp-LCP057/main.cpp b/LC/LCP057/cpp-LCP057/main.cpp new file mode 100644 index 00000000..0e42445c --- /dev/null +++ b/LC/LCP057/cpp-LCP057/main.cpp @@ -0,0 +1,68 @@ +/// Source : https://leetcode-cn.com/problems/ZbAuEH/ +/// Author : liuyubobobo +/// Time : 2022-04-23 + +#include +#include +#include + +using namespace std; + + +/// Memoization +/// Time Compelxity: O(n) +/// Space Complexity: O(n) +class Solution { + +private: + const vector>> next ={ + {{0}, {1, 3}, {2, 4, 6}, {5, 7}, {8}}, + {{1}, {0, 2, 4}, {3, 5, 7}, {6, 8}}, + {{2}, {1, 5}, {0, 4, 8}, {3, 7}, {6}}, + {{3}, {0, 4, 6}, {1, 5, 7}, {2, 8}}, + {{4}, {1, 3, 5, 7}, {0, 2, 6, 8}}, + {{5}, {2, 4, 8}, {1, 3, 7}, {0, 6}}, + {{6}, {3, 7}, {0, 4, 8}, {1, 5}, {2}}, + {{7}, {4, 6, 8}, {1, 3, 5}, {0, 2}}, + {{8}, {5, 7}, {2, 4, 6}, {1, 3}, {0}} + }; + +public: + int getMaximumNumber(vector>& moles) { + + int n = moles.size(); + vector> data(n); // t, pos + for(int i = 0; i < n; i ++) + data[i] = {moles[i][0], moles[i][1] * 3 + moles[i][2]}; + sort(data.begin(), data.end()); + + vector> dp(9, vector(n, -1)); + int res = 0; + for(int t = 0; t <= data[0].first && t < next[4].size(); t ++) + for(int pos: next[4][t]) + res = max(res, dfs(n, data, pos, 0, dp)); + return res; + } + +private: + int dfs(int n, const vector>& data, int pos, int index, + vector>& dp){ + + if(index == n - 1) + return pos == data[index].second; + if(dp[pos][index] != -1) return dp[pos][index]; + + int T = data[index + 1].first - data[index].first; + int res = 0; + for(int t = 0; t <= T && t < next[pos].size(); t ++) + for(int next_pos: next[pos][t]) + res = max(res, (data[index].second == pos) + dfs(n, data, next_pos, index + 1, dp)); + return dp[pos][index] = res; + } +}; + + +int main() { + + return 0; +} diff --git a/LC/LCP066/cpp-LCP066/CMakeLists.txt b/LC/LCP066/cpp-LCP066/CMakeLists.txt new file mode 100644 index 00000000..415e0a92 --- /dev/null +++ b/LC/LCP066/cpp-LCP066/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/LC/LCP066/cpp-LCP066/main.cpp b/LC/LCP066/cpp-LCP066/main.cpp new file mode 100644 index 00000000..31c931f9 --- /dev/null +++ b/LC/LCP066/cpp-LCP066/main.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.cn/problems/600YaG/ +/// Author : liuyubobobo +/// Time : 2022-10-07 + +#include +#include +#include + +using namespace std; + + +/// Linear Scan +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int minNumBooths(vector& demand) { + + vector res(26, 0); + for(const string& s: demand){ + vector t(26, 0); + for(char c: s) t[c - 'a'] ++; + for(int i = 0; i < 26; i ++) + res[i] = max(res[i], t[i]); + } + return accumulate(res.begin(), res.end(), 0); + } +}; + +int main() { + std::cout << "Hello, World!" << std::endl; + return 0; +} diff --git a/LC/LCP067/cpp-LCP067/CMakeLists.txt b/LC/LCP067/cpp-LCP067/CMakeLists.txt new file mode 100644 index 00000000..b1c82ab8 --- /dev/null +++ b/LC/LCP067/cpp-LCP067/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/LC/LCP067/cpp-LCP067/main.cpp b/LC/LCP067/cpp-LCP067/main.cpp new file mode 100644 index 00000000..cbb5e881 --- /dev/null +++ b/LC/LCP067/cpp-LCP067/main.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.cn/problems/KnLfVT/ +/// Author : liuyubobobo +/// Time : 2022-10-07 + +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(h) + +/// 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* expandBinaryTree(TreeNode* root) { + + return dfs(root); + } + +private: + TreeNode* dfs(TreeNode* node){ + + if(node->left){ + TreeNode* lnode = new TreeNode(-1, dfs(node->left), nullptr); + node->left = lnode; + } + + if(node->right){ + TreeNode* rnode = new TreeNode(-1, nullptr, dfs(node->right)); + node->right = rnode; + } + + return node; + } +}; + + +int main() { + + return 0; +} diff --git a/LC/LCP068/cpp-LCP068/CMakeLists.txt b/LC/LCP068/cpp-LCP068/CMakeLists.txt new file mode 100644 index 00000000..d0dc1506 --- /dev/null +++ b/LC/LCP068/cpp-LCP068/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/LC/LCP068/cpp-LCP068/main.cpp b/LC/LCP068/cpp-LCP068/main.cpp new file mode 100644 index 00000000..7959391b --- /dev/null +++ b/LC/LCP068/cpp-LCP068/main.cpp @@ -0,0 +1,43 @@ +/// Source : https://leetcode.cn/problems/1GxJYY/ +/// Author : liuyubobobo +/// Time : 2022-10-07 + +#include +#include + +using namespace std; + + +/// Sliding Window +/// Time Complexity: O(n) +/// Space Complexity: O(max(flowers)) +class Solution { + +private: + const long long MOD = 1e9 + 7; + +public: + int beautifulBouquet(vector& flowers, int cnt) { + + vector f(100001, 0); + int n = flowers.size(), l = 0, r = -1; + long long res = 0; + while(l < n){ + if(r + 1 < n && f[flowers[r + 1]] + 1 <= cnt){ + f[flowers[++ r]] ++; + res = (res + 1) % MOD; + } + else{ + f[flowers[l ++]] --; + res = (res + (r - l + 1)) % MOD; + } + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/LC/LCP069/cpp-LCP069/CMakeLists.txt b/LC/LCP069/cpp-LCP069/CMakeLists.txt new file mode 100644 index 00000000..8148fadd --- /dev/null +++ b/LC/LCP069/cpp-LCP069/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) diff --git a/LC/LCP069/cpp-LCP069/main.cpp b/LC/LCP069/cpp-LCP069/main.cpp new file mode 100644 index 00000000..af4ee8fa --- /dev/null +++ b/LC/LCP069/cpp-LCP069/main.cpp @@ -0,0 +1,87 @@ +/// Source : https://leetcode.cn/problems/rMeRt2/ +/// Author : liuyubobobo +/// Time : 2022-10-07 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// Memoization +/// Time Complexity: O(1000 * n * m * 2^m) +/// Space Complexity: O(1000 * n * 2^m) +int dp[2][2][5][2][4][3][2][25][1 << 8]; + +class Solution { + +private: + const string target = "helloleetcode"; + vector c2index; + const int INF = INT_MAX / 2; + +public: + int Leetcode(vector& words) { + + c2index.resize(26, -1); + c2index['c' - 'a'] = 0; + c2index['d' - 'a'] = 1; + c2index['e' - 'a'] = 2; + c2index['h' - 'a'] = 3; + c2index['l' - 'a'] = 4; + c2index['o' - 'a'] = 5; + c2index['t' - 'a'] = 6; + + vector leftv = {1, 1, 4, 1, 3, 2, 1}; + memset(dp, -1, sizeof(dp)); + + int res = dfs(words.size(), words, leftv, 0, 0, 13); + return res == INF ? -1 : res; + } + +private: + int dfs(int n, const vector& words, + vector& l, int index, int word_state, int left){ + + if(index == n) return left == 0 ? 0 : INF; + + if(dp[l[0]][l[1]][l[2]][l[3]][l[4]][l[5]][l[6]][index][word_state] != -1) + return dp[l[0]][l[1]][l[2]][l[3]][l[4]][l[5]][l[6]][index][word_state]; + + int res = dfs(n, words, l, index + 1, 0, left); + for(int i = 0; i < words[index].size(); i ++) + if(((word_state >> i) & 1) == 0){ + int cindex = c2index[words[index][i] - 'a']; + if(cindex != -1 && l[cindex] > 0){ + int a = i - __builtin_popcount(word_state & ((1 << i) - 1)); + int b = words[index].size() - 1 - i - __builtin_popcount(word_state >> (i + 1)); +// assert(a >= 0 && b >= 0); + l[cindex] --; + res = min(res, a * b + dfs(n, words, l, index, word_state + (1 << i), left - 1)); + l[cindex] ++; + } + } + return dp[l[0]][l[1]][l[2]][l[3]][l[4]][l[5]][l[6]][index][word_state] = res; + } +}; + + +int main() { + + vector words1 = {"engineer","hold","cost","level"}; + cout << Solution().Leetcode(words1) << '\n'; + // 5 + + vector words2 = {"hello","leetcode"}; + cout << Solution().Leetcode(words2) << '\n'; + // 0 + + vector words3 = {"ecleob","rho","tw","lpl","ebolddec"}; + cout << Solution().Leetcode(words3) << '\n'; + // 6 + + return 0; +} diff --git a/LC/LCP070/cpp-LCP070/CMakeLists.txt b/LC/LCP070/cpp-LCP070/CMakeLists.txt new file mode 100644 index 00000000..399824bd --- /dev/null +++ b/LC/LCP070/cpp-LCP070/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(E) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(E main.cpp) diff --git a/LC/LCP070/cpp-LCP070/main.cpp b/LC/LCP070/cpp-LCP070/main.cpp new file mode 100644 index 00000000..984381e7 --- /dev/null +++ b/LC/LCP070/cpp-LCP070/main.cpp @@ -0,0 +1,70 @@ +/// Source : https://leetcode.cn/problems/XxZZjK/ +/// Author : liuyubobobo +/// Time : 2022-10-07 + +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(size^2) +/// Space Complexity: O(1) +class Solution { +public: + vector> sandyLandManagement(int size) { + + if(size == 1) + return {{1, 1}}; + + vector> res = {{1, 1}}; + if(size % 2 == 1){ + for(int i = 2; i <= size; i += 2){ + if(i % 4 == 2){ + res.push_back({i, 1}); + for(int j = 3; j <= 2 * i + 1; j += 2) + res.push_back({i + 1, j}); + } + else{ + res.push_back({i, 2}); + for(int j = 1; j <= 2 * i + 1; j += 2) + res.push_back({i + 1, j}); + } + } + if((size - 1) % 4 == 2) res.push_back({size, 1}); + } + else if(size % 4 == 2){ + for(int i = 2; i < size; i += 2){ + if(i % 4 == 2){ + for(int j = 1; j <= 2 * i - 1; j += 2) res.push_back({i, j}); + res.push_back({i + 1, 1}); + } + else{ + for(int j = 3; j <= 2 * i - 1; j += 2) res.push_back({i, j}); + res.push_back({i + 1, 2}); + } + } + for(int j = 1; j <= 2 * size - 1; j += 2) res.push_back({size, j}); + } + else{ + res.push_back({2, 3}); + for(int i = 3; i <= size; i += 2){ + if(i % 4 == 3){ + res.push_back({i, 2}); + for(int j = 1; j <= 2 * (i + 1) - 1; j += 2) res.push_back({i + 1, j}); + } + else{ + res.push_back({i, 1}); + for(int j = 3; j <= 2 * (i + 1) - 1; j += 2) res.push_back({i + 1, j}); + } + } + } + return res; + } +}; + +int main() { + + return 0; +} diff --git a/LC/LCP072/cpp-LCP072/CMakeLists.txt b/LC/LCP072/cpp-LCP072/CMakeLists.txt new file mode 100644 index 00000000..8a306afe --- /dev/null +++ b/LC/LCP072/cpp-LCP072/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(A) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(A main.cpp) diff --git a/LC/LCP072/cpp-LCP072/main.cpp b/LC/LCP072/cpp-LCP072/main.cpp new file mode 100644 index 00000000..7001e549 --- /dev/null +++ b/LC/LCP072/cpp-LCP072/main.cpp @@ -0,0 +1,48 @@ +/// Source : https://leetcode.cn/problems/hqCnmP/ +/// Author : liuyubobobo +/// Time : 2023-04-22 + +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) +class Solution { +public: + vector supplyWagon(vector& supplies) { + + int n = supplies.size(), k = n - n / 2; + while(k --) + supplies = merge(supplies); + return supplies; + } + +private: + vector merge(vector& supplies) { + + int n = supplies.size(); + int min_sum = supplies[0] + supplies[1], pos = 1; + for(int i = 2; i < n; i ++){ + if(supplies[i - 1] + supplies[i] < min_sum) + min_sum = supplies[i - 1] + supplies[i], pos = i; + } + + vector res; + for(int i = 0; i < n; ) + if(i == pos - 1) + res.push_back(min_sum), i += 2; + else + res.push_back(supplies[i ++]); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/LC/LCP073/cpp-LCP073/CMakeLists.txt b/LC/LCP073/cpp-LCP073/CMakeLists.txt new file mode 100644 index 00000000..3e27b177 --- /dev/null +++ b/LC/LCP073/cpp-LCP073/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(B) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(B main.cpp) diff --git a/LC/LCP073/cpp-LCP073/main.cpp b/LC/LCP073/cpp-LCP073/main.cpp new file mode 100644 index 00000000..43f1a2f8 --- /dev/null +++ b/LC/LCP073/cpp-LCP073/main.cpp @@ -0,0 +1,60 @@ +/// Source : https://leetcode.cn/problems/0Zeoeg/ +/// Author : liuyubobobo +/// Time : 2023-04-22 + +#include +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(|total_characters|) +/// Space Complexity: O(|total_characters|) +class Solution { +public: + int adventureCamp(vector& expeditions) { + + set init_set = get_set(expeditions[0]); + + int best = 0, res = -1; + for(int i = 1; i < expeditions.size(); i ++){ + set cur_set = get_set(expeditions[i]); + int cur = 0; + for(const string& s: cur_set) + cur += !init_set.count(s); + + if(cur > best) best = cur, res = i; + + for(const string& s: cur_set) + init_set.insert(s); + } + return res; + } + +private: + set get_set(const string& s){ + + set res; + int pos = 0; + while(pos < s.size()){ + int arrow_pos = s.find("->", pos); + if(arrow_pos == string::npos){ + res.insert(s.substr(pos)); + break; + } + res.insert(s.substr(pos, arrow_pos - pos)); + pos = arrow_pos + 2; + } + return res; + } +}; + + +int main() { + + // ["xO->xO->xO","xO->BKbWDH","xO->BKbWDH","BKbWDH->mWXW","LSAYWW->LSAYWW","oAibBvPdJ","LSAYWW->u","LSAYWW->LSAYWW"] + // 1 + return 0; +} diff --git a/LC/LCP074/cpp-LCP074/CMakeLists.txt b/LC/LCP074/cpp-LCP074/CMakeLists.txt new file mode 100644 index 00000000..6d269de2 --- /dev/null +++ b/LC/LCP074/cpp-LCP074/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(C) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(C main.cpp) diff --git a/LC/LCP074/cpp-LCP074/main.cpp b/LC/LCP074/cpp-LCP074/main.cpp new file mode 100644 index 00000000..8e5af497 --- /dev/null +++ b/LC/LCP074/cpp-LCP074/main.cpp @@ -0,0 +1,104 @@ +/// Source : https://leetcode.cn/problems/xepqZ5/ +/// Author : liuyubobobo +/// Time : 2023-04-22 + +#include +#include +#include + +using namespace std; + + +/// Brute Force +/// Time Complexity: O(n^3) +/// Space Complexity: O(n^2) +class Solution { +public: + int fieldOfGreatestBlessing(vector>& forceField) { + + int n = forceField.size(); + vector> llforceField(n, vector(3)); + for(int i = 0; i < n; i ++) + for(int j = 0; j < 3; j ++) llforceField[i][j] = forceField[i][j] * 2ll; + + set> points; + for(int i = 0; i < n; i ++) + for(int j = i + 1; j < n; j ++) + get_points(points, llforceField[i], llforceField[j]); + + int res = 1; + for(const pair& p: points) + res = max(res, in_rec(p.first, p.second, llforceField)); + return res; + } + +private: + int in_rec(long long x, long long y, const vector>& f){ + int res = 0; + for(const vector& ff: f) res += in_rec(x, y, ff); + return res; + } + + int in_rec(long long x, long long y, const vector& f){ + long long x0 = f[0] - f[2] / 2, y0 = f[1] - f[2] / 2, len = f[2]; + return x0 <= x && x <= x0 + len && y0 <= y && y <= y0 + len; + } + + void get_points(set>& points, const vector& f1, const vector& f2) { + + long long x1 = f1[0] - f1[2] / 2, y1 = f1[1] - f1[2] / 2, len1 = f1[2]; + long long x2 = f2[0] - f2[2] / 2, y2 = f2[1] - f2[2] / 2, len2 = f2[2]; + + get_points(x1, y1, x1 + len1, y1, x2, y2, len2, points); + get_points(x1 + len1, y1, x1 + len1, y1 + len1, x2, y2, len2, points); + get_points(x1 + len1, y1 + len1, x1, y1 + len1, x2, y2, len2, points); + get_points(x1, y1 + len1, x1, y1, x2, y2, len2, points); + +// get_points(x2, y2, x2 + len2, y2, x1, y1, len1, points); +// get_points(x2 + len2, y2, x2 + len2, y2 + len2, x1, y1, len1, points); +// get_points(x2 + len2, y2 + len2, x2, y2 + len2, x1, y1, len1, points); +// get_points(x2, y2 + len2, x2, y2, x1, y1, len1, points); + } + + void get_points(long long x0, long long y0, long long x1, long long y1, + long long x, long long y, long long len, + set>& points) { + + if(x0 == x1) { + if(y0 > y1) swap(y0, y1); // y0 <= y1 + if(x <= x0 && x0 <= x + len) { + if(y0 <= y){ + if(y1 >= y) points.insert({x0, y}); + if(y1 <= y + len) points.insert({x0, y1}); + else if(y1 >= y + len) points.insert({x0, y + len}); + } + else if(y0 <= y + len) { + points.insert({x0, y0}); + if(y1 <= y + len) points.insert({x0, y1}); + else if(y1 >= y + len) points.insert({x0, y + len}); + } + } + } + if(y0 == y1){ + if(x0 > x1) swap(x0, x1); // x0 <= x1 + if(y <= y0 && y0 <= y + len) { + if(x0 <= x){ + if(x1 >= x) points.insert({x, y0}); + if(x1 <= x + len) points.insert({x1, y0}); + else if(x1 >= x + len) points.insert({x + len, y0}); + } + else if(x0 <= x + len) { + points.insert({x0, y0}); + if(x1 <= x + len) points.insert({x1, y0}); + else if(x1 >= x + len) points.insert({x + len, y0}); + } + } + } + } +}; + + +int main() { + + return 0; +} diff --git a/LC/LCP075/cpp-LCP075/CMakeLists.txt b/LC/LCP075/cpp-LCP075/CMakeLists.txt new file mode 100644 index 00000000..6a6bdfdb --- /dev/null +++ b/LC/LCP075/cpp-LCP075/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(D) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(D main.cpp) diff --git a/LC/LCP075/cpp-LCP075/main.cpp b/LC/LCP075/cpp-LCP075/main.cpp new file mode 100644 index 00000000..9b759ab1 --- /dev/null +++ b/LC/LCP075/cpp-LCP075/main.cpp @@ -0,0 +1,107 @@ +/// Source : https://leetcode.cn/problems/rdmXM7/ +/// Author : liuyubobobo +/// Time : 2023-04-22 + +#include +#include +#include + +using namespace std; + + +/// BFS + Dijkstra +/// Time Complexity: O(n^2 * log(n^2)) +/// Space Complexity: O(n^2) +class Solution { + +private: + int R, C; + const int INF = INT_MAX / 2; + const int dirs[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; + +public: + int challengeOfTheKeeper(vector& maze) { + + R = maze.size(), C = maze[0].size(); + + int sx = -1, sy = -1, tx = -1, ty = -1; + for(int i = 0; i < R && (sx == -1 || tx == -1); i ++) + for(int j = 0; j < C && (sx == -1 || tx == -1); j ++) + if(maze[i][j] == 'S') sx = i, sy = j; + else if(maze[i][j] == 'T') tx = i, ty = j; + + vector> tdis = bfs(maze, tx, ty); + if(tdis[sx][sy] == INF) return -1; + + vector> w(R, vector(C, INF)); + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++){ + if(maze[i][j] == 'S' || maze[i][j] == 'T'){ + w[i][j] = 0; continue; + } + if(maze[i][j] == '#') continue; + + int res = 0; + if(maze[R - 1 - i][j] != '#') res = max(res, tdis[R - 1 - i][j]); + if(maze[i][C - 1 - j] != '#') res = max(res, tdis[i][C - 1 - j]); + w[i][j] = res; + } + + vector> res = dij(maze, w, sx, sy); + return res[tx][ty] == INF ? -1 : res[tx][ty]; + } + +private: + vector> dij(const vector& maze, const vector>& w, int sx, int sy){ + + vector> dis(R, vector(C, INF)); + dis[sx][sy] = 0; + vector> visited(R, vector(C, false)); + priority_queue, vector>, greater<>> pq; + pq.push({0, sx * C + sy}); + while(!pq.empty()){ + int cd = pq.top().first, cx = pq.top().second / C, cy = pq.top().second % C; pq.pop(); + + if(visited[cx][cy]) continue; + visited[cx][cy] = true; + + for(int d = 0; d < 4; d ++){ + int nx = cx + dirs[d][0], ny = cy + dirs[d][1]; + if(in_area(nx, ny) && maze[nx][ny] != '#' && dis[nx][ny] > max(cd, w[nx][ny])){ + dis[nx][ny] = max(cd, w[nx][ny]); + pq.push({dis[nx][ny], nx * C + ny}); + } + } + } + return dis; + } + + vector> bfs(const vector& maze, int sx, int sy){ + + vector> dis(R, vector(C, INF)); + dis[sx][sy] = 0; + queue> q; + q.push({sx, sy}); + while(!q.empty()){ + int cx = q.front().first, cy = q.front().second; q.pop(); + for(int d = 0; d < 4; d ++){ + int nx = cx + dirs[d][0], ny = cy + dirs[d][1]; + if(in_area(nx, ny) && maze[nx][ny] != '#' && dis[nx][ny] == INF){ + dis[nx][ny] = dis[cx][cy] + 1; + q.push({nx, ny}); + } + } + } + return dis; + } + + bool in_area(int x, int y){ + return 0 <= x && x < R && 0 <= y && y < C; + } +}; + + +int main() { + + return 0; +} diff --git a/LC/LCP076/cpp-LCP076/CMakeLists.txt b/LC/LCP076/cpp-LCP076/CMakeLists.txt new file mode 100644 index 00000000..69cec56c --- /dev/null +++ b/LC/LCP076/cpp-LCP076/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(E) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(E main.cpp) diff --git a/LC/LCP076/cpp-LCP076/main.cpp b/LC/LCP076/cpp-LCP076/main.cpp new file mode 100644 index 00000000..d41bd34d --- /dev/null +++ b/LC/LCP076/cpp-LCP076/main.cpp @@ -0,0 +1,137 @@ +/// Source : https://leetcode.cn/problems/1ybDKD/ +/// Author : liuyubobobo +/// Time : 2023-04-23 + +#include +#include +#include +#include + +using namespace std; + + +/// State Compression DP +/// Time Complexity: O(3^(min(R, C))^2 * max(R, C)) +/// Space Complexity: O(3^(min(R, C))^3) + +int pow3[6]; +int new_states[243][243][243][2]; +long long dp[30][243][243]; + +class Solution { + +private: + int R, C; + + +public: + long long getSchemeCount(int n, int m, vector& chessboard) { + + pow3[0] = 1; + for(int i = 1; i <= 5; i ++) pow3[i] = pow3[i - 1] * 3ll; + + memset(new_states, -1, sizeof(new_states)); + + R = chessboard.size(), C = chessboard[0].size(); + if(C > R) chessboard = rotate(chessboard), swap(R, C); + + memset(dp, -1, sizeof(dp)); + return dfs(chessboard, 0, 0, 0); + } + +private: + long long dfs(const vector& chessboard, int index, int state0, int state1){ + + if(index == R) return 1; + if(dp[index][state0][state1] != -1) return dp[index][state0][state1]; + + vector ok_states; + get_ok_states(chessboard[index], state0, state1, 0, 0, 0, ok_states); + + long long res = 0; + for(int state: ok_states){ + + if(new_states[state0][state1][state][0] == -1){ + vector states = {state0, state1, state}; + get_new_state(states, new_states[state0][state1][state]); + } + + res += dfs(chessboard, index + 1, new_states[state0][state1][state][0], new_states[state0][state1][state][1]); + } + return dp[index][state0][state1] = res; + } + + void get_new_state(const vector& states, int res[2]){ + + res[0] = res[1] = 0; + for(int j = 0; j < 5; j ++){ + int write_pos = 1; + for(int i = 2; i >= 0 && write_pos >= 0; i --){ + int val = states[i] / pow3[5 - 1 - j] % 3; + if(val) res[write_pos --] += val * pow3[5 - 1 - j]; + } + } + } + + void get_ok_states(const string& s, int state0, int state1, int index, int state, + int pre, vector& ok_states){ + + if(index == C){ + ok_states.push_back(state); + return; + } + + int l, r; + if(s[index] != '?') l = r = (s[index] == '.' ? 0 : (s[index] == 'R' ? 1 : 2)); + else l = 0, r = 2; + + for(int val = l; val <= r; val ++){ + int val0 = state0 / pow3[C - 1 - index] % 3, val1 = state1 / pow3[C - 1 - index] % 3; + if(val0 && val1 && val && val != val0) continue; + if(pre / 3 % 3 && val && pre / 3 % 3 != val) continue; + + if(val) pre = pre * 3 + val; + get_ok_states(s, state0, state1, index + 1, state * 3 + val, pre, ok_states); + if(val) pre /= 3; + } + return; + } + + vector rotate(const vector& A){ + + int r = A.size(), c = A[0].size(); + + vector B(c, string(r, ' ')); + for(int i = 0; i < r; i ++) + for(int j = 0; j < c; j ++) + B[j][R - 1 - i] = A[i][j]; + return B; + } +}; + + +int main() { + + vector chessboard1 = {"..R","..B","?R?"}; + cout << Solution().getSchemeCount(3, 3, chessboard1) << '\n'; + // 5 + + vector chessboard2 = {"?R?","B?B","?R?"}; + cout << Solution().getSchemeCount(3, 3, chessboard2) << '\n'; + // 105 + + vector chessboard3 = {"?B?B","R?.?"}; + cout << Solution().getSchemeCount(2, 4, chessboard3) << '\n'; + // 42 + + vector chessboard4 = {"????","???.","????","??R?"}; + cout << Solution().getSchemeCount(4, 4, chessboard4) << '\n'; + // 322765 + + vector chessboard5 = { + "??.B??","??????","??B???","??????","???.?." + }; + cout << Solution().getSchemeCount(5, 6, chessboard5) << '\n'; + + return 0; +} diff --git a/LC/LCP077/cpp-LCP077/CMakeLists.txt b/LC/LCP077/cpp-LCP077/CMakeLists.txt new file mode 100644 index 00000000..8a306afe --- /dev/null +++ b/LC/LCP077/cpp-LCP077/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(A) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(A main.cpp) diff --git a/LC/LCP077/cpp-LCP077/main.cpp b/LC/LCP077/cpp-LCP077/main.cpp new file mode 100644 index 00000000..5c8d165b --- /dev/null +++ b/LC/LCP077/cpp-LCP077/main.cpp @@ -0,0 +1,36 @@ +/// Source : https://leetcode.cn/problems/W2ZX4X/ +/// Author : liuyubobobo +/// Time : 2023-05-07 + +#include +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + int runeReserve(vector& runes) { + + sort(runes.begin(), runes.end()); + + int n = runes.size(), start = 0, res = 0; + while(start < n){ + int i; + for(i = start + 1; i < n && runes[i] - runes[i - 1] <= 1; i ++); + res = max(res, i - start); + start = i; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/LC/LCP078/cpp-LCP078/CMakeLists.txt b/LC/LCP078/cpp-LCP078/CMakeLists.txt new file mode 100644 index 00000000..3e27b177 --- /dev/null +++ b/LC/LCP078/cpp-LCP078/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(B) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(B main.cpp) diff --git a/LC/LCP078/cpp-LCP078/main.cpp b/LC/LCP078/cpp-LCP078/main.cpp new file mode 100644 index 00000000..3a006403 --- /dev/null +++ b/LC/LCP078/cpp-LCP078/main.cpp @@ -0,0 +1,46 @@ +/// Source : https://leetcode.cn/problems/Nsibyl/ +/// Author : liuyubobobo +/// Time : 2023-05-07 + +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(nlog(max_rampart)) +/// Space Complexity: O(1) +class Solution { +public: + int rampartDefensiveLine(vector>& rampart) { + + int n = rampart.size(), l = 0, r = 1e8; + while(l < r){ + int mid = l + (r - l + 1) / 2; + if(ok(n, rampart, mid)) l = mid; + else r = mid - 1; + } + return l; + } + +private: + bool ok(int n, vector> segs, int k){ + int r = segs[0][1]; + for(int i = 1; i < n; i ++){ + int a = segs[i][0], b = segs[i][1]; + if(a < r) return false; + + int left = a - r; + if(left >= k) r = b; + else r = b + (k - left); + } + return true; + } +}; + + +int main() { + + return 0; +} diff --git a/LC/LCP079/cpp-LCP079/CMakeLists.txt b/LC/LCP079/cpp-LCP079/CMakeLists.txt new file mode 100644 index 00000000..6d269de2 --- /dev/null +++ b/LC/LCP079/cpp-LCP079/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(C) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(C main.cpp) diff --git a/LC/LCP079/cpp-LCP079/main.cpp b/LC/LCP079/cpp-LCP079/main.cpp new file mode 100644 index 00000000..dea31a70 --- /dev/null +++ b/LC/LCP079/cpp-LCP079/main.cpp @@ -0,0 +1,59 @@ +/// Source : https://leetcode.cn/problems/kjpLFZ/ +/// Author : liuyubobobo +/// Time : 2023-05-07 + +#include +#include +#include +#include + +using namespace std; + + +/// BFS +/// Time Complexity: O(R * C * k) +/// Space Complexity: O(R * C * k) +class Solution { + +private: + const int dirs[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; + +public: + int extractMantra(vector& matrix, string mantra) { + + int R = matrix.size(), C = matrix[0].size(), k = mantra.size(); + + vector>> dis(k + 1, vector>(R, vector(C, -1))); + queue> q; + q.push({0, 0, 0}); + dis[0][0][0] = 0; + while(!q.empty()){ + int index = get<0>(q.front()), cx = get<1>(q.front()), cy = get<2>(q.front()); + q.pop(); + + int cur_dis = dis[index][cx][cy]; + if(index == k) return cur_dis; + + for(int d = 0; d < 4; d ++){ + int nx = cx + dirs[d][0], ny = cy + dirs[d][1]; + if(0 <= nx && nx < R && 0 <= ny && ny < C && dis[index][nx][ny] == -1){ + dis[index][nx][ny] = cur_dis + 1; + q.push({index, nx, ny}); + } + } + + if(matrix[cx][cy] == mantra[index] && dis[index + 1][cx][cy] == -1){ + dis[index + 1][cx][cy] = cur_dis + 1; + q.push({index + 1, cx, cy}); + } + } + + return -1; + } +}; + + +int main() { + + return 0; +} diff --git a/LC/LCP080/cpp-LCP080/CMakeLists.txt b/LC/LCP080/cpp-LCP080/CMakeLists.txt new file mode 100644 index 00000000..6a6bdfdb --- /dev/null +++ b/LC/LCP080/cpp-LCP080/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(D) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(D main.cpp) diff --git a/LC/LCP080/cpp-LCP080/main.cpp b/LC/LCP080/cpp-LCP080/main.cpp new file mode 100644 index 00000000..8fc959e8 --- /dev/null +++ b/LC/LCP080/cpp-LCP080/main.cpp @@ -0,0 +1,71 @@ +/// Source : https://leetcode.cn/problems/qoQAMX/ +/// Author : liuyubobobo +/// Time : 2023-05-07 + +#include +#include +#include +#include +#include +#include + +using namespace std; + + +/// Tree Encoding +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + string evolutionaryRecord(vector& parents) { + + int n = parents.size(); + vector> tree(n); + int root = -1; + for(int i = 0; i < n; i ++){ + if(parents[i] != -1) tree[parents[i]].push_back(i); + else root = i; + } + assert(root != -1); + + map, int> table; + vector tree2str(n); + string res = tree2str[encode(tree, root, table, tree2str)]; + while(res.back() == '1') res.pop_back(); + return res; + } + +private: + int encode(const vector>& tree, int u, map, int>& table, vector& tree2str){ + + vector subtrees; + for(int v: tree[u]){ + subtrees.push_back(encode(tree, v, table, tree2str)); + } + sort(subtrees.begin(), subtrees.end()); + + if(!table.count(subtrees)){ + table[subtrees] = table.size(); + + vector v; + for(int subtree: subtrees){ + v.push_back("0" + tree2str[subtree] + "1"); + } + sort(v.begin(), v.end()); + string res = ""; + for(const string& s: v) res += s; + tree2str[table[subtrees]] = res; + } + return table[subtrees]; + } +}; + + +int main() { + + vector parents1 = {-1, 0, 0, 2}; + cout << Solution().evolutionaryRecord(parents1) << endl; + // 00110 + + return 0; +} diff --git a/LC/LCP081/cpp-LCP081/CMakeLists.txt b/LC/LCP081/cpp-LCP081/CMakeLists.txt new file mode 100644 index 00000000..69cec56c --- /dev/null +++ b/LC/LCP081/cpp-LCP081/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.25) +project(E) + +set(CMAKE_CXX_STANDARD 17) + +add_executable(E main.cpp) diff --git a/LC/LCP081/cpp-LCP081/main.cpp b/LC/LCP081/cpp-LCP081/main.cpp new file mode 100644 index 00000000..2730c221 --- /dev/null +++ b/LC/LCP081/cpp-LCP081/main.cpp @@ -0,0 +1,133 @@ +/// Source : https://leetcode.cn/problems/ryfUiz/ +/// Author : liuyubobobo +/// Time : 2023-05-07 + +#include +#include + +using namespace std; + + +/// BIT +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +template +class BIT{ + +private: + int n; + vector data; + vector tree; + +public: + BIT(const vector& arr) : n(arr.size()), data(arr.begin(), arr.end()), tree(n + 1){ + + for(int i = 0; i < n; i ++) + tree[i + 1]= data[i]; + + for(int i = 1; i <= n; i ++){ + int parent = i + (i & -i); + if(parent <= n) tree[parent] += tree[i]; + } + } + + BIT(int n): n(n), data(n, 0), tree(n + 1, 0){} + + void add(int index, T v){ + assert(0 <= index && index < n); + + data[index] += v; + + index ++; + for(;index <= n; index += (index & -index)) + tree[index] += v; + } + + T query(int l, int r){ + assert(0 <= l && l < n); + assert(0 <= r && r < n); + assert(l <= r); + return prefix_sum(r + 1) - prefix_sum(l); + } + + void set(int index, T v){ + assert(0 <= index && index < n); + add(index, v - data[index]); + } + +private: + // r is 1-based + T prefix_sum(int r){ + + T res = 0; + for(; r; r -= (r & -r)) + res += tree[r]; + return res; + } +}; + +class Solution { +public: + int getNandResult(int k, vector& arr, vector>& operations) { + + int n = arr.size(); + vector> bits(k, BIT(n)); + for(int i = 0; i < n; i ++){ + int e = arr[i]; + for(int p = 0; p < k; p ++) + bits[p].set(i, (e >> p) & 1); + } + + int res = 0; + for(const vector& op: operations){ + int type = op[0]; + if(type == 0){ + int index = op[1], x = op[2]; + for(int p = 0; p < k; p ++) + bits[p].set(index, (x >> p) & 1); + } + else{ + int cnt = op[1], num = op[2]; + + int tres = 0; + for(int p = 0; p < k; p ++){ + int len = get_len(n, bits[p]); + long long x; + if(len == 0) x= 1; + else if(len == n){ + x = 1ll * cnt * n; + if((num >> p) & 1) x ++; + } + else x = len + 1; + + if(x % 2) tres |= (1 << p); + } + + res ^= tres; + } + } + return res; + } + +private: + int get_len(int n, BIT& bit){ + int l = 0, r = n; + while(l < r){ + int mid = (l + r) / 2; + if(bit.query(mid, n - 1) == n - mid) r = mid; + else l = mid + 1; + } + return n - l; + } +}; + + +int main() { + + vector arr1 = {1, 2}; + vector> op1 = {{1, 2, 3}, {0, 0, 3}, {1, 2, 2}}; + cout << Solution().getNandResult(3, arr1, op1) << endl; + // 2 + + return 0; +} diff --git a/LC/readme.md b/LC/readme.md new file mode 100644 index 00000000..bd507912 --- /dev/null +++ b/LC/readme.md @@ -0,0 +1,72 @@ +## 力扣中文站比赛 + +| ID | Problem | Official
Solution | C++ | Java | Python | +| --- | --- | :---: | :---: | :---: | :---: | +| | | | | | | +| LCP081 | [与非的谜题](https://leetcode.cn/problems/ryfUiz/) | [无] | [C++](LCP081/cpp-LCP081/) | | | +| LCP080 | [生物进化录](https://leetcode.cn/problems/qoQAMX/) | [无] | [C++](LCP080/cpp-LCP080/) | | | +| LCP079 | [提取咒文](https://leetcode.cn/problems/kjpLFZ/) | [无] | [C++](LCP079/cpp-LCP079/) | | | +| LCP078 | [城墙防线](https://leetcode.cn/problems/Nsibyl/) | [无] | [C++](LCP078/cpp-LCP078/) | | | +| LCP077 | [符文储备](https://leetcode.cn/problems/W2ZX4X/) | [无] | [C++](LCP077/cpp-LCP077/) | | | +| LCP076 | [魔法棋盘](https://leetcode.cn/problems/1ybDKD/) | [无] | [C++](LCP076/cpp-LCP076/) | | | +| LCP075 | [传送卷轴](https://leetcode.cn/problems/rdmXM7/) | [无] | [C++](LCP075/cpp-LCP075/) | | | +| LCP074 | [最强祝福力场](https://leetcode.cn/problems/xepqZ5/) | [无] | [C++](LCP074/cpp-LCP074/) | | | +| LCP073 | [探险营地](https://leetcode.cn/problems/0Zeoeg/) | [无] | [C++](LCP073/cpp-LCP073/) | | | +| LCP072 | [补给马车](https://leetcode.cn/problems/hqCnmP/) | [无] | [C++](LCP072/cpp-LCP072/) | | | +| | | | | | | +| LCP070 | [沙地治理](https://leetcode.cn/problems/XxZZjK/) | [无] | [C++](LCP070/cpp-LCP070/) | | | +| LCP069 | [Hello LeetCode!](https://leetcode.cn/problems/rMeRt2/) | [无] | [C++](LCP069/cpp-LCP069/) | | | +| LCP068 | [美观的花束](https://leetcode.cn/problems/1GxJYY/) | [无] | [C++](LCP068/cpp-LCP068/) | | | +| LCP067 | [装饰树](https://leetcode.cn/problems/KnLfVT/) | [无] | [C++](LCP067/cpp-LCP067/) | | | +| LCP066 | [最小展台数量](https://leetcode.cn/problems/600YaG/) | [无] | [C++](LCP066/cpp-LCP066/) | | | +| | | | | | | +| LCP057 | [打地鼠](https://leetcode-cn.com/problems/ZbAuEH/) | [无] | [C++](LCP057/cpp-LCP057/) | | | +| LCP056 | [信物传送](https://leetcode-cn.com/problems/6UEx57/) | [无] | [C++](LCP056/cpp-LCP056/) | | | +| LCP055 | [采集果实](https://leetcode-cn.com/problems/PTXy4P/) | [无] | [C++](LCP055/cpp-LCP055/) | | | +| | | | | | | +| LCP052 | [二叉搜索树染色](https://leetcode-cn.com/problems/QO5KpG/) | [无] [缺:非线段树做法] | [C++](LCP052/cpp-LCP052/) | | | +| LCP051 | [烹饪料理](https://leetcode-cn.com/problems/UEcfPD/) | [无] | [C++](LCP051/cpp-LCP051/) | | | +| LCP050 | [宝石补给](https://leetcode-cn.com/problems/WHnhjV/) | [无] | [C++](LCP050/cpp-LCP050/) | | | +| | | | | | | +| LCP048 | [无限棋局](https://leetcode-cn.com/problems/fsa7oZ/) | [无] | [C++](LCP048/cpp-LCP048/) | | | +| LCP047 | [入场安检](https://leetcode-cn.com/problems/oPs9Bm/) | [无] | [C++](LCP047/cpp-LCP047/) | | | +| LCP046 | [志愿者调配](https://leetcode-cn.com/problems/05ZEDJ/) | [无] | [C++](LCP046/cpp-LCP046/) | | | +| LCP045 | [自行车炫技赛场](https://leetcode-cn.com/problems/kplEvH/) | [无] | [C++](LCP045/cpp-LCP045/) | | | +| LCP044 | [开幕式焰火](https://leetcode-cn.com/problems/sZ59z6/) | [无] | [C++](LCP044/cpp-LCP044/) | | | +| LCP043 | [十字路口的交通](https://leetcode-cn.com/problems/Y1VbOX/) | [无] | [C++](LCP043/cpp-LCP043/) | | | +| LCP042 | [玩具套圈](https://leetcode-cn.com/problems/vFjcfV/) | [无] | [C++](LCP042/cpp-LCP042/) | | | +| LCP041 | [黑白翻转棋](https://leetcode-cn.com/problems/fHi6rV/) | [无] | [C++](LCP041/cpp-LCP041/)| | | +| LCP040 | [心算挑战](https://leetcode-cn.com/problems/uOAnQW/) | [无] | [C++](LCP040/cpp-LCP040/) | | | +| LCP039 | [无人机方阵](https://leetcode-cn.com/problems/0jQkd0/) | [无] | [C++](LCP039/cpp-LCP039/) | | | +| | | | | | | +| LCP029 | [乐团站位](https://leetcode-cn.com/problems/SNJvJP/) | [无] | [C++](LCP029/cpp-LCP029/) | | | +| LCP028 | [采购方案](https://leetcode-cn.com/problems/4xy4Wx/) | [无] | [C++](LCP028/cpp-LCP028/) | | | +| | | | | | | +| LCP025 | [古董键盘](https://leetcode-cn.com/problems/Uh984O/) | [无] | [C++](LCP025/cpp-LCP025/) | | | +| LCP024 | [数字游戏](https://leetcode-cn.com/problems/5TxKeK/) | [无] | [C++](LCP024/cpp-LCP024/) | | | +| LCP023 | [魔术排列](https://leetcode-cn.com/problems/er94lq/) | [无] | [C++](LCP023/cpp-LCP023/) | | | +| LCP022 | [黑白方格画](https://leetcode-cn.com/problems/ccw6C7/) | [无] | [C++](LCP022/cpp-LCP022/) | | | +| LCP021 | [追逐游戏](https://leetcode-cn.com/problems/Za25hA/) | [无] | [C++](LCP021/cpp-LCP021/) | | | +| LCP020 | [快速公交](https://leetcode-cn.com/problems/meChtZ/) | [无] | [C++](LCP020/cpp-LCP020/) | | | +| LCP019 | [秋叶收藏集](https://leetcode-cn.com/problems/UlBDOe/) | [题解](https://leetcode-cn.com/problems/UlBDOe/solution/qiu-xie-shou-cang-ji-by-leetcode-solution/) | [C++](LCP019/cpp-LCP019/) | | | +| LCP018 | [早餐组合](https://leetcode-cn.com/problems/2vYnGI/) | [无] | [C++](LCP018/cpp-LCP018/) | | | +| LCP017 | [速算机器人](https://leetcode-cn.com/problems/nGK0Fy/) | [无] | [C++](LCP017/cpp-LCP017/) | | | +| LCP016 | [游乐园的游览计划](https://leetcode-cn.com/problems/you-le-yuan-de-you-lan-ji-hua/) | [题解](https://leetcode-cn.com/problems/you-le-yuan-de-you-lan-ji-hua/solution/you-le-yuan-de-you-lan-ji-hua-tu-lun-jie-xi-by-l-2/) | [C++](LCP016/cpp-LCP016/) | | | +| LCP015 | [游乐园的迷宫](https://leetcode-cn.com/problems/you-le-yuan-de-mi-gong/) | [题解](https://leetcode-cn.com/problems/you-le-yuan-de-mi-gong/solution/you-le-yuan-de-mi-gong-tan-xin-si-lu-by-leetcode-s/) | [C++](LCP015/cpp-LCP015/) | | | +| LCP014 | [切分数组](https://leetcode-cn.com/problems/qie-fen-shu-zu/) | [题解](https://leetcode-cn.com/problems/qie-fen-shu-zu/solution/qie-fen-shu-zu-zhi-shu-shai-dp-by-leetcode-solutio/) | [C++](LCP014/cpp-LCP014/) | | | +| LCP013 | [寻宝](https://leetcode-cn.com/problems/xun-bao/) | [题解](https://leetcode-cn.com/problems/xun-bao/solution/xun-bao-bfs-dp-by-leetcode-solution/) | [C++](LCP013/cpp-LCP013/) | | | +| LCP012 | [小张刷题计划](https://leetcode-cn.com/problems/xiao-zhang-shua-ti-ji-hua/) | [题解](https://leetcode-cn.com/problems/xiao-zhang-shua-ti-ji-hua/solution/xiao-zhang-shua-ti-ji-hua-er-fen-cha-zhao-by-leetc/) | [C++](LCP012/cpp-LCP012/) | | | +| LCP011 | [期望个数统计](https://leetcode-cn.com/problems/qi-wang-ge-shu-tong-ji/) | [题解](https://leetcode-cn.com/problems/qi-wang-ge-shu-tong-ji/solution/qi-wang-ge-shu-tong-ji-qi-wang-ji-suan-yu-zheng-mi/) | [C++](LCP011/cpp-LCP011/) | | | +| LCP010 | [二叉树任务调度](https://leetcode-cn.com/problems/er-cha-shu-ren-wu-diao-du/) | [题解](https://leetcode-cn.com/problems/er-cha-shu-ren-wu-diao-du/solution/dfs-si-lu-dai-ma-he-zheng-ming-by-leetcode-solutio/) | [C++](LCP010/cpp-LCP010/) | | | +| LCP009 | [最小跳跃次数](https://leetcode-cn.com/problems/zui-xiao-tiao-yue-ci-shu/) | [题解](https://leetcode-cn.com/problems/zui-xiao-tiao-yue-ci-shu/solution/zui-xiao-tiao-yue-ci-shu-by-leetcode-solution/) | [C++](LCP009/cpp-LCP009/) | | | +| LCP008 | [剧情触发时间](https://leetcode-cn.com/problems/ju-qing-hong-fa-shi-jian/) | [题解](https://leetcode-cn.com/problems/ju-qing-hong-fa-shi-jian/solution/ju-qing-hong-fa-shi-jian-by-leetcode-solution/) | [C++](LCP008/cpp-LCP008/) | | | +| LCP007 | [传递信息](https://leetcode-cn.com/problems/chuan-di-xin-xi/) | [题解](https://leetcode-cn.com/problems/chuan-di-xin-xi/solution/chuan-di-xin-xi-by-leetcode-solution/) | [C++](LCP007/cpp-LCP007/) | | | +| LCP006 | [拿硬币](https://leetcode-cn.com/problems/na-ying-bi/) | [题解](https://leetcode-cn.com/problems/na-ying-bi/solution/na-ying-bi-by-leetcode-solution/) | [C++](LCP006/cpp-LCP006/) | +| LCP005 | [发 LeetCoin](https://leetcode-cn.com/problems/coin-bonus/) | [无] | [C++](LCP005/cpp-LCP005/) | | | +| LCP004 | [覆盖](https://leetcode-cn.com/problems/broken-board-dominoes/) | [无] | [C++](LCP004/cpp-LCP004/) | | | +| LCP003 | [机器人大冒险](https://leetcode-cn.com/problems/programmable-robot/) | [无] | [C++](LCP003/cpp-LCP003/) | | | +| LCP002 | [分式化简](https://leetcode-cn.com/problems/deep-dark-fraction/) | [无] | [C++](LCP002/cpp-LCP002/) | | | +| LCP001 | [猜数字](https://leetcode-cn.com/problems/guess-numbers/) | [无] | [C++](LCP001/cpp-LCP001/) | | | + + + diff --git a/Others/2022-autox2023/A/CMakeLists.txt b/Others/2022-autox2023/A/CMakeLists.txt new file mode 100644 index 00000000..415e0a92 --- /dev/null +++ b/Others/2022-autox2023/A/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/Others/2022-autox2023/A/main.cpp b/Others/2022-autox2023/A/main.cpp new file mode 100644 index 00000000..8aab483b --- /dev/null +++ b/Others/2022-autox2023/A/main.cpp @@ -0,0 +1,38 @@ +/// Source : https://leetcode.cn/contest/autox2023/problems/l9HbCJ/ +/// Author : liuyubobobo +/// Time : 2022-08-28 + +#include +#include +#include + +using namespace std; + + +/// Using Set +/// Time Complexity: O((num + |block|) * log(num)) +/// Space Complexity: O(num) +class Solution { +public: + int getLengthOfWaterfallFlow(int num, vector& block) { + + set> cols; // height -> col + for(int i = 0; i < num; i ++) + cols.insert({0, i}); + + for(int b: block){ + auto iter = cols.begin(); + int h = iter->first, c = iter->second; + cols.erase(iter); + cols.insert({h + b, c}); + } + + return cols.rbegin()->first; + } +}; + + +int main() { + + return 0; +} diff --git a/Others/2022-autox2023/B/CMakeLists.txt b/Others/2022-autox2023/B/CMakeLists.txt new file mode 100644 index 00000000..b1c82ab8 --- /dev/null +++ b/Others/2022-autox2023/B/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/Others/2022-autox2023/B/main.cpp b/Others/2022-autox2023/B/main.cpp new file mode 100644 index 00000000..08177c7c --- /dev/null +++ b/Others/2022-autox2023/B/main.cpp @@ -0,0 +1,65 @@ +/// Source : https://leetcode.cn/contest/autox2023/problems/8p6t8R/ +/// Author : liuyubobobo +/// Time : 2022-08-28 + +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: type 1, 2, 3: O(1) +/// type 4: O(maxv) +/// Space Complexity: O(maxv) +class Solution { +public: + vector honeyQuotes(vector>& handle) { + + vector f(101, 0); + int sz = 0; + long long sum = 0; + + vector res; + for(const vector& h: handle){ + int type = h[0]; + if(type == 1){ + f[h[1]] ++; + sz ++; + sum += h[1]; + } + else if(type == 2){ + f[h[1]] --; + sz --; + sum -= h[1]; + } + else if(type == 3){ + if(sz == 0) res.push_back(-1); + else res.push_back((double)sum / sz); + } + else{ + + if(sz == 0){ + res.push_back(-1); + continue; + } + + double mean = (double)sum / sz; + + double upper = 0.0; + for(int v = 0; v <= 100; v ++){ + if(f[v] == 0) continue; + upper += (v - mean) * (v - mean) * f[v]; + } + res.push_back(upper / sz); + } + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/Others/2022-autox2023/C/CMakeLists.txt b/Others/2022-autox2023/C/CMakeLists.txt new file mode 100644 index 00000000..d0dc1506 --- /dev/null +++ b/Others/2022-autox2023/C/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/Others/2022-autox2023/C/main.cpp b/Others/2022-autox2023/C/main.cpp new file mode 100644 index 00000000..1c2e4309 --- /dev/null +++ b/Others/2022-autox2023/C/main.cpp @@ -0,0 +1,42 @@ +/// Source : https://leetcode.cn/contest/autox2023/problems/BjAFy9/ +/// Author : liuyubobobo +/// Time : 2022-08-28 + +#include +#include +#include +#include + +using namespace std; + + +/// DP + Binary Search +/// Time Complexity: O(|days| * |tickets| * log|days|) +/// Space Complexity: O(|days|) +class Solution { +public: + long long minCostToTravelOnDays(vector& days, vector>& tickets) { + + int n = days.size(); + vector dp(n, LONG_LONG_MAX); + for(int i = n - 1; i >= 0; i --){ + long long cur = LONG_LONG_MAX; + for(const vector& ticket: tickets){ + long long price = ticket[1]; + int d = ticket[0]; + auto iter = lower_bound(days.begin() + i, days.end(), days[i] + d); + + if(iter == days.end()) cur = min(cur, price); + else cur = min(cur, price + dp[iter - days.begin()]); + } + dp[i] = cur; + } + return dp[0]; + } +}; + + +int main() { + + return 0; +} diff --git a/Others/2022-autox2023/D/CMakeLists.txt b/Others/2022-autox2023/D/CMakeLists.txt new file mode 100644 index 00000000..541b2eff --- /dev/null +++ b/Others/2022-autox2023/D/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main2.cpp) diff --git a/Others/2022-autox2023/D/main.cpp b/Others/2022-autox2023/D/main.cpp new file mode 100644 index 00000000..80ded1f5 --- /dev/null +++ b/Others/2022-autox2023/D/main.cpp @@ -0,0 +1,220 @@ +/// Source : https://leetcode.cn/contest/autox2023/problems/TcdlJS/ +/// Author : liuyubobobo +/// Time : 2022-08-29 + +#include +#include +#include +#include + +#define X real() +#define Y imag() + +using namespace std; + +typedef complex P; + + +/// 线段与圆相交,使用线段的参数方程 +/// x = t * x1 + (1 - t) * x2 +/// y = t * y1 + (1 - t) * y2 +/// t 在 [0, 1] 之间 +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) + +long long cross_product(P a, P b){ + return (conj(a) * b).Y; // a.X * b.Y - b.X * a.Y +} + +// 1 : left +// 0 : touch +// -1 : right +int test_point_loc(P p, P s1, P s2){ + double res = cross_product(p - s1, p - s2); + if(res == 0ll) return 0; + return res > 0 ? 1 : -1; +} + +bool seg_intersect(long long x1, long long y1, long long x2, long long y2, + long long x3, long long y3, long long x4, long long y4){ + + P p1 = {x1, y1}, p2 = {x2, y2}; + P p3 = {x3, y3}, p4 = {x4, y4}; + + int loc1 = test_point_loc(p1, p3, p4), loc2 = test_point_loc(p2, p3, p4); + int loc3 = test_point_loc(p3, p1, p2), loc4 = test_point_loc(p4, p1, p2); + if(loc1 == 0 && min(x3, x4) <= x1 && x1 <= max(x3, x4) + && min(y3, y4) <= y1 && y1 <= max(y3, y4)){ + return true; + } + if(loc2 == 0 && min(x3, x4) <= x2 && x2 <= max(x3, x4) + && min(y3, y4) <= y2 && y2 <= max(y3, y4)){ + return true; + } + if(loc3 == 0 && min(x1, x2) <= x3 && x3 <= max(x1, x2) + && min(y1, y2) <= y3 && y3 <= max(y1, y2)){ + return true; + } + if(loc4 == 0 && min(x1, x2) <= x4 && x4 <= max(x1, x2) + && min(y1, y2) <= y4 && y4 <= max(y1, y2)){ + return true; + } + + if(!loc1 || !loc2 || !loc3 || !loc4){ + return false; + } + + if(loc1 * loc2 > 0 || loc3 * loc4 > 0) + return false; + + return true; +} + +class UF{ + +private: + vector parent; + +public: + UF(int n) : parent(n){ + for(int i = 0 ; i < n ; i ++) + parent[i] = i; + } + + int find(int p){ + if(p != parent[p]) + parent[p] = find(parent[p]); + return parent[p]; + } + + bool is_connected(int p, int q){ + return find(p) == find(q); + } + + void union_elements(int p, int q){ + + int p_root = find(p), q_root = find(q); + + if(p_root == q_root) return; + + parent[p_root] = q_root; + } +}; + +class Solution { +public: + vector antPass(vector>& geometry, vector>& path) { + + int n = geometry.size(); + UF uf(n); + + for(int i = 0; i < n; i ++) + for(int j = i + 1; j < n; j ++){ + + if(uf.is_connected(i, j)) continue; + + vector v1 = geometry[i]; + vector v2 = geometry[j]; + if(v1.size() > v2.size()) swap(v1, v2); + + // v1.size() <= v2.size() + if(intersect(v1, v2)) + uf.union_elements(i, j); + } + + vector res(path.size()); + for(int i = 0; i < path.size(); i ++) + res[i] = uf.is_connected(path[i][0], path[i][1]); + return res; + } + +private: + bool intersect(const vector& v1, const vector& v2){ + + if(v1.size() == 3 && v2.size() == 3) + return circle_intersect(v1[0], v1[1], v1[2], v2[0], v2[1], v2[2]); + + if(v1.size() == 4 && v2.size() == 4) + return seg_intersect(v1[0], v1[1], v1[2], v1[3], v2[0], v2[1], v2[2], v2[3]); + + return circle_seg_intersect(v1[0], v1[1], v1[2], v2[0], v2[1], v2[2], v2[3]); + } + + int sign(long long x){ + if(x > 0) return 1; + if(x == 0) return 0; + return -1; + } + + bool circle_seg_intersect(long long x0, long long y0, long long r0, + long long x1, long long y1, long long x2, long long y2){ + + long long a = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2); + long long b = 2ll * (x1 - x2) * (x2 - x0) + 2ll * (y1 - y2) * (y2 - y0); + long long c = (x2 - x0) * (x2 - x0) + (y2 - y0) * (y2 - y0) - r0 * r0; + + if(a == 0 && b == 0) return c == 0; + + if(a == 0){ + if(b < 0) b = -b, c = -c; + return 0 <= -c && -c <= b; + } + + if(a < 0){ + a = -a, b = -b, c = -c; + } + + long double delta = (long double)b * b - 4.0 * (long double)a * c; + if(delta < 0) return false; + + long double t1 = ((long double)(-b) - sqrt(delta)) / (2.0 * (long double)a); + if(0.0 <= t1 && t1 <= 1.0) return true; + + long double t2 = ((long double)(-b) + sqrt(delta)) / (2.0 * (long double)a); + if(0.0 <= t2 && t2 <= 1.0) return true; + + return false; + } + + bool circle_intersect(long long x1, long long y1, long long r1, + long long x2, long long y2, long long r2){ + + long long d2 = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2); + return (r1 - r2) * (r1 - r2) <= d2 && d2 <= (r1 + r2) * (r1 + r2); + } +}; + + +void print_vec(const vector& res){ + for(bool e: res) cout << e << ' '; cout << '\n'; +} + +int main(){ + + vector> g1 = {{2, 5, 7, 3}, {1, 1, 4, 2}, {4, 3, 2}}; + vector> p1 = {{0, 1}, {1, 2}, {0, 2}}; + print_vec(Solution().antPass(g1, p1)); + // 1 1 1 + + vector> g2 = {{4, 1, 1}, {3, 2, 1}, {1, 4, 5, 4}}; + vector> p2 = {{0, 1}, {2, 0}}; + print_vec(Solution().antPass(g2, p2)); + // 1 0 + + vector> g3 = {{5, 6, 5, 8}, {4, 3, 6, 4}, {2, 6, 5, 6}, {0, 5, 0, 6}, {4, 0, 6, 0}}; + vector> p3 = {{2, 0}, {2, 4}}; + print_vec(Solution().antPass(g3, p3)); + // 1 0 + + vector> g4 = {{3, 2, 6, 2}, {9, 0, 10, 0}, {3, 0, 6, 0}, {7, 2, 9, 3}, {4, 1, 5, 2}}; + vector> p4 = {{0, 1}, {3, 4}, {0, 3}}; + print_vec(Solution().antPass(g4, p4)); + // 0 0 0 + + vector> g5 = {{8, 8, 6}, {1, 1, 1, 2}, {1, 1, 3, 2}, {4, 3, 4, 4}, {2, 1, 5, 3}}; + vector> p5 = {{0, 4}, {3, 1}}; + print_vec(Solution().antPass(g5, p5)); + // 1 0 + + return 0; +} diff --git a/Others/2022-autox2023/D/main2.cpp b/Others/2022-autox2023/D/main2.cpp new file mode 100644 index 00000000..59ca3775 --- /dev/null +++ b/Others/2022-autox2023/D/main2.cpp @@ -0,0 +1,210 @@ +/// Source : https://leetcode.cn/contest/autox2023/problems/TcdlJS/ +/// Author : liuyubobobo +/// Time : 2022-08-29 + +#include +#include +#include +#include + +#define X real() +#define Y imag() + +using namespace std; + +typedef complex P; + + +/// 线段与圆相交,使用条件判断 +/// 参考这里:https://blog.csdn.net/SongBai1997/article/details/86599879 +/// Time Complexity: O(n^2) +/// Space Complexity: O(n) + +long long cross_product(P a, P b){ + return (conj(a) * b).Y; // a.X * b.Y - b.X * a.Y +} + +// 1 : left +// 0 : touch +// -1 : right +int test_point_loc(P p, P s1, P s2){ + double res = cross_product(p - s1, p - s2); + if(res == 0ll) return 0; + return res > 0 ? 1 : -1; +} + +bool seg_intersect(long long x1, long long y1, long long x2, long long y2, + long long x3, long long y3, long long x4, long long y4){ + + P p1 = {x1, y1}, p2 = {x2, y2}; + P p3 = {x3, y3}, p4 = {x4, y4}; + + int loc1 = test_point_loc(p1, p3, p4), loc2 = test_point_loc(p2, p3, p4); + int loc3 = test_point_loc(p3, p1, p2), loc4 = test_point_loc(p4, p1, p2); + if(loc1 == 0 && min(x3, x4) <= x1 && x1 <= max(x3, x4) + && min(y3, y4) <= y1 && y1 <= max(y3, y4)){ + return true; + } + if(loc2 == 0 && min(x3, x4) <= x2 && x2 <= max(x3, x4) + && min(y3, y4) <= y2 && y2 <= max(y3, y4)){ + return true; + } + if(loc3 == 0 && min(x1, x2) <= x3 && x3 <= max(x1, x2) + && min(y1, y2) <= y3 && y3 <= max(y1, y2)){ + return true; + } + if(loc4 == 0 && min(x1, x2) <= x4 && x4 <= max(x1, x2) + && min(y1, y2) <= y4 && y4 <= max(y1, y2)){ + return true; + } + + if(!loc1 || !loc2 || !loc3 || !loc4){ + return false; + } + + if(loc1 * loc2 > 0 || loc3 * loc4 > 0) + return false; + + return true; +} + +class UF{ + +private: + vector parent; + +public: + UF(int n) : parent(n){ + for(int i = 0 ; i < n ; i ++) + parent[i] = i; + } + + int find(int p){ + if(p != parent[p]) + parent[p] = find(parent[p]); + return parent[p]; + } + + bool is_connected(int p, int q){ + return find(p) == find(q); + } + + void union_elements(int p, int q){ + + int p_root = find(p), q_root = find(q); + + if(p_root == q_root) return; + + parent[p_root] = q_root; + } +}; + +class Solution { +public: + vector antPass(vector>& geometry, vector>& path) { + + int n = geometry.size(); + UF uf(n); + + for(int i = 0; i < n; i ++) + for(int j = i + 1; j < n; j ++){ + + if(uf.is_connected(i, j)) continue; + + vector v1 = geometry[i]; + vector v2 = geometry[j]; + if(v1.size() > v2.size()) swap(v1, v2); + + // v1.size() <= v2.size() + if(intersect(v1, v2)) + uf.union_elements(i, j); + } + + vector res(path.size()); + for(int i = 0; i < path.size(); i ++) + res[i] = uf.is_connected(path[i][0], path[i][1]); + return res; + } + +private: + bool intersect(const vector& v1, const vector& v2){ + + if(v1.size() == 3 && v2.size() == 3) + return circle_intersect(v1[0], v1[1], v1[2], v2[0], v2[1], v2[2]); + + if(v1.size() == 4 && v2.size() == 4) + return seg_intersect(v1[0], v1[1], v1[2], v1[3], v2[0], v2[1], v2[2], v2[3]); + + return circle_seg_intersect(v1[0], v1[1], v1[2], v2[0], v2[1], v2[2], v2[3]); + } + + int sign(long long x){ + if(x > 0) return 1; + if(x == 0) return 0; + return -1; + } + + bool circle_seg_intersect(long long x0, long long y0, long long r0, + long long x1, long long y1, long long x2, long long y2){ + + bool flag1 = (x1 - x0) * (x1 - x0) + (y1 - y0) * (y1 - y0) <= r0 * r0; + bool flag2 = (x2 - x0) * (x2 - x0) + (y2 - y0) * (y2 - y0) <= r0 * r0; + + if(flag1 && flag2) return false; + if((flag1 && !flag2) || (!flag1 && flag2)) return true; + + long long A = y2 - y1; + long long B = x1 - x2; + long long C = x2 * y1 - y2 * x1; + + if((long double)(A * x0 + B * y0 + C) * (A * x0 + B * y0 + C) > (long double)r0 * r0 * (A * A + B * B)) + return false; + + long long a1 = (x0 - x1) * (x2 - x1) + (y0 - y1) * (y2 - y1); + long long a2 = (x0 - x2) * (x1 - x2) + (y0 - y2) * (y1 - y2); + if(a1 > 0 && a2 > 0) return true; + return false; + } + + bool circle_intersect(long long x1, long long y1, long long r1, + long long x2, long long y2, long long r2){ + + long long d2 = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2); + return (r1 - r2) * (r1 - r2) <= d2 && d2 <= (r1 + r2) * (r1 + r2); + } +}; + + +void print_vec(const vector& res){ + for(bool e: res) cout << e << ' '; cout << '\n'; +} + +int main(){ + + vector> g1 = {{2, 5, 7, 3}, {1, 1, 4, 2}, {4, 3, 2}}; + vector> p1 = {{0, 1}, {1, 2}, {0, 2}}; + print_vec(Solution().antPass(g1, p1)); + // 1 1 1 + + vector> g2 = {{4, 1, 1}, {3, 2, 1}, {1, 4, 5, 4}}; + vector> p2 = {{0, 1}, {2, 0}}; + print_vec(Solution().antPass(g2, p2)); + // 1 0 + + vector> g3 = {{5, 6, 5, 8}, {4, 3, 6, 4}, {2, 6, 5, 6}, {0, 5, 0, 6}, {4, 0, 6, 0}}; + vector> p3 = {{2, 0}, {2, 4}}; + print_vec(Solution().antPass(g3, p3)); + // 1 0 + + vector> g4 = {{3, 2, 6, 2}, {9, 0, 10, 0}, {3, 0, 6, 0}, {7, 2, 9, 3}, {4, 1, 5, 2}}; + vector> p4 = {{0, 1}, {3, 4}, {0, 3}}; + print_vec(Solution().antPass(g4, p4)); + // 0 0 0 + + vector> g5 = {{8, 8, 6}, {1, 1, 1, 2}, {1, 1, 3, 2}, {4, 3, 4, 4}, {2, 1, 5, 3}}; + vector> p5 = {{0, 4}, {3, 1}}; + print_vec(Solution().antPass(g5, p5)); + // 1 0 + + return 0; +} diff --git a/Others/2022-hhrc/A/CMakeLists.txt b/Others/2022-hhrc/A/CMakeLists.txt new file mode 100644 index 00000000..415e0a92 --- /dev/null +++ b/Others/2022-hhrc/A/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/Others/2022-hhrc/A/main.cpp b/Others/2022-hhrc/A/main.cpp new file mode 100644 index 00000000..f186aa2c --- /dev/null +++ b/Others/2022-hhrc/A/main.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.cn/contest/hhrc2022/problems/o0Ma2v/ +/// Author : liuyubobobo +/// Time : 2022-10-03 + +#include +#include +#include + +using namespace std; + + +/// Using PQ +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { +public: + int lastMaterial(vector& material) { + + priority_queue pq; + for(int e: material) pq.push(e); + + while(pq.size() >= 2){ + int a = pq.top(); pq.pop(); + int b = pq.top(); pq.pop(); + if(a - b) pq.push(a - b); + } + return pq.empty() ? 0 : pq.top(); + } +}; + +int main() { + + return 0; +} diff --git a/Others/2022-hhrc/B/CMakeLists.txt b/Others/2022-hhrc/B/CMakeLists.txt new file mode 100644 index 00000000..b1c82ab8 --- /dev/null +++ b/Others/2022-hhrc/B/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/Others/2022-hhrc/B/main.cpp b/Others/2022-hhrc/B/main.cpp new file mode 100644 index 00000000..97cc6a6a --- /dev/null +++ b/Others/2022-hhrc/B/main.cpp @@ -0,0 +1,142 @@ +/// Source : https://leetcode.cn/contest/hhrc2022/problems/0Wx4Pc/ +/// Author : liuyubobobo +/// Time : 2022-10-03 + +#include +#include + +using namespace std; + + +/// Using Segment Tree +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +template +class SegmentTree{ + +private: + int n; + vector data, tree; + T (*combine)(T a, T b); + +public: + SegmentTree(const vector& data, T (*combine)(T a, T b)): n(data.size()), data(data), tree(4 * n, 0){ + this->combine = combine; + buildSegTree(0, 0, n - 1); + } + + SegmentTree(int n, T (*combine)(T a, T b)): n(n), data(n, 0), tree(4 * n, 0){ + this->combine = combine; + } + + void update(int index, T value){ + if(data[index] == value) return; + data[index] = value; + update(0, 0, n - 1, index, value); + } + + T query(int index){ + assert(0 <= index && index < n); + return data[index]; + } + + T query(int l, int r){ + assert(l <= r); + assert(0 <= l && l < n); + assert(0 <= r && r < n); + return query(0, 0, n - 1, l, r); + } + +private: + void buildSegTree(int treeID, int l, int r){ + + if(l == r){ + tree[treeID] = data[l]; + return; + } + + int mid = (l + r) / 2; + buildSegTree(treeID * 2 + 1, l, mid); + buildSegTree(treeID * 2 + 2, mid + 1, r); + tree[treeID] = combine(tree[treeID * 2 + 1], tree[treeID * 2 + 2]); + return; + } + + void update(int treeID, int l, int r, int index, T value){ + + if(l == r){ + assert(l == index); + tree[treeID] = value; + return; + } + + int mid = (l + r) / 2; + if(index <= mid) update(treeID * 2 + 1, l, mid, index, value); + else update(treeID * 2 + 2, mid + 1, r, index, value); + + tree[treeID] = combine(tree[treeID * 2 + 1], tree[treeID * 2 + 2]); + return; + } + + T query(int treeID, int l, int r, int ql, int qr){ + + if(ql == l && qr == r) + return tree[treeID]; + + int mid = (l + r) / 2; + if(qr <= mid) return query(treeID * 2 + 1, l, mid, ql, qr); + else if(ql > mid) return query(treeID * 2 + 2, mid + 1, r, ql, qr); + + T resl = query(treeID * 2 + 1, l, mid, ql, mid); + T resr = query(treeID * 2 + 2, mid + 1, r, mid + 1, qr); + return combine(resl, resr); + } +}; + +class Solution { +public: + int longestESR(vector& sales) { + + int n = sales.size(); + vector data(n); + for(int i = 0; i < n; i ++) data[i] = sales[i] > 8 ? 1 : -1; + + vector presum(n + 1, 0); + for(int i = 0; i < n; i ++) presum[i + 1] = presum[i] + data[i]; + + int OFFSET = n + 5; + SegmentTree seg_tree(vector(2 * n + 11, -1), [](int a, int b){return max(a, b);}); + seg_tree.update(presum.back() + OFFSET, n); + int res = 0; + for(int l = n - 1; l >= 0; l --){ + int cur = presum[l]; + int max_r = seg_tree.query(cur + 1 + OFFSET, 2 * n + 10); + res = max(res, max_r - l); + + seg_tree.update(cur + OFFSET, max(seg_tree.query(cur + OFFSET), l)); + } + return res; + } +}; + + +int main() { + + vector sales1 = {10,2,1,4,3,9,6,9,9}; + cout << Solution().longestESR(sales1) << '\n'; + // 5 + + vector sales2 = {5,6,7}; + cout << Solution().longestESR(sales2) << '\n'; + // 0 + + vector sales3 = {6,9,6}; + cout << Solution().longestESR(sales3) << '\n'; + // 1 + + vector sales4 = {9,9,6}; + cout << Solution().longestESR(sales4) << '\n'; + // 3 + + return 0; +} diff --git a/Others/2022-hhrc/C/CMakeLists.txt b/Others/2022-hhrc/C/CMakeLists.txt new file mode 100644 index 00000000..d0dc1506 --- /dev/null +++ b/Others/2022-hhrc/C/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/Others/2022-hhrc/C/main.cpp b/Others/2022-hhrc/C/main.cpp new file mode 100644 index 00000000..bb0077c8 --- /dev/null +++ b/Others/2022-hhrc/C/main.cpp @@ -0,0 +1,58 @@ +/// Source : https://leetcode.cn/contest/hhrc2022/problems/VAc7h3/ +/// Author : liuyubobobo +/// Time : 2022-10-03 + +#include +#include +#include + +using namespace std; + + +/// Hash +/// Time Complexity: O(n) +/// Space Complexity: O(n^2) + +/// 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 lightDistribution(TreeNode* root) { + + map> m; + dfs(root, m); + + vector res; + for(const pair>& p: m) + if(p.second.size() > 1) res.push_back(p.second[0]); + return res; + } + +private: + string dfs(TreeNode* node, map>& m){ + + if(node == nullptr) return "(null)"; + + string hash = "(" + to_string(node->val); + hash += dfs(node->left, m); + hash += dfs(node->right, m); + hash += ")"; + + m[hash].push_back(node); + return hash; + } +}; + + +int main() { + + return 0; +} diff --git a/Others/2022-hhrc/D/CMakeLists.txt b/Others/2022-hhrc/D/CMakeLists.txt new file mode 100644 index 00000000..8148fadd --- /dev/null +++ b/Others/2022-hhrc/D/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) diff --git a/Others/2022-hhrc/D/main.cpp b/Others/2022-hhrc/D/main.cpp new file mode 100644 index 00000000..6a8ab801 --- /dev/null +++ b/Others/2022-hhrc/D/main.cpp @@ -0,0 +1,72 @@ +/// Source : https://leetcode.cn/contest/hhrc2022/problems/wFtovi/ +/// Author : liuyubobobo +/// Time : 2022-10-04 + +#include +#include +#include + +using namespace std; + + +/// Tree DP +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// 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 { + +private: + const int INF = INT_MAX / 2; + +public: + int minSupplyStationNumber(TreeNode* root) { + + map, int> dp; + return dfs(root, 0, 0, dp); + } + +private: + int dfs(TreeNode* node, int covered, int must_set, map, int>& dp){ + + if(!node) return must_set ? INF : 0; + + tuple state = {node, covered, must_set}; + auto iter = dp.find(state); + if(iter != dp.end()) return iter->second; + + int res = INF; + if(must_set){ + res = min(res, 1 + dfs(node->left, 1, 0, dp) + dfs(node->right, 1, 0, dp)); + } + else if(covered){ + res = min(res, 1 + dfs(node->left, 1, 0, dp) + dfs(node->right, 1, 0, dp)); + res = min(res, dfs(node->left, 0, 0, dp) + dfs(node->right, 0, 0, dp)); + } + else{ + res = min(res, 1 + dfs(node->left, 1, 0, dp) + dfs(node->right, 1, 0, dp)); + if(node->left){ + res = min(res, dfs(node->left, 1, 1, dp) + dfs(node->right, 0, 0, dp)); + res = min(res, dfs(node->left, 1, 1, dp) + dfs(node->right, 1, 1, dp)); + } + if(node->right){ + res = min(res, dfs(node->left, 0, 0, dp) + dfs(node->right, 1, 1, dp)); + res = min(res, dfs(node->left, 1, 1, dp) + dfs(node->right, 1, 1, dp)); + } + } + return dp[state] = res; + } +}; + + +int main() { + + return 0; +} diff --git a/Others/2022-sf-tech/A/CMakeLists.txt b/Others/2022-sf-tech/A/CMakeLists.txt new file mode 100644 index 00000000..fe8bfd9f --- /dev/null +++ b/Others/2022-sf-tech/A/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/Others/2022-sf-tech/A/main.cpp b/Others/2022-sf-tech/A/main.cpp new file mode 100644 index 00000000..84c1fd41 --- /dev/null +++ b/Others/2022-sf-tech/A/main.cpp @@ -0,0 +1,92 @@ +/// Source : https://leetcode.cn/contest/sf-tech/problems/EUpcmh/ +/// Author : liuyubobobo +/// Time : 2022-06-23 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// DFS Cycle Finding +/// Time Complexity: O(|s| + n) +/// Space Compelxity: O(n) +class Solution { +public: + bool hasCycle(string graph) { + + vector edges_str = get_edges_str(graph); + + map> g; + for(const string& edge_str: edges_str){ + int u, v; + get_uv_from_edge_str(edge_str, u, v); + g[u].insert(v); + } + + set visited; + bool has_cycle = false; + for(const pair>& p: g){ + int u = p.first; + if(!visited.count(u)){ + set stack; + has_cycle = dfs(g, u, stack, visited); + if(has_cycle) break; + } + } + return has_cycle; + } + +private: + bool dfs(const map>& g, int u, set& stack, set& visited){ + + stack.insert(u); + if(g.count(u)){ + for(int v: g.at(u)){ + if(stack.count(v)) return true; + if(!visited.count(v) && dfs(g, v, stack, visited)) return true; + } + } + stack.erase(u); + return false; + } + + void get_uv_from_edge_str(const string& e, int& u, int& v){ + + int arrow_pos = e.find("->"); + assert(arrow_pos != string::npos); + + u = atoi(e.substr(0, arrow_pos).c_str()); + v = atoi(e.substr(arrow_pos + 2).c_str()); + } + + vector get_edges_str(const string& g){ + + vector res; + for(int start = 0, i = 1; i <= g.size(); i ++) + if(i == g.size() || g[i] == ','){ + res.push_back(g.substr(start, i - start)); + start = i + 1; + i = start + 1; + } + return res; + } +}; + + +int main() { + + cout << Solution().hasCycle("1->2,2->3,3->1") << '\n'; + // 1 + + cout << Solution().hasCycle("1->4,2->5,3->6,3->7,4->8,5->8,5->9,6->9,6->11,7->11,8->12,9->12,9->13,10->13,10->14,11->10,11->14") << '\n'; + // 0 + + cout << Solution().hasCycle("1->4,2->5,3->6,3->7,4->8,5->8,5->9,6->9,6->11,7->11,8->12,9->12,9->13,10->6,10->13,10->14,11->10,11->14") << '\n'; + // 1 + + return 0; +} diff --git a/Others/2022-sf-tech/B/CMakeLists.txt b/Others/2022-sf-tech/B/CMakeLists.txt new file mode 100644 index 00000000..8494c320 --- /dev/null +++ b/Others/2022-sf-tech/B/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/Others/2022-sf-tech/B/main.cpp b/Others/2022-sf-tech/B/main.cpp new file mode 100644 index 00000000..c9db26c1 --- /dev/null +++ b/Others/2022-sf-tech/B/main.cpp @@ -0,0 +1,37 @@ +/// Source : https://leetcode.cn/contest/sf-tech/problems/cINqyA/ +/// Author : liuyubobobo +/// Time : 2022-06-23 + +#include +#include +#include + +using namespace std; + + +/// Backpack DP +/// Time complexity: O(C * n) +/// Space Complexity: O(C) +class Solution { +public: + int minRemainingSpace(vector& V, int C) { + + vector dp(C + 1, false); + dp[0] = true; + for(int v: V){ + for(int c = C; c >= v; c --) + if(dp[c - v]) dp[c] = true; + } + + for(int i = C; i >= 0; i --) + if(dp[i]) return C - i; + assert(false); + return -1; + } +}; + + +int main() { + + return 0; +} diff --git a/Others/2022-sf-tech/B/main2.cpp b/Others/2022-sf-tech/B/main2.cpp new file mode 100644 index 00000000..0a6b6fd2 --- /dev/null +++ b/Others/2022-sf-tech/B/main2.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.cn/contest/sf-tech/problems/cINqyA/ +/// Author : liuyubobobo +/// Time : 2022-06-23 + +#include +#include +#include + +using namespace std; + + +/// Meet in the middle +/// Time complexity: O(n * 2^(n / 2)) +/// Space Complexity: O(2^(n/2)) +class Solution { +public: + int minRemainingSpace(vector& V, int C) { + + int n = V.size(); + if(n == 1) return max(C - V[0], 0); + + int left_n = n / 2, right_n = n - left_n; + vector left(1 << left_n, 0), right(1 << right_n, 0); + for(int state = 1; state < (1 << left_n); state ++){ + int p = __builtin_ffs(state) - 1; + left[state] = left[state - (1 << p)] + V[p]; + } + for(int state = 1; state < (1 << right_n); state ++){ + int p = __builtin_ffs(state) - 1; + right[state] = right[state - (1 << p)] + V[left_n + p]; + } + + set left_set(left.begin(), left.end()); + set right_set(right.begin(), right.end()); + + int res = C; + for(int e1: left){ + if(e1 > C) break; + auto iter = right_set.upper_bound(C - e1); + iter --; + res = min(res, C - e1 - *iter); + } + + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/Others/2022-sf-tech/C/CMakeLists.txt b/Others/2022-sf-tech/C/CMakeLists.txt new file mode 100644 index 00000000..830d3093 --- /dev/null +++ b/Others/2022-sf-tech/C/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/Others/2022-sf-tech/C/main.cpp b/Others/2022-sf-tech/C/main.cpp new file mode 100644 index 00000000..a387a4fa --- /dev/null +++ b/Others/2022-sf-tech/C/main.cpp @@ -0,0 +1,34 @@ +/// Source : https://leetcode.cn/contest/sf-tech/problems/8oimK4/ +/// Author : liuyubobobo +/// Time : 2022-06-23 + +#include +#include + +using namespace std; + + +/// Linear Scan +/// Time Compelxity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int findMaxCI(vector& nums) { + + int n = nums.size(); + int res = 0; + for(int start = 0, i = 1; i <= n; i ++) + if(i == n || nums[i] <= nums[i - 1]){ + res = max(res, i - start); + start = i; + i = start; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/Others/2022-sf-tech/D/CMakeLists.txt b/Others/2022-sf-tech/D/CMakeLists.txt new file mode 100644 index 00000000..9a6c5c78 --- /dev/null +++ b/Others/2022-sf-tech/D/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) diff --git a/Others/2022-sf-tech/D/main.cpp b/Others/2022-sf-tech/D/main.cpp new file mode 100644 index 00000000..4d5e2c9a --- /dev/null +++ b/Others/2022-sf-tech/D/main.cpp @@ -0,0 +1,116 @@ +/// Source : https://leetcode.cn/contest/sf-tech/problems/uWWzsv/ +/// Author : liuyubobobo +/// Time : 2022-06-23 + +#include +#include +#include + +#define X real() +#define Y imag() + +using namespace std; + + +typedef double C; +typedef complex P; + +const double EPS = 1e-6; + +/// Cross Product +/// Time Complexity: O(t) +/// Space Complexity: O(1) +C cross_product(P a, P b){ + return (conj(a) * b).Y; // a.X * b.Y - b.X * a.Y +} + +bool is_zero(C x){ + return abs(x) < EPS; +} +// 1 : left +// 0 : touch +// -1 : right +int test_point_loc(P p, P s1, P s2){ + C res = cross_product(p - s1, p - s2); + if(is_zero(res)) return 0; + return res > 0 ? 1 : -1; +} + +// 0 : on boundary +// 1 : intersection +// -1 : no intersection +int intersect(P p1, P p2, P p3, P p4){ + + C x1 = p1.X, y1 = p1.Y, x2 = p2.X, y2 = p2.Y, x3 = p3.X, y3 = p3.Y, x4 = p4.X, y4 = p4.Y; + + int loc1 = test_point_loc(p1, p3, p4), loc2 = test_point_loc(p2, p3, p4); + int loc3 = test_point_loc(p3, p1, p2), loc4 = test_point_loc(p4, p1, p2); + + if(loc1 == 0 && min(x3, x4) <= x1 && x1 <= max(x3, x4) + && min(y3, y4) <= y1 && y1 <= max(y3, y4)) return 0; + + if(loc2 == 0 && min(x3, x4) <= x2 && x2 <= max(x3, x4) + && min(y3, y4) <= y2 && y2 <= max(y3, y4)) return 0; + + if(loc3 == 0 && min(x1, x2) <= x3 && x3 <= max(x1, x2) + && min(y1, y2) <= y3 && y3 <= max(y1, y2)) return 0; + + if(loc4 == 0 && min(x1, x2) <= x4 && x4 <= max(x1, x2) + && min(y1, y2) <= y4 && y4 <= max(y1, y2)) return 0; + + if(!loc1 || !loc2 || !loc3 || !loc4) return -1; + + if(loc1 * loc2 > 0 || loc3 * loc4 > 0) return -1; + return 1; +} + +//long long gcd(long long a, long long b) +//{ +// if(a > b) swap(a, b); +// if (a == 0) return b; +// return gcd(b % a, a); +//} + +int in_polygon(int n, const vector

& polygon, P p){ + + for(int i = 1; i < n; i ++){ + int loc = test_point_loc(p, polygon[i], polygon[i - 1]); + if(loc == 0 && min(polygon[i].X, polygon[i - 1].X) <= p.X && p.X <= max(polygon[i].X, polygon[i - 1].X) + && min(polygon[i].Y, polygon[i - 1].Y) <= p.Y && p.Y <= max(polygon[i].Y, polygon[i - 1].Y)) + return 0; + } + + int loc = test_point_loc(p, polygon[n - 1], polygon[0]); + if(loc == 0 && min(polygon[n - 1].X, polygon[0].X) <= p.X && p.X <= max(polygon[n - 1].X, polygon[0].X) + && min(polygon[n - 1].Y, polygon[0].Y) <= p.Y && p.Y <= max(polygon[n - 1].Y, polygon[0].Y)) + return 0; + + // 保证 p2.X - p1.X 和 p2.Y - p1.Y 互质, + double INF = 1e9 + 7; + + P p1 = p, p2 = {p.X + INF, p.Y + 1}; + int cnt = 0; + for(int i = 1; i < n; i ++) + cnt += intersect(p1, p2, polygon[i], polygon[i - 1]) >= 0; + cnt += intersect(p1, p2, polygon[n - 1], polygon[0]) >= 0; + + return (cnt & 1) ? -1 : 1; +} + +class Solution { +public: + bool isPointInPolygon(double x, double y, vector& coords) { + + vector

polygon; + for(int i = 0; i < coords.size(); i += 2) + polygon.push_back({coords[i], coords[i + 1]}); + + P p = {x, y}; + return in_polygon(polygon.size(), polygon, p) < 0; + } +}; + +int main() { + + return 0; +} diff --git a/Others/2022-sf-tech/E/CMakeLists.txt b/Others/2022-sf-tech/E/CMakeLists.txt new file mode 100644 index 00000000..bfc48c82 --- /dev/null +++ b/Others/2022-sf-tech/E/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(E) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(E main.cpp) diff --git a/Others/2022-sf-tech/E/main.cpp b/Others/2022-sf-tech/E/main.cpp new file mode 100644 index 00000000..6b30ee89 --- /dev/null +++ b/Others/2022-sf-tech/E/main.cpp @@ -0,0 +1,69 @@ +/// Source : https://leetcode.cn/contest/sf-tech/problems/BN8jAm/ +/// Author : liuyubobobo +/// Time : 2022-06-23 + +#include +#include + +using namespace std; + + +/// Using UF +/// Time Complexity: O(m^2) +/// Space Complexity: O(m) +class UF{ + +private: + vector parent; + int sz; + +public: + UF(int n) : parent(n), sz(n){ + for(int i = 0 ; i < n ; i ++) + parent[i] = i; + } + + int find(int p){ + if(p != parent[p]) + parent[p] = find(parent[p]); + return parent[p]; + } + + bool is_connected(int p, int q){ + return find(p) == find(q); + } + + void union_elements(int p, int q){ + + int p_root = find(p), q_root = find(q); + + if(p_root == q_root) return; + + parent[p_root] = q_root; + sz --; + } + + int get_sz(){ + return sz; + } +}; + +class Solution { +public: + bool isCompliance(vector>& distance, int n) { + + int m = distance.size(); + UF uf(m); + + for(int i = 0; i < m; i ++) + for(int j = i + 1; j < m; j ++) + if(distance[i][j] <= 2) uf.union_elements(i, j); + return uf.get_sz() <= n; + } +}; + + +int main() { + + return 0; +} diff --git a/Others/2022-xdxykd/A/CMakeLists.txt b/Others/2022-xdxykd/A/CMakeLists.txt new file mode 100644 index 00000000..415e0a92 --- /dev/null +++ b/Others/2022-xdxykd/A/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/Others/2022-xdxykd/A/main.cpp b/Others/2022-xdxykd/A/main.cpp new file mode 100644 index 00000000..c315fe15 --- /dev/null +++ b/Others/2022-xdxykd/A/main.cpp @@ -0,0 +1,52 @@ +/// Source : https://leetcode.cn/contest/ubiquant2022/problems/xdxykd/ +/// Author : liuyubobobo +/// Time : 2022-08-25 + +#include +#include +#include +#include + +using namespace std; + + +/// Math +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { + +private: + const long long MOD = 1e9 + 7; + +public: + int numberOfPairs(vector& nums) { + + int n = nums.size(); + vector nums2(n); + for(int i = 0; i < n; i ++){ + string s = to_string(nums[i]); + reverse(s.begin(), s.end()); + nums2[i] = atoi(s.c_str()); + } + + for(int i = 0; i < n; i ++) + nums[i] -= nums2[i]; + + map f; + for(int e: nums) f[e] ++; + + long long res = 0; + for(const pair& p: f){ + long long cnt = p.second; + res += cnt * (cnt - 1) / 2 % MOD; + res %= MOD; + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/Others/2022-xdxykd/B/CMakeLists.txt b/Others/2022-xdxykd/B/CMakeLists.txt new file mode 100644 index 00000000..b1c82ab8 --- /dev/null +++ b/Others/2022-xdxykd/B/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/Others/2022-xdxykd/B/main.cpp b/Others/2022-xdxykd/B/main.cpp new file mode 100644 index 00000000..293ea1f5 --- /dev/null +++ b/Others/2022-xdxykd/B/main.cpp @@ -0,0 +1,60 @@ +/// Source : https://leetcode.cn/contest/ubiquant2022/problems/3PHTGp/ +/// Author : liuyubobobo +/// Time : 2022-08-25 + +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(R * C) +/// Space Complexity: O(R * C) +class Solution { + +private: + const int dirs[8][2] = { + {1, 0}, {-1, 0}, {0, 1}, {0, -1}, + {1, 1}, {1, -1}, {-1, 1}, {-1, -1} + }; + int R, C; + +public: + int lakeCount(vector& field) { + + R = field.size(), C = field[0].size(); + vector> visited(R, vector(C, false)); + + int res = 0; + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++){ + if(field[i][j] == '.' || visited[i][j]) continue; + + dfs(field, i, j, visited); + res ++; + } + return res; + } + +private: + void dfs(const vector& g, int x, int y, vector>& visited){ + + visited[x][y] = true; + for(int d = 0; d < 8; d ++){ + int nx = x + dirs[d][0], ny = y + dirs[d][1]; + if(in_area(nx, ny) && !visited[nx][ny] && g[nx][ny] != '.') + dfs(g, nx, ny, visited); + } + } + + bool in_area(int x, int y){ + return 0 <= x && x < R && 0 <= y && y < C; + } +}; + + +int main() { + + return 0; +} diff --git a/Others/2022-xdxykd/C/CMakeLists.txt b/Others/2022-xdxykd/C/CMakeLists.txt new file mode 100644 index 00000000..d0dc1506 --- /dev/null +++ b/Others/2022-xdxykd/C/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/Others/2022-xdxykd/C/main.cpp b/Others/2022-xdxykd/C/main.cpp new file mode 100644 index 00000000..1ef05a5e --- /dev/null +++ b/Others/2022-xdxykd/C/main.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode.cn/contest/ubiquant2022/problems/uGuf0v/ +/// Author : liuyubobobo +/// Time : 2022-08-25 + +#include +#include + +using namespace std; + + +/// Greedy +/// Time Compelxity: O(nlogA) +/// Space Complexity: O(n) +class Solution { +public: + int minOperations(vector& numbers) { + + int n = numbers.size(); + + vector two(n, 0), three(n, 0), base(n, 0); + for(int i = 0; i < n; i ++){ + int x = numbers[i]; + while(x % 2 == 0) two[i] ++, x /= 2; + while(x % 3 == 0) three[i] ++, x /= 3; + base[i] = x; + } + + for(int i = 1; i < n; i ++) + if(base[i] != base[0]) return -1; + + int res = 0; + + int max_two = *max_element(two.begin(), two.end()); + for(int e: two) res += max_two - e; + + int max_three = *max_element(three.begin(), three.end()); + for(int e: three) res += max_three - e; + + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/Others/2022-xdxykd/D/CMakeLists.txt b/Others/2022-xdxykd/D/CMakeLists.txt new file mode 100644 index 00000000..8148fadd --- /dev/null +++ b/Others/2022-xdxykd/D/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) diff --git a/Others/2022-xdxykd/D/main.cpp b/Others/2022-xdxykd/D/main.cpp new file mode 100644 index 00000000..2851ab78 --- /dev/null +++ b/Others/2022-xdxykd/D/main.cpp @@ -0,0 +1,80 @@ +/// Source : https://leetcode.cn/submissions/detail/355567783/ +/// Author : liuyubobobo +/// Time : 2022-08-27 + +#include +#include +#include +#include +#include + +using namespace std; + + +/// Memoization +/// The state transfer is super clever +/// Time Complexity: O(?) +/// Space Complexity: O(?) +class Solution { +public: + double chipGame(vector& nums, int kind) { + + while(nums.size() < kind) nums.push_back(0); + + sort(nums.begin(), nums.end()); + + map, double> dp; + dp[nums] = 0; + + vector cur(kind, 0); + double res = dfs(kind, cur, nums, dp); + return res; + } + +private: + double dfs(int n, vector& cur, const vector& target, + map, double>& dp){ + + if(dp.count(cur)) return dp[cur]; + + double res = 1; + int choice = 0; + for(int start = 0, i = 1; i <= n; i ++) + if(i == n || cur[i] != cur[start]){ + + int index = i - 1; + if(cur[index] == target[index]){ + start = i; + continue; + } + + int len = i - start; + choice += len; + double p = (double)len / n; + + cur[index] ++; + res += p * dfs(n, cur, target, dp); + cur[index] --; + + start = i; + } + + assert(choice <= n); + res /= (1.0 - (double)(n - choice) / n); + return dp[cur] = res; + } +}; + + +int main() { + +// vector nums1 = {1, 1}; +// cout << Solution().chipGame(nums1, 2) << '\n'; +// // 3 + + vector nums2 = {1, 2}; + cout << Solution().chipGame(nums2, 4) << '\n'; + // 3.833333 + + return 0; +} diff --git a/Others/2022-zj-future/A/CMakeLists.txt b/Others/2022-zj-future/A/CMakeLists.txt new file mode 100644 index 00000000..fe8bfd9f --- /dev/null +++ b/Others/2022-zj-future/A/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/Others/2022-zj-future/A/main.cpp b/Others/2022-zj-future/A/main.cpp new file mode 100644 index 00000000..531029b2 --- /dev/null +++ b/Others/2022-zj-future/A/main.cpp @@ -0,0 +1,33 @@ +/// Source : https://leetcode.cn/contest/zj-future2022/problems/WYKGLO/ +/// Author : liuyubobobo +/// Time : 2022-07-08 + +#include +#include +#include + +using namespace std; + + +/// Sorting +/// Time Complexity: O(nlogn) +/// Space Complexity: O(1) +class Solution { +public: + bool canReceiveAllSignals(vector>& intervals) { + + sort(intervals.begin(), intervals.end()); + for(int i = 1; i < intervals.size(); i ++){ + int s1 = intervals[i - 1][0], e1 = intervals[i - 1][1]; + int s2 = intervals[i][0], e2 = intervals[i][1]; + if(s2 < e1) return false; + } + return true; + } +}; + + +int main() { + + return 0; +} diff --git a/Others/2022-zj-future/B/CMakeLists.txt b/Others/2022-zj-future/B/CMakeLists.txt new file mode 100644 index 00000000..8494c320 --- /dev/null +++ b/Others/2022-zj-future/B/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/Others/2022-zj-future/B/main.cpp b/Others/2022-zj-future/B/main.cpp new file mode 100644 index 00000000..8a8842ee --- /dev/null +++ b/Others/2022-zj-future/B/main.cpp @@ -0,0 +1,36 @@ +/// Source : https://leetcode.cn/contest/zj-future2022/problems/GVbKaI/ +/// Author : liuyubobobo +/// Time : 2022-07-19 + +#include +#include +#include +#include + +using namespace std; + + +/// Presum +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int minSwaps(vector& chess) { + + int n = chess.size(); + + vector presum(n + 1, 0); + for(int i = 0; i < n; i ++) presum[i + 1] = presum[i] + chess[i]; + + int res = INT_MAX, total = accumulate(chess.begin(), chess.end(), 0); + for(int start = 0; start + total <= n; start ++) + res = min(res, total - (presum[start + total] - presum[start])); + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/Others/2022-zj-future/C/CMakeLists.txt b/Others/2022-zj-future/C/CMakeLists.txt new file mode 100644 index 00000000..830d3093 --- /dev/null +++ b/Others/2022-zj-future/C/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/Others/2022-zj-future/C/main.cpp b/Others/2022-zj-future/C/main.cpp new file mode 100644 index 00000000..05ef2ba2 --- /dev/null +++ b/Others/2022-zj-future/C/main.cpp @@ -0,0 +1,64 @@ +/// Source : https://leetcode.cn/contest/zj-future2022/problems/kflZMc/ +/// Author : liuyubobobo +/// Time : 2022-07-19 + +#include +#include + +using namespace std; + + +/// Sliding Window in 2D +/// Time Complexity: O(R * C) +/// Space Complexity: O(R + C) +class Solution { +public: + int buildTransferStation(vector>& area) { + + int R = area.size(), C = area[0].size(); + + vector rows(R, 0), cols(C, 0); + int total = 0; + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++) + if(area[i][j]) rows[i] ++, cols[j] ++, total ++; + + vector pre_rows(R, rows[0]), pre_cols(C, cols[0]); + for(int i = 1; i < R; i ++) pre_rows[i] = pre_rows[i - 1] + rows[i]; + for(int j = 1; j < C; j ++) pre_cols[j] = pre_cols[j - 1] + cols[j]; + + int prow = 0; + for(int i = 1; i < R; i ++) prow += rows[i] * i; + vector row_res(R, prow); + for(int i = 1; i < R; i ++){ + int crow = prow + pre_rows[i - 1] - (total - pre_rows[i - 1]); + row_res[i] = crow; + prow = crow; + } + + int pcol = 0; + for(int j = 1; j < C; j ++) pcol += cols[j] * j; + vector col_res(C, pcol); + for(int j = 1; j < C; j ++){ + int ccol = pcol + pre_cols[j - 1] - (total - pre_cols[j - 1]); + col_res[j] = ccol; + pcol = ccol; + } + + return *min_element(row_res.begin(), row_res.end()) + *min_element(col_res.begin(), col_res.end()); + } +}; + + +int main() { + + vector> area1 = { + {0, 1, 0, 0, 0}, + {0, 0, 0, 0, 1}, + {0, 0, 1, 0, 0} + }; + cout << Solution().buildTransferStation(area1) << '\n'; + // 5 + + return 0; +} diff --git a/Others/2022-zj-future/D/CMakeLists.txt b/Others/2022-zj-future/D/CMakeLists.txt new file mode 100644 index 00000000..9a6c5c78 --- /dev/null +++ b/Others/2022-zj-future/D/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.22) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) diff --git a/Others/2022-zj-future/D/main.cpp b/Others/2022-zj-future/D/main.cpp new file mode 100644 index 00000000..81be487e --- /dev/null +++ b/Others/2022-zj-future/D/main.cpp @@ -0,0 +1,84 @@ +/// Source : https://leetcode.cn/contest/zj-future2022/problems/NBCXIp/ +/// Author : liuyubobobo +/// Time : 2022-07-19 + +#include +#include +#include + +using namespace std; + + +/// Backtrack +/// Time Complexity: O(12!) +/// Space Complexity: O(12) +class Solution { +public: + int minTransfers(vector>& distributions) { + + int max_id = -1; + for(const vector& v: distributions) + max_id = max(max_id, max(v[0], v[1])); + + vector cnt(max_id + 1, 0); + for(const vector& v: distributions){ + int from_id = v[0], to_id = v[1], e = v[2]; + cnt[from_id] -= e; + cnt[to_id] += e; + } + + vector pos, neg; + for(int i = 0; i < cnt.size(); i ++) { + if (cnt[i] > 0) pos.push_back(cnt[i]); + else if (cnt[i] < 0) neg.push_back(-cnt[i]); + } + + sort(pos.begin(), pos.end(), greater()); + sort(neg.begin(), neg.end(), greater()); + + return dfs(pos, 0, neg); + } + +private: + int dfs(vector& pos, int index, vector& neg){ + + if(index == pos.size()) return 0; + + int res = INT_MAX; + for(int& e: neg){ + if(e){ + int t = min(pos[index], e); + pos[index] -= t; + e -= t; + res = min(res, 1 + dfs(pos, index + (pos[index] == 0), neg)); + pos[index] += t; + e += t; + } + } + return res; + } +}; + + +int main() { + + vector> distrubution1 = { + {0,1,5},{2,3,1},{2,0,1},{4,0,2} + }; + cout << Solution().minTransfers(distrubution1) << '\n'; + // 4 + + vector> distrubution2 = { + {1,5,8},{8,9,8},{2,3,9},{4,3,1} + }; + cout << Solution().minTransfers(distrubution2) << '\n'; + // 4 + + vector> distrubution3 = { + {0,2,4},{1,2,4},{3,4,5} + }; + cout << Solution().minTransfers(distrubution3) << '\n'; + // 3 + + return 0; +} diff --git a/Others/2022fall-cnunionpay/A/CMakeLists.txt b/Others/2022fall-cnunionpay/A/CMakeLists.txt new file mode 100644 index 00000000..415e0a92 --- /dev/null +++ b/Others/2022fall-cnunionpay/A/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/Others/2022fall-cnunionpay/A/main.cpp b/Others/2022fall-cnunionpay/A/main.cpp new file mode 100644 index 00000000..8c698c0b --- /dev/null +++ b/Others/2022fall-cnunionpay/A/main.cpp @@ -0,0 +1,41 @@ +/// Source : https://leetcode.cn/contest/cnunionpay2022/problems/VLNEbD/ +/// Author : liuyubobobo +/// Time : 2022-09-23 + +#include + +using namespace std; + + +/// Linked List +/// Time Complexity: O(n) +/// Space Complexity: O(1) + +/// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} +}; + +class Solution { +public: + ListNode* reContruct(ListNode* head) { + + ListNode* dummyHead = new ListNode(-1); + dummyHead->next = head; + + ListNode* pre = dummyHead; + while(pre->next){ + if(pre->next->val % 2 == 0) pre->next = pre->next->next; + else pre = pre->next; + } + return dummyHead->next; + } +}; + + +int main() { + + return 0; +} diff --git a/Others/2022fall-cnunionpay/B/CMakeLists.txt b/Others/2022fall-cnunionpay/B/CMakeLists.txt new file mode 100644 index 00000000..b1c82ab8 --- /dev/null +++ b/Others/2022fall-cnunionpay/B/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/Others/2022fall-cnunionpay/B/main.cpp b/Others/2022fall-cnunionpay/B/main.cpp new file mode 100644 index 00000000..2b6688dc --- /dev/null +++ b/Others/2022fall-cnunionpay/B/main.cpp @@ -0,0 +1,45 @@ +/// Source : https://leetcode.cn/contest/cnunionpay2022/problems/6olJmJ/ +/// Author : liuyubobobo +/// Time : 2022-09-23 + +#include +#include +#include +#include + +using namespace std; + + +/// Binary Search +/// Time Complexity: O(|pos| * log(|station|)) +/// Space Complexity: O(1) +class Solution { +public: + vector explorationSupply(vector& station, vector& pos) { + + int q = pos.size(); + vector res(q, -1); + for(int i = 0; i < q; i ++){ + int p = pos[i]; + int best_d = INT_MAX; + + auto iter = lower_bound(station.begin(), station.end(), p); + if(iter != station.end()){ + if(*iter - p < best_d) + res[i] = iter - station.begin(), best_d = *iter - p; + } + if(iter != station.begin()){ + iter --; + if(p - *iter <= best_d) + res[i] = iter - station.begin(), best_d = p - *iter; + } + } + return res; + } +}; + + +int main() { + + return 0; +} diff --git a/Others/2022fall-cnunionpay/C/CMakeLists.txt b/Others/2022fall-cnunionpay/C/CMakeLists.txt new file mode 100644 index 00000000..d0dc1506 --- /dev/null +++ b/Others/2022fall-cnunionpay/C/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/Others/2022fall-cnunionpay/C/main.cpp b/Others/2022fall-cnunionpay/C/main.cpp new file mode 100644 index 00000000..04259972 --- /dev/null +++ b/Others/2022fall-cnunionpay/C/main.cpp @@ -0,0 +1,35 @@ +/// Source : https://leetcode.cn/contest/cnunionpay2022/problems/wMGN0t/ +/// Author : liuyubobobo +/// Time : 2022-09-23 + +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(1) +class Solution { +public: + int StoredEnergy(int storeLimit, const vector& power, const vector>& supply){ + + int cur_store = 0, min_supply, max_supply; + for(int i = 0, j = 0; i < power.size(); i ++){ + if(j < supply.size() && supply[j][0] == i) + min_supply = supply[j][1], max_supply = supply[j][2], j ++; + + if(min_supply <= power[i] && power[i] <= max_supply) continue; + if(power[i] > max_supply) cur_store = min(cur_store + power[i] - max_supply, storeLimit); + if(power[i] < min_supply) cur_store = max(cur_store - (min_supply - power[i]), 0); + } + return cur_store; + } +}; + + +int main() { + + return 0; +} diff --git a/Others/2022fall-cnunionpay/D/CMakeLists.txt b/Others/2022fall-cnunionpay/D/CMakeLists.txt new file mode 100644 index 00000000..8148fadd --- /dev/null +++ b/Others/2022fall-cnunionpay/D/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.23) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) diff --git a/Others/2022fall-cnunionpay/D/main.cpp b/Others/2022fall-cnunionpay/D/main.cpp new file mode 100644 index 00000000..1ef17438 --- /dev/null +++ b/Others/2022fall-cnunionpay/D/main.cpp @@ -0,0 +1,80 @@ +/// Source : https://leetcode.cn/contest/cnunionpay2022/problems/NyZD2B/ +/// Author : liuyubobobo +/// Time : 2022-09-23 + +#include +#include +#include +#include + +using namespace std; + + +/// Using Map and Set to simulate +/// Time Complexity: O(logn) +/// Space Complexity: O(n) +class VendingMachine { + +private: + map discounts; + map, int>> items; // name -> price, expire_time -> number + +public: + VendingMachine() { + + } + + void addItem(int time, int number, string item, int price, int duration) { + items[item][{price, time + duration}] += number; + } + + long long sell(int time, string customer, string item, int number) { + + if(!items.count(item)) return -1; + + map, int>& s = items[item]; + vector> v, dels; + int total = 0; + for(const pair, int>& p: s){ + int expiration = p.first.second, cnt = p.second; + if(expiration < time){ + dels.push_back(p.first); + continue; + } + + v.push_back(p.first); + total += cnt; + if(total >= number) break; + } + + for(const pair& del_key: dels) s.erase(del_key); + + if(total < number) return -1; + + int discount = 100; + if(discounts.count(customer)){ + discount = discounts[customer]; + discounts[customer] = discount - 1; + } + else discounts[customer] = 99; + + long long total_price = 0; + for(const pair& buy_key: v){ + int cnt = s[buy_key]; + int buy_cnt = min(number, cnt); + number -= buy_cnt; + cnt -= buy_cnt; + total_price += 1ll * buy_key.first * buy_cnt; + + if(cnt == 0) s.erase(buy_key); + else s[buy_key] = cnt; + } + + return total_price * discount / 100ll + !!(total_price * discount % 100ll); + } +}; + +int main() { + + return 0; +} diff --git a/Others/2022spring-cmbchina/A/CMakeLists.txt b/Others/2022spring-cmbchina/A/CMakeLists.txt new file mode 100644 index 00000000..a3422f8f --- /dev/null +++ b/Others/2022spring-cmbchina/A/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/Others/2022spring-cmbchina/A/main.cpp b/Others/2022spring-cmbchina/A/main.cpp new file mode 100644 index 00000000..30a304ba --- /dev/null +++ b/Others/2022spring-cmbchina/A/main.cpp @@ -0,0 +1,39 @@ +/// Source : https://leetcode-cn.com/contest/cmbchina-2022spring/problems/fWcPGC/ +/// Author : liuyubobobo +/// Time : 2022-04-13 + +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + string deleteText(string article, int index) { + + if(article[index] == ' ') return article; + + article = " " + article + " "; + index ++; + + int start = -1, end = -1; + for(start = index; article[start] != ' '; start --); + for(end = index; article[end] != ' '; end ++); + + article = article.substr(0, start) + " " + article.substr(end + 1); + while(!article.empty() && article[0] == ' ') article = article.substr(1); + while(!article.empty() && article.back() == ' ') article.pop_back(); + return article; + } +}; + + +int main() { + + cout << Solution().deleteText("Singing dancing in the rain", 10) << '\n'; + + return 0; +} diff --git a/Others/2022spring-cmbchina/B/CMakeLists.txt b/Others/2022spring-cmbchina/B/CMakeLists.txt new file mode 100644 index 00000000..0700646a --- /dev/null +++ b/Others/2022spring-cmbchina/B/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/Others/2022spring-cmbchina/B/main.cpp b/Others/2022spring-cmbchina/B/main.cpp new file mode 100644 index 00000000..fd617358 --- /dev/null +++ b/Others/2022spring-cmbchina/B/main.cpp @@ -0,0 +1,36 @@ +/// Source : https://leetcode-cn.com/contest/cmbchina-2022spring/problems/ReWLAw/ +/// Author : liuyubobobo +/// Time : 2022-04-13 + +#include +#include + +using namespace std; + + +/// Ad-Hoc +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int numFlowers(vector>& roads) { + + int n = roads.size() + 1; + vector degrees(n); + for(const vector& road: roads){ + degrees[road[0]] ++; + degrees[road[1]] ++; + } + return *max_element(degrees.begin(), degrees.end()) + 1; + } +}; + + +int main() { + + vector> roads1 = {{0, 1}, {1, 3}, {1, 2}}; + cout << Solution().numFlowers(roads1) << '\n'; + // 4 + + return 0; +} diff --git a/Others/2022spring-cmbchina/C/CMakeLists.txt b/Others/2022spring-cmbchina/C/CMakeLists.txt new file mode 100644 index 00000000..8accde5b --- /dev/null +++ b/Others/2022spring-cmbchina/C/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/Others/2022spring-cmbchina/C/main.cpp b/Others/2022spring-cmbchina/C/main.cpp new file mode 100644 index 00000000..95283e13 --- /dev/null +++ b/Others/2022spring-cmbchina/C/main.cpp @@ -0,0 +1,106 @@ +/// Source : https://leetcode-cn.com/contest/cmbchina-2022spring/problems/Dk2Ytp/ +/// Author : liuyubobobo +/// Time : 2022-04-13 + +#include +#include +#include +#include +#include +#include +#include + +using namespace std; + + +/// BFS +/// Time complexity: O(V + E) +/// Space Complexity: O(V + E) +class Solution { +public: + vector lightSticks(int R, int C, vector& indices) { + + set removed_edges(indices.begin(), indices.end()); + + int n = (R + 1) * (C + 1); + vector vertex(n, false); + vector> g(n); + + for(int r = 0; r <= R; r ++){ + + for(int edge = 0; edge < C; edge ++){ + + int edge_id = r * (C + C + 1) + edge; + if(removed_edges.count(edge_id)) continue; + + int a = r * (C + 1) + edge, b = a + 1; + vertex[a] = vertex[b] = true; + g[a].push_back(b), g[b].push_back(a); + } + + if(r == R) break; + + for(int edge = 0; edge <= C; edge ++){ + int edge_id = r * (C + C + 1) + C + edge; + if(removed_edges.count(edge_id)) continue; + + int a = r * (C + 1) + edge, b = (r + 1) * (C + 1) + edge; + vertex[a] = vertex[b] = true; + g[a].push_back(b), g[b].push_back(a); + } + } + + for(int u = 0; u < n; u ++) + if(vertex[u]){ + vector visited(n, false); + dfs(g, u, visited); + + if(visited != vertex) return {}; + break; + } + + vector res; + int best = INT_MAX; + for(int u = 0; u < n; u ++) + if(vertex[u]){ + int d = bfs(n, g, u); + if(d < best) res = {u}, best = d; + else if(d == best) res.push_back(u); + } + return res; + } + +private: + int bfs(int n, const vector>& g, int s){ + + vector dis(n, -1); + queue q; + q.push(s); + dis[s] = 0; + int res = 0; + while(!q.empty()){ + int u = q.front(); q.pop(); + + for(int v: g[u]) + if(dis[v] == -1){ + dis[v] = dis[u] + 1; + res = max(res, dis[v]); + q.push(v); + } + } + return res; + } + + void dfs(const vector>& g, int u, vector& visited){ + + visited[u] = true; + for(int v: g[u]) + if(!visited[v]) dfs(g, v, visited); + } +}; + + +int main() { + + return 0; +} diff --git a/Others/2022spring-cmbchina/D/CMakeLists.txt b/Others/2022spring-cmbchina/D/CMakeLists.txt new file mode 100644 index 00000000..9031340e --- /dev/null +++ b/Others/2022spring-cmbchina/D/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main.cpp) diff --git a/Others/2022spring-cmbchina/D/main.cpp b/Others/2022spring-cmbchina/D/main.cpp new file mode 100644 index 00000000..6e6d304b --- /dev/null +++ b/Others/2022spring-cmbchina/D/main.cpp @@ -0,0 +1,72 @@ +/// Source : https://leetcode-cn.com/contest/cmbchina-2022spring/problems/OK3hsO/ +/// Author : liuyubobobo +/// Time : 2022-04-13 + +#include +#include + +using namespace std; + + +/// Memoization +/// Time Complexity: O(n) +/// Space Complexity: O(n) +class Solution { +public: + int goShopping(vector& priceA, vector& priceB) { + + int n = priceA.size(); + vector> price(n); + for(int i = 0; i < n; i ++) + price[i] = {priceB[i] * 10ll, priceA[i] * 10ll}; + + sort(price.begin(), price.end(), greater>()); + + // 2 * 4 * 3 * n + // 2: 0 - no use a discount; 1 - use a discount + // 4: last a number + // 3: last b number + vector> dp(24, vector(n, -1)); + return min(dfs(n, price, 0, 0, 0, 0, dp), dfs(n, price, 1, 0, 0, 0, dp)) / 10; + } + +private: + long long dfs(int n, const vector>& price, + int use_a, int last_a, int last_b, int index, + vector>& dp){ + + if(index == n){ + if(!use_a) return last_a == 3 ? LONG_LONG_MAX / 2 : 0; + return last_a < 3 ? LONG_LONG_MAX / 2 : 0; + } + + if(!use_a && last_a == 3) return LONG_LONG_MAX / 2; + + int state1 = use_a * 12 + last_a * 3 + last_b; + if( dp[state1][index] != -1) return dp[state1][index]; + + long long res = (last_b == 2 ? 0 : price[index].first) + dfs(n, price, use_a, last_a, (last_b + 1) % 3, index + 1, dp); + if(use_a) + res = min(res, price[index].second / 10 * 7 + dfs(n, price, use_a, min(last_a + 1, 3), last_b, index + 1, dp)); + else + res = min(res, price[index].second + dfs(n, price, use_a, min(last_a + 1, 3), last_b, index + 1, dp)); + return dp[state1][index] = res; + } +}; + +int main() { + + vector price1A = {1, 2, 5}, price1B = {2, 2, 2}; + cout << Solution().goShopping(price1A, price1B) << '\n'; + // 4 + + vector price2A = {1, 6, 1}, price2B = {2, 2, 6}; + cout << Solution().goShopping(price2A, price2B) << '\n'; + // 4 + + vector price3A = {3, 13, 5, 12}, price3B = {28, 12, 20, 7}; + cout << Solution().goShopping(price3A, price3B) << '\n'; + // 21 + + return 0; +} diff --git a/Others/2022spring-cnunionpay/A/CMakeLists.txt b/Others/2022spring-cnunionpay/A/CMakeLists.txt new file mode 100644 index 00000000..a3422f8f --- /dev/null +++ b/Others/2022spring-cnunionpay/A/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) diff --git a/Others/2022spring-cnunionpay/A/main.cpp b/Others/2022spring-cnunionpay/A/main.cpp new file mode 100644 index 00000000..d707b385 --- /dev/null +++ b/Others/2022spring-cnunionpay/A/main.cpp @@ -0,0 +1,58 @@ +/// Source : https://leetcode-cn.com/contest/cnunionpay-2022spring/problems/D7rekZ/ +/// Author : liuyubobobo +/// Time : 2022-03-13 + +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} +}; + +class Solution { +public: + bool isPalindrome(ListNode* head) { + + vector v; + ListNode* cur = head; + while(cur){ + v.push_back(cur->val); + cur = cur->next; + } + + int n = v.size(); + int l = 0, r = n - 1; + while(l < r && v[l] == v[r]) l ++, r --; + + if(l >= r) return true; + + return is_palindrome(v, l, r - 1) || is_palindrome(v, l + 1, r); + } + +private: + bool is_palindrome(const vector& v, int l, int r){ + + int i = l, j = r; + while(i < j){ + if(v[i] != v[j]) return false; + i ++, j --; + } + return true; + } +}; + + +int main() { + + return 0; +} diff --git a/Others/2022spring-cnunionpay/B/CMakeLists.txt b/Others/2022spring-cnunionpay/B/CMakeLists.txt new file mode 100644 index 00000000..0700646a --- /dev/null +++ b/Others/2022spring-cnunionpay/B/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) diff --git a/Others/2022spring-cnunionpay/B/main.cpp b/Others/2022spring-cnunionpay/B/main.cpp new file mode 100644 index 00000000..6183ce82 --- /dev/null +++ b/Others/2022spring-cnunionpay/B/main.cpp @@ -0,0 +1,72 @@ +/// Source : https://leetcode-cn.com/contest/cnunionpay-2022spring/problems/kDPV0f/ +/// Author : liuyubobobo +/// Time : 2022-03-13 + +#include +#include +#include + +using namespace std; + + +/// Simulation +/// Time Complexity: init: O(1) +/// add: O(1) +/// remove: O(1) +/// consume: O(n) +/// Space Complexity: O(n) +class DiscountSystem { + +private: + vector> activity; // 0: priceLimit, 1: discount, 2: number, 3: userLimit + vector> user_in_act; // {useid, actid} -> freq + vector act_number; // actid -> number + int max_id = -1; + +public: + DiscountSystem() : + activity(1001, {-1, -1, -1, -1}), + user_in_act(1001, vector(1001, 0)), + act_number(1001, 0){} + + void addActivity(int actId, int priceLimit, int discount, int number, int userLimit) { + activity[actId] = {priceLimit, discount, number, userLimit}; + max_id = max(max_id, actId); + } + + void removeActivity(int actId) { + activity[actId] = {-1, -1, -1, -1}; + } + + int consume(int userId, int cost) { + + int best_act_id = -1, best_discount = -1; + for(int actid = 0; actid <= max_id; actid ++){ + if(activity[actid][0] == -1) continue; + if(cost < activity[actid][0]) continue; + if(user_in_act[userId][actid] >= activity[actid][3]) continue; + if(act_number[actid] >= activity[actid][2]) continue; + + if(activity[actid][1] > best_discount) + best_act_id = actid, best_discount = activity[actid][1]; + } + + if(best_act_id == -1) return cost; + + user_in_act[userId][best_act_id] ++; + act_number[best_act_id] ++; + return max(cost - best_discount, 0); + } +}; + + +int main() { + + DiscountSystem sys; + sys.addActivity(1, 10, 6, 3, 2); + sys.addActivity(2, 15, 8, 8, 2); + cout << sys.consume(101, 13) << '\n'; // 7 + sys.removeActivity(2); + + return 0; +} diff --git a/Others/2022spring-cnunionpay/C/CMakeLists.txt b/Others/2022spring-cnunionpay/C/CMakeLists.txt new file mode 100644 index 00000000..8accde5b --- /dev/null +++ b/Others/2022spring-cnunionpay/C/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) diff --git a/Others/2022spring-cnunionpay/C/main.cpp b/Others/2022spring-cnunionpay/C/main.cpp new file mode 100644 index 00000000..f22cdf7e --- /dev/null +++ b/Others/2022spring-cnunionpay/C/main.cpp @@ -0,0 +1,91 @@ +/// Source : https://leetcode-cn.com/contest/cnunionpay-2022spring/problems/I4mOGz/ +/// Author : liuyubobobo +/// Time : 2022-03-13 + +#include +#include +#include +#include +#include +#include + +using namespace std; + + +/// Using PQ +/// Again, in Leetcode, unordered_map is faster than map +/// Time Complexity: O(nlogn) +/// Space Complexity: O(n) +class Solution { + +private: + const long long MOD = 1e9 + 7; + +public: + int maxInvestment(vector& product, int limit) { + + unordered_map f; + for(int e: product) f[e] ++; + + priority_queue> pq; + for(const pair& p: f) + pq.push({p.first, p.second}); + pq.push({0, 0}); + + long long res = 0ll; + while(limit && !pq.empty()){ + + long long price = pq.top().first; + int cnt = pq.top().second; + pq.pop(); + + if(price == 0) break; + assert(!pq.empty()); + + long long next_price = pq.top().first; + assert(next_price < price); + + if(limit >= (price - next_price) * cnt){ + limit -= (price - next_price) * cnt; + res += (next_price + 1ll + price) * (price - next_price) / 2 % MOD * cnt % MOD; + res %= MOD; + + pair next = pq.top(); + pq.pop(); + next.second += cnt; + pq.push(next); + + continue; + } + else{ + if(limit / cnt){ + int next_price = price - limit / cnt + 1; + res += (next_price + price) * (price - next_price + 1) / 2 % MOD * cnt % MOD; + res %= MOD; + + price = next_price - 1; + } + if(limit % cnt){ + res += price * (limit % cnt) % MOD; + res %= MOD; + } + break; + } + } + return res % MOD; + } +}; + + +int main() { + + vector product1 = {4, 5, 3}; + cout << Solution().maxInvestment(product1, 8) << '\n'; + // 26 + + vector product2 = {2, 1, 3}; + cout << Solution().maxInvestment(product2, 20) << '\n'; + // 10 + + return 0; +} diff --git a/Others/2022spring-cnunionpay/D/CMakeLists.txt b/Others/2022spring-cnunionpay/D/CMakeLists.txt new file mode 100644 index 00000000..2552f642 --- /dev/null +++ b/Others/2022spring-cnunionpay/D/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(D) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(D main2.cpp) diff --git a/Others/2022spring-cnunionpay/D/main.cpp b/Others/2022spring-cnunionpay/D/main.cpp new file mode 100644 index 00000000..8a5223af --- /dev/null +++ b/Others/2022spring-cnunionpay/D/main.cpp @@ -0,0 +1,102 @@ +/// Source : https://leetcode-cn.com/contest/cnunionpay-2022spring/problems/lCh58I/ +/// Author : liuyubobobo +/// Time : 2022-03-13 + +#include +#include +#include + +using namespace std; + + +/// Using Hash and Map +/// It seems in Leetcode, unordered_map is faster than map in most cases +/// Especially when the test data is large +/// But unprdered_map is dangerouse in codeforces... +/// +/// Time Complexity: O(n * 2^4) +/// Space Complexity: O(n + max_skills^2) +class Solution { + +private: + const long long MOD = 1e9 + 7; + +public: + int coopDevelop(vector>& skills) { + + for(vector& skill: skills) + sort(skill.begin(), skill.end()); + sort(skills.begin(), skills.end(), + [](const vector& skill1, const vector& skill2){ + return skill1.size() < skill2.size(); + }); + + unordered_map f; + long long no = 0; + for(const vector& skill: skills){ + no += contains(f, skill); + f[get_hash(skill)] ++; + } + + long long n = skills.size(); + return (n * (n - 1) / 2 - no) % MOD; + } + +private: + long long contains(const unordered_map & f, + const vector& skills){ + + long long res = 0; + for(int i = 0; i < skills.size(); i ++){ + auto iter = f.find(get_hash({skills[i]})); + res += iter == f.end() ? 0 : iter->second; + } + + if(skills.size() == 1) return res; + + for(int i = 0; i < skills.size(); i ++) + for(int j = i + 1; j < skills.size(); j ++){ + auto iter = f.find(get_hash({skills[i], skills[j]})); + res += iter == f.end() ? 0 : iter->second; + } + + if(skills.size() == 2) return res; + + for(int i = 0; i < skills.size(); i ++) + for(int j = i + 1; j < skills.size(); j ++) + for(int k = j + 1; k < skills.size(); k ++){ + auto iter = f.find(get_hash({skills[i], skills[j], skills[k]})); + res += iter == f.end() ? 0 : iter->second; + } + + if(skills.size() == 3) return res; + + res += f.find(get_hash(skills)) != f.end(); + return res; + } + + long long get_hash(const vector& v){ + long long res = 0; + for(int e: v) + res = res * 1001ll + e; + return res; + } +}; + + +int main() { + + vector> skills1 = {{1, 2, 3}, {3}, {2, 4}}; + cout << Solution().coopDevelop(skills1) << '\n'; + // 2 + + vector> skills2 = {{3}, {6}}; + cout << Solution().coopDevelop(skills2) << '\n'; + // 1 + + vector> skills3 = {{2},{3,5,7},{2,3,5,6},{3,4,8},{2,6},{3,4,8},{3}}; + cout << Solution().coopDevelop(skills3) << '\n'; + // 13 + + return 0; +} diff --git a/Others/2022spring-cnunionpay/D/main2.cpp b/Others/2022spring-cnunionpay/D/main2.cpp new file mode 100644 index 00000000..ae6997c9 --- /dev/null +++ b/Others/2022spring-cnunionpay/D/main2.cpp @@ -0,0 +1,109 @@ +#include +#include +#include + +using namespace std; + + +/// Using Hash and Map +/// Precalc some hash to optimize +/// +/// It seems in Leetcode, unordered_map is faster than map in most cases +/// Especially when the test data is large +/// But unprdered_map is dangerouse in codeforces... +/// +/// Time Complexity: O(n * 2^4) +/// Space Complexity: O(n + max_skills^2) +class Solution { + +private: + const long long MOD = 1e9 + 7; + + vector h1, h4; + vector> h2; + +public: + Solution(): h1(1001), h2(1001, vector(1001)){ + + for(int i = 0; i <= 1000; i ++) h1[i] = i; + for(int i = 0; i <= 1000; i ++) + for(int j = 0; j <= 1000; j ++) h2[i][j] = i * 1001 + j; + } + + int coopDevelop(vector>& skills) { + + for(vector& skill: skills) + sort(skill.begin(), skill.end()); + sort(skills.begin(), skills.end(), + [](const vector& skill1, const vector& skill2){ + return skill1.size() < skill2.size(); + }); + + unordered_map f; + long long no = 0; + for(const vector& skill: skills){ + no += contains(f, skill); + f[get_hash(skill)] ++; + } + + long long n = skills.size(); + return (n * (n - 1) / 2 - no) % MOD; + } + +private: + long long contains(const unordered_map & f, + const vector& skills){ + + long long res = 0; + for(int i = 0; i < skills.size(); i ++){ + auto iter = f.find(h1[skills[i]]); + res += iter == f.end() ? 0 : iter->second; + } + + if(skills.size() == 1) return res; + + for(int i = 0; i < skills.size(); i ++) + for(int j = i + 1; j < skills.size(); j ++){ + auto iter = f.find(h2[skills[i]][skills[j]]); + res += iter == f.end() ? 0 : iter->second; + } + + if(skills.size() == 2) return res; + + for(int i = 0; i < skills.size(); i ++) + for(int j = i + 1; j < skills.size(); j ++) + for(int k = j + 1; k < skills.size(); k ++){ + auto iter = f.find(get_hash({skills[i], skills[j], skills[k]})); + res += iter == f.end() ? 0 : iter->second; + } + + if(skills.size() == 3) return res; + + res += f.find(get_hash(skills)) != f.end(); + return res; + } + + long long get_hash(const vector& v){ + long long res = 0; + for(int e: v) + res = res * 1001ll + e; + return res; + } +}; + +int main() { + + vector> skills1 = {{1, 2, 3}, {3}, {2, 4}}; + cout << Solution().coopDevelop(skills1) << '\n'; + // 2 + + vector> skills2 = {{3}, {6}}; + cout << Solution().coopDevelop(skills2) << '\n'; + // 1 + + vector> skills3 = {{2},{3,5,7},{2,3,5,6},{3,4,8},{2,6},{3,4,8},{3}}; + cout << Solution().coopDevelop(skills3) << '\n'; + // 13 + + return 0; +} diff --git a/Others/LCS01/cpp-LCS01/CMakeLists.txt b/Others/LCS01/cpp-LCS01/CMakeLists.txt new file mode 100644 index 00000000..56912ed2 --- /dev/null +++ b/Others/LCS01/cpp-LCS01/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(A) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(A main.cpp) \ No newline at end of file diff --git a/Others/LCS01/cpp-LCS01/main.cpp b/Others/LCS01/cpp-LCS01/main.cpp new file mode 100644 index 00000000..bbb9a8fc --- /dev/null +++ b/Others/LCS01/cpp-LCS01/main.cpp @@ -0,0 +1,38 @@ +/// Source : https://leetcode-cn.com/problems/Ju9Xwi/ +/// Author : liuyubobobo +/// Time : 2021-06-19 + +#include +#include + +using namespace std; + + +/// Greedy +/// Time Complexity: O(logn) +/// Space Complexity: O(1) +class Solution { +public: + int leastMinutes(int n) { + + int res = 1, cur = 1; + while(cur < n) + res ++, cur *= 2; + return res; + } +}; + + +int main() { + + cout << Solution().leastMinutes(2) << endl; + // 2 + + cout << Solution().leastMinutes(4) << endl; + // 3 + + cout << Solution().leastMinutes(7) << endl; + // 4 + + return 0; +} diff --git a/Others/LCS02/cpp-LCS02/CMakeLists.txt b/Others/LCS02/cpp-LCS02/CMakeLists.txt new file mode 100644 index 00000000..358dfef4 --- /dev/null +++ b/Others/LCS02/cpp-LCS02/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(B) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(B main.cpp) \ No newline at end of file diff --git a/Others/LCS02/cpp-LCS02/main.cpp b/Others/LCS02/cpp-LCS02/main.cpp new file mode 100644 index 00000000..371fb835 --- /dev/null +++ b/Others/LCS02/cpp-LCS02/main.cpp @@ -0,0 +1,47 @@ +/// Source : https://leetcode-cn.com/problems/WqXACV/ +/// Author : liuyubobobo +/// Time : 2021-06-19 + +#include +#include +#include + +using namespace std; + + +class Solution { +public: + int halfQuestions(vector& questions) { + + int N = questions.size() / 2; + + unordered_map f; + for(int e: questions) f[e] ++; + + vector data; + for(const pair& p: f) + data.push_back(p.second); + sort(data.rbegin(), data.rend()); + + int res = 0; + for(int cur = 0, i = 0; i < data.size() && cur < N; i ++){ + res ++; + cur += data[i]; + } + return res; + } +}; + + +int main() { + + vector q1 = {2, 1, 6, 2}; + cout << Solution().halfQuestions(q1) << endl; + // 1 + + vector q2 = {1,5,1,3,4,5,2,5,3,3,8,6}; + cout << Solution().halfQuestions(q2) << endl; + // 2 + + return 0; +} diff --git a/Others/LCS03/cpp-LCS03/CMakeLists.txt b/Others/LCS03/cpp-LCS03/CMakeLists.txt new file mode 100644 index 00000000..ad5a4184 --- /dev/null +++ b/Others/LCS03/cpp-LCS03/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.19) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/Others/LCS03/cpp-LCS03/main.cpp b/Others/LCS03/cpp-LCS03/main.cpp new file mode 100644 index 00000000..1436ea75 --- /dev/null +++ b/Others/LCS03/cpp-LCS03/main.cpp @@ -0,0 +1,74 @@ +/// Source : https://leetcode-cn.com/problems/YesdPw/ +/// Author : liuyubobobo +/// Time : 2021-06-19 + +#include +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(R * C) +/// Space Complexity: O(R * C) +class Solution { + +private: + const int dirs[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; + int R, C; + +public: + int largestArea(vector& grid) { + + R = grid.size(), C = grid[0].size(); + vector> visited(R, vector(C, false)); + + int res = 0; + for(int i = 0; i < R; i ++) + for(int j = 0; j < C; j ++) + if(!visited[i][j]){ + bool isOK = true; + int area = dfs(grid, grid[i][j], i, j, visited, isOK); + if(isOK) res = max(res, area); + } + return res; + } + +private: + int dfs(const vector& g, char c, int x, int y, + vector>& visited, bool& isOK){ + + visited[x][y] = true; + int res = 1; + for(int d = 0; d < 4; d ++){ + int nx = x + dirs[d][0], ny = y + dirs[d][1]; + if(!in_area(nx, ny) || g[nx][ny] == '0'){ + isOK = false; + continue; + } + + if(g[nx][ny] == c && !visited[nx][ny]) + res += dfs(g, c, nx, ny, visited, isOK); + } + return res; + } + + bool in_area(int x, int y){ + return x >= 0 && x < R && y >= 0 && y < C; + } +}; + + +int main() { + + vector g1 = {"110","231","221"}; + cout << Solution().largestArea(g1) << endl; + // 1 + + vector g2 = {"11111100000","21243101111","21224101221","11111101111"}; + cout << Solution().largestArea(g2) << endl; + // 3 + + return 0; +} diff --git a/Others/readme.md b/Others/readme.md new file mode 100644 index 00000000..bdc21322 --- /dev/null +++ b/Others/readme.md @@ -0,0 +1,51 @@ +## 力扣其他比赛 + +| ID | Problem | Official
Solution | C++ | Java | Python | +| --- | --- | :---: | :---: | :---: | :---: | +| | | | | | | +| 22 天堂硅谷-4 | [补给覆盖](https://leetcode.cn/contest/hhrc2022/problems/wFtovi/) | [无] | [C++](2022-hhrc/D/) | | | +| 22 天堂硅谷-3 | [重复的彩灯树](https://leetcode.cn/contest/hhrc2022/problems/VAc7h3/) | [无] | [C++](2022-hhrc/C/) | | | +| 22 天堂硅谷-2 | [销售出色区间](https://leetcode.cn/contest/hhrc2022/problems/0Wx4Pc/) | [无] | [C++](2022-hhrc/B/) | | | +| 22 天堂硅谷-1 | [化学反应](https://leetcode.cn/contest/hhrc2022/problems/o0Ma2v/) | [无] | [C++](2022-hhrc/A/) | | | +| | | | | | | +| 22秋 银联-4 | [设计自动售货机](https://leetcode.cn/contest/cnunionpay2022/problems/NyZD2B/) | [无] | [C++](2022fall-cnunionpay/D/) | | | +| 22秋 银联-3 | [风能发电](https://leetcode.cn/contest/cnunionpay2022/problems/wMGN0t/) | [无] | [C++](2022fall-cnunionpay/C/) | | | +| 22秋 银联-2 | [勘探补给](https://leetcode.cn/contest/cnunionpay2022/problems/6olJmJ/) | [无] | [C++](2022fall-cnunionpay/B/) | | | +| 22秋 银联-1 | [重构链表](https://leetcode.cn/contest/cnunionpay2022/problems/VLNEbD/) | [无] | [C++](2022fall-cnunionpay/A/) | | | +| | | | | | | +| 22 AutoX-4 | [蚂蚁爬行](https://leetcode.cn/contest/autox2023/problems/TcdlJS/) | [无] | [C++](2022-autox2023/D/) | | | +| 22 AutoX-3 | [出行的最少购票费用](https://leetcode.cn/contest/autox2023/problems/BjAFy9/) | [无] | [C++](2022-autox2023/C/) | | | +| 22 AutoX-2 | [蚂蚁王国的蜂蜜](https://leetcode.cn/contest/autox2023/problems/8p6t8R/) | [无] | [C++](2022-autox2023/B/) | | | +| 22 AutoX-1 | [网页瀑布流](https://leetcode.cn/contest/autox2023/problems/l9HbCJ/) | [无] | [C++](2022-autox2023/A/) | | | +| | | | | | | +| 22 九坤-04 | [筹码游戏](https://leetcode.cn/contest/ubiquant2022/problems/I3Gm2h/) | [无] | [C++](2022-xdxykd/D/) | | | +| 22 九坤-03 | [数字默契考验](https://leetcode.cn/contest/ubiquant2022/problems/uGuf0v/) | [无] | [C++](2022-xdxykd/C/) | | | +| 22 九坤-02 | [池塘计数](https://leetcode.cn/contest/ubiquant2022/problems/3PHTGp/) | [无] | [C++](2022-xdxykd/B/) | | | +| 22 九坤-01 | [可以读通讯稿的组数](https://leetcode.cn/contest/ubiquant2022/problems/xdxykd/) | [无] | [C++](2022-xdxykd/A/) | | | +| | | | | | | +| 22 zj-future01 | [信号接收](https://leetcode.cn/contest/zj-future2022/problems/WYKGLO/) | [无] | [C++](2022-zj-future/A/) | | | +| 22 zj-future02 | [黑白棋游戏](https://leetcode.cn/contest/zj-future2022/problems/GVbKaI/) | [无] | [C++](2022-zj-future/B/) | | | +| 22 zj-future03 | [快递中转站选址](https://leetcode.cn/contest/zj-future2022/problems/kflZMc/) | [无] | [C++](2022-zj-future/C/) | | | +| 22 zj-future04 | [门店商品调配](https://leetcode.cn/contest/zj-future2022/problems/NBCXIp/) | [无] | [C++](2022-zj-future/D/) | | | +| | | | | | | +| 22 顺丰01 | [顺丰鄂州枢纽运转中心环线检测](https://leetcode.cn/contest/sf-tech/problems/EUpcmh/) | [无] | [C++](2022-sf-tech/A/) | | | +| 22 顺丰02 | [小哥派件装载问题](https://leetcode.cn/contest/sf-tech/problems/cINqyA/) | [无] | [C++](2022-sf-tech/B/) | | | +| 22 顺丰03 | [收件节节高](https://leetcode.cn/contest/sf-tech/problems/8oimK4/) | [无] | [C++](2022-sf-tech/C/) | | | +| 22 顺丰04 | [顺丰中转场车辆入场识别-电子围栏](https://leetcode.cn/contest/sf-tech/problems/uWWzsv/) | [无] | [C++](2022-sf-tech/D/) | | | +| 22 顺丰05 | [慧眼神瞳](https://leetcode.cn/contest/sf-tech/problems/BN8jAm/) | [无] | [C++](2022-sf-tech/E/) | | | +| | | | | | | +| 22春 招商银行-01 | [文本编辑程序设计](https://leetcode-cn.com/contest/cmbchina-2022spring/problems/fWcPGC/) | [无] | [C++](2022spring-cmbchina/A/) | | | +| 22春 招商银行-02 | [公园规划](https://leetcode-cn.com/contest/cmbchina-2022spring/problems/ReWLAw/) | [无] | [C++](2022spring-cmbchina/B/) | | | +| 22春 招商银行-03 | [点燃木棒](https://leetcode-cn.com/contest/cmbchina-2022spring/problems/Dk2Ytp/) | [无] | [C++](2022spring-cmbchina/C/) | | | +| 22春 招商银行-04 | [商店促销活动](https://leetcode-cn.com/contest/cmbchina-2022spring/problems/OK3hsO/) | [无] | [C++](2022spring-cmbchina/D/) | | | +| | | | | | | +| 22春 银联-01 | [回文链表](https://leetcode-cn.com/contest/cnunionpay-2022spring/problems/D7rekZ/) | [无] | [C++](2022spring-cnunionpay/A/) | | | +| 22春 银联-02 | [优惠活动系统](https://leetcode-cn.com/contest/cnunionpay-2022spring/problems/kDPV0f/) | [无] | [C++](2022spring-cnunionpay/B/) | | | +| 22春 银联-03 | [理财产品](https://leetcode-cn.com/contest/cnunionpay-2022spring/problems/I4mOGz/) | [无] | [C++](2022spring-cnunionpay/C/) | | | +| 22春 银联-04 | [合作开发](https://leetcode-cn.com/contest/cnunionpay-2022spring/problems/lCh58I/) | [无] | [C++](2022spring-cnunionpay/D/) | | | +| | | | | | | +| LCS01 | [下载插件](https://leetcode-cn.com/problems/Ju9Xwi/) | [无] | [C++](LCS01/cpp-LCS01/) | | | +| LCS02 | [完成一半题目](https://leetcode-cn.com/problems/WqXACV/) | [无] | [C++](LCS02/cpp-LCS02/) | | | +| LCS03 | [主题空间](https://leetcode-cn.com/problems/YesdPw/) | [无] | [C++](LCS03/cpp-LCS03/) | | | +| | | | | | | + diff --git a/old/0011 Container With Most Water/cpp-Container-With-Most-Water/main.cpp b/old/0011 Container With Most Water/cpp-Container-With-Most-Water/main.cpp deleted file mode 100644 index e1e60861..00000000 --- a/old/0011 Container With Most Water/cpp-Container-With-Most-Water/main.cpp +++ /dev/null @@ -1,55 +0,0 @@ -#include -#include -#include - -using namespace std; - -/// Problem -/********************************************************************************************** - * - * Given n non-negative integers a1, a2, ..., an, - * where each represents a point at coordinate (i, ai). - * n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). - * Find two lines, which together with x-axis forms a container, - * such that the container contains the most water. - * - * Note: You may not slant the container and n is at least 2. - **********************************************************************************************/ - - -/// Solution -/*********************************************************************************************** - * Using two pointer technique - * - * Time Complexity: O(n) - * Space Complexity: O(1) - ************************************************************************************************/ - -class Solution { -public: - int maxArea(vector& height) { - - assert( height.size() >= 2 ); - - int l = 0, r = height.size() - 1; - int area = 0; - while( l < r ){ - area = max( area , min(height[l],height[r])*(r-l) ); - if( height[l] < height[r] ) - l ++; - else - r --; - } - - return area; - } -}; - -int main() { - - int nums[] = {1, 1}; - vector nums_vec = vector( nums , nums + sizeof(nums)/sizeof(int)); - cout< -#include -#include -#include -#include -#include -#include - -using namespace std; - - -/// Problem -/***************************************************************************************************** - * - * Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. - * - * Note: The solution set must not contain duplicate triplets. - * - * For example, given array S = [-1, 0, 1, 2, -1, -4], - * - * A solution set is: - * [ - * [-1, 0, 1], - * [-1, -1, 2] - * ] - *****************************************************************************************************/ - - -/// Solution 1 -/*********************************************************************************************** - * Use a hashtable to store all the numbers - * For every a and b, find if c exists - * - * To identify the unique triplet, - * we sort every triplet we found and make the sorted-triplet as a string to be the triplet id - * - * Pay attention when all the numbers in a triplet are the same - * - * Time Complexity: O(n^2) - * Space Complexity: O(n) - * - * This method will be TLE! - ************************************************************************************************/ - -class Solution { - -public: - vector> threeSum(vector& nums) { - - unordered_map numbers; - for( int i = 0 ; i < nums.size() ; i ++ ) - numbers[nums[i]] ++; - - unordered_set triplet_ids; - - vector> res; - - for( int i = 0 ; i < nums.size() ; i ++ ) - for( int j = i + 1 ; j < nums.size() ; j ++ ){ - int c = 0 - nums[i] - nums[j]; - int c_cnt = numbers[c]; - - if( c_cnt == 0 ) - continue; - - if( (c == nums[i] || c == nums[j]) && c_cnt == 1 ) - continue; - - // tricky - if( nums[i] == nums[j] && c == nums[i] && c_cnt <= 2 ) - continue; - - // c != a && c != b - // c == a || c == b and c_cnt > 1 - // c == a && c == b && c_cnt > 2 - - int triplet[] = {nums[i], nums[j], c}; - sort(triplet, triplet + 3 ); - // make the sorted triplet as a string - // use this string as an id - string triplet_id = to_string(triplet[0]) + to_string(triplet[1]) + to_string(triplet[2]); - - if( triplet_ids.find(triplet_id) == triplet_ids.end()){ - triplet_ids.insert( triplet_id ); - res.push_back( vector(triplet, triplet + 3) ); - } - } - - return res; - } -}; - -int main() { - - int nums[] = {-1, 0, 1, 2, -1, -4}; - vector nums_vec = vector( nums , nums + sizeof(nums)/sizeof(int)); - - vector> res = Solution().threeSum( nums_vec ); - for( int i = 0 ; i < res.size() ; i ++ ){ - for( int j = 0 ; j < res[i].size() ; j ++ ) - cout< -#include -#include -#include - -using namespace std; - - -/// Problem -/******************************************************************************************** - * - * Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? - * Find all unique triplets in the array which gives the sum of zero. - * - * Note: The solution set must not contain duplicate triplets. - * - * For example, given array S = [-1, 0, 1, 2, -1, -4], - * - * A solution set is: - * [ - * [-1, 0, 1], - * [-1, -1, 2] - * ] - *********************************************************************************************/ - - -/// Solution 2 -/*********************************************************************************************** - * Using two pointer technique - * Sort the array first. - * For every different number a, try to find a pair (b, c), which a + b + c == 0 - * - * Using this way, we don't need to see whether the triplet is a repeated one - * - * Time Complexity: O(n^2) - * Space Complexity: O(n) - * - * It's a classic problem: https://en.wikipedia.org/wiki/3SUM - ************************************************************************************************/ - -class Solution { - -public: - vector> threeSum(vector& nums) { - - sort(nums.begin(), nums.end()); - - vector> res; - - int index = 0; - while( index < nums.size() ){ - - // a = nums[index] - // find the pair (b,c) - - // tricky optimization - if( nums[index] > 0 ) - break; - - int bindex = index + 1; - int cindex = nums.size()-1; - while( bindex < cindex) { - - if (nums[bindex] + nums[cindex] == -nums[index]) { - int triplet[] = {nums[index], nums[bindex], nums[cindex]}; - res.push_back(vector(triplet, triplet + 3)); - - // continue to look for other pairs - bindex = next_num_index( nums, bindex ); - cindex = pre_num_index( nums, cindex); - } - else if (nums[bindex] + nums[cindex] < -nums[index]) - bindex = next_num_index( nums, bindex ); - else //nums[bindex] + nums[cindex] > -nums[index] - cindex = pre_num_index( nums, cindex); - } - - index = next_num_index( nums , index ); - } - - return res; - } - -private: - int next_num_index( const vector &nums, int cur ){ - - for( int i = cur + 1; i < nums.size() ; i ++ ) - if( nums[i] != nums[cur] ) - return i; - return nums.size(); - } - - int pre_num_index( const vector &nums, int cur){ - - for( int i = cur - 1; i >= 0 ; i -- ) - if( nums[i] != nums[cur] ) - return i; - return -1; - } -}; - -int main() { - - int nums[] = {-1, 0, 1, 2, -1, -4}; - vector nums_vec = vector( nums , nums + sizeof(nums)/sizeof(int)); - - vector> res = Solution().threeSum( nums_vec ); - for( int i = 0 ; i < res.size() ; i ++ ){ - for( int j = 0 ; j < res[i].size() ; j ++ ) - cout< -#include -#include -#include - -using namespace std; - - -/// Problem -/***************************************************************************************************** - * - * Given an array S of n integers, - * find three integers in S such that the sum is closest to a given number, target. - * Return the sum of the three integers. - * You may assume that each input would have exactly one solution. - * - * For example, given array S = {-1 2 1 -4}, and target = 1. - * - * The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). - *****************************************************************************************************/ - - -/// Solution -/************************************************************************************** - * Sort the entire numbers first. - * For every number a in numbers, - * use two pointers tecnique to find the pair (b, c), - * which makes a + b + c is close to target - * - * Time Complexity: O(nlogn) + O(n^2) - * Space Complexity: O(1) - **************************************************************************************/ - -class Solution { -public: - int threeSumClosest(vector& nums, int target) { - - assert( nums.size() >= 3 ); - - sort(nums.begin(), nums.end()); - - int diff = abs(nums[0]+nums[1]+nums[2]-target); - int res = nums[0] + nums[1] + nums[2]; - - for( int i = 0 ; i < nums.size() ; i ++ ){ - - int l = i+1, r = nums.size()-1; - int t = target - nums[i]; - while( l < r ){ - if( nums[l] + nums[r] == t ) - return nums[i] + nums[l] + nums[r]; - else{ - - if( abs( nums[l] + nums[r] - t ) < diff ){ - diff = abs( nums[l] + nums[r] - t ); - res = nums[i] + nums[l] + nums[r]; - } - - if( nums[l] + nums[r] < t ) - l ++; - else // nums[l] + nums[r] > t - r --; - } - - } - } - - return res; - } -}; - -int main() { - - //int nums[] = {-1, 2, 1, -4}; - int nums[] = {0, 0, 0}; - vector nums_vec(nums, nums + sizeof(nums)/sizeof(int)); - int target = 1; - - cout< -#include -#include -#include - -using namespace std; - -class Solution1 { -public: - vector> fourSum(vector& nums, int target) { - - int n = nums.size(); - - vector> res; - if( n < 4 ) - return res; - - sort( nums.begin() , nums.end() ); - - vector one_res(4, 0); - for( int i = 0 ; i <= n - 4 ; i = nextNumberIndex(nums, i) ) { - - for (int j = i + 1; j <= n - 3; j = nextNumberIndex(nums, j)) { - - int t = target - nums[i] - nums[j]; - - if( nums[j+1] + nums[j+2] > t || nums[n-1] + nums[n-2] < t) - continue; - - int p1 = j + 1; - int p2 = nums.size() - 1; - - if (p1 >= p2) - break; - - while (p1 < p2) { - if (nums[p1] + nums[p2] == t) { - one_res[0] = nums[i]; - one_res[1] = nums[j]; - one_res[2] = nums[p1]; - one_res[3] = nums[p2]; - res.push_back(one_res); - - p1 = nextNumberIndex(nums, p1); - p2 = preNumberIndex(nums, p2); - } - else if (nums[p1] + nums[p2] < t) - p1 = nextNumberIndex(nums, p1); - else // nums[p1] + nums[p2] > t - p2 = preNumberIndex(nums, p2); - } - } - } - - return res; - } - -private: - int nextNumberIndex( const vector &nums , int index ){ - - for( int i = index + 1 ; i < nums.size() ; i ++ ) - if( nums[i] != nums[index] ) - return i; - return nums.size(); - } - - int preNumberIndex( const vector &nums , int index ){ - - for( int i = index-1 ; i >= 0 ; i -- ) - if( nums[i] != nums[index] ) - return i; - return -1; - } -}; - -#endif //CPP_4SUM_SOLUTION1_H diff --git a/old/0018 4Sum/cpp-4Sum/Solution2.h b/old/0018 4Sum/cpp-4Sum/Solution2.h deleted file mode 100644 index 05601cee..00000000 --- a/old/0018 4Sum/cpp-4Sum/Solution2.h +++ /dev/null @@ -1,80 +0,0 @@ -// -// Created by liuyubobobo on 9/27/17. -// - -#ifndef CPP_4SUM_SOLUTION2_H -#define CPP_4SUM_SOLUTION2_H - -#include -#include -#include -#include -#include -#include - -using namespace std; - -class Solution2 { -public: - vector> fourSum(vector& nums, int target) { - - int n = nums.size(); - - vector> res; - if( n < 4 ) - return res; - - sort( nums.begin() , nums.end() ); - - unordered_map>> hashtable; - for(int i = 0 ; i < n - 1 ; i = nextNumberIndex(nums, i)) - for(int j = i + 1 ; j < n ; j = nextNumberIndex(nums, j)) - hashtable[nums[i]+nums[j]].push_back(make_pair(nums[i], nums[j])); - - vector one_res(4, 0); - for( int i = 0 ; i <= n - 4 ; i = nextNumberIndex(nums, i) ) { - - for (int j = i + 1; j <= n - 3; j = nextNumberIndex(nums, j)) { - - int t = target - nums[i] - nums[j]; - if( nums[j+1] + nums[j+2] > t || nums[n-1] + nums[n-2] < t) - continue; - - if(hashtable.find(t) == hashtable.end()) - continue; - - one_res[0] = nums[i]; - one_res[1] = nums[j]; - - vector>::iterator iter = - lower_bound(hashtable[t].begin(), hashtable[t].end(), make_pair(nums[j+1], nums[j+1])); - for(; iter != hashtable[t].end() ; iter ++){ - one_res[2] = iter->first; - one_res[3] = iter->second; - res.push_back(one_res); - } - } - } - - return res; - } - -private: - int nextNumberIndex( const vector &nums , int index ){ - - for( int i = index + 1 ; i < nums.size() ; i ++ ) - if( nums[i] != nums[index] ) - return i; - return nums.size(); - } - - int preNumberIndex( const vector &nums , int index ){ - - for( int i = index-1 ; i >= 0 ; i -- ) - if( nums[i] != nums[index] ) - return i; - return -1; - } -}; - -#endif //CPP_4SUM_SOLUTION2_H diff --git a/old/0018 4Sum/cpp-4Sum/main.cpp b/old/0018 4Sum/cpp-4Sum/main.cpp deleted file mode 100644 index 68efc7c3..00000000 --- a/old/0018 4Sum/cpp-4Sum/main.cpp +++ /dev/null @@ -1,107 +0,0 @@ -/// Source : https://leetcode.com/problems/4sum/ -/// Author : liuyubobobo -/// Time : 2016-12-06 - -/*********************************************************************************************** - * Using two pointer technique - * - * Sort the array first. - * For every different number a and b, try to find a pair (c, d), which a + b + c + d == 0 - * - * Using this way, we don't need to see whether the triplet is a repeated one - * - * Time Complexity: O(nlogn) + O(n^3) - * Space Complexity: O(1) - ************************************************************************************************/ - - -#include -#include -#include -#include - -using namespace std; - -class Solution { -public: - vector> fourSum(vector& nums, int target) { - - int n = nums.size(); - - vector> res; - if( n < 4 ) - return res; - - sort( nums.begin() , nums.end() ); - - vector one_res(4, 0); - for( int i = 0 ; i <= n - 4 ; i = nextNumberIndex(nums, i) ) { - - for (int j = i + 1; j <= n - 3; j = nextNumberIndex(nums, j)) { - - int t = target - nums[i] - nums[j]; - - if( nums[j+1] + nums[j+2] > t || nums[n-1] + nums[n-2] < t) - continue; - - int p1 = j + 1; - int p2 = nums.size() - 1; - - if (p1 >= p2) - break; - - while (p1 < p2) { - if (nums[p1] + nums[p2] == t) { - one_res[0] = nums[i]; - one_res[1] = nums[j]; - one_res[2] = nums[p1]; - one_res[3] = nums[p2]; - res.push_back(one_res); - - p1 = nextNumberIndex(nums, p1); - p2 = preNumberIndex(nums, p2); - } - else if (nums[p1] + nums[p2] < t) - p1 = nextNumberIndex(nums, p1); - else // nums[p1] + nums[p2] > t - p2 = preNumberIndex(nums, p2); - } - } - } - - return res; - } - -private: - int nextNumberIndex( const vector &nums , int index ){ - - for( int i = index + 1 ; i < nums.size() ; i ++ ) - if( nums[i] != nums[index] ) - return i; - return nums.size(); - } - - int preNumberIndex( const vector &nums , int index ){ - - for( int i = index-1 ; i >= 0 ; i -- ) - if( nums[i] != nums[index] ) - return i; - return -1; - } -}; - -int main() { - - int nums[] = {1, 0, -1, 0, -2, 2}; - vector nums_vec = vector( nums , nums + sizeof(nums)/sizeof(int)); - int target = 0; - - vector> res = Solution().fourSum( nums_vec , target ); - for( int i = 0 ; i < res.size() ; i ++ ){ - for( int j = 0 ; j < res[i].size() ; j ++ ) - cout< -#include -#include -#include -#include -#include - -using namespace std; - -class Solution { -public: - vector> fourSum(vector& nums, int target) { - - int n = nums.size(); - - vector> res; - if( n < 4 ) - return res; - - sort( nums.begin() , nums.end() ); - - unordered_map>> hashtable; - for(int i = 0 ; i < n - 1 ; i = nextNumberIndex(nums, i)) - for(int j = i + 1 ; j < n ; j = nextNumberIndex(nums, j)) - hashtable[nums[i]+nums[j]].push_back(make_pair(nums[i], nums[j])); - - vector one_res(4, 0); - for( int i = 0 ; i <= n - 4 ; i = nextNumberIndex(nums, i) ) { - - for (int j = i + 1; j <= n - 3; j = nextNumberIndex(nums, j)) { - - int t = target - nums[i] - nums[j]; - if( nums[j+1] + nums[j+2] > t || nums[n-1] + nums[n-2] < t) - continue; - - if(hashtable.find(t) == hashtable.end()) - continue; - - one_res[0] = nums[i]; - one_res[1] = nums[j]; - - vector>::iterator iter = - lower_bound(hashtable[t].begin(), hashtable[t].end(), make_pair(nums[j+1], nums[j+1])); - for(; iter != hashtable[t].end() ; iter ++){ - one_res[2] = iter->first; - one_res[3] = iter->second; - res.push_back(one_res); - } - } - } - - return res; - } - -private: - int nextNumberIndex( const vector &nums , int index ){ - - for( int i = index + 1 ; i < nums.size() ; i ++ ) - if( nums[i] != nums[index] ) - return i; - return nums.size(); - } - - int preNumberIndex( const vector &nums , int index ){ - - for( int i = index-1 ; i >= 0 ; i -- ) - if( nums[i] != nums[index] ) - return i; - return -1; - } -}; - -int main() { - - int nums[] = {1, 0, -1, 0, -2, 2}; - vector nums_vec = vector( nums , nums + sizeof(nums)/sizeof(int)); - int target = 0; - - vector> res = Solution().fourSum( nums_vec , target ); - for( int i = 0 ; i < res.size() ; i ++ ){ - for( int j = 0 ; j < res[i].size() ; j ++ ) - cout< -#include -#include -#include -#include -#include "Solution1.h" -#include "Solution2.h" - -using namespace std; - -int main() { - - int N = 2000; - - srand(time(NULL)); - vector vec1; - for(int i = 0 ; i < N ; i ++){ - int randNumber = rand() % N; - if(randNumber % 2) - vec1.push_back(randNumber); - else - vec1.push_back(-randNumber); - } - - vector vec2(vec1.begin(), vec1.end()); - - int target = rand() % N; - time_t startTime, endTime; - - startTime = clock(); - Solution1().fourSum(vec1, target); - endTime = clock(); - cout << "Solution 1 time: " << (double)(endTime - startTime) / CLOCKS_PER_SEC << " s." << endl; - - startTime = clock(); - Solution2().fourSum(vec2, target); - endTime = clock(); - cout << "Solution 2 time: " << (double)(endTime - startTime) / CLOCKS_PER_SEC << " s." << endl; - - return 0; -} \ No newline at end of file diff --git a/old/0026 Remove Duplicates from Sorted Array/cpp-Remove-Duplicates-from-Sorted-Array/main.cpp b/old/0026 Remove Duplicates from Sorted Array/cpp-Remove-Duplicates-from-Sorted-Array/main.cpp deleted file mode 100644 index d4ed97af..00000000 --- a/old/0026 Remove Duplicates from Sorted Array/cpp-Remove-Duplicates-from-Sorted-Array/main.cpp +++ /dev/null @@ -1,80 +0,0 @@ -/// Source : https://leetcode.com/problems/remove-duplicates-from-sorted-array/ -/// Author : liuyubobobo -/// Time : 2016-12-06 - - -#include -#include -#include -#include - -using namespace std; - - -/// Problem -/***************************************************************************************************** - * - * Given a sorted array, - * remove the duplicates in place such that each element appear only once and return the new length. - * - * Do not allocate extra space for another array, - * you must do this in place with constant memory. - * - * For example, - * Given input array nums = [1,1,2], - * - * Your function should return length = 2, - * with the first two elements of nums being 1 and 2 respectively. - * It doesn't matter what you leave beyond the new length. - *******************************************************************************************************/ - - -/// Solution -/************************************** - * Using two pointer technique - * - * Time Complexity: O(n) - * Space Complexity: O(1) - **************************************/ - -class Solution { -public: - int removeDuplicates(vector& nums) { - - if( nums.size() == 0 ) - return 0; - - int res = 1; - int index = nextDifferentCharacterIndex(nums, 1 ); - int i = 1; - while( index < nums.size() ){ - res ++; - nums[i++] = nums[index]; - index = nextDifferentCharacterIndex(nums, index + 1 ); - } - - return res; - } - -private: - int nextDifferentCharacterIndex( const vector &nums, int p ){ - for( ; p < nums.size() ; p ++ ) - if( nums[p] != nums[p-1] ) - break; - return p; - } -}; - -int main() { - - const int nums[] = {1,1,2}; - vector nums_vec( nums, nums + sizeof(nums)/sizeof(int) ); - - int newlen = Solution().removeDuplicates( nums_vec ); - cout< -#include -#include -#include - -using namespace std; - - -/// Problem -/***************************************************************************************************** - * - * Given an array and a value, - * remove all instances of that value in place and return the new length. - * - * Do not allocate extra space for another array, - * you must do this in place with constant memory. - * - * The order of elements can be changed. - * It doesn't matter what you leave beyond the new length. - * - * Example: - * Given input array nums = [3,2,2,3], val = 3 - * - * Your function should return length = 2, - * with the first two elements of nums being 2. - *****************************************************************************************************/ - - -/// Solution 1 -/************************************************************************************** - * Two Pointers - * - * Time Complexity: O(n) - * Space Complexity: O(1) - **************************************************************************************/ - -class Solution { - -public: - int removeElement(vector& nums, int val) { - - int newl = 0; - for( int i = 0 ; i < nums.size() ; i ++ ) - if( nums[i] != val ) - nums[newl++] = nums[i]; - - return newl; - } -}; - -int main() { - - int nums[] = {3, 2, 2, 3}; - vector nums_vec(nums, nums + sizeof(nums)/sizeof(int)); - int val = 3; - - cout< -#include -#include -#include - -using namespace std; - - -/// Problem -/***************************************************************************************************** - * - * Given an array and a value, - * remove all instances of that value in place and return the new length. - * - * Do not allocate extra space for another array, - * you must do this in place with constant memory. - * - * The order of elements can be changed. - * It doesn't matter what you leave beyond the new length. - * - * Example: - * Given input array nums = [3,2,2,3], val = 3 - * - * Your function should return length = 2, - * with the first two elements of nums being 2. - *****************************************************************************************************/ - - -/// Solution 2 -/************************************************************************************** - * Two Pointers - * Move the deleted element to the last - * This method would be save the unnecessary copy when the removed element is rare. - * - * Time Complexity: O(n) - * Space Complexity: O(1) - **************************************************************************************/ - -class Solution { - -public: - int removeElement(vector& nums, int val) { - - int newl = nums.size(); - int i = 0; - while( i < newl ) - if( nums[i] == val ) - nums[i] = nums[--newl]; - else - i ++; - - return newl; - } -}; - -int main() { - - int nums[] = {3, 2, 2, 3}; - vector nums_vec(nums, nums + sizeof(nums)/sizeof(int)); - int val = 3; - - cout< -#include -#include -#include -#include - -using namespace std; - - -/// Problem -/***************************************************************************************************** - * - * Implement strStr(). - * - * Returns the index of the first occurrence of needle in haystack, - * or -1 if needle is not part of haystack. - *****************************************************************************************************/ - - -/// Solution -/************************************************************************************** - * The basic O(s1*s2) Implementation - * - * Time Complexity: O(s1*s2) - * Space Complexity: O(1) - **************************************************************************************/ - -class Solution { -public: - int strStr(string haystack, string needle) { - - int len1 = haystack.size(); - int len2 = needle.size(); - - for( int i = 0 ; i <= len1 - len2 ; i ++ ){ - bool ok = true; - for( int j = i ; j < i + len2 ; j ++ ) - if( haystack[j] != needle[j-i] ){ - ok = false; - break; - } - if( ok ) - return i; - } - - return -1; - } -}; - -int main() { - - string s1 = "ababc"; - string s2 = "bab"; - - cout< -#include -#include -#include - -using namespace std; - - -/// Problem -/***************************************************************************************************** - * - * Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules. - * http://sudoku.com.au/TheRules.aspx - * - * The Sudoku board could be partially filled, - * where empty cells are filled with the character '.'. - * - * Note: - * A valid Sudoku board (partially filled) is not necessarily solvable. - * Only the filled cells need to be validated. - *****************************************************************************************************/ - - -/// Solution -/************************************************************************************** - * Using hashtable to check every row, column and block. - * - * Time Complexity: O(9*9) - * Space Complexity: O(1) - **************************************************************************************/ - -class Solution { -public: - bool isValidSudoku(vector>& board) { - - assert( board.size() == 9 ); - for( int i = 0 ; i < 9 ; i ++ ){ - assert( board[i].size() == 9 ); - for( int j = 0 ; j < 9 ; j ++ ) - assert( board[i][j] == '.' || ( board[i][j] >= '1' && board[i][j] <= '9')) ; - } - - - bool hashtable[9][9]; - - // check for every row - memset( hashtable, 0, sizeof(hashtable)); - for( int i = 0 ; i < 9 ; i ++ ) - for( int j = 0 ; j < 9 ; j ++ ) - if( board[i][j] != '.'){ - int num = board[i][j] - '0' - 1; - if( hashtable[i][num] == 1 ) - return false; - hashtable[i][num] = 1; - } - - // check for every col - memset( hashtable, 0, sizeof(hashtable)); - for( int i = 0 ; i < 9 ; i ++ ) - for( int j = 0 ; j < 9 ; j ++ ) - if( board[j][i] != '.'){ - int num = board[j][i] - '0' - 1; - if( hashtable[i][num] == 1 ) - return false; - hashtable[i][num] = 1; - } - - // check for every block - memset( hashtable, 0, sizeof(hashtable)); - for( int i = 0 ; i < 9 ; i ++ ){ - int br = i/3; - int bc = i%3; - for( int ii = 0 ; ii < 3 ; ii ++ ) - for( int jj = 0 ; jj < 3 ; jj ++ ){ - - int r = br*3 + ii; - int c = bc*3 + jj; - if( board[r][c] != '.') { - int num = board[r][c] - '0' - 1; - if ( hashtable[i][num] == 1 ) - return false; - hashtable[i][num] = 1; - } - } - } - - return true; - } -}; - -int main() { - - char b[9][10] = { - "53..7....", - "6..195...", - ".98....6.", - "8...6...3", - "4..8.3..1", - "7...2...6", - ".6....28.", - "...419..5", - "....8..79" - }; - - vector> board; - for( int i = 0 ; i < 9 ; i ++ ){ - vector row; - for( int j = 0 ; j < 9 ; j ++ ) - row.push_back( b[i][j] ); - board.push_back( row ); - } - - cout< -#include - -using namespace std; - -/// Problem -/******************************************************************************************************** - * - * Given a string S and a string T, - * find the minimum window in S which will contain all the characters in T in complexity O(n). - * - * For example, - * S = "ADOBECODEBANC" - * T = "ABC" - * Minimum window is "BANC". - * - * Note: - * If there is no such window in S that covers all characters in T, return the empty string "". - * - * If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S. - ********************************************************************************************************/ - - -/// Solution -/*********************************************************************************************** - * Using sliding window - * - * Time Complexity: O(n) - * Space Complexity: O(1) - ************************************************************************************************/ - -class Solution { -public: - string minWindow(string s, string t) { - - int tFreq[256] = {0}; - for( int i = 0 ; i < t.size() ; i ++ ) - tFreq[t[i]] ++; - - int sFreq[256] = {0}; - int sCnt = 0; - - int minLength = s.size() + 1; - int startIndex = -1; - - int l = 0, r = -1; - while( l < s.size() ){ - - if( r + 1 < s.size() && sCnt < t.size() ){ - - sFreq[s[r+1]] ++; - if( sFreq[s[r+1]] <= tFreq[s[r+1]] ) - sCnt ++; - r ++; - } - else{ - assert( sCnt <= t.size() ); - if( sCnt == t.size() && r - l + 1 < minLength ){ - minLength = r - l + 1; - startIndex = l; - } - - sFreq[s[l]] --; - if( sFreq[s[l]] < tFreq[s[l]] ) - sCnt --; - l ++; - } - } - - if( startIndex != -1 ) - return s.substr( startIndex, minLength ); - - return ""; - } -}; - -int main() { - - cout << Solution().minWindow( "ADOBECODEBANC" , "ABC" )< -#include - -using namespace std; - - -/// Problem -/*********************************************************************************** - * - * Follow up for "Remove Duplicates": - * What if duplicates are allowed at most twice? - * - * For example, - * Given sorted array nums = [1,1,1,2,2,3], - * Your function should return length = 5, - * with the first five elements of nums being 1, 1, 2, 2 and 3. - * It doesn't matter what you leave beyond the new length. - **************************************************************************************/ - - -/// Solution -/*********************************************************************************************** - * Same algorithm for Remove Duplicates - * - * Time Complexity: O(n) - * Space Complexity: O(1) - ************************************************************************************************/ - -class Solution { -public: - int removeDuplicates(vector& nums) { - - int i = 0; - int j = 0; - while( j < nums.size() ){ - int k = nextIndex( nums, j ); - int len = min( 2, k-j); - for( int ii = 0 ; ii < len ; ii ++ ) - nums[i+ii] = nums[j]; - i += len; - j = k; - } - - return i; - } - -private: - int nextIndex( const vector& nums, int index ){ - for( int i = index ; i < nums.size() ; i ++ ) - if( nums[i] != nums[index] ) - return i; - return nums.size(); - } -}; - -int main() { - - int nums[] = {1, 1, 1, 2, 2, 3}; - vector nums_vec = vector( nums , nums + sizeof(nums)/sizeof(int)); - - cout< -#include -#include -#include - -using namespace std; - - -/// Problem -/******************************************************************************** - * - * Given a string, determine if it is a palindrome, - * considering only alphanumeric characters and ignoring cases. - * - * For example, - * "A man, a plan, a canal: Panama" is a palindrome. - * "race a car" is not a palindrome. - * - * Note: - * - Have you consider that the string might be empty? - * This is a good question to ask during an interview. - * - For the purpose of this problem, we define empty string as valid palindrome. - **********************************************************************************/ - - -/// Solution -/***************************************************************************** - * Using Two Pointers - * - * Time Complexity: O(s) - * Space Complexity: O(1) - ******************************************************************************/ - -class Solution { -public: - bool isPalindrome(string s) { - - int i = nextCharacterIndex(s, -1) , j = preCharacterIndex(s, s.size()); - while( i <= j ){ - - if( tolower(s[i]) != tolower(s[j]) ) - return false; - - i = nextCharacterIndex( s , i ); - j = preCharacterIndex( s , j ); - } - - return true; - } - -private: - int nextCharacterIndex( const string &s , int index ){ - - int res = index + 1; - for( res = index + 1 ; res < s.size() ; res ++ ) - if( isalnum(s[res]) ) - return res; - return res; - } - - int preCharacterIndex( const string &s , int index ){ - - int res = index - 1; - for( res = index - 1 ; res >= 0 ; res -- ) - if( isalnum(s[res]) ) - return res; - return res; - } -}; - - -int main() { - - cout< -#include -#include - -using namespace std; - - -class Solution { -private: - int m, n; - vector> visited; - int d[4][2] = {{0,1}, {1,0}, {0,-1}, {-1,0}}; - -private: - bool inArea(int x, int y){ - return x >= 0 && y >= 0 && x < m && y < n; - } - - bool dfs(vector> &board, int x, int y){ - - visited[x][y] = true; - board[x][y] = 'X'; - - for(int i = 0; i < 4; i++){ - int newX = x + d[i][0]; - int newY = y + d[i][1]; - if (!inArea(newX, newY)){ - board[x][y] = 'O'; - return false; - } - if(board[newX][newY] == 'O' && !visited[newX][newY]) - if(!dfs(board, newX, newY)){ - board[x][y] = 'O'; - return false; - } - } - return true; - } - -public: - void solve(vector>& board) { - m = board.size(); - if (m == 0) - return; - n = board[0].size(); - if( n == 0) - return; - - visited = vector>(m, vector(n, false)); - - for(int i = 0; i < m; i++) - for(int j = 0; j < n; j++) - if (board[i][j] == 'O' && !visited[i][j]) - dfs(board, i, j); - - return; - } -}; - -int main(){ - - int n = 4, m = 4; - string board_array[] = { - "XXXX", - "XOOX", - "XXOX", - "XOXX"}; - vector> board = vector>(n, vector(m, ' ')); - for(int i = 0 ; i < n ; i ++) - for(int j = 0 ; j < m ; j ++) - board[i][j] = board_array[i][j]; - - Solution().solve(board); - - for(int i = 0 ; i < n ; i ++){ - for(int j = 0 ; j < m ; j ++) - cout << board[i][j]; - cout << endl; - } - - return 0; -} \ No newline at end of file diff --git a/old/0130 Surrounded Regions/cpp-Surrounded-Regions/main2.cpp b/old/0130 Surrounded Regions/cpp-Surrounded-Regions/main2.cpp deleted file mode 100644 index 2b0f0d24..00000000 --- a/old/0130 Surrounded Regions/cpp-Surrounded-Regions/main2.cpp +++ /dev/null @@ -1,121 +0,0 @@ -/// Created by liuyubobobo on 7/13/17. -/// Leetcode 130. Surrounded Regions -/// https://leetcode.com/problems/surrounded-regions/#/description - -/*** - * This version of code uses BFS instead of DFS to solve the problem. - * It will get Accept:) - */ - - -#include -#include -#include -#include -#include - -using namespace std; - - -class Solution { -private: - int m; - int n; - vector> visited; - int d[4][2] = {{0,1}, {1,0}, {0,-1}, {-1,0}}; - - // record every position has been visited during a BFS - vector> record; - -private: - bool inArea(int x, int y){ - return x >= 0 && y >= 0 && x < m && y < n; - } - - bool bfs(vector> &board, int x, int y){ - - queue> q; - - // return true if we can only get to 'X' during BFS, - // otherwise, return false - bool ret = true; - - visited[x][y] = true; - q.push(pair(x, y)); - while( !q.empty()){ - pair cur = q.front(); - q.pop(); - record.push_back(pair(cur.first, cur.second)); - - for(int i = 0 ; i < 4 ;i ++){ - int newX = cur.first + d[i][0]; - int newY = cur.second + d[i][1]; - - if(!inArea(newX, newY)) - // If newX, newY is not in the area, - // it means we get out of the board in this BFS, - // we need to return false in this case - ret = false; - else if(board[newX][newY] == 'O' && !visited[newX][newY]){ - visited[newX][newY] = true; - q.push(pair(newX, newY)); - } - } - } - - return ret; - } - -public: - void solve(vector>& board) { - m = board.size(); - if(m == 0) - return; - n = board[0].size(); - if(n == 0) - return; - - visited = vector>(m, vector(n, false)); - - for (int i = 0; i < m; i++) - for (int j = 0; j < n; j++) - if (board[i][j] == 'O' && !visited[i][j]){ - // clear record before each time we run BFS - record.clear(); - if(bfs(board, i, j)) - // If BFS return true, - // means from this position, - // we will not get out of the board. - // As a result, we can make every position we visited in this BFS from 'O' to 'X' - for(int k = 0 ; k < record.size() ; k ++) - board[record[k].first][record[k].second] = 'X'; - } - - return; - } -}; - - -int main(){ - - int n = 4, m = 4; - string board_array[] = { - "XXXX", - "XOOX", - "XXOX", - "XOXX"}; - vector> board = vector>(n, vector(m, ' ')); - for(int i = 0 ; i < n ; i ++) - for(int j = 0 ; j < m ; j ++) - board[i][j] = board_array[i][j]; - - Solution().solve(board); - - for(int i = 0 ; i < n ; i ++){ - for(int j = 0 ; j < m ; j ++) - cout << board[i][j]; - cout << endl; - } - - return 0; -} \ No newline at end of file diff --git a/old/0136 Single Number/cpp-Single-Number/main1.cpp b/old/0136 Single Number/cpp-Single-Number/main1.cpp deleted file mode 100644 index 521c59fc..00000000 --- a/old/0136 Single Number/cpp-Single-Number/main1.cpp +++ /dev/null @@ -1,61 +0,0 @@ -/// Source : https://leetcode.com/problems/single-number/ -/// Author : liuyubobobo -/// Time : 2016-12-05 - - -#include -#include -#include -#include -#include - -using namespace std; - - -/// Problem -/*************************************************************************** - * - * Given an array of integers, every element appears twice except for one. - * Find that single one. - * - * Note: - * Your algorithm should have a linear runtime complexity. - * Could you implement it without using extra memory? - ***************************************************************************/ - - -/// Solution 1 -/************************************************************************************** - * Using hashtable to find the one - * - * Time Complexity: O(n) - * Space Complexity: O(n) - **************************************************************************************/ - -class Solution { -public: - int singleNumber(vector& nums) { - - assert( nums.size()%2 == 1 ); - - unordered_set hashtable; - for( int i = 0 ; i < nums.size() ; i ++ ) - if( hashtable.find(nums[i]) == hashtable.end() ) - hashtable.insert( nums[i] ); - else - hashtable.erase( nums[i] ); - - assert( hashtable.size() == 1 ); - return *hashtable.begin(); - } -}; - -int main() { - - int nums[] = {0, 0, 1, 1, 2}; - vector nums_vec(nums, nums + sizeof(nums)/sizeof(int)); - - cout< -#include -#include -#include -#include - -using namespace std; - - -/// Problem -/*************************************************************************** - * - * Given an array of integers, every element appears twice except for one. - * Find that single one. - * - * Note: - * Your algorithm should have a linear runtime complexity. - * Could you implement it without using extra memory? - ***************************************************************************/ - - -/// Solution 2 -/************************************************************************************** - * Using the attribution of xor operation: - * a ^ 0 = a - * a ^ a = 0 - * - * Time Complexity: O(n) - * Space Complexity: O(1) - **************************************************************************************/ - -class Solution { -public: - int singleNumber(vector& nums) { - - assert( nums.size()%2 == 1 ); - - int res = 0; - for( int i = 0 ; i < nums.size() ; i ++ ) - res ^= nums[i]; - return res; - } -}; - -int main() { - - int nums[] = {0, 0, 1, 1, 2}; - vector nums_vec(nums, nums + sizeof(nums)/sizeof(int)); - - cout< -#include -#include -#include -#include - -using namespace std; - - -/// Problem -/*********************************************************************************************** - * Given a string, - * find the length of the longest substring T that contains at most 2 distinct characters. - * - * For example, Given s = “eceba”, - * - * T is "ece" which its length is 3. - ***********************************************************************************************/ - - -/// Solution 1 -/********************************************************************************** - * Using two pointer technique. - * Recording how many different characters in the current string by map. - * - * Time Complexity: O(n) - * Space Complexity: O(1) - **********************************************************************************/ - -class Solution { -public: - int lengthOfLongestSubstringTwoDistinct(string s) { - - unordered_map map; - int l = 0, r = 0; - int res = 0; - while( r <= s.size() ){ - - if( r == s.size() || (map.size() == 2 && map.find(s[r]) == map.end() ) ){ - res = max( res , r-l ); - while( map.size() >= 2 ){ - if( map[s[l]] == 1 ) - map.erase( s[l] ); - else - map[s[l]] --; - l ++; - } - - if( r == s.size() ) - break; - } - else{ - if( map.find(s[r]) == map.end() ) - map[s[r]] = 1; - else - map[s[r]] += 1; - r ++; - } - } - - return res; - } -}; - -int main() { - - cout< -#include -#include -#include -#include - -using namespace std; - - -/// Problem -/*********************************************************************************************** - * Given a string, - * find the length of the longest substring T that contains at most 2 distinct characters. - * - * For example, Given s = “eceba”, - * - * T is "ece" which its length is 3. - ***********************************************************************************************/ - - -/// Solution 2 -/******************************************************************************************** - * Using two pointer technique. - * Using self-built hashtable to record how many different characters in the current string - * - * Time Complexity: O(n) - * Space Complexity: O(1) - ********************************************************************************************/ - -class Solution { -public: - int lengthOfLongestSubstringTwoDistinct(string s) { - - int hashtable[256] = {0}; - int l = 0, r = 0; - int res = 0; - int count = 0; - while( r <= s.size() ){ - - if( r == s.size() || (count == 2 && !hashtable[s[r]] ) ){ - res = max( res , r-l ); - while( count >= 2 ){ - hashtable[s[l]] --; - if( hashtable[s[l]] == 0 ) - count --; - l ++; - } - - if( r == s.size() ) - break; - } - else{ - hashtable[s[r]] ++; - if( hashtable[s[r]] == 1 ) - count ++; - r ++; - } - } - - return res; - } -}; - -int main() { - - cout< -#include -#include -#include - -using namespace std; - - -/// Problem -/***************************************************************************************************** - * - * Design and implement a TwoSum class. - * It should support the following operations: add and find. - * - * add - Add the number to an internal data structure. - * find - Find if there exists any pair of numbers which sum is equal to the value. - * - * For example, - * add(1); add(3); add(5); - * find(4) -> true - * find(7) -> false - *****************************************************************************************************/ - - -/// Solution -/******************************************************************************* - * If using array to store all the elements, - * - * We can make sure all the elements sorted whenever add a new number, - * In this case, - * add operation : O(n) - * find operation : O(n) - Two Pointers - * - * We can also sort the array when we need to do the find operation. - * In this case, - * add operation : O(1) - * find operation : O(nlogn) + O(n) - Sort + Two Pointers - * - * - * But, the most convenient way to store all the elements is using hashtable - * - * Time Complexity: add: O(1) , find: O(n) - * Space Complexity: O(n) - *****************************************************************************/ - -class TwoSum { - -private: - // The numbers store the number pair represent (number, count of the number) - unordered_map numbers; - -public: - - // Add the number to an internal data structure. - void add(int number) { - numbers[number] += 1; - } - - // Find if there exists any pair of numbers which sum is equal to the value. - bool find(int value) { - - for( unordered_map::iterator iter = numbers.begin() ; iter != numbers.end() ; iter ++ ){ - int num = iter->first; - if( numbers.find(value - num) != numbers.end() ){ - if( value - num == num && numbers[num] == 1 ) - continue; - - // value - num == num && numbers[num] >= 2 - // value - num != num - return true; - } - } - - return false; - } -}; - -int main() { - - TwoSum twoSum; - twoSum.add(1); - twoSum.add(3); - twoSum.add(5); - - cout< -#include - -using namespace std; - -/// Problem -/******************************************************************************************************** - * - * Write an algorithm to determine if a number is "happy". - * - * A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers. - * - * Example: 19 is a happy number - * - * 1^2 + 9^2 = 82 - * 8^2 + 2^2 = 68 - * 6^2 + 8^2 = 100 - * 1^2 + 0^2 + 0^2 = 1 - * - * Credits: - * Special thanks to @mithmatt and @ts for adding this problem and creating all test cases. - ********************************************************************************************************/ - - -/// Solution -/*********************************************************************************************** - * Using HashTable - * - * Time Complexity: O(?) - * Space Complexity: O(?) - ************************************************************************************************/ - -class Solution { -public: - bool isHappy(int n) { - - unordered_set record; - record.insert( n ); - while( n != 1 ){ - n = op(n); - if( record.find(n) == record.end() ) - record.insert(n); - else - return false; - } - - return true; - } - -private: - int op(int x){ - int res = 0; - while( x ){ - int t = x%10; - res += t*t; - x /= 10; - } - return res; - } -}; - -int main() { - - cout << Solution().isHappy(19)< -#include -#include -#include -#include - -using namespace std; - - -void printVector( const vector& v){ - - for( int i = 0 ; i < v.size() ; i ++) - cout<& nums, int k) { - - srand(time(NULL)); - return __findKthLargest(nums, 0, nums.size()-1 , k - 1 ); - } - -private: - int __findKthLargest( vector& nums, int l, int r, int k ){ - - if( l == r ) - return nums[l]; - - int p = partition( nums, l, r ); - - if( p == k ) - return nums[p]; - else if( k < p ) - return __findKthLargest( nums, l, p-1, k); - else // k > p - return __findKthLargest( nums, p+1 , r, k ); - } - - int partition( vector& nums, int l, int r ){ - - int p = rand()%(r-l+1) + l; - swap( nums[l] , nums[p] ); - - int lt = l + 1; //[l+1...lt) > p ; [lt..i) < p - for( int i = l + 1 ; i <= r ; i ++ ) - if( nums[i] > nums[l] ) - swap(nums[i], nums[lt++]); - - swap(nums[l], nums[lt-1]); - - return lt-1; - } -}; - -int main() { - - int nums1[] = {3, 2, 1, 5, 6, 4}; - vector vec1(nums1, nums1 + sizeof(nums1)/sizeof(int)); - - cout< vec2(nums2, nums2 + sizeof(nums2)/sizeof(int)); - - cout< vec3(nums3, nums3 + sizeof(nums3)/sizeof(int)); - - cout< -#include -#include - -using namespace std; - -/// Problem -/******************************************************************************************************** - * - * Given an array of integers, find if the array contains any duplicates. - * Your function should return true if any value appears at least twice in the array, - * and it should return false if every element is distinct. - ********************************************************************************************************/ - - -/// Solution -/*********************************************************************************************** - * Using HashTable - * - * Time Complexity: O(n) - * Space Complexity: O(n) - ************************************************************************************************/ - -class Solution { -public: - bool containsDuplicate(vector& nums) { - - unordered_set record; - for( int i = 0 ; i < nums.size() ; i ++ ) - if( record.find( nums[i] ) == record.end() ) - record.insert( nums[i] ); - else - return true; - - return false; - } -}; - -int main() { - - int nums[] = {0, 0, 1}; - vector vec( nums, nums + sizeof(nums)/sizeof(int)); - - cout << Solution().containsDuplicate( vec )< -#include - -using namespace std; - -/// Problem -/************************************************************************************************* - * Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. - * - * According to the definition of LCA on Wikipedia: - * “The lowest common ancestor is defined between two nodes v and w as the lowest node in T - * that has both v and w as descendants (where we allow a node to be a descendant of itself).” - * - * _______3______ - * / \ - * ___5__ ___1__ - * / \ / \ - * 6 _2 0 8 - * / \ - * 7 4 - * For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. - * Another example is LCA of nodes 5 and 4 is 5, - * since a node can be a descendant of itself according to the LCA definition. - **************************************************************************************************/ - - -/// Solution -/************************************************************************************** - * Recursion implementation - * - * Time Complexity: O(n) - * Space Complexity: O(1) - **************************************************************************************/ - - -///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: - // 在root中寻找p和q - // 如果p和q都在root所在的二叉树中, 则返回LCA - // 如果p和q只有一个在root所在的二叉树中, 则返回p或者q - // 如果p和q均不在root所在的二叉树中, 则返回NULL - TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { - - if( root == NULL ) - return root; - - if( root == p || root == q ) - return root; - - TreeNode *left = lowestCommonAncestor(root->left, p, q); - TreeNode *right = lowestCommonAncestor(root->right, p, q); - - if( left != NULL && right != NULL ) - return root; - - if( left != NULL ) - return left; - - if( right != NULL ) - return right; - - return NULL; - } -}; - -int main() { - cout << "Hello, World!" << endl; - return 0; -} \ No newline at end of file diff --git a/old/0242 Valid Anagram/cpp-Valid-Anagram/main.cpp b/old/0242 Valid Anagram/cpp-Valid-Anagram/main.cpp deleted file mode 100644 index 113d85d7..00000000 --- a/old/0242 Valid Anagram/cpp-Valid-Anagram/main.cpp +++ /dev/null @@ -1,63 +0,0 @@ -/// Source : https://leetcode.com/problems/valid-anagram/ -/// Author : liuyubobobo -/// Time : 2017-01-17 - -#include - -using namespace std; - -/// Problem -/******************************************************************************************************** - * - * Given two strings s and t, write a function to determine if t is an anagram of s. - * - * For example, - * s = "anagram", t = "nagaram", return true. - * s = "rat", t = "car", return false. - * - * Note: - * You may assume the string contains only lowercase alphabets. - * - * Follow up: - * What if the inputs contain unicode characters? - * How would you adapt your solution to such case? - ********************************************************************************************************/ - - -/// Solution -/*********************************************************************************************** - * Using Hashtable - * - * Time Complexity: O(n) - * Space Complexity: O(26) - ************************************************************************************************/ - -class Solution { -public: - bool isAnagram(string s, string t) { - - if( s.size() != t.size() ) - return false; - - int freq[26] = {0}; - for( int i = 0 ; i < s.size() ; i ++ ) - freq[s[i]-'a'] ++; - - for( int i = 0 ; i < t.size() ; i ++ ){ - freq[t[i]-'a'] --; - if( freq[t[i]-'a'] < 0 ) - return false; - } - - return true; - } -}; - -int main() { - - cout< -#include -#include -#include - -using namespace std; - - -/// Problem -/***************************************************************************************************** - * - * Given an array of n integers nums and a target, - * find the number of index triplets i, j, k with 0 <= i < j < k < n - * that satisfy the condition nums[i] + nums[j] + nums[k] < target. - * - * For example, given nums = [-2, 0, 1, 3], and target = 2. - * - * Return 2. Because there are two triplets which sums are less than 2: - * - * [-2, 0, 1] - * [-2, 0, 3] - *****************************************************************************************************/ - - -/// Solution 1 -/************************************************************************************** - * Sort the entire numbers first. - * For every number nums[i] and nums[j] in numbers, - * use binary search to find index k, - * which makes nums[i] + nums[j] + nums[k] is the closest sum less than the target. - * - * Time Complexity: O(nlogn) + O((n^2)logn) - * Space Complexity: O(1) - **************************************************************************************/ - -class Solution { -public: - int threeSumSmaller(vector& nums, int target) { - - // There're testcases which the nums.size < 3 - //assert( nums.size() >= 3 ); - if( nums.size() < 3 ) - return 0; - - sort(nums.begin(), nums.end()); - - int res = 0; - for( int i = 0 ; i < nums.size()-2 ; i ++ ){ - - for( int j = i + 1 ; j < nums.size()-1 ; j ++ ){ - - int t = target - nums[i] - nums[j]; - - // find the largest index in nums[j+1...nums.size()-1] - // where nums[index] < t - int index = bsearch( nums , j+1 , nums.size()-1 , t ); - - if( index != -1 ) - res += (index - j); - - } - } - - return res; - } - -private: - // find the largest index j in the range [l...r] where nums[j] < target - // return -1 if there's no element less than the given target - int bsearch(const vector &nums, int l, int r, int target){ - - assert( l >= 0 && r < nums.size() && l <= r ); - - // the left point is l-1 to give the space for non solution. - int left = l-1, right = r; - while( left != right ){ - - // Using round-up tecnique to avoid inifinite loop - int mid = left + (right-left+1)/2; - - if( nums[mid] >= target ) - right = mid - 1; - else - left = mid; - } - - if( left <= l-1 ) - return -1; - - return left; - } -}; - -int main() { - - int nums[] = {-2, 0, 1, 3}; - vector nums_vec(nums, nums + sizeof(nums)/sizeof(int)); - int target = 4; - - cout< -#include -#include -#include - -using namespace std; - - -/// Problem -/***************************************************************************************************** - * - * Given an array of n integers nums and a target, - * find the number of index triplets i, j, k with 0 <= i < j < k < n - * that satisfy the condition nums[i] + nums[j] + nums[k] < target. - * - * For example, given nums = [-2, 0, 1, 3], and target = 2. - * - * Return 2. Because there are two triplets which sums are less than 2: - * - * [-2, 0, 1] - * [-2, 0, 3] - *****************************************************************************************************/ - - -/// Solution 2 -/************************************************************************************************ - * Sort the entire numbers first. - * For every number nums[i], - * using two pointers technique to find indexes j and k, - * which makes nums[i] + nums[j] + nums[k] < target. - * Then, we can use j and k to calculate how many pairs can be got between nums[j] and nums[k]. - * - * Time Complexity: O(nlogn) + O(n^2) - * Space Complexity: O(1) - ************************************************************************************************/ - -class Solution { -public: - int threeSumSmaller(vector& nums, int target) { - - // There're testcases which the nums.size < 3 - //assert( nums.size() >= 3 ); - if( nums.size() < 3 ) - return 0; - - sort(nums.begin(), nums.end()); - - int res = 0; - for( int i = 0 ; i < nums.size()-2 ; i ++ ){ - - int j = i+1, k = nums.size()-1; - while( j < k ){ - - if( nums[i] + nums[j] + nums[k] < target ){ - res += (k-j); - j ++; - } - else - k --; - } - } - - return res; - } - -}; - -int main() { - - int nums[] = {-2, 0, 1, 3}; - vector nums_vec(nums, nums + sizeof(nums)/sizeof(int)); - int target = 4; - - cout< -#include -#include -#include -#include -//#include -#include -#include - -using namespace std; - - -/// Problem -/***************************************************************************************************** - * - * An abbreviation of a word follows the form . - * Below are some examples of word abbreviations: - * - * a) it --> it (no abbreviation) - * - * 1 - * b) d|o|g --> d1g - * - * 18 - * c) i|nternationalizatio|n --> i18n - * - * 10 - * d) l|ocalizatio|n --> l10n - * - * Assume you have a dictionary and given a word, - * find whether its abbreviation is unique in the dictionary. - * A word's abbreviation is unique if no other word from the dictionary has the same abbreviation. - * - * Example: - * Given dictionary = [ "deer", "door", "cake", "card" ] - * - * isUnique("dear") -> false - * - * isUnique("cart") -> true - * - * isUnique("cane") -> false - * - * isUnique("make") -> true - *****************************************************************************************************/ - - -/// Solution -/************************************************************************************** - * Use a hashtable to store all the string's abbreviation. - * The tricky part here is that we need another set to store all the different words. - * For function isUnique, we need to see: - * - The dictionary doesn't contain the word, then it's unique - * - The dictionary contains exactly the same word, - * and no aother word's abbreviation is the same, then it's unique (tricky) - * - The dictionary contains other words have the same abbreviation, - * then it's not unique. - * - * Time Complexity: - * If there are n words and the longest word contains slen character, then - * the building time : O(n*slen) - * isUnique : O(slen) - * Space Complexity: O(n) - **************************************************************************************/ - -class ValidWordAbbr { - -private: - unordered_set words; - unordered_map abbr_words; - - string abbr(const string &word){ - - //assert( word.size() >= 2 ); - - // According to the test cases, - // If a word's length is less than 2, - // Then the abbreviation is itself. - if( word.size() <= 2 ) - return word; - - int num = word.substr( 1 , word.size()-2 ).size(); - return word[0] + to_string(num) + word[word.size()-1]; - } - -public: - ValidWordAbbr(vector &dictionary) { - - for( int i = 0 ; i < dictionary.size() ; i ++ ){ - string word = dictionary[i]; - if( words.find( word ) == words.end() ){ - words.insert( word ); - abbr_words[ abbr(dictionary[i]) ] += 1; - } - } - } - - bool isUnique(string word) { - //assert( word.size() >= 2 ); - - if( words.find(word) == words.end() ) - return abbr_words[abbr(word)] == 0; - - return abbr_words[abbr(word)] == 1; - } - - void show(){ - - cout<<"words:"<::iterator iter = words.begin() ; iter != words.end() ; iter ++ ) - cout<<" "<<*iter<::iterator iter = abbr_words.begin() ; iter != abbr_words.end() ; iter ++ ) - cout << " ( " << iter->first << " , " << iter->second << " )"< dictionary; - dictionary.push_back("deer"); - dictionary.push_back("door"); - dictionary.push_back("cake"); - dictionary.push_back("card"); - dictionary.push_back("hello"); - - ValidWordAbbr vwa(dictionary); - vwa.show(); - - cout< -#include -#include -#include - -using namespace std; - - -/// Problem -/******************************************************************************** - * - * Write a function that takes a string as input and returns the string reversed. - * - * Example: - * - Given s = "hello", return "olleh". - **********************************************************************************/ - - -/// Solution -/************************************** - * Basic two pointers algorithm - * - * Time Complexity: O(n) - * Space Complexity: O(1) - **************************************/ - -class Solution { -public: - string reverseString(string s) { - int i = 0, j = s.size()-1; - while( i < j ) - swap( s[i++] , s[j--] ); - return s; - } -}; - -int main() { - - cout< -#include -#include -#include -#include - -using namespace std; - - -/// Problem -/****************************************************************************************** - * - * Write a function that takes a string as input and reverse only the vowels of a string. - * - * Example 1: - * Given s = "hello", return "holle". - * - * Example 2: - * Given s = "leetcode", return "leotcede". - * - * Note: - * The vowels does not include the letter "y". - *******************************************************************************************/ - - -/// Solution -/************************************** - * Using two pointers - * - * Time Complexity: O(n) - * Space Complexity: O(1) - **************************************/ - -class Solution { -public: - string reverseVowels(string s) { - - int i = nextVowelIndex( s , 0 ); - int j = preVowelIndex( s , s.size() - 1 ); - while( i < j ){ - swap( s[i] , s[j] ); - i = nextVowelIndex( s , i + 1 ); - j = preVowelIndex( s , j - 1 ); - } - - return s; - } - -private: - int nextVowelIndex( const string &s , int index ){ - - for( int i = index ; i < s.size() ; i ++ ) - if( isVowel(s[i]) ) - return i; - return s.size(); - } - - int preVowelIndex( const string &s , int index ){ - - for( int i = index ; i >= 0 ; i -- ) - if( isVowel(s[i]) ) - return i; - return -1; - } - - bool isVowel( char c ){ - - char lowerc = tolower(c); - return lowerc == 'a' || lowerc == 'e' || lowerc == 'i' || lowerc == 'o' || lowerc == 'u'; - } -}; - -int main() { - - cout< -#include -#include -#include - -using namespace std; - - -/// Problem -/*********************************************************************************************** - * - * Given a sorted array of integers nums and integer values a, b and c. - * Apply a function of the form f(x) = ax^2 + bx + c to each element x in the array. - * - * The returned array must be in sorted order. - * - * Expected time complexity: O(n) - * - * Example: - * - * nums = [-4, -2, 2, 4], a = 1, b = 3, c = 5, - * Result: [3, 9, 15, 33] - * - * nums = [-4, -2, 2, 4], a = -1, b = 3, c = 5 - * Result: [-23, -5, 1, 7] - * - * Credits: - * Special thanks to @elmirap for adding this problem and creating all test cases. - ***********************************************************************************************/ - - -/// Solution -/********************************************************************************** - * Based on the middle axis -b/(2a) to get the proper order of the transformation - * Need to pay attention when a == 0 - * - * Time Complexity: O(n) - * Space Complexity: O(1) - **********************************************************************************/ - -class Solution { -public: - vector sortTransformedArray(const vector& nums, int a, int b, int c) { - - vector res; - - if( a == 0 ){ - // If a == 0, the result of the transform is linear - for( int i = 0 ; i < nums.size() ; i ++ ) - res.push_back( applyTransform(nums[i], a, b, c) ); - - // If b < 0, we need to reverse the result to make the res be sorted - // from small elements to large elements - if( b < 0 ) - reverseArray( res ); - } - else{ - // If a != 0, we need to find the middle axis first - // which can be calculated as - b / 2*a - double m = - double(b)/double(2*a); - //cout<<"m = "< res2 = Solution().sortTransformedArray(nums_vec, -1, 3, 5); - for( int i = 0 ; i < res2.size() ; i ++ ) - cout< - -using namespace std; - -/// Problem -/******************************************************************************************************** - * - * Given a string, sort it in decreasing order based on the frequency of characters. - * - * Example 1: - * - * Input: "tree" - * Output: "eert" - * - * Explanation: - * 'e' appears twice while 'r' and 't' both appear once. - * So 'e' must appear before both 'r' and 't'. - * Therefore "eetr" is also a valid answer. - * - * Example 2: - * - * Input: "cccaaa" - * Output: "cccaaa" - * - * Explanation: - * Both 'c' and 'a' appear three times, so "aaaccc" is also a valid answer. - * Note that "cacaca" is incorrect, as the same characters must be together. - * - * Example 3: - * - * Input: "Aabb" - * Output: "bbAa" - * - * Explanation: - * "bbaA" is also a valid answer, but "Aabb" is incorrect. - * Note that 'A' and 'a' are treated as two different characters. - ********************************************************************************************************/ - - -/// Solution -/*********************************************************************************************** - * Using Counting Sort - * - * Time Complexity: O(n) - * Space Complexity: O(256) - ************************************************************************************************/ - -class Solution { -public: - string frequencySort(string s) { - - pair freq[256]; - for( int i = 0 ; i < 256 ; i ++ ){ - freq[i].first = i; - freq[i].second = 0; - } - - for( int i = 0 ; i < s.size() ; i ++ ) - freq[s[i]].second ++; - - sort( freq, freq+256, cmpFreq ); - - int index = 0; - for( int i = 0 ; i < s.size() ; i ++ ){ - while( !freq[index].second ) - index ++; - s[i] = freq[index].first; - freq[index].second --; - } - - return s; - } - -private: - static bool cmpFreq( const pair &a, const pair &b){ - return a.second > b.second; - } -}; - -int main() { - - cout << Solution().frequencySort("tree")< -#include -#include - -using namespace std; - -/// Problem -/*************************************************************************************** - * In the computer world, - * use restricted resource you have to generate maximum benefit is what we always want to pursue. - * - * For now, suppose you are a dominator of m 0s and n 1s respectively. - * On the other hand, there is an array with strings consisting of only 0s and 1s. - * - * Now your task is to find the maximum number of strings that you can form with given m 0s and n 1s. - * Each 0 and 1 can be used at most once. - * - * Note: - * The given numbers of 0s and 1s will both not exceed 100 - * The size of given string array won't exceed 600. - * - * Example 1: - * Input: Array = {"10", "0001", "111001", "1", "0"}, m = 5, n = 3 - * Output: 4 - * Explanation: - * This are totally 4 strings can be formed by the using of 5 0s and 3 1s, - * which are “10,”0001”,”1”,”0” - * - * Example 2: - * Input: Array = {"10", "0", "1"}, m = 1, n = 1 - * Output: 2 - * - * Explanation: You could form "10", but then you'd have nothing left. - * Better form "0" and "1". - ***************************************************************************************/ - - -/// Solution -/************************************************************************************** - * 0-1 backsack problem - * Recursion Implimentation - * - * Time Complexity: O(sizeof(array)*m*n) - * Space Complexity: O(sizeof(array)*m*n) - * - * Memory Limit Exceeded - **************************************************************************************/ - -class Solution { - -private: - vector mcost, ncost; - vector>> dp; - -public: - int findMaxForm(vector& strs, int m, int n) { - - for( int i = 0 ; i < strs.size() ; i ++ ){ - mcost.push_back(0); - ncost.push_back(0); - for( int j = 0 ; j < strs[i].size() ; j ++ ) - if( strs[i][j] == '0' ) - mcost[i] ++; - else - ncost[i] ++; - } - - for( int i = 0 ; i < strs.size() ; i ++ ){ - vector> t; - for( int j = 0 ; j <= m ; j ++ ) - t.push_back( vector( n+1, -1 ) ); - dp.push_back( t ); - } - - return __findMaxForm( strs.size() - 1 , m , n ); - } - -private: - int __findMaxForm( int k , int m , int n ){ - - if( k < 0 ) - return 0; - - if( dp[k][m][n] != -1 ) - return dp[k][m][n]; - - dp[k][m][n] = __findMaxForm( k-1 , m , n ); - if( m >= mcost[k] && n >= ncost[k] ) - dp[k][m][n] = max( 1 + __findMaxForm( k-1 , m - mcost[k] , n - ncost[k] ), - dp[k][m][n] ); - - return dp[k][m][n]; - } -}; - -int main() { - - vector vec1; - vec1.push_back("10"); - vec1.push_back("0001"); - vec1.push_back("111001"); - vec1.push_back("1"); - vec1.push_back("0"); - int m1 = 5; - int n1 = 3; - cout< vec2; - vec2.push_back("10"); - vec2.push_back("0"); - vec2.push_back("1"); - int m2 = 1; - int n2 = 1; - cout< -#include -#include - -using namespace std; - -/// Problem -/*************************************************************************************** - * In the computer world, - * use restricted resource you have to generate maximum benefit is what we always want to pursue. - * - * For now, suppose you are a dominator of m 0s and n 1s respectively. - * On the other hand, there is an array with strings consisting of only 0s and 1s. - * - * Now your task is to find the maximum number of strings that you can form with given m 0s and n 1s. - * Each 0 and 1 can be used at most once. - * - * Note: - * The given numbers of 0s and 1s will both not exceed 100 - * The size of given string array won't exceed 600. - * - * Example 1: - * Input: Array = {"10", "0001", "111001", "1", "0"}, m = 5, n = 3 - * Output: 4 - * Explanation: - * This are totally 4 strings can be formed by the using of 5 0s and 3 1s, - * which are “10,”0001”,”1”,”0” - * - * Example 2: - * Input: Array = {"10", "0", "1"}, m = 1, n = 1 - * Output: 2 - * - * Explanation: You could form "10", but then you'd have nothing left. - * Better form "0" and "1". - ***************************************************************************************/ - - -/// Solution -/************************************************************************************** - * 0-1 backsack problem - * Non-Recursion Implimentation - * - * Time Complexity: O(sizeof(array)*m*n) - * Space Complexity: O(sizeof(array)*m*n) - * - * Memory Limit Exceeded - **************************************************************************************/ - -class Solution { - -private: - vector mcost, ncost; - vector>> dp; - -public: - int findMaxForm(vector& strs, int m, int n) { - - for( int i = 0 ; i < strs.size() ; i ++ ){ - mcost.push_back(0); - ncost.push_back(0); - for( int j = 0 ; j < strs[i].size() ; j ++ ) - if( strs[i][j] == '0' ) - mcost[i] ++; - else - ncost[i] ++; - } - - for( int i = 0 ; i < strs.size() ; i ++ ){ - vector> t; - for( int j = 0 ; j <= m ; j ++ ) - t.push_back( vector( n+1, 0 ) ); - dp.push_back( t ); - } - - for( int u = mcost[0]; u <= m ; u ++ ) - for( int v = ncost[0] ; v <= n ; v ++ ) - dp[0][u][v] = 1; - - for( int i = 1 ; i < strs.size() ; i ++ ){ - - for( int u = 0 ; u <= m ; u ++ ) - for( int v = 0 ; v <= n ; v ++ ){ - dp[i][u][v] = dp[i-1][u][v]; - if( u >= mcost[i] && v >= ncost[i] ) - dp[i][u][v] = max( dp[i][u][v] , 1 + dp[i-1][u-mcost[i]][v-ncost[i]]); - } - } - - return dp[strs.size()-1][m][n]; - } - -}; - -int main() { - - vector vec1; - vec1.push_back("10"); - vec1.push_back("0001"); - vec1.push_back("111001"); - vec1.push_back("1"); - vec1.push_back("0"); - int m1 = 5; - int n1 = 3; - cout< vec2; - vec2.push_back("10"); - vec2.push_back("0"); - vec2.push_back("1"); - int m2 = 1; - int n2 = 1; - cout< -#include -#include - -using namespace std; - -/// Problem -/*************************************************************************************** - * In the computer world, - * use restricted resource you have to generate maximum benefit is what we always want to pursue. - * - * For now, suppose you are a dominator of m 0s and n 1s respectively. - * On the other hand, there is an array with strings consisting of only 0s and 1s. - * - * Now your task is to find the maximum number of strings that you can form with given m 0s and n 1s. - * Each 0 and 1 can be used at most once. - * - * Note: - * The given numbers of 0s and 1s will both not exceed 100 - * The size of given string array won't exceed 600. - * - * Example 1: - * Input: Array = {"10", "0001", "111001", "1", "0"}, m = 5, n = 3 - * Output: 4 - * Explanation: - * This are totally 4 strings can be formed by the using of 5 0s and 3 1s, - * which are “10,”0001”,”1”,”0” - * - * Example 2: - * Input: Array = {"10", "0", "1"}, m = 1, n = 1 - * Output: 2 - * - * Explanation: You could form "10", but then you'd have nothing left. - * Better form "0" and "1". - ***************************************************************************************/ - - -/// Solution -/************************************************************************************** - * 0-1 backsack problem - * Non-Recursion Implimentation, with space optimization - * - * Time Complexity: O(sizeof(array)*m*n) - * Space Complexity: O(m*n) - **************************************************************************************/ - -class Solution { - -private: - vector mcost, ncost; - vector>> dp; - -public: - int findMaxForm(vector& strs, int m, int n) { - - for( int i = 0 ; i < strs.size() ; i ++ ){ - mcost.push_back(0); - ncost.push_back(0); - for( int j = 0 ; j < strs[i].size() ; j ++ ) - if( strs[i][j] == '0' ) - mcost[i] ++; - else - ncost[i] ++; - } - - for( int i = 0 ; i < 2 ; i ++ ){ - vector> t; - for( int j = 0 ; j <= m ; j ++ ) - t.push_back( vector( n+1, 0 ) ); - dp.push_back( t ); - } - - for( int u = mcost[0]; u <= m ; u ++ ) - for( int v = ncost[0] ; v <= n ; v ++ ) - dp[0][u][v] = 1; - - for( int i = 1 ; i < strs.size() ; i ++ ){ - - for( int u = 0 ; u <= m ; u ++ ) - for( int v = 0 ; v <= n ; v ++ ){ - dp[i%2][u][v] = dp[(i-1)%2][u][v]; - if( u >= mcost[i] && v >= ncost[i] ) - dp[i%2][u][v] = max( dp[i%2][u][v] , 1 + dp[(i-1)%2][u-mcost[i]][v-ncost[i]]); - } - } - - return dp[(strs.size()-1)%2][m][n]; - } - -}; - -int main() { - - vector vec1; - vec1.push_back("10"); - vec1.push_back("0001"); - vec1.push_back("111001"); - vec1.push_back("1"); - vec1.push_back("0"); - int m1 = 5; - int n1 = 3; - cout< vec2; - vec2.push_back("10"); - vec2.push_back("0"); - vec2.push_back("1"); - int m2 = 1; - int n2 = 1; - cout< -#include -#include - -using namespace std; - -/// Problem -/*************************************************************************************** - * In the computer world, - * use restricted resource you have to generate maximum benefit is what we always want to pursue. - * - * For now, suppose you are a dominator of m 0s and n 1s respectively. - * On the other hand, there is an array with strings consisting of only 0s and 1s. - * - * Now your task is to find the maximum number of strings that you can form with given m 0s and n 1s. - * Each 0 and 1 can be used at most once. - * - * Note: - * The given numbers of 0s and 1s will both not exceed 100 - * The size of given string array won't exceed 600. - * - * Example 1: - * Input: Array = {"10", "0001", "111001", "1", "0"}, m = 5, n = 3 - * Output: 4 - * Explanation: - * This are totally 4 strings can be formed by the using of 5 0s and 3 1s, - * which are “10,”0001”,”1”,”0” - * - * Example 2: - * Input: Array = {"10", "0", "1"}, m = 1, n = 1 - * Output: 2 - * - * Explanation: You could form "10", but then you'd have nothing left. - * Better form "0" and "1". - ***************************************************************************************/ - - -/// Solution -/************************************************************************************** - * 0-1 backsack problem - * Non-Recursion Implimentation, with space optimization - * - * Time Complexity: O(sizeof(array)*m*n) - * Space Complexity: O(m*n) - **************************************************************************************/ - -class Solution { - -public: - int findMaxForm(vector& strs, int m, int n) { - - vector> dp( m+1 , vector(n+1, 0)); - - for( int i = 0 ; i < strs.size() ; i ++ ){ - - int mcost = 0, ncost = 0; - for( int j = 0 ; j < strs[i].size() ; j ++ ) - if( strs[i][j] == '0' ) - mcost ++; - else - ncost ++; - - for( int u = m ; u >= mcost ; u -- ) - for( int v = n ; v >= ncost ; v -- ) - dp[u][v] = max( dp[u][v] , 1 + dp[u-mcost][v-ncost]); - } - - return dp[m][n]; - } - -}; - -int main() { - - vector vec1; - vec1.push_back("10"); - vec1.push_back("0001"); - vec1.push_back("111001"); - vec1.push_back("1"); - vec1.push_back("0"); - int m1 = 5; - int n1 = 3; - cout< vec2; - vec2.push_back("10"); - vec2.push_back("0"); - vec2.push_back("1"); - int m2 = 1; - int n2 = 1; - cout< -contest 76: 801, 802, 803;
-contest 75: 798;
-contest 71: 782;
-contest 70: 779, 776, 777, 778;
-contest 69: 771, 775, 773, 774;
-772;
-contest 68: 767, 768, 769, 770;
-contest 67: 762, 763, 764, 765;
-contest 66: 758, 759, 760, 761;
-446;
-contest 65: 754, 755, 756, 757;
-409; 50; 305;
-contest 64: 747, 751, 752, 753;
-22, 527;
-contest 63: 746, 748, 749, 750;
-240, 200, 410, 118, 179, 287, 543, 646, 651, 647, 650, 541, 660, 659, 648, 663, 652, 661, 666, 664, 662, 657, 544, 649;
-contest 62: 743, 744;
-contest 61: 738, 739;
-contest 59: 730;
-contest 58: 726;
-contest 56, ... \ No newline at end of file diff --git a/qrcode.jpg b/qrcode.jpg deleted file mode 100644 index 2e4a05a3..00000000 Binary files a/qrcode.jpg and /dev/null differ diff --git a/qrcode.png b/qrcode.png new file mode 100644 index 00000000..e3a1ce7b Binary files /dev/null and b/qrcode.png differ diff --git a/readme.md b/readme.md index a96ecdd4..a9dd2126 100644 --- a/readme.md +++ b/readme.md @@ -1,289 +1,2674 @@ -## This is my solutions for Leetcode +## My solutions to Leetcode -I will put my solutions of [Leetcode Problems](https://leetcode.com/problemset/all/) in this repo. Every problem will be solved in C++; part of the problems will be solved in Java also. I will try my best to support more language in the future :) +I will put my solutions to [Leetcode Problems](https://leetcode.com/problemset/all/) in this repo. Every problem will be solved in C++; part of the problems will be solved in Java also. I will try my best to support more language in the future :) -Please feel free to contact me if you have any problems with this repo:) +Please feel free to contact me if you have any questions with this repo:) email: [liuyubobobo@gmail.com](mailto:liuyubobobo@gmail.com) --- -如果有任何问题,欢迎联系我:) +大家好,欢迎大家来到我的 **Leetcode 算法题解**代码仓。在这个代码仓中,近乎每一个问题都会使用多种方式进行解决,同时标注了简明的算法思想,时间复杂度和空间复杂度。所有问题都会使用C++进行解决,各别问题支持Java语言和Python语言。 -**个人网站**:[liuyubobobo.com](http://liuyubobobo.com) +如果对代码仓有任何问题,欢迎联系我:) **电子邮件**:[liuyubobobo@gmail.com](mailto:liuyubobobo@gmail.com) -**微博**: [刘宇波bobo http://weibo.com/liuyubobobo](http://weibo.com/liuyubobobo) - **知乎**: [刘宇波 http://www.zhihu.com/people/liuyubobobo](http://www.zhihu.com/people/liuyubobobo) **知乎专栏:**[是不是很酷 https://zhuanlan.zhihu.com/liuyubobobo](https://zhuanlan.zhihu.com/liuyubobobo) **个人公众号:是不是很酷**:) -![QRCode](qrcode.jpg) +![QRCode](qrcode.png) ---- +**知识星球(免费)** + +![zsxq](zsxq.jpg) + +
+ +## 其他相关代码仓 + +* [**《算法与数据结构》课程**](https://coding.imooc.com/class/71.html), 代码仓: [Play-with-Algorithms](https://github.com/liuyubobobo/Play-with-Algorithms) + +* [**《玩转算法面试》课程**](https://coding.imooc.com/class/82.html), 代码仓: [Play-with-Algorithm-Interview](https://github.com/liuyubobobo/Play-with-Algorithm-Interview) + +* [**《看得见的算法》课程**](https://coding.imooc.com/class/138.html), 代码仓: [Play-with-Algorithm-Visualization](https://github.com/liuyubobobo/Play-with-Algorithm-Visualization) -### Problems +* [**《玩转数据结构》课程**](https://coding.imooc.com/class/207.html), 代码仓: [Play-with-Data-Structures](https://github.com/liuyubobobo/Play-with-Data-Structures) + +* [**《玩转图论算法》课程**](https://coding.imooc.com/class/370.html), 代码仓: [Play-with-Graph-Algorithms](https://github.com/liuyubobobo/Play-with-Graph-Algorithms) + +* **LeetCode Database 题解代码仓**:[Play Leetcode Database](https://github.com/liuyubobobo/Play-Leetcode-Database/) + + +## Problems | ID | Problem | Official
Solution | C++ | Java | Python | -| --- | --- | :---: | :--- | :--- | :--- | -| 001 | [Two Sum](https://leetcode.com/problems/two-sum/description/) | [solution](https://leetcode.com/problems/two-sum/solution/) | [C++](0001-Two-Sum/cpp-0001/) | [Java](0001-Two-Sum/java-0001/src/) | | -| | | | | | | -| 003 | [Longest-Substring-Without-Repeating-Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/description/) | [solution](https://leetcode.com/problems/longest-substring-without-repeating-characters/solution/) | [C++](0003-Longest-Substring-Without-Repeating-Characters/cpp-0003/) | [Java](0003-Longest-Substring-Without-Repeating-Characters/java-0003/src/) | | -| | | | | | | -| 015 | [3Sum](https://leetcode.com/problems/3sum/description/) | [无] | [C++](0015-3Sum/cpp-0015/) | | | -| | | | | | | -| 017 | [Letter Combinations of a Phone Number](https://leetcode.com/problems/letter-combinations-of-a-phone-number/description/) | [无] | [C++](0017-Letter-Combinations-of-a-Phone-Number/cpp-0017/) | [Java](0017-Letter-Combinations-of-a-Phone-Number/java-0017/src/) | | -| | | | | | | -| 019 | [Remove Nth Node From End of List](https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/) | [solution](https://leetcode.com/problems/remove-nth-node-from-end-of-list/solution/) | [C++](0019-Remove-Nth-Node-From-End-of-List/cpp-0019/) | [Java](0019-Remove-Nth-Node-From-End-of-List/java-0019/src/) | | -| 020 | [Valid Parentheses](https://leetcode.com/problems/valid-parentheses/description/) | [无] | [C++](0020-Valid-Parentheses/cpp-0020/) | [Java](0020-Valid-Parentheses/java-0020/src/) | | -| 021 | [Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/description/) | [solution](https://leetcode.com/problems/merge-two-sorted-lists/solution/) | [C++](0021-Merge-Two-Sorted-Lists/cpp-0021/) | | | -| | | | | | | -| 024 | [Swap Nodes in Pairs](https://leetcode.com/problems/swap-nodes-in-pairs/description/) | [无] | [C++](0024-Swap-Nodes-in-Pairs/cpp-0024/) | [Java](0024-Swap-Nodes-in-Pairs/java-0024/src/) | | -| | | | | | | -| 034 | [Search for a Range](https://leetcode.com/problems/search-for-a-range/description/) | [solution](https://leetcode.com/problems/search-for-a-range/solution/) | [C++](0034-Search-for-a-Range/cpp-0034/) | | | -| | | | | | | -| 039 | [Combination Sum](https://leetcode.com/problems/combination-sum/description/) | [无] | [C++](0039-Combination-Sum/cpp-0039/) | | | -| 040 | [Combination Sum II](https://leetcode.com/problems/combination-sum-ii/description/) | [无] | [C++](0040-Combination-Sum-II/cpp-0040/) | | | -| | | | | | | -| 046 | [Permutations](https://leetcode.com/problems/permutations/description/) | [缺:排列算法整理] | [C++](0046-Permutations/cpp-0046/) | [Java](0046-Permutations/java-0046/src/) | | -| 047 | [Permutations II](https://leetcode.com/problems/permutations-ii/description/) | [无] | [C++](0047-Permutations-II/cpp-0047/) | | | -| | | | | | | -| 051 | [N-Queens](https://leetcode.com/problems/n-queens/description/) | [缺:N皇后问题整理] | [C++](0051-N-Queens/cpp-0051/) | [Java](0051-N-Queens/java-0051/src/) | | -| | | | | | | -| 056 | [Merge Intervals](https://leetcode.com/problems/merge-intervals/description/) | [solution](https://leetcode.com/problems/merge-intervals/solution/) | [C++](0056-Merge-Intervals/cpp-0056/) | | | -| | | | | | | -| 061 | [Rotate List](https://leetcode.com/problems/rotate-list/description/) | [无] | [C++](0061-Rotate-List/cpp-0061/) | | | -| | | | | | | -| 064 | [Minimum Path Sum](https://leetcode.com/problems/minimum-path-sum/description/) | [solution](https://leetcode.com/problems/minimum-path-sum/solution/) | [C++](0064-Minimum-Path-Sum/cpp-0064/) | [Java](0064-Minimum-Path-Sum/java-0064/src/) | | -| | | | | | | -| 070 | [Climbing Stairs](https://leetcode.com/problems/climbing-stairs/description/) | [solution](https://leetcode.com/problems/climbing-stairs/solution/) | [C++](0070-Climbing-Stairs/cpp-0070/) | [Java](0070-Climbing-Stairs/java-0070/src/) | | -| | | | | | | -| 075 | [Sort Colors](https://leetcode.com/problems/sort-colors/description/) | [无] | [C++](0075-Sort-Colors/cpp-0075/) | [Java](0075-Sort-Colors/java-0075/src/) | | -| | | | | | | -| 077 | [Combinations](https://leetcode.com/problems/combinations/description/) | [缺:组合算法整理] | [C++](0077-Combinations/cpp-0077/) | [Java](0077-Combinations/java-0077/src/) | | -| | | | | | | -| 079 | [Word Search](https://leetcode.com/problems/word-search/description/) | [无] | [C++](0079-Word-Search/cpp-0079/) | [Java](0079-Word-Search/java-0079/src/) | | -| | | | | | | -| 088 | [Merge Sorted Array](https://leetcode.com/problems/merge-sorted-array/description/) | [无] | [C++](0088-Merge-Sorted-Array/cpp-0088/) | | | -| | | | | | | -| 094 | [Binary Tree Inorder Traversal](https://leetcode.com/problems/binary-tree-inorder-traversal/description/) | [solution](https://leetcode.com/problems/binary-tree-inorder-traversal/solution/)
[缺:经典非递归算法] | [C++](0094-Binary-Tree-Inorder-Traversal/cpp-0094/) | [Java](0094-Binary-Tree-Inorder-Traversal/java-0094/src/) | | -| | | | | | | -| 102 | [Binary Tree Level Order Traversal](https://leetcode.com/problems/binary-tree-level-order-traversal/description/) | [无] | [C++](0102-Binary-Tree-Level-Order-Traversal/cpp-0102/) | [Java](0102-Binary-Tree-Level-Order-Traversal/java-0102/src/) | | -| | | | | | | -| 104 | [Maximum Depth of Binary Tree](https://leetcode.com/problems/maximum-depth-of-binary-tree/description/) | [无] | [C++](0104-Maximum-Depth-of-Binary-Tree/cpp-0104/) | [Java](0104-Maximum-Depth-of-Binary-Tree/java-0104/src/) | | -| | | | | | | -| 112 | [Path Sum](https://leetcode.com/problems/path-sum/description/) | [无] | [C++](0112-Path-Sum/cpp-0112/) | [Java](0112-Path-Sum/cpp-0112/src/) | | -| | | | | | | -| 120 | [Triangle](https://leetcode.com/problems/triangle/description/) | [无] | [C++](0120-Triangle/cpp-0120/) | | | -| 121 | [Best Time to Buy and Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/solution/) | | [C++](0121-Best-Time-to-Buy-and-Sell-Stock/cpp-0121/) | | | -| 122 | [Best Time to Buy and Sell Stock II](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/description/) | | [C++](0122-Best-Time-to-Buy-and-Sell-Stock-II/cpp-0122/) | | | -| 123 | [Best Time to Buy and Sell Stock III](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/description/) | | [C++](0123-Best-Time-to-Buy-and-Sell-Stock-III/cpp-0123/) | | | -| | | | | | | -| 127 | [Word Ladder](https://leetcode.com/problems/word-ladder/description/) | [无] | [C++](0127-Word-Ladder/cpp-0127/) | [Java](0127-Word-Ladder/java-0127/) | | -| 128 | [Longest Consecutive Sequence](https://leetcode.com/problems/longest-9consecutive-sequence/description/) | | [C++](0128-Longest-Consecutive-Sequence/cpp-0128/) | | | -| | | | | | | -| 141 | [Linked List Cycle](https://leetcode.com/problems/linked-list-cycle/description/) | [solution](https://leetcode.com/problems/linked-list-cycle/solution/) | [C++](0141-Linked-List-Cycle/cpp-0141/) | | | -| 142 | [Linked List Cycle II](https://leetcode.com/problems/linked-list-cycle-ii/description/) | [solution](https://leetcode.com/problems/linked-list-cycle-ii/description/) | [C++](0142-Linked-List-Cycle-II/cpp-0142/) | | | -| | | | | | | -| 144 | [Binary Tree Preorder Traversal](https://leetcode.com/problems/binary-tree-preorder-traversal/description/) | [无] | [C++](0144-Binary-Tree-Preorder-Traversal/cpp-0144/) | [Java](0144-Binary-Tree-Preorder-Traversal/java-0144/src/) | | -| 145 | [Binary Tree Postorder Traversal](https://leetcode.com/problems/binary-tree-postorder-traversal/description/) | [缺:经典非递归算法] | [C++](0145-Binary-Tree-Postorder-Traversal/cpp-0145/) | [Java](0145-Binary-Tree-Postorder-Traversal/java-0145/src/) | | -| | | | | | | -| 149 | [Max Points on a Line](https://leetcode.com/problems/max-points-on-a-line/description/) | [无] | [C++](0149-Max-Points-on-a-Line/cpp-0149/) | | | -| | | | | | | -| 249 | [Max Points on a Line](https://leetcode.com/problems/max-points-on-a-line/description/) | [无] | [C++](0249-Max-Points-on-a-Line/cpp-0249/) | | | -| | | | | | | -| 155 | [Min Stack](https://leetcode.com/problems/min-stack/description/) | [无] | [C++](0155-Min-Stack/cpp-0155/) | | | -| | | | | | | -| 167 | [Two Sum II - Input array is sorted](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/description/) | [solution](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/solution/) | [C++](0167-Two-Sum-II-Input-array-is-sorted/cpp-0167/) | [Java](0167-Two-Sum-II-Input-array-is-sorted/java-0167/src/) | | -| | | | | | | -| 169 | [Majority Element](https://leetcode.com/problems/majority-element/description/) | [solution](https://leetcode.com/problems/majority-element/solution/) | [C++](0169-Majority-Element/cpp-0169/) | | | -| | | | | | | -| 188 | [Best-Time-to-Buy-and-Sell-Stock-IV](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/description/) | | [C++](0188-Best-Time-to-Buy-and-Sell-Stock-IV/cpp-0188/) | | | -| | | | | | | -| 198 | [House Robber](https://leetcode.com/problems/house-robber/description/) | [solution](https://leetcode.com/problems/house-robber/solution/) | [C++](0198-House-Robber/cpp-0198/) | [Java](0198-House-Robber/java-0198/src/) | | -| | | | | | | -| 200 | [Number of Islands](https://leetcode.com/problems/number-of-islands/description/) | [无] | [C++](0200-Number-of-Islands/cpp-0200/) | [Java](0200-Number-of-Islands/java-0200/src/) | | -| | | | | | | -| 203 | [Remove Linked List Elements](https://leetcode.com/problems/remove-linked-list-elements/description/) | [无] | [C++](0203-Remove-Linked-List-Elements/cpp-0203/) | [Java](0203-Remove-Linked-List-Elements/java-0203/src/) | | -| | | | | | | -| 206 | [Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/description/) | [solution](https://leetcode.com/problems/reverse-linked-list/solution/) | [C++](0206-Reverse-Linked-List/cpp-0206/) | [Java](0206-Reverse-Linked-List/java-0206/src/) | | -| | | | | | | -| 208 | [Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree/description/) | [solution](https://leetcode.com/problems/implement-trie-prefix-tree/solution/) | [C++](0208-Implement-Trie-Prefix-Tree/cpp-0208/) | | | -| 209 | [Minimum Size Subarray Sum](https://leetcode.com/problems/minimum-size-subarray-sum/description/) | [solution](https://leetcode.com/problems/minimum-size-subarray-sum/solution/) | [C++](0209-Minimum-Size-Subarray-Sum/cpp-0209/) | [Java](0209-Minimum-Size-Subarray-Sum/java-0209/src/) | | -| | | | | | | -| 211 | [Add and Search Word - Data structure design](https://leetcode.com/problems/add-and-search-word-data-structure-design/description/) | [无] | [C++](0211-Add-and-Search-Word-Data-structure-design/cpp-0211/) | | | -| | | | | | | -| 213 | [House Robber II](https://leetcode.com/problems/house-robber-ii/description/) | [无] | [C++](0213/House-Robber-II/cpp-0213/) | | | -| | | | | | | -| 216 | [Combination Sum III](https://leetcode.com/problems/combination-sum-iii/description/) | [无] | [C++](0216/Combination-Sum-III/cpp-0216/) | | | -| | | | | | | -| 218 | [The Skyline Problem](https://leetcode.com/problems/the-skyline-problem/description/) | | [C++](0218-The-Skyline-Problem/cpp-0218/) | | | -| 219 | [Contains Duplicate II](https://leetcode.com/problems/contains-duplicate-ii/description/) | [solution](https://leetcode.com/problems/contains-duplicate-ii/solution/) | [C++](0219-Contains-Duplicate-II/cpp-0219/) | [Java](0219-Contains-Duplicate-II/java-0219/src/) | | -| 220 | [Contains Duplicate III](https://leetcode.com/problems/contains-duplicate-iii/description/) | [solution](https://leetcode.com/problems/contains-duplicate-iii/solution/) | [C++](0220-Contains-Duplicate-III/cpp-0220/) | [Java](0220-Contains-Duplicate-III/java-0220/) | | -| | | | | | | -| 226 | [Invert Binary Tree](https://leetcode.com/problems/invert-binary-tree/description/) | [solution](https://leetcode.com/problems/invert-binary-tree/solution/) | [C++](0226-Invert-Binary-Tree/cpp-0226/) | [Java](0226-Invert-Binary-Tree/java-0226/src/) | | -| | | | | | | -| 235 | [Lowest Common Ancestor of a Binary Search Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/description/) | [无] | [C++](0235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree/cpp-0235/) | [Java](0235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree/java-0235/src/) | | -| | | | | | | -| 237 | [Delete Node in a Linked List](https://leetcode.com/problems/delete-node-in-a-linked-list/description/) | [solution](https://leetcode.com/problems/delete-node-in-a-linked-list/solution/) | [C++](0237-Delete-Node-in-a-Linked-List/cpp-0237/) | [Java](0237-Delete-Node-in-a-Linked-List/java-0237/src/) | | -| | | | | | | -| 239 | [Sliding Window Maximum](https://leetcode.com/problems/sliding-window-maximum/description/) | [无] | [C++](0239-Sliding-Window-Maximum/cpp-0239/) | | | -| | | | | | | -| 254 | [Factor Combinations](https://leetcode.com/problems/factor-combinations/description/) | [无] | [C++](0254-Factor-Combinations/cpp-0254/) | | | -| | | | | | | -| 257 | [Binary Tree Paths](https://leetcode.com/problems/binary-tree-paths/description/) | [缺:非递归算法] | [C++](0257-Binary-Tree-Paths/cpp-0257/) | [Java](0257-Binary-Tree-Paths/java-0257/src/) | | -| | | | | | | -| 268 | [Missing Number](https://leetcode.com/problems/missing-number/description/) | [solution](https://leetcode.com/problems/missing-number/solution/) | [C++](0268-Missing-Number/cpp-0268/) | | | -| | | | | | | -| 279 | [Perfect Squares](https://leetcode.com/problems/perfect-squares/description/) | [无] | [C++](0279-Perfect-Squares/cpp-0279/) | [Java](0279-Perfect-Squares/java-0279/src/) | | -| | | | | | | -| 283 | [Move Zeroes](https://leetcode.com/problems/move-zeroes/description/) | [solution](https://leetcode.com/problems/move-zeroes/solution/) | [C++](0283-Move-Zeroes/cpp-0283/) | [Java](0283-Move-Zeroes/java-0283/src/) | | -| | | | | | | -| 287 | [Find the Duplicate Number](https://leetcode.com/problems/find-the-duplicate-number/description/) | | [C++](0287-Find-the-Duplicate-Number/cpp-0287/) | | | -| | | | | | | -| 300 | [Longest Increasing Subsequence](https://leetcode.com/problems/longest-increasing-subsequence/description/) | [solution](https://leetcode.com/problems/longest-increasing-subsequence/solution/) | [C++](0300-Longest-Increasing-Subsequence/cpp-0300/) | [Java](0300-Longest-Increasing-Subsequence/java-0300/src/) | | -| | | | | | | -| 303 | [Range Sum Query - Immutable](https://leetcode.com/problems/range-sum-query-immutable/description/) | | [C++](0303/Range-Sum-Query-Immutable/cpp-0303/) | | | -| | | | | | | -| 307 | [Range Sum Query - Mutable](https://leetcode.com/problems/range-sum-query-mutable/description/) | [缺:BIT] | [C++](0307-Range-Sum-Query-Mutable/cpp-0307/) | | | -| 308 | [Range Sum Query 2D - Mutable](https://leetcode.com/problems/range-sum-query-2d-mutable/description/) | | [C++](0308-Range-Sum-Query-2D-Mutable/cpp-0308/) | | | -| 309 | [Best Time to Buy and Sell Stock with Cooldown](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/description/) | | [C++](0309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown/cpp-0309/) | | | -| | | | | | | -| 319 | [Bulb Switcher](https://leetcode.com/problems/bulb-switcher/description/) | [无] | [C++](0319-Bulb-Switcher/cpp-0319/) | | | -| | | | | | | -| 322 | [Coin Change](https://leetcode.com/problems/coin-change/description/) | [solution](https://leetcode.com/problems/coin-change/solution/) | [C++](0322-Coin-Change/cpp-0322/) | | | -| | | | | | | -| 337 | [House Robber III](https://leetcode.com/problems/house-robber-iii/description/) | [无] | [C++](0337-House-Robber-III/cpp-0337/) | | | -| | | | | | | -| 343 | [Integer Break](https://leetcode.com/problems/integer-break/description/) | [无] | [C++](0343-Integer-Break/cpp-0343/) | [Java](0343-Integer-Break/java-0343/src/) | | -| | | | | | | -| 347 | [Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/description/) | [无] | [C++](0347-Top-K-Frequent-Elements/cpp-0347/) | [Java](0347-Top-K-Frequent-Elements/java-0347/src/) | | -| | | | | | | -| 349 | [Intersection of Two Arrays](https://leetcode.com/problems/intersection-of-two-arrays/description/) | [无] | [C++](0349-Intersection-of-Two-Arrays/cpp-0349/) | [Java](0349-Intersection-of-Two-Arrays/java-0349/src/) | | -| 350 | [Intersection of Two Arrays II](https://leetcode.com/problems/intersection-of-two-arrays-ii/description/) | [无] | [C++](0350-Intersection-of-Two-Arrays-II/cpp-0350/) | [Java](0350-Intersection-of-Two-Arrays-II/java-0350/src/) | | -| | | | | | | -| 370 | [Range Addition](https://leetcode.com/problems/range-addition/description/) | | [C++](0370-Range-Addition/cpp-0370/) | | | -| | | | | | | -| 377 | [Combination Sum IV](https://leetcode.com/problems/combination-sum-iv/description/) | [无] | [C++](0377-Combination-Sum-IV/cpp-0377/) | | | -| | | | | | | -| 384 | [Shuffle an Array](https://leetcode.com/problems/shuffle-an-array/description/) | [solution](https://leetcode.com/problems/shuffle-an-array/solution/) | [C++](0384-Shuffle-an-Array/cpp-0384/) | | | -| | | | | | | -| 386 | [Lexicographical Numbers](https://leetcode.com/problems/lexicographical-numbers/description/) | | [C++](0386-Lexicographical-Numbers/cpp-0386/) | | | -| 387 | [First Unique Character in a String](https://leetcode.com/problems/first-unique-character-in-a-string/description/) | | [C++](0387-First-Unique-Character-in-a-String/cpp-0387/) | | | -| 388 | [Longest Absolute File Path](https://leetcode.com/problems/longest-absolute-file-path/description/) | | [C++](0388-Longest-Absolute-File-Path/cpp-0388/) | | | -| 389 | [Find the Difference](https://leetcode.com/problems/find-the-difference/description/) | | [C++](0389-Find-the-Difference/cpp-0389/) | | | -| 390 | [Elimination Game](https://leetcode.com/problems/elimination-game/description/) | | [C++](0390-Elimination-Game/cpp-0390/) | | | -| 391 | [Perfect Rectangle](https://leetcode.com/problems/perfect-rectangle/description/) | [缺:矩形求交] | [C++](0391-Perfect-Rectangle/cpp-0391/) | | | -| | | | | | | -| 416 | [Partition Equal Subset Sum](https://leetcode.com/problems/partition-equal-subset-sum/description/) | [无] | [C++](0416-Partition-Equal-Subset-Sum/cpp-0416/) | [Java](0416-Partition-Equal-Subset-Sum/java-0416/src/) | | -| | | | | | | -| 434 | [Number of Segments in a String](https://leetcode.com/problems/number-of-segments-in-a-string/description/) | | [C++](0434-Number-of-Segments-in-a-String/cpp-0434/) | | | -| 435 | [Non-overlapping Intervals](https://leetcode.com/problems/non-overlapping-intervals/description/) | [solution](https://leetcode.com/problems/non-overlapping-intervals/solution/) | [C++](0435-Non-overlapping-Intervals/cpp-0435/) | [Java](0435-Non-overlapping-Intervals/java-0435/src/) | | -| | | | | | | -| 437 | [Path Sum III](https://leetcode.com/problems/path-sum-iii/description/) | [无] | [C++](0437-Path-Sum-III/cpp-0437/) | [Java](0437-Path-Sum-III/java-0437/src/) | | -| 438 | [Find All Anagrams in a String](https://leetcode.com/problems/find-all-anagrams-in-a-string/description/) | [无] | [C++](0438-Find-All-Anagrams-in-a-String/cpp-0438/) | | | -| | | | | | | -| 443 | [String Compression](https://leetcode.com/problems/string-compression/description/) | | [C++](0443-String-Compression/cpp-0443/) | | | -| | | | | | | -| 447 | [Number of Boomerangs](https://leetcode.com/problems/number-of-boomerangs/description/) | [无] | [C++](0447-Number-of-Boomerangs/cpp-0447/) | [Java](0447-Number-of-Boomerangs/java-0447/src/) | | -| | | | | | | -| 454 | [4Sum II](https://leetcode.com/problems/4sum-ii/description/) | [无] | [C++](0454-4Sum-II/cpp-0454/) | [Java](0454-4Sum-II/java-0454/src/) | | -| 455 | [Assign Cookies](https://leetcode.com/problems/assign-cookies/description/) | [无] | [C++](0455-Assign-Cookies/cpp-0455/) | [Java](0455-Assign-Cookies/java-0455/src/) | | -| | | | | | | -| 518 | [Coin Change 2](https://leetcode.com/problems/coin-change-2/description/) | [无] | [C++](0518-Coin-Change-2/cpp-0518/) | | | -| | | | | | | -| 583 | [Delete Operation for Two Strings](https://leetcode.com/problems/delete-operation-for-two-strings/description/) | [solution](https://leetcode.com/problems/delete-operation-for-two-strings/solution/) | [C++](0583-Delete-Operation-for-Two-Strings/cpp-0583/) | | | -| | | | | | | -| 598 | [Range Addition II](https://leetcode.com/problems/range-addition-ii/description/) | | [C++](0598-Range-Addition-II/cpp-0598/) | | | -| | | | | | | -| 600 | [Non-negative Integers without Consecutive Ones](https://leetcode.com/problems/non-negative-integers-without-consecutive-ones/description/) | [solution](https://leetcode.com/problems/non-negative-integers-without-consecutive-ones/solution/)
[缺:Bit Manipulation]| [C++](0600-Non-negative-Integers-without-Consecutive-Ones/cpp-0600/) | | | -| | | | | | | -| 648 | [Replace Words](https://leetcode.com/problems/replace-words/description/) | [无] | [C++](0648-Replace-Words/cpp-0648/) | | | -| | | | | | | -| 672 | [Bulb Switcher II](https://leetcode.com/problems/bulb-switcher-ii/description/) | [solution](https://leetcode.com/problems/bulb-switcher-ii/solution/) | [C++](0672-Bulb-Switcher-II/cpp-0672/) | | | -| 673 | [Number of Longest Increasing Subsequence](https://leetcode.com/problems/number-of-longest-increasing-subsequence/description/) | [缺:BIT;线段树] | [C++](0673-Number-of-Longest-Increasing-Subsequence/cpp-0673/) | | | -| 674 | [Longest Continuous Increasing Subsequence](https://leetcode.com/problems/longest-continuous-increasing-subsequence/description/) | | [C++](0674-Longest-Continuous-Increasing-Subsequence/cpp-0674/) | | | -| 675 | [Cut Off Trees for Golf Event](https://leetcode.com/problems/cut-off-trees-for-golf-event/description/) | [缺:A*;Hadlock's Algo] | [C++](0675-Cut-Off-Trees-for-Golf-Event/cpp-0675/) | | | -| 676 | [Implement Magic Dictionary](https://leetcode.com/problems/implement-magic-dictionary/description/) | [solution](https://leetcode.com/problems/implement-magic-dictionary/solution/) | [C++](0676-Implement-Magic-Dictionary/cpp-0676/) | | | -| 677 | [Map Sum Pairs](https://leetcode.com/problems/map-sum-pairs/description/) | [solution](https://leetcode.com/problems/map-sum-pairs/solution/) | [C++](0677/Map-Sum-Pairs/cpp-0677/) | | | -| | | | | | | -| 684 | [Redundant Connection](https://leetcode.com/problems/redundant-connection/description/) | [solution](https://leetcode.com/problems/redundant-connection/solution/) | [C++](0684-Redundant-Connection/cpp-0684/) | | | -| 685 | [Redundant Connection II](https://leetcode.com/problems/redundant-connection-ii/description/) | [solution](https://leetcode.com/problems/redundant-connection-ii/solution/) | [C++](0685-Redundant-Connection-II/cpp-0685/) | | | -| | | | | | | -| 690 | [Employee Importance](https://leetcode.com/problems/employee-importance/description/) | [solution](https://leetcode.com/problems/employee-importance/solution/) | [C++](0690-Employee-Importance/cpp-0690/) | | | -| | | | | | | -| 692 | [Top K Frequent Words](https://leetcode.com/problems/top-k-frequent-words/description/) | [solution](https://leetcode.com/problems/top-k-frequent-words/solution/) | [C++](0692-Top-K-Frequent-Words/cpp-0692/) | | | -| | | | | | | -| 694 | [Number of Distinct Islands](https://leetcode.com/problems/number-of-distinct-islands/description/) | [review: hash的方式] | [C++](0694-Number-of-Distinct-Islands/cpp-0694/) | | | -| 695 | [Max-Area-of-Island](https://leetcode.com/problems/max-area-of-island/description/) | | [C++](0695-Max-Area-of-Island/cpp-0695) | | | -| 696 | [Count Binary Substrings](https://leetcode.com/problems/count-binary-substrings/description/) | | [C++](0696-Count-Binary-Substrings/cpp-0696/) | | | -| 697 | [Degree of an Array](https://leetcode.com/problems/degree-of-an-array/description/) | | [C++](0697-Degree-of-an-Array/cpp-0697/) | | | -| 698 | [Partition to K Equal Sum Subsets](https://leetcode.com/problems/partition-to-k-equal-sum-subsets/description/) | | [C++](0698-Partition-to-K-Equal-Sum-Subsets/cpp-0698/) | [Java](0698-Partition-to-K-Equal-Sum-Subsets/java-0698/src/) | | -| 699 | [Falling Squares](https://leetcode.com/contest/leetcode-weekly-contest-54/problems/falling-squares/) | [缺:线段树;块状链表] | [C++](0699-Falling-Squares/cpp-0699/) | | | -| | | | | | | -| 711 | [Number of Distinct Islands II](https://leetcode.com/problems/number-of-distinct-islands-ii/description/) | [review: hash的方式] | [C++](0711-Number-of-Distinct-Islands-II/cpp-0711/) | | | -| 712 | [Minimum ASCII Delete Sum for Two Strings](https://leetcode.com/problems/minimum-ascii-delete-sum-for-two-strings/description/) | | [C++](0712-Minimum-ASCII-Delete-Sum-for-Two-Strings/cpp-0712/) | | | -| 713 | [Subarray Product Less Than K](https://leetcode.com/problems/subarray-product-less-than-k/description/) | | [C++](0713-Subarray-Product-Less-Than-K/cpp-0713/) | | | -| 714 | [Best Time to Buy and Sell Stock with Transaction Fee](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/description/) | | [C++](0714-Best-Time-to-Buy-and-Sell-Stock-with-Transaction-Fee/cpp-0714/) | | | -| 715 | [Range Module](https://leetcode.com/problems/range-module/description/) | [缺:set查找] | [C++](0715-Range-Module/cpp-0715/) | | | -| 716 | [Max Stack](https://leetcode.com/problems/max-stack/description/) | [solution](https://leetcode.com/problems/max-stack/solution/) | [C++](0716-Max-Stack/cpp-0716/) | | | -| 717 | [1-bit and 2-bit Characters](https://leetcode.com/problems/1-bit-and-2-bit-characters/description/) | | [C++](0717-1-bit-and-2-bit-Characters/cpp-0717/) | | | -| 718 | [Maximum Length of Repeated Subarray](https://leetcode.com/problems/maximum-length-of-repeated-subarray/description/) | [缺:Rolling Hash] | [C++](0718-Maximum-Length-of-Repeated-Subarray/cpp-0718/) | | | -| 719 | [Find K-th Smallest Pair Distance](https://leetcode.com/problems/find-k-th-smallest-pair-distance/description/) | [缺:二分搜索] | [C++](0719-Find-K-th-Smallest-Pair-Distance/cpp-0719/) | | | -| 720 | [Longest Word in Dictionary](https://leetcode.com/problems/longest-word-in-dictionary/description/) | [solution](https://leetcode.com/problems/longest-word-in-dictionary/solution/) | [C++](0720-Longest-Word-in-Dictionary/cpp-0720/) | | | -| 721 | [Accounts Merge](https://leetcode.com/problems/accounts-merge/description/) | [solution](https://leetcode.com/problems/accounts-merge/solution/) | [C++](0721-Accounts-Merge/cpp-0721/) | | | -| 722 | [Remove Comments](https://leetcode.com/problems/remove-comments/description/) | [solution](https://leetcode.com/problems/remove-comments/solution/) | [C++](0722-Remove-Comments/cpp-0722/) | | | -| 723 | [Candy Crush](https://leetcode.com/problems/candy-crush/description/) | [solution](https://leetcode.com/problems/candy-crush/solution/) | [C++](0723-Candy-Crush/cpp-0723/) | | | -| 724 | [Find Pivot Index](https://leetcode.com/problems/find-pivot-index/description/) | [solution](https://leetcode.com/problems/find-pivot-index/solution/) | [C++](0724-Find-Pivot-Index/cpp-0724/) | | | -| 725 | [Split Linked List in Parts](https://leetcode.com/problems/split-linked-list-in-parts/description/) | [solution](https://leetcode.com/problems/split-linked-list-in-parts/solution/) | [C++](0725-Split-Linked-List-in-Parts/cpp-0725/) | | | -| | | | | | | -| 727 | [Minimum Window Subsequence](https://leetcode.com/problems/minimum-window-subsequence/description/) | [solution](https://leetcode.com/problems/minimum-window-subsequence/solution/) | [C++](cpp-Minimum-Window-Subsequence/cpp-0727/) | | | -| 728 | [Self Dividing Numbers](https://leetcode.com/problems/self-dividing-numbers/description/) | [solution](https://leetcode.com/problems/self-dividing-numbers/solution/) | [C++](0728-Self-Dividing-Numbers/cpp-0728/) | | | -| 729 | [My Calendar I](https://leetcode.com/problems/my-calendar-i/description/) | [solution](https://leetcode.com/problems/my-calendar-i/solution/) | [C++](0729-My-Calendar-I/cpp-0729/) | | | -| | | | | | | -| 731 | [My Calendar II](https://leetcode.com/problems/my-calendar-ii/description/) | [solution](https://leetcode.com/problems/my-calendar-ii/solution/) | [C++](0731-My-Calendar-II/cpp-0731/) | | | -| 732 | [My Calendar III](https://leetcode.com/problems/my-calendar-iii/description/) | [solution](https://leetcode.com/problems/my-calendar-iii/solution/) | [C++](0732-My-Calendar-III/cpp-0732/) | | | -| 733 | [Flood Fill](https://leetcode.com/problems/flood-fill/description/) | [solution](https://leetcode.com/problems/flood-fill/solution/) | [C++](0733-Flood-Fill/cpp-0733/) | | | -| 734 | [Sentence Similarity](https://leetcode.com/problems/sentence-similarity/description/) | [solution](https://leetcode.com/problems/sentence-similarity/solution/) | [C++](0734-Sentence-Similarity/cpp-0734/) | | | -| 735 | [Asteroid Collision](https://leetcode.com/problems/asteroid-collision/description/) | [solution](https://leetcode.com/problems/asteroid-collision/solution/) | [C++](0735-Asteroid-Collision/cpp-0735/) | | | -| 736 | [Parse Lisp Expression](https://leetcode.com/problems/parse-lisp-expression/description/) | [solution](https://leetcode.com/problems/parse-lisp-expression/solution/) | [C++](0736-Parse-Lisp-Expression/cpp-0736/) | | | -| 737 | [Sentence Similarity II](https://leetcode.com/problems/sentence-similarity-ii/description/) | [solution](https://leetcode.com/problems/sentence-similarity-ii/solution/) | [C++](0737-Sentence-Similarity-II/cpp-0737/) | | | -| | | | | | | -| 740 | [Delete and Earn](https://leetcode.com/problems/delete-and-earn/description/) | [solution](https://leetcode.com/problems/delete-and-earn/solution/) | [C++](0740-Delete-and-Earn/cpp-0740/) | | | -| 741 | [Cherry Pickup](https://leetcode.com/problems/cherry-pickup/description/) | [solution](https://leetcode.com/problems/cherry-pickup/solution/)
[缺:自底向上的动态规划] | [C++](0741-Cherry-Pickup/cpp-0741/) | | | -| | | | | | | -| 766 | [Toeplitz Matrix](https://leetcode.com/problems/toeplitz-matrix/description/) | [solution](https://leetcode.com/problems/toeplitz-matrix/solution/) | [C++](0766-Toeplitz-Matrix/cpp-0766/) | | | -| 780 | [Reaching Points](https://leetcode.com/problems/reaching-points/description/) | [solution](https://leetcode.com/problems/reaching-points/solution/) | [C++](0780-Reaching-Points/cpp-0780/) | | | -| 781 | [Rabbits in Forest](https://leetcode.com/problems/rabbits-in-forest/description/) | [solution](https://leetcode.com/problems/rabbits-in-forest/solution/) | [C++](0781-Rabbits-in-Forest/cpp-0781/) | | | -| | | | | | | -| 783 | [Minimum Distance Between BST Nodes](https://leetcode.com/problems/minimum-distance-between-bst-nodes/description/) | [solution](https://leetcode.com/problems/minimum-distance-between-bst-nodes/solution/) | [C++](0783-Minimum-Distance-Between-BST-Nodes/cpp-0783/) | | | -| 784 | [Letter Case Permutation](https://leetcode.com/problems/letter-case-permutation/description/) | [solution](https://leetcode.com/problems/letter-case-permutation/solution/) | [C++](0784-Letter-Case-Permutation/cpp-0784/) | | | -| 785 | [Is Graph Bipartite?](https://leetcode.com/problems/is-graph-bipartite/description/) | [solution](https://leetcode.com/problems/is-graph-bipartite/description/) | [C++](0785-Is-Graph-Bipartite/cpp-0785/) | | | -| 786 | [K-th Smallest Prime Fraction](https://leetcode.com/problems/k-th-smallest-prime-fraction/description/) | [solution](https://leetcode.com/problems/k-th-smallest-prime-fraction/solution/)
[缺:分治算法] | [C++](0786-K-th-Smallest-Prime-Fraction/cpp-0786/) | | | -| 787 | [Cheapest Flights Within K Stops](https://leetcode.com/problems/cheapest-flights-within-k-stops/description/) | [solution](https://leetcode.com/problems/cheapest-flights-within-k-stops/solution/)
[缺:使用Heap] | [C++](0787-Cheapest-Flights-Within-K-Stops/cpp-0787/) | | | -| 788 | [Rotated Digits](https://leetcode.com/problems/rotated-digits/description/) | [solution](https://leetcode.com/problems/rotated-digits/solution/) | [C++](0788-Rotated-Digits/cpp-0788/) | | | -| 789 | [Escape The Ghosts](https://leetcode.com/problems/escape-the-ghosts/description/) | [solution](https://leetcode.com/problems/escape-the-ghosts/solution/) | [C++](0789-Escape-The-Ghosts/cpp-0789/) | | | -| 790 | [Domino and Tromino Tiling](https://leetcode.com/problems/domino-and-tromino-tiling/description/) | [solution](https://leetcode.com/problems/domino-and-tromino-tiling/solution/)
[缺:转移矩阵求幂解法] | [C++](0790-Domino-and-Tromino-Tiling/cpp-0790/) | | | -| 791 | [Custom Sort String](https://leetcode.com/problems/custom-sort-string/description/) | [solution](https://leetcode.com/problems/custom-sort-string/solution/) | [C++](0791-Custom-Sort-String/cpp-0791/) | | | -| 792 | [Number of Matching Subsequences](https://leetcode.com/problems/number-of-matching-subsequences/description/) | [solution](https://leetcode.com/problems/number-of-matching-subsequences/solution/) | [C++](0792-Number-of-Matching-Subsequences/cpp-0792/) | | | -| 793 | [Preimage Size of Factorial Zeroes Function](https://leetcode.com/problems/preimage-size-of-factorial-zeroes-function/description/) | [solution](https://leetcode.com/problems/preimage-size-of-factorial-zeroes-function/solution/) | [C++](0793-Preimage-Size-of-Factorial-Zeroes-Function/cpp-0793/) | | | -| 794 | [Valid Tic-Tac-Toe State](https://leetcode.com/problems/valid-tic-tac-toe-state/description/) | [solution](https://leetcode.com/problems/valid-tic-tac-toe-state/solution/) | [C++](0794-Valid-Tic-Tac-Toe-State/cpp-0794/) | | | -| 795 | [Number of Subarrays with Bounded Maximum](https://leetcode.com/problems/number-of-subarrays-with-bounded-maximum/description/) | [solution](https://leetcode.com/problems/number-of-subarrays-with-bounded-maximum/solution/) | [C++](0795-Number-of-Subarrays-with-Bounded-Maximum/cpp-0795/) | | | -| 796 | [Rotate String](https://leetcode.com/problems/rotate-string/description/) | [solution](https://leetcode.com/problems/rotate-string/solution/)
[缺:Rolling Hash] | [C++](0796-Rotate-String/cpp-0796/) | | | -| 797 | [All Paths From Source to Target](https://leetcode.com/problems/all-paths-from-source-to-target/description/) | [solution](https://leetcode.com/problems/all-paths-from-source-to-target/solution/) | [C++](0797-All-Paths-From-Source-to-Target/cpp-0797/) | | | -| | | | | | | -| 799 | [Champagne Tower](https://leetcode.com/problems/champagne-tower/description/) | [solution](https://leetcode.com/problems/champagne-tower/solution/) | [C++](0799-Champagne-Tower/cpp-0799/) | | | -| 800 | [Similar RGB Color](https://leetcode.com/problems/similar-rgb-color/description/) | [solution](https://leetcode.com/problems/similar-rgb-color/solution/) | [C++](0800-Similar-RGB-Color/cpp-0800/) | | | -| | | | | | | -| 804 | [Unique Morse Code Words](https://leetcode.com/problems/unique-morse-code-words/description/) | [solution](https://leetcode.com/problems/unique-morse-code-words/solution/) | [C++](0804-Unique-Morse-Code-Words/cpp-0804/) | | | -| 805 | [Split Array With Same Average](https://leetcode.com/problems/split-array-with-same-average/description/) | [solution](https://leetcode.com/problems/split-array-with-same-average/solution/) | [C++](0805-Split-Array-With-Same-Average/cpp-0805/) | | | -| 806 | [Number of Lines To Write String](https://leetcode.com/problems/number-of-lines-to-write-string/description/) | [solution](https://leetcode.com/problems/number-of-lines-to-write-string/solution/) | [C++](0806-Number-of-Lines-To-Write-String/cpp-0806/) | | | +| --- | --- | :---: | :---: | :---: | :---: | +| 001 | [Two Sum](https://leetcode.com/problems/two-sum/description/) | [solution](https://leetcode.com/problems/two-sum/solution/) | [C++](0001-0500/0001-Two-Sum/cpp-0001/) | [Java](0001-0500/0001-Two-Sum/java-0001/src/) | | +| 002 | [Add Two Numbers](https://leetcode.com/problems/add-two-numbers/description/) | [solution](https://leetcode.com/problems/add-two-numbers/solution/) | [C++](0001-0500/0002-Add-Two-Numbers/cpp-0002/) | | | +| 003 | [Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/description/) | [solution](https://leetcode.com/problems/longest-substring-without-repeating-characters/solution/) | [C++](0001-0500/0003-Longest-Substring-Without-Repeating-Characters/cpp-0003/) | [Java](0001-0500/0003-Longest-Substring-Without-Repeating-Characters/java-0003/src/) | | +| 004 | [Median of Two Sorted Arrays](https://leetcode.com/problems/median-of-two-sorted-arrays/) | [solution](https://leetcode.com/problems/median-of-two-sorted-arrays/solution/) | [C++](0001-0500/0004-Median-of-Two-Sorted-Arrays/cpp-0004/) | [Java](0001-0500/0004-Median-of-Two-Sorted-Arrays/java-0004/) | | +| 005 | [Longest Palindromic Substring](https://leetcode.com/problems/longest-palindromic-substring/) | [solution](https://leetcode.com/problems/longest-palindromic-substring/solution/) | [C++](0001-0500/0005-Longest-Palindromic-Substring/cpp-0005/) | | | +| 006 | [Zigzag Conversion](https://leetcode.com/problems/zigzag-conversion/) | [solution](https://leetcode.com/problems/zigzag-conversion/solution/) | [C++](0001-0500/0006-Zigzag-Conversion/cpp-006/) | | | +| 007 | [Reverse Integer](https://leetcode.com/problems/reverse-integer/description/) | [solution](https://leetcode.com/problems/reverse-integer/solution/) | [C++](0001-0500/0007-Reverse-Integer/cpp-0007/) | | | +| 008 | [String to Integer (atoi)](https://leetcode.com/problems/string-to-integer-atoi/) | [solution](https://leetcode.com/problems/string-to-integer-atoi/solution/) | [C++](0001-0500/0008-String-to-Integer/cpp-0008/) | | | +| | | | | | | +| 010 | [Regular Expression Matching](https://leetcode.com/problems/regular-expression-matching/) | [solution](https://leetcode.com/problems/regular-expression-matching/solution/) | [C++](0001-0500/0010-Regular-Expression-Matching/cpp-0010/) | | | +| 011 | [Container With Most Water](https://leetcode.com/problems/container-with-most-water/description/) | [solution](https://leetcode.com/problems/container-with-most-water/solution/) | [C++](0001-0500/0011-Container-With-Most-Water/cpp-0011/) | | | +| 012 | [Integer to Roman](https://leetcode.com/problems/integer-to-roman/description/) | [无] | [C++](0001-0500/0012-Integer-to-Roman/cpp-0012/) | | | +| 013 | [Roman to Integer](https://leetcode.com/problems/roman-to-integer/description/) | [无] | [C++](0001-0500/0013-Roman-to-Integer/cpp-0013/) | | | +| 014 | [Longest Common Prefix](https://leetcode.com/problems/longest-common-prefix/description/) | [无] | [C++](0001-0500/0014-Longest-Common-Prefix/cpp-0014/) | | | +| 015 | [3Sum](https://leetcode.com/problems/3sum/description/) | [无] | [C++](0001-0500/0015-3Sum/cpp-0015/) | | | +| 016 | [3Sum Closest](https://leetcode.com/problems/3sum-closest/description/) | [无] | [C++](0001-0500/0016-3Sum-Closest/cpp-0016/) | | | +| 017 | [Letter Combinations of a Phone Number](https://leetcode.com/problems/letter-combinations-of-a-phone-number/description/) | [solution](https://leetcode.com/problems/letter-combinations-of-a-phone-number/solution/) | [C++](0001-0500/0017-Letter-Combinations-of-a-Phone-Number/cpp-0017/) | [Java](0001-0500/0017-Letter-Combinations-of-a-Phone-Number/java-0017/src/) | | +| 018 | [4Sum](https://leetcode.com/problems/4sum/description/) | [无] | [C++](0001-0500/0018-4Sum/cpp-0018/) | | | +| 019 | [Remove Nth Node From End of List](https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/) | [solution](https://leetcode.com/problems/remove-nth-node-from-end-of-list/solution/) | [C++](0001-0500/0019-Remove-Nth-Node-From-End-of-List/cpp-0019/) | [Java](0001-0500/0019-Remove-Nth-Node-From-End-of-List/java-0019/src/) | | +| 020 | [Valid Parentheses](https://leetcode.com/problems/valid-parentheses/description/) | [solution](https://leetcode.com/problems/valid-parentheses/solution/) | [C++](0001-0500/0020-Valid-Parentheses/cpp-0020/) | [Java](0001-0500/0020-Valid-Parentheses/java-0020/src/) | | +| 021 | [Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/description/) | [solution](https://leetcode.com/problems/merge-two-sorted-lists/solution/) | [C++](0001-0500/0021-Merge-Two-Sorted-Lists/cpp-0021/) | | | +| 022 | [Generate Parentheses](https://leetcode.com/problems/generate-parentheses/description/) | [solution](https://leetcode.com/problems/generate-parentheses/solution/) | [C++](0001-0500/0022-Generate-Parentheses/cpp-0022/) | [Java](0001-0500/0022-Generate-Parentheses/java-0022/) | [Python](0022-Generate-Parentheses/py-0022/) | +| 023 | [Merge k Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/description/) | [solution](https://leetcode.com/problems/merge-k-sorted-lists/solution/) | [C++](0001-0500/0023-Merge-k-Sorted-Lists/cpp-0023/) | | | +| 024 | [Swap Nodes in Pairs](https://leetcode.com/problems/swap-nodes-in-pairs/description/) | [无] | [C++](0001-0500/0024-Swap-Nodes-in-Pairs/cpp-0024/) | [Java](0001-0500/0024-Swap-Nodes-in-Pairs/java-0024/src/) | | +| 025 | [Reverse Nodes in k-Group](https://leetcode.com/problems/reverse-nodes-in-k-group/description/) | [无] | [C++](0001-0500/0025-Reverse-Nodes-in-k-Group/cpp-0025/) | | | +| 026 | [Remove Duplicates from Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/) | [solution](https://leetcode.com/problems/remove-duplicates-from-sorted-array/solution/) | [C++](0001-0500/0026-Remove-Duplicates-from-Sorted-Array/cpp-0026/) | | | +| 027 | [Remove Element](https://leetcode.com/problems/remove-element/description/) | [solution](https://leetcode.com/problems/remove-element/solution/) | [C++](0001-0500/0027-Remove-Element/cpp-0027/) | | | +| 028 | [Implement strStr()](https://leetcode.com/problems/implement-strstr/description/) | [无]
[缺:完整BM算法, 其他模式匹配算法] | [C++](0001-0500/0028-Implement-strStr/cpp-0028/) | | | +| 029 | [Divide Two Integers](https://leetcode.com/problems/divide-two-integers/) | [solution](https://leetcode.com/problems/divide-two-integers/solution/)
[缺:不使用乘法加法除法] | [C++](0001-0500/0029-Divide-Two-Integers/cpp-0029/) | | | +| 030 | [Substring with Concatenation of All Words](https://leetcode.com/problems/substring-with-concatenation-of-all-words/) | [solution](https://leetcode.com/problems/substring-with-concatenation-of-all-words/solution/) | [C++](0001-0500/0030-Substring-with-Concatenation-of-All-Words/cpp-0030/) | | | +| 031 | [Next Permutation](https://leetcode.com/problems/next-permutation/) | [solution](https://leetcode.com/problems/next-permutation/solution/) | [C++](0001-0500/0031-Next-Permutation/cpp-0031/) | | | +| | | | | | | +| 033 | [Search in Rotated Sorted Array](https://leetcode.com/problems/search-in-rotated-sorted-array/description/) | [solution](https://leetcode.com/problems/search-in-rotated-sorted-array/solution/) | [C++](0001-0500/0033-Search-in-Rotated-Sorted-Array/cpp-0033/) | | | +| 034 | [Search for a Range](https://leetcode.com/problems/search-for-a-range/description/) | [solution](https://leetcode.com/problems/search-for-a-range/solution/) | [C++](0001-0500/0034-Search-for-a-Range/cpp-0034/) | | | +| 035 | [Search Insert Position](https://leetcode.com/problems/search-insert-position/) | [solution](https://leetcode.com/problems/search-insert-position/solution/) | [C++](0001-0500/0035-Search-Insert-Position/cpp-0035/) | | | +| 036 | [Valid Sudoku](https://leetcode.com/problems/valid-sudoku/description/) | [solution](https://leetcode.com/problems/valid-sudoku/solution/) | [C++](0001-0500/0036-Valid-Sudoku/cpp-0036/) | | | +| 037 | [Sudoku Solver](https://leetcode.com/problems/sudoku-solver/description/) | [solution](https://leetcode.com/problems/sudoku-solver/)
[缺:Dancing Links] | [C++](0001-0500/0037-Sudoku-Solver/cpp-0037/) | [C++](0001-0500/0037-Sudoku-Solver/java-0037/) | | +| 038 | [Count and Say](https://leetcode.com/problems/count-and-say/description/) | [无] | [C++](0001-0500/0038-Count-and-Say/cpp-0038/) | | | +| 039 | [Combination Sum](https://leetcode.com/problems/combination-sum/description/) | [无] | [C++](0001-0500/0039-Combination-Sum/cpp-0039/) | | | +| 040 | [Combination Sum II](https://leetcode.com/problems/combination-sum-ii/description/) | [无] | [C++](0001-0500/0040-Combination-Sum-II/cpp-0040/) | | | +| 041 | [First Missing Positive](https://leetcode.com/problems/first-missing-positive/) | [solution](https://leetcode.com/problems/first-missing-positive/solution/) | [C++](0001-0500/0041-First-Missing-Positive/cpp-0041/) | | | +| 042 | [Trapping Rain Water](https://leetcode.com/problems/trapping-rain-water/description/) | [solution](https://leetcode.com/problems/trapping-rain-water/solution/) | [C++](0001-0500/0042-Trapping-Rain-Water/cpp-0042/) | | | +| 043 | [Multiply Strings](https://leetcode.com/problems/multiply-strings/) | [solution](https://leetcode.com/problems/multiply-strings/solution/) | [C++](0001-0500/0043-Multiply-Strings/cpp-0043/) | | | +| | | | | | | +| 045 | [Jump Game II](https://leetcode.com/problems/jump-game-ii/) | [solution](https://leetcode.com/problems/jump-game-ii/solution/) | [C++](0001-0500/0045-Jump-Game-II/cpp-0045/) | | | +| 046 | [Permutations](https://leetcode.com/problems/permutations/description/) | [solution](https://leetcode.com/problems/permutations/solution/)
[缺:排列算法整理] | [C++](0001-0500/0046-Permutations/cpp-0046/) | [Java](0001-0500/0046-Permutations/java-0046/src/) | | +| 047 | [Permutations II](https://leetcode.com/problems/permutations-ii/description/) | [无] | [C++](0001-0500/0047-Permutations-II/cpp-0047/) | | | +| 048 | [Rotate Image](https://leetcode.com/problems/rotate-image/description/) | [solution](https://leetcode.com/problems/rotate-image/) | [C++](0001-0500/0048-Rotate-Image/cpp-0048/) | | | +| 049 | [Group Anagrams](https://leetcode.com/problems/group-anagrams/description/) | [solution](https://leetcode.com/problems/group-anagrams/solution/) | [C++](0001-0500/0049-Group-Anagrams/cpp-0049/) | | | +| 050 | [Pow(x, n)](https://leetcode.com/problems/powx-n/) | [无] | [C++](0001-0500/0050-Pow-x-n/cpp-0050/) | | | +| 051 | [N-Queens](https://leetcode.com/problems/n-queens/description/) | [缺:N皇后问题整理] | [C++](0001-0500/0051-N-Queens/cpp-0051/) | [Java](0001-0500/0051-N-Queens/java-0051/src/) | | +| 052 | [N-Queens II](https://leetcode.com/problems/n-queens-ii/) | [solution](https://leetcode.com/problems/n-queens-ii/solution/)
[缺:N皇后问题整理] | [C++](0001-0500/0052-N-Queens-II/cpp-0052/) | | | +| 053 | [Maximum Subarray](https://leetcode.com/problems/maximum-subarray/) | [solution](https://leetcode.com/problems/maximum-subarray/solution/) | [C++](0001-0500/0053-Maximum-Subarray/cpp-0053/) | | | +| 054 | [Spiral Matrix](https://leetcode.com/problems/spiral-matrix/description/) | [solution](https://leetcode.com/problems/spiral-matrix/solution/) | [C++](0001-0500/0054-Spiral-Matrix/cpp-0054/) | | | +| 055 | [Jump Game](https://leetcode.com/problems/jump-game/) | [solution](https://leetcode.com/problems/jump-game/solution/) | [C++](0001-0500/0055-Jump-Game/cpp-0055/) | | | +| 056 | [Merge Intervals](https://leetcode.com/problems/merge-intervals/description/) | [solution](https://leetcode.com/problems/merge-intervals/solution/) | [C++](0001-0500/0056-Merge-Intervals/cpp-0056/) | | | +| 057 | [Insert Interval](https://leetcode.com/problems/insert-interval/) | [solution](https://leetcode.com/problems/insert-interval/solutions/2914120/insert-intervals/?orderBy=most_votes) | [C++](0001-0500/0057-Insert-Interval/cpp-0057/) | | | +| 058 | [Length of Last Word](https://leetcode.com/problems/length-of-last-word/) | [solution](https://leetcode.com/problems/length-of-last-word/solution/) | [C++](0001-0500/0058-Length-of-Last-Word/cpp-0058/) | | | +| 059 | [Spiral Matrix II](https://leetcode.com/problems/spiral-matrix-ii/description/) | [无] | [C++](0001-0500/0059-Spiral-Matrix-II/cpp-0059/) | | | +| | | | | | | +| 061 | [Rotate List](https://leetcode.com/problems/rotate-list/description/) | [solution](https://leetcode.com/problems/rotate-list/solution/) | [C++](0001-0500/0061-Rotate-List/cpp-0061/) | | | +| 062 | [Unique Paths](https://leetcode.com/problems/unique-paths/) | [无]
[缺:数学解] | [C++](0001-0500/0062-Unique-Paths/cpp-0062/) | | | +| 063 | [Unique Paths II](https://leetcode.com/problems/unique-paths-ii/) | [solution](https://leetcode.com/problems/unique-paths-ii/solution/) | [C++](0001-0500/0063-Unique-Paths-II/cpp-0063/) | | | +| 064 | [Minimum Path Sum](https://leetcode.com/problems/minimum-path-sum/description/) | [solution](https://leetcode.com/problems/minimum-path-sum/solution/) | [C++](0001-0500/0064-Minimum-Path-Sum/cpp-0064/) | [Java](0001-0500/0064-Minimum-Path-Sum/java-0064/src/) | [Python](0001-0500/0064-Minimum-Path-Sum/py-0064/) | +| 065 | [Valid Number](https://leetcode.com/problems/valid-number/) | [solution](https://leetcode.com/problems/valid-number/solution/) | [C++](0001-0500/0065-Valid-Number/cpp-0065/) | | | +| 066 | [Plus One](https://leetcode.com/problems/plus-one/description/) | [无] | [C++](0001-0500/0066-Plus-One/cpp-0066/) | | | +| 067 | [Add Binary](https://leetcode.com/problems/add-binary/description/) | [无] | [C++](0001-0500/0067-Add-Binary/cpp-0067/) | | | +| 068 | [Text Justification](https://leetcode.com/problems/text-justification/) | [无] | [C++](0001-0500/0068-Text-Justification/cpp-0068/) | | | +| 069 | [Sqrt(x)](https://leetcode.com/problems/sqrtx/description/)| [无] | [C++](0001-0500/0069-Sqrt-x/cpp-0069/) | | | +| 070 | [Climbing Stairs](https://leetcode.com/problems/climbing-stairs/description/) | [solution](https://leetcode.com/problems/climbing-stairs/solution/) | [C++](0001-0500/0070-Climbing-Stairs/cpp-0070/) | [Java](0001-0500/0070-Climbing-Stairs/java-0070/src/) | | +| 071 | [Simplify Path](https://leetcode.com/problems/simplify-path/) | [无] | [C++](0001-0500/0071-Simplify-Path/cpp-0071/) | | | +| 072 | [Edit Distance](https://leetcode.com/problems/edit-distance/) | [solution](https://leetcode.com/problems/edit-distance/solution/) | [C++](0001-0500/0072-Edit-Distance/cpp-0072/) | | | +| 073 | [Set Matrix Zeroes](https://leetcode.com/problems/set-matrix-zeroes/description/) | [solution](https://leetcode.com/problems/set-matrix-zeroes/solution/) | [C++](0001-0500/0073-Set-Matrix-Zeroes/cpp-0073/) | | | +| 074 | [Search a 2D Matrix](https://leetcode.com/problems/search-a-2d-matrix/) | [无] | [C++](0001-0500/0074-Search-a-2D-Matrix/cpp-0074/) | | | +| 075 | [Sort Colors](https://leetcode.com/problems/sort-colors/description/) | [solution](https://leetcode.com/problems/sort-colors/solution/) | [C++](0001-0500/0075-Sort-Colors/cpp-0075/) | [Java](0001-0500/0075-Sort-Colors/java-0075/src/) | [Python](0001-0500/0075-Sort-Colors/py-0075/) | +| 076 | [Minimum Window Substring](https://leetcode.com/problems/minimum-window-substring/description/) | [solution](https://leetcode.com/problems/minimum-window-substring/solution/) | [C++](0001-0500/0076-Minimum-Window-Substring/cpp-0076/) | | | +| 077 | [Combinations](https://leetcode.com/problems/combinations/description/) | [solution](https://leetcode.com/problems/combinations/solution/) | [C++](0001-0500/0077-Combinations/cpp-0077/) | [Java](0001-0500/0077-Combinations/java-0077/src/) | | +| 078 | [Subsets](https://leetcode.com/problems/subsets/) | [solution](https://leetcode.com/problems/subsets/solution/) | [C++](0001-0500/0078-Subsets/cpp-0078/) | | | +| 079 | [Word Search](https://leetcode.com/problems/word-search/description/) | [无] | [C++](0001-0500/0079-Word-Search/cpp-0079/) | [Java](0001-0500/0079-Word-Search/java-0079/src/) | | +| 080 | [Remove Duplicates from Sorted Array II](https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/description/) | [无] | [C++](0001-0500/0080-Remove-Duplicates-from-Sorted-Array-II/cpp-0080/) | | | +| 081 | [Search in Rotated Sorted Array II](https://leetcode.com/problems/search-in-rotated-sorted-array-ii/) | [solution](https://leetcode.com/problems/search-in-rotated-sorted-array-ii/solution/) | [C++](0001-0500/0081-Search-in-Rotated-Sorted-Array-II/cpp-0081/) | | | +| 082 | [Remove Duplicates from Sorted List II](https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/) | [无] | [C++](0001-0500/0082-Remove-Duplicates-from-Sorted-List-II/cpp-0082/) | | | +| 083 | [Remove Duplicates from Sorted List](https://leetcode.com/problems/remove-duplicates-from-sorted-list/) | [无] | [C++](0001-0500/0083-Remove-Duplicates-from-Sorted-List/cpp-0083/) | | | +| 084 | [Largest Rectangle in Histogram](https://leetcode.com/problems/largest-rectangle-in-histogram/) | [solution](https://leetcode.com/problems/largest-rectangle-in-histogram/solution/) [题解](https://leetcode-cn.com/problems/largest-rectangle-in-histogram/solution/zhu-zhuang-tu-zhong-zui-da-de-ju-xing-by-leetcode/) | [C++](0001-0500/0084-Largest-Rectangle-in-Histogram/cpp-0084/) | | | +| 085 | [Maximal Rectangle](https://leetcode.com/problems/maximal-rectangle/) | [solution](https://leetcode.com/problems/maximal-rectangle/solution/) | [C++](0001-0500/0085-Maximal-Rectangle/cpp-0085/) | | | +| 086 | [Partition List](https://leetcode.com/problems/partition-list/description/) | [solution](https://leetcode.com/problems/partition-list/solution/) | [C++](0001-0500/0086-Partition-List/cpp-0086/) | | | +| 087 | [Scramble String](https://leetcode.com/problems/scramble-string/description/) | [无] | [C++](0001-0500/0087-Scramble-String/cpp-0087/) | | | +| 088 | [Merge Sorted Array](https://leetcode.com/problems/merge-sorted-array/description/) | [solution](https://leetcode.com/problems/merge-sorted-array/solution/) | [C++](0001-0500/0088-Merge-Sorted-Array/cpp-0088/) | [Java](0001-0500/0088-Merge-Sorted-Array/java-0088/) | | +| 089 | [Gray Code](https://leetcode.com/problems/gray-code/) | [无] | [C++](0001-0500/0089-Gray-Code/cpp-0089/) | | | +| 090 | [Subsets II](https://leetcode.com/problems/subsets-ii/) | [无] | [C++](0001-0500/0090-Subsets-II/cpp-0090/) | | | +| 091 | [Decode Ways](https://leetcode.com/problems/decode-ways/) | [无] | [C++](0001-0500/0091-Decode-Ways/cpp-0091/) | | | +| 092 | [Reverse Linked List II](https://leetcode.com/problems/reverse-linked-list-ii/description/) | [solution](https://leetcode.com/problems/reverse-linked-list-ii/solution/) | [C++](0001-0500/0092-Reverse-Linked-List-II/cpp-0092/) | | | +| 093 | [Restore IP Addresses](https://leetcode.com/problems/restore-ip-addresses/) | [solution](https://leetcode.com/problems/restore-ip-addresses/solution/) | [C++](0001-0500/0093-Restore-IP-Addresses/cpp-0093/) | | | +| 094 | [Binary Tree Inorder Traversal](https://leetcode.com/problems/binary-tree-inorder-traversal/description/) | [solution](https://leetcode.com/problems/binary-tree-inorder-traversal/solution/) | [C++](0001-0500/0094-Binary-Tree-Inorder-Traversal/cpp-0094/) | [Java](0001-0500/0094-Binary-Tree-Inorder-Traversal/java-0094/src/) | | +| 095 | [Unique Binary Search Trees II](https://leetcode.com/problems/unique-binary-search-trees-ii/description/) | [solution](https://leetcode.com/problems/unique-binary-search-trees-ii/solution/) | [C++](0001-0500/0095-Unique-Binary-Search-Trees-II/cpp-0095/) | | | +| 096 | [Unique Binary Search Trees](https://leetcode.com/problems/unique-binary-search-trees/description/) | [solution](https://leetcode.com/problems/unique-binary-search-trees/solution/) | [C++](0001-0500/0096-Unique-Binary-Search-Trees/cpp-0096/) | | | +| 097 | [Interleaving String](https://leetcode.com/problems/interleaving-string/) | [solution](https://leetcode.com/problems/interleaving-string/solution/)
[缺:DP] | [C++](0001-0500/0097-Interleaving-String/cpp-0097/) | | | +| 098 | [Validate Binary Search Tree](https://leetcode.com/problems/validate-binary-search-tree/description/) | [solution](https://leetcode.com/problems/validate-binary-search-tree/solution/) | [C++](0001-0500/0098-Validate-Binary-Search-Tree/cpp-0098/) | [Java](0001-0500/0098-Validate-Binary-Search-Tree/java-0098/src/) | | +| 099 | [Recover Binary Search Tree](https://leetcode.com/problems/recover-binary-search-tree/description/) | [无] | | [Java](0001-0500/0099-Recover-Binary-Search-Tree/java-0099/src/) | | +| 100 | [Same Tree](https://leetcode.com/problems/same-tree/description/) | [solution](https://leetcode.com/problems/same-tree/solution/) | [C++](0001-0500/0100-Same-Tree/cpp-0100/) | | | +| 101 | [Symmetric Tree](https://leetcode.com/problems/symmetric-tree/description/) | [solution](https://leetcode.com/problems/symmetric-tree/solution/) | [C++](0001-0500/0101-Symmetric-Tree/cpp-0101/) | | [Python](0001-0500/0101-Symmetric-Tree/py-0101/) | +| 102 | [Binary Tree Level Order Traversal](https://leetcode.com/problems/binary-tree-level-order-traversal/description/) | [solution](https://leetcode.com/problems/binary-tree-level-order-traversal/solution/) | [C++](0001-0500/0102-Binary-Tree-Level-Order-Traversal/cpp-0102/) | [Java](0001-0500/0102-Binary-Tree-Level-Order-Traversal/java-0102/src/) | | +| 103 | [Binary Tree Zigzag Level Order Traversal](https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/) | [无] | [C++](0001-0500/0103-Binary-Tree-Zigzag-Level-Order-Traversal/cpp-0103/) | | | +| 104 | [Maximum Depth of Binary Tree](https://leetcode.com/problems/maximum-depth-of-binary-tree/description/) | [solution](https://leetcode.com/problems/maximum-depth-of-binary-tree/solution/) | [C++](0001-0500/0104-Maximum-Depth-of-Binary-Tree/cpp-0104/) | [Java](0001-0500/0104-Maximum-Depth-of-Binary-Tree/java-0104/src/) | | +| 105 | [Construct Binary Tree from Preorder and Inorder Traversal](https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/description/) | [solution](https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/solution/) | [C++](0001-0500/0105-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal/cpp-0105/) | | | +| 106 | [Construct Binary Tree from Inorder and Postorder Traversal](https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/description/) | [无] | [C++](0001-0500/0106-Construct-Binary-Tree-from-Inorder-and-Postorder-Traversal/cpp-0106/) | | | +| 107 | [Binary Tree Level Order Traversal II](https://leetcode.com/problems/binary-tree-level-order-traversal-ii/description/) | [无] | [C++](0001-0500/0107-Binary-Tree-Level-Order-Traversal-II/cpp-0107/) | | | +| 108 | [Convert Sorted Array to Binary Search Tree](https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/) | [无] | [C++](0001-0500/0108-Convert-Sorted-Array-to-Binary-Search-Tree/cpp-0108/) | | | +| 109 | [Convert Sorted List to Binary Search Tree](https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/description/) | [solution](https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/solution/) | [C++](0001-0500/0109-Convert-Sorted-List-to-Binary-Search-Tree/cpp-0109/) | | | +| 110 | [Balanced Binary Tree](https://leetcode.com/problems/balanced-binary-tree/) | [solution](https://leetcode.com/problems/balanced-binary-tree/solution/) | [C++](0001-0500/0110-Balanced-Binary-Tree/cpp-0110/) | | | +| 111 | [Minimum Depth of Binary Tree](https://leetcode.com/problems/minimum-depth-of-binary-tree/description/) | [solution](https://leetcode.com/problems/minimum-depth-of-binary-tree/solution/) | [C++](0001-0500/0111-Minimum-Depth-of-Binary-Tree/cpp-0111/) | | | +| 112 | [Path Sum](https://leetcode.com/problems/path-sum/description/) | [solution](https://leetcode.com/problems/path-sum/solution/) | [C++](0001-0500/0112-Path-Sum/cpp-0112/) | [Java](0001-0500/0112-Path-Sum/cpp-0112/src/) | | +| 113 | [Path Sum II](https://leetcode.com/problems/path-sum-ii/description/) | [无] | [C++](0001-0500/0113-Path-Sum-II/cpp-0113/) | | | +| 114 | [Flatten Binary Tree to Linked List](https://leetcode.com/problems/flatten-binary-tree-to-linked-list/) | [solution](https://leetcode.com/problems/flatten-binary-tree-to-linked-list/solution/) | [C++](0001-0500/0114-Flatten-Binary-Tree-to-Linked-List/cpp-0114/) | | | +| 115 | [Distinct Subsequences](https://leetcode.com/problems/distinct-subsequences/description/) | [无] | [C++](0001-0500/0115/Distinct-Subsequences/cpp-0115/) | [Java](0001-0500/0115/Distinct-Subsequences/java-0115/) | | +| 116 | [Populating Next Right Pointers in Each Node](https://leetcode.com/problems/populating-next-right-pointers-in-each-node/description/) | [无] | [C++](0001-0500/0116-Populating-Next-Right-Pointers-in-Each-Node/cpp-0116/) | | | +| 117 | [Populating Next Right Pointers in Each Node II](https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/) | [无] | [C++](0001-0500/0117-Populating-Next-Right-Pointers-in-Each-Node-II/cpp-0117/) | | | +| 118 | [Pascal's Triangle](https://leetcode.com/problems/pascals-triangle/description/) | [solution](https://leetcode.com/problems/pascals-triangle/solution/) | [C++](0001-0500/0118-Pascals-Triangle/cpp-0118/) | | | +| 119 | [Pascal's Triangle II](https://leetcode.com/problems/pascals-triangle-ii/description/) | [无] | [C++](0001-0500/0119-Pascals-Triangle-II/cpp-0119/) | | | +| 120 | [Triangle](https://leetcode.com/problems/triangle/description/) | [无] | [C++](0001-0500/0120-Triangle/cpp-0120/) | | | +| 121 | [Best Time to Buy and Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/solution/) | | [C++](0001-0500/0121-Best-Time-to-Buy-and-Sell-Stock/cpp-0121/) | | | +| 122 | [Best Time to Buy and Sell Stock II](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/description/) | [solution](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/solution/) | [C++](0001-0500/0122-Best-Time-to-Buy-and-Sell-Stock-II/cpp-0122/) | | | +| 123 | [Best Time to Buy and Sell Stock III](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/description/) | | [C++](0001-0500/0123-Best-Time-to-Buy-and-Sell-Stock-III/cpp-0123/) | | | +| 124 | [Binary Tree Maximum Path Sum](https://leetcode.com/problems/binary-tree-maximum-path-sum/) | [solution](https://leetcode.com/problems/binary-tree-maximum-path-sum/) | [C++](0001-0500/0124-Binary-Tree-Maximum-Path-Sum/cpp-0124/) | | | +| 125 | [Valid Palindrome](https://leetcode.com/problems/valid-palindrome/description/) | [无] | [C++](0001-0500/0125-Valid-Palindrome/cpp-0125/) | | | +| 126 | [Word Ladder II](https://leetcode.com/problems/word-ladder-ii/description/) | [无]
[缺:双端搜索] | [C++](0001-0500/0126-Word-Ladder-II/cpp-0126/) | | | +| 127 | [Word Ladder](https://leetcode.com/problems/word-ladder/description/) | [solution](https://leetcode.com/problems/word-ladder/solution/) | [C++](0001-0500/0127-Word-Ladder/cpp-0127/) | [Java](0001-0500/0127-Word-Ladder/java-0127/) | | +| 128 | [Longest Consecutive Sequence](https://leetcode.com/problems/longest-9consecutive-sequence/description/) | | [C++](0001-0500/0128-Longest-Consecutive-Sequence/cpp-0128/) | | | +| 129 | [Sum Root to Leaf Numbers](https://leetcode.com/problems/sum-root-to-leaf-numbers/description/) | [无] | [C++](0001-0500/0129-Sum-Root-to-Leaf-Numbers/cpp-0129/) | | | +| 130 | [Surrounded Regions](https://leetcode.com/problems/surrounded-regions/description/) | [无] | [C++](0001-0500/0130-Surrounded-Regions/cpp-0130/) | | | +| 131 | [Palindrome Partitioning](https://leetcode.com/problems/palindrome-partitioning/) | [solution](https://leetcode.com/problems/palindrome-partitioning/solution/)
[缺:DP] | [C++](0001-0500/0131-Palindrome-Partitioning/cpp-0131/) | | | +| 132 | [Palindrome Partitioning II](https://leetcode.com/problems/palindrome-partitioning-ii/) | [无] | [C++](0001-0500/0132-Palindrome-Partitioning-II/cpp-0132/) | | | +| 133 | [Clone Graph](https://leetcode.com/problems/clone-graph/description/) | [无] | [C++](0001-0500/0133-Clone-Graph/cpp-0133/) | | | +| 134 | [Gas Station](https://leetcode.com/problems/gas-station/) | [solution](https://leetcode.com/problems/gas-station/solution/) | [C++](0001-0500/0134-Gas-Station/cpp-0134/) | | | +| 135 | [Candy](https://leetcode.com/problems/candy/) | [solution](https://leetcode.com/problems/candy/solution/)
[缺:O(1)空间算法] | [C++](0001-0500/0135-Candy/cpp-0135/) | | | +| 136 | [Single Number](https://leetcode.com/problems/single-number/description/) | [solution](https://leetcode.com/problems/single-number/solution/) | [C++](0001-0500/0136-Single-Number/cpp-0136/) | | | +| 137 | [Single Number II](https://leetcode.com/problems/single-number-ii/) | [solution](https://leetcode.com/problems/single-number-ii/solution/) | [C++](0001-0500/0137-Single-Number-II/cpp-0137/) | | | +| 138 | [Copy List with Random Pointer](https://leetcode.com/problems/copy-list-with-random-pointer/description/) | [solution](https://leetcode.com/problems/copy-list-with-random-pointer/solution/) | [C++](0001-0500/0138-Copy-List-with-Random-Pointer/cpp-0138/) | | | +| 139 | [Word Break](https://leetcode.com/problems/word-break/) | [solution](https://leetcode.com/problems/word-break/solution/) | [C++](0001-0500/0139-Word-Break/cpp-0139/) | | | +| | | | | | | +| 141 | [Linked List Cycle](https://leetcode.com/problems/linked-list-cycle/description/) | [solution](https://leetcode.com/problems/linked-list-cycle/solution/) | [C++](0001-0500/0141-Linked-List-Cycle/cpp-0141/) | | | +| 142 | [Linked List Cycle II](https://leetcode.com/problems/linked-list-cycle-ii/description/) | [solution](https://leetcode.com/problems/linked-list-cycle-ii/description/) | [C++](0001-0500/0142-Linked-List-Cycle-II/cpp-0142/) | | | +| 143 | [Reorder List](https://leetcode.com/problems/reorder-list/) | [无] | [C++](0001-0500/0143-Reorder-List/cpp-0143/) | | | +| 144 | [Binary Tree Preorder Traversal](https://leetcode.com/problems/binary-tree-preorder-traversal/description/) | [solution](https://leetcode.com/problems/binary-tree-preorder-traversal/) | [C++](0001-0500/0144-Binary-Tree-Preorder-Traversal/cpp-0144/) | [Java](0001-0500/0144-Binary-Tree-Preorder-Traversal/java-0144/src/) | | +| 145 | [Binary Tree Postorder Traversal](https://leetcode.com/problems/binary-tree-postorder-traversal/description/) | [solution](https://leetcode.com/problems/binary-tree-postorder-traversal/solution/) | [C++](0001-0500/0145-Binary-Tree-Postorder-Traversal/cpp-0145/) | [Java](0001-0500/0145-Binary-Tree-Postorder-Traversal/java-0145/src/) | | +| 146 | [LRU Cache](https://leetcode.com/problems/lru-cache/) | [solution](https://leetcode.com/problems/lru-cache/solution/)
[缺:封装一个Double Linked List] | [C++](0001-0500/0146-LRU-Cache/cpp-0146/) | | | +| 147 | [Insertion Sort List](https://leetcode.com/problems/insertion-sort-list/) | [无] | [C++](0001-0500/0147-Insertion-Sort-List/cpp-0147/) | | | +| 148 | [Sort List](https://leetcode.com/problems/sort-list/description/) | [无] | [C++](0001-0500/0148-Sort-List/cpp-0148/) | | | +| 149 | [Max Points on a Line](https://leetcode.com/problems/max-points-on-a-line/description/) | [solution](https://leetcode.com/problems/max-points-on-a-line/solution/) | [C++](0001-0500/0149-Max-Points-on-a-Line/cpp-0149/) | | | +| 150 | [Evaluate Reverse Polish Notation](https://leetcode.com/problems/evaluate-reverse-polish-notation/description/) | [无] | [C++](0001-0500/0150-Evaluate-Reverse-Polish-Notation/cpp-0150/) | | | +| 151 | [Reverse Words in a String](https://leetcode.com/problems/reverse-words-in-a-string/description/) | [无] | [C++](0001-0500/151-Reverse-Words-in-a-String/cpp-0151/) | | | +| 152 | [Maximum Product Subarray](https://leetcode.com/problems/maximum-product-subarray/) | [solution](https://leetcode.com/problems/maximum-product-subarray/)
[缺:Linear] | [C++](0001-0500/0152-Maximum-Product-Subarray/cpp-0152/) | | [Python](0001-0500/0152-Maximum-Product-Subarray/py-0152/) | +| 153 | [Find Minimum in Rotated Sorted Array](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/description/) | [solution](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/solution/) | [C++](0001-0500/0153-Find-Minimum-in-Rotated-Sorted-Array/cpp-0153/) | | | +| | | | | | | +| 155 | [Min Stack](https://leetcode.com/problems/min-stack/description/) | [无] | [C++](0001-0500/0155-Min-Stack/cpp-0155/) | | | +| | | | | | | +| 159 | [Longest Substring with At Most Two Distinct Characters](https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/description/) | [solution](https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/solution/) | [C++](0001-0500/0159-Longest-Substring-with-At-Most-Two-Distinct-Characters/cpp-0159/) | | | +| 160 | [Intersection of Two Linked Lists](https://leetcode.com/problems/intersection-of-two-linked-lists/description/) | [solution](https://leetcode.com/problems/intersection-of-two-linked-lists/solution/) | [C++](0001-0500/0160-Intersection-of-Two-Linked-Lists/cpp-0160/) | | | +| 161 | [One Edit Distance](https://leetcode.com/problems/one-edit-distance/) | [solution](https://leetcode.com/problems/one-edit-distance/solution/) | [C++](0001-0500/0161-One-Edit-Distance/cpp-0161/) | | | +| 162 | [Find Peak Element](https://leetcode.com/problems/find-peak-element/) | [solution](https://leetcode.com/problems/find-peak-element/solution/) | [C++](0001-0500/0162-Find-Peak-Element/cpp-0162/) | | | +| 163 | [Missing Ranges](https://leetcode.com/problems/missing-ranges/) | [solution](https://leetcode.com/problems/missing-ranges/solution/) | [C++](0001-0500/0163-Missing-Ranges/cpp-0163/) | | | +| 164 | [Maximum Gap](https://leetcode.com/problems/maximum-gap/) | [solution](https://leetcode.com/problems/maximum-gap/solution/)
[缺:桶排序] | [C++](0001-0500/0164-Maximum-Gap/cpp-0164/) | | | +| 165 | [Compare Version Numbers](https://leetcode.com/problems/compare-version-numbers/) | [solution](https://leetcode.com/problems/compare-version-numbers/solution/) | [C++](0001-0500/0165-Compare-Version-Numbers/cpp-0165/) | | | +| 166 | [Fraction to Recurring Decimal](https://leetcode.com/problems/fraction-to-recurring-decimal/) | [solution](https://leetcode.com/problems/fraction-to-recurring-decimal/solution/) | [C++](0001-0500/0166-Fraction-to-Recurring-Decimal/cpp-0166/) | | | +| 167 | [Two Sum II - Input array is sorted](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/description/) | [solution](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/solution/) | [C++](0001-0500/0167-Two-Sum-II-Input-array-is-sorted/cpp-0167/) | [Java](0001-0500/0167-Two-Sum-II-Input-array-is-sorted/java-0167/src/) | | +| 168 | [Excel Sheet Column Title](https://leetcode.com/problems/excel-sheet-column-title/) | [无] | [C++](0001-0500/0168-Excel-Sheet-Column-Title/cpp-0168/) | | | +| 169 | [Majority Element](https://leetcode.com/problems/majority-element/description/) | [solution](https://leetcode.com/problems/majority-element/solution/) | [C++](0001-0500/0169-Majority-Element/cpp-0169/) | | [Python](0001-0500/0169-Majority-Element/py-0169/) | +| 170 | [Two Sum III - Data structure design](https://leetcode.com/problems/two-sum-iii-data-structure-design/description/) | [无] | [C++](0001-0500/0170-Two-Sum-III-Data-structure-design/cpp-0170/) | | | +| 171 | [Excel Sheet Column Number](https://leetcode.com/problems/excel-sheet-column-number/description/) | [无] | [C++](0001-0500/0171-Excel-Sheet-Column-Number/cpp-0171/) | | | +| 172 | [Factorial Trailing Zeroes](https://leetcode.com/problems/factorial-trailing-zeroes/) | [solution](https://leetcode.com/problems/factorial-trailing-zeroes/solution/) | [C++](0001-0500/0172/Factorial-Trailing-Zeroes/cpp-0172/) | | | +| 173 | [Binary Search Tree Iterator](https://leetcode.com/problems/binary-search-tree-iterator/description/) | [无]
[缺:Morris遍历] | [C++](0001-0500/0173-Binary-Search-Tree-Iterator/cpp-0173/) | | | +| 174 | [Dungeon Game](https://leetcode.com/problems/dungeon-game/) | [solution](https://leetcode.com/problems/dungeon-game/solution/) | [C++](0001-0500/0174-Dungeon-Game/cpp-0174/) | | | +| 175 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 176 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| | | | | | | +| 179 | [Largest Number](https://leetcode.com/problems/largest-number/) | [无] | [C++](0001-0500/0179-Largest-Number/cpp-0179/) | | | +| | | | | | | +| 181 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| | | | | | | +| 184 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| | | | | | | +| 186 | [Reverse Words in a String II](https://leetcode.com/problems/reverse-words-in-a-string-ii/description/) | [无] | [C++](0001-0500/0186-Reverse-Words-in-a-String-II/cpp-0186/) | | | +| | | | | | | +| 188 | [Best-Time-to-Buy-and-Sell-Stock-IV](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/description/) | | [C++](0001-0500/0188-Best-Time-to-Buy-and-Sell-Stock-IV/cpp-0188/) | | | +| 189 | [Rotate Array](https://leetcode.com/problems/rotate-array/description/) | [solution](https://leetcode.com/problems/rotate-array/solution/) | [C++](0001-0500/0189-Rotate-Array/cpp-0189/) | | | +| 190 | [Reverse Bits](https://leetcode.com/problems/reverse-bits/) | [solution](https://leetcode.com/problems/reverse-bits/solution/) | [C++](0001-0500/0190-Reverse-Bits/cpp-0190/) | | | +| 191 | [Number of 1 Bits](https://leetcode.com/problems/number-of-1-bits/description/) | [solution](https://leetcode.com/problems/number-of-1-bits/solution/) | [C++](0001-0500/0191-Number-of-1-Bits/cpp-0191/) | | | +| | | | | | | +| 196 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 197 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 198 | [House Robber](https://leetcode.com/problems/house-robber/description/) | [solution](https://leetcode.com/problems/house-robber/solution/) | [C++](0001-0500/0198-House-Robber/cpp-0198/) | [Java](0001-0500/0198-House-Robber/java-0198/src/) | | +| 199 | [Binary Tree Right Side View](https://leetcode.com/problems/binary-tree-right-side-view/) | [solution](https://leetcode.com/problems/binary-tree-right-side-view/solution/) | [C++](0001-0500/199-Binary-Tree-Right-Side-View/cpp-0199/) | | | +| 200 | [Number of Islands](https://leetcode.com/problems/number-of-islands/description/) | [solution](https://leetcode.com/problems/number-of-islands/solution/) | [C++](0001-0500/0200-Number-of-Islands/cpp-0200/) | [Java](0001-0500/0200-Number-of-Islands/java-0200/src/) | | +| 201 | [Bitwise AND of Numbers Range](https://leetcode.com/problems/bitwise-and-of-numbers-range/) | [solution](https://leetcode.com/problems/bitwise-and-of-numbers-range/solution/) | [C++](0001-0500/0201-Bitwise-AND-of-Numbers-Range/cpp-0201/) | | | +| 202 | [Happy Number](https://leetcode.com/problems/happy-number/description/) | [solution](https://leetcode.com/problems/happy-number/solution/) | [C++](0001-0500/0202-Happy-Number/cpp-0202/) | | | +| 203 | [Remove Linked List Elements](https://leetcode.com/problems/remove-linked-list-elements/description/) | [无] | [C++](0001-0500/0203-Remove-Linked-List-Elements/cpp-0203/) | [Java](0001-0500/0203-Remove-Linked-List-Elements/java-0203/src/) | | +| 204 | [Count Primes](https://leetcode.com/problems/count-primes/) | [无] | [C++](0001-0500/0204-Count-Primes/cpp-0204/) | | | +| 205 | [Isomorphic Strings](https://leetcode.com/problems/isomorphic-strings/description/) | [无] | [C++](0001-0500/0205-Isomorphic-Strings/cpp-0205/) | | | +| 206 | [Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/description/) | [solution](https://leetcode.com/problems/reverse-linked-list/solution/) | [C++](0001-0500/0206-Reverse-Linked-List/cpp-0206/) | [Java](0001-0500/0206-Reverse-Linked-List/java-0206/src/) | | +| 207 | [Course Schedule](https://leetcode.com/problems/course-schedule/) | [无] | [C++](0001-0500/0207-Course-Schedule/cpp-0207/) | | | +| 208 | [Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree/description/) | [solution](https://leetcode.com/problems/implement-trie-prefix-tree/solution/) | [C++](0001-0500/0208-Implement-Trie-Prefix-Tree/cpp-0208/) | | | +| 209 | [Minimum Size Subarray Sum](https://leetcode.com/problems/minimum-size-subarray-sum/description/) | [solution](https://leetcode.com/problems/minimum-size-subarray-sum/solution/) | [C++](0001-0500/0209-Minimum-Size-Subarray-Sum/cpp-0209/) | [Java](0001-0500/0209-Minimum-Size-Subarray-Sum/java-0209/src/) | | +| 210 | [Course Schedule II](https://leetcode.com/problems/course-schedule-ii/) | [solution](https://leetcode.com/problems/course-schedule-ii/solution/) | [C++](0001-0500/0210-Course-Schedule-II/cpp-0210/) | | | +| 211 | [Add and Search Word - Data structure design](https://leetcode.com/problems/add-and-search-word-data-structure-design/description/) | [无] | [C++](0001-0500/0211-Add-and-Search-Word-Data-structure-design/cpp-0211/) | [Java](0001-0500/0211-Add-and-Search-Word-Data-structure-design/java-0211/) | | +| 212 | [Word Search II](https://leetcode.com/problems/word-search-ii/) | [无] | [C++](0001-0500/0212-Word-Search-II/cpp-0212/) | | | +| 213 | [House Robber II](https://leetcode.com/problems/house-robber-ii/description/) | [无] | [C++](0001-0500/0213/House-Robber-II/cpp-0213/) | | | +| | | | | | | +| 215 | [Kth Largest Element in an Array](https://leetcode.com/problems/kth-largest-element-in-an-array/description/) | [solution](https://leetcode.com/problems/kth-largest-element-in-an-array/solution/) | [C++](0001-0500/0215-Kth-Largest-Element-in-an-Array/cpp-0215/) | | | +| 216 | [Combination Sum III](https://leetcode.com/problems/combination-sum-iii/description/) | [无] | [C++](0001-0500/0216/Combination-Sum-III/cpp-0216/) | | | +| 217 | [Contains Duplicate](https://leetcode.com/problems/contains-duplicate/description/) | [无] | [C++](0001-0500/0217/Contains-Duplicate/cpp-0217/) | | | +| 218 | [The Skyline Problem](https://leetcode.com/problems/the-skyline-problem/description/) | | [C++](0001-0500/0218-The-Skyline-Problem/cpp-0218/) | | | +| 219 | [Contains Duplicate II](https://leetcode.com/problems/contains-duplicate-ii/description/) | [solution](https://leetcode.com/problems/contains-duplicate-ii/solution/) | [C++](0001-0500/0219-Contains-Duplicate-II/cpp-0219/) | [Java](0001-0500/0219-Contains-Duplicate-II/java-0219/src/) | | +| 220 | [Contains Duplicate III](https://leetcode.com/problems/contains-duplicate-iii/description/) | [solution](https://leetcode.com/problems/contains-duplicate-iii/solution/) | [C++](0001-0500/0220-Contains-Duplicate-III/cpp-0220/) | [Java](0001-0500/0220-Contains-Duplicate-III/java-0220/) | | +| 221 | [Maximal Square](https://leetcode.com/problems/maximal-square/) | [solution](https://leetcode.com/problems/maximal-square/solution/) | [C++](0001-0500/0221-Maximal-Square/cpp-0221) | | [Python](0001-0500/0221-Maximal-Square/py-0221) | +| 222 | [Count Complete Tree Nodes](https://leetcode.com/problems/count-complete-tree-nodes/description/) | [无] | [C++](0001-0500/0222-Count-Complete-Tree-Nodes/cpp-0222/) | | | +| 223 | [Rectangle Area](https://leetcode.com/problems/rectangle-area/) | [无] | [C++](0001-0500/0223-Rectangle-Area/cpp-0223/) | | | +| 224 | [Basic Calculator](https://leetcode.com/problems/basic-calculator/description/) | [无] | [C++](0001-0500/0224-Basic-Calculator/cpp-0224/) | | | +| 225 | [Implement Stack using Queues](https://leetcode.com/problems/implement-stack-using-queues/description/) | [solution](https://leetcode.com/problems/implement-stack-using-queues/solution/) | [C++](0001-0500/0225-Implement-Stack-using-Queues/cpp-0225/) | | | +| 226 | [Invert Binary Tree](https://leetcode.com/problems/invert-binary-tree/description/) | [solution](https://leetcode.com/problems/invert-binary-tree/solution/) | [C++](0001-0500/0226-Invert-Binary-Tree/cpp-0226/) | [Java](0001-0500/0226-Invert-Binary-Tree/java-0226/src/) | [Python](0001-0500/0226-Invert-Binary-Tree/py-0226/) | +| 227 | [Basic Calculator II](https://leetcode.com/problems/basic-calculator-ii/description/) | [无] | [C++](0001-0500/0227-Basic-Calculator-II/cpp-0227/) | | | +| 228 | [Summary Ranges](https://leetcode.com/problems/summary-ranges/) | [solution](https://leetcode.com/problems/summary-ranges/solution/) | [C++](0001-0500/0228-Summary-Ranges/cpp-0228/) | | | +| 229 | [Majority Element II](https://leetcode.com/problems/majority-element-ii/) | [solution](https://leetcode.com/problems/majority-element-ii/solution/)
[缺:BM Voting] | [C++](0001-0500/0229-Majority-Element-II/cpp-0229/) | | | +| 230 | [Kth Smallest Element in a BST](https://leetcode.com/problems/kth-smallest-element-in-a-bst/description/) | [solution](https://leetcode.com/problems/kth-smallest-element-in-a-bst/solution/)
[缺:非递归] | [C++](0001-0500/0230-Kth-Smallest-Element-in-a-BST/cpp-0230/) | | | +| 231 | [Power of Two](https://leetcode.com/problems/power-of-two/) | [solution](https://leetcode.com/problems/power-of-two/solution/) | [C++](0001-0500/0231-Power-of-Two/cpp-0231/) | | | +| 232 | [Implement Queue using Stacks](https://leetcode.com/problems/implement-queue-using-stacks/description/) | [solution](https://leetcode.com/problems/implement-queue-using-stacks/solution/) | [C++](0001-0500/0232-Implement-Queue-using-Stacks/cpp-0232/) | | | +| 233 | [Number of Digit One](https://leetcode.com/problems/number-of-digit-one/) | [solution](https://leetcode.com/problems/number-of-digit-one/solution/)
[缺:数学方法] | [C++](0001-0500/0233-Number-of-Digit-One/cpp-0233/) | | | +| 234 | [Palindrome Linked List](https://leetcode.com/problems/palindrome-linked-list/description/) | [无] | [C++](0001-0500/0234-Palindrome-Linked-List/cpp-0234/) | | | +| 235 | [Lowest Common Ancestor of a Binary Search Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/description/) | [solution](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/solution/) | [C++](0001-0500/0235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree/cpp-0235/) | [Java](0001-0500/0235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree/java-0235/src/) | | +| 236 | [Lowest Common Ancestor of a Binary Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/description/) | [solution](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/solution/)
[缺:非递归解法;LCA问题总结] | [C++](0001-0500/0236-Lowest-Common-Ancestor-of-a-Binary-Tree/cpp-0236/) | | | +| 237 | [Delete Node in a Linked List](https://leetcode.com/problems/delete-node-in-a-linked-list/description/) | [solution](https://leetcode.com/problems/delete-node-in-a-linked-list/solution/) | [C++](0001-0500/0237-Delete-Node-in-a-Linked-List/cpp-0237/) | [Java](0001-0500/0237-Delete-Node-in-a-Linked-List/java-0237/src/) | | +| 238 | [Product of Array Except Self](https://leetcode.com/problems/product-of-array-except-self/) | [solution](https://leetcode.com/problems/product-of-array-except-self/solution/) | [C++](0001-0500/0238-Product-of-Array-Except-Self/cpp-0238/) | | [Python](0001-0500/0238-Product-of-Array-Except-Self/py-0238/) | +| 239 | [Sliding Window Maximum](https://leetcode.com/problems/sliding-window-maximum/description/) | [solution](https://leetcode.com/problems/sliding-window-maximum/solution/) | [C++](0001-0500/0239-Sliding-Window-Maximum/cpp-0239/) | | | +| 240 | [Search a 2D Matrix II](https://leetcode.com/problems/search-a-2d-matrix-ii/) | [solution](https://leetcode.com/problems/search-a-2d-matrix-ii/solution/)
[缺:分治] | [C++](0001-0500/240-Search-a-2D-Matrix-II/cpp-240/) | | | +| 241 | [Different Ways to Add Parentheses](https://leetcode.com/problems/different-ways-to-add-parentheses/) | [无] | [C++](0001-0500/241-Different-Ways-to-Add-Parentheses/cpp-241/) | | | +| 242 | [Valid Anagram](https://leetcode.com/problems/valid-anagram/description/) | [solution](https://leetcode.com/problems/valid-anagram/solution/) | [C++](0001-0500/0242-Valid-Anagram/cpp-0242/) | | | +| 243 | [Shortest Word Distance](https://leetcode.com/problems/shortest-word-distance/) | [solution](https://leetcode.com/problems/shortest-word-distance/solution/) | [C++](0001-0500/0243-Shortest-Word-Distance/cpp-0243/) | | | +| 244 | [Shortest Word Distance II](https://leetcode.com/problems/shortest-word-distance-ii/) | [solution](https://leetcode.com/problems/shortest-word-distance-ii/solution/) | [C++](0001-0500/0244-Shortest-Word-Distance-II/cpp-0244/) | | | +| 245 | [Shortest Word Distance III](https://leetcode.com/problems/shortest-word-distance-iii/) | [无] | [C++](0001-0500/0245-Shortest-Word-Distance-III/cpp-0245/) | | | +| 246 | [Strobogrammatic Number](https://leetcode.com/problems/strobogrammatic-number/) | [solution](https://leetcode.com/problems/strobogrammatic-number/solution/) | [C++](0001-0500/0246-Strobogrammatic-Number/cpp-0246/) | | | +| 247 | [Strobogrammatic Number II](https://leetcode.com/problems/strobogrammatic-number-ii/) | [无] | [C++](0001-0500/0247-Strobogrammatic-Number-II/cpp-0247/) | | | +| 248 | [Strobogrammatic Number III](https://leetcode.com/problems/strobogrammatic-number-iii/) | [无] | [C++](0001-0500/0248-Strobogrammatic-Number-III/cpp-0248/) | | | +| 249 | [Group Shifted Strings](https://leetcode.com/problems/group-shifted-strings/description/) | [无] | [C++](0001-0500/0249-Group-Shifted-Strings/cpp-0249/) | | | +| 250 | [Count Univalue Subtrees](https://leetcode.com/problems/count-univalue-subtrees/description/) | [solution](https://leetcode.com/problems/count-univalue-subtrees/solution/) | [C++](0001-0500/0250-Count-Univalue-Subtrees/cpp-0250/) | | | +| 251 | [Flatten 2D Vector](https://leetcode.com/problems/flatten-2d-vector/) | [solution](https://leetcode.com/problems/flatten-2d-vector/solution/) | [C++](0001-0500/0251-Flatten-2D-Vector/cpp-0251/) | | | +| 252 | [Meeting Rooms](https://leetcode.com/problems/meeting-rooms/description/) | [solution](https://leetcode.com/problems/meeting-rooms/solution/) | [C++](0001-0500/0252-Meeting-Rooms/cpp-0252/) | | | +| 253 | [Meeting Rooms II](https://leetcode.com/problems/meeting-rooms-ii/description/) | [solution](https://leetcode.com/problems/meeting-rooms-ii/solution/) | [C++](0001-0500/0253-Meeting-Rooms-II/cpp-0253/) | | | +| 254 | [Factor Combinations](https://leetcode.com/problems/factor-combinations/description/) | [无] | [C++](0001-0500/0254-Factor-Combinations/cpp-0254/) | | | +| | | | | | | +| 256 | [Paint House](https://leetcode.com/problems/paint-house/) | [无] | [C++](0001-0500/0256-Paint-House/cpp-0256/) | | | +| 257 | [Binary Tree Paths](https://leetcode.com/problems/binary-tree-paths/description/) | [solution](https://leetcode.com/problems/binary-tree-paths/solution/) | [C++](0001-0500/0257-Binary-Tree-Paths/cpp-0257/) | [Java](0001-0500/0257-Binary-Tree-Paths/java-0257/src/) | | +| 258 | [Add Digits](https://leetcode.com/problems/add-digits/) | [solution](https://leetcode.com/problems/add-digits/solution/) | [C++](0001-0500/0258-Add-Digits/cpp-0258/) | | | +| 259 | [3Sum Smaller](https://leetcode.com/problems/3sum-smaller/description/) | [solution](https://leetcode.com/problems/3sum-smaller/solution/) | [C++](0001-0500/0259-3Sum-Smaller/cpp-0259/) | | | +| 260 | [Single Number III](https://leetcode.com/problems/single-number-iii/) | [solution](https://leetcode.com/problems/single-number-iii/solution/) | [C++](0001-0500/0260-Single-Number-III/cpp-0260/) | | | +| 261 | [Graph Valid Tree](https://leetcode.com/problems/graph-valid-tree/) | [C++](0001-0500/0261-Graph-Valid-Tree/cpp-0261/) | | | | +| | | | | | | +| 263 | [Ugly Number](https://leetcode.com/problems/ugly-number/) | [无] | [C++](0001-0500/0263-Ugly-Number/cpp-0263/) | | | +| 264 | [Ugly Number II](https://leetcode.com/problems/ugly-number-ii/) | [solution](https://leetcode.com/problems/ugly-number-ii/solution/) | [C++](0001-0500/0264-Ugly-Number-II/cpp-0264/) | | | +| 265 | [Paint House II](https://leetcode.com/problems/paint-house-ii/) | [C++](0001-0500/0265-Paint-House-II/cpp-0265/) | | | | +| 266 | [Palindrome Permutation](https://leetcode.com/problems/palindrome-permutation/) | [solution](https://leetcode.com/problems/palindrome-permutation/solution/) | [C++](0001-0500/0266-Palindrome-Permutation/cpp-0266/) | | | +| 267 | [Palindrome Permutation II](https://leetcode.com/problems/palindrome-permutation-ii/) | [solution](https://leetcode.com/problems/palindrome-permutation-ii/solution/) | [C++](0001-0500/0267-Palindrome-Permutation-II/cpp-0267/) | | | +| 268 | [Missing Number](https://leetcode.com/problems/missing-number/description/) | [solution](https://leetcode.com/problems/missing-number/solution/) | [C++](0001-0500/0268-Missing-Number/cpp-0268/) | | | +| 269 | [Alien Dictionary](https://leetcode.com/problems/alien-dictionary/) | [solution](https://leetcode.com/problems/alien-dictionary/solution/) | [C++](0001-0500/0269-Alien-Dictionary/cpp-0269/) | | | +| | | | | | | +| 273 | [Integer to English Words](https://leetcode.com/problems/integer-to-english-words/) | [solution](https://leetcode.com/problems/integer-to-english-words/solution/) | [C++](0001-0500/0273-Integer-to-English-Words/cpp-0273/) | | | +| 274 | [H-Index](https://leetcode.com/problems/h-index/) | [solution](https://leetcode.com/problems/h-index/solution/)
[缺:非二分] | [C++](0001-0500/0274-H-Index/) | | | +| 275 | [H-Index II](https://leetcode.com/problems/h-index-ii/) | [solution](https://leetcode.com/problems/h-index-ii/solution/) | [C++](0001-0500/0275-H-Index-II/) | | | +| 276 | [Paint Fence](https://leetcode.com/problems/paint-fence/) | [solution](https://leetcode.com/problems/paint-fence/solution/) | [C++](0001-0500/0276-Paint-Fence/) | | | +| 277 | [Find the Celebrity](https://leetcode.com/problems/find-the-celebrity/) | [solution](https://leetcode.com/problems/find-the-celebrity/solution/)
[缺:O(n) 解法] | [C++](0001-0500/0277-Find-the-Celebrity/cpp-0277/) | | | +| 278 | [First Bad Version](https://leetcode.com/problems/first-bad-version/) | [solution](https://leetcode.com/problems/first-bad-version/solution/) | [C++](0001-0500/0278-First-Bad-Version/cpp-0278/) | | | +| 279 | [Perfect Squares](https://leetcode.com/problems/perfect-squares/description/) | [无]
四平方和数学解 | [C++](0001-0500/0279-Perfect-Squares/cpp-0279/) | [Java](0001-0500/0279-Perfect-Squares/java-0279/src/) | | +| 280 | [Wiggle Sort](https://leetcode.com/problems/wiggle-sort/description/) | [solution](https://leetcode.com/problems/wiggle-sort/solutions/2961467/wiggle-sort/?orderBy=most_votes) | [C++](0001-0500/0280-Wiggle-Sort/cpp-0280/) | | | +| | | | | | | +| 282 | [Expression Add Operators](https://leetcode.com/problems/expression-add-operators/description/) | [solution](https://leetcode.com/problems/expression-add-operators/solution/) | [C++](0001-0500/0282-Expression-Add-Operators/cpp-0282/) | | | +| 283 | [Move Zeroes](https://leetcode.com/problems/move-zeroes/description/) | [solution](https://leetcode.com/problems/move-zeroes/solution/) | [C++](0001-0500/0283-Move-Zeroes/cpp-0283/) | [Java](0001-0500/0283-Move-Zeroes/java-0283/src/) | | +| 284 | [Peeking Iterator](https://leetcode.com/problems/peeking-iterator/) | [solution](https://leetcode.com/problems/peeking-iterator/solution/) | [C++](0001-0500/0284-Peeking-Iterator/cpp-0284/) | | | +| 285 | [Inorder Successor in BST](https://leetcode.com/problems/inorder-successor-in-bst/) | [无]
[缺:空间O(h)] | [C++](0001-0500/0285-Inorder-Successor-in-BST/cpp-0285/) | | | +| 286 | [Walls and Gates](https://leetcode.com/problems/walls-and-gates/description/) | [solution](https://leetcode.com/problems/walls-and-gates/solution/) | [C++](0001-0500/0286-Walls-and-Gates/cpp-0286/) | | | +| 287 | [Find the Duplicate Number](https://leetcode.com/problems/find-the-duplicate-number/description/) | | [C++](0001-0500/0287-Find-the-Duplicate-Number/cpp-0287/) | | | +| 288 | [Unique Word Abbreviation](https://leetcode.com/problems/unique-word-abbreviation/description/) | [solution](https://leetcode.com/problems/unique-word-abbreviation/solution/) | [C++](0001-0500/0288-Unique-Word-Abbreviation/cpp-0288/) | | | +| 289 | [Game of Life](https://leetcode.com/problems/game-of-life/) | [solution](https://leetcode.com/problems/game-of-life/solution/) | [C++](0001-0500/0289-Game-of-Life/cpp-0289/) | | | +| 290 | [Word Pattern](https://leetcode.com/problems/word-pattern/description/) | [无] | [C++](0001-0500/0290-Word-Pattern/cpp-0290/) | | | +| | | | | | | +| 292 | [Nim Game](https://leetcode.com/problems/nim-game/) | [solution](https://leetcode.com/problems/nim-game/solution/) | [C++](0001-0500/0292-Nim-Game/cpp-0292/) | | | +| | | | | | | +| 295 | [Find Median from Data Stream](https://leetcode.com/problems/find-median-from-data-stream/) | [无] | [C++](0001-0500/0295-Find-Median-from-Data-Stream/cpp-0295/) | | | +| 296 | [Best Meeting Point](https://leetcode.com/problems/best-meeting-point/) | [solution](https://leetcode.com/problems/best-meeting-point/solution/) | [C++](0001-0500/0296-Best-Meeting-Point/cpp-0296/) | | | +| 297 | [Serialize and Deserialize Binary Tree](https://leetcode.com/problems/serialize-and-deserialize-binary-tree/description/) | [solution](https://leetcode.com/problems/serialize-and-deserialize-binary-tree/solution/) | [C++](0001-0500/0297-Serialize-and-Deserialize-Binary-Tree/cpp-0297/) | | | +| 298 | [Binary Tree Longest Consecutive Sequence](https://leetcode.com/problems/binary-tree-longest-consecutive-sequence/) | [solution](https://leetcode.com/problems/binary-tree-longest-consecutive-sequence/solution/) | [C++](0001-0500/0298-Binary-Tree-Longest-Consecutive-Sequence/cpp-0298/) | | | +| 299 | [Bulls and Cows](https://leetcode.com/problems/bulls-and-cows/) | [solution](https://leetcode.com/problems/bulls-and-cows/solution/) | [C++](0001-0500/0299-Bulls-and-Cows/cpp-0299/) | | | +| 300 | [Longest Increasing Subsequence](https://leetcode.com/problems/longest-increasing-subsequence/description/) | [solution](https://leetcode.com/problems/longest-increasing-subsequence/solution/) | [C++](0001-0500/0300-Longest-Increasing-Subsequence/cpp-0300/) | [Java](0001-0500/0300-Longest-Increasing-Subsequence/java-0300/src/) | | +| 301 | [0301-Remove-Invalid-Parentheses](https://leetcode.com/problems/remove-invalid-parentheses/) | [solution](https://leetcode.com/problems/remove-invalid-parentheses/solution/)
[缺:DP+构建] | [C++](0001-0500/0301-Remove-Invalid-Parentheses/cpp-0301/) | | | +| | | | | | | +| 303 | [Range Sum Query - Immutable](https://leetcode.com/problems/range-sum-query-immutable/description/) | | [C++](0001-0500/0303/Range-Sum-Query-Immutable/cpp-0303/) | | | +| 304 | [Range Sum Query 2D - Immutable](https://leetcode.com/problems/range-sum-query-2d-immutable/) | [solution](https://leetcode.com/problems/range-sum-query-2d-immutable/solution/) | [C++](0001-0500/0304-Range-Sum-Query-2D-Immutable/cpp-0304/) | | | +| 305 | [Number of Islands II](https://leetcode.com/problems/number-of-islands-ii/description/) | [solution](https://leetcode.com/problems/number-of-islands-ii/solutions/3033683/number-of-islands-ii/?orderBy=most_votes) | [C++](0001-0500/0305-Number-of-Islands-II/cpp-0305/) | | | +| 306 | [Additive Number](https://leetcode.com/problems/additive-number/) | [无] | [C++](0001-0500/0306-Additive-Number/cpp-0306/) | | | +| 307 | [Range Sum Query - Mutable](https://leetcode.com/problems/range-sum-query-mutable/description/) | [缺:BIT] | [C++](0001-0500/0307-Range-Sum-Query-Mutable/cpp-0307/) | | | +| 308 | [Range Sum Query 2D - Mutable](https://leetcode.com/problems/range-sum-query-2d-mutable/description/) | | [C++](0001-0500/0308-Range-Sum-Query-2D-Mutable/cpp-0308/) | | | +| 309 | [Best Time to Buy and Sell Stock with Cooldown](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/description/) | [solution](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/solution/) | [C++](0001-0500/0309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown/cpp-0309/) | | | +| 310 | [Minimum Height Trees](https://leetcode.com/problems/minimum-height-trees/) | [solution](https://leetcode.com/problems/minimum-height-trees/solution/) | [C++](0001-0500/0310-Minimum-Height-Trees/cpp-0310/) | | | +| 311 | [Sparse Matrix Multiplication](https://leetcode.com/problems/sparse-matrix-multiplication/) | [无] | [C++](0001-0500/0311-Sparse-Matrix-Multiplication/cpp-0311/) | | | +| 312 | [Burst Balloons](https://leetcode.com/problems/burst-balloons/) | [solution](https://leetcode.com/problems/burst-balloons/solution/) [题解](https://leetcode-cn.com/problems/burst-balloons/solution/chuo-qi-qiu-by-leetcode/) | [C++](0001-0500/0312-Burst-Balloons/cpp-0312/) | | | +| 313 | [Super Ugly Number](https://leetcode.com/problems/super-ugly-number/) | [无] | [C++](0001-0500/0313-Super-Ugly-Number/cpp-0313/) | | | +| 314 | [Binary Tree Vertical Order Traversal](https://leetcode.com/problems/binary-tree-vertical-order-traversal/) | [无] | [C++](0001-0500/0314-Binary-Tree-Vertical-Order-Traversal/cpp-0314/) | | | +| 315 | [Count of Smaller Numbers After Self](https://leetcode.com/problems/count-of-smaller-numbers-after-self/) | [无] | [C++](0001-0500/0315-Count-of-Smaller-Numbers-After-Self/cpp-0315/) | | | +| 316 | [Remove Duplicate Letters](https://leetcode.com/problems/remove-duplicate-letters/) | [solution](https://leetcode.com/problems/remove-duplicate-letters/solution/) | [C++](0001-0500/0316-Remove-Duplicate-Letters/cpp-0316/) | | | +| 317 | [Shortest Distance from All Buildings](https://leetcode.com/problems/shortest-distance-from-all-buildings/) | [solution](https://leetcode.com/problems/shortest-distance-from-all-buildings/solution/) | [C++](0001-0500/0317-Shortest-Distance-from-All-Buildings/cpp-0317/) | | | +| 318 | [Maximum Product of Word Lengths](https://leetcode.com/problems/maximum-product-of-word-lengths/) | [solution](https://leetcode.com/problems/maximum-product-of-word-lengths/solution/) | [C++](0001-0500/0318-Maximum-Product-of-Word-Lengths/cpp-0318/) | | | +| 319 | [Bulb Switcher](https://leetcode.com/problems/bulb-switcher/description/) | [无] | [C++](0001-0500/0319-Bulb-Switcher/cpp-0319/) | | | +| | | | | | | +| 321 | [Create Maximum Number](https://leetcode.com/problems/create-maximum-number/) | [无] | [C++](0001-0500/0321-Create-Maximum-Number/cpp-0321/) | | | +| 322 | [Coin Change](https://leetcode.com/problems/coin-change/description/) | [solution](https://leetcode.com/problems/coin-change/solution/) | [C++](0001-0500/0322-Coin-Change/cpp-0322/) | | | +| 323 | [Number of Connected Components in an Undirected Graph](https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/) | [solution](https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/solution/) | [C++](0001-0500/0323-Number-of-Connected-Components-in-an-Undirected-Graph/cpp-0323/) | | | +| 324 | [Wiggle Sort II](https://leetcode.com/problems/wiggle-sort-ii/) | [无] | [C++](0001-0500/0324-Wiggle-Sort-II/cpp-0324/) | | | +| 325 | [Maximum Size Subarray Sum Equals k](https://leetcode.com/problems/maximum-size-subarray-sum-equals-k/) | [solution](https://leetcode.com/problems/maximum-size-subarray-sum-equals-k/solution/) | [C++](0001-0500/0325-Maximum-Size-Subarray-Sum-Equals-k/cpp-0325/) | | | +| 326 | [Power of Three](https://leetcode.com/problems/power-of-three/) | [solution](https://leetcode.com/problems/power-of-three/solution/) | [C++](0001-0500/0326-Power-of-Three/cpp-0326/) | | | +| | | | | | | +| 328 | [Odd Even Linked List](https://leetcode.com/problems/odd-even-linked-list/description/) | [solution](https://leetcode.com/problems/odd-even-linked-list/solution/) | [C++](0001-0500/0328-Odd-Even-Linked-List/cpp-0328/) | | | +| 329 | [Longest Increasing Path in a Matrix](https://leetcode.com/problems/longest-increasing-path-in-a-matrix/) | [solution](https://leetcode.com/problems/longest-increasing-path-in-a-matrix/solution/) | [C++](0001-0500/0329-Longest-Increasing-Path-in-a-Matrix/cpp-0329/) | | | +| 330 | [Patching Array](https://leetcode.com/problems/patching-array/) | [无] | [C++](0001-0500/0330-Patching-Array/cpp-0330/) | | | +| 331 | [Verify Preorder Serialization of a Binary Tree](https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/) | [solution](https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/solution/) | [C++](0001-0500/0331-Verify-Preorder-Serialization-of-a-Binary-Tree/cpp-0331/) | | | +| 332 | [Reconstruct Itinerary](https://leetcode.com/problems/reconstruct-itinerary/) | [solution](https://leetcode.com/problems/reconstruct-itinerary/solution/) | [C++](0001-0500/0332-Reconstruct-Itinerary/cpp-0332/) | | | +| | | | | | | +| 334 | [Increasing Triplet Subsequence](https://leetcode.com/problems/increasing-triplet-subsequence/) | [solution](https://leetcode.com/problems/increasing-triplet-subsequence/solution/) | [C++](0001-0500/0334-Increasing-Triplet-Subsequence/cpp-0334/) | | | +| 335 | [Self Crossing](https://leetcode.com/problems/self-crossing/) | [无] | [C++](0001-0500/0335-Self-Crossing/cpp-0335/) | | | +| 336 | [Palindrome Pairs](https://leetcode.com/problems/palindrome-pairs/) | [solution](https://leetcode.com/problems/palindrome-pairs/solution/) | [C++](0001-0500/0336-Palindrome-Pairs/cpp-0336/)| | | +| 337 | [House Robber III](https://leetcode.com/problems/house-robber-iii/description/) | [无] | [C++](0001-0500/0337-House-Robber-III/cpp-0337/) | | | +| 338 | [Counting Bits](https://leetcode.com/problems/counting-bits/) | [solution](https://leetcode.com/problems/counting-bits/solution/) | [C++](0001-0500/0338-Counting-Bits/cpp-0338/) | | | +| 339 | [Nested List Weight Sum](https://leetcode.com/problems/nested-list-weight-sum/) | [无] | [C++](0001-0500/0339-Nested-List-Weight-Sum/cpp-0339/) | | | +| 340 | [Longest Substring with At Most K Distinct Characters](https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/) | [solution](https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/solution/) | [C++](0001-0500/0340-Longest-Substring-with-At-Most-K-Distinct-Characters/cpp-0340/) | | | +| 341 | [Flatten Nested List Iterator](https://leetcode.com/problems/flatten-nested-list-iterator/) | [无] | [C++](0001-0500/0341-Flatten-Nested-List-Iterator/cpp-0341/) | | | +| 342 | [Power of Four](https://leetcode.com/problems/power-of-four/) | [solution](https://leetcode.com/problems/power-of-four/solution/) | [C++](0001-0500/0342-Power-of-Four/cpp-0342/) | | | +| 343 | [Integer Break](https://leetcode.com/problems/integer-break/description/) | [无] | [C++](0001-0500/0343-Integer-Break/cpp-0343/) | [Java](0001-0500/0343-Integer-Break/java-0343/src/) | | +| 344 | [Reverse String](https://leetcode.com/problems/reverse-string/description/) | [无] | [C++](0001-0500/0344-Reverse-String/cpp-0344/) | | | +| 345 | [Reverse Vowels of a String](https://leetcode.com/problems/reverse-vowels-of-a-string/description/) | [无] | [C++](0001-0500/0345-Reverse-Vowels-of-a-String/cpp-0345/) | | | +| 346 | [Moving Average from Data Stream](https://leetcode.com/problems/moving-average-from-data-stream/solution/) | [无] | [C++](0001-0500/0346-Moving-Average-from-Data-Stream/cpp-0346/) | | | +| 347 | [Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/description/) | [solution](https://leetcode.com/problems/top-k-frequent-elements/solution/) | [C++](0001-0500/0347-Top-K-Frequent-Elements/cpp-0347/) | [Java](0001-0500/0347-Top-K-Frequent-Elements/java-0347/src/) | | +| 348 | [Find Winner on a Tic Tac Toe Game](https://leetcode.com/problems/find-winner-on-a-tic-tac-toe-game/) | [无] | [C++](0001-0500/0348-Find-Winner-on-a-Tic-Tac-Toe-Game/cpp-0348/) | | | +| 349 | [Intersection of Two Arrays](https://leetcode.com/problems/intersection-of-two-arrays/description/) | [solution](https://leetcode.com/problems/intersection-of-two-arrays/solution/) | [C++](0001-0500/0349-Intersection-of-Two-Arrays/cpp-0349/) | [Java](0001-0500/0349-Intersection-of-Two-Arrays/java-0349/src/) | | +| 350 | [Intersection of Two Arrays II](https://leetcode.com/problems/intersection-of-two-arrays-ii/description/) | [无] | [C++](0001-0500/0350-Intersection-of-Two-Arrays-II/cpp-0350/) | [Java](0001-0500/0350-Intersection-of-Two-Arrays-II/java-0350/src/) | | +| | | | | | | +| 352 | [Data Stream as Disjoint Intervals](https://leetcode.com/problems/data-stream-as-disjoint-intervals/) | [无] | [C++](0001-0500/0352-Data-Stream-as-Disjoint-Intervals/cpp-0352/) | | | +| | | | | | | +| 354 | [Russian Doll Envelopes](https://leetcode.com/problems/russian-doll-envelopes/) | [solution](https://leetcode.com/problems/russian-doll-envelopes/solution/) | [C++](0001-0500/0354-Russian-Doll-Envelopes/cpp-0354/) | | | +| | | | | | | +| 357 | [Count Numbers with Unique Digits](https://leetcode.com/problems/count-numbers-with-unique-digits/) | [无] | [C++](0001-0500/0357-Count-Numbers-with-Unique-Digits/cpp-0357/) | | | +| | | | | | | +| 359 | [Logger Rate Limiter](https://leetcode.com/problems/logger-rate-limiter/description/) | [无] | [C++](0001-0500/0359-Logger-Rate-Limiter/cpp-0359/) | | | +| 360 | [Sort Transformed Array](https://leetcode.com/problems/sort-transformed-array/description/) | [无] | [C++](0001-0500/0360-Sort-Transformed-Array/cpp-0360/) | | | +| | | | | | | +| 362 | [Design Hit Counter](https://leetcode.com/problems/design-hit-counter/) | [无] | [C++](0001-0500/0362-Design-Hit-Counter/cpp-0362/) | | | +| 363 | [Max Sum of Rectangle No Larger Than K](https://leetcode.com/problems/max-sum-of-rectangle-no-larger-than-k/) | [无] | [C++](0001-0500/0363-Max-Sum-of-Rectangle-No-Larger-Than-K/cpp-0363/) | | | +| 364 | [Nested List Weight Sum II](https://leetcode.com/problems/nested-list-weight-sum-ii/) | [无] | [C++](0001-0500/0364-Nested-List-Weight-Sum-II/cpp-0364/) | | | +| 365 | [Water and Jug Problem](https://leetcode.com/problems/water-and-jug-problem/) | [题解](https://leetcode-cn.com/problems/water-and-jug-problem/solution/shui-hu-wen-ti-by-leetcode-solution/)
[缺:数学解法] | [C++](0001-0500/0365-Water-and-Jug-Problem/cpp-0365/) | | | +| 366 | [Find Leaves of Binary Tree](https://leetcode.com/problems/find-leaves-of-binary-tree/) | [solution](https://leetcode.com/problems/find-leaves-of-binary-tree/solution/) | [C++](0001-0500/0366-Find-Leaves-of-Binary-Tree/cpp-0366/) | | | +| 367 | [Valid Perfect Square](https://leetcode.com/problems/valid-perfect-square/) | [solution](https://leetcode.com/problems/valid-perfect-square/solution/) | [C++](0001-0500/0367-Valid-Perfect-Square/cpp-0367/) | | | +| 368 | [Largest Divisible Subset](https://leetcode.com/problems/largest-divisible-subset/) | [solution](https://leetcode.com/problems/largest-divisible-subset/solution/) | [C++](0001-0500/0368-Largest-Divisible-Subset/cpp-0368/) | | | +| 369 | [Plus One Linked List](https://leetcode.com/problems/plus-one-linked-list/) | [solution](https://leetcode.com/problems/plus-one-linked-list/solution/) | [C++](0001-0500/0369-Plus-One-Linked-List/cpp-0369/) | | | +| 370 | [Range Addition](https://leetcode.com/problems/range-addition/description/) | | [C++](0001-0500/0370-Range-Addition/cpp-0370/) | | | +| | | | | | | +| 372 | [Super Pow](https://leetcode.com/problems/super-pow/) | [无] | [C++](0001-0500/0372-Super-Pow/cpp-0372/) | | | +| 373 | [Find K Pairs with Smallest Sums](https://leetcode.com/problems/find-k-pairs-with-smallest-sums/) | [无] | [C++](0001-0500/0373-Find-K-Pairs-with-Smallest-Sums/cpp-0373/) | | | +| 374 | [Guess Number Higher or Lower](https://leetcode.com/problems/guess-number-higher-or-lower/description/) | [solution](https://leetcode.com/problems/guess-number-higher-or-lower/solution/) | [C++](0001-0500/0374-Guess-Number-Higher-or-Lower/cpp-0374/) | | | +| 375 | [Guess Number Higher or Lower II](https://leetcode.com/problems/guess-number-higher-or-lower-ii/) | [无] | [C++](0001-0500/0375-Guess-Number-Higher-or-Lower-II/cpp-0375/) | | | +| 376 | [Wiggle Subsequence](https://leetcode.com/problems/wiggle-subsequence/) | [solution](https://leetcode.com/problems/wiggle-subsequence/solution/) | [C++](0001-0500/0376-Wiggle-Subsequence/cpp-0376/)
[缺:DP;O(1) 空间贪心] | | | +| 377 | [Combination Sum IV](https://leetcode.com/problems/combination-sum-iv/description/) | [无] | [C++](0001-0500/0377-Combination-Sum-IV/cpp-0377/) | | | +| 378 | [Kth Smallest Element in a Sorted Matrix](https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/) | [无] | [C++](0001-0500/0378-Kth-Smallest-Element-in-a-Sorted-Matrix/cpp-0378/) | | | +| | | | | | | +| 380 | [Insert Delete GetRandom O(1)](https://leetcode.com/problems/insert-delete-getrandom-o1/description/) | [无] | [C++](0001-0500/0380-Insert-Delete-GetRandom-O(1)/cpp-0380/) | | | +| 381 | [Insert Delete GetRandom O(1) - Duplicates allowed](https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/description/) | [无] | [C++](0001-0500/0381-Insert-Delete-GetRandom-O(1)-Duplicates-allowed/cpp-0381/) | | | +| 382 | [Linked List Random Node](https://leetcode.com/problems/linked-list-random-node/description/) | [无] | [C++](0001-0500/0382-Linked-List-Random-Node/cpp-0382/) | | | +| 383 | [Ransom Note](https://leetcode.com/problems/ransom-note/) | [solution](https://leetcode.com/problems/ransom-note/solution/) | [C++](0001-0500/0383-Ransom-Note/cpp-0383/) | | | +| 384 | [Shuffle an Array](https://leetcode.com/problems/shuffle-an-array/description/) | [solution](https://leetcode.com/problems/shuffle-an-array/solution/) | [C++](0001-0500/0384-Shuffle-an-Array/cpp-0384/) | | | +| 385 | [Mini Parser](https://leetcode.com/problems/mini-parser/) | [无] | [C++](0001-0500/0385-Mini-Parser/cpp-0385/) | | | +| 386 | [Lexicographical Numbers](https://leetcode.com/problems/lexicographical-numbers/description/) | | [C++](0001-0500/0386-Lexicographical-Numbers/cpp-0386/) | | | +| 387 | [First Unique Character in a String](https://leetcode.com/problems/first-unique-character-in-a-string/description/) | [solution](https://leetcode.com/problems/first-unique-character-in-a-string/solution/) | [C++](0001-0500/0387-First-Unique-Character-in-a-String/cpp-0387/) | [Java](0001-0500/0387-First-Unique-Character-in-a-String/java-0387/src/) | | +| 388 | [Longest Absolute File Path](https://leetcode.com/problems/longest-absolute-file-path/description/) | | [C++](0001-0500/0388-Longest-Absolute-File-Path/cpp-0388/) | | | +| 389 | [Find the Difference](https://leetcode.com/problems/find-the-difference/description/) | | [C++](0001-0500/0389-Find-the-Difference/cpp-0389/) | | | +| 390 | [Elimination Game](https://leetcode.com/problems/elimination-game/description/) | | [C++](0001-0500/0390-Elimination-Game/cpp-0390/) | | | +| 391 | [Perfect Rectangle](https://leetcode.com/problems/perfect-rectangle/description/) | [缺:矩形求交] | [C++](0001-0500/0391-Perfect-Rectangle/cpp-0391/) | | | +| 392 | [Is Subsequence](https://leetcode.com/problems/is-subsequence/) | [无] | [C++](0001-0500/0392-Is-Subsequence/cpp-0392/) | | | +| 393 | [UTF-8 Validation](https://leetcode.com/problems/utf-8-validation/) | [solution](https://leetcode.com/problems/utf-8-validation/solution/) | [C++](0001-0500/0393-UTF-8-Validation/cpp-0393/) | | | +| 394 | [Decode String](https://leetcode.com/problems/decode-string/description/) | [无] | [C++](0001-0500/0394-Decode-String/cpp-0394/) | | | +| 395 | [Longest Substring with At Least K Repeating Characters](https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/) | [solution](https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/solution/)
[缺:滑动窗口] | [C++](0001-0500/0395-Longest-Substring-with-At-Least-K-Repeating-Characters/cpp-0395/) | | | +| 396 | [Rotate Function](https://leetcode.com/problems/rotate-function/) | [无] | [C++](0001-0500/0396-Rotate-Function/cpp-0396/) | | | +| 397 | [Integer Replacement](https://leetcode.com/problems/integer-replacement/) | [无] | [C++](0001-0500/0397-Integer-Replacement/cpp-0397/) | | | +| 398 | [Random Pick Index](https://leetcode.com/problems/random-pick-index/description/) | [无] | [C++](0001-0500/0398-Random-Pick-Index/cpp-0398/) | | | +| 399 | [Evaluate Division](https://leetcode.com/problems/evaluate-division/) | [solution](https://leetcode.com/problems/evaluate-division/solution/)
[缺:UF] | [C++](0001-0500/0399-Evaluate-Division/cpp-0399/) | | | +| 400 | [Nth Digit](https://leetcode.com/problems/nth-digit/) | [无] | [C++](0001-0500/0400-Nth-Digit/cpp-0400/) | | | +| 401 | [Binary Watch](https://leetcode.com/problems/binary-watch/) | [无] | [C++](0001-0500/0401-Binary-Watch/cpp-0401/) | | | +| 402 | [Remove K Digits](https://leetcode.com/problems/remove-k-digits/) | [solution](https://leetcode.com/problems/remove-k-digits/solution/) [题解](https://leetcode-cn.com/problems/remove-k-digits/solution/yi-diao-kwei-shu-zi-by-leetcode/) | [C++](0001-0500/0402-Remove-K-Digits/cpp-0402/) | | | +| 403 | [Frog Jump](https://leetcode.com/problems/Frog-Jump/) | [solution](https://leetcode.com/problems/Frog-Jump/)
[缺:dp] | [C++](0001-0500/0403-Frog-Jump/cpp-0403/) | | | +| 404 | [Sum of Left Leaves](https://leetcode.com/problems/sum-of-left-leaves/) | [无] | [C++](0001-0500/0404-Sum-of-Left-Leaves/cpp-0404/) | | | +| 405 | [Convert a Number to Hexadecimal](https://leetcode.com/problems/convert-a-number-to-hexadecimal/) | [无] | [C++](0001-0500/0405-Convert-a-Number-to-Hexadecimal/cpp-0405/) | | | +| 406 | [Queue Reconstruction by Height](https://leetcode.com/problems/queue-reconstruction-by-height/) | [无] | [C++](0001-0500/0406-Queue-Reconstruction-by-Height/cpp-0406/) | | | +| 407 | [Trapping Rain Water II](https://leetcode.com/problems/trapping-rain-water-ii/) | [无] | [C++](0001-0500/0407-Trapping-Rain-Water-II/cpp-0407/) | | | +| | | | | | | +| 410 | [Split Array Largest Sum](https://leetcode.com/problems/split-array-largest-sum/) | [solution](https://leetcode.com/problems/split-array-largest-sum/solution/) [题解](https://leetcode-cn.com/problems/split-array-largest-sum/solution/fen-ge-shu-zu-de-zui-da-zhi-by-leetcode/) | [C++](0001-0500/410-Split-Array-Largest-Sum/cpp-410/) | | | +| | | | | | | +| 412 | [Fizz Buzz](https://leetcode.com/problems/fizz-buzz/description/) | [solution](https://leetcode.com/problems/fizz-buzz/solution/) | [C++](0001-0500/0412-Fizz-Buzz/cpp-0412/) | | | +| 413 | [Arithmetic Slices](https://leetcode.com/problems/arithmetic-slices/) | [solution](https://leetcode.com/problems/arithmetic-slices/solution/) | [C++](0001-0500/0413-Arithmetic-Slices/cpp-0413/) | | | +| 414 | [Third Maximum Number](https://leetcode.com/problems/third-maximum-number/) | [无] | [C++](0001-0500/0414-Third-Maximum-Number/cpp-0414/) | | | +| 415 | [Add Strings](https://leetcode.com/problems/add-strings/) | [solution](https://leetcode.com/problems/add-strings/solution/) | [C++](0001-0500/0415-Add-Strings/cpp-0415/) | | | +| 416 | [Partition Equal Subset Sum](https://leetcode.com/problems/partition-equal-subset-sum/description/) | [无] | [C++](0001-0500/0416-Partition-Equal-Subset-Sum/cpp-0416/) | [Java](0001-0500/0416-Partition-Equal-Subset-Sum/java-0416/src/) | | +| 417 | [Pacific Atlantic Water Flow](https://leetcode.com/problems/pacific-atlantic-water-flow/description/) | | [C++](0001-0500/0417-Pacific-Atlantic-Water-Flow/cpp-0417/) | [Java](0001-0500/0417-Pacific-Atlantic-Water-Flow/java-0417/src/) | | +| | | | | | | +| 419 | [Battleships in a Board](https://leetcode.com/problems/battleships-in-a-board/) | [无] | [C++](0001-0500/0419-Battleships-in-a-Board/cpp-0419/) | | | +| 420 | [Strong Password Checker](https://leetcode.com/problems/strong-password-checker/) | [无] | [C++](0001-0500/0420-Strong-Password-Checker/cpp-0420/) | | | +| 421 | [Maximum XOR of Two Numbers in an Array](https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array/) | [solution](https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array/solution/) | [C++](0001-0500/0421-Maximum-XOR-of-Two-Numbers-in-an-Array/cpp-0421/) | | | +| 422 | [Valid Word Square](https://leetcode.com/problems/valid-word-square/description/) | [无] | [C++](0001-0500/0422-Valid-Word-Square/cpp-0422/) | | | +| 423 | [Reconstruct Original Digits from English](https://leetcode.com/problems/reconstruct-original-digits-from-english/) | [solution](https://leetcode.com/problems/reconstruct-original-digits-from-english/solution/) | [C++](0001-0500/0423-Reconstruct-Original-Digits-from-English/cpp-0423/) | | | +| 424 | [Longest Repeating Character Replacement](https://leetcode.com/problems/longest-repeating-character-replacement/) | [无] | [C++](0001-0500/0424-Longest-Repeating-Character-Replacement/cpp-0424/) | | | +| | | | | | | +| 426 | [Convert Binary Search Tree to Sorted Doubly Linked List](https://leetcode.com/problems/convert-binary-search-tree-to-sorted-doubly-linked-list/) | [solution](https://leetcode.com/problems/convert-binary-search-tree-to-sorted-doubly-linked-list/solution/) | [C++](0001-0500/0426-Convert-Binary-Search-Tree-to-Sorted-Doubly-Linked-List/cpp-0426/) | | | +| 427 | [Construct Quad Tree](https://leetcode.com/problems/construct-quad-tree/) | [无] | [C++](0001-0500/0427-Construct-Quad-Tree/cpp-0427/) | | | +| | | | | | | +| 429 | [N-ary Tree Level Order Traversal](https://leetcode.com/problems/n-ary-tree-level-order-traversal/) | [无] | [C++](0001-0500/0429-N-ary-Tree-Level-Order-Traversal/cpp-0429/) | | | +| 430 | [Flatten a Multilevel Doubly Linked List](https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list/description/) | [无] | [C++](0001-0500/0430-Flatten-a-Multilevel-Doubly-Linked-List/cpp-0430/) | | | +| 431 | [Encode N-ary Tree to Binary Tree](https://leetcode.com/problems/encode-n-ary-tree-to-binary-tree/) | [solution](https://leetcode.com/problems/encode-n-ary-tree-to-binary-tree/solution/) | [C++](0001-0500/0431-Encode-N-ary-Tree-to-Binary-Tree/cpp-0431/) | | | +| 432 | [All O one Data Structure](https://leetcode.com/problems/all-oone-data-structure/) | [无] [缺:O(1)] | [C++](0001-0500/0432-All-O-one-Data-Structure/cpp-0432/) | | | +| 433 | [Minimum Genetic Mutation](https://leetcode.com/problems/minimum-genetic-mutation/) | [无] | [C++](0001-0500/0433-Minimum-Genetic-Mutation/cpp-0433/) | | | +| 434 | [Number of Segments in a String](https://leetcode.com/problems/number-of-segments-in-a-string/description/) | [无] | [C++](0001-0500/0434-Number-of-Segments-in-a-String/cpp-0434/) | | | +| 435 | [Non-overlapping Intervals](https://leetcode.com/problems/non-overlapping-intervals/description/) | [solution](https://leetcode.com/problems/non-overlapping-intervals/solution/) | [C++](0001-0500/0435-Non-overlapping-Intervals/cpp-0435/) | [Java](0001-0500/0435-Non-overlapping-Intervals/java-0435/src/) | | +| 436 | [Find Right Interval](https://leetcode.com/problems/find-right-interval/) | [无] | [C++](0001-0500/0436-Find-Right-Interval/cpp-0436/) | | | +| 437 | [Path Sum III](https://leetcode.com/problems/path-sum-iii/description/) | [无] | [C++](0001-0500/0437-Path-Sum-III/cpp-0437/) | [Java](0001-0500/0437-Path-Sum-III/java-0437/src/) | | +| 438 | [Find All Anagrams in a String](https://leetcode.com/problems/find-all-anagrams-in-a-string/description/) | [无] | [C++](0001-0500/0438-Find-All-Anagrams-in-a-String/cpp-0438/) | | | +| 439 | [Ternary Expression Parser](https://leetcode.com/problems/ternary-expression-parser/) | [无] | [C++](0001-0500/0439-Ternary-Expression-Parser/cpp-0439/) | | | +| 440 | [K-th Smallest in Lexicographical Order](https://leetcode.com/problems/k-th-smallest-in-lexicographical-order/) | [无] [缺:更简单的实现] | [C++](0001-0500/0440-K-th-Smallest-in-Lexicographical-Order/cpp-0440/) | | | +| 441 | [Arranging Coins](https://leetcode.com/problems/arranging-coins/) | [solution](https://leetcode.com/problems/arranging-coins/solution/) | [C++](0001-0500/0441-Arranging-Coins/cpp-0441/) | | | +| 442 | [Find All Duplicates in an Array](https://leetcode.com/problems/find-all-duplicates-in-an-array/) | [solution](https://leetcode.com/problems/find-all-duplicates-in-an-array/solution/) | [C++](0001-0500/0442-Find-All-Duplicates-in-an-Array/cpp-0442/) | | | +| 443 | [String Compression](https://leetcode.com/problems/string-compression/description/) | | [C++](0001-0500/0443-String-Compression/cpp-0443/) | | | +| 444 | [Sequence Reconstruction](https://leetcode.com/problems/sequence-reconstruction/) | [无] | [C++](0001-0500/0444-Sequence-Reconstruction/cpp-0444/) | | | +| 445 | [Add Two Numbers II](https://leetcode.com/problems/add-two-numbers-ii/) | [无] | [C++](0001-0500/0445-Add-Two-Numbers-II/cpp-0445/) | | | +| 446 | [Arithmetic Slices II - Subsequence](https://leetcode.com/problems/arithmetic-slices-ii-subsequence/) | [solution](https://leetcode.com/problems/arithmetic-slices-ii-subsequence/solution/) | [C++](0001-0500/0446-Arithmetic-Slices-II-Subsequence/cpp-0446/) | | | +| 447 | [Number of Boomerangs](https://leetcode.com/problems/number-of-boomerangs/description/) | [无] | [C++](0001-0500/0447-Number-of-Boomerangs/cpp-0447/) | [Java](0001-0500/0447-Number-of-Boomerangs/java-0447/src/) | | +| 448 | [Find All Numbers Disappeared in an Array](https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/) | [solution](https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/solution/) | [C++](0001-0500/0448-Find-All-Numbers-Disappeared-in-an-Array/cpp-0448/) | | | +| 449 | [Serialize and Deserialize BST](https://leetcode.com/problems/serialize-and-deserialize-bst/) | [solution](https://leetcode.com/problems/serialize-and-deserialize-bst/solution/) | [C++](0001-0500/0449-Serialize-and-Deserialize-BST/cpp-0449/) | | | +| 450 | [Delete Node in a BST](https://leetcode.com/problems/delete-node-in-a-bst/) | [solution](https://leetcode.com/problems/delete-node-in-a-bst/solution/) | [C++](0001-0500/0450-Delete-Node-in-a-BST/cpp-0450/) | | | +| 451 | [Sort Characters By Frequency](https://leetcode.com/problems/sort-characters-by-frequency/description/) | [无] | [C++](0001-0500/0451-Sort-Characters-By-Frequency/cpp-0451/) | [Java](0001-0500/0451-Sort-Characters-By-Frequency/java-0451/) | | +| 452 | [Minimum Number of Arrows to Burst Balloons](https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/) | [solution](https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/solution/) | [C++](0001-0500/0452-Minimum-Number-of-Arrows-to-Burst-Balloons/cpp-0452/) | | | +| 453 | [Minimum Moves to Equal Array Elements](https://leetcode.com/problems/minimum-moves-to-equal-array-elements/) | [solution](https://leetcode.com/problems/minimum-moves-to-equal-array-elements/solution/) | [C++](0001-0500/0453-Minimum-Moves-to-Equal-Array-Elements/cpp-0453/) | | | +| 454 | [4Sum II](https://leetcode.com/problems/4sum-ii/description/) | [无] | [C++](0001-0500/0454-4Sum-II/cpp-0454/) | [Java](0001-0500/0454-4Sum-II/java-0454/src/) | | +| 455 | [Assign Cookies](https://leetcode.com/problems/assign-cookies/description/) | [无] | [C++](0001-0500/0455-Assign-Cookies/cpp-0455/) | [Java](0001-0500/0455-Assign-Cookies/java-0455/src/) | | +| 456 | [132 Pattern](https://leetcode.com/problems/132-pattern/) | [solution](https://leetcode.com/problems/132-pattern/solution/)
[缺:O(n) 单调栈算法] | [C++](0001-0500/0456-132-Pattern/cpp-0456/) | | | +| 457 | [Circular Array Loop](https://leetcode.com/problems/circular-array-loop/) | [无] | [C++](0001-0500/0457-Circular-Array-Loop/cpp-0457/) | | | +| 458 | [Poor Pigs](https://leetcode.com/problems/poor-pigs/) | [solution](https://leetcode.com/problems/poor-pigs/solution/) | [C++](0001-0500/0458-Poor-Pigs/) | | | +| 459 | [Repeated Substring Pattern](https://leetcode.com/problems/repeated-substring-pattern/description/) | [无] | [C++](0001-0500/0459-Repeated-Substring-Pattern/cpp-0459/) | | | +| 460 | [LFU Cache](https://leetcode.com/problems/lfu-cache/description/) | [solution](https://leetcode.com/problems/lfu-cache/solutions/2815229/lfu-cache/?orderBy=most_votes) | [C++](0001-0500/0460-LFU-Cache/) | | | +| 461 | [Hamming Distance](https://leetcode.com/problems/hamming-distance/) | [solution](https://leetcode.com/problems/hamming-distance/solution/) | [C++](0001-0500/0461-Hamming-Distance/cpp-0461/) | | | +| 462 | [Minimum Moves to Equal Array Elements II](https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii/) | [solution](https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii/solution/) | [C++](0001-0500/0462-Minimum-Moves-to-Equal-Array-Elements-II/cpp-0462/) | | | +| 463 | [Island Perimeter](https://leetcode.com/problems/island-perimeter/) | [solution](https://leetcode.com/problems/island-perimeter/solution/) | [C++](0001-0500/0463-Island-Perimeter/cpp-0463/) | | | +| 464 | [Can I Win](https://leetcode.com/problems/can-i-win/) | [无] | [C++](0001-0500/0464-Can-I-Win/cpp-0464/) | | | +| | | | | | | +| 467 | [Unique Substrings in Wraparound String](https://leetcode.com/problems/unique-substrings-in-wraparound-string/) | [无] | [C++](0001-0500/0467-Unique-Substrings-in-Wraparound-String/cpp-0467/) | | | +| 468 | [Validate IP Address](https://leetcode.com/problems/validate-ip-address/) | [无] | [C++](0001-0500/0468-Validate-IP-Address/cpp-0468/) | | | +| | | | | | | +| 470 | [Implement Rand10() Using Rand7()](https://leetcode.com/problems/implement-rand10-using-rand7/description/) | [solution](https://leetcode.com/problems/implement-rand10-using-rand7/solution/) | [C++](0001-0500/0470-Implement-Rand10-Using-Rand7/cpp-0470/) | | | +| | | | | | | +| 472 | [Concatenated Words](https://leetcode.com/problems/concatenated-words/) | [无] | [C++](0001-0500/0472-Matchsticks-to-Square/cpp-0472/) | | | +| 473 | [Matchsticks to Square](https://leetcode.com/problems/matchsticks-to-square/description/) | [solution](https://leetcode.com/problems/matchsticks-to-square/solution/) | [C++](0001-0500/0473-Matchsticks-to-Square/cpp-0473/) | | | +| 474 | [Ones and Zeroes](https://leetcode.com/problems/ones-and-zeroes/description/) | [solution](https://leetcode.com/problems/ones-and-zeroes/solution/) | [C++](0001-0500/0474-Ones-and-Zeroes/cpp-0474/) | | | +| 475 | [Heaters](https://leetcode.com/problems/heaters/) | [无] | [C++](0001-0500/0475-Heaters/cpp-0475/) | | | +| 476 | [Number Complement](https://leetcode.com/problems/number-complement/) | [solution](https://leetcode.com/problems/number-complement/solution/) | [C++](0001-0500/0476-Number-Complement/cpp-0476/) | | | +| 477 | [Total Hamming Distance](https://leetcode.com/problems/total-hamming-distance/) | [solution](https://leetcode.com/problems/total-hamming-distance/solution/) [题解](https://leetcode-cn.com/problems/total-hamming-distance/solution/yi-ming-ju-chi-zong-he-by-leetcode/) | [C++](0001-0500/477-Total-Hamming-Distance/cpp-477/) | | | +| 478 | [Generate Random Point in a Circle](https://leetcode.com/problems/generate-random-point-in-a-circle/description/) | [solution](https://leetcode.com/problems/generate-random-point-in-a-circle/solution/) | [C++](0001-0500/0478-Generate-Random-Point-in-a-Circle/cpp-0478/) | | | +| 479 | [Largest Palindrome Product](https://leetcode.com/problems/largest-palindrome-product/) | [无] | [C++](0001-0500/0479-Largest-Palindrome-Product/cpp-0479/) | | | +| 480 | [Sliding Window Median](https://leetcode.com/problems/sliding-window-median/) | [无]
[缺:双数据结构] | [C++](0001-0500/0480-Sliding-Window-Median/cpp-0480/) | | | +| 481 | [Magical String](https://leetcode.com/problems/magical-string/) | [无] | [C++](0001-0500/0481-Magical-String/cpp-0481/) | | | +| 482 | [License Key Formatting](https://leetcode.com/problems/license-key-formatting/) | [无] | [C++](0001-0500/0482-License-Key-Formatting/cpp-0482/) | | | +| 483 | [Smallest Good Base](https://leetcode.com/problems/smallest-good-base/) | [无] | [C++](0001-0500/0483-Smallest-Good-Base/cpp-0483/) | | | +| 484 | [Find Permutation](https://leetcode.com/problems/find-permutation/) | [solution](https://leetcode.com/problems/find-permutation/solution/) | [C++](0001-0500/0484-Find-Permutation/cpp-0484/) | | | +| 485 | [Max Consecutive Ones](https://leetcode.com/problems/max-consecutive-ones/description/) | [无] | [C++](0001-0500/0485-Max-Consecutive-Ones/cpp-0485/) | | | +| 486 | [Predict the Winner](https://leetcode.com/problems/predict-the-winner/) | [无] | [C++](0001-0500/0486-Predict-the-Winner/cpp-0486/) | | | +| 487 | [Max Consecutive Ones II](https://leetcode.com/problems/max-consecutive-ones-ii/) | [无] | [C++](0001-0500/0487-Max-Consecutive-Ones-II/cpp-0487/) | | | +| 488 | [Zuma Game](https://leetcode.com/problems/zuma-game/) | [无] | [C++](0001-0500/0488-Zuma-Game/cpp-0488/) | | | +| 489 | [Robot Room Cleaner](https://leetcode.com/problems/robot-room-cleaner/) | [solution](https://leetcode.com/problems/robot-room-cleaner/solution/) | [C++](0001-0500/0489-Robot-Room-Cleaner/cpp-0489/) | | | +| 490 | [The Maze](https://leetcode.com/problems/the-maze/description/) | [solution](https://leetcode.com/problems/the-maze/solution/) | [C++](0001-0500/0490-The-Maze/cpp-0490/) | | | +| 491 | [Non-decreasing Subsequences](https://leetcode.com/problems/non-decreasing-subsequences/description/) | [无] | [C++](0001-0500/0491-Non-decreasing-Subsequences/cpp-0491/) | | | +| 492 | [Construct the Rectangle](https://leetcode.com/problems/construct-the-rectangle/) | [无] | [C++](0001-0500/0492-Construct-the-Rectangle/cpp-0492/) | | | +| | | | | | | +| 494 | [Target Sum](https://leetcode.com/problems/target-sum/description/) | [solution](https://leetcode.com/problems/target-sum/solution/) | [C++](0001-0500/0494-Target-Sum/cpp-0494/) | | | +| 495 | [Teemo Attacking](https://leetcode.com/problems/teemo-attacking/) | [solution](https://leetcode.com/problems/teemo-attacking/solution/) | [C++](0001-0500/0495-Teemo-Attacking/cpp-0495/) | | | +| 496 | [Next Greater Element I](https://leetcode.com/problems/next-greater-element-i/) | [solution](https://leetcode.com/problems/next-greater-element-i/solution/) | [C++](0001-0500/0496-Next-Greater-Element-I/cpp-0496/) | | | +| 497 | [Random Point in Non-overlapping Rectangles](https://leetcode.com/problems/random-point-in-non-overlapping-rectangles/solution/) | [solution](https://leetcode.com/problems/random-point-in-non-overlapping-rectangles/solution/) | [C++](0001-0500/0497-Random-Point-in-Non-overlapping-Rectangles/cpp-0497/) | | | +| 498 | [Diagonal Traverse](https://leetcode.com/problems/diagonal-traverse/description/) | [无] | [C++](0001-0500/0498-Diagonal-Traverse/cpp-0498/) | | | +| | | | | | | +| 500 | [Keyboard Row](https://leetcode.com/problems/keyboard-row/) | [无] | [C++](0001-0500/0500-Keyboard-Row/cpp-0500/) | | | +| 501 | [Find Mode in Binary Search Tree](https://leetcode.com/problems/find-mode-in-binary-search-tree/) | [无] | [C++](0501-1000/0501-Find-Mode-in-Binary-Search-Tree/cpp-0501/) | | | +| 502 | [IPO](https://leetcode.com/problems/ipo/) | [solution](https://leetcode.com/problems/ipo/solution/) | [C++](0501-1000/0502-IPO/cpp-0502/) | | | +| 503 | [Next Greater Element II](https://leetcode.com/problems/next-greater-element-ii/) | [solution](https://leetcode.com/problems/next-greater-element-ii/solution/) | [C++](0501-1000/0503-Next-Greater-Element-II/cpp-0503/) | | | +| 504 | [Base 7](https://leetcode.com/problems/base-7/) | [无] | [C++](0501-1000/0504-Base-7/cpp-0504/) | | | +| 505 | [The Maze II](https://leetcode.com/problems/the-maze-ii/) | [solution](https://leetcode.com/problems/the-maze-ii/solution/) | [C++](0501-1000/0505-The-Maze-II/cpp-0505/) | | | +| 506 | [Relative Ranks](https://leetcode.com/problems/relative-ranks/) | [无] | [C++](0501-1000/0506-Relative-Ranks/cpp-0506/) | | | +| 507 | [Perfect Number](https://leetcode.com/problems/perfect-number/) | [solution](https://leetcode.com/problems/perfect-number/solution/) | [C++](0501-1000/0507-Perfect-Number/cpp-0507/) | | | +| 508 | [Most Frequent Subtree Sum](https://leetcode.com/problems/most-frequent-subtree-sum/) | [无] | [C++](0501-1000/0508-Most-Frequent-Subtree-Sum/cpp-0508/) | | | +| 509 | [Fibonacci Number](https://leetcode.com/problems/fibonacci-number/) | [无] | [C++](0501-1000/0509-Fibonacci-Number/cpp-0509/) | | | +| 510 | [Inorder Successor in BST II](https://leetcode.com/problems/inorder-successor-in-bst-ii/) | [无] | [C++](0501-1000/0510-Inorder-Successor-in-BST-II/cpp-0510/) | | | +| 511 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| | | | | | | +| 513 | [Find Bottom Left Tree Value](https://leetcode.com/problems/find-bottom-left-tree-value/) | [无] | [C++](0501-1000/0513-Find-Bottom-Left-Tree-Value/cpp-0513/) | | | +| | | | | | | +| 515 | [Find Largest Value in Each Tree Row](https://leetcode.com/problems/find-largest-value-in-each-tree-row/) | [无] | [C++](0501-1000/0515-Find-Largest-Value-in-Each-Tree-Row/cpp-0515/) | | | +| 516 | [Longest Palindromic Subsequence](https://leetcode.com/problems/longest-palindromic-subsequence/) | [无] | [C++](0501-1000/0516-Longest-Palindromic-Subsequence/cpp-0516/) | | | +| 517 | [Super Washing Machines](https://leetcode.com/problems/super-washing-machines/) | [solution](https://leetcode.com/problems/super-washing-machines/solution/) | [C++](0501-1000/0517-Super-Washing-Machines/cpp-0517/) | | | +| 518 | [Coin Change 2](https://leetcode.com/problems/coin-change-2/description/) | [无] | [C++](0501-1000/0518-Coin-Change-2/cpp-0518/) | | | +| 519 | [Random Flip Matrix](https://leetcode.com/problems/random-flip-matrix/description/) | [solution](https://leetcode.com/problems/random-flip-matrix/solution/) | [C++](0501-1000/0519-Random-Flip-Matrix/cpp-0519/) | | | +| 520 | [Detect Capital](https://leetcode.com/problems/detect-capital/) | [solution](https://leetcode.com/problems/detect-capital/solution/) | [C++](0501-1000/0520-Detect-Capital/cpp-0520/) | | | +| 521 | [Longest Uncommon Subsequence I](https://leetcode.com/problems/longest-uncommon-subsequence-i/) | [solution](https://leetcode.com/problems/longest-uncommon-subsequence-i/solution/) | [C++](0501-1000/0521-Longest-Uncommon-Subsequence-I/cpp-0521/) | | | +| 522 | [Longest Uncommon Subsequence II](https://leetcode.com/problems/longest-uncommon-subsequence-ii/) | [solution](https://leetcode.com/problems/longest-uncommon-subsequence-ii/solution/) | [C++](0501-1000/0522-Longest-Uncommon-Subsequence-II/cpp-0522/) | | | +| 523 | [Continuous Subarray Sum](https://leetcode.com/problems/continuous-subarray-sum/) | [无] | [C++](0501-1000/0523-Continuous-Subarray-Sum/cpp-0523/) | | | +| 524 | [Longest Word in Dictionary through Deleting](https://leetcode.com/problems/longest-word-in-dictionary-through-deleting/) | [solution](https://leetcode.com/problems/longest-word-in-dictionary-through-deleting/solution/) | [C++](0501-1000/0524-Longest-Word-in-Dictionary-through-Deleting/cpp-0524/) | | | +| 525 | [Contiguous Array](https://leetcode.com/problems/contiguous-array/) | [solution](https://leetcode.com/problems/contiguous-array/solution/) [题解](https://leetcode-cn.com/problems/contiguous-array/solution/lian-xu-shu-zu-by-leetcode/) | [C++](0501-1000/0525-Contiguous-Array/cpp-0525/) | | | +| 526 | [Beautiful Arrangement](https://leetcode.com/problems/beautiful-arrangement/) | [solution](https://leetcode.com/problems/beautiful-arrangement/solution/) | [C++](0501-1000/0526-Beautiful-Arrangement/cpp-0526/) | | | +| 527 | [Word Abbreviation](https://leetcode.com/problems/word-abbreviation/) | [solution](https://leetcode.com/problems/word-abbreviation/solution/) | [C++](0501-1000/0527-Word-Abbreviation/cpp-0527/) | | | +| 528 | [Random Pick with Weight](https://leetcode.com/problems/random-pick-with-weight/description/) | [solution](https://leetcode.com/problems/random-pick-with-weight/solution/) | [C++](0501-1000/0528-Random-Pick-with-Weight/cpp-0528/) | | | +| 529 | [Minesweeper](https://leetcode.com/problems/minesweeper/) | [无] | [C++](0501-1000/0529-Minesweeper/cpp-0529/) | | | +| 530 | [Minimum Absolute Difference in BST](https://leetcode.com/problems/minimum-absolute-difference-in-bst/description/) | [无] | | [Java](0501-1000/0530-Minimum-Absolute-Difference-in-BST/java-0530/src/) | | +| 531 | [Lonely Pixel I](https://leetcode.com/problems/lonely-pixel-i/) | [无] | [C++](0501-1000/0531-Lonely-Pixel-I/cpp-0531/) | | | +| 532 | [K-diff Pairs in an Array](https://leetcode.com/problems/k-diff-pairs-in-an-array/) | [solution](https://leetcode.com/problems/k-diff-pairs-in-an-array/solution/) | [C++](0501-1000/0532-K-diff-Pairs-in-an-Array/cpp-0532/) | | | +| 533 | [Lonely Pixel II](https://leetcode.com/problems/lonely-pixel-ii/) | [无] | [C++](0501-1000/0533-Lonely-Pixel-II/cpp-0533/) | | | +| | | | | | | +| 536 | [Construct Binary Tree from String](https://leetcode.com/problems/construct-binary-tree-from-string/) | [solution](https://leetcode.com/problems/construct-binary-tree-from-string/solution/)
[缺:stack] | [C++](0501-1000/0536-Construct-Binary-Tree-from-String/cpp-0536/) | | | +| 537 | [Complex Number Multiplication](https://leetcode.com/problems/complex-number-multiplication/) | [solution](https://leetcode.com/problems/complex-number-multiplication/solution/) | [C++](0501-1000/0537-Complex-Number-Multiplication/cpp-0537/) | | | +| 538 | [Convert BST to Greater Tree](https://leetcode.com/problems/convert-bst-to-greater-tree/) | [solution](https://leetcode.com/problems/convert-bst-to-greater-tree/solution/) | [C++](0501-1000/0538-Convert-BST-to-Greater-Tree/cpp-0538/) | | | +| 539 | [Minimum Time Difference](https://leetcode.com/problems/minimum-time-difference/) | [无] | [C++](0501-1000/0539-Convert-BST-to-Greater-Tree/cpp-0539/) | | | +| 540 | [Single Element in a Sorted Array](https://leetcode.com/problems/single-element-in-a-sorted-array/) | [solution](https://leetcode.com/problems/single-element-in-a-sorted-array/solution/) | [C++](0501-1000/0540-Single-Element-in-a-Sorted-Array/cpp-0540/) | | | +| 541 | [Reverse String II](https://leetcode.com/problems/reverse-string-ii/description/) | [solution](https://leetcode.com/problems/reverse-string-ii/solution/) | [C++](0501-1000/0541-Reverse-String-II/cpp-0541/) | | | +| 542 | [01 Matrix](https://leetcode.com/problems/01-matrix/description/) | [solution](https://leetcode.com/problems/01-matrix/solution/) | [C++](0501-1000/0542-01-Matrix/cpp-0542/) | | | +| 543 | [Diameter of Binary Tree](https://leetcode.com/problems/diameter-of-binary-tree/) | [solution](https://leetcode.com/problems/diameter-of-binary-tree/solution/) | [C++](0501-1000/0543-Diameter-of-Binary-Tree/cpp-0543/) | | | +| | | | | | | +| 546 | [Remove Boxes](https://leetcode.com/problems/remove-boxes/) | [solution](https://leetcode.com/problems/remove-boxes/solution/) | [C++](0501-1000/0546-Remove-Boxes/cpp-0546/) | | | +| 547 | [Number of Provinces](https://leetcode.com/problems/number-of-provinces/) | [solution](https://leetcode.com/problems/number-of-provinces/solution/) | [C++](0501-1000/0547-Number-of-Provinces/cpp-0547/) | | | +| | | | | | | +| 549 | [Binary Tree Longest Consecutive Sequence II](https://leetcode.com/problems/binary-tree-longest-consecutive-sequence-ii/) | [solution](https://leetcode.com/problems/binary-tree-longest-consecutive-sequence-ii/solution/) | [C++](0501-1000/0549-Binary-Tree-Longest-Consecutive-Sequence-II/cpp-0549/) | | | +| | | | | | | +| 551 | [Student Attendance Record I](https://leetcode.com/problems/student-attendance-record-i/) | [solution](https://leetcode.com/problems/student-attendance-record-i/solution/) | [C++](0501-1000/0551-Student-Attendance-Record-I/cpp-0551/) | | | +| 552 | [Student Attendance Record II](https://leetcode.com/problems/student-attendance-record-ii/) | [solution](https://leetcode.com/problems/student-attendance-record-ii/solution/) | [C++](0501-1000/0552-Student-Attendance-Record-II/cpp-0552/) | | | +| 553 | [Optimal Division](https://leetcode.com/problems/optimal-division/) | [solution](https://leetcode.com/problems/optimal-division/solution/)
[缺:O(n) 解法] | [C++](0501-1000/0553-Optimal-Division/cpp-0553/) | | | +| 554 | [Brick Wall](https://leetcode.com/problems/brick-wall/) | [solution](https://leetcode.com/problems/brick-wall/solution/) | [C++](0501-1000/0554-Brick-Wall/cpp-0554/) | | | +| | | | | | | +| 556 | [Next Greater Element III](https://leetcode.com/problems/next-greater-element-iii/) | [solution](https://leetcode.com/problems/next-greater-element-iii/solution/)
[缺:底层实现] | [C++](0501-1000/0556-Next-Greater-Element-III/cpp-0556/) | | | +| 557 | [Reverse Words in a String III](https://leetcode.com/problems/reverse-words-in-a-string-iii/description/) | [solution](https://leetcode.com/problems/reverse-words-in-a-string-iii/solution/) | [C++](0501-1000/0557-Reverse-Words-in-a-String-III/cpp-0557/) | | | +| 558 | [Logical OR of Two Binary Grids Represented as Quad-Trees](https://leetcode.com/problems/logical-or-of-two-binary-grids-represented-as-quad-trees/) | [无] | [C++](0501-1000/0558-Logical-OR-of-Two-Binary-Grids-Represented-as-Quad-Trees/cpp-0558/) | | | +| 559 | [Maximum Depth of N-ary Tree](https://leetcode.com/problems/maximum-depth-of-n-ary-tree/description/) | [solution](https://leetcode.com/problems/maximum-depth-of-n-ary-tree/solution/) | [C++](0501-1000/0559-Maximum-Depth-of-N-ary-Tree/cpp-0559/) | | | +| 560 | [Subarray Sum Equals K](https://leetcode.com/problems/subarray-sum-equals-k/) | [solution](https://leetcode.com/problems/subarray-sum-equals-k/solution/) | [C++](0501-1000/0560-Subarray-Sum-Equals-K/cpp-0560/) | | | +| 561 | [Array Partition I](https://leetcode.com/problems/array-partition-i/description/) | [solution](https://leetcode.com/problems/array-partition-i/solution/) | [C++](0501-1000/0561-Array-Partition-I/cpp-0561/) | | | +| | | | | | | +| 563 | [Binary Tree Tilt](https://leetcode.com/problems/binary-tree-tilt/) | [solution](https://leetcode.com/problems/binary-tree-tilt/solution/) | [C++](0501-1000/0563-Binary-Tree-Tilt/cpp-0563/) | | | +| 564 | [Find the Closest Palindrome](https://leetcode.com/problems/find-the-closest-palindrome/) | [无] | [C++](0501-1000/0564-Find-the-Closest-Palindrome/cpp-0564/) | | | +| 565 | [Array Nesting](https://leetcode.com/problems/array-nesting/) | [solution](https://leetcode.com/problems/array-nesting/solution/) | [C++](0501-1000/0565-Array-Nesting/cpp-0565/) | | | +| 566 | [Reshape the Matrix](https://leetcode.com/problems/reshape-the-matrix/) | [solution](https://leetcode.com/problems/reshape-the-matrix/solution/) | [C++](0501-1000/0566-Reshape-the-Matrix/cpp-0566/) | | | +| 567 | [Permutation in String](https://leetcode.com/problems/permutation-in-string/) | [solution](https://leetcode.com/problems/permutation-in-string/solution/) [题解](https://leetcode-cn.com/problems/permutation-in-string/solution/zi-fu-chuan-de-pai-lie-by-leetcode/) | [C++](0501-1000/0567-Permutation-in-String/cpp-0567/) | | | +| | | | | | | +| 570 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| | | | | | | +| 572 | [Subtree of Another Tree](https://leetcode.com/problems/subtree-of-another-tree/description/) | [solution](https://leetcode.com/problems/subtree-of-another-tree/solution/) | [C++](0501-1000/0572-Subtree-of-Another-Tree/cpp-0572/) | | | +| 573 | [Squirrel Simulation](https://leetcode.com/problems/squirrel-simulation/) |[solution](https://leetcode.com/problems/squirrel-simulation/solution/) | [C++](0501-1000/0573-Squirrel-Simulation/cpp-0573/) | | | +| | | | | | | +| 575 | [Distribute Candies](https://leetcode.com/problems/distribute-candies/) | [solution](https://leetcode.com/problems/distribute-candies/solution/) | [C++](0501-1000/0575-Distribute-Candies/cpp-0575/) | | | +| 576 | [Out of Boundary Paths](https://leetcode.com/problems/out-of-boundary-paths/) | [solution](https://leetcode.com/problems/out-of-boundary-paths/solution/) | [C++](0501-1000/0576-Out-of-Boundary-Paths/cpp-0576/) | | | +| | | | | | | +| 580 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 581 | [Shortest Unsorted Continuous Subarray](https://leetcode.com/problems/shortest-unsorted-continuous-subarray/) | [solution](https://leetcode.com/problems/shortest-unsorted-continuous-subarray/solution/)
[缺:Stack] | [C++](0501-1000/0581-Shortest-Unsorted-Continuous-Subarray/cpp-0581/) | | | +| 582 | [Kill Process](https://leetcode.com/problems/kill-process/) | [solution](https://leetcode.com/problems/kill-process/solution/) | [C++](0501-1000/0582-Kill-Process/cpp-0582/) | | | +| 583 | [Delete Operation for Two Strings](https://leetcode.com/problems/delete-operation-for-two-strings/description/) | [solution](https://leetcode.com/problems/delete-operation-for-two-strings/solution/) | [C++](0501-1000/0583-Delete-Operation-for-Two-Strings/cpp-0583/) | | | +| 584 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| | | | | | | +| 586 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 587 | [Erect the Fence](https://leetcode.com/problems/erect-the-fence/) | [solution](https://leetcode.com/problems/erect-the-fence/solution/) [题解](https://leetcode-cn.com/problems/erect-the-fence/solution/an-zhuang-zha-lan-by-leetcode/)
[缺:凸包解法整理] | [C++](0501-1000/0587-Erect-the-Fence/cpp-0587/) | | | +| | | | | | | +| 589 | [N-ary Tree Preorder Traversal](https://leetcode.com/problems/n-ary-tree-preorder-traversal/) | [solution](https://leetcode.com/problems/n-ary-tree-preorder-traversal/solution/) | [C++](0501-1000/0589-N-ary-Tree-Preorder-Traversal/cpp-0589/) | | | +| 590 | [N-ary Tree Postorder Transversal](https://leetcode.com/problems/n-ary-tree-postorder-traversal/) | [solution](https://leetcode.com/problems/n-ary-tree-postorder-traversal/solution/) | [C++](0501-1000/0590-N-ary-Tree-Postorder-Transversal/cpp-0590/) | | | +| 591 | [Tag Validator](https://leetcode.com/problems/tag-validator/) | [solution](https://leetcode.com/problems/tag-validator/solution/) | [C++](0501-1000/0591-Tag-Validator/cpp-0591/) | | | +| 592 | [Fraction Addition and Subtraction](https://leetcode.com/problems/fraction-addition-and-subtraction/) | [无] | [C++](0501-1000/0592-Fraction-Addition-and-Subtraction/cpp-0592/) | | | +| 593 | [Valid Square](https://leetcode.com/problems/valid-square/) | [solution](https://leetcode.com/problems/valid-square/solution/) | [C++](0501-1000/0593-Valid-Square/cpp-0593/) | | | +| 594 | [Longest Harmonious Subsequence](https://leetcode.com/problems/longest-harmonious-subsequence/) | [solution](https://leetcode.com/problems/longest-harmonious-subsequence/solution/) | [C++](0501-1000/0594-Longest-Harmonious-Subsequence/cpp-0594/) | | | +| 595 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| | | | | | | +| 598 | [Range Addition II](https://leetcode.com/problems/range-addition-ii/description/) | | [C++](0501-1000/0598-Range-Addition-II/cpp-0598/) | | | +| 599 | [Minimum Index Sum of Two Lists](https://leetcode.com/explore/learn/card/hash-table/184/comparison-with-other-data-structures/1177/) | [solution](https://leetcode.com/problems/minimum-index-sum-of-two-lists/solution/) | [C++](0501-1000/0599-Minimum-Index-Sum-of-Two-Lists/cpp-0599/) | | | +| 600 | [Non-negative Integers without Consecutive Ones](https://leetcode.com/problems/non-negative-integers-without-consecutive-ones/description/) | [solution](https://leetcode.com/problems/non-negative-integers-without-consecutive-ones/solution/)
[缺:Bit Manipulation]| [C++](0501-1000/0600-Non-negative-Integers-without-Consecutive-Ones/cpp-0600/) | | | +| | | | | | | +| 605 | [Can Place Flowers](https://leetcode.com/problems/can-place-flowers/) | [solution](https://leetcode.com/problems/can-place-flowers/solution/) | [C++](0501-1000/0605-Can-Place-Flowers/cpp-0605/) | | | +| 606 | [Construct String from Binary Tree](https://leetcode.com/problems/construct-string-from-binary-tree/) | [solution](https://leetcode.com/problems/construct-string-from-binary-tree/solution/) | [C++](0501-1000/0606-Construct-String-from-Binary-Tree/cpp-0606/) | | | +| 607 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 608 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 609 | [Find Duplicate File in System](https://leetcode.com/problems/find-duplicate-file-in-system/) | [solution](https://leetcode.com/problems/find-duplicate-file-in-system/solution/) | [C++](0501-1000/0609-Find-Duplicate-File-in-System/cpp-0609/) | | | +| | | | | | | +| 611 | [Valid Triangle Number](https://leetcode.com/problems/valid-triangle-number/) | [solution](https://leetcode.com/problems/valid-triangle-number/solution/) | [C++](0501-1000/0611-Valid-Triangle-Number/cpp-0611/) | | | +| | | | | | | +| 617 | [Merge Two Binary Trees](https://leetcode.com/problems/merge-two-binary-trees/) | [C++](0501-1000/0617-Merge-Two-Binary-Trees/cpp-0617/) | | | | +| | | | | | | +| 619 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| | | | | | | +| 621 | [Task Scheduler](https://leetcode.com/problems/task-scheduler/) | [solution](https://leetcode.com/problems/task-scheduler/solution/) | [C++](0501-1000/0621-Task-Scheduler/cpp-0621/) | | | +| 622 | [Design Circular Queue](https://leetcode.com/problems/design-circular-queue/description/) | [无] | [C++](0501-1000/0622-Design-Circular-Queue/cpp-0622/) | | | +| 623 | [Add One Row to Tree](https://leetcode.com/problems/add-one-row-to-tree/) | [solution](https://leetcode.com/problems/add-one-row-to-tree/solution/) | [C++](0501-1000/0623-Add-One-Row-to-Tree/cpp-0623/) | | | +| | | | | | | +| 627 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 628 | [Maximum Product of Three Numbers](https://leetcode.com/problems/maximum-product-of-three-numbers/) | [solution](https://leetcode.com/problems/maximum-product-of-three-numbers/solution/) | [C++](0501-1000/0628-Maximum-Product-of-Three-Numbers/cpp-0628/) | | | +| 629 | [K-Inverse-Pairs-Array](https://leetcode.com/problems/k-inverse-pairs-array/) | [solution](https://leetcode.com/problems/k-inverse-pairs-array/solution/)
[缺:其他 dp 优化思路] | [C++](0501-1000/0629-K-Inverse-Pairs-Array/cpp-0629/) | | | +| 630 | [Course Schedule III](https://leetcode.com/problems/course-schedule-iii/) | [solution](https://leetcode.com/problems/course-schedule-iii/solution/) | [C++](0501-1000/0630-Course-Schedule-III/cpp-0630/) | | | +| | | | | | | +| 632 | [Smallest Range Covering Elements from K Lists](https://leetcode.com/problems/smallest-range-covering-elements-from-k-lists/) | [solution](https://leetcode.com/problems/smallest-range-covering-elements-from-k-lists/solution/) | [C++](0501-1000/0632-Smallest-Range-Covering-Elements-from-K-Lists/cpp-0632/) | | | +| 633 | [Sum of Square Numbers](https://leetcode.com/problems/sum-of-square-numbers/) | [C++](0501-1000/0633-Sum-of-Square-Numbers/cpp-0633/) | | | | +| | | | | | | +| 636 | [Exclusive Time of Functions](https://leetcode.com/problems/exclusive-time-of-functions/) | [无] | [C++](0501-1000/0636-Exclusive-Time-of-Functions/cpp-0636/) | | | +| 637 | [Average of Levels in Binary Tree](https://leetcode.com/problems/average-of-levels-in-binary-tree/description/) | [solution](https://leetcode.com/problems/average-of-levels-in-binary-tree/description/) | [C++](0501-1000/0637-Average-of-Levels-in-Binary-Tree/cpp-0637/) | | | +| 638 | [Shopping Offers](https://leetcode.com/problems/shopping-offers/) | [solution](https://leetcode.com/problems/shopping-offers/solution/) | [C++](0501-1000/0638-Shopping-Offers/cpp-0638/) | | | +| 639 | [Decode Ways II](https://leetcode.com/problems/decode-ways-ii/) | [solution](https://leetcode.com/problems/decode-ways-ii/solution/)
[缺:DP] | [C++](0501-1000/0639-Decode-Ways-II/cpp-0639/) | | | +| 640 | [Solve the Equation](https://leetcode.com/problems/solve-the-equation/) | [无] | [C++](0501-1000/0640-Solve-the-Equation/cpp-0640/) | | | +| | | | | | | +| 642 | [Design Search Autocomplete System](https://leetcode.com/problems/design-search-autocomplete-system/) | [无] | [C++](0501-1000/0642-Design-Search-Autocomplete-System/cpp-0642/) | | | +| 643 | [Maximum Average Subarray I](https://leetcode.com/problems/maximum-average-subarray-i/) | [solution](https://leetcode.com/problems/maximum-average-subarray-i/solution/) | [C++](0501-1000/0643-Maximum-Average-Subarray-I/cpp-0643/) | | | +| 644 | [Maximum Average Subarray II](https://leetcode.com/problems/maximum-average-subarray-ii/) | [solution](https://leetcode.com/problems/maximum-average-subarray-ii/solution/) | [C++](0501-1000/0644-Maximum-Average-Subarray-II/cpp-0644/) | | | +| 645 | [Set Mismatch](https://leetcode.com/problems/set-mismatch/) | [solution](https://leetcode.com/problems/set-mismatch/solution/)
[缺:空间 O(1) 解法] | [C++](0501-1000/0645-Set-Mismatch/cpp-0645/) | | | +| 646 | [Maximum Length of Pair Chain](https://leetcode.com/problems/maximum-length-of-pair-chain/) | [solution](https://leetcode.com/problems/maximum-length-of-pair-chain/solution/) | [C++](0501-1000/0646-Maximum-Length-of-Pair-Chain/cpp-0646/) | | | +| 647 | [Palindromic Substrings](https://leetcode.com/problems/palindromic-substrings/) | [solution](https://leetcode.com/problems/palindromic-substrings/solution/) | [C++](0501-1000/0647-Palindromic-Substrings/cpp-0647/) | | | +| 648 | [Replace Words](https://leetcode.com/problems/replace-words/description/) | [无] | [C++](0501-1000/0648-Replace-Words/cpp-0648/) | | | +| 649 | [Dota2 Senate](https://leetcode.com/problems/dota2-senate/) | [solution](https://leetcode.com/problems/dota2-senate/solution/)
[缺:队列] | [C++](0501-1000/0649-Dota2-Senate/cpp-0649/) | | | +| 650 | [2 Keys Keyboard](https://leetcode.com/problems/2-keys-keyboard/) | [solution](https://leetcode.com/problems/2-keys-keyboard/solution/) | [C++](0501-1000/0650-2-Keys-Keyboard/cpp-0650/) | | | +| | | | | | | +| 652 | [Find Duplicate Subtrees](https://leetcode.com/problems/find-duplicate-subtrees/description/) | [solution](https://leetcode.com/problems/find-duplicate-subtrees/solution/) | [C++](0501-1000/0652-Find-Duplicate-Subtrees/cpp-0652/) | | | +| 653 | [Two Sum IV - Input is a BST](https://leetcode.com/problems/two-sum-iv-input-is-a-bst/) | [无] | [C++](0501-1000/0653-Two-Sum-IV-Input-is-a-BST/cpp-0653/) | | | +| 654 | [Maximum Binary Tree](https://leetcode.com/problems/maximum-binary-tree/) | [solution](https://leetcode.com/problems/maximum-binary-tree/solution/) | [C++](0501-1000/0654-Maximum-Binary-Tree/cpp-0654/) | | | +| 655 | |[Print Binary Tree](https://leetcode.com/problems/print-binary-tree/) | [无] | [C++](0501-1000/0655-Print-Binary-Tree/cpp-0655/) | | +| | | | | | | +| 658 | [Find K Closest Elements](https://leetcode.com/problems/find-k-closest-elements/) | [solution](https://leetcode.com/problems/find-k-closest-elements/solution/)
[缺:二分] | [C++](0501-1000/0658-Find-K-Closest-Elements/cpp-0658/) | | | +| 659 | [Split Array into Consecutive Subsequences](https://leetcode.com/problems/split-array-into-consecutive-subsequences/) | [solution](https://leetcode.com/problems/split-array-into-consecutive-subsequences/solution/) | [C++](0501-1000/0659-Split-Array-into-Consecutive-Subsequences/cpp-0659/) | | | +| | | | | | | +| 661 | [Image Smoother](https://leetcode.com/problems/image-smoother/) | [无] | [C++](0501-1000/0658-Image-Smoother/cpp-0658/) | | | +| 662 | [Maximum Width of Binary Tree](https://leetcode.com/problems/maximum-width-of-binary-tree/) | [solution](https://leetcode.com/problems/maximum-width-of-binary-tree/solution/) | [C++](0501-1000/0662-Maximum-Width-of-Binary-Tree/cpp-0662/) | | | +| | | | | | | +| 664 | [Strange Printer](https://leetcode.com/problems/strange-printer/) | [solution](https://leetcode.com/problems/strange-printer/) | [C++](0501-1000/0664-Strange-Printer/cpp-0664/) | | | +| 665 | [Non-decreasing Array](https://leetcode.com/problems/non-decreasing-array/) | [solution](https://leetcode.com/problems/non-decreasing-array/solution/) | [C++](0501-1000/0665-Non-decreasing-Array/cpp-0665/) | | | +| 666 | [Path Sum IV](https://leetcode.com/problems/path-sum-iv/) | [solution](https://leetcode.com/problems/path-sum-iv/solution/) | [C++](0501-1000/0666-Path-Sum-IV/cpp-0666/) | | | +| 667 | [Beautiful Arrangement II](https://leetcode.com/problems/beautiful-arrangement-ii/) | [solution](https://leetcode.com/problems/beautiful-arrangement-ii/solution/) | [C++](0501-1000/0667-Beautiful-Arrangement-II/ccp-0667/) | | | +| 668 | [Kth Smallest Number in Multiplication Table](https://leetcode.com/problems/kth-smallest-number-in-multiplication-table/) | [solution](https://leetcode.com/problems/kth-smallest-number-in-multiplication-table/) | [C++](0501-1000/0668-Kth-Smallest-Number-in-Multiplication-Table/cpp-0668/) | | | +| 669 | [Trim a Binary Search Tree](https://leetcode.com/problems/trim-a-binary-search-tree/) | [solution](https://leetcode.com/problems/trim-a-binary-search-tree/solution/) | [C++](0501-1000/0669-Trim-a-Binary-Search-Tree/cpp-0669/) | | | +| 670 | [Maximum Swap](https://leetcode.com/problems/maximum-swap/) | [无] | [C++](0501-1000/0670-Maximum-Swap/cpp-0670/) | | | +| 671 | [Second Minimum Node In a Binary Tree](https://leetcode.com/problems/second-minimum-node-in-a-binary-tree/) | [solution](https://leetcode.com/problems/second-minimum-node-in-a-binary-tree/solution/) | [C++](0501-1000/0671-Second-Minimum-Node-In-a-Binary-Tree/cpp-0671/) | | | +| 672 | [Bulb Switcher II](https://leetcode.com/problems/bulb-switcher-ii/description/) | [solution](https://leetcode.com/problems/bulb-switcher-ii/solution/) | [C++](0501-1000/0672-Bulb-Switcher-II/cpp-0672/) | | | +| 673 | [Number of Longest Increasing Subsequence](https://leetcode.com/problems/number-of-longest-increasing-subsequence/description/) | [缺:BIT;线段树] | [C++](0501-1000/0673-Number-of-Longest-Increasing-Subsequence/cpp-0673/) | | | +| 674 | [Longest Continuous Increasing Subsequence](https://leetcode.com/problems/longest-continuous-increasing-subsequence/description/) | | [C++](0501-1000/0674-Longest-Continuous-Increasing-Subsequence/cpp-0674/) | | | +| 675 | [Cut Off Trees for Golf Event](https://leetcode.com/problems/cut-off-trees-for-golf-event/description/) | [缺:A*;Hadlock's Algo] | [C++](0501-1000/0675-Cut-Off-Trees-for-Golf-Event/cpp-0675/) | | | +| 676 | [Implement Magic Dictionary](https://leetcode.com/problems/implement-magic-dictionary/description/) | [solution](https://leetcode.com/problems/implement-magic-dictionary/solution/) | [C++](0501-1000/0676-Implement-Magic-Dictionary/cpp-0676/) | | | +| 677 | [Map Sum Pairs](https://leetcode.com/problems/map-sum-pairs/description/) | [solution](https://leetcode.com/problems/map-sum-pairs/solution/) | [C++](0501-1000/0677-Map-Sum-Pairs/cpp-0677/) | | | +| 678 | [Valid Parenthesis String](https://leetcode.com/problems/valid-parenthesis-string/) | [solution](https://leetcode.com/problems/valid-parenthesis-string/solution/) | [C++](0501-1000/0678-Valid-Parenthesis-String/cpp-0678/) | | | +| 679 | [24 Game](https://leetcode.com/problems/24-game/) | [solution](https://leetcode.com/problems/24-game/) | [C++](0501-1000/0679-24-Game/cpp-0679/) | | | +| 680 | [Valid Palindrome II](https://leetcode.com/problems/valid-palindrome-ii/) | [无] | [C++](0501-1000/0680-Valid-Palindrome-II/cpp-0680/) | | | +| | | | | | | +| 682 | [Baseball Game](https://leetcode.com/problems/baseball-game/) | [solution](https://leetcode.com/problems/baseball-game/solution/) | [C++](0501-1000/0682-Baseball-Game/cpp-0682/) | | | +| | | | | | | +| 684 | [Redundant Connection](https://leetcode.com/problems/redundant-connection/description/) | [solution](https://leetcode.com/problems/redundant-connection/solution/) | [C++](0501-1000/0684-Redundant-Connection/cpp-0684/) | | | +| 685 | [Redundant Connection II](https://leetcode.com/problems/redundant-connection-ii/description/) | [solution](https://leetcode.com/problems/redundant-connection-ii/solution/) | [C++](0501-1000/0685-Redundant-Connection-II/cpp-0685/) | | | +| 686 | [Repeated String Match](https://leetcode.com/problems/repeated-string-match/) |[无] | [C++](0501-1000/0686-Repeated-String-Match/cpp-0686/) | | | +| 687 | [Longest Univalue Path](https://leetcode.com/problems/longest-univalue-path/) | [solution](https://leetcode.com/problems/longest-univalue-path/solution/) | [C++](0501-1000/0687-Longest-Univalue-Path/cpp-0687/) | | | +| 688 | [Knight Probability in Chessboard](https://leetcode.com/problems/knight-probability-in-chessboard/) | [solution](https://leetcode.com/problems/knight-probability-in-chessboard/solution/) | [C++](0501-1000/0688-Knight-Probability-in-Chessboard/cpp-0688/) | | | +| 689 | [Maximum Sum of 3 Non-Overlapping Subarrays](https://leetcode.com/problems/maximum-sum-of-3-non-overlapping-subarrays/) | [solution](https://leetcode.com/problems/maximum-sum-of-3-non-overlapping-subarrays/solution/) | [C++](0501-1000/0689-Maximum-Sum-of-3-Non-Overlapping-Subarrays/cpp-0689/)| | | +| 690 | [Employee Importance](https://leetcode.com/problems/employee-importance/description/) | [solution](https://leetcode.com/problems/employee-importance/solution/) | [C++](0501-1000/0690-Employee-Importance/cpp-0690/) | | | +| 691 | [Stickers to Spell Word](https://leetcode.com/problems/stickers-to-spell-word/) | [无] | [C++](0501-1000/0691-Stickers-to-Spell-Word/cpp-0691/) | | | +| 692 | [Top K Frequent Words](https://leetcode.com/problems/top-k-frequent-words/description/) | [solution](https://leetcode.com/problems/top-k-frequent-words/solution/) | [C++](0501-1000/0692-Top-K-Frequent-Words/cpp-0692/) | | | +| 693 | [Binary Number with Alternating Bits](https://leetcode.com/problems/binary-number-with-alternating-bits/) | [无] | [C++](0501-1000/0693-Binary-Number-with-Alternating-Bits/cpp-0693/) | | | +| 694 | [Number of Distinct Islands](https://leetcode.com/problems/number-of-distinct-islands/description/) | [review: hash的方式] | [C++](0501-1000/0694-Number-of-Distinct-Islands/cpp-0694/) | | | +| 695 | [Max-Area-of-Island](https://leetcode.com/problems/max-area-of-island/description/) | | [C++](0501-1000/0695-Max-Area-of-Island/cpp-0695) | | | +| 696 | [Count Binary Substrings](https://leetcode.com/problems/count-binary-substrings/description/) | | [C++](0501-1000/0696-Count-Binary-Substrings/cpp-0696/) | | | +| 697 | [Degree of an Array](https://leetcode.com/problems/degree-of-an-array/description/) | | [C++](0501-1000/0697-Degree-of-an-Array/cpp-0697/) | | | +| 698 | [Partition to K Equal Sum Subsets](https://leetcode.com/problems/partition-to-k-equal-sum-subsets/description/) | | [C++](0501-1000/0698-Partition-to-K-Equal-Sum-Subsets/cpp-0698/) | [Java](0501-1000/0698-Partition-to-K-Equal-Sum-Subsets/java-0698/src/) | | +| 699 | [Falling Squares](https://leetcode.com/contest/leetcode-weekly-contest-54/problems/falling-squares/) | [缺:线段树;块状链表] | [C++](0501-1000/0699-Falling-Squares/cpp-0699/) | | | +| 700 | [Search in a Binary Search Tree](https://leetcode.com/problems/search-in-a-binary-search-tree/) | [solution](https://leetcode.com/problems/search-in-a-binary-search-tree/solution/) | [C++](0501-1000/0700-Search-in-a-Binary-Search-Tree/cpp-0700/) | | | +| 701 | [Insert into a Binary Search Tree](https://leetcode.com/problems/insert-into-a-binary-search-tree/) | [solution](https://leetcode.com/problems/insert-into-a-binary-search-tree/solution/) | [C++](0501-1000/0701-Insert-into-a-Binary-Search-Tree/cpp-0701/) | | | +| | | | | | | +| 703 | [Kth Largest Element in a Stream](https://leetcode.com/problems/kth-largest-element-in-a-stream/) | [无] | [C++](0501-1000/0703-Kth-Largest-Element-in-a-Stream/cpp-0703/) | | | +| 704 | [Binary Search](https://leetcode.com/problems/binary-search/description/) | [solution](https://leetcode.com/problems/binary-search/solution/) | [C++](0501-1000/0704-Binary-Search/cpp-0704/) | | | +| 705 | [Design HashSet](https://leetcode.com/problems/design-hashset/description/) | [无] | [C++](0501-1000/0705-Design-HashSet/cpp-0705/) | | | +| 706 | [Design HashMap](https://leetcode.com/problems/design-hashmap/description/) | [无] | [C++](0501-1000/0706-Design-HashMap/cpp-0706/) | | | +| 707 | [Design Linked List](https://leetcode.com/problems/design-linked-list/description/) | [无] | [C++](0501-1000/0707-Design-Linked-List/cpp-0707/) | | | +| 708 | [Insert into a Cyclic Sorted List](https://leetcode.com/problems/insert-into-a-cyclic-sorted-list/description/) | [无] | [C++](0501-1000/0708-Insert-into-a-Cyclic-Sorted-List/cpp-0708/) | | | +| 709 | [To Lower Case](https://leetcode.com/problems/to-lower-case/) | [solution](https://leetcode.com/problems/to-lower-case/solution/) | [C++](0501-1000/0709-To-Lower-Case/cpp-0709/) | | | +| 710 | [Random Pick with Blacklist](https://leetcode.com/problems/random-pick-with-blacklist/description/) | [solution](https://leetcode.com/problems/random-pick-with-blacklist/solution/) | [C++](0501-1000/0710-Random-Pick-with-Blacklist/cpp-0710/) | | | +| 711 | [Number of Distinct Islands II](https://leetcode.com/problems/number-of-distinct-islands-ii/description/) | [review: hash的方式] | [C++](0501-1000/0711-Number-of-Distinct-Islands-II/cpp-0711/) | | | +| 712 | [Minimum ASCII Delete Sum for Two Strings](https://leetcode.com/problems/minimum-ascii-delete-sum-for-two-strings/description/) | | [C++](0501-1000/0712-Minimum-ASCII-Delete-Sum-for-Two-Strings/cpp-0712/) | | | +| 713 | [Subarray Product Less Than K](https://leetcode.com/problems/subarray-product-less-than-k/description/) | | [C++](0501-1000/0713-Subarray-Product-Less-Than-K/cpp-0713/) | | | +| 714 | [Best Time to Buy and Sell Stock with Transaction Fee](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/description/) | | [C++](0501-1000/0714-Best-Time-to-Buy-and-Sell-Stock-with-Transaction-Fee/cpp-0714/) | | | +| 715 | [Range Module](https://leetcode.com/problems/range-module/description/) | [缺:set查找] | [C++](0501-1000/0715-Range-Module/cpp-0715/) | | | +| 716 | [Max Stack](https://leetcode.com/problems/max-stack/description/) | [solution](https://leetcode.com/problems/max-stack/solution/) | [C++](0501-1000/0716-Max-Stack/cpp-0716/) | | | +| 717 | [1-bit and 2-bit Characters](https://leetcode.com/problems/1-bit-and-2-bit-characters/description/) | | [C++](0501-1000/0717-1-bit-and-2-bit-Characters/cpp-0717/) | | | +| 718 | [Maximum Length of Repeated Subarray](https://leetcode.com/problems/maximum-length-of-repeated-subarray/description/) | [缺:Rolling Hash] | [C++](0501-1000/0718-Maximum-Length-of-Repeated-Subarray/cpp-0718/) | | | +| 719 | [Find K-th Smallest Pair Distance](https://leetcode.com/problems/find-k-th-smallest-pair-distance/description/) | [solution](https://leetcode.com/problems/find-k-th-smallest-pair-distance/solution/) | [C++](0501-1000/0719-Find-K-th-Smallest-Pair-Distance/cpp-0719/) | | | +| 720 | [Longest Word in Dictionary](https://leetcode.com/problems/longest-word-in-dictionary/description/) | [solution](https://leetcode.com/problems/longest-word-in-dictionary/solution/) | [C++](0501-1000/0720-Longest-Word-in-Dictionary/cpp-0720/) | | | +| 721 | [Accounts Merge](https://leetcode.com/problems/accounts-merge/description/) | [solution](https://leetcode.com/problems/accounts-merge/solution/) | [C++](0501-1000/0721-Accounts-Merge/cpp-0721/) | | | +| 722 | [Remove Comments](https://leetcode.com/problems/remove-comments/description/) | [solution](https://leetcode.com/problems/remove-comments/solution/) | [C++](0501-1000/0722-Remove-Comments/cpp-0722/) | | | +| 723 | [Candy Crush](https://leetcode.com/problems/candy-crush/description/) | [solution](https://leetcode.com/problems/candy-crush/solution/) | [C++](0501-1000/0723-Candy-Crush/cpp-0723/) | | | +| 724 | [Find Pivot Index](https://leetcode.com/problems/find-pivot-index/description/) | [solution](https://leetcode.com/problems/find-pivot-index/solution/) | [C++](0501-1000/0724-Find-Pivot-Index/cpp-0724/) | | | +| 725 | [Split Linked List in Parts](https://leetcode.com/problems/split-linked-list-in-parts/description/) | [solution](https://leetcode.com/problems/split-linked-list-in-parts/solution/) | [C++](0501-1000/0725-Split-Linked-List-in-Parts/cpp-0725/) | | | +| 726 | [Number of Atoms](https://leetcode.com/problems/number-of-atoms/) | [solution](https://leetcode.com/problems/number-of-atoms/solution/) | [C++](0501-1000/0726-Number-of-Atoms/cpp-0726/) | | | +| 727 | [Minimum Window Subsequence](https://leetcode.com/problems/minimum-window-subsequence/description/) | [solution](https://leetcode.com/problems/minimum-window-subsequence/solution/) | [C++](0501-1000/cpp-Minimum-Window-Subsequence/cpp-0727/) | | | +| 728 | [Self Dividing Numbers](https://leetcode.com/problems/self-dividing-numbers/description/) | [solution](https://leetcode.com/problems/self-dividing-numbers/solution/) | [C++](0501-1000/0728-Self-Dividing-Numbers/cpp-0728/) | | | +| 729 | [My Calendar I](https://leetcode.com/problems/my-calendar-i/description/) | [solution](https://leetcode.com/problems/my-calendar-i/solution/) | [C++](0501-1000/0729-My-Calendar-I/cpp-0729/) | | | +| 730 | [Count Different Palindromic Subsequences](https://leetcode.com/problems/count-different-palindromic-subsequences/) | [无] | [C++](0501-1000/0730-Count-Different-Palindromic-Subsequences/cpp-0730/) | | | +| 731 | [My Calendar II](https://leetcode.com/problems/my-calendar-ii/description/) | [solution](https://leetcode.com/problems/my-calendar-ii/solution/) | [C++](0501-1000/0731-My-Calendar-II/cpp-0731/) | | | +| 732 | [My Calendar III](https://leetcode.com/problems/my-calendar-iii/description/) | [solution](https://leetcode.com/problems/my-calendar-iii/solution/) | [C++](0501-1000/0732-My-Calendar-III/cpp-0732/) | | | +| 733 | [Flood Fill](https://leetcode.com/problems/flood-fill/description/) | [solution](https://leetcode.com/problems/flood-fill/solution/) | [C++](0501-1000/0733-Flood-Fill/cpp-0733/) | | | +| 734 | [Sentence Similarity](https://leetcode.com/problems/sentence-similarity/description/) | [solution](https://leetcode.com/problems/sentence-similarity/solution/) | [C++](0501-1000/0734-Sentence-Similarity/cpp-0734/) | | | +| 735 | [Asteroid Collision](https://leetcode.com/problems/asteroid-collision/description/) | [solution](https://leetcode.com/problems/asteroid-collision/solution/) | [C++](0501-1000/0735-Asteroid-Collision/cpp-0735/) | | | +| 736 | [Parse Lisp Expression](https://leetcode.com/problems/parse-lisp-expression/description/) | [solution](https://leetcode.com/problems/parse-lisp-expression/solution/) | [C++](0501-1000/0736-Parse-Lisp-Expression/cpp-0736/) | | | +| 737 | [Sentence Similarity II](https://leetcode.com/problems/sentence-similarity-ii/description/) | [solution](https://leetcode.com/problems/sentence-similarity-ii/solution/) | [C++](0501-1000/0737-Sentence-Similarity-II/cpp-0737/) | | | +| | | | | | | +| 739 | [Daily Temperatures](https://leetcode.com/problems/daily-temperatures/description/) | [solution](https://leetcode.com/problems/daily-temperatures/solution/) | [C++](0501-1000/0739-Daily-Temperatures/cpp-0739/) | | | +| 740 | [Delete and Earn](https://leetcode.com/problems/delete-and-earn/description/) | [solution](https://leetcode.com/problems/delete-and-earn/solution/) | [C++](0501-1000/0740-Delete-and-Earn/cpp-0740/) | | | +| 741 | [Cherry Pickup](https://leetcode.com/problems/cherry-pickup/description/) | [solution](https://leetcode.com/problems/cherry-pickup/solution/)
[缺:自底向上的动态规划] | [C++](0501-1000/0741-Cherry-Pickup/cpp-0741/) | | | +| | | | | | | +| 745 | [Prefix and Suffix Search](https://leetcode.com/problems/prefix-and-suffix-search/) | [solution](https://leetcode.com/problems/prefix-and-suffix-search/solution/) | [C++](0501-1000/0745-Prefix-and-Suffix-Search/cpp-0745/) | | | +| 746 | [Min Cost Climbing Stairs](https://leetcode.com/problems/min-cost-climbing-stairs/) | [solution](https://leetcode.com/problems/min-cost-climbing-stairs/solution/) | [C++](0501-1000/0746-Min-Cost-Climbing-Stairs/cpp-0746/) | | | +| 747 | [Largest Number At Least Twice of Others](https://leetcode.com/problems/largest-number-at-least-twice-of-others/description/) | [solution](https://leetcode.com/problems/largest-number-at-least-twice-of-others/solution/) | [C++](0501-1000/0747-Largest-Number-At-Least-Twice-of-Others/cpp-0747/) | | | +| | | | | | | +| 749 | [Contain Virus](https://leetcode.com/problems/contain-virus/) | [无] | [C++](0501-1000/0749-Contain-Virus/cpp-0749/)| | | +| | | | | | | +| 752 | [Open the Lock](https://leetcode.com/problems/open-the-lock/description/) | [solution](https://leetcode.com/problems/open-the-lock/solution/) | [C++](0501-1000/0752-Open-the-Lock/cpp-0752/) | | | +| 753 | [Cracking the Safe](https://leetcode.com/problems/cracking-the-safe/) | [无] | [C++](0501-1000/0753-Cracking-the-Safe/cpp-0753/) | | | +| 754 | [Reach a Number](https://leetcode.com/problems/reach-a-number/) | [Solution](https://leetcode.com/problems/reach-a-number/solution/) | [C++](0501-1000/0754-Reach-a-Number/cpp-0754/) | | | +| | | | | | | +| 757 | [Set Intersection Size At Least Two](https://leetcode.com/problems/set-intersection-size-at-least-two/) | [无] | [C++](0501-1000/0757-Set-Intersection-Size-At-Least-Two/cpp-0757/) | | | +| | | | | | | +| 761 | [Special Binary String](https://leetcode.com/problems/special-binary-string/) | [solution](https://leetcode.com/problems/special-binary-string/solution/) | [C++](0501-1000/0761-Special-Binary-String/cpp-0761/) | | | +| 762 | [Prime Number of Set Bits in Binary Representation](https://leetcode.com/problems/prime-number-of-set-bits-in-binary-representation/) | [无] | [C++](0501-1000/0762-Prime-Number-of-Set-Bits-in-Binary-Representation/cpp-0762/) | | | +| 763 | [Partition Labels](https://leetcode.com/problems/partition-labels/) | [无] | [C++](0501-1000/0763-Partition-Labels/cpp-0763/) | | | +| 764 | [Largest Plus Sign](https://leetcode.com/problems/largest-plus-sign/) | [C++](0501-1000/0764-Largest-Plus-Sign/cpp-0764/) | | | | +| 765 | [Couples Holding Hands](https://leetcode.com/problems/couples-holding-hands/description/) | [solution](https://leetcode.com/problems/couples-holding-hands/solution/) | [C++](0501-1000/0765-Couples-Holding-Hands/cpp-0765/) | | | +| 766 | [Toeplitz Matrix](https://leetcode.com/problems/toeplitz-matrix/description/) | [solution](https://leetcode.com/problems/toeplitz-matrix/solution/) | [C++](0501-1000/0766-Toeplitz-Matrix/cpp-0766/) | | | +| | | | | | | +| 771 | [Jewels and Stones](https://leetcode.com/problems/jewels-and-stones/description/) | [solution](https://leetcode.com/problems/jewels-and-stones/solution/) | [C++](0501-1000/0771-Jewels-and-Stones/cpp-0771/) | | | +| 772 | [Basic Calculator III](https://leetcode.com/problems/basic-calculator-iii/description/) | [无] | [C++](0501-1000/0772-Basic-Calculator-III/cpp-0772/) | | | +| | | | | | | +| 774 | [Minimize Max Distance to Gas Station](https://leetcode.com/problems/minimize-max-distance-to-gas-station/) | [solution](https://leetcode.com/problems/minimize-max-distance-to-gas-station/) | [C++](0501-1000/0774-Minimize-Max-Distance-to-Gas-Station/cpp-0774/) | | | +| 775 | [Global and Local Inversions](https://leetcode.com/problems/global-and-local-inversions/) | [C++](0501-1000/0775-Global-and-Local-Inversions/cpp-0775/) | | | | +| | | | | | | +| 779 | [K-th Symbol in Grammar](https://leetcode.com/problems/k-th-symbol-in-grammar/) | [无] | [C++](0501-1000/0779-K-th-Symbol-in-Grammar/cpp-0779/) | | | +| 780 | [Reaching Points](https://leetcode.com/problems/reaching-points/description/) | [solution](https://leetcode.com/problems/reaching-points/solution/) | [C++](0501-1000/0780-Reaching-Points/cpp-0780/) | | | +| 781 | [Rabbits in Forest](https://leetcode.com/problems/rabbits-in-forest/description/) | [solution](https://leetcode.com/problems/rabbits-in-forest/solution/) | [C++](0501-1000/0781-Rabbits-in-Forest/cpp-0781/) | | | +| 782 | [Transform to Chessboard](https://leetcode.com/problems/transform-to-chessboard/) | [solution](https://leetcode.com/problems/transform-to-chessboard/solution/) | [C++](0501-1000/0782-Transform-to-Chessboard/cpp-0782/) | | | +| 783 | [Minimum Distance Between BST Nodes](https://leetcode.com/problems/minimum-distance-between-bst-nodes/description/) | [solution](https://leetcode.com/problems/minimum-distance-between-bst-nodes/solution/) | [C++](0501-1000/0783-Minimum-Distance-Between-BST-Nodes/cpp-0783/) | | | +| 784 | [Letter Case Permutation](https://leetcode.com/problems/letter-case-permutation/description/) | [solution](https://leetcode.com/problems/letter-case-permutation/solution/) | [C++](0501-1000/0784-Letter-Case-Permutation/cpp-0784/) | | | +| 785 | [Is Graph Bipartite?](https://leetcode.com/problems/is-graph-bipartite/description/) | [solution](https://leetcode.com/problems/is-graph-bipartite/description/) | [C++](0501-1000/0785-Is-Graph-Bipartite/cpp-0785/) | | | +| 786 | [K-th Smallest Prime Fraction](https://leetcode.com/problems/k-th-smallest-prime-fraction/description/) | [solution](https://leetcode.com/problems/k-th-smallest-prime-fraction/solution/)
[缺:分治算法] | [C++](0501-1000/0786-K-th-Smallest-Prime-Fraction/cpp-0786/) | | | +| 787 | [Cheapest Flights Within K Stops](https://leetcode.com/problems/cheapest-flights-within-k-stops/description/) | [solution](https://leetcode.com/problems/cheapest-flights-within-k-stops/solution/)
[缺:使用Heap] | [C++](0501-1000/0787-Cheapest-Flights-Within-K-Stops/cpp-0787/) | | | +| 788 | [Rotated Digits](https://leetcode.com/problems/rotated-digits/description/) | [solution](https://leetcode.com/problems/rotated-digits/solution/) | [C++](0501-1000/0788-Rotated-Digits/cpp-0788/) | | | +| 789 | [Escape The Ghosts](https://leetcode.com/problems/escape-the-ghosts/description/) | [solution](https://leetcode.com/problems/escape-the-ghosts/solution/) | [C++](0501-1000/0789-Escape-The-Ghosts/cpp-0789/) | | | +| 790 | [Domino and Tromino Tiling](https://leetcode.com/problems/domino-and-tromino-tiling/description/) | [solution](https://leetcode.com/problems/domino-and-tromino-tiling/solution/)
[缺:转移矩阵求幂解法] | [C++](0501-1000/0790-Domino-and-Tromino-Tiling/cpp-0790/) | | | +| 791 | [Custom Sort String](https://leetcode.com/problems/custom-sort-string/description/) | [solution](https://leetcode.com/problems/custom-sort-string/solution/) | [C++](0501-1000/0791-Custom-Sort-String/cpp-0791/) | | | +| 792 | [Number of Matching Subsequences](https://leetcode.com/problems/number-of-matching-subsequences/description/) | [solution](https://leetcode.com/problems/number-of-matching-subsequences/solution/) | [C++](0501-1000/0792-Number-of-Matching-Subsequences/cpp-0792/) | | | +| 793 | [Preimage Size of Factorial Zeroes Function](https://leetcode.com/problems/preimage-size-of-factorial-zeroes-function/description/) | [solution](https://leetcode.com/problems/preimage-size-of-factorial-zeroes-function/solution/) | [C++](0501-1000/0793-Preimage-Size-of-Factorial-Zeroes-Function/cpp-0793/) | | | +| 794 | [Valid Tic-Tac-Toe State](https://leetcode.com/problems/valid-tic-tac-toe-state/description/) | [solution](https://leetcode.com/problems/valid-tic-tac-toe-state/solution/) | [C++](0501-1000/0794-Valid-Tic-Tac-Toe-State/cpp-0794/) | | | +| 795 | [Number of Subarrays with Bounded Maximum](https://leetcode.com/problems/number-of-subarrays-with-bounded-maximum/description/) | [solution](https://leetcode.com/problems/number-of-subarrays-with-bounded-maximum/solution/) | [C++](0501-1000/0795-Number-of-Subarrays-with-Bounded-Maximum/cpp-0795/) | | | +| 796 | [Rotate String](https://leetcode.com/problems/rotate-string/description/) | [solution](https://leetcode.com/problems/rotate-string/solution/)
[缺:Rolling Hash] | [C++](0501-1000/0796-Rotate-String/cpp-0796/) | | | +| 797 | [All Paths From Source to Target](https://leetcode.com/problems/all-paths-from-source-to-target/description/) | [solution](https://leetcode.com/problems/all-paths-from-source-to-target/solution/) | [C++](0501-1000/0797-All-Paths-From-Source-to-Target/cpp-0797/) | | | +| 798 | [Smallest Rotation with Highest Score](https://leetcode.com/problems/smallest-rotation-with-highest-score/) | [solution](https://leetcode.com/problems/smallest-rotation-with-highest-score/solution/)
[缺:O(n) 解法] | [C++](0501-1000/0798-Smallest-Rotation-with-Highest-Score/cpp-0798/) | | | +| 799 | [Champagne Tower](https://leetcode.com/problems/champagne-tower/description/) | [solution](https://leetcode.com/problems/champagne-tower/solution/) | [C++](0501-1000/0799-Champagne-Tower/cpp-0799/) | | | +| 800 | [Similar RGB Color](https://leetcode.com/problems/similar-rgb-color/description/) | [solution](https://leetcode.com/problems/similar-rgb-color/solution/) | [C++](0501-1000/0800-Similar-RGB-Color/cpp-0800/) | | | +| | | | | | | +| 802 | [Find Eventual Safe States](https://leetcode.com/problems/find-eventual-safe-states/) | [solution](https://leetcode.com/problems/find-eventual-safe-states/solution/) | [C++](0501-1000/0802-Find-Eventual-Safe-States/cpp-0802/) | | | +| 803 | [Bricks Falling When Hit](https://leetcode.com/problems/bricks-falling-when-hit/) | [无] | [C++](0501-1000/0803-Bricks-Falling-When-Hit/cpp-0803/) | | | +| 804 | [Unique Morse Code Words](https://leetcode.com/problems/unique-morse-code-words/description/) | [solution](https://leetcode.com/problems/unique-morse-code-words/solution/) | [C++](0501-1000/0804-Unique-Morse-Code-Words/cpp-0804/) | | | +| 805 | [Split Array With Same Average](https://leetcode.com/problems/split-array-with-same-average/description/) | [solution](https://leetcode.com/problems/split-array-with-same-average/solution/) | [C++](0501-1000/0805-Split-Array-With-Same-Average/cpp-0805/) | | | +| 806 | [Number of Lines To Write String](https://leetcode.com/problems/number-of-lines-to-write-string/description/) | [solution](https://leetcode.com/problems/number-of-lines-to-write-string/solution/) | [C++](0501-1000/0806-Number-of-Lines-To-Write-String/cpp-0806/) | | | | 807 | [Max Increase to Keep City Skyline](https://leetcode.com/problems/max-increase-to-keep-city-skyline/description/) | [solution](https://leetcode.com/problems/max-increase-to-keep-city-skyline/solution/) | [C++](0807-Max-Increase-to-Keep-City-Skyline/cpp-0807/) | | | | | | | | | | -| 809 | [Expressive Words](https://leetcode.com/problems/expressive-words/description/) | [solution](https://leetcode.com/problems/expressive-words/solution/) | [C++](0809-Expressive-Words/cpp-0809/) | | | +| 809 | [Expressive Words](https://leetcode.com/problems/expressive-words/description/) | [solution](https://leetcode.com/problems/expressive-words/solution/) | [C++](0501-1000/0809-Expressive-Words/cpp-0809/) | | | +| 810 | [Chalkboard XOR Game](https://leetcode.com/problems/chalkboard-xor-game/) | [solution](https://leetcode.com/problems/chalkboard-xor-game/solution/) | [C++](0501-1000/0810-Chalkboard-XOR-Game/cpp-0810/) | | | +| 811 | [Subdomain Visit Count](https://leetcode.com/problems/subdomain-visit-count/description/) | [solution](https://leetcode.com/problems/subdomain-visit-count/solution/) | [C++](0501-1000/0811-Subdomain-Visit-Count/cpp-0811/) | | | +| | | | | | | +| 813 | [Largest Sum of Averages](https://leetcode.com/problems/largest-sum-of-averages/description/) | [solution](https://leetcode.com/problems/largest-sum-of-averages/solutions/) | [C++](0501-1000/0813-Largest-Sum-of-Averages/cpp-0813/) | | | +| 814 | [Binary Tree Pruning](https://leetcode.com/problems/binary-tree-pruning/) | [solution](https://leetcode.com/problems/binary-tree-pruning/solution/) | [C++](0501-1000/0814-Binary-Tree-Pruning/cpp-0814/) | | | +| 815 | [Bus Routes](https://leetcode.com/problems/bus-routes/) | [solution](https://leetcode.com/problems/bus-routes/solution/) | [C++](0501-1000/0815-Bus-Routes/cpp-0815/) | | | +| | | | | | | +| 817 | [Linked List Components](https://leetcode.com/problems/linked-list-components/description/) | [solution](https://leetcode.com/problems/linked-list-components/solution/) | [C++](0501-1000/0817-Linked-List-Components/cpp-0817/) | | | +| | | | | | | +| 819 | [Most Common Word](https://leetcode.com/problems/most-common-word/description/) | [solution](https://leetcode.com/problems/most-common-word/solution/) | [C++](0501-1000/0819-Most-Common-Word/cpp-0819/) | | | +| | | | | | | +| 822 | [Card Flipping Game](https://leetcode.com/problems/card-flipping-game/description/) | [无] | [C++](0501-1000/0822-Card-Flipping-Game/cpp-0822/) | | | +| 823 | [Binary Trees With Factors](https://leetcode.com/problems/binary-trees-with-factors/) | [solution](https://leetcode.com/problems/binary-trees-with-factors/solution/) | [C++](0501-1000/0823-Binary-Trees-With-Factors/cpp-0823/) | | | +| 824 | [Goat Latin](https://leetcode.com/problems/goat-latin/) | [无] | [C++](0501-1000/0824-Goat-Latin/cpp-0824/) | | | +| 825 | [Friends Of Appropriate Ages](https://leetcode.com/problems/friends-of-appropriate-ages/) | [无] | [C++](0501-1000/0825-Friends-Of-Appropriate-Ages/cpp-0825/) | | | +| | | | | | | +| 827 | [Making A Large Island](https://leetcode.com/problems/making-a-large-island/) | [无] | [C++](0501-1000/0827-Making-A-Large-Island/cpp-0827/) | | | +| 828 | [Count Unique Characters of All Substrings of a Given String](https://leetcode.com/problems/count-unique-characters-of-all-substrings-of-a-given-string/) | [无] | [C++](0501-1000/0828-Count-Unique-Characters-of-All-Substrings-of-a-Given-String/cpp-0828/) | | | +| 829 | [Consecutive Numbers Sum](https://leetcode.com/problems/consecutive-numbers-sum/) | [无] | [C++](0501-1000/0829-Consecutive-Numbers-Sum/cpp-0829/) | | | +| 830 | [Positions of Large Groups](https://leetcode.com/problems/positions-of-large-groups/) | [solution](https://leetcode.com/problems/positions-of-large-groups/solution/) | [C++](0501-1000/0830-Positions-of-Large-Groups/cpp-0830/) | | | +| 831 | [Masking Personal Information](https://leetcode.com/problems/masking-personal-information/) | [无] | [C++](0501-1000/0831-Masking-Personal-Information/cpp-0831/) | | | +| 832 | [Flipping an Image](https://leetcode.com/problems/flipping-an-image/) | [solution](https://leetcode.com/problems/flipping-an-image/solution/) | [C++](0501-1000/0832-Flipping-an-Image/cpp-0832/) | | | +| 833 | [Find And Replace in String](https://leetcode.com/problems/find-and-replace-in-string/) | [无] | [C++](https://leetcode.com/problems/find-and-replace-in-string/) | | | +| 834 | [Sum of Distances in Tree](https://leetcode.com/problems/sum-of-distances-in-tree/) | [solution](https://leetcode.com/problems/sum-of-distances-in-tree/solution/) | [C++](0501-1000/0834-Sum-of-Distances-in-Tree/cpp-0834/) | | | +| 835 | [Image Overlap](https://leetcode.com/problems/image-overlap/) | [无] | [C++](0501-1000/0835-Image-Overlap/cpp-0835/) | | | +| | | | | | | +| 837 | [New 21 Game](https://leetcode.com/problems/new-21-game/) | [无] | [C++](0501-1000/0837-New-21-Game/cpp-0837/) | | | +| 838 | [Push Dominoes](https://leetcode.com/problems/push-dominoes/) | [solution](https://leetcode.com/problems/push-dominoes/solution/) | [C++](0501-1000/0838-Push-Dominoes/cpp-0838/) | | | +| 839 | [Similar String Groups](https://leetcode.com/problems/similar-string-groups/) | [solution](https://leetcode.com/problems/similar-string-groups/solution/) | +[C++](0501-1000/0839-Similar-String-Groups/cpp-0839/) | | | +| | | | | | | +| 841 | [Keys and Rooms](https://leetcode.com/problems/keys-and-rooms/description/) | [solution](https://leetcode.com/problems/keys-and-rooms/solution/) | [C++](0501-1000/0841-Keys-and-Rooms/cpp-0841/) | | | +| 842 | [Split Array into Fibonacci Sequence](https://leetcode.com/problems/split-array-into-fibonacci-sequence/) | [solution](https://leetcode.com/problems/split-array-into-fibonacci-sequence/solution/) | [C++](0501-1000/0842-Split-Array-into-Fibonacci-Sequence/cpp-0842/) | | | +| | | | | | | +| 844 | [Backspace String Compare](https://leetcode.com/problems/backspace-string-compare/) | [solution](https://leetcode.com/problems/backspace-string-compare/solution/) | [C++](0501-1000/0844-Backspace-String-Compare/cpp-0844/) | | | +| | | | | | | +| 846 | [Hand of Straights](https://leetcode.com/problems/hand-of-straights/) | [无] | [C++](0501-1000/0846-Hand-of-Straights/cpp-0846/) | | | +| 847 | [Shortest Path Visiting All Nodes](https://leetcode.com/problems/shortest-path-visiting-all-nodes/) | [无] | [C++](0501-1000/0847-Shortest-Path-Visiting-All-Nodes/cpp-0847/) | | | +| 848 | [Shifting Letters](https://leetcode.com/problems/shifting-letters/) | [无] | [C++](0501-1000/0848-Shifting-Letters/cpp-0848/) | | | +| 849 | [Maximize Distance to Closest Person](https://leetcode.com/problems/maximize-distance-to-closest-person/) | [无] | [C++](0501-1000/0849-Maximize-Distance-to-Closest-Person/cpp-0849/) | | | +| 850 | [Rectangle Area II](https://leetcode.com/problems/rectangle-area-ii/) | [solution](https://leetcode.com/problems/rectangle-area-ii/solution/) | [C++](0501-1000/0850-Rectangle-Area-II/cpp-0850/) | | | +| 851 | [Loud and Rich](https://leetcode.com/problems/loud-and-rich/) | [solution](https://leetcode.com/problems/loud-and-rich/solution/) | [C++](0501-1000/0851-Loud-and-Rich/cpp-0851/) | | | +| 852 | [Peak Index in a Mountain Array](https://leetcode.com/problems/peak-index-in-a-mountain-array/description/) | [solution](https://leetcode.com/problems/peak-index-in-a-mountain-array/solution/) | [C++](0501-1000/0852-Peak-Index-in-a-Mountain-Array/cpp-0852/) | | | +| 853 | [Car Fleet](https://leetcode.com/problems/car-fleet/description/) | [solution](https://leetcode.com/problems/car-fleet/solution/) | [C++](0501-1000/0853-Car-Fleet/cpp-0853/) | | | +| 854 | [K-Similar Strings](https://leetcode.com/problems/k-similar-strings/description/) | [solution](https://leetcode.com/problems/k-similar-strings/solution/) | [C++](0501-1000/0854-K-Similar-Strings/cpp-0854/) | | | +| 855 | [Exam Room](https://leetcode.com/problems/exam-room/description/) | [solution](https://leetcode.com/problems/exam-room/solution/) | [C++](0501-1000/0855-Exam-Room/cpp-0855/) | | | +| 856 | [Score of Parentheses](https://leetcode.com/problems/score-of-parentheses/description/) | [solution](https://leetcode.com/problems/score-of-parentheses/solution/) | [C++](0501-1000/0856-Score-of-Parentheses/cpp-0856/) | | | +| 857 | [Minimum Cost to Hire K Workers](https://leetcode.com/problems/minimum-cost-to-hire-k-workers/description/) | [solution](https://leetcode.com/problems/minimum-cost-to-hire-k-workers/solution/)
[缺:二分搜索] | [C++](0501-1000/0857-Minimum-Cost-to-Hire-K-Workers/cpp-0857/) | | | +| 858 | [Mirror Reflection](https://leetcode.com/problems/mirror-reflection/description/) | [solution](https://leetcode.com/problems/mirror-reflection/solution/) | [C++](0501-1000/0858-Mirror-Reflection/cpp-0858/) | | | +| 859 | [Buddy Strings](https://leetcode.com/problems/buddy-strings/description/) | [solution](https://leetcode.com/problems/buddy-strings/solution/) | [C++](0501-1000/0859-Buddy-Strings/cpp-0859/) | | | +| 860 | [Lemonade Change](https://leetcode.com/problems/lemonade-change/description/) | [solution](https://leetcode.com/problems/lemonade-change/solution/) | [C++](0501-1000/0860-Lemonade-Change/cpp-0860/) | | | +| 861 | [Score After Flipping Matrix](https://leetcode.com/problems/score-after-flipping-matrix/description/) | [solution](https://leetcode.com/problems/score-after-flipping-matrix/solution/) | [C++](0501-1000/0861-Score-After-Flipping-Matrix/cpp-0861/) | | | +| | | | | | | +| 863 | [All Nodes Distance K in Binary Tree](https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/description/) | [solution](https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/solution/) | [C++](0501-1000/0863-All-Nodes-Distance-K-in-Binary-Tree/cpp-0863/) | | | +| 864 | [Shortest Path to Get All Keys](https://leetcode.com/problems/shortest-path-to-get-all-keys/description/) | [solution](https://leetcode.com/problems/shortest-path-to-get-all-keys/solution/)
[缺:Dijkstra] | [C++](0501-1000/0864-Shortest-Path-to-Get-All-Keys/cpp-0864/) | | | +| 865 | [Smallest Subtree with all the Deepest Nodes](https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/description/) | [solution](https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/solution/) | [C++](0501-1000/0865-Smallest-Subtree-with-all-the-Deepest-Nodes/cpp-0865/) | | | +| 866 | [Prime Palindrome](https://leetcode.com/problems/prime-palindrome/description/) | [solution](https://leetcode.com/problems/prime-palindrome/solution/) | [C++](0501-1000/0866-Prime-Palindrome/cpp-0866/) | | | +| 867 | [Transpose Matrix](https://leetcode.com/problems/transpose-matrix/description/) | [solution](https://leetcode.com/problems/transpose-matrix/solution/) | [C++](0501-1000/0867-Transpose-Matrix/cpp-0867/) | | | +| 868 | [Binary Gap](https://leetcode.com/problems/binary-gap/description/) | [solution](https://leetcode.com/problems/binary-gap/solution/) | [C++](0501-1000/0868-Binary-Gap/cpp-0868/) | | | +| 869 | [Reordered Power of 2](https://leetcode.com/problems/reordered-power-of-2/description/) | [solution](https://leetcode.com/problems/reordered-power-of-2/solution/) | [C++](0501-1000/0869-Reordered-Power-of-2/cpp-0869/) | | | +| 870 | [Advantage Shuffle](https://leetcode.com/problems/advantage-shuffle/description/) | [solution](https://leetcode.com/problems/advantage-shuffle/solution/) | [C++](0501-1000/0870-Advantage-Shuffle/cpp-0870/) | | | +| 871 | [Minimum Number of Refueling Stops](https://leetcode.com/problems/minimum-number-of-refueling-stops/description/) | [solution](https://leetcode.com/problems/minimum-number-of-refueling-stops/solution/) [题解](https://leetcode-cn.com/problems/minimum-number-of-refueling-stops/solution/zui-di-jia-you-ci-shu-by-leetcode/) | [C++](0501-1000/0871-Minimum-Number-of-Refueling-Stops/cpp-0871/) | | | +| 872 | [Leaf-Similar Trees](https://leetcode.com/problems/leaf-similar-trees/description/) | [solution](https://leetcode.com/problems/leaf-similar-trees/solution/) | [C++](0501-1000/0872-Leaf-Similar-Trees/cpp-0872/) | | | +| 873 | [Length of Longest Fibonacci Subsequence](https://leetcode.com/problems/length-of-longest-fibonacci-subsequence/description/) | [solution](https://leetcode.com/problems/length-of-longest-fibonacci-subsequence/solution/) | [C++](0501-1000/0873-Length-of-Longest-Fibonacci-Subsequence/cpp-0873/) | | | +| 874 | [Walking-Robot-Simulation](https://leetcode.com/problems/walking-robot-simulation/description/) | [solution](https://leetcode.com/problems/walking-robot-simulation/solution/) | [C++](0501-1000/0874-Walking-Robot-Simulation/cpp-0874/) | | | +| 875 | [Koko Eating Bananas](https://leetcode.com/problems/koko-eating-bananas/description/) | [solution](https://leetcode.com/problems/koko-eating-bananas/solution/) | [C++](0501-1000/0875-Koko-Eating-Bananas/cpp-0875/) | | | +| 876 | [Middle of the Linked List](https://leetcode.com/problems/middle-of-the-linked-list/description/) | [solution](https://leetcode.com/problems/middle-of-the-linked-list/solution/) | [C++](0501-1000/0876-Middle-of-the-Linked-List/cpp-0876/) | | | +| 877 | [Stone Game](https://leetcode.com/problems/stone-game/description/) | [solution](https://leetcode.com/problems/stone-game/solution/) | [C++](0501-1000/0877-Stone-Game/cpp-0877/) | | | +| 878 | [Nth Magical Number](https://leetcode.com/problems/nth-magical-number/description/) | [solution](https://leetcode.com/problems/nth-magical-number/solution/) | [C++](0501-1000/0878-Nth-Magical-Number/cpp-0878/) | | | +| 879 | [Profitable Schemes](https://leetcode.com/problems/profitable-schemes/description/) | [solution](https://leetcode.com/problems/profitable-schemes/solution/) | [C++](0501-1000/0879-Profitable-Schemes/cpp-0879/) | | | +| 880 | [Decoded String at Index](https://leetcode.com/problems/decoded-string-at-index/description/) | [solution](https://leetcode.com/problems/decoded-string-at-index/solution/) | [C++](0501-1000/0880-Decoded-String-at-Index/cpp-0880/) | | | +| 881 | [Boats to Save People](https://leetcode.com/problems/boats-to-save-people/description/) | [solution](https://leetcode.com/problems/boats-to-save-people/solution/) | [C++](0501-1000/0881-Boats-to-Save-People/cpp-0881/) | | | +| 882 | [Reachable Nodes In Subdivided Graph](https://leetcode.com/problems/reachable-nodes-in-subdivided-graph/description/) | [solution](https://leetcode.com/problems/reachable-nodes-in-subdivided-graph/solution/) | [C++](0501-1000/0882-Reachable-Nodes-In-Subdivided-Graph/cpp-0882/) | | | +| 883 | [Projection Area of 3D Shapes](https://leetcode.com/problems/projection-area-of-3d-shapes/description/) | [solution](https://leetcode.com/problems/projection-area-of-3d-shapes/solution/) | [C++](0501-1000/0883-Projection-Area-of-3D-Shapes/cpp-0883/) | | | +| 884 | [Uncommon Words from Two Sentences](https://leetcode.com/problems/uncommon-words-from-two-sentences/description/) | [solution](https://leetcode.com/problems/uncommon-words-from-two-sentences/solution/) | [C++](0501-1000/0884-Uncommon-Words-from-Two-Sentences/cpp-0884/) | | | +| 885 | [Spiral Matrix III](https://leetcode.com/problems/spiral-matrix-iii/description/) | [solution](https://leetcode.com/problems/spiral-matrix-iii/solution/) | [C++](0885-Spiral-Matrix-III/cpp-0885/) | | | +| 886 | [Possible Bipartition](https://leetcode.com/problems/possible-bipartition/description/) | [solution](https://leetcode.com/problems/possible-bipartition/solution/) | [C++](0501-1000/0886-Possible-Bipartition/cpp-0886/) | | | +| | | | | | | +| 888 | [Fair Candy Swap](https://leetcode.com/problems/fair-candy-swap/description/) | [solution](https://leetcode.com/problems/fair-candy-swap/solution/) | [C++](0501-1000/0888-Fair-Candy-Swap/cpp-0888/) | | | +| 889 | [Construct Binary Tree from Preorder and Postorder Traversal](https://leetcode.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal/description/) | [solution](https://leetcode.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal/solution/) | [C++](0501-1000/0889-Construct-Binary-Tree-from-Preorder-and-Postorder-Traversal/cpp-0889/) | | | +| 890 | [Find and Replace Pattern](https://leetcode.com/problems/find-and-replace-pattern/description/) | [solution](https://leetcode.com/problems/find-and-replace-pattern/solution/) | [C++](0501-1000/0890-Find-and-Replace-Pattern/cpp-0890/) | | | +| 891 | [Sum of Subsequence Widths](https://leetcode.com/problems/sum-of-subsequence-widths/description/) | [solution](https://leetcode.com/problems/sum-of-subsequence-widths/solution/) | [C++](0501-1000/0891-Sum-of-Subsequence-Widths/cpp-0891/) | | | +| 892 | [Surface Area of 3D Shapes](https://leetcode.com/problems/surface-area-of-3d-shapes/description/) | [solution](https://leetcode.com/problems/surface-area-of-3d-shapes/solution/) | [C++](0501-1000/0892-Surface-Area-of-3D-Shapes/cpp-0892/) | | | +| 893 | [Groups of Special-Equivalent Strings](https://leetcode.com/problems/groups-of-special-equivalent-strings/description/) | [solution](https://leetcode.com/problems/groups-of-special-equivalent-strings/solution/) | [C++](0501-1000/0893-Groups-of-Special-Equivalent-Strings/cpp-0893/) | | | +| 894 | [All Possible Full Binary Trees](https://leetcode.com/problems/all-possible-full-binary-trees/description/) | [solution](https://leetcode.com/problems/all-possible-full-binary-trees/solution/) | [C++](0501-1000/0894-All-Possible-Full-Binary-Trees/cpp-0894/) | | | +| 895 | [Maximum Frequency Stack](https://leetcode.com/problems/maximum-frequency-stack/description/) | [solution](https://leetcode.com/problems/maximum-frequency-stack/solution/) | [C++](0501-1000/0895-Maximum-Frequency-Stack/cpp-0895/) | | | +| 896 | [Monotonic Array](https://leetcode.com/problems/monotonic-array/description/) | [solution](https://leetcode.com/problems/monotonic-array/solution/) | [C++](0501-1000/0896-Monotonic-Array/cpp-0896/) | | [Python](0501-1000/0896-Monotonic-Array/py-0896/) | +| 897 | [Increasing Order Search Tree](https://leetcode.com/problems/increasing-order-search-tree/description/) | [solution](https://leetcode.com/problems/increasing-order-search-tree/solution/) | [C++](0501-1000/0897-Increasing-Order-Search-Tree/cpp-0897/) | | | +| 898 | [Bitwise ORs of Subarrays](https://leetcode.com/problems/bitwise-ors-of-subarrays/description/) | [solution](https://leetcode.com/problems/bitwise-ors-of-subarrays/solution/) | [C++](0501-1000/0898-Bitwise-ORs-of-Subarrays/cpp-0898/) | | | +| 899 | [Orderly Queue](https://leetcode.com/problems/orderly-queue/description/) | [solution](https://leetcode.com/problems/orderly-queue/solution/) | [C++](0501-1000/0899-Orderly-Queue/cpp-0899/) | | | +| 900 | [RLE Iterator](https://leetcode.com/problems/rle-iterator/description/) | [solution](https://leetcode.com/problems/rle-iterator/solution/) | [C++](0501-1000/0900-RLE-Iterator/cpp-0900/) | | | +| 901 | [Online Stock Span](https://leetcode.com/problems/online-stock-span/description/) | [solution](https://leetcode.com/problems/online-stock-span/solution/) | [C++](0501-1000/0901-Online-Stock-Span/cpp-0901/) | | | +| 902 | [Numbers At Most N Given Digit Set](https://leetcode.com/problems/numbers-at-most-n-given-digit-set/description/) | [solution](https://leetcode.com/problems/numbers-at-most-n-given-digit-set/solution/) | [C++](0501-1000/0902-Numbers-At-Most-N-Given-Digit-Set/cpp-0902/) | | | +| 903 | [Valid Permutations for DI Sequence](https://leetcode.com/problems/valid-permutations-for-di-sequence/description/) | [solution](https://leetcode.com/problems/valid-permutations-for-di-sequence/solution/)
[缺:O(n^2) DP] | [C++](0501-1000/0903-Valid-Permutations-for-DI-Sequence/cpp-0903/) | | | +| 904 | [Fruit Into Baskets](https://leetcode.com/problems/fruit-into-baskets/description/) | [solution](https://leetcode.com/problems/fruit-into-baskets/solution/) | [C++](0501-1000/0904-Fruit-Into-Baskets/cpp-0904/) | | | +| 905 | [Sort Array By Parity](https://leetcode.com/problems/sort-array-by-parity/description/) | [solution](https://leetcode.com/problems/sort-array-by-parity/solution/) | [C++](0501-1000/0905-Sort-Array-By-Parity/cpp-0905/) | | | +| 906 | [Super Palindromes](https://leetcode.com/problems/super-palindromes/description/) | [solution](https://leetcode.com/problems/super-palindromes/solution/) | [C++](0501-1000/0906-Super-Palindromes/cpp-0906/) | | | +| 907 | [Sum of Subarray Minimums](https://leetcode.com/problems/sum-of-subarray-minimums/description/) | [solution](https://leetcode.com/problems/sum-of-subarray-minimums/solution/) | [C++](0501-1000/0907-Sum-of-Subarray-Minimums/cpp-0907/) | | | +| 908 | [Smallest Range I](https://leetcode.com/problems/smallest-range-i/description/) | [solution](https://leetcode.com/problems/smallest-range-i/solution/) | [C++](0501-1000/0908-Smallest-Range-I/cpp-0908/) | | | +| 909 | [Snakes and Ladders](https://leetcode.com/problems/snakes-and-ladders/description/) | [solution](https://leetcode.com/problems/snakes-and-ladders/solution/) | [C++](0501-1000/0909-Snakes-and-Ladders/cpp-0909/) | | | +| 910 | [Smallest Range II](https://leetcode.com/problems/smallest-range-ii/description/) | [solution](https://leetcode.com/problems/smallest-range-ii/solution/) | [C++](0501-1000/0910-Smallest-Range-II/cpp-0910/) | | | +| 911 | [Online Election](https://leetcode.com/problems/online-election/description/) | [solution](https://leetcode.com/problems/online-election/solution/) | [C++](0501-1000/0911-Online-Election/cpp-0911/) | | | +| 912 | [Sort an Array](https://leetcode.com/problems/sort-an-array/) | [无] | [C++](0501-1000/0912-Sort-an-Array/cpp-0912/) | | | +| 913 | [Cat and Mouse Game](https://leetcode.com/problems/cat-and-mouse/) | [solution](https://leetcode.com/problems/cat-and-mouse/solution/)
[缺:DFS拓扑排序;DP] | [C++](0501-1000/0913-Cat-and-Mouse-Game/cpp-0913/) | | | +| 914 | [X of a Kind in a Deck of Cards](https://leetcode.com/problems/x-of-a-kind-in-a-deck-of-cards/description/) | [solution](https://leetcode.com/problems/x-of-a-kind-in-a-deck-of-cards/solution/) | [C++](0501-1000/0914-X-of-a-Kind-in-a-Deck-of-Cards/cpp-0914/) | | | +| 915 | [Partition Array into Disjoint Intervals](https://leetcode.com/problems/partition-array-into-disjoint-intervals/description/) | [solution](https://leetcode.com/problems/partition-array-into-disjoint-intervals/solution/) | [C++](0501-1000/0915-Partition-Array-into-Disjoint-Intervals/cpp-0915/) | | | +| 916 | [Word Subsets](https://leetcode.com/problems/word-subsets/description/) | [solution](https://leetcode.com/problems/word-subsets/solution/) | [C++](0501-1000/0916-Word-Subsets/cpp-0916/) | | | +| 917 | [Reverse Only Letters](https://leetcode.com/problems/reverse-only-letters/description/) | [solution](https://leetcode.com/problems/reverse-only-letters/solution/) | [C++](0501-1000/0917-Reverse-Only-Letters/cpp-0917/) | | | +| 918 | [Maximum Sum Circular Subarray](https://leetcode.com/problems/maximum-sum-circular-subarray/description/) | [solution](https://leetcode.com/problems/maximum-sum-circular-subarray/solution/) | [C++](0501-1000/0918-Maximum-Sum-Circular-Subarray/cpp-0918/) | | | +| 919 | [Complete Binary Tree Inserter](https://leetcode.com/problems/complete-binary-tree-inserter/description/) | [solution](https://leetcode.com/problems/complete-binary-tree-inserter/solution/) | [C++](0501-1000/0919-Complete-Binary-Tree-Inserter/cpp-0919/) | | | +| 920 | [Number of Music Playlists](https://leetcode.com/problems/number-of-music-playlists/description/) | [solution](https://leetcode.com/problems/number-of-music-playlists/solution/)
[缺:生成函数] | [C++](0501-1000/0920-Number-of-Music-Playlists/cpp-0920/) | | | +| 921 | [Minimum Add to Make Parentheses Valid](https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/description/) | [solution](https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/solution/) | [C++](0501-1000/0921-Minimum-Add-to-Make-Parentheses-Valid/cpp-0921/) | | | +| 922 | [Sort Array By Parity II](https://leetcode.com/problems/sort-array-by-parity-ii/description/) | [solution](https://leetcode.com/problems/sort-array-by-parity-ii/solution/) | [C++](0501-1000/0922-Sort-Array-By-Parity-II/cpp-0922/) | | | +| 923 | [3Sum With Multiplicity](https://leetcode.com/problems/3sum-with-multiplicity/description/) | [solution](https://leetcode.com/problems/3sum-with-multiplicity/solution/) | [C++](0501-1000/0923-3Sum-With-Multiplicity/cpp-0923/) | | | +| 924 | [Minimize Malware Spread](https://leetcode.com/problems/minimize-malware-spread/description/) | [solution](https://leetcode.com/problems/minimize-malware-spread/solution/) | [C++](0501-1000/0924-Minimize-Malware-Spread/cpp-0924/) | | | +| 925 | [Long Pressed Name](https://leetcode.com/problems/long-pressed-name/submissions/) | [solution](https://leetcode.com/problems/long-pressed-name/solution/) | [C++](0501-1000/0925-Long-Pressed-Name/cpp-0925/) | | | +| 926 | [Flip String to Monotone Increasing](https://leetcode.com/problems/flip-string-to-monotone-increasing/) | [solution](https://leetcode.com/problems/flip-string-to-monotone-increasing/solution/) | [C++](0501-1000/0926-Flip-String-to-Monotone-Increasing/cpp-0926/) | | | +| 927 | [Three Equal Parts](https://leetcode.com/problems/three-equal-parts/) | [solution](https://leetcode.com/problems/three-equal-parts/solution/) | [C++](0501-1000/0927-Three-Equal-Parts/cpp-0927/) | | | +| 928 | [Minimize Malware Spread II](https://leetcode.com/problems/minimize-malware-spread-ii/description/) | [solution](https://leetcode.com/problems/minimize-malware-spread-ii/solution/) | [C++](0501-1000/0928-Minimize-Malware-Spread-II/cpp-0928/) | | | +| 929 | [Unique Email Addresses](https://leetcode.com/problems/unique-email-addresses/solution/) | [solution](https://leetcode.com/problems/unique-email-addresses/) | [C++](0501-1000/0929-Unique-Email-Addresses/cpp-0929/) | | | +| 930 | [Binary Subarrays With Sum](https://leetcode.com/problems/binary-subarrays-with-sum/) | [solution](https://leetcode.com/problems/binary-subarrays-with-sum/solution/) | [C++](0501-1000/0930-Binary-Subarrays-With-Sum/cpp-0930/) | | | +| 931 | [Minimum Path Falling Sum](https://leetcode.com/problems/minimum-falling-path-sum/) | [solution](https://leetcode.com/problems/minimum-falling-path-sum/solution/) | [C++](0501-1000/0931-Minimum-Path-Falling-Sum/cpp-0931/) | | | +| 932 | [Beautiful Array](https://leetcode.com/problems/beautiful-array/description/) | [solution](https://leetcode.com/problems/beautiful-array/solution/) | [C++](0501-1000/0932-Beautiful-Array/cpp-0932/) | | | +| 933 | [Number of Recent Calls](https://leetcode.com/problems/number-of-recent-calls/) | [solution](https://leetcode.com/problems/number-of-recent-calls/solution/) | [C++](0501-1000/0933-Number-of-Recent-Calls/cpp-0933/) | | | +| 934 | [Shortest Bridge](https://leetcode.com/problems/shortest-bridge/) | [solution](https://leetcode.com/problems/shortest-bridge/solution/) | [C++](0501-1000/0934-Shortest-Bridge/cpp-0934/) | | | +| 935 | [Knight Dialer](https://leetcode.com/problems/knight-dialer/) | [solution](https://leetcode.com/problems/knight-dialer/solution/) | [C++](0501-1000/0935-Knight-Dialer/cpp-0935/) | | | +| 936 | [Stamping The Sequence](https://leetcode.com/problems/stamping-the-sequence/) | [solution](https://leetcode.com/problems/stamping-the-sequence/solution/) | [C++](0501-1000/0936-Stamping-The-Sequence/cpp-0936/) | | | +| 937 | [Reorder Log Files](https://leetcode.com/problems/reorder-log-files/) | [solution](https://leetcode.com/problems/reorder-log-files/solution/) | [C++](0501-1000/0937-Reorder-Log-Files/cpp-0937/) | | | +| 938 | [Range Sum of BST](https://leetcode.com/problems/range-sum-of-bst/) | [solution](https://leetcode.com/problems/range-sum-of-bst/solution/) | [C++](0501-1000/0938-Range-Sum-of-BST/cpp-0938/) | | | +| 939 | [Minimum Area Rectangle](https://leetcode.com/problems/minimum-area-rectangle/) | [solution](https://leetcode.com/problems/minimum-area-rectangle/solution/) | [C++](0501-1000/0939-Minimum-Area-Rectangle/cpp-0939/) | | | +| 940 | [Distinct Subsequences II](https://leetcode.com/problems/distinct-subsequences-ii/) | [solution](https://leetcode.com/problems/distinct-subsequences-ii/solution/) | [C++](0501-1000/0940-Distinct-Subsequences-II/cpp-0940/) | | | +| 941 | [Valid Mountain Array](https://leetcode.com/problems/valid-mountain-array/) | [solution](https://leetcode.com/problems/valid-mountain-array/solution/) | [C++](0501-1000/0941-Valid-Mountain-Array/cpp-0941/) | | | +| 942 | [DI String Match](https://leetcode.com/problems/di-string-match/) | [solution](https://leetcode.com/problems/di-string-match/solution/) | [C++](0501-1000/0942-DI-String-Match/cpp-0942/) | | | +| 943 | [Find the Shortest Superstring](https://leetcode.com/problems/find-the-shortest-superstring/) | [solution](https://leetcode.com/problems/find-the-shortest-superstring/solution/)
[缺:动态规划] | [C++](0501-1000/0943-Find-the-Shortest-Superstring/cpp-0943/) | | | +| 944 | [Delete Columns to Make Sorted](https://leetcode.com/problems/delete-columns-to-make-sorted/) | [solution](https://leetcode.com/problems/delete-columns-to-make-sorted/solution/) | [C++](0501-1000/0944-Delete-Columns-to-Make-Sorted/cpp-0944/) | | | +| 945 | [Minimum Increment to Make Array Unique](https://leetcode.com/problems/minimum-increment-to-make-array-unique/) | [solution](https://leetcode.com/problems/minimum-increment-to-make-array-unique/solution/) | [C++](0501-1000/0945-Minimum-Increment-to-Make-Array-Unique/cpp-0945/) | | | +| 946 | [Validate Stack Sequences](https://leetcode.com/problems/validate-stack-sequences/) | [solution](https://leetcode.com/problems/validate-stack-sequences/solution/) | [C++](0501-1000/0946-Validate-Stack-Sequences/cpp-0946/) | | | +| 947 | [Most Stones Removed with Same Row or Column](https://leetcode.com/problems/most-stones-removed-with-same-row-or-column/) | [solution](https://leetcode.com/problems/most-stones-removed-with-same-row-or-column/solution/) | [C++](0501-1000/0947-Most-Stones-Removed-with-Same-Row-or-Column/cpp-0947/) | | | +| 948 | [Bag of Tokens](https://leetcode.com/problems/bag-of-tokens/) | [solution](https://leetcode.com/problems/bag-of-tokens/solution/) | [C++](0501-1000/0948-Bag-of-Tokens/cpp-0948/) | | | +| 949 | [Largest Time for Given Digits](https://leetcode.com/problems/largest-time-for-given-digits/) | [solution](https://leetcode.com/problems/largest-time-for-given-digits/solution/) | [C++](0501-1000/0949-Largest-Time-for-Given-Digits/cpp-0949/) | | | +| 950 | [Reveal Cards In Increasing Order](https://leetcode.com/problems/reveal-cards-in-increasing-order/) | [solution](https://leetcode.com/problems/reveal-cards-in-increasing-order/solution/) | [C++](0501-1000/0950-Reveal-Cards-In-Increasing-Order/cpp-0950/) | | | +| 951 | [Flip Equivalent Binary Trees](https://leetcode.com/problems/flip-equivalent-binary-trees/) | [solution](https://leetcode.com/problems/flip-equivalent-binary-trees/solution/) | [C++](0501-1000/0951-Flip-Equivalent-Binary-Trees/cpp-0951/) | | | +| 952 | [Largest Component Size by Common Factor](https://leetcode.com/problems/largest-component-size-by-common-factor/) | [solution](https://leetcode.com/problems/largest-component-size-by-common-factor/solution/) | [C++](0501-1000/0952-Largest-Component-Size-by-Common-Factor/cpp-0952/) | | | +| 953 | [isAlienSorted](https://leetcode.com/problems/verifying-an-alien-dictionary/) | [solution](https://leetcode.com/problems/verifying-an-alien-dictionary/solution/) | [C++](0501-1000/0953-isAlienSorted/cpp-0953/) | | | +| 954 | [Array of Doubled Pairs](https://leetcode.com/problems/array-of-doubled-pairs/) | [solution](https://leetcode.com/problems/array-of-doubled-pairs/solution/) | [C++](0501-1000/0954-Array-of-Doubled-Pairs/cpp-0954/) | | | +| 955 | [Delete Columns to Make Sorted II](https://leetcode.com/problems/delete-columns-to-make-sorted-ii/) | [solution](https://leetcode.com/problems/delete-columns-to-make-sorted-ii/solution/) | [C++](0501-1000/0955-Delete-Columns-to-Make-Sorted-II/cpp-0955/) | | | +| 956 | [Tallest Billboard](https://leetcode.com/problems/tallest-billboard/) | [solution](https://leetcode.com/problems/tallest-billboard/solution/) | [C++](0501-1000/0956-Tallest-Billboard/cpp-0956/) | | | +| 957 | [Prison Cells After N Days](https://leetcode.com/problems/prison-cells-after-n-days/) | [solution](https://leetcode.com/problems/prison-cells-after-n-days/solution/) | [C++](0501-1000/0957-Prison-Cells-After-N-Days/cpp-0957/) | | | +| 958 | [Check Completeness of a Binary Tree](https://leetcode.com/problems/check-completeness-of-a-binary-tree/) | [solution](https://leetcode.com/problems/check-completeness-of-a-binary-tree/solution/) | [C++](0501-1000/0958-Check-Completeness-of-a-Binary-Tree/cpp-0958/) | | | +| 959 | [Regions Cut By Slashes](https://leetcode.com/problems/regions-cut-by-slashes/) | [solution](https://leetcode.com/problems/regions-cut-by-slashes/solution/) | [C++](0501-1000/0959-Regions-Cut-By-Slashes/cpp-0959/) | | | +| 960 | [Delete Columns to Make Sorted III](https://leetcode.com/problems/delete-columns-to-make-sorted-iii/) | [solution](https://leetcode.com/problems/delete-columns-to-make-sorted-iii/solution/) | [C++](0501-1000/0960-Delete-Columns-to-Make-Sorted-III/cpp-0960/) | | | +| 961 | [N-Repeated Element in Size 2N Array](https://leetcode.com/problems/n-repeated-element-in-size-2n-array/) | [solution](https://leetcode.com/problems/n-repeated-element-in-size-2n-array/solution/) | [C++](0501-1000/0961-N-Repeated-Element-in-Size-2N-Array/cpp-0961/) | | | +| | | | | | | +| 965 | [Univalued Binary Tree](https://leetcode.com/problems/univalued-binary-tree/) | [solution](https://leetcode.com/problems/univalued-binary-tree/solution/) | [C++](0501-1000/0965-Univalued-Binary-Tree/cpp-0965/) | | | +| 966 | [Vowel Spellchecker](https://leetcode.com/problems/vowel-spellchecker/) | [solution](https://leetcode.com/problems/vowel-spellchecker/solution/) | [C++](0501-1000/0966-Vowel-Spellchecker/cpp-0966/) | | | +| 967 | [Numbers With Same Consecutive Differences](https://leetcode.com/problems/numbers-with-same-consecutive-differences/) | [solution](https://leetcode.com/problems/numbers-with-same-consecutive-differences/solution/) | [C++](0501-1000/0967-Numbers-With-Same-Consecutive-Differences/cpp-0967/) | | | +| 968 | [Binary Tree Cameras](https://leetcode.com/problems/binary-tree-cameras/) | [solution](https://leetcode.com/problems/binary-tree-cameras/solution/) | [C++](0501-1000/0968-Binary-Tree-Cameras/cpp-0968/) | | | +| 969 | [Pancake Sorting](https://leetcode.com/problems/pancake-sorting/) | [solution](https://leetcode.com/problems/pancake-sorting/solution/) | [C++](0501-1000/0969-Pancake-Sorting/cpp-0969/) | | | +| 970 | [Powerful Integers](https://leetcode.com/problems/powerful-integers/) | [solution](https://leetcode.com/problems/powerful-integers/solution/) | [C++](0501-1000/0970-Powerful-Integers/cpp-0970/) | | | +| 971 | [Flip Binary Tree To Match Preorder Traversal](https://leetcode.com/problems/flip-binary-tree-to-match-preorder-traversal/) | [solution](https://leetcode.com/problems/flip-binary-tree-to-match-preorder-traversal/solution/) | [C++](0501-1000/0971-Flip-Binary-Tree-To-Match-Preorder-Traversal/cpp-0971/) | | | +| 972 | [Equal Rational Numbers](https://leetcode.com/problems/equal-rational-numbers/) | [solution](https://leetcode.com/problems/equal-rational-numbers/solution/) | [C++](0501-1000/0972-Equal-Rational-Numbers/cpp-0972/) | | | +| 973 | [K Closest Points to Origin](https://leetcode.com/problems/k-closest-points-to-origin/) | [solution](https://leetcode.com/problems/k-closest-points-to-origin/solution/) | [C++](0501-1000/0973-K-Closest-Points-to-Origin/cpp-0973/) | | | +| 974 | [Subarray Sums Divisible by K](https://leetcode.com/problems/subarray-sums-divisible-by-k/) | [solution](https://leetcode.com/problems/subarray-sums-divisible-by-k/solution/) | [C++](0501-1000/0974-Subarray-Sums-Divisible-by-K/cpp-0974/) | | | +| 975 | [Odd Even Jump](https://leetcode.com/problems/odd-even-jump/) | [solution](https://leetcode.com/problems/odd-even-jump/solution/) | [C++](0501-1000/0975-Odd-Even-Jump/cpp-0975/) | | | +| 976 | [Largest Perimeter Triangle](https://leetcode.com/problems/largest-perimeter-triangle/) | [solution](https://leetcode.com/problems/largest-perimeter-triangle/solution/) | [C++](0501-1000/0976-Largest-Perimeter-Triangle/cpp-0976/) | | | +| 977 | [Squares of a Sorted Array](https://leetcode.com/problems/squares-of-a-sorted-array/) | [solution](https://leetcode.com/problems/squares-of-a-sorted-array/solution/) | [C++](0501-1000/0977-Squares-of-a-Sorted-Array/cpp-0977/) | | | +| 978 | [Longest Turbulent Subarray](https://leetcode.com/problems/longest-turbulent-subarray/) | [solution](https://leetcode.com/problems/longest-turbulent-subarray/solution/)
[缺:滑动窗口 & dp] | [C++](0501-1000/0978-Longest-Turbulent-Subarray/cpp-0978/) | | | +| 979 | [Distribute Coins in Binary Tree](https://leetcode.com/problems/distribute-coins-in-binary-tree/) | [solution](https://leetcode.com/problems/distribute-coins-in-binary-tree/solution/) | [C++](0501-1000/0979-Distribute-Coins-in-Binary-Tree/cpp-0979/) | | | +| 980 | [Unique Paths III](https://leetcode.com/problems/unique-paths-iii/) | [solution](https://leetcode.com/problems/unique-paths-iii/solution/)
[缺:记忆化搜索] | [C++](0501-1000/0980-Unique-Paths-III/cpp-0980/) | [Java](0980-Unique-Paths-III/java-0980/)| | +| 981 | [Time Based Key-Value Store](https://leetcode.com/problems/time-based-key-value-store/) | [solution](https://leetcode.com/problems/time-based-key-value-store/solution/) | [C++](0501-1000/0981-Time-Based-Key-Value-Store/cpp-0981/) | | | +| 982 | [Triples with Bitwise AND Equal To Zero](https://leetcode.com/problems/triples-with-bitwise-and-equal-to-zero/) | [无] | [C++](0501-1000/0982-Triples-with-Bitwise-AND-Equal-To-Zero/cpp-0982/) | | | +| 983 | [Minimum Cost For Tickets](https://leetcode.com/problems/minimum-cost-for-tickets/) | [solution](https://leetcode.com/problems/minimum-cost-for-tickets/solution/) | [C++](0501-1000/0983-Minimum-Cost-For-Tickets/cpp-0983/) | | | +| 984 | [String Without AAA or BBB](https://leetcode.com/problems/string-without-aaa-or-bbb/) | [solution](https://leetcode.com/problems/string-without-aaa-or-bbb/solution/) | [C++](0501-1000/0984-String-Without-AAA-or-BBB/cpp-0984/) | | | +| 985 | [Sum of Even Numbers After Queries](https://leetcode.com/problems/sum-of-even-numbers-after-queries/) | [solution](https://leetcode.com/problems/sum-of-even-numbers-after-queries/) | [C++](0501-1000/0985-Sum-of-Even-Numbers-After-Queries/cpp-0985/) | | | +| 986 | [Interval List Intersections](https://leetcode.com/problems/interval-list-intersections/) | [solution](https://leetcode.com/problems/interval-list-intersections/solution/) | [C++](0501-1000/0986-Interval-List-Intersections/cpp-0986/) | | | +| 987 | [Vertical Order Traversal of a Binary Tree](https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/) | [solution](https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/solution/) | [C++](0501-1000/0987-Vertical-Order-Traversal-of-a-Binary-Tree/cpp-0987/) | | | +| 988 | [Smallest String Starting From Leaf](https://leetcode.com/problems/smallest-string-starting-from-leaf/) | [solution](https://leetcode.com/problems/smallest-string-starting-from-leaf/solution/) | [C++](0501-1000/0988-Smallest-String-Starting-From-Leaf/cpp-0988/) | | | +| 989 | [Add to Array-Form of Integer](https://leetcode.com/problems/add-to-array-form-of-integer/) | [solution](https://leetcode.com/problems/add-to-array-form-of-integer/solution/) | [C++](0501-1000/0989-Add-to-Array-Form-of-Integer/cpp-0989/) | | | +| 990 | [Satisfiability of Equality Equations](https://leetcode.com/problems/satisfiability-of-equality-equations/) | [solution](https://leetcode.com/problems/satisfiability-of-equality-equations/solution/) | [C++](0501-1000/0990-Satisfiability-of-Equality-Equations/cpp-0990/) | | | +| 991 | [Broken Calculator](https://leetcode.com/problems/broken-calculator/) | [solution](https://leetcode.com/problems/broken-calculator/solution/) | [C++](0501-1000/0991-Broken-Calculator/cpp-0991/) | | | +| 992 | [Subarrays with K Different Integers](https://leetcode.com/problems/subarrays-with-k-different-integers/) | [solution](https://leetcode.com/problems/subarrays-with-k-different-integers/solution/) | [C++](0501-1000/0992-Subarrays-with-K-Different-Integers/cpp-0992/) | | | +| 993 | [Cousins in Binary Tree](https://leetcode.com/problems/cousins-in-binary-tree/) | [solution](https://leetcode.com/problems/cousins-in-binary-tree/solution/) | [C++](0501-1000/0993-Cousins-in-Binary-Tree/cpp-0993/) | | | +| 994 | [Rotting Oranges](https://leetcode.com/problems/rotting-oranges/) | [solution](https://leetcode.com/problems/rotting-oranges/solution/) | [C++](0501-1000/0994-Rotting-Oranges/cpp-0994/) | | | +| 995 | [Minimum Number of K Consecutive Bit Flips](https://leetcode.com/problems/minimum-number-of-k-consecutive-bit-flips/) | [solution](https://leetcode.com/problems/minimum-number-of-k-consecutive-bit-flips/solution/) | [C++](0501-1000/0995-Minimum-Number-of-K-Consecutive-Bit-Flips/cpp-0995/) | | | +| 996 | [Number of Squareful Arrays](https://leetcode.com/problems/number-of-squareful-arrays/) | [solution](https://leetcode.com/problems/number-of-squareful-arrays/solution/) | [C++](0501-1000/0996-Number-of-Squareful-Arrays/cpp-0996/) | | | +| 997 | [Find the Town Judge](https://leetcode.com/problems/find-the-town-judge/) | [无] | [C++](0501-1000/0997-Find-the-Town-Judge/cpp-0997/) | | | +| 998 | [Maximum Binary Tree II](https://leetcode.com/problems/maximum-binary-tree-ii/) | [无] | [C++](0501-1000/0998-Maximum-Binary-Tree-II/cpp-0998/) | | | +| 999 | [Available Captures for Rook](https://leetcode.com/problems/available-captures-for-rook/) | [无] | [C++](0501-1000/0999-Available-Captures-for-Rook/cpp-0999/) | | | +| 1000 | [Minimum Cost to Merge Stones](https://leetcode.com/problems/minimum-cost-to-merge-stones/) | [无] | [C++](0501-1000/1000-Minimum-Cost-to-Merge-Stones/cpp-1000/) | | | +| 1001 | [Grid Illumination](https://leetcode.com/problems/grid-illumination/) | [无] | [C++](1001-1500/1001-Grid-Illumination/cpp-1001/) | | | +| 1002 | [Find Common Characters](https://leetcode.com/problems/find-common-characters/) | [无] | [C++](1001-1500/1002-Find-Common-Characters/cpp-1002/) | | | +| 1003 | [Check If Word Is Valid After Substitutions](https://leetcode.com/problems/check-if-word-is-valid-after-substitutions/) | [无] | [C++](1001-1500/1003-Check-If-Word-Is-Valid-After-Substitutions/cpp-1003/) | | | +| 1004 | [Max Consecutive Ones III](https://leetcode.com/problems/max-consecutive-ones-iii/) | [无] | [C++](1001-1500/1004-Max-Consecutive-Ones-III/cpp-1004/) | | | +| 1005 | [Maximize Sum Of Array After K Negations](https://leetcode.com/problems/maximize-sum-of-array-after-k-negations/) | [无] | [C++](1001-1500/1005-Maximize-Sum-Of-Array-After-K-Negations/cpp-1005/) | | | +| 1006 | [Clumsy Factorial](https://leetcode.com/problems/clumsy-factorial/) | [无] | [C++](1001-1500/1006-Clumsy-Factorial/cpp-1006/) | | | +| 1007 | [Minimum Domino Rotations For Equal Row](https://leetcode.com/problems/minimum-domino-rotations-for-equal-row/) | [无] | [C++](1001-1500/1007-Minimum-Domino-Rotations-For-Equal-Row/cpp-1007/) | | | +| 1008 | [Construct Binary Search Tree from Preorder Traversal](https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/) | [无] | [C++](1001-1500/1008-Construct-Binary-Search-Tree-from-Preorder-Traversal/cpp-1008/) | | | +| 1009 | [Complement of Base 10 Integer](https://leetcode.com/problems/complement-of-base-10-integer/) | [无] | [C++](1001-1500/1009-Complement-of-Base-10-Integer/cpp-1009/) | | | +| 1010 | [Pairs of Songs With Total Durations Divisible by 60](https://leetcode.com/problems/pairs-of-songs-with-total-durations-divisible-by-60/) | [无] | [C++](1001-1500/1010-Pairs-of-Songs-With-Total-Durations-Divisible-by-60/cpp-1010/) | | | +| 1011 | [Capacity To Ship Packages Within D Days](https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/) | [无] | [C++](1001-1500/1011-Capacity-To-Ship-Packages-Within-D-Days/cpp-1011/) | | | +| 1012 | [Numbers With 1 Repeated Digit](https://leetcode.com/problems/numbers-with-1-repeated-digit/) | [无] | [C++](1001-1500/1012-Numbers-With-1-Repeated-Digit/cpp-1012/) | | | +| 1013 | [Partition Array Into Three Parts With Equal Sum](https://leetcode.com/problems/partition-array-into-three-parts-with-equal-sum/) | [无] | [C++](1001-1500/1013-Partition-Array-Into-Three-Parts-With-Equal-Sum/cpp-1013/) | | | +| 1014 | [Best Sightseeing Pair](https://leetcode.com/problems/best-sightseeing-pair/) | [无] | [C++](1001-1500/1014-Best-Sightseeing-Pair/cpp-1014/) | | | +| 1015 | [Smallest Integer Divisible by K](https://leetcode.com/problems/smallest-integer-divisible-by-k/) | [无] | [C++](1001-1500/1015-Smallest-Integer-Divisible-by-K/cpp-1015/) | | | +| 1016 | [Binary String With Substrings Representing 1 To N](https://leetcode.com/problems/binary-string-with-substrings-representing-1-to-n/) | [无] | [C++](1001-1500/1016-Binary-String-With-Substrings-Representing-1-To-N/cpp-10`6/) | | | +| 1017 | [Convert to Base -2](https://leetcode.com/problems/convert-to-base-2/) | [无] | [C++](1001-1500/1017-Convert-to-Base--2/cpp-1017/) | | | +| 1018 | [Binary Prefix Divisible By 5](https://leetcode.com/problems/binary-prefix-divisible-by-5/) | [无] | [C++](1001-1500/1018-Binary-Prefix-Divisible-By-5/cpp-1018/) | | | +| 1019 | [Next Greater Node In Linked List](https://leetcode.com/problems/next-greater-node-in-linked-list/) | [无] | [C++](1001-1500/1019-Next-Greater-Node-In-Linked-List/cpp-1019/) | | | +| 1020 | [Number of Enclaves](https://leetcode.com/problems/number-of-enclaves/) | [无] | [C++](1001-1500/1020-Number-of-Enclaves/cpp-1020/) | | | +| 1021 | [Remove Outermost Parentheses](https://leetcode.com/problems/remove-outermost-parentheses/) | [无] | [C++](1001-1500/1021-Remove-Outermost-Parentheses/cpp-1021/) | | | +| 1022 | [Sum of Root To Leaf Binary Numbers](https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/) | [无] | [C++](1001-1500/1022-Sum-of-Root-To-Leaf-Binary-Numbers/cpp-1022/) | | | +| 1023 | [Camelcase Matching](https://leetcode.com/problems/camelcase-matching/) | [无] | [C++](1001-1500/1023-Camelcase-Matching/cpp-1023/) | | | +| 1024 | [Video Stitching](https://leetcode.com/problems/video-stitching/) | [无] | [C++](1001-1500/1024-Video-Stitching/cpp-1024/) | | | +| 1025 | [Divisor Game](https://leetcode.com/problems/divisor-game/) | [无] | [C++](1001-1500/1025-Divisor-Game/cpp-1025/) | | | +| 1026 | [Maximum Difference Between Node and Ancestor](https://leetcode.com/problems/maximum-difference-between-node-and-ancestor/) | [无] | [C++](1001-1500/1026-Maximum-Difference-Between-Node-and-Ancestor/cpp-1026/) | | | +| 1027 | [Longest Arithmetic Sequence](https://leetcode.com/problems/longest-arithmetic-sequence/) | [无] | [C++](1001-1500/1027-Longest-Arithmetic-Sequence/cpp-1027/) | | | +| 1028 | [Recover a Tree From Preorder Traversal](https://leetcode.com/problems/recover-a-tree-from-preorder-traversal/) | [无] | [C++](1001-1500/1028-Recover-a-Tree-From-Preorder-Traversal/cpp-1028/) | | | +| 1029 | [Two City Scheduling](https://leetcode.com/problems/two-city-scheduling/) | [无] | [C++](1001-1500/1029-Two-City-Scheduling/cpp-1029/) | | | +| 1030 | [Matrix Cells in Distance Order](https://leetcode.com/problems/matrix-cells-in-distance-order/) | [无] | [C++](1001-1500/1030-Matrix-Cells-in-Distance-Order/cpp-1030/) | | | +| 1031 | [Maximum Sum of Two Non-Overlapping Subarrays](https://leetcode.com/problems/maximum-sum-of-two-non-overlapping-subarrays/) | [无] | [C++](1001-1500/1031-Maximum-Sum-of-Two-Non-Overlapping-Subarrays/cpp-1031/) | | | +| 1032 | [Stream of Characters](https://leetcode.com/problems/stream-of-characters/) | [无] | [C++](1001-1500/1032-Stream-of-Characters/cpp-1032/) | | | +| 1033 | [Moving Stones Until Consecutive](https://leetcode.com/problems/moving-stones-until-consecutive/) | [无] | [C++](1001-1500/1033-Moving-Stones-Until-Consecutive/cpp-1033/) | | | +| 1034 | [Coloring A Border](https://leetcode.com/problems/coloring-a-border/) | [无] | [C++](1001-1500/1034-Coloring-A-Border/cpp-1034/) | | | +| 1035 | [Uncrossed Lines](https://leetcode.com/problems/uncrossed-lines/) | [无] | [C++](1001-1500/1035-Uncrossed-Lines/cpp-1035/) | | | +| 1036 | [Escape a Large Maze](https://leetcode.com/problems/escape-a-large-maze/) | [无] | [C++](1001-1500/1036-Escape-a-Large-Maze/cpp-1036/) | | | +| 1037 | [Valid Boomerang](https://leetcode.com/problems/valid-boomerang/) | [无] | [C++](1001-1500/1037-Valid-Boomerang/cpp-1037/) | | | +| 1038 | [Binary Search Tree to Greater Sum Tree](https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/) | [无] | [C++](1001-1500/1038-Binary-Search-Tree-to-Greater-Sum-Tree/cpp-1038/) | | | +| 1039 | [Minimum Score Triangulation of Polygon](https://leetcode.com/problems/minimum-score-triangulation-of-polygon/) | [无] | [C++](1001-1500/1039-Minimum-Score-Triangulation-of-Polygon/cpp-1039/) | | | +| 1040 | [Moving Stones Until Consecutive II](https://leetcode.com/problems/moving-stones-until-consecutive-ii/) | [无] | [C++](1001-1500/1040-Moving-Stones-Until-Consecutive-II/cpp-1040/) | | | +| 1041 | [Robot Bounded In Circle](https://leetcode.com/problems/robot-bounded-in-circle/) | [无] | [C++](1001-1500/1041-Robot-Bounded-In-Circle/cpp-1041/) | | | +| 1042 | [Flower Planting With No Adjacent](https://leetcode.com/problems/flower-planting-with-no-adjacent/) | [无] | [C++](1001-1500/1042-Flower-Planting-With-No-Adjacent/cpp-1042/) | | | +| 1043 | [Partition Array for Maximum Sum](https://leetcode.com/problems/partition-array-for-maximum-sum/) | [无] | [C++](1001-1500/1043-Partition-Array-for-Maximum-Sum/cpp-1043/) | | | +| 1044 | [Longest Duplicate Substring](https://leetcode.com/problems/longest-duplicate-substring/) | [无]
[缺:后缀数组] | [C++](1001-1500/1044-Longest-Duplicate-Substring/cpp-1044/) | | | +| | | | | | | +| 1046 | [Last Stone Weight](https://leetcode.com/problems/last-stone-weight/) | [无] | [C++](1001-1500/1046-Last-Stone-Weight/cpp-1046/) | | | +| 1047 | [Remove All Adjacent Duplicates In String](https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string/) | [无] | [C++](1001-1500/1047-Remove-All-Adjacent-Duplicates-In-String/cpp-1047/) | | | +| | | | | | | +| 1049 | [Last Stone Weight II](https://leetcode.com/problems/last-stone-weight-ii/) | [无] | [C++](1001-1500/1049-Last-Stone-Weight-II/cpp-1049/) | | | +| 1050 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1051 | [Height Checker](https://leetcode.com/problems/height-checker/) | [无] | [C++](1001-1500/1051-Height-Checker/cpp-1051/) | | | +| 1052 | [Grumpy Bookstore Owner](https://leetcode.com/problems/grumpy-bookstore-owner/) | [无] | [C++](1001-1500/1052-Grumpy-Bookstore-Owner/cpp-1052/) | | | +| 1053 | [Previous Permutation With One Swap](https://leetcode.com/problems/previous-permutation-with-one-swap/description/) | [无] | [C++](1001-1500/1053-Previous-Permutation-With-One-Swap/cpp-1053/) | | | +| 1054 | [Distant Barcodes](https://leetcode.com/problems/distant-barcodes/description/) | [无] | [C++](1001-1500/1054-Distant-Barcodes/cpp-1054/) | | | +| 1055 | [Shortest Way to Form String](https://leetcode.com/problems/shortest-way-to-form-string/description/) | [无] | [C++](1001-1500/1055-Shortest-Way-to-Form-String/cpp-1055/) | | | +| 1056 | [Confusing Number](https://leetcode.com/problems/confusing-number/description/) | [无] | [C++](1001-1500/1056-Confusing-Number/cpp-1056/) | | | +| | | | | | | +| 1059 | [All Paths from Source Lead to Destination](https://leetcode.com/problems/all-paths-from-source-lead-to-destination/) | [solution](https://leetcode.com/problems/all-paths-from-source-lead-to-destination/solution/) | [C++](1001-1500/1059-All-Paths-from-Source-Lead-to-Destination/cpp-1059/) | | | +| | | | | | | +| 1061 | [Lexicographically Smallest Equivalent String](https://leetcode.com/problems/lexicographically-smallest-equivalent-string/description/) | [无] | [C++](1001-1500/1061-Lexicographically-Smallest-Equivalent-String/cpp-1061/) | | | +| 1062 | [Longest Repeating Substring](https://leetcode.com/problems/longest-repeating-substring/) | [无] | [C++](1001-1500/1062-Longest-Repeating-Substring/cpp-1062/) | | | +| | | | | | | +| 1065 | [Index Pairs of a String](https://leetcode.com/problems/index-pairs-of-a-string/description/) | [无] | [C++](1001-1500/1065-Index-Pairs-of-a-String/cpp-1065/) | | | +| 1066 | [Campus Bikes II](https://leetcode.com/problems/campus-bikes-ii/) | [solution](https://leetcode.com/problems/campus-bikes-ii/solutions/1451959/campus-bikes-ii/) | [C++](1001-1500/1066-Campus-Bikes-II/cpp-1066/) | | | +| | | | | | | +| 1072 | [Flip Columns For Maximum Number of Equal Rows](https://leetcode.com/problems/flip-columns-for-maximum-number-of-equal-rows/) | [无] | [C++](1001-1500/1072-Flip-Columns-For-Maximum-Number-of-Equal-Rows/cpp-1072/) | | | +| | | | | | | +| 1074 | [Number of Submatrices That Sum to Target](https://leetcode.com/problems/number-of-submatrices-that-sum-to-target/) | [无] | [C++](1001-1500/1074-Number-of-Submatrices-That-Sum-to-Target/cpp-1074/) | | | +| | | | | | | +| 1078 | [Occurrences After Bigram](https://leetcode.com/problems/occurrences-after-bigram/) | [无] | [C++](1001-1500/1078-Occurrences-After-Bigram/cpp-1078/) | | | +| 1079 | [Letter Tile Possibilities](https://leetcode.com/problems/letter-tile-possibilities/) | [无] | [C++](1001-1500/1079-Letter-Tile-Possibilities/cpp-1079/) | | | +| 1080 | [Insufficient Nodes in Root to Leaf Paths](https://leetcode.com/problems/insufficient-nodes-in-root-to-leaf-paths/) | [无] | [C++](1001-1500/1080-Insufficient-Nodes-in-Root-to-Leaf-Paths/cpp-1080/) | | | +| 1081 | [Smallest Subsequence of Distinct Characters](https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/) | [无] | [C++](1001-1500/1081-Smallest-Subsequence-of-Distinct-Characters/cpp-1081/) | | | +| | | | | | | +| 1084 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| | | | | | | +| 1087 | [Brace Expansion](https://leetcode.com/problems/brace-expansion/) | [无] | [C++](1001-1500/1087-Brace-Expansion/cpp-1087/) | | | +| 1088 | [Confusing Number II](https://leetcode.com/problems/confusing-number-ii/description/) | [无] | [C++](1001-1500/1088-Confusing-Number-II/cpp-1088/) | | | +| 1089 | [Duplicate Zeros](https://leetcode.com/problems/duplicate-zeros/) | [无] | [C++](1001-1500/1089-Duplicate-Zeros/cpp-1089/) | | | +| 1090 | [Largest Values From Labels](https://leetcode.com/problems/largest-values-from-labels/) | [无] | [C++](1001-1500/1090-Largest-Values-From-Labels/cpp-1090/) | | | +| 1091 | [Shortest Path in Binary Matrix](https://leetcode.com/problems/shortest-path-in-binary-matrix/) | [无] | [C++](1001-1500/1091-Shortest-Path-in-Binary-Matrix/cpp-1091/) | | | +| 1092 | [Shortest Common Supersequence](https://leetcode.com/problems/shortest-common-supersequence/) | [无] | [C++](1001-1500/1092-Shortest-Common-Supersequence/cpp-1092/) | | | +| 1093 | [Statistics from a Large Sample](https://leetcode.com/problems/statistics-from-a-large-sample/) | [无] | [C++](1001-1500/1093-Statistics-from-a-Large-Sample/cpp-1093/) | | | +| 1094 | [Car Pooling](https://leetcode.com/problems/car-pooling/) | [无] | [C++](1001-1500/1094-Car-Pooling/cpp-1094/) | | | +| 1095 | [Find in Mountain Array](https://leetcode.com/problems/find-in-mountain-array/) | [无] | [C++](1001-1500/1095-Find-in-Mountain-Array/cpp-1095/) | | | +| 1096 | [Brace Expansion II](https://leetcode.com/problems/brace-expansion-ii/) | [无]
[缺:非递归算法] | [C++](1001-1500/1096-Brace-Expansion-II/cpp-1096/) | | | +| | | | | | | +| 1099 | [Two Sum Less Than K](https://leetcode.com/problems/two-sum-less-than-k/) | [无] | [C++](1001-1500/1099-Two-Sum-Less-Than-K/cpp-1099/) | | | +| 1100 | [Find K-Length Substrings With No Repeated Characters](https://leetcode.com/problems/find-k-length-substrings-with-no-repeated-characters/) | [无] | [C++](1001-1500/1100-Find-K-Length-Substrings-With-No-Repeated-Characters/cpp-1100/) | | | +| 1101 | [The Earliest Moment When Everyone Become Friends](https://leetcode.com/problems/the-earliest-moment-when-everyone-become-friends/) | [无] | [C++](1001-1500/1101-The-Earliest-Moment-When-Everyone-Become-Friends/cpp-1101/) | | | +| 1102 | [Path With Maximum Minimum Value](https://leetcode.com/problems/path-with-maximum-minimum-value/) | [无]
[缺:并查集] | [C++](1001-1500/1102-Path-With-Maximum-Minimum-Value/cpp-1102/) | | | +| 1103 | [Distribute Candies to People](https://leetcode.com/problems/distribute-candies-to-people/) | [solution](https://leetcode.com/problems/distribute-candies-to-people/solution/) | [C++](1001-1500/1103-Distribute-Candies-to-People/cpp-1103/) | | | +| 1104 | [Path In Zigzag Labelled Binary Tree](https://leetcode.com/problems/path-in-zigzag-labelled-binary-tree/) | [无] | [C++](1001-1500/1104-Path-In-Zigzag-Labelled-Binary-Tree/cpp-1104/) | | | +| 1105 | [Filling Bookcase Shelves](https://leetcode.com/problems/filling-bookcase-shelves/) | [无] | [C++](1001-1500/1105-Filling-Bookcase-Shelves/cpp-1105/) | | | +| 1106 | [Parsing A Boolean Expression](https://leetcode.com/problems/parsing-a-boolean-expression/) | [无]
[缺:非递归算法] | [C++](1001-1500/1106-Parsing-A-Boolean-Expression/cpp-1106/) | | | +| | | | | | | +| 1108 | [Defanging an IP Address](https://leetcode.com/problems/defanging-an-ip-address/) | [无] | [C++](1001-1500/1108-Defanging-an-IP-Address/cpp-1108/) | | | +| 1109 | [Corporate Flight Bookings](https://leetcode.com/problems/corporate-flight-bookings/) | [无] | [C++](1001-1500/1109-Corporate-Flight-Bookings/cpp-1009/) | | | +| 1110 | [Delete Nodes And Return Forest](https://leetcode.com/problems/delete-nodes-and-return-forest/) | [无] | [C++](1001-1500/1110-Delete-Nodes-And-Return-Forest/cpp-1110/) | | | +| 1111 | [Maximum Nesting Depth of Two Valid Parentheses Strings](https://leetcode.com/problems/maximum-nesting-depth-of-two-valid-parentheses-strings/) | [无] | [C++](1001-1500/1111-Maximum-Nesting-Depth-of-Two-Valid-Parentheses-Strings/cpp-1111/) | | | +| 1112 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| | | | | | | +| 1118 | [Number of Days in a Month](https://leetcode.com/problems/number-of-days-in-a-month/) | [无] | [C++](1001-1500/1118-Number-of-Days-in-a-Month/cpp-1118/) | | | +| 1119 | [Remove Vowels from a String](https://leetcode.com/problems/remove-vowels-from-a-string/) | [无] | [C++](1001-1500/1119-Remove-Vowels-from-a-String/cpp-1119/) | | | +| 1120 | [Maximum Average Subtree](https://leetcode.com/problems/maximum-average-subtree/) | [无] | [C++](1001-1500/1120-Maximum-Average-Subtree/cpp-1120/) | | | +| 1121 | [Divide Array Into Increasing Sequences](https://leetcode.com/problems/divide-array-into-increasing-sequences/) | [无] | [C++](1001-1500/1121-Divide-Array-Into-Increasing-Sequences/cpp-1121/) | | | +| | | | | | | +| 1124 | [Longest Well-Performing Interval](https://leetcode.com/problems/longest-well-performing-interval/) | [无] | [C++](1001-1500/1124-Longest-Well-Performing-Interval/cpp-1124/) | | | +| | | | | | | +| 1128 | [Number of Equivalent Domino Pairs](https://leetcode.com/problems/number-of-equivalent-domino-pairs/) | [无] | [C++](1001-1500/1128-Number-of-Equivalent-Domino-Pairs/cpp-1128/) | | | +| 1129 | [Shortest Path with Alternating Colors](https://leetcode.com/problems/shortest-path-with-alternating-colors/) | [无] | [C++](1001-1500/1129-Shortest-Path-with-Alternating-Colors/cpp-1129/) | | | +| 1130 | [Minimum Cost Tree From Leaf Values](https://leetcode.com/problems/minimum-cost-tree-from-leaf-values/) | [无] | [C++](1001-1500/1130-Minimum-Cost-Tree-From-Leaf-Values/cpp-1130/) | | | +| 1131 | [Maximum of Absolute Value Expression](https://leetcode.com/problems/maximum-of-absolute-value-expression/) | [无] | [C++](1001-1500/1131-Maximum-of-Absolute-Value-Expression/cpp-1131/) | | | +| | | | | | | +| 1133 | [Largest Unique Number](https://leetcode.com/problems/largest-unique-number/) | [无] | [C++](1001-1500/1133-Largest-Unique-Number/cpp-1133/) | | | +| 1134 | [Armstrong Number](https://leetcode.com/problems/armstrong-number/) | [无] | [C++](1001-1500/1134-Armstrong-Number/cpp-1134/) | | | +| 1135 | [Connecting Cities With Minimum Cost](https://leetcode.com/problems/connecting-cities-with-minimum-cost/) | [无] | [C++](1001-1500/1135-Connecting-Cities-With-Minimum-Cost/cpp-1135/) | | | +| 1136 | [Parallel Courses](https://leetcode.com/problems/parallel-courses/) | [无]
[缺:后序遍历拓扑排序] | [C++](1001-1500/1136-Parallel-Courses/cpp-1136/) | | | +| 1137 | [N-th Tribonacci Number](https://leetcode.com/problems/n-th-tribonacci-number/) | [无] | [C++](1001-1500/1137-N-th-Tribonacci-Number/cpp-1137/) | | | +| 1138 | [Alphabet Board Path](https://leetcode.com/problems/alphabet-board-path/) | [无] | [C++](1001-1500/1138-Alphabet-Board-Path/cpp-1138/) | | | +| 1139 | [Largest 1-Bordered Square](https://leetcode.com/problems/largest-1-bordered-square/) | [无] | [C++](1001-1500/1139-Largest-1-Bordered-Square/cpp-1139/) | | | +| 1140 | [Stone Game II](https://leetcode.com/problems/stone-game-ii/) | [无] | [C++](1001-1500/1140-Stone-Game-II/cpp-1140/) | | | +| 1141 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| | | | | | | +| 1143 | [Longest Common Subsequence](https://leetcode.com/problems/longest-common-subsequence/) | [无] | [C++](1001-1500/1143-Longest-Common-Subsequence/cpp-1143/) | | | +| 1144 | [Decrease Elements To Make Array Zigzag](https://leetcode.com/problems/decrease-elements-to-make-array-zigzag/) | [无] | [C++](1001-1500/1144-Decrease-Elements-To-Make-Array-Zigzag/cpp-1144/) | | | +| 1145 | [Binary Tree Coloring Game](https://leetcode.com/problems/binary-tree-coloring-game/) | [无] | [C++](1001-1500/1145-Binary-Tree-Coloring-Game/cpp-1145/) | | | +| 1146 | [Snapshot Array](https://leetcode.com/problems/snapshot-array/) | [无] | [C++](1001-1500/1146-Snapshot-Array/cpp-1146/) | | | +| 1147 | [Longest Chunked Palindrome Decomposition](https://leetcode.com/problems/longest-chunked-palindrome-decomposition/) | [无] | [C++](1001-1500/1147-Longest-Chunked-Palindrome-Decomposition/cpp-1147/) | | | +| 1148 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| | | | | | | +| 1150 | [Check If a Number Is Majority Element in a Sorted Array](https://leetcode.com/problems/is-a-a-majority-element/) | [无] | [C++](1001-1500/1150-Check-If-a-Number-Is-Majority-Element-in-a-Sorted-Array/cpp-1150/) | | | +| 1151 | [Minimum Swaps to Group All 1's Together](https://leetcode.com/problems/minimum-swaps-to-group-all-1s-together/) | [无] | [C++](1001-1500/1151-Minimum-Swaps-to-Group-All-1s-Together/cpp-1151/) | | | +| 1152 | [Analyze User Website Visit Pattern](https://leetcode.com/problems/analyse-user-website-visit-pattern/) | [无] | [C++](1001-1500/1152-Analyze-User-Website-Visit-Pattern/cpp-1152/) | | | +| 1153 | [String Transforms Into Another String](https://leetcode.com/problems/string-transforms-into-another-string/) | [无] | [C++](1001-1500/1153-String-Transforms-Into-Another-String/cpp-1153/) | | | +| 1154 | [Day of the Year](https://leetcode.com/problems/ordinal-number-of-date/) | [无] | [C++](1001-1500/1154-Day-of-the-Year/cpp-1154/) | | | +| 1155 | [Number of Dice Rolls With Target Sum](https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/) | [无]
[缺:空间优化] | [C++](1001-1500/1155-Number-of-Dice-Rolls-With-Target-Sum/cpp-1155/) | | | +| 1156 | [Swap For Longest Repeated Character Substring](https://leetcode.com/problems/swap-for-maximum-repeated-substring/) | [无] | [C++](1001-1500/1156-Swap-For-Longest-Repeated-Character-Substring/cpp-1156/) | | | +| 1157 | [Online Majority Element In Subarray](https://leetcode.com/problems/online-majority-element-in-subarray/) | [无] | [C++](1001-1500/1157-Online-Majority-Element-In-Subarray/cpp-1157/) | | | +| 1158 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| | | | | | | +| 1160 | [Find Words That Can Be Formed by Characters](https://leetcode.com/problems/find-words-that-can-be-formed-by-characters/) | [无] | [C++](1001-1500/1160-Find-Words-That-Can-Be-Formed-by-Characters/cpp-1160/) | | | +| 1161 | [Maximum Level Sum of a Binary Tree](https://leetcode.com/problems/maximum-level-sum-of-a-binary-tree/) | [无] | [C++](1001-1500/1161-Maximum-Level-Sum-of-a-Binary-Tree/cpp-1161/) | | | +| 1162 | [As Far from Land as Possible](https://leetcode.com/problems/as-far-from-land-as-possible/) | [无] | [C++](1001-1500/1162-As-Far-from-Land-as-Possible/cpp-1162/) | | | +| 1163 | [Last Substring in Lexicographical Order](https://leetcode.com/problems/last-substring-in-lexicographical-order/) | [无] | [C++](1001-1500/1163-Last-Substring-in-Lexicographical-Order/cpp-1163/) | | | +| | | | | | | +| 1165 | [Single-Row Keyboard](https://leetcode.com/problems/single-row-keyboard/) | [无] | [C++](1001-1500/1165-Single-Row-Keyboard/cpp-1165/) | | | +| 1166 | [Design File System](https://leetcode.com/problems/design-file-system/) | [无] | [C++](1001-1500/1166-Design-File-System/cpp-1166/) | | | +| 1167 | [Minimum Cost to Connect Sticks](https://leetcode.com/problems/minimum-cost-to-connect-sticks/) | [无] | [C++](1001-1500/1167-Minimum-Cost-to-Connect-Sticks/cpp-1167/) | | | +| 1168 | [Optimize Water Distribution in a Village](https://leetcode.com/problems/optimize-water-distribution-in-a-village/) | [无] | [C++](1001-1500/1168-Optimize-Water-Distribution-in-a-Village/cpp-1168/) | | | +| 1169 | [Invalid Transactions](https://leetcode.com/problems/invalid-transactions/) | [无] | [C++](1001-1500/1169-Invalid-Transactions/cpp-1169/) | | | +| 1170 | [Compare Strings by Frequency of the Smallest Character](https://leetcode.com/problems/compare-strings-by-frequency-of-the-smallest-character/) | [无] | [C++](1001-1500/1170-Compare-Strings-by-Frequency-of-the-Smallest-Character/cpp-1170/) | | | +| 1171 | [Remove Zero Sum Consecutive Nodes from Linked List](https://leetcode.com/problems/remove-zero-sum-consecutive-nodes-from-linked-list/) | [无] | [C++](1001-1500/1171-Remove-Zero-Sum-Consecutive-Nodes-from-Linked-List/cpp-1171/) | | | +| 1172 | [Dinner Plate Stacks](https://leetcode.com/problems/dinner-plate-stacks/) | [无] | [C++](1001-1500/1172-Dinner-Plate-Stacks/cpp-1172/) | | | +| 1173 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| | | | | | | +| 1175 | [Prime Arrangements](https://leetcode.com/problems/prime-arrangements/) | [无] | [C++](1001-1500/1175-Prime-Arrangements/) | | | +| 1176 | [Diet Plan Performance](https://leetcode.com/problems/diet-plan-performance/) | [无] | [C++](1001-1500/1176-Diet-Plan-Performance/cpp-1176/) | | | +| 1177 | [Can Make Palindrome from Substring](https://leetcode.com/problems/can-make-palindrome-from-substring/) | [无] | [C++](1001-1500/1177-Can-Make-Palindrome-from-Substring/cpp-1177/) | | | +| 1178 | [Number of Valid Words for Each Puzzle](https://leetcode.com/problems/number-of-valid-words-for-each-puzzle/) | [无] | [C++](1001-1500/1178-Number-of-Valid-Words-for-Each-Puzzle/cpp-1178/) | | | +| | | | | | | +| 1180 | [Count Substrings with Only One Distinct Letter](https://leetcode.com/problems/count-substrings-with-only-one-distinct-letter/) | [无] | [C++](1001-1500/1180-Count-Substrings-with-Only-One-Distinct-Letter/cpp-1180/) | | | +| 1181 | [Before and After Puzzle](https://leetcode.com/problems/before-and-after-puzzle/) | [无] | [C++](1001-1500/1181-Before-and-After-Puzzle/cpp-1181/) | | | +| 1182 | [Shortest Distance to Target Color](https://leetcode.com/problems/shortest-distance-to-target-color/) | [无] | [C++](1001-1500/1182-Shortest-Distance-to-Target-Color/cpp-1182/) | | | +| 1183 | [Maximum Number of Ones](https://leetcode.com/problems/maximum-number-of-ones/) | [无] | [C++](1001-1500/1183-Maximum-Number-of-Ones/cpp-1183/) | | | +| 1184 | [Distance Between Bus Stops](https://leetcode.com/problems/distance-between-bus-stops/) | [无] | [C++](1001-1500/1184-Distance-Between-Bus-Stops/cpp-1184/) | | | +| 1185 | [Day of the Week](https://leetcode.com/problems/day-of-the-week/) | [无] | [C++](1001-1500/1185-Day-of-the-Week/cpp-1185/) | | | +| 1186 | [Maximum Subarray Sum with One Deletion](https://leetcode.com/problems/maximum-subarray-sum-with-one-deletion/) | [无] | [C++](1001-1500/1186-Maximum-Subarray-Sum-with-One-Deletion/cpp-1186/) | | | +| 1187 | [Make Array Strictly Increasing](https://leetcode.com/problems/make-array-strictly-increasing/) | [无]
[缺:动态规划] | [C++](1001-1500/1187-Make-Array-Strictly-Increasing/cpp-1187/) | | | +| | | | | | | +| 1189 | [Maximum Number of Balloons](https://leetcode.com/problems/maximum-number-of-balloons/) | [无] | [C++](1001-1500/1189-Maximum-Number-of-Balloons/cpp-1189/) | | | +| 1190 | [Reverse Substrings Between Each Pair of Parentheses](https://leetcode.com/problems/reverse-substrings-between-each-pair-of-parentheses/) | [无] | [C++](1001-1500/1190-Reverse-Substrings-Between-Each-Pair-of-Parentheses/cpp-1190/) | | | +| 1191 | [K-Concatenation Maximum Sum](https://leetcode.com/problems/k-concatenation-maximum-sum/) | [无] | [C++](1001-1500/1191-K-Concatenation-Maximum-Sum/cpp-1191/) | | | +| 1192 | [Critical Connections in a Network](https://leetcode.com/problems/critical-connections-in-a-network/) | [无] | [C++](1001-1500/1192-Critical-Connections-in-a-Network/cpp-1192/) | | | +| | | | | | | +| 1196 | [How Many Apples Can You Put into the Basket](https://leetcode.com/problems/how-many-apples-can-you-put-into-the-basket/) | [无] | [C++](1001-1500/1196-How-Many-Apples-Can-You-Put-into-the-Basket/cpp-1196/) | | | +| 1197 | [Minimum Knight Moves](https://leetcode.com/problems/minimum-knight-moves/) | [无] | [C++](1001-1500/1197-Minimum-Knight-Moves/cpp-1197/cpp-1197/) | | | +| 1198 | [Find Smallest Common Element in All Rows](https://leetcode.com/problems/find-smallest-common-element-in-all-rows/) | [无] | [C++](1001-1500/1198-Find-Smallest-Common-Element-in-All-Rows/cpp-1198/) | | | +| 1199 | [Minimum Time to Build Blocks](https://leetcode.com/problems/minimum-time-to-build-blocks/) | [无] | [C++](1001-1500/1199-Minimum-Time-to-Build-Blocks/cpp-1199/) | | | +| 1200 | [Minimum Absolute Difference](https://leetcode.com/problems/minimum-absolute-difference/) | [无] | [C++](1001-1500/1200-Minimum-Absolute-Difference/cpp-1200/) | | | +| 1201 | [Ugly Number III](https://leetcode.com/problems/ugly-number-iii/) | [无] | [C++](1001-1500/1201-Ugly-Number-III/cpp-1201/) | | | +| 1202 | [Smallest String With Swaps](https://leetcode.com/problems/smallest-string-with-swaps/) | [无] | [C++](1001-1500/1202-Smallest-String-With-Swaps/cpp-1202/) | | | +| 1203 | [Sort Items by Groups Respecting Dependencies](https://leetcode.com/problems/sort-items-by-groups-respecting-dependencies/) | [无] | [C++](1001-1500/1203-Sort-Items-by-Groups-Respecting-Dependencies/cpp-1203/) | | | +| | | | | | | +| 1207 | [Unique Number of Occurrences](https://leetcode.com/problems/unique-number-of-occurrences/) | [无] | [C++](1001-1500/1207-Unique-Number-of-Occurrences/cpp-1207/) | | | +| 1208 | [Get Equal Substrings Within Budget](https://leetcode.com/problems/get-equal-substrings-within-budget/) | [无] | [C++](1001-1500/1208-Get-Equal-Substrings-Within-Budget/cpp-1208/) | | | +| 1209 | [Remove All Adjacent Duplicates in String II](https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string-ii/) | [无] | [C++](1001-1500/1209-Remove-All-Adjacent-Duplicates-in-String-II/cpp-1209/) | | | +| 1210 | [Minimum Moves to Reach Target with Rotations](https://leetcode.com/problems/minimum-moves-to-reach-target-with-rotations/) | [无] | [C++](1001-1500/1210-Minimum-Moves-to-Reach-Target-with-Rotations/cpp-1210/) | | | +| 1211 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| | | | | | | +| 1213 | [Intersection of Three Sorted Arrays](https://leetcode.com/problems/intersection-of-three-sorted-arrays/) | [无] | [C++](1001-1500/1213-Intersection-of-Three-Sorted-Arrays/cpp-1213/) | | | +| 1214 | [Two Sum BSTs](https://leetcode.com/problems/two-sum-bsts/) | [无] | [C++](1001-1500/1214-Two-Sum-BSTs/cpp-1214/) | | | +| 1215 | [Stepping Numbers](https://leetcode.com/problems/stepping-numbers/) | [无] | [C++](1001-1500/1215-Stepping-Numbers/cpp-1215/) | | | +| 1216 | [Valid Palindrome III](https://leetcode.com/problems/valid-palindrome-iii/) | [无] | [C++](1001-1500/1216-Valid-Palindrome-III/cpp-1216/) | | | +| 1217 | [Play with Chips](https://leetcode.com/problems/play-with-chips/) | [无] | [C++](1001-1500/1217-Play-with-Chips/cpp-1217/) | | | +| 1218 | [Longest Arithmetic Subsequence of Given Difference](https://leetcode.com/problems/longest-arithmetic-subsequence-of-given-difference/) | [无] | [C++](1001-1500/1218-Longest-Arithmetic-Subsequence-of-Given-Difference/cpp-1218/) | | | +| 1219 | [Path with Maximum Gold](https://leetcode.com/problems/path-with-maximum-gold/) | [无] | [C++](1001-1500/1219-Path-with-Maximum-Gold/cpp-1219/) | | | +| 1220 | [Count Vowels Permutation](https://leetcode.com/problems/count-vowels-permutation/) | [无] | [C++](1001-1500/1220-Count-Vowels-Permutation/cpp-1220/) | | | +| 1221 | [Split a String in Balanced Strings](https://leetcode.com/problems/split-a-string-in-balanced-strings/) | [无] | [C++](1001-1500/1221-Split-a-String-in-Balanced-Strings/cpp-1221/) | | | +| 1222 | [Queens That Can Attack the King](https://leetcode.com/problems/queens-that-can-attack-the-king/) | [无] | [C++](1001-1500/1222-Queens-That-Can-Attack-the-King/cpp-1222/) | | | +| 1223 | [Dice Roll Simulation](https://leetcode.com/problems/dice-roll-simulation/) | [无] | [C++](1001-1500/1223-Dice-Roll-Simulation/cpp-1223/) | | | +| 1224 | [Maximum Equal Frequency](https://leetcode.com/problems/maximum-equal-frequency/) | [无] | [C++](1001-1500/1224-Maximum-Equal-Frequency/cpp-1224/) | | | +| | | | | | | +| 1228 | [Missing Number In Arithmetic Progression](https://leetcode.com/problems/missing-number-in-arithmetic-progression/) | [无] | [C++](1001-1500/1228-Missing-Number-In-Arithmetic-Progression/cpp-1228/) | | | +| 1229 | [Meeting Scheduler](https://leetcode.com/problems/meeting-scheduler/) | [无] | [C++](1001-1500/1229-Meeting-Scheduler/cpp-1229/) | | | +| 1230 | [Toss Strange Coins](https://leetcode.com/problems/toss-strange-coins/) | [无] | [C++](1001-1500/1230-Toss-Strange-Coins/cpp-1230/) | | | +| 1231 | [Divide Chocolate](https://leetcode.com/problems/divide-chocolate/) | [无] | [C++](1001-1500/1231-Divide-Chocolate/cpp-1231/) | | | +| 1232 | [Check If It Is a Straight Line](https://leetcode.com/problems/check-if-it-is-a-straight-line/) | [无] | [C++](1001-1500/1232-Check-If-It-Is-a-Straight-Line/cpp-1232/) | | | +| 1233 | [Remove Sub-Folders from the Filesystem](https://leetcode.com/problems/remove-sub-folders-from-the-filesystem/) | [无] | [C++](1001-1500/1233-Remove-Sub-Folders-from-the-Filesystem/cpp-1233/) | | | +| 1234 | [Replace the Substring for Balanced String](https://leetcode.com/problems/replace-the-substring-for-balanced-string/) | [无] | [C++](1001-1500/1234-Replace-the-Substring-for-Balanced-String/cpp-1234/) | | | +| 1235 | [Maximum Profit in Job Scheduling](https://leetcode.com/problems/maximum-profit-in-job-scheduling/) | [无] | [C++](1001-1500/1235-Maximum-Profit-in-Job-Scheduling/cpp-1235/) | | | +| 1236 | [Web Crawler](https://leetcode.com/problems/web-crawler/description/) | [无] | [C++](1001-1500/1236-Web-Crawler/cpp-1236/) | | | +| 1237 | [Find Positive Integer Solution for a Given Equation](https://leetcode.com/problems/find-positive-integer-solution-for-a-given-equation/) | [无] | [C++](1001-1500/1237-Find-Positive-Integer-Solution-for-a-Given-Equation/cpp-1237/) | | | +| 1238 | [Circular Permutation in Binary Representation](https://leetcode.com/problems/circular-permutation-in-binary-representation/) | [无] | [C++](1001-1500/1238-Circular-Permutation-in-Binary-Representation/cpp-1238/) | | | +| 1239 | [Maximum Length of a Concatenated String with Unique Characters](https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/) | [无] | [C++](1001-1500/1239-Maximum-Length-of-a-Concatenated-String-with-Unique-Characters/cpp-1239/) | | | +| 1240 | [Tiling a Rectangle with the Fewest Squares](https://leetcode.com/problems/tiling-a-rectangle-with-the-fewest-squares/) | [无] | [C++](1001-1500/1240-Tiling-a-Rectangle-with-the-Fewest-Squares/cpp-1240/) | | | +| | | | | | | +| 1243 | [Array Transformation](https://leetcode.com/problems/array-transformation/) | [无] | [C++](1001-1500/1243-Array-Transformation/cpp-1243/) | | | +| 1244 | [Design A Leaderboard](https://leetcode.com/problems/design-a-leaderboard/) | [无] | [C++](1001-1500/1244-Design-A-Leaderboard/cpp-1244/) | | | +| 1245 | [Tree Diameter](https://leetcode.com/problems/tree-diameter/) | [无] | [C++](1001-1500/1245-Tree-Diameter/cpp-1245/) | | | +| | | | | | | +| 1247 | [Minimum Swaps to Make Strings Equal](https://leetcode.com/problems/minimum-swaps-to-make-strings-equal/) | [无] | [C++](1001-1500/1247-Minimum-Swaps-to-Make-Strings-Equal/cpp-1247/) | | | +| 1248 | [Count Number of Nice Subarrays](https://leetcode.com/problems/count-number-of-nice-subarrays/) | [无] | [C++](1001-1500/1248-Count-Number-of-Nice-Subarrays/cpp-1248/) | [Java](1001-1500/1248-Count-Number-of-Nice-Subarrays/java-1248/) | | +| 1249 | [Minimum Remove to Make Valid Parentheses](https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/) | [solution](https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/solution/) | [C++](1001-1500/1249-Minimum-Remove-to-Make-Valid-Parentheses/cpp-1249/) | | | +| 1250 | [Check If It Is a Good Array](https://leetcode.com/problems/check-if-it-is-a-good-array/description/) | [无] | [C++](1001-1500/1250-Check-If-It-Is-a-Good-Array/cpp-1250/) | | | +| 1251 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1252 | [Cells with Odd Values in a Matrix](https://leetcode.com/problems/cells-with-odd-values-in-a-matrix/) | [无] | [C++](1001-1500/1252-Cells-with-Odd-Values-in-a-Matrix/cpp-1252/) | | | +| 1253 | [Reconstruct a 2-Row Binary Matrix](https://leetcode.com/problems/reconstruct-a-2-row-binary-matrix/description/) | [无] | [C++](1001-1500/1253-Reconstruct-a-2-Row-Binary-Matrix/cpp-1253/) | | | +| 1254 | [Number of Closed Islands](https://leetcode.com/problems/number-of-closed-islands/description/) | [无] | [C++](1001-1500/1254-Number-of-Closed-Islands/cpp-1254/) | | | +| 1255 | [Maximum Score Words Formed by Letters](https://leetcode.com/problems/maximum-score-words-formed-by-letters/description/) | [无] | [C++](1001-1500/1255-Maximum-Score-Words-Formed-by-Letters/cpp-1255/) | | | +| | | | | | | +| 1259 | [Handshakes That Don't Cross](https://leetcode.com/problems/handshakes-that-dont-cross/description/) | [无] | [C++](1001-1500/1259-Handshakes-That-Dont-Cross/cpp-1259/) | | | +| 1260 | [Shift 2D Grid](https://leetcode.com/problems/shift-2d-grid/) | [solution](https://leetcode.com/problems/shift-2d-grid/solution/) | [C++](1001-1500/1260-Shift-2D-Grid/cpp-1260/) | | | +| 1261 | [Find Elements in a Contaminated Binary Tree](https://leetcode.com/contest/weekly-contest-163/problems/find-elements-in-a-contaminated-binary-tree/) | [C++](1001-1500/1261-Find-Elements-in-a-Contaminated-Binary-Tree/cpp-1261/) | | | | +| 1262 | [Greatest Sum Divisible by Three](https://leetcode.com/problems/greatest-sum-divisible-by-three/) | [无] | [C++](1001-1500/1262-Greatest-Sum-Divisible-by-Three/cpp-1262/) | | | +| 1263 | [Minimum Moves to Move a Box to Their Target Location](https://leetcode.com/problems/minimum-moves-to-move-a-box-to-their-target-location/) | [无] | [C++](1001-1500/1263-Minimum-Moves-to-Move-a-Box-to-Their-Target-Location/cpp-1263/) | | | +| 1264 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| | | | | | | +| 1272 | [Remove Interval](https://leetcode.com/problems/remove-interval/) | [无] | [C++](1001-1500/1272-Remove-Interval/cpp-1272/) | | | +| | | | | | | +| 1275 | [Find Winner on a Tic Tac Toe Game](https://leetcode.com/problems/find-winner-on-a-tic-tac-toe-game/) | [无] | [C++](1001-1500/1275-Find-Winner-on-a-Tic-Tac-Toe-Game/cpp-1275/) | | | +| | | | | | | +| 1277 | [Count Square Submatrices with All Ones](https://leetcode.com/problems/count-square-submatrices-with-all-ones/) | [题解](https://leetcode-cn.com/problems/count-square-submatrices-with-all-ones/solution/tong-ji-quan-wei-1-de-zheng-fang-xing-zi-ju-zhen-2/) | [C++](1001-1500/1277-Count-Square-Submatrices-with-All-Ones/cpp-1277/) | | | +| 1278 | [Palindrome Partitioning III](https://leetcode.com/problems/palindrome-partitioning-iii/) | [无] | [C++](1001-1500/1278-Palindrome-Partitioning-III/cpp-1278/) | | | +| | | | | | | +| 1280 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1281 | [Subtract the Product and Sum of Digits of an Integer](https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/) | [无] | [C++](1001-1500/1281-Subtract-the-Product-and-Sum-of-Digits-of-an-Integer/cpp-1281/) | | | +| 1282 | [Group the People Given the Group Size They Belong To](https://leetcode.com/problems/group-the-people-given-the-group-size-they-belong-to/) | [无] | [C++](1001-1500/1282-Group-the-People-Given-the-Group-Size-They-Belong-To/cpp-1282/) | | | +| | | | | | | +| 1286 | [Iterator for Combination](https://leetcode.com/problems/iterator-for-combination/) | [solution](https://leetcode.com/problems/iterator-for-combination/solution/) | [C++](1001-1500/1286-Iterator-for-Combination/cpp-1286/) | | | +| | | | | | | +| 1288 | [Remove Covered Intervals](https://leetcode.com/problems/remove-covered-intervals/) | [solution](https://leetcode.com/problems/remove-covered-intervals/solution/) | [C++](1001-1500/1288-Remove-Covered-Intervals/cpp-1288/) | | | +| 1289 | [Minimum Falling Path Sum II](https://leetcode.com/problems/minimum-falling-path-sum-ii/) | [无] | [C++](1001-1500/1289-Minimum-Falling-Path-Sum-II/cpp-1289/) | | | +| 1290 | [Convert Binary Number in a Linked List to Integer](https://leetcode.com/problems/convert-binary-number-in-a-linked-list-to-integer/) | [solution](https://leetcode.com/problems/convert-binary-number-in-a-linked-list-to-integer/solution/) | [C++](1001-1500/1290-Convert-Binary-Number-in-a-Linked-List-to-Integer/cpp-1290/) | | | +| 1291 | [Sequential Digits](https://leetcode.com/problems/sequential-digits/) | [solution](https://leetcode.com/problems/sequential-digits/solution/) | [C++](1001-1500/1291-Sequential-Digits/cpp-1291/) | | | +| | | | | | | +| 1293 | [Shortest Path in a Grid with Obstacles Elimination](https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/) | [solution](https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/) | [C++](1001-1500/1293-Shortest-Path-in-a-Grid-with-Obstacles-Elimination/cpp-1293/) | | | +| | | | | | | +| 1302 | [Deepest Leaves Sum](https://leetcode.com/problems/deepest-leaves-sum/) | [solution](https://leetcode.com/problems/deepest-leaves-sum/solution/) | [C++](1302-Deepest-Leaves-Sum/cpp-1302/) | | | +| 1303 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1304 | [Find N Unique Integers Sum up to Zero](https://leetcode.com/problems/find-n-unique-integers-sum-up-to-zero/) | [无] | [C++](1001-1500/1304-Find-N-Unique-Integers-Sum-up-to-Zero/cpp-1304/) | | | +| 1305 | [All Elements in Two Binary Search Trees](https://leetcode.com/problems/all-elements-in-two-binary-search-trees/) | [无] | [C++](1001-1500/1305-All-Elements-in-Two-Binary-Search-Trees/cpp-1305/) | | | +| 1306 | [Jump Game III](https://leetcode.com/problems/jump-game-iii/) | [无] | [C++](1001-1500/1306-Jump-Game-III/cpp-1306/) | | | +| 1307 | [Verbal Arithmetic Puzzle](https://leetcode.com/problems/verbal-arithmetic-puzzle/) | [无] | [C++](1001-1500/1307-Verbal-Arithmetic-Puzzle/cpp-1307/) | | | +| | | | | | | +| 1309 | [Decrypt String from Alphabet to Integer Mapping](https://leetcode.com/problems/decrypt-string-from-alphabet-to-integer-mapping/) | [无] | [C++](1001-1500/1309-Decrypt-String-from-Alphabet-to-Integer-Mapping/cpp-1309/) | | | +| 1310 | [XOR Queries of a Subarray](https://leetcode.com/problems/xor-queries-of-a-subarray/) | [无] | [C++](1001-1500/1310-XOR-Queries-of-a-Subarray/cpp-1310/) | | | +| 1311 | [Get Watched Videos by Your Friends](https://leetcode.com/problems/get-watched-videos-by-your-friends/) | [无] | [C++](1001-1500/1311-Get-Watched-Videos-by-Your-Friends/cpp-1311/) | | | +| 1312 | [Minimum Insertion Steps to Make a String Palindrome](https://leetcode.com/problems/minimum-insertion-steps-to-make-a-string-palindrome/) | [无] | [C++](1001-1500/1312-Minimum-Insertion-Steps-to-Make-a-String-Palindrome/cpp-1312/) | | | +| | | | | | | +| 1317 | [Convert Integer to the Sum of Two No-Zero Integers](https://leetcode.com/problems/convert-integer-to-the-sum-of-two-no-zero-integers/) | [无] | [C++](1001-1500/1317-Convert-Integer-to-the-Sum-of-Two-No-Zero-Integers/cpp-1317/) | | | +| 1318 | [Minimum Flips to Make a OR b Equal to c](https://leetcode.com/problems/minimum-flips-to-make-a-or-b-equal-to-c/) | [无] | [C++](1001-1500/1318-Minimum-Flips-to-Make-a-OR-b-Equal-to-c/cpp-1318/) | | | +| 1319 | [Number of Operations to Make Network Connected](https://leetcode.com/problems/number-of-operations-to-make-network-connected/) | [无] | [C++](1001-1500/1319-Number-of-Operations-to-Make-Network-Connected/cpp-1319/) | | | +| | | | | | | +| 1323 | [Maximum 69 Number](https://leetcode.com/problems/maximum-69-number/description/) | [无] | [C++](1001-1500/1323-Maximum-69-Number/cpp-1323/) | | | +| | | | | | | +| 1326 | [Minimum Number of Taps to Open to Water a Garden](https://leetcode.com/problems/minimum-number-of-taps-to-open-to-water-a-garden/description/) | [无] | [C++](1001-1500/1326-Minimum-Number-of-Taps-to-Open-to-Water-a-Garden/cpp-1326/) | | | +| | | | | | | +| 1328 | [Break a Palindrome](https://leetcode.com/problems/break-a-palindrome/) | [solution](https://leetcode.com/problems/break-a-palindrome/solution/) | [C++](1001-1500/1328-Break-a-Palindrome/cpp-1328/) | | | +| 1329 | [Sort the Matrix Diagonally](https://leetcode.com/problems/sort-the-matrix-diagonally/) | [solution](https://leetcode.com/problems/sort-the-matrix-diagonally/solution/) | [C++](1001-1500/1329-Sort-the-Matrix-Diagonally/cpp-1329/) | | | +| 1330 | [Reverse Subarray To Maximize Array Value](https://leetcode.com/problems/reverse-subarray-to-maximize-array-value/description/) | [无] | [C++](1001-1500/1330-Reverse-Subarray-To-Maximize-Array-Value/cpp-1330/) | | | +| 1331 | [Rank Transform of an Array](https://leetcode.com/problems/rank-transform-of-an-array/) | [无] | [C++](1001-1500/1331-Rank-Transform-of-an-Array/cpp-1331/) | | | +| 1332 | [Remove Palindromic Subsequences](https://leetcode.com/problems/remove-palindromic-subsequences/) | [solution](https://leetcode.com/problems/remove-palindromic-subsequences/solution/) | [C++](1001-1500/1332-Remove-Palindromic-Subsequences/cpp-1332/) | | | +| 1333 | [Filter Restaurants by Vegan-Friendly, Price and Distance](https://leetcode.com/problems/filter-restaurants-by-vegan-friendly-price-and-distance/) | [无] | [C++](1001-1500/1333-Filter-Restaurants-by-Vegan-Friendly-Price-and-Distance/cpp-1333/) | | | +| 1334 | [Find the City With the Smallest Number of Neighbors at a Threshold Distance](https://leetcode.com/problems/find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/) | [无] | [C++](1001-1500/1334-Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance/cpp-1334/) | | | +| 1335 | [Minimum Difficulty of a Job Schedule](https://leetcode.com/problems/minimum-difficulty-of-a-job-schedule/) | [无] | [C++](1001-1500/1335-Minimum-Difficulty-of-a-Job-Schedule/cpp-1335/) | | | +| | | | | | | +| 1337 | [The K Weakest Rows in a Matrix](https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/) | [solution](https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/solution/) | [C++](1001-1500/1337-The-K-Weakest-Rows-in-a-Matrix/cpp-1337/) | | | +| 1338 | [Reduce Array Size to The Half](https://leetcode.com/problems/reduce-array-size-to-the-half/) | [solution](https://leetcode.com/problems/reduce-array-size-to-the-half/solution/) | [C++](1001-1500/1338-Reduce-Array-Size-to-The-Half/cpp-1338/) | | | +| 1339 | [Maximum Product of Splitted Binary Tree](https://leetcode.com/problems/maximum-product-of-splitted-binary-tree/) | [solution](https://leetcode.com/problems/maximum-product-of-splitted-binary-tree/solution/) | [C++](1001-1500/1339-Maximum-Product-of-Splitted-Binary-Tree/cpp-1339/) | | | +| 1340 | [Jump Game V](https://leetcode.com/problems/jump-game-v/) | [无] | [C++](1001-1500/1340-Jump-Game-V/cpp-1340/) | | | +| 1341 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1342 | [Number of Steps to Reduce a Number to Zero](https://leetcode.com/problems/number-of-steps-to-reduce-a-number-to-zero/) | [无] | [C++](1001-1500/1342-Number-of-Steps-to-Reduce-a-Number-to-Zero/cpp-1342/) | | | +| 1343 | [Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold](https://leetcode.com/problems/number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/) | [无] | [C++](1001-1500/1343-Number-of-Sub-arrays-of-Size-K-and-Average-Greater-than-or-Equal-to-Threshold/cpp-1343/) | | | +| 1344 | [Angle Between Hands of a Clock](https://leetcode.com/problems/angle-between-hands-of-a-clock/) | [C++](1001-1500/1344-Angle-Between-Hands-of-a-Clock/cpp-1344/) | | | | +| 1345 | [Jump Game IV](https://leetcode.com/problems/jump-game-iv/) | [无] | [C++](1001-1500/1345-Jump-Game-IV/cpp-1345/) | | | +| 1346 | [Check If N and Its Double Exist](https://leetcode.com/problems/check-if-n-and-its-double-exist/) | [无] | [C++](1001-1500/1346-Check-If-N-and-Its-Double-Exist/cpp-1346/) | | | +| 1347 | [Minimum Number of Steps to Make Two Strings Anagram](https://leetcode.com/problems/minimum-number-of-steps-to-make-two-strings-anagram/) | [无] | [C++](1001-1500/1347-Minimum-Number-of-Steps-to-Make-Two-Strings-Anagram/cpp-1347/) | | | +| 1348 | [Tweet Counts Per Frequency](https://leetcode.com/problems/tweet-counts-per-frequency/) | [无] | [C++](1001-1500/1348-Tweet-Counts-Per-Frequency/cpp-1348/) | | | +| 1349 | [Maximum Students Taking Exam](https://leetcode.com/problems/maximum-students-taking-exam/) | [无] | [C++](1001-1500/1349-Maximum-Students-Taking-Exam/cpp-1349/) | | | +| 1350 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1351 | [Count Negative Numbers in a Sorted Matrix](https://leetcode.com/problems/count-negative-numbers-in-a-sorted-matrix/) | [无] | [C++](1001-1500/1351-Count-Negative-Numbers-in-a-Sorted-Matrix/cpp-1351/) | | | +| 1352 | [Product of the Last K Numbers](https://leetcode.com/problems/product-of-the-last-k-numbers/) | [无] | [C++](1001-1500/1352-Product-of-the-Last-K-Numbers/cpp-1352/) | | | +| 1353 | [Maximum Number of Events That Can Be Attended](https://leetcode.com/problems/maximum-number-of-events-that-can-be-attended/) | [无] | [C++](1001-1500/1353-Maximum-Number-of-Events-That-Can-Be-Attended/cpp-1353/) | | | +| 1354 | [Construct Target Array With Multiple Sums](https://leetcode.com/problems/construct-target-array-with-multiple-sums/) | [solution](https://leetcode.com/problems/construct-target-array-with-multiple-sums/solution/) | [C++](1001-1500/1354-Construct-Target-Array-With-Multiple-Sums/cpp-1354/) | | | +| 1355 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1356 | [Sort Integers by The Number of 1 Bits](https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/) | [无] | [C++](1001-1500/1356-Sort-Integers-by-The-Number-of-1-Bits/cpp-1356/) | | | +| 1357 | [Apply Discount Every n Orders](https://leetcode.com/problems/apply-discount-every-n-orders/) | [无] | [C++](1001-1500/1357-Apply-Discount-Every-n-Orders/cpp-1357/) | | | +| 1358 | [Number of Substrings Containing All Three Characters](1358-Number-of-Substrings-Containing-All-Three-Characters/cpp-1358/) | [无] | [C++](1001-1500/1358-Number-of-Substrings-Containing-All-Three-Characters/cpp-1358/) | | | +| 1359 | [Count All Valid Pickup and Delivery Options](https://leetcode.com/problems/count-all-valid-pickup-and-delivery-options/) | [无] | [C++](1001-1500/1359-Count-All-Valid-Pickup-and-Delivery-Options/cpp-1359/) | | | +| 1360 | [Number of Days Between Two Dates](https://leetcode.com/problems/number-of-days-between-two-dates/) | [无] | [C++](1001-1500/1360-Number-of-Days-Between-Two-Dates/cpp-1360/) | | | +| 1361 | [Validate Binary Tree Nodes](https://leetcode.com/problems/validate-binary-tree-nodes/) | [无] | [C++](1001-1500/1361-Validate-Binary-Tree-Nodes/cpp-1361/) | | | +| 1362 | [Closest Divisors](https://leetcode.com/problems/closest-divisors/) | [无] | [C++](1001-1500/1362-Closest-Divisors/cpp-1362/) | | | +| 1363 | [Largest Multiple of Three](https://leetcode.com/problems/largest-multiple-of-three/) | [无] | [C++](1001-1500/1363-Largest-Multiple-of-Three/cpp-1363/) | | | +| 1364 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1365 | [How Many Numbers Are Smaller Than the Current Number](https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/) | [无] | [C++](1001-1500/1365-How-Many-Numbers-Are-Smaller-Than-the-Current-Number/cpp-1365/) | | | +| 1366 | [Rank Teams by Votes](https://leetcode.com/problems/rank-teams-by-votes/) | [无] | [C++](1001-1500/1366-Rank-Teams-by-Votes/cpp-1366/) | | | +| 1367 | [Linked List in Binary Tree](https://leetcode.com/problems/linked-list-in-binary-tree/) | [无] | [C++](1001-1500/1367-Linked-List-in-Binary-Tree/cpp-1367/) | | | +| 1368 | [Minimum Cost to Make at Least One Valid Path in a Grid](https://leetcode.com/problems/minimum-cost-to-make-at-least-one-valid-path-in-a-grid/) | [无] | [C++](1001-1500/1368-Minimum-Cost-to-Make-at-Least-One-Valid-Path-in-a-Grid/cpp-1368/) | | | +| 1369 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1370 | [Increasing Decreasing String](https://leetcode.com/problems/increasing-decreasing-string/) | [无] | [C++](1001-1500/1370-Increasing-Decreasing-String/cpp-1370/) | | | +| 1371 | [Find the Longest Substring Containing Vowels in Even Counts](https://leetcode.com/problems/find-the-longest-substring-containing-vowels-in-even-counts/) | [无] | [C++](1001-1500/1371-Find-the-Longest-Substring-Containing-Vowels-in-Even-Counts/cpp-1371/) | | | +| 1372 | [Longest ZigZag Path in a Binary Tree](https://leetcode.com/problems/longest-zigzag-path-in-a-binary-tree/) | [题解](https://leetcode-cn.com/problems/longest-zigzag-path-in-a-binary-tree/solution/er-cha-shu-zhong-de-zui-chang-jiao-cuo-lu-jing-b-2/)
[缺:dp,返回值DFS] | [C++](1001-1500/1372-Longest-ZigZag-Path-in-a-Binary-Tree/cpp-1372/) | | | +| 1373 | [Maximum Sum BST in Binary Tree](https://leetcode.com/problems/maximum-sum-bst-in-binary-tree/) | [无] | [C++](1001-1500/1373-Maximum-Sum-BST-in-Binary-Tree/cpp-1373/) | | | +| 1374 | [Generate a String With Characters That Have Odd Counts](https://leetcode.com/problems/generate-a-string-with-characters-that-have-odd-counts/) | [无] | [C++](1001-1500/1374-Generate-a-String-With-Characters-That-Have-Odd-Counts/cpp-1374/) | | | +| 1375 | [Bulb Switcher III](https://leetcode.com/problems/bulb-switcher-iii/) | [无] | [C++](1001-1500/1375-Bulb-Switcher-III/cpp-1375/) | | | +| 1376 | [Time Needed to Inform All Employees](https://leetcode.com/problems/time-needed-to-inform-all-employees/) | [无] | [C++](1001-1500/1376-Time-Needed-to-Inform-All-Employees/cpp-1376/) | | | +| 1377 | [Frog Position After T Seconds](https://leetcode.com/problems/frog-position-after-t-seconds/) | [无] | [C++](1001-1500/1377-Frog-Position-After-T-Seconds/cpp-1377/) | | | +| 1378 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1379 | [Find a Corresponding Node of a Binary Tree in a Clone of That Tree](https://leetcode.com/problems/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/) | [无] | [C++](1001-1500/1379-Find-a-Corresponding-Node-of-a-Binary-Tree-in-a-Clone-of-That-Tree/cpp-1379/) | | | +| | | | | | | +| 1383 | [Maximum Performance of a Team](https://leetcode.com/problems/maximum-performance-of-a-team/) | [无] | [C++](1001-1500/1383-Maximum-Performance-of-a-Team/cpp-1383/) | | | +| 1384 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| | | | | | | +| 1389 | [Create Target Array in the Given Order](https://leetcode.com/problems/create-target-array-in-the-given-order/) | [无] | [C++](1001-1500/1389-Create-Target-Array-in-the-Given-Order/cpp-1389/) | | | +| 1390 | [Four Divisors](https://leetcode.com/problems/four-divisors/) | [无] | [C++](1001-1500/1390-Four-Divisors/cpp-1390/) | | | +| 1391 | [Check if There is a Valid Path in a Grid](https://leetcode.com/problems/check-if-there-is-a-valid-path-in-a-grid/) | [无] | [C++](1001-1500/1391-Check-if-There-is-a-Valid-Path-in-a-Grid/cpp-1391/) | | | +| 1392 | [Longest Happy Prefix](https://leetcode.com/problems/longest-happy-prefix/) | [无] | [C++](1001-1500/1392-Longest-Happy-Prefix/cpp-1392/) | | | +| 1393 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1394 | [Find Lucky Integer in an Array](https://leetcode.com/problems/find-lucky-integer-in-an-array/) | [无] | [C++](1001-1500/1394-Find-Lucky-Integer-in-an-Array/cpp-1394/) | | | +| 1395 | [Count Number of Teams](https://leetcode.com/problems/count-number-of-teams/) | [无]
[缺:线段树] | [C++](1001-1500/1395-Count-Number-of-Teams/cpp-1395/) | | | +| 1396 | [Design Underground System](https://leetcode.com/problems/design-underground-system/) | [solution](https://leetcode.com/problems/design-underground-system/solution/) | [C++](1001-1500/1396-Design-Underground-System/cpp-1396/) | | | +| 1397 | [Find All Good Strings](https://leetcode.com/problems/find-all-good-strings/) | [无]
[缺:双端数位 DP] | [C++](1001-1500/1397-Find-All-Good-Strings/cpp-1397/) | | | +| 1398 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1399 | [Count Largest Group](https://leetcode.com/problems/count-largest-group/) | [无] | [C++](1001-1500/1399-Count-Largest-Group/cpp-1399/) | | | +| 1400 | [Construct K Palindrome Strings](https://leetcode.com/problems/construct-k-palindrome-strings/) | [无] | [C++](1001-1500/1400-Construct-K-Palindrome-Strings/cpp-1400/) | | | +| 1401 | [Circle and Rectangle Overlapping](https://leetcode.com/problems/circle-and-rectangle-overlapping/) | [无] | [C++](1001-1500/1401-Circle-and-Rectangle-Overlapping/cpp-1401/) | | | +| 1402 | [Reducing Dishes](https://leetcode.com/problems/reducing-dishes/) | [无] | [C++](1001-1500/1402-Reducing-Dishes/cpp-1402/) | | | +| 1403 | [Minimum Subsequence in Non Increasing Order](https://leetcode.com/problems/minimum-subsequence-in-non-increasing-order/) | [无] | [C++](1001-1500/1403-Minimum-Subsequence-in-Non-Increasing-Order/cpp-1403/) | | | +| 1404 | [Number of Steps to Reduce a Number in Binary Representation to One](https://leetcode.com/problems/number-of-steps-to-reduce-a-number-in-binary-representation-to-one/) | [无] | [C++](1001-1500/1404-Number-of-Steps-to-Reduce-a-Number-in-Binary-Representation-to-One/cpp-1404/) | | | +| 1405 | [Longest Happy String](https://leetcode.com/problems/longest-happy-string/) | [无] | [C++](1001-1500/1405-Longest-Happy-String/cpp-1405/) | | | +| 1406 | [Stone Game III](https://leetcode.com/problems/stone-game-iii/) | [无] | [C++](1001-1500/1406-Stone-Game-III/cpp-1406/) | | | +| 1407 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1408 | [String Matching in an Array](https://leetcode.com/problems/string-matching-in-an-array/) | [无] | [C++](1001-1500/1408-String-Matching-in-an-Array/cpp-1408/) | | | +| 1409 | [Queries on a Permutation With Key](https://leetcode.com/problems/queries-on-a-permutation-with-key/) | [无]
[缺:BIT] | [C++](1001-1500/1409-Queries-on-a-Permutation-With-Key/cpp-1409/) | | | +| 1410 | [HTML Entity Parser](https://leetcode.com/problems/html-entity-parser/) | [无] | [C++](1001-1500/1410-HTML-Entity-Parser/cpp-1410/) | | | +| 1411 | [Number of Ways to Paint N × 3 Grid](https://leetcode.com/problems/number-of-ways-to-paint-n-3-grid/) | [无] | [C++](1001-1500/1411-Number-of-Ways-to-Paint-N×3-Grid/cpp-1411/) | | | +| 1412 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1413 | [Minimum Value to Get Positive Step by Step Sum](https://leetcode.com/problems/minimum-value-to-get-positive-step-by-step-sum/) | [无] | [C++](1001-1500/1413-Minimum-Value-to-Get-Positive-Step-by-Step-Sum/cpp-1413/) | | | +| 1414 | [Find the Minimum Number of Fibonacci Numbers Whose Sum Is K](https://leetcode.com/problems/find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/) | [无] | [C++](1001-1500/1414-Find-the-Minimum-Number-of-Fibonacci-Numbers-Whose-Sum-Is-K/cpp-1414/) | | | +| 1415 | [The k-th Lexicographical String of All Happy Strings of Length n](https://leetcode.com/problems/the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/) | [无] | [C++](1001-1500/1415-The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n/cpp-1415/) | | | +| 1416 | [Restore The Array](https://leetcode.com/problems/restore-the-array/) | [无] | [C++](1001-1500/1416-Restore-The-Array/cpp-1416/) | | | +| 1417 | [Reformat The String](https://leetcode.com/problems/reformat-the-string/) | [无] | [C++](1001-1500/1417-Reformat-The-String/cpp-1417/) | | | +| 1418 | [Display Table of Food Orders in a Restaurant](https://leetcode.com/problems/display-table-of-food-orders-in-a-restaurant/) | [无] | [C++](1001-1500/1418-Display-Table-of-Food-Orders-in-a-Restaurant/cpp-1418/) | | | +| 1419 | [Minimum Number of Frogs Croaking](https://leetcode.com/problems/minimum-number-of-frogs-croaking/) | [无] | [C++](1001-1500/1419-Minimum-Number-of-Frogs-Croaking/cpp-1419/) | | | +| 1420 | [Build Array Where You Can Find The Maximum Exactly K Comparisons](https://leetcode.com/problems/build-array-where-you-can-find-the-maximum-exactly-k-comparisons/) | [无] | [C++](1001-1500/1420-Build-Array-Where-You-Can-Find-The-Maximum-Exactly-K-Comparisons/cpp-1420/) | | | +| 1421 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1422 | [Maximum Score After Splitting a String](https://leetcode.com/problems/maximum-score-after-splitting-a-string/) | [无] | [C++](1001-1500/1422-Maximum-Score-After-Splitting-a-String/cpp-1422/) | | | +| 1423 | [Maximum Points You Can Obtain from Cards](https://leetcode.com/problems/maximum-points-you-can-obtain-from-cards/) | [无] | [C++](1001-1500/1423-Maximum-Points-You-Can-Obtain-from-Cards/cpp-1423/) | | | +| 1424 | [Diagonal Traverse II](https://leetcode.com/problems/diagonal-traverse-ii/) | [无] | [C++](1001-1500/1424-Diagonal-Traverse-II/cpp-1424/) | | | +| 1425 | [Constrained Subset Sum](https://leetcode.com/problems/constrained-subset-sum/) | [无] | [C++](1001-1500/1425-Constrained-Subset-Sum/cpp-1425/) | | | +| 1426 | [Counting Elements](https://leetcode.com/problems/counting-elements/) | [solution](https://leetcode.com/problems/counting-elements/solution/) | [C++](1001-1500/1426-Counting-Elements/cpp-1426/) | | | +| 1427 | [Perform String Shifts](https://leetcode.com/problems/perform-string-shifts/) | [solution](https://leetcode.com/problems/perform-string-shifts/solution/) | [C++](1001-1500/1427-Perform-String-Shifts/cpp-1427/) | | | +| 1428 | [Leftmost Column with at Least a One](https://leetcode.com/problems/leftmost-column-with-at-least-a-one/) | [solution](https://leetcode.com/problems/leftmost-column-with-at-least-a-one/solution/) | [C++](1001-1500/1428-Leftmost-Column-with-at-Least-a-One/cpp-1428/) | | | +| 1429 | [First Unique Number](https://leetcode.com/problems/first-unique-number/) | [solution](https://leetcode.com/problems/first-unique-number/) | [C++](1001-1500/1429-First-Unique-Number/cpp-1429/) | | | +| 1430 | [Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree](https://leetcode.com/problems/check-if-a-string-is-a-valid-sequence-from-root-to-leaves-path-in-a-binary-tree/) | [无] | [C++](1001-1500/1430-Check-If-a-String-Is-a-Valid-Sequence-from-Root-to-Leaves-Path-in-a-Binary-Tree/cpp-1430/) | | | +| 1431 | [Kids With the Greatest Number of Candies](https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/) | [无] | [C++](1001-1500/1431-Kids-With-the-Greatest-Number-of-Candies/cpp-1431/) | | | +| 1432 | [Max Difference You Can Get From Changing an Integer](https://leetcode.com/problems/max-difference-you-can-get-from-changing-an-integer/) | [无] | [C++](1001-1500/1432-Max-Difference-You-Can-Get-From-Changing-an-Integer/cpp-1432/) | | | +| 1433 | [Check If a String Can Break Another String](https://leetcode.com/problems/check-if-a-string-can-break-another-string/) | [无] | [C++](1001-1500/1433-Check-If-a-String-Can-Break-Another-String/cpp-1433/) | | | +| 1434 | [Number of Ways to Wear Different Hats to Each Other](https://leetcode.com/problems/number-of-ways-to-wear-different-hats-to-each-other/) | [无] | [C++](1001-1500/1434-Number-of-Ways-to-Wear-Different-Hats-to-Each-Other/cpp-1434/) | | | +| 1435 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1436 | [Destination City](https://leetcode.com/problems/destination-city/) | [无] | [C++](1001-1500/1436-Destination-City/cpp-1436/) | | | +| 1437 | [Check If All 1's Are at Least Length K Places Away](https://leetcode.com/problems/check-if-all-1s-are-at-least-length-k-places-away/) | [无] | [C++](1001-1500/1437-Check-If-All-1s-Are-at-Least-Length-K-Places-Away/cpp-1437/)| | | +| 1438 | [Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit](https://leetcode.com/problems/longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/) | [无] | [C++](1001-1500/1438-Longest-Continuous-Subarray-With-Absolute-Diff-Less-Than-or-Equal-to-Limit/cpp-1438/) | | | +| 1439 | [Find the Kth Smallest Sum of a Matrix With Sorted Rows](https://leetcode.com/problems/find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/) | [无] | [C++](1001-1500/1439-Find-the-Kth-Smallest-Sum-of-a-Matrix-With-Sorted-Rows/cpp-1439/) | | | +| 1440 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1441 | [Build an Array With Stack Operations](https://leetcode.com/problems/build-an-array-with-stack-operations/) | [无] | [C++](1001-1500/1441-Build-an-Array-With-Stack-Operations/cpp-1441/) | | | +| 1442 | [Count Triplets That Can Form Two Arrays of Equal XOR](https://leetcode.com/problems/count-triplets-that-can-form-two-arrays-of-equal-xor/) | [无]
[缺:O(n)] | [C++](1001-1500/1442-Count-Triplets-That-Can-Form-Two-Arrays-of-Equal-XOR/cpp-1442/) | | | +| 1443 | [Minimum Time to Collect All Apples in a Tree](https://leetcode.com/problems/minimum-time-to-collect-all-apples-in-a-tree/) | [无] | [C++](1001-1500/1443-Minimum-Time-to-Collect-All-Apples-in-a-Tree/cpp-1443/) | | | +| 1444 | [Number of Ways of Cutting a Pizza](https://leetcode.com/problems/number-of-ways-of-cutting-a-pizza/) | [无] | [C++](1001-1500/1444-Number-of-Ways-of-Cutting-a-Pizza/cpp-1444/) | | | +| 1445 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1446 | [Consecutive Characters](https://leetcode.com/problems/consecutive-characters/) | [无] | [C++](1001-1500/1446-Consecutive-Characters/cpp-1446/) | | | +| 1447 | [Simplified Fractions](https://leetcode.com/problems/simplified-fractions/) | [无] | [C++](1001-1500/1447-Simplified-Fractions/cpp-1447/) | | | +| 1448 | [Count Good Nodes in Binary Tree](https://leetcode.com/problems/count-good-nodes-in-binary-tree/) | [无] | [C++](1001-1500/1448-Count-Good-Nodes-in-Binary-Tree/cpp-1448/) | | | +| 1449 | [Form Largest Integer With Digits That Add up to Target](https://leetcode.com/problems/form-largest-integer-with-digits-that-add-up-to-target/) | [无] | [C++](1001-1500/1449-Form-Largest-Integer-With-Digits-That-Add-up-to-Target/cpp-1449/) | | | +| 1450 | [Number of Students Doing Homework at a Given Time](https://leetcode.com/problems/number-of-students-doing-homework-at-a-given-time/) | [无] | [C++](1001-1500/1450-Number-of-Students-Doing-Homework-at-a-Given-Time/cpp-1450/) | | | +| 1451 | [Rearrange Words in a Sentence](https://leetcode.com/problems/rearrange-words-in-a-sentence/) | [无] | [C++](1001-1500/1451-Rearrange-Words-in-a-Sentence/cpp-1451/) | | | +| 1452 | [People Whose List of Favorite Companies Is Not a Subset of Another List](https://leetcode.com/problems/people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/) | [无] | [C++](1001-1500/1452-People-Whose-List-of-Favorite-Companies-Is-Not-a-Subset-of-Another-List/cpp-1452/) | | | +| 1453 | [Maximum Number of Darts Inside of a Circular Dartboard](https://leetcode.com/problems/maximum-number-of-darts-inside-of-a-circular-dartboard/) | [无]
[缺:[Angular Sweep](https://www.geeksforgeeks.org/angular-sweep-maximum-points-can-enclosed-circle-given-radius/)] | [C++](1001-1500/1453-Maximum-Number-of-Darts-Inside-of-a-Circular-Dartboard/cpp-1453/) | | | +| 1454 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1455 | [Check If a Word Occurs As a Prefix of Any Word in a Sentence](https://leetcode.com/problems/check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/) | [无] | [C++](1001-1500/1455-Check-If-a-Word-Occurs-As-a-Prefix-of-Any-Word-in-a-Sentence/cpp-1455/) | | | +| 1456 | [Maximum Number of Vowels in a Substring of Given Length](https://leetcode.com/problems/maximum-number-of-vowels-in-a-substring-of-given-length/) | [无] | [C++](1001-1500/1456-Maximum-Number-of-Vowels-in-a-Substring-of-Given-Length/cpp-1456/) | | | +| 1457 | [Pseudo Palindromic Paths in a Binary Tree](https://leetcode.com/problems/pseudo-palindromic-paths-in-a-binary-tree/) | [无] | [C++](1001-1500/1457-Pseudo-Palindromic-Paths-in-a-Binary-Tree/) | | | +| 1458 | [Max Dot Product of Two Subsequences](https://leetcode.com/problems/max-dot-product-of-two-subsequences/) | [无] | [C++](1001-1500/1458-Max-Dot-Product-of-Two-Subsequences/cpp-1458/) | | | +| 1459 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1460 | [Make Two Arrays Equal by Reversing Sub-arrays](https://leetcode.com/problems/make-two-arrays-equal-by-reversing-sub-arrays/) | [无] | [C++](1001-1500/1460-Make-Two-Arrays-Equal-by-Reversing-Sub-arrays/cpp-1460/) | | | +| 1461 | [Check If a String Contains All Binary Codes of Size K](https://leetcode.com/problems/check-if-a-string-contains-all-binary-codes-of-size-k/) | [无] | [C++](1001-1500/1461-Check-If-a-String-Contains-All-Binary-Codes-of-Size-K/cpp-1461/) | | | +| 1462 | [Course Schedule IV](https://leetcode.com/problems/course-schedule-iv/) | [无] | [C++](1001-1500/1462-Course-Schedule-IV/cpp-1462/) | | | +| 1463 | [Cherry Pickup II](https://leetcode.com/problems/cherry-pickup-ii/) | [无] | [C++](1001-1500/1463-Cherry-Pickup-II/cpp-1463/) | | | +| 1464 | [Maximum Product of Two Elements in an Array](https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/) | [无] | [C++](1001-1500/1464-Maximum-Product-of-Two-Elements-in-an-Array/cpp-1464/) | | | +| 1465 | [Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts](https://leetcode.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/) | [无] | [C++](1001-1500/1465-Maximum-Area-of-a-Piece-of-Cake-After-Horizontal-and-Vertical-Cuts/cpp-1465/) | | | +| 1466 | [Reorder Routes to Make All Paths Lead to the City Zero](https://leetcode.com/problems/reorder-routes-to-make-all-paths-lead-to-the-city-zero/) | [无] | [C++](1001-1500/1466-Reorder-Routes-to-Make-All-Paths-Lead-to-the-City-Zero/cpp-1466/) | | | +| 1467 | [Probability of a Two Boxes Having The Same Number of Distinct Balls](https://leetcode.com/problems/probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/) | [无] | [C++](1001-1500/1467-Probability-of-a-Two-Boxes-Having-The-Same-Number-of-Distinct-Balls/cpp-1467/) | | | +| 1468 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1469 | [Find All the Lonely Nodes](https://leetcode.com/problems/find-all-the-lonely-nodes/) | [无] | [C++](1001-1500/1469-Find-All-the-Lonely-Nodes/cpp-1469/) | | | +| 1470 | [Shuffle the Array](https://leetcode.com/problems/shuffle-the-array/) | [无] | [C++](1001-1500/1470-Shuffle-the-Array/cpp-1470/) | | | +| 1471 | [The k Strongest Values in an Array](https://leetcode.com/problems/the-k-strongest-values-in-an-array/) | [无] | [C++](1001-1500/1471-The-k-Strongest-Values-in-an-Array/cpp-1471/) | | | +| 1472 | [Design Browser History](https://leetcode.com/problems/design-browser-history/) | [无] | [C++](1001-1500/1472-Design-Browser-History/cpp-1472/) | | | +| 1473 | [Paint House III](https://leetcode.com/problems/paint-house-iii/) | [无] | [C++](1001-1500/1473-Paint-House-III/cpp-1473/) | | | +| 1474 | [Delete N Nodes After M Nodes of a Linked List](https://leetcode.com/problems/delete-n-nodes-after-m-nodes-of-a-linked-list/) | [无] | [C++](1001-1500/1474-Delete-N-Nodes-After-M-Nodes-of-a-Linked-List/cpp-1474/) | | | +| 1475 | [Final Prices With a Special Discount in a Shop](https://leetcode.com/problems/final-prices-with-a-special-discount-in-a-shop/) | [无] | [C++](1001-1500/1475-Final-Prices-With-a-Special-Discount-in-a-Shop/cpp-1475/) | | | +| 1476 | [Subrectangle Queries](https://leetcode.com/problems/subrectangle-queries/) | [无] | [C++](1001-1500/1476-Subrectangle-Queries/cpp-1476/) | | | +| 1477 | [Find Two Non-overlapping Sub-arrays Each With Target Sum](https://leetcode.com/problems/find-two-non-overlapping-sub-arrays-each-with-target-sum/) | [无] | [C++](1001-1500/1477-Find-Two-Non-overlapping-Sub-arrays-Each-With-Target-Sum/cpp-1477/) | | | +| 1478 | [Allocate Mailboxes](https://leetcode.com/problems/allocate-mailboxes/) | [无] | [C++](1001-1500/1478-Allocate-Mailboxes/cpp-1478/) | | | +| 1479 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1480 | [Running Sum of 1d Array](https://leetcode.com/problems/running-sum-of-1d-array/) | [无] | [C++](1001-1500/1480-Running-Sum-of-1d-Array/cpp-1480/) | | | +| 1481 | [Least Number of Unique Integers after K Removals](https://leetcode.com/problems/least-number-of-unique-integers-after-k-removals/) | [无] | [C++](1001-1500/1481-Least-Number-of-Unique-Integers-after-K-Removals/cpp-1481/) | | | +| 1482 | [Minimum Number of Days to Make m Bouquets](https://leetcode.com/problems/minimum-number-of-days-to-make-m-bouquets/) | [无] | [C++](1001-1500/1482-Minimum-Number-of-Days-to-Make-m-Bouquets/cpp-1482/) | | | +| 1483 | [Kth Ancestor of a Tree Node](https://leetcode.com/problems/kth-ancestor-of-a-tree-node/) | [无] | [C++](1001-1500/1483-Kth-Ancestor-of-a-Tree-Node/cpp-1483/) | | | +| 1484 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1485 | [Clone Binary Tree With Random Pointer](https://leetcode.com/problems/clone-binary-tree-with-random-pointer/) | [无] | [C++](1001-1500/1485-Clone-Binary-Tree-With-Random-Pointer/cpp-1485/) | | | +| 1486 | [XOR Operation in an Array](https://leetcode.com/problems/xor-operation-in-an-array/) | [无] | [C++](1001-1500/1486-XOR-Operation-in-an-Array/cpp-1486/) | | | +| 1487 | [Making File Names Unique](https://leetcode.com/problems/making-file-names-unique/) | [无] | [C++](1001-1500/1487-Making-File-Names-Unique/cpp-1487/) | | | +| 1488 | [Avoid Flood in The City](https://leetcode.com/problems/avoid-flood-in-the-city/) | [无] | [C++](1001-1500/1488-Avoid-Flood-in-The-City/cpp-1488/) | | | +| 1489 | [Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree](https://leetcode.com/problems/find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/) | [无]
[缺:O(ElogE) 的解] | [C++](1001-1500/1489-Find-Critical-and-Pseudo-Critical-Edges-in-Minimum-Spanning-Tree/cpp-1489/) | | | +| 1490 | [Clone N-ary Tree](https://leetcode.com/problems/clone-n-ary-tree/) | [无] | [C++](1001-1500/1490-Clone-N-ary-Tree/cpp-1490/) | | | +| 1491 | [Average Salary Excluding the Minimum and Maximum Salary](https://leetcode.com/problems/average-salary-excluding-the-minimum-and-maximum-salary/) | [无] | [C++](1001-1500/1491-Average-Salary-Excluding-the-Minimum-and-Maximum-Salary/cpp-1491/) | | | +| 1492 | [The kth Factor of n](https://leetcode.com/problems/the-kth-factor-of-n/) | [无] | [C++](1001-1500/1492-The-kth-Factor-of-n/cpp-1492/) | | | +| 1493 | [Longest Subarray of 1's After Deleting One Element](https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element/) | [无] | [C++](1001-1500/1493-Longest-Subarray-of-1's-After-Deleting-One-Element/cpp-1493/) | | | +| 1494 | [Parallel Courses II](https://leetcode.com/problems/parallel-courses-ii/) | [无] | [C++](1001-1500/1494-Parallel-Courses-II/cpp-1494/) | | | +| 1495 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1496 | [Path Crossing](https://leetcode.com/problems/path-crossing/) | [无] | [C++](1001-1500/1496-Path-Crossing/cpp-1496/) | | | +| 1497 | [Check If Array Pairs Are Divisible by k](https://leetcode.com/problems/check-if-array-pairs-are-divisible-by-k/) | [无] | [C++](1001-1500/1497-Check-If-Array-Pairs-Are-Divisible-by-k/cpp-1497/) | | | +| 1498 | [Number of Subsequences That Satisfy the Given Sum Condition](https://leetcode.com/problems/number-of-subsequences-that-satisfy-the-given-sum-condition/) | [无] | [C++](1001-1500/1498-Number-of-Subsequences-That-Satisfy-the-Given-Sum-Condition/cpp-1498/) | | | +| 1499 | [Max Value of Equation](https://leetcode.com/problems/max-value-of-equation/) | [无] | [C++](1001-1500/1499-Max-Value-of-Equation/cpp-1499/) | | | +| | | | | | | +| 1506 | [Find Root of N-Ary Tree](https://leetcode.com/problems/find-root-of-n-ary-tree/) | [solution](https://leetcode.com/problems/find-root-of-n-ary-tree/solution/) | [C++](1501-2000/1506-Find-Root-of-N-Ary-Tree/cpp-1506/) | | | +| | | | | | | +| 1519 | [Number of Nodes in the Sub-Tree With the Same Label](https://leetcode.com/problems/number-of-nodes-in-the-sub-tree-with-the-same-label/description/) | [solution](https://leetcode.com/problems/number-of-nodes-in-the-sub-tree-with-the-same-label/solutions/2864718/number-of-nodes-in-the-sub-tree-with-the-same-label/?orderBy=most_votes) | [C++](1501-2000/1519-Number-of-Nodes-in-the-Sub-Tree-With-the-Same-Label/cpp-1519/) | | | +| | | | | | | +| 1522 | [Diameter of N-Ary Tree](https://leetcode.com/problems/diameter-of-n-ary-tree/) | [无] | [C++](1501-2000/1522-Diameter-of-N-Ary-Tree/cpp-1522/) | | | +| 1523 | [Count Odd Numbers in an Interval Range](https://leetcode.com/problems/count-odd-numbers-in-an-interval-range/description/) | [无] | [C++](1501-2000/1523-Count-Odd-Numbers-in-an-Interval-Range/cpp-1523/) | | | +| | | | | | | +| 1527 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| | | | | | | +| 1531 | [String Compression II](https://leetcode.com/problems/string-compression-ii/) | [无][缺:其他解法] | [C++](1501-2000/1531-String-Compression-II/cpp-1531/) | | | +| | | | | | | +| 1533 | [Find the Index of the Large Integer](https://leetcode.com/problems/find-the-index-of-the-large-integer/) | [solution](https://leetcode.com/problems/find-the-index-of-the-large-integer/solutions/2885830/find-the-index-of-the-large-integer/?orderBy=most_votes) | [C++](1501-2000/1533-Find-the-Index-of-the-Large-Integer/cpp-1533/) | | | +| | | | | | | +| 1539 | [Kth Missing Positive Number](https://leetcode.com/problems/kth-missing-positive-number/) | [solution](https://leetcode.com/problems/kth-missing-positive-number/solution/) | [C++](1501-2000/1539-Kth-Missing-Positive-Number/cpp-1539/) | | | +| | | | | | | +| 1557 | [Minimum Number of Vertices to Reach All Nodes](https://leetcode.com/problems/minimum-number-of-vertices-to-reach-all-nodes/description/) | [无] | [C++](1501-2000/1557-Minimum-Number-of-Vertices-to-Reach-All-Nodes/cpp-1557/) | | | +| | | | | | | +| 1559 | [Detect Cycles in 2D Grid](https://leetcode.com/problems/detect-cycles-in-2d-grid/) | [无] | [C++](1501-2000/1559-Detect-Cycles-in-2D-Grid/cpp-1559/) | | | +| | | | | | | +| 1564 | [Put Boxes Into the Warehouse I](https://leetcode.com/problems/put-boxes-into-the-warehouse-i/) | [无] | [C++](1501-2000/1564-Put-Boxes-Into-the-Warehouse-I/cpp-1564/) | | | +| | | | | | | +| 1570 | [Dot Product of Two Sparse Vectors](https://leetcode.com/problems/dot-product-of-two-sparse-vectors/) | [solution](https://leetcode.com/problems/dot-product-of-two-sparse-vectors/) | [C++](1501-2000/1570-Dot-Product-of-Two-Sparse-Vectors/cpp-1570/) | | | +| 1571 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1572 | [Matrix Diagonal Sum](https://leetcode.com/problems/matrix-diagonal-sum/) | [无] | [C++](1501-2000/1572-Matrix-Diagonal-Sum/cpp-1572/) | | | +| | | | | | | +| 1574 | [Shortest Subarray to be Removed to Make Array Sorted](https://leetcode.com/problems/shortest-subarray-to-be-removed-to-make-array-sorted/description/) | [无] | [C++](1501-2000/1574-Shortest-Subarray-to-be-Removed-to-Make-Array-Sorted/cpp-1574/) | | | +| 1575 | [Count All Possible Routes](https://leetcode.com/problems/count-all-possible-routes/description/) | [无] | [C++](1501-2000/1575-Count-All-Possible-Routes/cpp-1575/) | | | +| 1576 | [Replace All ?'s to Avoid Consecutive Repeating Characters](https://leetcode.com/problems/replace-all-s-to-avoid-consecutive-repeating-characters/) | [无] | [C++](1501-2000/1576-Replace-All-Question-Marks-to-Avoid-Consecutive-Repeating-Characters/cpp-1576/) | | | +| 1577 | [Number of Ways Where Square of Number Is Equal to Product of Two Numbers](https://leetcode.com/problems/number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/) | [无] | [C++](1501-2000/1577-Number-of-Ways-Where-Square-of-Number-Is-Equal-to-Product-of-Two-Numbers/cpp-1577/) | | | +| 1578 | [Minimum Deletion Cost to Avoid Repeating Letters](https://leetcode.com/problems/minimum-deletion-cost-to-avoid-repeating-letters/) | [无] | [C++](1501-2000/1578-Minimum-Deletion-Cost-to-Avoid-Repeating-Letters/cpp-1578/) | | | +| 1579 | [Remove Max Number of Edges to Keep Graph Fully Traversable](https://leetcode.com/problems/remove-max-number-of-edges-to-keep-graph-fully-traversable/) | [无] | [C++](1501-2000/1579-Remove-Max-Number-of-Edges-to-Keep-Graph-Fully-Traversable/cpp-1579/) | | | +| 1580 | [Put Boxes Into the Warehouse II](https://leetcode.com/problems/put-boxes-into-the-warehouse-ii/) | [无] | [C++](1501-2000/1580-Put-Boxes-Into-the-Warehouse-II/cpp-1580/) | | | +| 1581 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1582 | [Special Positions in a Binary Matrix](https://leetcode.com/problems/special-positions-in-a-binary-matrix/) | [无] | [C++](1501-2000/1582-Special-Positions-in-a-Binary-Matrix/cpp-1582/) | | | +| 1583 | [Count Unhappy Friends](https://leetcode.com/problems/count-unhappy-friends/) | [无] | [C++](1501-2000/1583-Count-Unhappy-Friends/cpp-1583/) | | | +| 1584 | [Min Cost to Connect All Points](https://leetcode.com/problems/min-cost-to-connect-all-points/) | [无]
[缺:prim 和 ] | [C++](1501-2000/1584-Min-Cost-to-Connect-All-Points/cpp-1584/) | | | +| 1585 | [Check If String Is Transformable With Substring Sort Operations](https://leetcode.com/problems/check-if-string-is-transformable-with-substring-sort-operations/) | [无] | [C++](1501-2000/1585-Check-If-String-Is-Transformable-With-Substring-Sort-Operations/cpp-1585/) | | | +| 1586 | [Binary Search Tree Iterator II](https://leetcode.com/problems/binary-search-tree-iterator-ii/) | [无]
[缺:用栈模拟] | [C++](1501-2000/1586-Binary-Search-Tree-Iterator-II/cpp-1586/) | | | +| 1587 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1588 | [Sum of All Odd Length Subarrays](https://leetcode.com/problems/sum-of-all-odd-length-subarrays/) | [无] | [C++](1501-2000/1588-Sum-of-All-Odd-Length-Subarrays/cpp-1588/) | | | +| 1589 | [Maximum Sum Obtained of Any Permutation](https://leetcode.com/problems/maximum-sum-obtained-of-any-permutation/) | [无] | [C++](1501-2000/1589-Maximum-Sum-Obtained-of-Any-Permutation/cpp-1589/) | | | +| 1590 | [Make Sum Divisible by P](https://leetcode.com/problems/make-sum-divisible-by-p/) | [无] | [C++](1501-2000/1590-Make-Sum-Divisible-by-P/cpp-1590/) | | | +| 1591 | [Strange Printer II](https://leetcode.com/problems/strange-printer-ii/) | [无] | [C++](1501-2000/1591-Strange-Printer-II/cpp-1591/) | | | +| 1592 | [Rearrange Spaces Between Words](https://leetcode.com/problems/rearrange-spaces-between-words/) | [无] | [C++](1501-2000/1592-Rearrange-Spaces-Between-Words/cpp-1592/) | | | +| 1593 | [Split a String Into the Max Number of Unique Substrings](https://leetcode.com/problems/split-a-string-into-the-max-number-of-unique-substrings/) | [无] | [C++](1501-2000/1593-Split-a-String-Into-the-Max-Number-of-Unique-Substrings/cpp-1593/) | | | +| 1594 | [Maximum Non Negative Product in a Matrix](https://leetcode.com/problems/maximum-non-negative-product-in-a-matrix/) | [无] | [C++](1501-2000/1594-Maximum-Non-Negative-Product-in-a-Matrix/cpp-1594/) | | | +| 1595 | [Minimum Cost to Connect Two Groups of Points](https://leetcode.com/problems/minimum-cost-to-connect-two-groups-of-points/) | [无] | [C++](1501-2000/1595-Minimum-Cost-to-Connect-Two-Groups-of-Points/cpp-1595/) | | | +| 1596 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1597 | [Build Binary Expression Tree From Infix Expression](https://leetcode.com/problems/build-binary-expression-tree-from-infix-expression/) | [无] | [C++](1501-2000/1597-Build-Binary-Expression-Tree-From-Infix-Expression/cpp-1597/) | | | +| 1598 | [Crawler Log Folder](https://leetcode.com/problems/crawler-log-folder/) | [无] | [C++](1501-2000/1598-Crawler-Log-Folder/cpp-1598/) | | | +| 1599 | [Maximum Profit of Operating a Centennial Wheel](https://leetcode.com/problems/maximum-profit-of-operating-a-centennial-wheel/) | [无] | [C++](1501-2000/1599-Maximum-Profit-of-Operating-a-Centennial-Wheel/cpp-1599/) | | | +| 1600 | [Throne Inheritance](https://leetcode.com/problems/throne-inheritance/) | [无] | [C++](1501-2000/1600-Throne-Inheritance/cpp-1600/) | | | +| 1601 | [Maximum Number of Achievable Transfer Requests](https://leetcode.com/problems/maximum-number-of-achievable-transfer-requests/) | [无]
[缺:网络流解法] | [C++](1501-2000/1601-Maximum-Number-of-Achievable-Transfer-Requests/cpp-1601/) | | | +| 1602 | [Find Nearest Right Node in Binary Tree](https://leetcode.com/problems/find-nearest-right-node-in-binary-tree/) | [solution](https://leetcode.com/problems/find-nearest-right-node-in-binary-tree/solution/) | [C++](1501-2000/1602-Find-Nearest-Right-Node-in-Binary-Tree/cpp-1602/) | | | +| 1603 | [Design Parking System](https://leetcode.com/problems/design-parking-system/) | [无] | [C++](1501-2000/1603-Design-Parking-System/cpp-1603/) | | | +| 1604 | [Alert Using Same Key-Card Three or More Times in a One Hour Period](https://leetcode.com/problems/alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/) | [无] | [C++](1501-2000/1604-Alert-Using-Same-Key-Card-Three-or-More-Times-in-a-One-Hour-Period/cpp-1604/) | | | +| 1605 | [Find Valid Matrix Given Row and Column Sums](https://leetcode.com/problems/find-valid-matrix-given-row-and-column-sums/) | [无] | [C++](1501-2000/1605-Find-Valid-Matrix-Given-Row-and-Column-Sums/cpp-1605/) | | | +| 1606 | [Find Servers That Handled Most Number of Requests](https://leetcode.com/problems/find-servers-that-handled-most-number-of-requests/) | [无] | [C++](1501-2000/1606-Find-Servers-That-Handled-Most-Number-of-Requests/cpp-1606/) | | | +| 1607 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1608 | [Special Array With X Elements Greater Than or Equal X](https://leetcode.com/problems/special-array-with-x-elements-greater-than-or-equal-x/) | [无] | [C++](1501-2000/1608-Special-Array-With-X-Elements-Greater-Than-or-Equal-X/cpp-1608/) | | | +| 1609 | [Even Odd Tree](https://leetcode.com/problems/even-odd-tree/) | [无] | [C++](1501-2000/1609-Even-Odd-Tree/cpp-1609/) | | | +| 1610 | [Maximum Number of Visible Points](https://leetcode.com/problems/maximum-number-of-visible-points/) | [无] | [C++](1501-2000/1610-Maximum-Number-of-Visible-Points/cpp-1610/) | | | +| 1611 | [Minimum One Bit Operations to Make Integers Zero](https://leetcode.com/problems/minimum-one-bit-operations-to-make-integers-zero/) | [无] | [C++](1501-2000/1611-Minimum-One-Bit-Operations-to-Make-Integers-Zero/cpp-1611/) | | | +| 1612 | [Check If Two Expression Trees are Equivalent](https://leetcode.com/problems/check-if-two-expression-trees-are-equivalent/) | [无] | [C++](1501-2000/1612-Check-If-Two-Expression-Trees-are-Equivalent/cpp-1612/) | | | +| 1613 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1614 | [Maximum Nesting Depth of the Parentheses](https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/) | [无] | [C++](1501-2000/1614-Maximum-Nesting-Depth-of-the-Parentheses/cpp-1614/) | | | +| 1615 | [Maximal Network Rank](https://leetcode.com/problems/maximal-network-rank/) | [无] | [C++](1501-2000/1615-Maximal-Network-Rank/cpp-1615/) | | | +| 1616 | [Split Two Strings to Make Palindrome](https://leetcode.com/problems/split-two-strings-to-make-palindrome/) | [无] | [C++](1501-2000/1616-Split-Two-Strings-to-Make-Palindrome/cpp-1616/) | | | +| 1617 | [Count Subtrees With Max Distance Between Cities](https://leetcode.com/problems/count-subtrees-with-max-distance-between-cities/) | [无] | [C++](1501-2000/1617-Count-Subtrees-With-Max-Distance-Between-Cities/cpp-1617/) | | | +| 1618 | [Maximum Font to Fit a Sentence in a Screen](https://leetcode.com/problems/maximum-font-to-fit-a-sentence-in-a-screen/) | [无] | [C++](1501-2000/1618-Maximum-Font-to-Fit-a-Sentence-in-a-Screen/cpp-1618/) | | | +| 1619 | [Mean of Array After Removing Some Elements](https://leetcode.com/problems/mean-of-array-after-removing-some-elements/) | [无] | [C++](1501-2000/1619-Mean-of-Array-After-Removing-Some-Elements/cpp-1619/) | | | +| 1620 | [Coordinate With Maximum Network Quality](https://leetcode.com/problems/coordinate-with-maximum-network-quality/) | [无] | [C++](1501-2000/1620-Coordinate-With-Maximum-Network-Quality/cpp-1620/) | | | +| 1621 | [Number of Sets of K Non-Overlapping Line Segments](https://leetcode.com/problems/number-of-sets-of-k-non-overlapping-line-segments/) | [无] | [C++](1501-2000/1621-Number-of-Sets-of-K-Non-Overlapping-Line-Segments/cpp-1621/) | | | +| 1622 | [Fancy Sequence](https://leetcode.com/problems/fancy-sequence/) | [无] | [C++](1501-2000/1622-Fancy-Sequence/cpp-1622/) | | | +| 1623 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1624 | [Largest Substring Between Two Equal Characters](https://leetcode.com/problems/largest-substring-between-two-equal-characters/) | [无] | [C++](1501-2000/1624-Largest-Substring-Between-Two-Equal-Characters/cpp-1624/) | | | +| 1625 | [Lexicographically Smallest String After Applying Operations](https://leetcode.com/problems/lexicographically-smallest-string-after-applying-operations/) | [无] | [C++](1501-2000/1625-Lexicographically-Smallest-String-After-Applying-Operations/cpp-1625/) | | | +| 1626 | [Best Team With No Conflicts](https://leetcode.com/problems/best-team-with-no-conflicts/) | [无]
[缺:nlogn 算法] | [C++](1501-2000/1626-Best-Team-With-No-Conflicts/cpp-1626/) | | | +| 1627 | [Graph Connectivity With Threshold](https://leetcode.com/problems/graph-connectivity-with-threshold/) | [无] | [C++](1501-2000/1627-Graph-Connectivity-With-Threshold/cpp-1627/) | | | +| 1628 | [Design an Expression Tree With Evaluate Function](https://leetcode.com/problems/design-an-expression-tree-with-evaluate-function/) | [无] | [C++](1501-2000/1628-Design-an-Expression-Tree-With-Evaluate-Function/cpp-1628/) | | | +| 1629 | [Slowest Key](https://leetcode.com/problems/slowest-key/) | [无] | [C++](1501-2000/1629-Slowest-Key/cpp-1629/) | | +| 1630 | [Arithmetic Subarrays](https://leetcode.com/problems/arithmetic-subarrays/) | [无] | [C++](1501-2000/1630-Arithmetic-Subarrays/cpp-1630/) | | | +| 1631 | [Path With Minimum Effort](https://leetcode.com/problems/path-with-minimum-effort/) | [solution](https://leetcode.com/problems/path-with-minimum-effort/solution/) | [C++](1501-2000/1631-Path-With-Minimum-Effort/cpp-1631/) | | | +| 1632 | [Rank Transform of a Matrix](https://leetcode.com/problems/rank-transform-of-a-matrix/) | [solution](https://leetcode.com/problems/rank-transform-of-a-matrix/solution/) | [C++](1501-2000/1632-Rank-Transform-of-a-Matrix/cpp-1632/) | | | +| 1633 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1634 | [Add Two Polynomials Represented as Linked Lists](https://leetcode.com/problems/add-two-polynomials-represented-as-linked-lists/) | [无] | [C++](1501-2000/1634-Add-Two-Polynomials-Represented-as-Linked-Lists/cpp-1634/) | | | +| 1635 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1636 | [Sort Array by Increasing Frequency](https://leetcode.com/problems/sort-array-by-increasing-frequency/) | [无] | [C++](1501-2000/1636-Sort-Array-by-Increasing-Frequency/cpp-1636/) | | | +| 1637 | [Widest Vertical Area Between Two Points Containing No Points](https://leetcode.com/problems/widest-vertical-area-between-two-points-containing-no-points/) | [无] | [C++](1501-2000/1637-Widest-Vertical-Area-Between-Two-Points-Containing-No-Points/cpp-1637/) | | | +| 1638 | [Count Substrings That Differ by One Character](https://leetcode.com/problems/count-substrings-that-differ-by-one-character/) | [无] | [C++](1501-2000/1638-Count-Substrings-That-Differ-by-One-Character/cpp-1638/) | | | +| 1639 | [Number of Ways to Form a Target String Given a Dictionary](https://leetcode.com/problems/number-of-ways-to-form-a-target-string-given-a-dictionary/) | [无] | [C++](1501-2000/1639-Number-of-Ways-to-Form-a-Target-String-Given-a-Dictionary/cpp-1639/) | | | +| 1640 | [Check Array Formation Through Concatenation](https://leetcode.com/problems/check-array-formation-through-concatenation/) | [solution](https://leetcode.com/problems/check-array-formation-through-concatenation/solution/) | [C++](1501-2000/1640-Check-Array-Formation-Through-Concatenation/cpp-1640/) | | | +| 1641 | [Count Sorted Vowel Strings](https://leetcode.com/problems/count-sorted-vowel-strings/) | [solution](https://leetcode.com/problems/count-sorted-vowel-strings/solution/) | [C++](1501-2000/1641-Count-Sorted-Vowel-Strings/cpp-1641/) | | | +| 1642 | [Furthest Building You Can Reach](https://leetcode.com/problems/furthest-building-you-can-reach/) | [无] | [C++](1501-2000/1642-Furthest-Building-You-Can-Reach/cpp-1642/) | | | +| 1643 | [Kth Smallest Instructions](https://leetcode.com/problems/kth-smallest-instructions/) | [无] | [C++](1501-2000/1643-Kth-Smallest-Instructions/cpp-1643/) | | | +| 1644 | [Lowest Common Ancestor of a Binary Tree II](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree-ii/) | [无] | [C++](1501-2000/1644-Lowest-Common-Ancestor-of-a-Binary-Tree-II/cpp-1644/) | | | +| 1645 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1646 | [Get Maximum in Generated Array](https://leetcode.com/problems/get-maximum-in-generated-array/) | [solution](https://leetcode.com/problems/get-maximum-in-generated-array/) | [C++](1501-2000/1646-Get-Maximum-in-Generated-Array/cpp-1646/) | | | +| 1647 | [Minimum Deletions to Make Character Frequencies Unique](https://leetcode.com/problems/minimum-deletions-to-make-character-frequencies-unique/) | [无] | [C++](1501-2000/1647-Minimum-Deletions-to-Make-Character-Frequencies-Unique/cpp-1647/) | | | +| 1648 | [Sell Diminishing-Valued Colored Balls](https://leetcode.com/problems/sell-diminishing-valued-colored-balls/) | [无] | [C++](1501-2000/1648-Sell-Diminishing-Valued-Colored-Balls/cpp-1648/) | | | +| 1649 | [Create Sorted Array through Instructions](https://leetcode.com/problems/create-sorted-array-through-instructions/) | [solution](https://leetcode.com/problems/create-sorted-array-through-instructions/solution/)
[缺:树状数组;归并] | [C++](1501-2000/1649-Create-Sorted-Array-through-Instructions/cpp-1649/) | | | +| 1650 | [Lowest Common Ancestor of a Binary Tree III](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree-iii/) | [无] | [C++](1501-2000/1650-Lowest-Common-Ancestor-of-a-Binary-Tree-III/cpp-1650/) | | | +| 1651 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1652 | [Defuse the Bomb](https://leetcode.com/problems/defuse-the-bomb/) | [无] | [C++](1501-2000/1652-Defuse-the-Bomb/cpp-1652/) | | | +| 1653 | [Minimum Deletions to Make String Balanced](https://leetcode.com/problems/minimum-deletions-to-make-string-balanced/) | [无] | [C++](1501-2000/1653-Minimum-Deletions-to-Make-String-Balanced/cpp-1653/) | | | +| 1654 | [Minimum Jumps to Reach Home](https://leetcode.com/problems/minimum-jumps-to-reach-home/) | [无] | [C++](1501-2000/1654-Minimum-Jumps-to-Reach-Home/cpp-1654/) | | | +| 1655 | [Distribute Repeating Integers](https://leetcode.com/problems/distribute-repeating-integers/) | [无] | [C++](1501-2000/1655-Distribute-Repeating-Integers/cpp-1655/) | | | +| 1656 | [Design an Ordered Stream](https://leetcode.com/problems/design-an-ordered-stream/) | [无] | [C++](1501-2000/1656-Design-an-Ordered-Stream/cpp-1656/) | | | +| 1657 | [Determine if Two Strings Are Close](https://leetcode.com/problems/determine-if-two-strings-are-close/) | [solution](https://leetcode.com/problems/determine-if-two-strings-are-close/solution/) | [C++](1501-2000/1657-Determine-if-Two-Strings-Are-Close/cpp-1657/) | | | +| 1658 | [Minimum Operations to Reduce X to Zero](https://leetcode.com/problems/minimum-operations-to-reduce-x-to-zero/) | [solution](https://leetcode.com/problems/minimum-operations-to-reduce-x-to-zero/solution/) | [C++](1501-2000/1658-Minimum-Operations-to-Reduce-X-to-Zero/cpp-1658/) | | | +| 1659 | [Maximize Grid Happiness](https://leetcode.com/problems/maximize-grid-happiness/) | [无] | [C++](1501-2000/1659-Maximize-Grid-Happiness/cpp-1659/) | [Java](1501-2000/1659-Maximize-Grid-Happiness/java-1659/) | | +| 1660 | [Correct a Binary Tree](https://leetcode.com/problems/correct-a-binary-tree/) | [无] | [C++](1501-2000/1660-Correct-a-Binary-Tree/cpp-1660/) | | | +| 1661 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1662 | [Check If Two String Arrays are Equivalent](https://leetcode.com/problems/check-if-two-string-arrays-are-equivalent/) | [solution](https://leetcode.com/problems/check-if-two-string-arrays-are-equivalent/) | [C++](1501-2000/1662-Check-If-Two-String-Arrays-are-Equivalent/cpp-1662/) | | | +| 1663 | [Smallest String With A Given Numeric Value](https://leetcode.com/problems/smallest-string-with-a-given-numeric-value/) | [solution](https://leetcode.com/problems/smallest-string-with-a-given-numeric-value/solution/) | [C++](1501-2000/1663-Smallest-String-With-A-Given-Numeric-Value/cpp-1663/) | | | +| 1664 | [Ways to Make a Fair Array](https://leetcode.com/problems/ways-to-make-a-fair-array/) | [无] | [C++](1501-2000/1664-Ways-to-Make-a-Fair-Array/cpp-1664/) | | | +| 1665 | [Minimum Initial Energy to Finish Tasks](https://leetcode.com/problems/minimum-initial-energy-to-finish-tasks/) | [无] | [C++](1501-2000/1665-Minimum-Initial-Energy-to-Finish-Tasks/cpp-1665/) | | | +| 1666 | [Change the Root of a Binary Tree](https://leetcode.com/problems/change-the-root-of-a-binary-tree/) | [无] | [C++](1501-2000/1666-Change-the-Root-of-a-Binary-Tree/cpp-1666/) | | | +| 1667 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1668 | [Maximum Repeating Substring](https://leetcode.com/problems/maximum-repeating-substring/) | [无] | [C++](1501-2000/1668-Maximum-Repeating-Substring/cpp-1668/) | | | +| 1669 | [Merge In Between Linked Lists](https://leetcode.com/problems/merge-in-between-linked-lists/) | [无] | [C++](1501-2000/1669-Merge-In-Between-Linked-Lists/cpp-1669/) | | | +| 1670 | [Design Front Middle Back Queue](https://leetcode.com/problems/design-front-middle-back-queue/) | [无] | [C++](1501-2000/1670-Design-Front-Middle-Back-Queue/cpp-1670/) | | | +| 1671 | [Minimum Number of Removals to Make Mountain Array](https://leetcode.com/problems/minimum-number-of-removals-to-make-mountain-array/) | [无] | [C++](1501-2000/1671-Minimum-Number-of-Removals-to-Make-Mountain-Array/cpp-1671/) | | | +| 1672 | [Richest Customer Wealth](https://leetcode.com/problems/richest-customer-wealth/) | [无] | [C++](1501-2000/1672-Richest-Customer-Wealth/cpp-1672/) | | | +| 1673 | [Find the Most Competitive Subsequence](https://leetcode.com/problems/find-the-most-competitive-subsequence/) | [solution](https://leetcode.com/problems/find-the-most-competitive-subsequence/solution/) | [C++](1501-2000/1673-Find-the-Most-Competitive-Subsequence/cpp-1673/) | | | +| 1674 | [Minimum Moves to Make Array Complementary](https://leetcode.com/problems/minimum-moves-to-make-array-complementary/) | [无] | [C++](1501-2000/1674-Minimum-Moves-to-Make-Array-Complementary/cpp-1674/) | | | +| 1675 | [Minimize Deviation in Array](https://leetcode.com/problems/minimize-deviation-in-array/) | [solution](https://leetcode.com/problems/minimize-deviation-in-array/) | [C++](1501-2000/1675-Minimize-Deviation-in-Array/cpp-1675/) | | | +| 1676 | [Lowest Common Ancestor of a Binary Tree IV](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree-iv/) | [无] | [C++](1501-2000/1676-Lowest-Common-Ancestor-of-a-Binary-Tree-IV/cpp-1676/) | | | +| 1677 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1678 | [Goal Parser Interpretation](https://leetcode.com/problems/goal-parser-interpretation/) | [无] | [C++](1501-2000/1678-Goal-Parser-Interpretation/cpp-1678/) | | | +| 1679 | [Max Number of K-Sum Pairs](https://leetcode.com/problems/max-number-of-k-sum-pairs/) | [solution](https://leetcode.com/problems/max-number-of-k-sum-pairs/solution/) | [C++](1501-2000/1679-Max-Number-of-K-Sum-Pairs/cpp-1679/) | | | +| 1680 | [Concatenation of Consecutive Binary Numbers](https://leetcode.com/problems/concatenation-of-consecutive-binary-numbers/) | [solution](https://leetcode.com/problems/concatenation-of-consecutive-binary-numbers/solution/) | [C++](1501-2000/1680-Concatenation-of-Consecutive-Binary-Numbers/cpp-1680/) | | | +| 1681 | [Minimum Incompatibility](https://leetcode.com/problems/minimum-incompatibility/) | [无] | [C++](1501-2000/1681-Minimum-Incompatibility/cpp-1681/) | | | +| 1682 | [Longest Palindromic Subsequence II](https://leetcode.com/problems/longest-palindromic-subsequence-ii/) | [无] | [C++](1501-2000/1682-Longest-Palindromic-Subsequence-II/cpp-1682/) | | | +| 1683 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1684 | [Count the Number of Consistent Strings](https://leetcode.com/problems/count-the-number-of-consistent-strings/) | [无] | [C++](1501-2000/1684-Count-the-Number-of-Consistent-Strings/cpp-1684/) | | | +| 1685 | [Sum of Absolute Differences in a Sorted Array](https://leetcode.com/problems/sum-of-absolute-differences-in-a-sorted-array/) | [无] | [C++](1501-2000/1685-Sum-of-Absolute-Differences-in-a-Sorted-Array/cpp-1685/) | | | +| 1686 | [Stone Game VI](https://leetcode.com/problems/stone-game-vi/) | [无] | [C++](1501-2000/1686-Stone-Game-VI/cpp-1686/) | | | +| 1687 | [Delivering Boxes from Storage to Ports](https://leetcode.com/problems/delivering-boxes-from-storage-to-ports/) | [无]
[缺:dp + 优化] | [C++](1501-2000/1687-Delivering-Boxes-from-Storage-to-Ports/cpp-1687/) | | | +| 1688 | [Count of Matches in Tournament](https://leetcode.com/problems/count-of-matches-in-tournament/) | [C++](1501-2000/1688-Count-of-Matches-in-Tournament/cpp-1688/) | | | | +| 1689 | [Partitioning Into Minimum Number Of Deci-Binary Numbers](https://leetcode.com/problems/partitioning-into-minimum-number-of-deci-binary-numbers/) | [solution](https://leetcode.com/problems/partitioning-into-minimum-number-of-deci-binary-numbers/solution/) | [C++](1501-2000/1689-Partitioning-Into-Minimum-Number-Of-Deci-Binary-Numbers/cpp-1689/) | | | +| 1690 | [Stone Game VII](https://leetcode.com/problems/stone-game-vii/) | [solution](https://leetcode.com/problems/stone-game-vii/solution/)
[缺:记忆化搜索;DP 空间优化] | [C++](1501-2000/1690-Stone-Game-VII/cpp-1690/) | | | +| 1691 | [Maximum Height by Stacking Cuboids](https://leetcode.com/problems/maximum-height-by-stacking-cuboids/) | [无] | [C++](1501-2000/1691-Maximum-Height-by-Stacking-Cuboids/cpp-1691/) | | | +| 1692 | [Count Ways to Distribute Candies](https://leetcode.com/problems/count-ways-to-distribute-candies/) | [无] | [C++](1501-2000/1692-Count-Ways-to-Distribute-Candies/cpp-1692/) | | | +| 1693 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1694 | [Reformat Phone Number](https://leetcode.com/problems/reformat-phone-number/) | [无] | [C++](1501-2000/1694-Reformat-Phone-Number/cpp-1694/) | | | +| 1695 | [Maximum Erasure Value](https://leetcode.com/problems/maximum-erasure-value/) | [无] | [C++](1501-2000/1695-Maximum-Erasure-Value/cpp-1695/) | | | +| 1696 | [Jump Game VI](https://leetcode.com/problems/jump-game-vi/) | [无] | [C++](1501-2000/1696-Jump-Game-VI/cpp-1696/) | | | +| 1697 | [Checking Existence of Edge Length Limited Paths](https://leetcode.com/problems/checking-existence-of-edge-length-limited-paths/) | [无] | [C++](1501-2000/1697-Checking-Existence-of-Edge-Length-Limited-Paths/cpp-1697/) | | | +| 1698 | [Number of Distinct Substrings in a String](https://leetcode.com/problems/number-of-distinct-substrings-in-a-string/) | [无] | [C++](1501-2000/1698-Number-of-Distinct-Substrings-in-a-String/cpp-1698/) | | | +| 1699 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1700 | [Number of Students Unable to Eat Lunch](https://leetcode.com/problems/number-of-students-unable-to-eat-lunch/) | [无] | [C++](1501-2000/1700-Number-of-Students-Unable-to-Eat-Lunch/cpp-1700/) | | | +| 1701 | [Average Waiting Time](https://leetcode.com/problems/average-waiting-time/) | [无] | [C++](1501-2000/1701-Average-Waiting-Time/cpp-1701/) | | | +| 1702 | [Maximum Binary String After Change](https://leetcode.com/problems/maximum-binary-string-after-change/) | [无] | [C++](1501-2000/1702-Maximum-Binary-String-After-Change/cpp-1702/) | | | +| 1703 | [Minimum Adjacent Swaps for K Consecutive Ones](https://leetcode.com/problems/minimum-adjacent-swaps-for-k-consecutive-ones/) | [无] | [C++](1501-2000/1703-Minimum-Adjacent-Swaps-for-K-Consecutive-Ones/cpp-1703/) | | | +| 1704 | [Determine if String Halves Are Alike](https://leetcode.com/problems/determine-if-string-halves-are-alike/) | [solution](https://leetcode.com/problems/determine-if-string-halves-are-alike/solution/) | [C++](1501-2000/1704-Determine-if-String-Halves-Are-Alike/cpp-1704/) | | | +| 1705 | [Maximum Number of Eaten Apples](https://leetcode.com/problems/maximum-number-of-eaten-apples/) | [solution](https://leetcode.com/problems/maximum-number-of-eaten-apples/solution/) | [C++](1501-2000/1705-Maximum-Number-of-Eaten-Apples/cpp-1705/) | | | +| 1706 | [Where Will the Ball Fall](https://leetcode.com/problems/where-will-the-ball-fall/) | [无] | [C++](1501-2000/1706-Where-Will-the-Ball-Fall/cpp-1706/) | | | +| 1707 | [Maximum XOR With an Element From Array](https://leetcode.com/problems/maximum-xor-with-an-element-from-array/) | [无] | [C++](1501-2000/1707-Maximum-XOR-With-an-Element-From-Array/cpp-1707/) | | | +| 1708 | [Largest Subarray Length K](https://leetcode.com/problems/largest-subarray-length-k/) | [无] | [C++](1708-Largest-Subarray-Length-K/cpp-1708/) | | | +| 1709 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1710 | [Maximum Units on a Truck](https://leetcode.com/problems/maximum-units-on-a-truck/) | [solution](https://leetcode.com/problems/maximum-units-on-a-truck/solution/) | [C++](1501-2000/1710-Maximum-Units-on-a-Truck/cpp-1710/) | | | +| 1711 | [Count Good Meals](https://leetcode.com/problems/count-good-meals/) | [无] | [C++](1711-Count-Good-Meals/cpp-1711/) | | | +| 1712 | [Ways to Split Array Into Three Subarrays](https://leetcode.com/problems/ways-to-split-array-into-three-subarrays/) | [solution](https://leetcode.com/problems/ways-to-split-array-into-three-subarrays/solution/) | [C++](1501-2000/1712-Ways-to-Split-Array-Into-Three-Subarrays/cpp-1712/) | | | +| 1713 | [Minimum Operations to Make a Subsequence](https://leetcode.com/problems/minimum-operations-to-make-a-subsequence/) | [无] | [C++](1501-2000/1713-Minimum-Operations-to-Make-a-Subsequence/cpp-1713/) | | | +| 1714 | [Sum Of Special Evenly-Spaced Elements In Array](https://leetcode.com/problems/sum-of-special-evenly-spaced-elements-in-array/) | [无] | [C++](1501-2000/1714-Sum-Of-Special-Evenly-Spaced-Elements-In-Array/cpp-1714/) | | | +| 1715 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1716 | [Calculate Money in Leetcode Bank](https://leetcode.com/problems/calculate-money-in-leetcode-bank/) | [无] | [C++](1501-2000/1716-Calculate-Money-in-Leetcode-Bank/cpp-1716/) | | | +| 1717 | [Maximum Score From Removing Substrings](https://leetcode.com/problems/maximum-score-from-removing-substrings/) | [无] | [C++](1501-2000/1717-Maximum-Score-From-Removing-Substrings/cpp-1717/) | | | +| 1718 | [Construct the Lexicographically Largest Valid Sequence](https://leetcode.com/problems/construct-the-lexicographically-largest-valid-sequence/) | [无] | [C++](1501-2000/1718-Construct-the-Lexicographically-Largest-Valid-Sequence/cpp-1718/) | | | +| 1719 | [Number Of Ways To Reconstruct A Tree](https://leetcode.com/problems/number-of-ways-to-reconstruct-a-tree/) | [无] | [C++](1501-2000/1719-Number-Of-Ways-To-Reconstruct-A-Tree/cpp-1719/) | | | +| 1720 | [Decode XORed Array](https://leetcode.com/problems/decode-xored-array/) | [无] | [C++](1501-2000/1720-Decode-XORed-Array/cpp-1720/) | | | +| 1721 | [Swapping Nodes in a Linked List](https://leetcode.com/problems/swapping-nodes-in-a-linked-list/) | [无] | [C++](1501-2000/1721-Swapping-Nodes-in-a-Linked-List/cpp-1721/) | | | +| 1722 | [Minimize Hamming Distance After Swap Operations](https://leetcode.com/problems/minimize-hamming-distance-after-swap-operations/) | [无] | [C++](1501-2000/1722-Minimize-Hamming-Distance-After-Swap-Operations/cpp-1722/) | | | +| 1723 | [Find Minimum Time to Finish All Jobs](https://leetcode.com/problems/find-minimum-time-to-finish-all-jobs/) | [无] | [C++](1501-2000/1723-Find-Minimum-Time-to-Finish-All-Jobs/cpp-1723/) | | | +| 1724 | [Checking Existence of Edge Length Limited Paths II](https://leetcode.com/problems/checking-existence-of-edge-length-limited-paths-ii/) | [无] | [C++](1501-2000/1724-Checking-Existence-of-Edge-Length-Limited-Paths-II/cpp-1724/) | | | +| 1725 | [Number Of Rectangles That Can Form The Largest Square](https://leetcode.com/problems/number-of-rectangles-that-can-form-the-largest-square/) | [无] | [C++](1501-2000/1725-Number-Of-Rectangles-That-Can-Form-The-Largest-Square/cpp-1725/) | | | +| 1726 | [Tuple with Same Product](https://leetcode.com/problems/tuple-with-same-product/) | [无] | [C++](1501-2000/1726-Tuple-with-Same-Product/cpp-1726/)| | | +| 1727 | [Largest Submatrix With Rearrangements](https://leetcode.com/problems/largest-submatrix-with-rearrangements/) | [无] | [C++](1501-2000/1727-Largest-Submatrix-With-Rearrangements/cpp-1727/) | | | +| 1728 | [Cat and Mouse II](https://leetcode.com/problems/cat-and-mouse-ii/) | [无] | [C++](1501-2000/1728-Cat-and-Mouse-II/cpp-1728/) | | | +| 1729 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1730 | [Shortest Path to Get Food](https://leetcode.com/problems/shortest-path-to-get-food/) | [无] | [C++](1501-2000/1730-Shortest-Path-to-Get-Food/cpp-1730/) | | | +| 1731 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1732 | [Find the Highest Altitude](https://leetcode.com/problems/find-the-highest-altitude/) | [无] | [C++](1501-2000/1732-Find-the-Highest-Altitude/cpp-1732/) | | | +| 1733 | [Minimum Number of People to Teach](https://leetcode.com/problems/minimum-number-of-people-to-teach/) | [无] | [C++](1501-2000/1733-Minimum-Number-of-People-to-Teach/cpp-1733/) | | | +| 1734 | [Decode XORed Permutation](https://leetcode.com/problems/decode-xored-permutation/) | [无] | [C++](1501-2000/1734-Decode-XORed-Permutation/cpp-1734/) | | | +| 1735 | [Count Ways to Make Array With Product](https://leetcode.com/problems/count-ways-to-make-array-with-product/) | [无] | [C++](1501-2000/1735-Count-Ways-to-Make-Array-With-Product/cpp-1735/) | | | +| 1736 | [Latest Time by Replacing Hidden Digits](https://leetcode.com/problems/latest-time-by-replacing-hidden-digits/) | [无] | [C++](1501-2000/1736-Latest-Time-by-Replacing-Hidden-Digits/cpp-1736/) | | | +| 1737 | [Change Minimum Characters to Satisfy One of Three Conditions](https://leetcode.com/problems/change-minimum-characters-to-satisfy-one-of-three-conditions/) | [无] | [C++](1501-2000/1737-Change-Minimum-Characters-to-Satisfy-One-of-Three-Conditions/cpp-1737/) | | | +| 1738 | [Find Kth Largest XOR Coordinate Value](https://leetcode.com/problems/find-kth-largest-xor-coordinate-value/) | [无] | [C++](1501-2000/1738-Find-Kth-Largest-XOR-Coordinate-Value/cpp-1738/) | | | +| 1739 | [Building Boxes](https://leetcode.com/problems/building-boxes/) | [无]
[缺:二分;数学] | [C++](1501-2000/1739-Building-Boxes/cpp-1739/) | | | +| 1740 | [Find Distance in a Binary Tree](https://leetcode.com/problems/find-distance-in-a-binary-tree/) | [无]
[缺:LCA] | [C++](1501-2000/1740-Find-Distance-in-a-Binary-Tree/cpp-1740/) | | | +| 1741 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1742 | [Maximum Number of Balls in a Box](https://leetcode.com/problems/maximum-number-of-balls-in-a-box/) | [无] | [C++](1501-2000/1742-Maximum-Number-of-Balls-in-a-Box/cpp-1742/) | | | +| 1743 | [Restore the Array From Adjacent Pairs](https://leetcode.com/problems/restore-the-array-from-adjacent-pairs/) | [无] | [C++](1501-2000/1743-Restore-the-Array-From-Adjacent-Pairs/cpp-1743/) | | | +| 1744 | [Can You Eat Your Favorite Candy on Your Favorite Day?](https://leetcode.com/problems/can-you-eat-your-favorite-candy-on-your-favorite-day/) | [无] | [C++](1501-2000/1744-Can-You-Eat-Your-Favorite-Candy-on-Your-Favorite-Day/cpp-1744/) | | | +| 1745 | [Palindrome Partitioning IV](https://leetcode.com/problems/palindrome-partitioning-iv/) | [无] | [C++](1501-2000/1745-Palindrome-Partitioning-IV/cpp-1745/) | | | +| 1746 | [Maximum Subarray Sum After One Operation](https://leetcode.com/problems/maximum-subarray-sum-after-one-operation/) | [无] | [C++](1501-2000/1746-Maximum-Subarray-Sum-After-One-Operation/cpp-1746/) | | | +| 1747 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1748 | [Sum of Unique Elements](https://leetcode.com/problems/sum-of-unique-elements/) | [无] | [C++](1501-2000/1748-Sum-of-Unique-Elements/cpp-1748/) | | | +| 1749 | [Maximum Absolute Sum of Any Subarray](https://leetcode.com/problems/maximum-absolute-sum-of-any-subarray/) | [无] | [C++](1501-2000/1749-Maximum-Absolute-Sum-of-Any-Subarray/cpp-1749/) | | | +| 1750 | [Minimum Length of String After Deleting Similar Ends](https://leetcode.com/problems/minimum-length-of-string-after-deleting-similar-ends/) | [无] | [C++](1501-2000/1750-Minimum-Length-of-String-After-Deleting-Similar-Ends/cpp-1750/) | | | +| 1751 | [Maximum Number of Events That Can Be Attended II](https://leetcode.com/problems/maximum-number-of-events-that-can-be-attended-ii/) | [无] | [C++](1501-2000/1751-Maximum-Number-of-Events-That-Can-Be-Attended-II/cpp-1751/) | | | +| 1752 | [Check if Array Is Sorted and Rotated](https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/) | [无] | [C++](1501-2000/1752-Check-if-Array-Is-Sorted-and-Rotated/cpp-1752/) | | | +| 1753 | [Maximum Score From Removing Stones](https://leetcode.com/problems/maximum-score-from-removing-stones/) | [无] | [C++](1501-2000/1753-Maximum-Score-From-Removing-Stones/cpp-1753/) | | | +| 1754 | [Largest Merge Of Two Strings](https://leetcode.com/problems/largest-merge-of-two-strings/) | [无] | [C++](1501-2000/1754-Largest-Merge-Of-Two-Strings/cpp-1754/) | | | +| 1755 | [Closest Subsequence Sum](https://leetcode.com/problems/closest-subsequence-sum/) | [无] | [C++](1501-2000/1755-Closest-Subsequence-Sum/cpp-1755/) | | | +| 1756 | [Design Most Recently Used Queue](https://leetcode.com/problems/design-most-recently-used-queue/) | [无]
[缺:线段树,sqrt 分解] | [C++](1501-2000/1756-Design-Most-Recently-Used-Queue/cpp-1756/) | | | +| 1757 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1758 | [Minimum Changes To Make Alternating Binary String](https://leetcode.com/problems/minimum-changes-to-make-alternating-binary-string/) | [无] | [C++](1501-2000/1758-Minimum-Changes-To-Make-Alternating-Binary-String/cpp-1758/) | | | +| 1759 | [Count Number of Homogenous Substrings](https://leetcode.com/problems/count-number-of-homogenous-substrings/) | [无] | [C++](1501-2000/1759-Count-Number-of-Homogenous-Substrings/cpp-1759/) | | | +| 1760 | [Minimum Limit of Balls in a Bag](https://leetcode.com/problems/minimum-limit-of-balls-in-a-bag/) | [无] | [C++](1501-2000/1760-Minimum-Limit-of-Balls-in-a-Bag/cpp-1760/) | | | +| 1761 | [Minimum Degree of a Connected Trio in a Graph](https://leetcode.com/problems/minimum-degree-of-a-connected-trio-in-a-graph/) | [无] | [C++](1501-2000/1761-Minimum-Degree-of-a-Connected-Trio-in-a-Graph/cpp-1761/) | | | +| 1762 | [Buildings With an Ocean View](https://leetcode.com/problems/buildings-with-an-ocean-view/) | [无] | [C++](1501-2000/1762-Buildings-With-an-Ocean-View/cpp-1762/) | | | +| 1763 | [Longest Nice Substring](https://leetcode.com/problems/longest-nice-substring/) | [无] | [C++](1501-2000/1763-Longest-Nice-Substring/cpp-1763/) | | | +| 1764 | [Form Array by Concatenating Subarrays of Another Array](1501-2000/1764-Form-Array-by-Concatenating-Subarrays-of-Another-Array/cpp-1764/) | | | | | +| 1765 | [Map of Highest Peak](https://leetcode.com/problems/map-of-highest-peak/) | [无] | [C++](1501-2000/1765-Map-of-Highest-Peak/cpp-1765/) | | | +| 1766 | [Tree of Coprimes](https://leetcode.com/problems/tree-of-coprimes/) | [无] | [C++](1501-2000/1766-Tree-of-Coprimes/cpp-1766/) | | | +| 1767 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1768 | [Merge Strings Alternately](https://leetcode.com/problems/merge-strings-alternately/) | [无] | [C++](1501-2000/1768-Merge-Strings-Alternately/cpp-1768/) | | | +| 1769 | [Minimum Number of Operations to Move All Balls to Each Box](https://leetcode.com/problems/minimum-number-of-operations-to-move-all-balls-to-each-box/) | [无] | [C++](1501-2000/1769-Minimum-Number-of-Operations-to-Move-All-Balls-to-Each-Box/cpp-1769/) | | | +| 1770 | [Maximum Score from Performing Multiplication Operations](https://leetcode.com/problems/maximum-score-from-performing-multiplication-operations/) | [无] | [C++](1501-2000/1770-Maximum-Score-from-Performing-Multiplication-Operations/cpp-1770/) | | | +| 1771 | [Maximize Palindrome Length From Subsequences](https://leetcode.com/problems/maximize-palindrome-length-from-subsequences/) | [无] | [C++](1501-2000/1771-Maximize-Palindrome-Length-From-Subsequences/cpp-1771/) | | | +| 1772 | [Sort Features by Popularity](https://leetcode.com/problems/sort-features-by-popularity/) | [无] | [C++](1501-2000/1772-Sort-Features-by-Popularity/cpp-1772/) | | | +| 1773 | [Count Items Matching a Rule](https://leetcode.com/problems/count-items-matching-a-rule/) | [无] | [C++](1501-2000/1773-Count-Items-Matching-a-Rule/cpp-1773/) | | | +| 1774 | [Closest Dessert Cost](https://leetcode.com/problems/closest-dessert-cost/) | [无] | [C++](1501-2000/1774-Closest-Dessert-Cost/cpp-1774/) | | | +| 1775 | [Equal Sum Arrays With Minimum Number of Operations](https://leetcode.com/problems/equal-sum-arrays-with-minimum-number-of-operations/) | [无] | [C++](1501-2000/1775-Equal-Sum-Arrays-With-Minimum-Number-of-Operations/cpp-1775/) | | | +| 1776 | [Car Fleet II](https://leetcode.com/problems/car-fleet-ii/) | [无]
[缺:stack] | [C++](1501-2000/1776-Car-Fleet-II/cpp-1776/) | | | +| 1777 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1778 | [Shortest Path in a Hidden Grid](https://leetcode.com/problems/shortest-path-in-a-hidden-grid/) | [无] | [C++](1501-2000/1778-Shortest-Path-in-a-Hidden-Grid/cpp-1778/) | | | +| 1779 | [Find Nearest Point That Has the Same X or Y Coordinate](https://leetcode.com/problems/find-nearest-point-that-has-the-same-x-or-y-coordinate/) | [无] | [C++](1501-2000/1779-Find-Nearest-Point-That-Has-the-Same-X-or-Y-Coordinate/cpp-1779/) | | | +| 1780 | [Check if Number is a Sum of Powers of Three](https://leetcode.com/problems/check-if-number-is-a-sum-of-powers-of-three/) | [无] | [C++](1501-2000/1780-Check-if-Number-is-a-Sum-of-Powers-of-Three/cpp-1780/) | | | +| 1781 | [Sum of Beauty of All Substrings](https://leetcode.com/problems/sum-of-beauty-of-all-substrings/) | [无] | [C++](1501-2000/1781-Sum-of-Beauty-of-All-Substrings/cpp-1781/) | | | +| 1782 | [Count Pairs Of Nodes](https://leetcode.com/problems/count-pairs-of-nodes/) | [无] | [C++](1501-2000/1782-Count-Pairs-Of-Nodes/cpp-1782/) | | | +| 1783 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1784 | [Check if Binary String Has at Most One Segment of Ones](https://leetcode.com/problems/check-if-binary-string-has-at-most-one-segment-of-ones/) | [无] | [C++](1501-2000/1784-Check-if-Binary-String-Has-at-Most-One-Segment-of-Ones/cpp-1784/) | | | +| 1785 | [Minimum Elements to Add to Form a Given Sum](https://leetcode.com/problems/minimum-elements-to-add-to-form-a-given-sum/) | [无] | [C++](1501-2000/1785-Minimum-Elements-to-Add-to-Form-a-Given-Sum/cpp-1785/) | | | +| 1786 | [Number of Restricted Paths From First to Last Node](https://leetcode.com/problems/number-of-restricted-paths-from-first-to-last-node/) | [无] | [C++](1501-2000/1786-Number-of-Restricted-Paths-From-First-to-Last-Node/cpp-1786/) | | | +| 1787 | [Make the XOR of All Segments Equal to Zero](https://leetcode.com/problems/make-the-xor-of-all-segments-equal-to-zero/) | [无] | [C++](1501-2000/1787-Make-the-XOR-of-All-Segments-Equal-to-Zero/cpp-1787/) | | | +| 1788 | [Maximize the Beauty of the Garden](https://leetcode.com/problems/maximize-the-beauty-of-the-garden/) | [无] | [C++](1501-2000/1788-Maximize-the-Beauty-of-the-Garden/cpp-1788/) | | | +| 1789 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1790 | [Check if One String Swap Can Make Strings Equal](https://leetcode.com/problems/check-if-one-string-swap-can-make-strings-equal/) | [无] | [C++](1501-2000/1790-Check-if-One-String-Swap-Can-Make-Strings-Equal/cpp-1790/) | | | +| 1791 | [Find Center of Star Graph](https://leetcode.com/problems/find-center-of-star-graph/) | [无] | [C++](1501-2000/1791-Find-Center-of-Star-Graph/cpp-1791/) | | | +| 1792 | [Maximum Average Pass Ratio](https://leetcode.com/problems/maximum-average-pass-ratio/) | [无] | [C++](1501-2000/1792-Maximum-Average-Pass-Ratio/cpp-1792/) | | | +| 1793 | [Maximum Score of a Good Subarray](https://leetcode.com/problems/maximum-score-of-a-good-subarray/) | [无] | [C++](1501-2000/1793-Maximum-Score-of-a-Good-Subarray/cpp-1793/) | | | +| 1794 | [Count Pairs of Equal Substrings With Minimum Difference](https://leetcode.com/problems/count-pairs-of-equal-substrings-with-minimum-difference/) | [无] | [C++](1501-2000/1794-Count-Pairs-of-Equal-Substrings-With-Minimum-Difference/cpp-1794/) | | | +| 1795 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1796 | [Second Largest Digit in a String](https://leetcode.com/problems/second-largest-digit-in-a-string/) | [无] | [C++](1501-2000/1796-Second-Largest-Digit-in-a-String/cpp-1796/) | | | +| 1797 | [Design Authentication Manager](https://leetcode.com/problems/design-authentication-manager/) | [无] | [C++](1501-2000/1797-Design-Authentication-Manager/cpp-1797/) | | | +| 1798 | [Maximum Number of Consecutive Values You Can Make](https://leetcode.com/problems/maximum-number-of-consecutive-values-you-can-make/) | [无] | [C++](1501-2000/1798-Maximum-Number-of-Consecutive-Values-You-Can-Make/cpp-1798/) | | | +| 1799 | [Maximize Score After N Operations](https://leetcode.com/problems/maximize-score-after-n-operations/) | [无] | [C++](1501-2000/1799-Maximize-Score-After-N-Operations/cpp-1799/) | | | +| 1800 | [Maximum Ascending Subarray Sum](https://leetcode.com/problems/maximum-ascending-subarray-sum/) | [无] | [C++](1501-2000/1800-Maximum-Ascending-Subarray-Sum/cpp-1800/) | | | +| 1801 | [Number of Orders in the Backlog](https://leetcode.com/problems/number-of-orders-in-the-backlog/) | [无] | [C++](1501-2000/1801-Number-of-Orders-in-the-Backlog/cpp-1801/) | | | +| 1802 | [Maximum Value at a Given Index in a Bounded Array](https://leetcode.com/problems/maximum-value-at-a-given-index-in-a-bounded-array/) | [无] | [C++](1501-2000/1802-Maximum-Value-at-a-Given-Index-in-a-Bounded-Array/cpp-1802/) | | | +| 1803 | [Count Pairs With XOR in a Range](https://leetcode.com/problems/count-pairs-with-xor-in-a-range/) | [无] | [C++](1501-2000/1803-Count-Pairs-With-XOR-in-a-Range/cpp-1803/) | | | +| 1804 | [Implement Trie II (Prefix Tree)](https://leetcode.com/problems/implement-trie-ii-prefix-tree/) | [无] | [C++](1501-2000/Implement-Trie-II/cpp-1804/) | | | +| 1805 | [Number of Different Integers in a String](https://leetcode.com/problems/number-of-different-integers-in-a-string/) | [无] | [C++](1501-2000/1805-Number-of-Different-Integers-in-a-String/cpp-1805/) | | | +| 1806 | [Minimum Number of Operations to Reinitialize a Permutation](https://leetcode.com/problems/minimum-number-of-operations-to-reinitialize-a-permutation/) | [无]
[缺:数学方法] | [C++](1501-2000/1806-Minimum-Number-of-Operations-to-Reinitialize-a-Permutation/cpp-1806/) | | | +| 1807 | [Evaluate the Bracket Pairs of a String](https://leetcode.com/problems/evaluate-the-bracket-pairs-of-a-string/) | [无] | [C++](1501-2000/1807-Evaluate-the-Bracket-Pairs-of-a-String/cpp-1807/) | | | +| 1808 | [Maximize Number of Nice Divisors](https://leetcode.com/problems/maximize-number-of-nice-divisors/) | [无] | [C++](1501-2000/1808-Maximize-Number-of-Nice-Divisors/cpp-1808/) | | | +| 1809 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1810 | [Minimum Path Cost in a Hidden Grid](https://leetcode-cn.com/problems/minimum-path-cost-in-a-hidden-grid/) | [无] | [C++](1501-2000/1810-Minimum-Path-Cost-in-a-Hidden-Grid/cpp-1810/) | | | +| 1811 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1812 | [Determine Color of a Chessboard Square](https://leetcode.com/problems/determine-color-of-a-chessboard-square/) | [无] | [C++](1501-2000/1812-Determine-Color-of-a-Chessboard-Square/cpp-1812/) | | | +| 1813 | [Sentence Similarity III](https://leetcode.com/problems/sentence-similarity-iii/) | [无] | [C++](1501-2000/1813-Sentence-Similarity-III/cpp-1813/) | | | +| 1814 | [Count Nice Pairs in an Array](https://leetcode.com/problems/count-nice-pairs-in-an-array/) | [无] | [C++](1501-2000/1814-Count-Nice-Pairs-in-an-Array/cpp-1814/) | | | +| 1815 | [Maximum Number of Groups Getting Fresh Donuts](https://leetcode.com/problems/maximum-number-of-groups-getting-fresh-donuts/) | [无] | [C++](1501-2000/1815-Maximum-Number-of-Groups-Getting-Fresh-Donuts/cpp-1815/) | | | +| 1816 | [Truncate Sentence](https://leetcode.com/problems/truncate-sentence/) | [无] | [C++](1501-2000/1816-Truncate-Sentence/cpp-1816/) | | | +| 1817 | [Finding the Users Active Minutes](https://leetcode.com/problems/finding-the-users-active-minutes/) | [无] | [C++](1501-2000/1817-Finding-the-Users-Active-Minutes/cpp-1817/) | | | +| 1818 | [Minimum Absolute Sum Difference](https://leetcode.com/problems/minimum-absolute-sum-difference/) | [无] | [C++](1501-2000/1818-Minimum-Absolute-Sum-Difference/cpp-1818/) | | | +| 1819 | [Number of Different Subsequences GCDs](https://leetcode.com/problems/number-of-different-subsequences-gcds/) | [无] | [C++](1501-2000/1819-Number-of-Different-Subsequences-GCDs/cpp-1819/) | | | +| 1820 | [Maximum Number of Accepted Invitations](https://leetcode.com/problems/maximum-number-of-accepted-invitations/) | [无] | [C++](1501-2000/1820-Maximum-Number-of-Accepted-Invitations/cpp-1820/) | | | +| 1821 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1822 | [Sign of the Product of an Array](https://leetcode.com/problems/sign-of-the-product-of-an-array/) | [无] | [C++](1501-2000/1822-Sign-of-the-Product-of-an-Array/cpp-1822/) | | | +| 1823 | [Find the Winner of the Circular Game](https://leetcode.com/problems/find-the-winner-of-the-circular-game/) | [无] | [C++](1501-2000/1823-Find-the-Winner-of-the-Circular-Game/cpp-1823/) | | | +| 1824 | [Minimum Sideway Jumps](https://leetcode.com/problems/minimum-sideway-jumps/) | [无]
[缺:DP] | [C++](1501-2000/1824-Minimum-Sideway-Jumps/cpp-1824/) | | | +| 1825 | [Finding MK Average](https://leetcode.com/problems/finding-mk-average/)| [无]
[缺:线段树,AVL] | [C++](1501-2000/1825-Finding-MK-Average/cpp-1825/) | | | +| 1826 | [Faulty Sensor](https://leetcode.com/problems/faulty-sensor/) | [无] | [C++](1501-2000/1826-Faulty-Sensor/cpp-1826/) | | | +| 1827 | [Minimum Operations to Make the Array Increasing](https://leetcode.com/problems/minimum-operations-to-make-the-array-increasing/) | [无] | [C++](1501-2000/1827-Minimum-Operations-to-Make-the-Array-Increasing/cpp-1827/) | | | +| 1828 | [Queries on Number of Points Inside a Circle](https://leetcode.com/problems/queries-on-number-of-points-inside-a-circle/) | [无] | [C++](1501-2000/1828-Queries-on-Number-of-Points-Inside-a-Circle/cpp-1828/)| | | +| 1829 | [Maximum XOR for Each Query](https://leetcode.com/problems/maximum-xor-for-each-query/) | [无] | [C++](1501-2000/1829-Maximum-XOR-for-Each-Query/cpp-1829/) | | | +| 1830 | [Minimum Number of Operations to Make String Sorted](https://leetcode.com/problems/minimum-number-of-operations-to-make-string-sorted/) | [无] | [C++](1501-2000/1830-Minimum-Number-of-Operations-to-Make-String-Sorted/cpp-1830/) | | | +| 1831 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1832 | [Check if the Sentence Is Pangram](https://leetcode.com/problems/check-if-the-sentence-is-pangram/) | [无] | [C++](1501-2000/1832-Check-if-the-Sentence-Is-Pangram/cpp-1832/) | | | +| 1833 | [Maximum Ice Cream Bars](https://leetcode.com/problems/maximum-ice-cream-bars/) | [无] | [C++](1501-2000/1833-Maximum-Ice-Cream-Bars/cpp-1833/) | | | +| 1834 | [Single-Threaded CPU](https://leetcode.com/problems/single-threaded-cpu/) | [无] | [C++](1501-2000/1834-Single-Threaded-CPU/cpp-1834/) | | | +| 1835 | [Find XOR Sum of All Pairs Bitwise AND](https://leetcode.com/problems/find-xor-sum-of-all-pairs-bitwise-and/) | [无]
[缺:数学方法] | [C++](1501-2000/1835-Find-XOR-Sum-of-All-Pairs-Bitwise-AND/cpp-1835/) | | | +| 1836 | [Remove Duplicates From an Unsorted Linked List](https://leetcode.com/problems/remove-duplicates-from-an-unsorted-linked-list/) | [无] | [C++](1501-2000/1836-Remove-Duplicates-From-an-Unsorted-Linked-List/cpp-1836/) | | | +| 1837 | [Sum of Digits in Base K](https://leetcode.com/problems/sum-of-digits-in-base-k/) | [无] | [C++](1501-2000/1837-Sum-of-Digits-in-Base-K/cpp-1837/) | | | +| 1838 | [Frequency of the Most Frequent Element](https://leetcode.com/problems/frequency-of-the-most-frequent-element/) | [无] | [C++](1501-2000/1838-Frequency-of-the-Most-Frequent-Element/cpp-1838/) | | | +| 1839 | [Longest Substring Of All Vowels in Order](https://leetcode.com/problems/longest-substring-of-all-vowels-in-order/) | [无] | [C++](1501-2000/1839-Longest-Substring-Of-All-Vowels-in-Order/cpp-1839/) | | | +| 1840 | [Maximum Building Height](https://leetcode.com/problems/maximum-building-height/) | [无] | [C++](1501-2000/1840-Maximum-Building-Height/cpp-1840/) | | | +| 1841 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1842 | [Next Palindrome Using Same Digits](https://leetcode.com/problems/next-palindrome-using-same-digits/) | [无] | [C++](1501-2000/1842-Next-Palindrome-Using-Same-Digits/cpp-1842/) | | | +| 1843 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1844 | [Replace All Digits with Characters](https://leetcode.com/problems/replace-all-digits-with-characters/) | [无] | [C++](1501-2000/1844-Replace-All-Digits-with-Characters/cpp-1844/) | | | +| 1845 | [Seat Reservation Manager](https://leetcode.com/problems/seat-reservation-manager/) | [无] | [C++](1501-2000/1845-Seat-Reservation-Manager/cpp-1845/) | | | +| 1846 | [Maximum Element After Decreasing and Rearranging](https://leetcode.com/problems/maximum-element-after-decreasing-and-rearranging/) | [无] | [C++](1501-2000/1846-Maximum-Element-After-Decreasing-and-Rearranging/cpp-1846/) | | | +| 1847 | [Closest Room](https://leetcode.com/problems/closest-room/) | [无] | [C++](1501-2000/1847-Closest-Room/cpp-1847/) | | | +| 1848 | [Minimum Distance to the Target Element](https://leetcode.com/problems/minimum-distance-to-the-target-element/) | [无] | [C++](1501-2000/1848-Minimum-Distance-to-the-Target-Element/cpp-1848/) | | | +| 1849 | [Splitting a String Into Descending Consecutive Values](https://leetcode.com/problems/splitting-a-string-into-descending-consecutive-values/) | [无] | [C++](1501-2000/1849-Splitting-a-String-Into-Descending-Consecutive-Values/cpp-1849/) | | | +| 1850 | [Minimum Adjacent Swaps to Reach the Kth Smallest Number](https://leetcode.com/problems/minimum-adjacent-swaps-to-reach-the-kth-smallest-number/) | [无] | [C++](1501-2000/1850-Minimum-Adjacent-Swaps-to-Reach-the-Kth-Smallest-Number/cpp-1850/) | | | +| 1851 | [Minimum Interval to Include Each Query](https://leetcode.com/problems/minimum-interval-to-include-each-query/) | [无] | [C++](1501-2000/1851-Minimum-Interval-to-Include-Each-Query/cpp=1851/) | | | +| 1852 | [Distinct Numbers in Each Subarray](https://leetcode.com/problems/distinct-numbers-in-each-subarray/) | [无] | [C++](1501-2000/1852-Distinct-Numbers-in-Each-Subarray/cpp-1852/) | | | +| 1853 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1854 | [Maximum Population Year](https://leetcode.com/problems/maximum-population-year/) | [无] | [C++](1501-2000/1854-Maximum-Population-Year/cpp-1854/) | | | +| 1855 | [Maximum Distance Between a Pair of Values](https://leetcode.com/problems/maximum-distance-between-a-pair-of-values/) | [无] | [C++](1501-2000/1855-Maximum-Distance-Between-a-Pair-of-Values/cpp-1855/) | | | +| 1856 | [Maximum Subarray Min-Product](https://leetcode.com/problems/maximum-subarray-min-product/) | [无] | [C++](1501-2000/1856-Maximum-Subarray-Min-Product/cpp-1856/) | | | +| 1857 | [Largest Color Value in a Directed Graph](https://leetcode.com/problems/largest-color-value-in-a-directed-graph/) | [无] | [C++](1501-2000/1857-Largest-Color-Value-in-a-Directed-Graph/cpp-1857/) | | | +| 1858 | [Longest Word With All Prefixes](https://leetcode.com/problems/longest-word-with-all-prefixes/) | [无] | [C++](1501-2000/1858-Longest-Word-With-All-Prefixes/cpp-1858/) | | | +| 1859 | [Sorting the Sentence](https://leetcode.com/problems/sorting-the-sentence/) | [无] | [C++](1501-2000/1859-Sorting-the-Sentence/cpp-1859/) | | | +| 1860 | [Incremental Memory Leak](https://leetcode.com/problems/incremental-memory-leak/) | [无] | [C++](1501-2000/1860-Incremental-Memory-Leak/cpp-1860/) | | | +| 1861 | [Rotating the Box](https://leetcode.com/problems/rotating-the-box/) | [无] | [C++](1501-2000/1861-Rotating-the-Box/cpp-1861/) | | | +| 1862 | [Sum of Floored Pairs](https://leetcode.com/problems/sum-of-floored-pairs/) | [无] | [C++](1501-2000/1862-Sum-of-Floored-Pairs/cpp-1862/) | | | +| 1863 | [Sum of All Subset XOR Totals](https://leetcode.com/problems/sum-of-all-subset-xor-totals/) | [无]
[缺:数学解] | [C++](1501-2000/1863-Sum-of-All-Subset-XOR-Totals/cpp-1863/) | | | +| 1864 | [Minimum Number of Swaps to Make the Binary String Alternating](https://leetcode.com/problems/minimum-number-of-swaps-to-make-the-binary-string-alternating/) | [无] | [C++](1501-2000/1864-Minimum-Number-of-Swaps-to-Make-the-Binary-String-Alternating/cpp-1864/) | | | +| 1865 | [Finding Pairs With a Certain Sum](https://leetcode.com/problems/finding-pairs-with-a-certain-sum/) | [无] | [C++](1501-2000/1865-Finding-Pairs-With-a-Certain-Sum/cpp-1865/) | | | +| 1866 | [Number of Ways to Rearrange Sticks With K Sticks Visible](https://leetcode.com/problems/number-of-ways-to-rearrange-sticks-with-k-sticks-visible/) | [无] | [C++](1501-2000/1866-Number-of-Ways-to-Rearrange-Sticks-With-K-Sticks-Visible/cpp-1866/) | | | +| 1867 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1868 | [Product of Two Run-Length Encoded Arrays](https://leetcode.com/problems/product-of-two-run-length-encoded-arrays/) | [无] | [C++](1501-2000/1868-Product-of-Two-Run-Length-Encoded-Arrays/cpp-1868/) | | | +| 1869 | [Longer Contiguous Segments of Ones than Zeros](https://leetcode.com/problems/longer-contiguous-segments-of-ones-than-zeros/) | [无] | [C++](1501-2000/1869-Longer-Contiguous-Segments-of-Ones-than-Zeros/cpp-1869/) | | | +| 1870 | [Minimum Speed to Arrive on Time](https://leetcode.com/problems/minimum-speed-to-arrive-on-time/) | [无] | [C++](1501-2000/1870-Minimum-Speed-to-Arrive-on-Time/cpp-1870/) | | | +| 1871 | [Jump Game VII](https://leetcode.com/problems/jump-game-vii/) | [无] | [C++](1501-2000/1871-Jump-Game-VII/cpp-1871/) | | | +| 1872 | [Stone Game VIII](https://leetcode.com/problems/stone-game-viii/) | [solution](1501-2000/1872-Stone-Game-VIII/cpp-1872/) | | | | +| 1873 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1874 | [Minimize Product Sum of Two Arrays](https://leetcode.com/problems/minimize-product-sum-of-two-arrays/) | [无] | [C++](1501-2000/1874-Minimize-Product-Sum-of-Two-Arrays/cpp-1874/) | | | +| 1875 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1876 | [Substrings of Size Three with Distinct Characters](https://leetcode.com/problems/substrings-of-size-three-with-distinct-characters/) | [无] | [C++](1501-2000/1876-Substrings-of-Size-Three-with-Distinct-Characters/cpp-1876/) | | | +| 1877 | [Minimize Maximum Pair Sum in Array](https://leetcode.com/problems/minimize-maximum-pair-sum-in-array/) | [无] | [C++](1501-2000/1877-Minimize-Maximum-Pair-Sum-in-Array/cpp-1877/) | | | +| 1878 | [Get Biggest Three Rhombus Sums in a Grid](https://leetcode.com/problems/get-biggest-three-rhombus-sums-in-a-grid/) | [无] | [C++](1501-2000/1878-Get-Biggest-Three-Rhombus-Sums-in-a-Grid/cpp-1878/) | | | +| 1879 | [Minimum XOR Sum of Two Arrays](https://leetcode.com/problems/minimum-xor-sum-of-two-arrays/) | [无]
[缺:DP] | [C++](1501-2000/1879-Minimum-XOR-Sum-of-Two-Arrays/cpp-1879/) | | | +| 1880 | [Check if Word Equals Summation of Two Words](https://leetcode.com/problems/check-if-word-equals-summation-of-two-words/) | [无] | [C++](1501-2000/1880-Check-if-Word-Equals-Summation-of-Two-Words/cpp-1880/) | | | +| 1881 | [Maximum Value after Insertion](https://leetcode.com/problems/maximum-value-after-insertion/) | [无] | [C++](1501-2000/1881-Maximum-Value-after-Insertion/cpp-1881/) | | | +| 1882 | [Process Tasks Using Servers](https://leetcode.com/problems/process-tasks-using-servers/) | [无] | [C++](1501-2000/1882-Process-Tasks-Using-Servers/cpp-1882/) | | | +| 1883 | [Minimum Skips to Arrive at Meeting On Time](https://leetcode.com/problems/minimum-skips-to-arrive-at-meeting-on-time/) | [无]
[缺:DP] | [C++](1501-2000/1883-Minimum-Skips-to-Arrive-at-Meeting-On-Time/cpp-1883/) | | | +| 1884 | [Egg Drop With 2 Eggs and N Floors](https://leetcode.com/problems/egg-drop-with-2-eggs-and-n-floors/) | [无]
[缺:O(1) 数学] | [C++](1501-2000/1884-Egg-Drop-With-2-Eggs-and-N-Floors/cpp-1884/) | | | +| 1885 | [Count Pairs in Two Arrays](https://leetcode.com/problems/count-pairs-in-two-arrays/) | [无] | [C++](1501-2000/1885-Count-Pairs-in-Two-Arrays/cpp-1885/) | | | +| 1886 | [Determine Whether Matrix Can Be Obtained By Rotation](https://leetcode.com/problems/determine-whether-matrix-can-be-obtained-by-rotation/) | [无] | [C++](1501-2000/1886-Determine-Whether-Matrix-Can-Be-Obtained-By-Rotation/cpp-1886/) | | | +| 1887 | [Reduction Operations to Make the Array Elements Equal](https://leetcode.com/problems/reduction-operations-to-make-the-array-elements-equal/) | [无] | [C++](1501-2000/1887-Reduction-Operations-to-Make-the-Array-Elements-Equal/cpp-1887/) | | | +| 1888 | [Minimum Number of Flips to Make the Binary String Alternating](https://leetcode.com/problems/minimum-number-of-flips-to-make-the-binary-string-alternating/) | [无] | [C++](1501-2000/1888-Minimum-Number-of-Flips-to-Make-the-Binary-String-Alternating/cpp-1888/) | | | +| 1889 | [Minimum Space Wasted From Packaging](https://leetcode.com/problems/minimum-space-wasted-from-packaging/) | [无] | [C++](1501-2000/1889-Minimum-Space-Wasted-From-Packaging/cpp-1889/) | | | +| 1890 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1891 | [Cutting Ribbons](https://leetcode.com/problems/cutting-ribbons/) | [无] | [C++](1501-2000/1891-Cutting-Ribbons/cpp-1891/) | | | +| 1892 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1893 | [Check if All the Integers in a Range Are Covered](https://leetcode.com/problems/check-if-all-the-integers-in-a-range-are-covered/) | [无] | [C++](1501-2000/1893-Check-if-All-the-Integers-in-a-Range-Are-Covered/cpp-1893/) | | | +| 1894 | [Find the Student that Will Replace the Chalk](https://leetcode.com/problems/find-the-student-that-will-replace-the-chalk/) | [无] | [C++](1501-2000/1894-Find-the-Student-that-Will-Replace-the-Chalk/cpp-1894/) | | | +| 1895 | [Largest Magic Square](https://leetcode.com/problems/largest-magic-square/) | [无] | [C++](1501-2000/1895-Largest-Magic-Square/cpp-1895/) | | | +| 1896 | [Minimum Cost to Change the Final Value of Expression](https://leetcode.com/problems/minimum-cost-to-change-the-final-value-of-expression/) | [无] | [C++](1501-2000/1896-Minimum-Cost-to-Change-the-Final-Value-of-Expression/cpp-1896/) | | | +| 1897 | [Redistribute Characters to Make All Strings Equal](https://leetcode.com/problems/redistribute-characters-to-make-all-strings-equal/) | [无] | [C++](1501-2000/1897-Redistribute-Characters-to-Make-All-Strings-Equal/cpp-1897/) | | | +| 1898 | [Maximum Number of Removable Characters](https://leetcode.com/problems/maximum-number-of-removable-characters/) | [无] | [C++](1501-2000/1898-Maximum-Number-of-Removable-Characters/cpp-1898/) | | | +| 1899 | [Merge Triplets to Form Target Triplet](https://leetcode.com/problems/merge-triplets-to-form-target-triplet/) | [无] | [C++](1501-2000/1899-Merge-Triplets-to-Form-Target-Triplet/cpp-1899/) | | | +| 1900 | [The Earliest and Latest Rounds Where Players Compete](https://leetcode.com/problems/the-earliest-and-latest-rounds-where-players-compete/) | [无] | [C++](1501-2000/1900-The-Earliest-and-Latest-Rounds-Where-Players-Compete/cpp-1900/) | | | +| 1901 | [Find a Peak Element II](https://leetcode.com/problems/find-a-peak-element-ii/) | [无] | [C++](1501-2000/1901-Find-a-Peak-Element-II/cpp-1901/) | | | +| 1902 | [Depth of BST Given Insertion Order](https://leetcode.com/problems/depth-of-bst-given-insertion-order/) | [无] | [C++](1501-2000/1902-Depth-of-BST-Given-Insertion-Order/cpp-1902/) | | | +| 1903 | [Largest Odd Number in String](https://leetcode.com/problems/largest-odd-number-in-string/) | [无] | [C++](1501-2000/1903-Largest-Odd-Number-in-String/cpp-1903/) | | | +| 1904 | [The Number of Full Rounds You Have Played](https://leetcode.com/problems/the-number-of-full-rounds-you-have-played/) | [无] | [C++](1501-2000/1904-The-Number-of-Full-Rounds-You-Have-Played/cpp-1904/) | | | +| 1905 | [Count Sub Islands](https://leetcode.com/problems/count-sub-islands/) | [无] | [C++](1501-2000/1905-Count-Sub-Islands/cpp-1905/) | | | +| 1906 | [Minimum Absolute Difference Queries](https://leetcode.com/problems/minimum-absolute-difference-queries/) | [无]
[缺:二分] | [C++](1501-2000/1906-Minimum-Absolute-Difference-Queries/cpp-1906/) | | | +| 1907 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1908 | [Game of Nim](https://leetcode.com/problems/game-of-nim/) | [无]
[缺:dp] | [C++](1501-2000/1908-Game-of-Nim/cpp-1908/) | | | +| 1909 | [Remove One Element to Make the Array Strictly Increasing](https://leetcode.com/problems/remove-one-element-to-make-the-array-strictly-increasing/) | [无] | [C++](1501-2000/1909-Remove-One-Element-to-Make-the-Array-Strictly-Increasing/cpp-1909/) | | | +| 1910 | [Remove All Occurrences of a Substring](https://leetcode.com/problems/remove-all-occurrences-of-a-substring/) | [无] | [C++](1501-2000/1910-Remove-All-Occurrences-of-a-Substring/cpp-1910/) | | | +| 1911 | [Maximum Alternating Subsequence Sum](https://leetcode.com/problems/maximum-alternating-subsequence-sum/) | [无]
[缺:dp] | [C++](1501-2000/1911-Maximum-Alternating-Subsequence-Sum/cpp-1911/) | | | +| 1912 | [Design Movie Rental System](https://leetcode.com/problems/design-movie-rental-system/) | [无] | [C++](1501-2000/1912-Design-Movie-Rental-System/cpp-1912/) | | | +| 1913 | [Maximum Product Difference Between Two Pairs](https://leetcode.com/problems/maximum-product-difference-between-two-pairs/) | [无] | [C++](1501-2000/1913-Maximum-Product-Difference-Between-Two-Pairs/cpp-1913/) | | | +| 1914 | [Cyclically Rotating a Grid](https://leetcode.com/problems/cyclically-rotating-a-grid/) | [无] | [C++](1501-2000/1914-Cyclically-Rotating-a-Grid/cpp-1914/) | | | +| 1915 | [Number of Wonderful Substrings](https://leetcode.com/problems/number-of-wonderful-substrings/) | [无] | [C++](1501-2000/1915-Number-of-Wonderful-Substrings/cpp-1915/) | | | +| 1916 | [Count Ways to Build Rooms in an Ant Colony](https://leetcode.com/problems/count-ways-to-build-rooms-in-an-ant-colony/) | [无] | [C++](1501-2000/1916-Count-Ways-to-Build-Rooms-in-an-Ant-Colony/cpp-1916/) | | | +| 1917 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1918 | [Kth Smallest Subarray Sum](https://leetcode.com/problems/kth-smallest-subarray-sum/) | [无] | [C++](1501-2000/1918-Kth-Smallest-Subarray-Sum/cpp-1918/) | | | +| 1919 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1920 | [Build Array from Permutation](https://leetcode.com/problems/build-array-from-permutation/) | [无] | [C++](1501-2000/1920-Build-Array-from-Permutation/cpp-1920/) | | | +| 1921 | [Eliminate Maximum Number of Monsters](https://leetcode.com/problems/eliminate-maximum-number-of-monsters/) | [无] | [C++](1501-2000/1921-Eliminate-Maximum-Number-of-Monsters/cpp-1921/) | | | +| 1922 | [Count Good Numbers](https://leetcode.com/problems/count-good-numbers/) | [无] | [C++](1501-2000/1922-Count-Good-Numbers/cpp-1922/) | | | +| 1923 | [Longest Common Subpath](https://leetcode.com/problems/longest-common-subpath/) | [无]
[缺:后缀树组+LCP
滚动哈希两次碰撞] | [C++](1501-2000/1923-Longest-Common-Subpath/cpp-1923/) | | | +| 1924 | [Erect the Fence II](https://leetcode.com/problems/erect-the-fence-ii/) | [无] | [C++](1501-2000/1924-Erect-the-Fence-II/cpp-1924/) | | | +| 1925 | [Count Square Sum Triples](https://leetcode.com/problems/count-square-sum-triples/) | [无] | [C++](1501-2000/1925-Count-Square-Sum-Triples/cpp-1925/) | | | +| 1926 | [Nearest Exit from Entrance in Maze](https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/) | [无] | [C++](1501-2000/1926-Nearest-Exit-from-Entrance-in-Maze/cpp-1926/) | | | +| 1927 | [Sum Game](https://leetcode.com/problems/sum-game/) | [无] | [C++](1501-2000/1927-Sum-Game/cpp-1927/) | | | +| 1928 | [Minimum Cost to Reach Destination in Time](https://leetcode.com/problems/minimum-cost-to-reach-destination-in-time/) | [无] | [C++](1501-2000/1928-Minimum-Cost-to-Reach-Destination-in-Time/cpp-1928/) | | | +| 1929 | [Concatenation of Array](https://leetcode.com/problems/concatenation-of-array/) | [无] | [C++](1501-2000/1929-Concatenation-of-Array/cpp-1929/) | | | +| 1930 | [Unique Length-3 Palindromic Subsequences](https://leetcode.com/problems/unique-length-3-palindromic-subsequences/) | [无] | [C++](1501-2000/1930-Unique-Length-3-Palindromic-Subsequences/cpp-1930/) | | | +| 1931 | [Painting a Grid With Three Different Colors](https://leetcode.com/problems/painting-a-grid-with-three-different-colors/) | [无] | [C++](1501-2000/1931-Painting-a-Grid-With-Three-Different-Colors/cpp-1931/) | | | +| 1932 | [Merge BSTs to Create Single BST](https://leetcode.com/problems/merge-bsts-to-create-single-bst/) | [无] | [C++](1501-2000/1932-Merge-BSTs-to-Create-Single-BST/cpp-1932/) | | | +| 1933 | [Check if String Is Decomposable Into Value-Equal Substrings](https://leetcode.com/problems/check-if-string-is-decomposable-into-value-equal-substrings/) | [无] | [C++](1501-2000/1933-Check-if-String-Is-Decomposable-Into-Value-Equal-Substrings/cpp-1933/) | | | +| 1934 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1935 | [Maximum Number of Words You Can Type](https://leetcode.com/problems/maximum-number-of-words-you-can-type/) | [无] | [C++](1501-2000/1935-Maximum-Number-of-Words-You-Can-Type/cpp-1935/) | | | +| 1936 | [Add Minimum Number of Rungs](https://leetcode.com/problems/add-minimum-number-of-rungs/) | [无] | [C++](1501-2000/1936-Add-Minimum-Number-of-Rungs/cpp-1936/) | | | +| 1937 | [Maximum Number of Points with Cost](https://leetcode.com/problems/maximum-number-of-points-with-cost/) | [无] | [C++](1501-2000/1937-Maximum-Number-of-Points-with-Cost/cpp-1937/) | | | +| 1938 | [Maximum Genetic Difference Query](https://leetcode.com/problems/maximum-genetic-difference-query/) | [无] | [C++](1501-2000/1938-Maximum-Genetic-Difference-Query/cpp-1938/) | | | +| 1939 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1940 | [Longest Common Subsequence Between Sorted Arrays](https://leetcode.com/problems/longest-common-subsequence-between-sorted-arrays/) | [无] | [C++](1501-2000/1940-Longest-Common-Subsequence-Between-Sorted-Arrays/cpp-1940/) | | | +| 1941 | [Check if All Characters Have Equal Number of Occurrences](https://leetcode.com/problems/check-if-all-characters-have-equal-number-of-occurrences/) | [无] | [C++](1501-2000/1941-Check-if-All-Characters-Have-Equal-Number-of-Occurrences/cpp-1941/) | | | +| 1942 | [The Number of the Smallest Unoccupied Chair](https://leetcode.com/problems/the-number-of-the-smallest-unoccupied-chair/) | [无] | [C++](1501-2000/1942-The-Number-of-the-Smallest-Unoccupied-Chair/cpp-1942/) | | | +| 1943 | [Describe the Painting](https://leetcode.com/problems/describe-the-painting/) | [无] | [C++](1501-2000/1943-Describe-the-Painting/cpp-1943/) | | | +| 1944 | [Number of Visible People in a Queue](https://leetcode.com/problems/number-of-visible-people-in-a-queue/) | [无] | [C++](1501-2000/1944-Number-of-Visible-People-in-a-Queue/cpp-1944/) | | | +| 1945 | [Sum of Digits of String After Convert](https://leetcode.com/problems/sum-of-digits-of-string-after-convert/) | [无] | [C++](1501-2000/1945-Sum-of-Digits-of-String-After-Convert/cpp-1945/) | | | +| 1946 | [Largest Number After Mutating Substring](https://leetcode.com/problems/largest-number-after-mutating-substring/) | [无] | [C++](1501-2000/1946-Largest-Number-After-Mutating-Substring/cpp-1946/) | | | +| 1947 | [Maximum Compatibility Score Sum](https://leetcode.com/problems/maximum-compatibility-score-sum/) | [无] | [C++](1501-2000/1947-Maximum-Compatibility-Score-Sum/cpp-1947/) | | | +| 1948 | [Delete Duplicate Folders in System](https://leetcode.com/problems/delete-duplicate-folders-in-system/) | [无] | [C++](1501-2000/1948-Delete-Duplicate-Folders-in-System/cpp-1948/) | | | +| 1949 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1950 | [Maximum of Minimum Values in All Subarrays](https://leetcode.com/problems/maximum-of-minimum-values-in-all-subarrays/) | [无] | [C++](1501-2000/1950-Maximum-of-Minimum-Values-in-All-Subarrays/cpp-1950/) | | | +| 1951 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1952 | [Three Divisors](https://leetcode.com/problems/three-divisors/) | [无] | [C++](1501-2000/1952-Three-Divisors/cpp-1952/) | | | +| 1953 | [Maximum Number of Weeks for Which You Can Work](https://leetcode.com/problems/maximum-number-of-weeks-for-which-you-can-work/) | [无] | [C++](1501-2000/1953-Maximum-Number-of-Weeks-for-Which-You-Can-Work/cpp-1953/) | | | +| 1954 | [Minimum Garden Perimeter to Collect Enough Apples](https://leetcode.com/problems/minimum-garden-perimeter-to-collect-enough-apples/) | [无] | [C++](1501-2000/1954-Minimum-Garden-Perimeter-to-Collect-Enough-Apples/cpp-1954/) | | | +| 1955 | [Count Number of Special Subsequences](https://leetcode.com/problems/count-number-of-special-subsequences/) | [无] | [C++](1501-2000/1955-Count-Number-of-Special-Subsequences/cpp-1955/) | | | +| 1956 | [Minimum Time For K Virus Variants to Spread](https://leetcode.com/problems/minimum-time-for-k-virus-variants-to-spread/) | [无] | [C++](1501-2000/1956-Minimum-Time-For-K-Virus-Variants-to-Spread/cpp-1956/) | | | +| 1957 | [Delete Characters to Make Fancy String](https://leetcode.com/problems/delete-characters-to-make-fancy-string/) | [无] | [C++](1501-2000/1957-Delete-Characters-to-Make-Fancy-String/cpp-1957/) | | | +| 1958 | [Check if Move is Legal](https://leetcode.com/problems/check-if-move-is-legal/) | [无] | [C++](1501-2000/1958-Check-if-Move-is-Legal/cpp-1958/) | | | +| 1959 | [Minimum Total Space Wasted With K Resizing Operations](https://leetcode.com/problems/minimum-total-space-wasted-with-k-resizing-operations/) | [无] | [C++](1501-2000/1959-Minimum-Total-Space-Wasted-With-K-Resizing-Operations/cpp-1959/) | | | +| 1960 | [Maximum Product of the Length of Two Palindromic Substrings](https://leetcode.com/problems/maximum-product-of-the-length-of-two-palindromic-substrings/) | [无] | [C++](1501-2000/1960-Maximum-Product-of-the-Length-of-Two-Palindromic-Substrings/cpp-1960/) | | | +| 1961 | [Check If String Is a Prefix of Array](https://leetcode.com/problems/check-if-string-is-a-prefix-of-array/) | [无] | [C++](1501-2000/1961-Check-If-String-Is-a-Prefix-of-Array/cpp-1961/) | | | +| 1962 | [Remove Stones to Minimize the Total](https://leetcode.com/problems/remove-stones-to-minimize-the-total/) | [无] | [C++](1501-2000/1962-Remove-Stones-to-Minimize-the-Total/cpp-1962/) | | | +| 1963 | [Minimum Number of Swaps to Make the String Balanced](https://leetcode.com/problems/minimum-number-of-swaps-to-make-the-string-balanced/) | [无] | [C++](1501-2000/1963-Minimum-Number-of-Swaps-to-Make-the-String-Balanced/cpp-1963/) | | | +| 1964 | [Find the Longest Valid Obstacle Course at Each Position](https://leetcode.com/problems/find-the-longest-valid-obstacle-course-at-each-position/) | [无] | [C++](1501-2000/1964-Find-the-Longest-Valid-Obstacle-Course-at-Each-Position/cpp-1964/) | | | +| 1965 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1966 | [Binary Searchable Numbers in an Unsorted Array](https://leetcode.com/problems/binary-searchable-numbers-in-an-unsorted-array/) | [无] | [C++](1501-2000/1966-Binary-Searchable-Numbers-in-an-Unsorted-Array/cpp-1966/) | | | +| 1967 | [Number of Strings That Appear as Substrings in Word](https://leetcode.com/problems/number-of-strings-that-appear-as-substrings-in-word/) | [无] | [C++](1501-2000/1967-Number-of-Strings-That-Appear-as-Substrings-in-Word/cpp-1967/) | | | +| 1968 | [Array With Elements Not Equal to Average of Neighbors](https://leetcode.com/problems/array-with-elements-not-equal-to-average-of-neighbors/) | [无] | [C++](1501-2000/1968-Array-With-Elements-Not-Equal-to-Average-of-Neighbors/cpp-1968/) | | | +| 1969 | [Minimum Non-Zero Product of the Array Elements](https://leetcode.com/problems/minimum-non-zero-product-of-the-array-elements/) | [无] | [C++](1501-2000/1969-Minimum-Non-Zero-Product-of-the-Array-Elements/cpp-1969/) | | | +| 1970 | [Last Day Where You Can Still Cross](https://leetcode.com/problems/last-day-where-you-can-still-cross/) | [无] | [C++](1501-2000/1970-Last-Day-Where-You-Can-Still-Cross/cpp-1970/) | | | +| 1971 | [Find if Path Exists in Graph](https://leetcode.com/problems/find-if-path-exists-in-graph/) | [无] | [C++](1501-2000/1971-Find-if-Path-Exists-in-Graph/cpp-1971/) | | | +| 1972 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1973 | [Count Nodes Equal to Sum of Descendants](https://leetcode.com/problems/count-nodes-equal-to-sum-of-descendants/) | [无] | [C++](1501-2000/1973-Count-Nodes-Equal-to-Sum-of-Descendants/cpp-1973/) | | | +| 1974 | [Minimum Time to Type Word Using Special Typewriter](https://leetcode.com/problems/minimum-time-to-type-word-using-special-typewriter/) | [无] | [C++](1501-2000/1974-Minimum-Time-to-Type-Word-Using-Special-Typewriter/cpp-1974/) | | | +| 1975 | [Maximum Matrix Sum](https://leetcode.com/problems/maximum-matrix-sum/) | [无] | [C++](1501-2000/1975-Maximum-Matrix-Sum/cpp-1975/) | | | +| 1976 | [Number of Ways to Arrive at Destination](https://leetcode.com/problems/number-of-ways-to-arrive-at-destination/) | [无] | [C++](1501-2000/1976-Number-of-Ways-to-Arrive-at-Destination/cpp-1976/) | | | +| 1977 | [Number of Ways to Separate Numbers](https://leetcode.com/problems/number-of-ways-to-separate-numbers/) | [无] | [C++](1501-2000/1977-Number-of-Ways-to-Separate-Numbers/cpp-1977/) | | | +| 1978 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1979 | [Find Greatest Common Divisor of Array](https://leetcode.com/problems/find-greatest-common-divisor-of-array/) | [无] | [C++](1501-2000/1979-Number-of-Ways-to-Separate-Numbers/cpp-1979/) | | | +| 1980 | [Find Unique Binary String](https://leetcode.com/problems/find-unique-binary-string/) | [无] | [C++](1501-2000/1980-Find-Unique-Binary-String/cpp-1980/) | | | +| 1981 | [Minimize the Difference Between Target and Chosen Elements](https://leetcode.com/problems/minimize-the-difference-between-target-and-chosen-elements/) | [无] | [C++](1501-2000/1981-Minimize-the-Difference-Between-Target-and-Chosen-Elements/cpp-1981/) | | | +| 1982 | [Find Array Given Subset Sums](https://leetcode.com/problems/find-array-given-subset-sums/) | [无] | [C++](1501-2000/1982-Find-Array-Given-Subset-Sums/cpp-1982/) | | | +| 1983 | [Widest Pair of Indices With Equal Range Sum](https://leetcode.com/problems/widest-pair-of-indices-with-equal-range-sum/) | [无] | [C++](1501-2000/1983-Widest-Pair-of-Indices-With-Equal-Range-Sum/cpp-1983/) | | | +| 1984 | [Minimum Difference Between Highest and Lowest of K Scores](https://leetcode.com/problems/minimum-difference-between-highest-and-lowest-of-k-scores/) | [无] | [C++](1501-2000/1984-Minimum-Difference-Between-Highest-and-Lowest-of-K-Scores/cpp-1984/) | | | +| 1985 | [Find the Kth Largest Integer in the Array](https://leetcode.com/problems/find-the-kth-largest-integer-in-the-array/) | [无] | [C++](1501-2000/1985-Find-the-Kth-Largest-Integer-in-the-Array/cpp-1985/) | | | +| 1986 | [Minimum Number of Work Sessions to Finish the Tasks](https://leetcode.com/problems/minimum-number-of-work-sessions-to-finish-the-tasks/) | [无] | [C++](1501-2000/1986-Minimum-Number-of-Work-Sessions-to-Finish-the-Tasks/cpp-1986/) | | | +| 1987 | [Number of Unique Good Subsequences](https://leetcode.com/problems/number-of-unique-good-subsequences/) | [无] | [C++](1501-2000/1987-Number-of-Unique-Good-Subsequences/cpp-1987/) | | | +| 1988 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1989 | [Maximum Number of People That Can Be Caught in Tag](https://leetcode.com/problems/maximum-number-of-people-that-can-be-caught-in-tag/) | [无] | [C++](1501-2000/1989-Maximum-Number-of-People-That-Can-Be-Caught-in-Tag/cpp-1989/) | | | +| 1990 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 1991 | [Find the Middle Index in Array](https://leetcode.com/problems/find-the-middle-index-in-array/) | [无] | [C++](1501-2000/1991-Find-the-Middle-Index-in-Array/cpp-1991/) | | | +| 1992 | [Find All Groups of Farmland](https://leetcode.com/problems/find-all-groups-of-farmland/) | [无] | [C++](1501-2000/1992-Find-All-Groups-of-Farmland/cpp-1992/) | | | +| 1993 | [Operations on Tree](https://leetcode.com/problems/operations-on-tree/) | [无] | [C++](1501-2000/1993-Operations-on-Tree/cpp-1993/) | | | +| 1994 | [The Number of Good Subsets](https://leetcode.com/problems/the-number-of-good-subsets/) | [无] | [C++](1501-2000/1994-The-Number-of-Good-Subsets/cpp-1994/) | | | +| 1995 | [Count Special Quadruplets](https://leetcode.com/problems/count-special-quadruplets/) | [无] | [C++](1501-2000/1995-Count-Special-Quadruplets/cpp-1995/) | | | +| 1996 | [The Number of Weak Characters in the Game](https://leetcode.com/problems/the-number-of-weak-characters-in-the-game/) | [无] | [C++](1501-2000/1996-The-Number-of-Weak-Characters-in-the-Game/cpp-1996/) | | | +| 1997 | [First Day Where You Have Been in All the Rooms](https://leetcode.com/problems/first-day-where-you-have-been-in-all-the-rooms/) | [无] | [C++](1501-2000/1997-First-Day-Where-You-Have-Been-in-All-the-Rooms/cpp-1997/) | | | +| 1998 | [GCD Sort of an Array](https://leetcode.com/problems/gcd-sort-of-an-array/) | [无] | [C++](1501-2000/1998-GCD-Sort-of-an-Array/cpp-1998/) | | | +| 1999 | [Smallest Greater Multiple Made of Two Digits](https://leetcode.com/problems/smallest-greater-multiple-made-of-two-digits/) | [无] | [C++](1501-2000/1999-Smallest-Greater-Multiple-Made-of-Two-Digits/cpp-1999/) | | | +| 2000 | [Reverse Prefix of Word](https://leetcode.com/problems/reverse-prefix-of-word/) | [无] | [C++](1501-2000/2000-Reverse-Prefix-of-Word/cpp-2000/) | | | +| 2001 | [Number of Pairs of Interchangeable Rectangles](https://leetcode.com/problems/number-of-pairs-of-interchangeable-rectangles/) | [无] | [C++](2001-2500/2001-Number-of-Pairs-of-Interchangeable-Rectangles/cpp-2001/) | | | +| 2002 | [Maximum Product of the Length of Two Palindromic Subsequences](https://leetcode.com/problems/maximum-product-of-the-length-of-two-palindromic-subsequences/) | [无] | [C++](2001-2500/2002-Maximum-Product-of-the-Length-of-Two-Palindromic-Subsequences/cpp-2002/) | | | +| 2003 | [Smallest Missing Genetic Value in Each Subtree](https://leetcode.com/problems/smallest-missing-genetic-value-in-each-subtree/) | [无] | [C++](2001-2500/2003-Smallest-Missing-Genetic-Value-in-Each-Subtree/cpp-2003/) | | | +| 2004 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 2005 | [Subtree Removal Game with Fibonacci Tree](https://leetcode.com/problems/subtree-removal-game-with-fibonacci-tree/) | [无] | [C++](2001-2500/2005-Subtree-Removal-Game-with-Fibonacci-Tree/cpp-2005/) | | | +| 2006 | [Count Number of Pairs With Absolute Difference K](https://leetcode.com/problems/count-number-of-pairs-with-absolute-difference-k/) | [无] | [C++](2001-2500/2006-Count-Number-of-Pairs-With-Absolute-Difference-K/cpp-2006/) | | | +| 2007 | [Find Original Array From Doubled Array](https://leetcode.com/problems/find-original-array-from-doubled-array/) | [无] | [C++](2001-2500/2007-Find-Original-Array-From-Doubled-Array/cpp-2007/) | | | +| 2008 | [Maximum Earnings From Taxi](https://leetcode.com/problems/maximum-earnings-from-taxi/) | [无] | [C++](2001-2500/2008-Maximum-Earnings-From-Taxi/cpp-2008/) | | | +| 2009 | [Minimum Number of Operations to Make Array Continuous](https://leetcode.com/problems/minimum-number-of-operations-to-make-array-continuous/) | [无] | [C++](2001-2500/2009-Minimum-Number-of-Operations-to-Make-Array-Continuous/cpp-2009/) | | | +| 2010 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 2011 | [Final Value of Variable After Performing Operations](https://leetcode.com/problems/final-value-of-variable-after-performing-operations/) | [无] | [C++](2001-2500/2011-Final-Value-of-Variable-After-Performing-Operations/cpp-2011/) | | | +| 2012 | [Sum of Beauty in the Array](https://leetcode.com/problems/sum-of-beauty-in-the-array/) | [无] | [C++](2001-2500/2012-Sum-of-Beauty-in-the-Array/cpp-2012/) | | | +| 2013 | [Detect Squares](https://leetcode.com/problems/detect-squares/) | [无] | [C++](2001-2500/2013-Detect-Squares/cpp-2013/) | | | +| 2014 | [Longest Subsequence Repeated k Times](https://leetcode.com/problems/longest-subsequence-repeated-k-times/) | [无] | [C++](2001-2500/2014-Longest-Subsequence-Repeated-k-Times/cpp-2014/) | | | +| 2015 | [Average Height of Buildings in Each Segment](https://leetcode.com/problems/average-height-of-buildings-in-each-segment/) | [无] | [C++](2001-2500/2015-Average-Height-of-Buildings-in-Each-Segment/cpp-2015/) | | | +| 2016 | [Maximum Difference Between Increasing Elements](https://leetcode.com/problems/maximum-difference-between-increasing-elements/) | [无] | [C++](2001-2500/2016-Maximum-Difference-Between-Increasing-Elements/cpp-2016/) | | | +| 2017 | [Grid Game](https://leetcode.com/problems/grid-game/) | [无] | [C++](2001-2500/2017-Grid-Game/cpp-2017/) | | | +| 2018 | [Check if Word Can Be Placed In Crossword](https://leetcode.com/problems/check-if-word-can-be-placed-in-crossword/) | [无] | [C++](2001-2500/2018-Check-if-Word-Can-Be-Placed-In-Crossword/cpp-2018/) | | | +| 2019 | [The Score of Students Solving Math Expression](https://leetcode.com/problems/the-score-of-students-solving-math-expression/) | [无] | [C++](2001-2500/2019-The-Score-of-Students-Solving-Math-Expression/cpp-2019/) | | | +| 2020 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 2021 | [Brightest Position on Street](https://leetcode.com/problems/brightest-position-on-street/) | [无] | [C++](2001-2500/2021-Brightest-Position-on-Street/cpp-2021/) | | | +| 2022 | [Convert 1D Array Into 2D Array](https://leetcode.com/problems/convert-1d-array-into-2d-array/) | [无] | [C++](2001-2500/2022-Convert-1D-Array-Into-2D-Array/cpp-2022/) | | | +| 2023 | [Number of Pairs of Strings With Concatenation Equal to Target](https://leetcode.com/problems/number-of-pairs-of-strings-with-concatenation-equal-to-target/) | [无] | [C++](2001-2500/2023-Number-of-Pairs-of-Strings-With-Concatenation-Equal-to-Target/cpp-2023/) | | | +| 2024 | [Maximize the Confusion of an Exam](https://leetcode.com/problems/maximize-the-confusion-of-an-exam/) | [无] | [C++](2001-2500/2024-Maximize-the-Confusion-of-an-Exam/cpp-2024/) | | | +| 2025 | [Maximum Number of Ways to Partition an Array](https://leetcode.com/problems/maximum-number-of-ways-to-partition-an-array/) | [无] | [C++](2001-2500/2025-Maximum-Number-of-Ways-to-Partition-an-Array/cpp-2025/) | | | +| 2026 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 2027 | [Minimum Moves to Convert String](https://leetcode.com/problems/minimum-moves-to-convert-string/) | [无] | [C++](2001-2500/2027-Minimum-Moves-to-Convert-String/cpp-2027/) | | | +| 2028 | [Find Missing Observations](https://leetcode.com/problems/find-missing-observations/) | [无] | [C++](2001-2500/2028-Find-Missing-Observations/cpp-2028/) | | | +| 2029 | [Stone Game IX](https://leetcode.com/problems/stone-game-ix/) | [无] | [C++](2001-2500/2029-Stone-Game-IX/cpp-2029/) | | | +| 2030 | [Smallest K-Length Subsequence With Occurrences of a Letter](https://leetcode.com/problems/smallest-k-length-subsequence-with-occurrences-of-a-letter/) | [无] | [C++](2001-2500/2030-Smallest-K-Length-Subsequence-With-Occurrences-of-a-Letter/cpp-2030/) | | | +| 2031 | [Count Subarrays With More Ones Than Zeros](https://leetcode.com/problems/count-subarrays-with-more-ones-than-zeros/) | [缺:更简单的解法] | [C++](2001-2500/2031-Count-Subarrays-With-More-Ones-Than-Zeros/cpp-2031/) | | | +| 2032 | [Two Out of Three](https://leetcode.com/problems/two-out-of-three/) | [无] | [C++](2001-2500/2032-Two-Out-of-Three/cpp-2032/) | | | +| 2033 | [Minimum Operations to Make a Uni-Value Grid](https://leetcode.com/problems/minimum-operations-to-make-a-uni-value-grid/) | [无] | [C++](2001-2500/2033-Minimum-Operations-to-Make-a-Uni-Value-Grid/cpp-2033/) | | | +| 2034 | [Stock Price Fluctuation](https://leetcode.com/problems/stock-price-fluctuation/) | [无] | [C++](2001-2500/2034-Stock-Price-Fluctuation/cpp-2034/) | | | +| 2035 | [Partition Array Into Two Arrays to Minimize Sum Difference](https://leetcode.com/problems/partition-array-into-two-arrays-to-minimize-sum-difference/) | [无] | [C++](2001-2500/2035-Partition-Array-Into-Two-Arrays-to-Minimize-Sum-Difference/cpp-2035/) | | | +| 2036 | [Maximum Alternating Subarray Sum](https://leetcode.com/problems/maximum-alternating-subarray-sum/) | [无] | [c++](2001-2500/2036-Maximum-Alternating-Subarray-Sum/cpp-2036/) | | | +| 2037 | [Minimum Number of Moves to Seat Everyone](https://leetcode.com/problems/minimum-number-of-moves-to-seat-everyone/) | [无] | [C++](2001-2500/2037-Minimum-Number-of-Moves-to-Seat-Everyone/cpp-2037/) | | | +| 2038 | [Remove Colored Pieces if Both Neighbors are the Same Color](https://leetcode.com/problems/remove-colored-pieces-if-both-neighbors-are-the-same-color/) | [无] | [C++](2001-2500/2038-Remove-Colored-Pieces-if-Both-Neighbors-are-the-Same-Color/cpp-2038/) | | | +| 2039 | [The Time When the Network Becomes Idle](https://leetcode.com/problems/the-time-when-the-network-becomes-idle/) | [无] | [C++](2001-2500/2039-The-Time-When-the-Network-Becomes-Idle/cpp-2039/) | | | +| 2040 | [Kth Smallest Product of Two Sorted Arrays](https://leetcode.com/problems/kth-smallest-product-of-two-sorted-arrays/) | [无] | [C++](2001-2500/2040-Kth-Smallest-Product-of-Two-Sorted-Arrays/cpp-2040/) | | | +| 2041 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 2042 | [Check if Numbers Are Ascending in a Sentence](https://leetcode.com/problems/check-if-numbers-are-ascending-in-a-sentence/) | [无] | [C++](2001-2500/2042-Check-if-Numbers-Are-Ascending-in-a-Sentence/cpp-2042/) | | | +| 2043 | [Simple Bank System](https://leetcode.com/problems/simple-bank-system/) | [无] | [C++](2001-2500/2043-Simple-Bank-System/cpp-02043/) | | | +| 2044 | [Count Number of Maximum Bitwise-OR Subsets](https://leetcode.com/problems/count-number-of-maximum-bitwise-or-subsets/) | [无] | [C++](2001-2500/2044-Count-Number-of-Maximum-Bitwise-OR-Subsets/cpp-2044/) | | | +| 2045 | [Second Minimum Time to Reach Destination](https://leetcode.com/problems/second-minimum-time-to-reach-destination/) | [无] | [C++](2001-2500/2045-Second-Minimum-Time-to-Reach-Destination/cpp-2045/) | | | +| 2046 | [Sort Linked List Already Sorted Using Absolute Values](https://leetcode.com/problems/sort-linked-list-already-sorted-using-absolute-values/) | [无] | [C++](2001-2500/2046-Sort-Linked-List-Already-Sorted-Using-Absolute-Values/cpp-2046/) | | | +| 2047 | [Number of Valid Words in a Sentence](https://leetcode.com/problems/number-of-valid-words-in-a-sentence/) | [无] | [C++](2001-2500/2047-Number-of-Valid-Words-in-a-Sentence/cpp-2047/) | | | +| 2048 | [Next Greater Numerically Balanced Number](https://leetcode.com/problems/next-greater-numerically-balanced-number/) | [无] | [C++](2001-2500/2048-Next-Greater-Numerically-Balanced-Number/cpp-2048/) | | | +| 2049 | [Count Nodes With the Highest Score](https://leetcode.com/problems/count-nodes-with-the-highest-score/) | [无] | [C++](2001-2500/2049-Count-Nodes-With-the-Highest-Score/cpp-2049/) | | | +| 2050 | [Parallel Courses III](https://leetcode.com/problems/parallel-courses-iii/) | [无] | [C++](2001-2500/2050-Parallel-Courses-III/cpp-2050/) | | | +| 2051 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 2052 | [Minimum Cost to Separate Sentence Into Rows](https://leetcode.com/problems/minimum-cost-to-separate-sentence-into-rows/) | [无] | [C++](2001-2500/2052-Minimum-Cost-to-Separate-Sentence-Into-Rows/cpp-2052/) | | | +| 2053 | [Kth Distinct String in an Array](https://leetcode.com/problems/kth-distinct-string-in-an-array/) | [无] | [C++](2001-2500/2053-Kth-Distinct-String-in-an-Array/cpp-2053/) | | | +| 2054 | [Two Best Non-Overlapping Events](https://leetcode.com/problems/two-best-non-overlapping-events/) | [无] | [C++](2001-2500/2054-Two-Best-Non-Overlapping-Events/cpp-2054/) | | | +| 2055 | [Plates Between Candles](https://leetcode.com/problems/plates-between-candles/) | [无] | [C++](2001-2500/2055-Plates-Between-Candles/cpp-2055/) | | | +| 2056 | [Number of Valid Move Combinations On Chessboard](https://leetcode.com/problems/number-of-valid-move-combinations-on-chessboard/) | [无] | [C++](2001-2500/2056-Number-of-Valid-Move-Combinations-On-Chessboard/cpp-2056/) | | | +| 2057 | [Smallest Index With Equal Value](https://leetcode.com/problems/smallest-index-with-equal-value/) | [无] | [C++](2001-2500/2057-Smallest-Index-With-Equal-Value/cpp-2057/) | | | +| 2058 | [Find the Minimum and Maximum Number of Nodes Between Critical Points](https://leetcode.com/problems/find-the-minimum-and-maximum-number-of-nodes-between-critical-points/) | [无] | [C++](2001-2500/2058-Find-the-Minimum-and-Maximum-Number-of-Nodes-Between-Critical-Points/cpp-2058/) | | | +| 2059 | [Minimum Operations to Convert Number](https://leetcode.com/problems/minimum-operations-to-convert-number/) | [无] | [C++](2001-2500/2059-Minimum-Operations-to-Convert-Number/cpp-2059/) | | | +| 2060 | [Check if an Original String Exists Given Two Encoded Strings](https://leetcode.com/problems/check-if-an-original-string-exists-given-two-encoded-strings/) | [无] | [C++](2001-2500/2060-Check-if-an-Original-String-Exists-Given-Two-Encoded-Strings/cpp-2060/) | | | +| 2061 | [Number of Spaces Cleaning Robot Cleaned](https://leetcode.com/problems/number-of-spaces-cleaning-robot-cleaned/) | [无] | [C++](2001-2500/2061-Number-of-Spaces-Cleaning-Robot-Cleaned/cpp-2061/) | | | +| 2062 | [Count Vowel Substrings of a String](https://leetcode.com/problems/count-vowel-substrings-of-a-string/) | [无] | [C++](2001-2500/2062-Count-Vowel-Substrings-of-a-String/cpp-2062/) | | | +| 2063 | [Vowels of All Substrings](https://leetcode.com/problems/vowels-of-all-substrings/) | [无] | [C++](2001-2500/2063-Vowels-of-All-Substrings/cpp-2063/) | | | +| 2064 | [Minimized Maximum of Products Distributed to Any Store](https://leetcode.com/problems/minimized-maximum-of-products-distributed-to-any-store/) | [无] | [C++](2001-2500/2064-Minimized-Maximum-of-Products-Distributed-to-Any-Store/cpp-2064/) | | | +| 2065 | [Maximum Path Quality of a Graph](https://leetcode.com/problems/maximum-path-quality-of-a-graph/) | [无] | [C++](2001-2500/2065-Maximum-Path-Quality-of-a-Graph/cpp-2065/) | | | +| 2066 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 2067 | [Number of Equal Count Substrings](https://leetcode.com/problems/number-of-equal-count-substrings/) | [无] | [C++](2001-2500/2067-Number-of-Equal-Count-Substrings/cpp-2067/) | | | +| 2068 | [Check Whether Two Strings are Almost Equivalent](https://leetcode.com/problems/check-whether-two-strings-are-almost-equivalent/) | [无] | [C++](2001-2500/2068-Check-Whether-Two-Strings-are-Almost-Equivalent/cpp-2068/) | | | +| 2069 | [Walking Robot Simulation II](https://leetcode.com/problems/walking-robot-simulation-ii/) | [无] | [C++](2001-2500/2069-Walking-Robot-Simulation-II/cpp-2069/) | | | +| 2070 | [Most Beautiful Item for Each Query](https://leetcode.com/problems/most-beautiful-item-for-each-query/) | [无] | [C++](2001-2500/2070-Most-Beautiful-Item-for-Each-Query/cpp-2070/) | | | +| 2071 | [Maximum Number of Tasks You Can Assign](https://leetcode.com/problems/maximum-number-of-tasks-you-can-assign/) | [无] | [C++](2001-2500/2071-Maximum-Number-of-Tasks-You-Can-Assign/cpp-2071/) | | | +| 2072 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 2073 | [Time Needed to Buy Tickets](https://leetcode.com/problems/time-needed-to-buy-tickets/) | [无] | [C++](2001-2500/2073-Time-Needed-to-Buy-Tickets/cpp-2073/) | | | +| 2074 | [Reverse Nodes in Even Length Groups](https://leetcode.com/problems/reverse-nodes-in-even-length-groups/) | [无] | [C++](2001-2500/2074-Reverse-Nodes-in-Even-Length-Groups/cpp-2074/) | | | +| 2075 | [Decode the Slanted Ciphertext](https://leetcode.com/problems/decode-the-slanted-ciphertext/) | [无] | [C++](2001-2500/2075-Decode-the-Slanted-Ciphertext/cpp-2075/) | | | +| 2076 | [Process Restricted Friend Requests](https://leetcode.com/problems/process-restricted-friend-requests/) | [无] | [C++](2001-2500/2076-Process-Restricted-Friend-Requests/cpp-2076/) | | | +| 2077 | [Paths in Maze That Lead to Same Room](https://leetcode.com/problems/paths-in-maze-that-lead-to-same-room/) | [无] | [C++](2001-2500/2077-Paths-in-Maze-That-Lead-to-Same-Room/cpp-2077/) | | | +| 2078 | [Two Furthest Houses With Different Colors](https://leetcode.com/problems/two-furthest-houses-with-different-colors/) | [无] | [C++](2001-2500/2078-Two-Furthest-Houses-With-Different-Colors/cpp-2078/) | | | +| 2079 | [Watering Plants](https://leetcode.com/problems/watering-plants/) | [无] | [C++](2001-2500/2079-Watering-Plants/cpp-2079/) | | | +| 2080 | [Range Frequency Queries](https://leetcode.com/problems/range-frequency-queries/) | [无] | [C++](2001-2500/2080-Range-Frequency-Queries/cpp-2080/) | | | +| 2081 | [Sum of k-Mirror Numbers](https://leetcode.com/problems/sum-of-k-mirror-numbers/) | [无] | [C++](2001-2500/2081-Sum-of-k-Mirror-Numbers/cpp-2081/) | | | +| 2082 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 2083 | [Substrings That Begin and End With the Same Letter](https://leetcode.com/problems/substrings-that-begin-and-end-with-the-same-letter/) | [无] | [C++](2001-2500/2083-Substrings-That-Begin-and-End-With-the-Same-Letter/cpp-2083/) | | | +| 2084 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 2085 | [Count Common Words With One Occurrence](https://leetcode.com/problems/count-common-words-with-one-occurrence/) | [无] | [C++](2001-2500/2085-Count-Common-Words-With-One-Occurrence/cpp-2085/) | | | +| 2086 | [Minimum Number of Buckets Required to Collect Rainwater from Houses](https://leetcode.com/problems/minimum-number-of-buckets-required-to-collect-rainwater-from-houses/) | [无] | [C++](2001-2500/2086-Minimum-Number-of-Buckets-Required-to-Collect-Rainwater-from-Houses/cpp-2086/) | | | +| 2087 | [Minimum Cost Homecoming of a Robot in a Grid](https://leetcode.com/problems/minimum-cost-homecoming-of-a-robot-in-a-grid/) | [无] | [C++](2001-2500/2087-Minimum-Cost-Homecoming-of-a-Robot-in-a-Grid/cpp-2087/) | | | +| 2088 | [Count Fertile Pyramids in a Land](https://leetcode.com/problems/count-fertile-pyramids-in-a-land/) | [无] | [C++](2001-2500/2088-Count-Fertile-Pyramids-in-a-Land/cpp-2088/) | | | +| 2089 | [Find Target Indices After Sorting Array](https://leetcode.com/problems/find-target-indices-after-sorting-array/) | [无] | [C++](2001-2500/2089-Find-Target-Indices-After-Sorting-Array/cpp-2089/) | | | +| 2090 | [K Radius Subarray Averages](https://leetcode.com/problems/k-radius-subarray-averages/) | [无] | [C++](2001-2500/2090-K-Radius-Subarray-Averages/cpp-2090/) | | | +| 2091 | [Removing Minimum and Maximum From Array](https://leetcode.com/problems/removing-minimum-and-maximum-from-array/) | [无] | [C++](2001-2500/2091-Removing-Minimum-and-Maximum-From-Array/cpp-2091/) | | | +| 2092 | [Find All People With Secret](https://leetcode.com/problems/find-all-people-with-secret/) | [无] | [C++](2001-2500/2092-Find-All-People-With-Secret/cpp-2092/) | | | +| 2093 | [Minimum Cost to Reach City With Discounts](https://leetcode.com/problems/minimum-cost-to-reach-city-with-discounts/) | [无] | [C++](2001-2500/2093-Minimum-Cost-to-Reach-City-With-Discounts/cpp-2093/) | | | +| 2094 | [Finding 3-Digit Even Numbers](https://leetcode.com/problems/finding-3-digit-even-numbers/) | [无] | [C++](2001-2500/2094-Finding-3-Digit-Even-Numbers/cpp-2094/) | | | +| 2095 | [Delete the Middle Node of a Linked List](https://leetcode.com/problems/delete-the-middle-node-of-a-linked-list/) | [无] | [C++](2001-2500/2095-Delete-the-Middle-Node-of-a-Linked-List/cpp-2095/) | | | +| 2096 | [Step-By-Step Directions From a Binary Tree Node to Another](https://leetcode.com/problems/step-by-step-directions-from-a-binary-tree-node-to-another/) | [无] | [C++](2001-2500/2096-Step-By-Step-Directions-From-a-Binary-Tree-Node-to-Another/cpp-2096/) | | | +| 2097 | [Valid Arrangement of Pairs](https://leetcode.com/problems/valid-arrangement-of-pairs/) | [无] | [C++](2001-2500/2097-Valid-Arrangement-of-Pairs/cpp-2097/) | | | +| 2098 | [Subsequence of Size K With the Largest Even Sum](https://leetcode.com/problems/subsequence-of-size-k-with-the-largest-even-sum/) | [无] | [C++](2001-2500/2098-Subsequence-of-Size-K-With-the-Largest-Even-Sum/cpp-2098/) | | | +| 2099 | [Find Subsequence of Length K With the Largest Sum](https://leetcode.com/problems/find-subsequence-of-length-k-with-the-largest-sum/) | [无] | [C++](2001-2500/2099-Find-Subsequence-of-Length-K-With-the-Largest-Sum/cpp-2099/) | | | +| 2100 | [Find Good Days to Rob the Bank](https://leetcode.com/problems/find-good-days-to-rob-the-bank/) | [无] | [C++](2001-2500/2100-Find-Good-Days-to-Rob-the-Bank/cpp-2100/) | | | +| 2101 | [Detonate the Maximum Bombs](https://leetcode.com/problems/detonate-the-maximum-bombs/) | [无] | [C++](2001-2500/2101-Detonate-the-Maximum-Bombs/cpp-2101/) | | | +| 2102 | [Sequentially Ordinal Rank Tracker](https://leetcode.com/problems/sequentially-ordinal-rank-tracker/) | [无] | [C++](2001-2500/2102-Sequentially-Ordinal-Rank-Tracker/cpp-2102/) | | | +| 2103 | [Rings and Rods](https://leetcode.com/problems/rings-and-rods/) | [无] | [C++](2001-2500/2103-Rings-and-Rods/cpp-2103/) | | | +| 2104 | [Sum of Subarray Ranges](https://leetcode.com/problems/sum-of-subarray-ranges/) | [无] | [C++](2001-2500/2104-Sum-of-Subarray-Ranges/cpp-2104/) | | | +| 2105 | [Watering Plants II](https://leetcode.com/problems/watering-plants-ii/) | [无] | [C++](2001-2500/2105-Watering-Plants-II/cpp-2105/) | | | +| 2106 | [Maximum Fruits Harvested After at Most K Steps](https://leetcode.com/problems/maximum-fruits-harvested-after-at-most-k-steps/) | [无] | [C++](2001-2500/2106-Maximum-Fruits-Harvested-After-at-Most-K-Steps/cpp-2106/) | | | +| 2107 | [Number of Unique Flavors After Sharing K Candies](https://leetcode.com/problems/number-of-unique-flavors-after-sharing-k-candies/) | [无] | [C++](2001-2500/2107-Number-of-Unique-Flavors-After-Sharing-K-Candies/cpp-2107/) | | | +| 2108 | [Find First Palindromic String in the Array](https://leetcode.com/problems/find-first-palindromic-string-in-the-array/) | [无] | [C++](2001-2500/2108-Find-First-Palindromic-String-in-the-Array/cpp-2108/) | | | +| 2109 | [Adding Spaces to a String](https://leetcode.com/problems/adding-spaces-to-a-string/) | [无] | [C++](2001-2500/2109-Adding-Spaces-to-a-String/cpp-2109/) | | | +| 2110 | [Number of Smooth Descent Periods of a Stock](https://leetcode.com/problems/number-of-smooth-descent-periods-of-a-stock/) | [无] | [C++](2001-2500/2110-Number-of-Smooth-Descent-Periods-of-a-Stock/cpp-2110/) | | | +| 2111 | [Minimum Operations to Make the Array K-Increasing](https://leetcode.com/problems/minimum-operations-to-make-the-array-k-increasing/) | [无] | [C++](2001-2500/2111-Minimum-Operations-to-Make-the-Array-K-Increasing/cpp-2111/) | | | +| 2112 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 2113 | [Elements in Array After Removing and Replacing Elements](https://leetcode.com/problems/elements-in-array-after-removing-and-replacing-elements/) | [无] | [C++](2001-2500/2113-Elements-in-Array-After-Removing-and-Replacing-Elements/cpp-2113/) | | | +| 2114 | [Maximum Number of Words Found in Sentences](https://leetcode.com/problems/maximum-number-of-words-found-in-sentences/) | [无] | [C++](2001-2500/2114-Maximum-Number-of-Words-Found-in-Sentences/cpp-2114/) | | | +| 2115 | [Find All Possible Recipes from Given Supplies](https://leetcode.com/problems/find-all-possible-recipes-from-given-supplies/) | [无] | [C++](2001-2500/2115-Find-All-Possible-Recipes-from-Given-Supplies/cpp-2115/) | | | +| 2116 | [Check if a Parentheses String Can Be Valid](https://leetcode.com/problems/check-if-a-parentheses-string-can-be-valid/) | [无] | [C++](2001-2500/2116-Check-if-a-Parentheses-String-Can-Be-Valid/cpp-2116/) | | | +| 2117 | [Abbreviating the Product of a Range](https://leetcode.com/problems/abbreviating-the-product-of-a-range/) | [无] | [C++](2001-2500/2117-Abbreviating-the-Product-of-a-Range/cpp-2117/) | | | +| 2118 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 2119 | [A Number After a Double Reversal](https://leetcode.com/problems/a-number-after-a-double-reversal/) | [无] | [C++](2001-2500/2119-A-Number-After-a-Double-Reversal/cpp-2119/) | | | +| 2120 | [Execution of All Suffix Instructions Staying in a Grid](https://leetcode.com/problems/execution-of-all-suffix-instructions-staying-in-a-grid/) | [无] | [C++](2001-2500/2120-Execution-of-All-Suffix-Instructions-Staying-in-a-Grid/cpp-2120/) | | | +| 2121 | [Intervals Between Identical Elements](https://leetcode.com/problems/intervals-between-identical-elements/) | [无] | [C++](2001-2500/2121-Intervals-Between-Identical-Elements/cpp-2121/) | | | +| 2122 | [Recover the Original Array](https://leetcode.com/problems/recover-the-original-array/) | [无] | [C++](2001-2500/2122-Recover-the-Original-Array/cpp-2122/) | | | +| 2123 | [Minimum Operations to Remove Adjacent Ones in Matrix](2001-2500/2123-Minimum-Operations-to-Remove-Adjacent-Ones-in-Matrix/cpp-2123/) | [无] | [C++](2001-2500/2123-Minimum-Operations-to-Remove-Adjacent-Ones-in-Matrix/cpp-2123/) | | | +| 2124 | [Check if All A's Appears Before All B's](https://leetcode.com/problems/check-if-all-as-appears-before-all-bs/) | [无] | [C++](2001-2500/2124-Check-if-All-As-Appears-Before-All-Bs/cpp-2124/) | | | +| 2125 | [Number of Laser Beams in a Bank](https://leetcode.com/problems/number-of-laser-beams-in-a-bank/) | [无] | [C++](2001-2500/2125-Number-of-Laser-Beams-in-a-Bank/cpp-2125/) | | | +| 2126 | [Destroying Asteroids](https://leetcode.com/problems/destroying-asteroids/) | [无] | [C++](2001-2500/2126-Destroying-Asteroids/cpp-2126/) | | | +| 2127 | [Maximum Employees to Be Invited to a Meeting](https://leetcode.com/problems/maximum-employees-to-be-invited-to-a-meeting/) | [无] | [C++](2001-2500/2127-Maximum-Employees-to-Be-Invited-to-a-Meeting/cpp-2127/) | | | +| 2128 | [Remove All Ones With Row and Column Flips](https://leetcode.com/problems/remove-all-ones-with-row-and-column-flips/) | [C++](2001-2500/2128-Remove-All-Ones-With-Row-and-Column-Flips/cpp-2128/) | | | | +| 2129 | [Capitalize the Title](https://leetcode.com/problems/capitalize-the-title/) | [无] | [C++](2001-2500/2129-Capitalize-the-Title/cpp-2129/) | | | +| 2130 | [Maximum Twin Sum of a Linked List](https://leetcode.com/problems/maximum-twin-sum-of-a-linked-list/) | [无] | [C++](2001-2500/2130-Maximum-Twin-Sum-of-a-Linked-List/cpp-2130/) | | | +| 2131 | [Longest Palindrome by Concatenating Two Letter Words](https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/) | [无] | [C++](2001-2500/2131-Longest-Palindrome-by-Concatenating-Two-Letter-Words/cpp-2131/) | | | +| 2132 | [Stamping the Grid](https://leetcode.com/problems/stamping-the-grid/) | [缺:二维差分数组] | [C++](2001-2500/2132-Stamping-the-Grid/cpp-2132/) | | | +| 2133 | [Check if Every Row and Column Contains All Numbers](https://leetcode.com/problems/check-if-every-row-and-column-contains-all-numbers/) | [无] | [C++](2001-2500/2133-Check-if-Every-Row-and-Column-Contains-All-Numbers/cpp-2133/) | | | +| 2134 | [Minimum Swaps to Group All 1's Together II](https://leetcode.com/problems/minimum-swaps-to-group-all-1s-together-ii/) | [无] | [C++](2001-2500/2134-Minimum-Swaps-to-Group-All-1s-Together-II/cpp-2134/) | | | +| 2135 | [Count Words Obtained After Adding a Letter](https://leetcode.com/problems/count-words-obtained-after-adding-a-letter/) | [无] | [C++](2001-2500/2135-Count-Words-Obtained-After-Adding-a-Letter/cpp-2135/) | | | +| 2136 | [Earliest Possible Day of Full Bloom](https://leetcode.com/problems/earliest-possible-day-of-full-bloom/) | [无] | [C++](2001-2500/2136-Earliest-Possible-Day-of-Full-Bloom/cpp-2136/) | | | +| 2137 | [Pour Water Between Buckets to Make Water Levels Equal](https://leetcode.com/problems/pour-water-between-buckets-to-make-water-levels-equal/) | [无] | [C++](2001-2500/2137-Pour-Water-Between-Buckets-to-Make-Water-Levels-Equal/cpp-2137/) | | | +| 2138 | [Divide a String Into Groups of Size k](https://leetcode.com/problems/divide-a-string-into-groups-of-size-k/) | [无] | [C++](2001-2500/2138-Divide-a-String-Into-Groups-of-Size-k/cpp-2138/) | | | +| 2139 | [Minimum Moves to Reach Target Score](https://leetcode.com/problems/minimum-moves-to-reach-target-score/) | [无] | [C++](2001-2500/2139-Minimum-Moves-to-Reach-Target-Score/cpp-2139/) | | | +| 2140 | [Solving Questions With Brainpower](https://leetcode.com/problems/solving-questions-with-brainpower/) | [无] | [C++](2001-2500/2140-Solving-Questions-With-Brainpower/cpp-2140/) | | | +| 2141 | [Maximum Running Time of N Computers](https://leetcode.com/problems/maximum-running-time-of-n-computers/) | [无] | [C++](2001-2500/2141-Maximum-Running-Time-of-N-Computers/cpp-2141/) | | | +| 2142 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 2143 | [Choose Numbers From Two Arrays in Range](https://leetcode.com/problems/choose-numbers-from-two-arrays-in-range/) | [无] | [C++](2001-2500/2143-Choose-Numbers-From-Two-Arrays-in-Range/cpp-2143/) | | | +| 2144 | [Minimum Cost of Buying Candies With Discount](https://leetcode.com/problems/minimum-cost-of-buying-candies-with-discount/) | [无] | [C++](2001-2500/2144-Minimum-Cost-of-Buying-Candies-With-Discount/cpp-2144/) | | | +| 2145 | [Count the Hidden Sequences](https://leetcode.com/problems/count-the-hidden-sequences/) | [无] | [C++](2001-2500/2145-Count-the-Hidden-Sequences/cpp-2145/) | | | +| 2146 | [K Highest Ranked Items Within a Price Range](https://leetcode.com/problems/k-highest-ranked-items-within-a-price-range/) | [无] | [C++](2001-2500/2146-K-Highest-Ranked-Items-Within-a-Price-Range/cpp-2146/) | | | +| 2147 | [Number of Ways to Divide a Long Corridor](https://leetcode.com/problems/number-of-ways-to-divide-a-long-corridor/) | [无]
[缺:数学更简单的写法;dp] | [C++](2001-2500/2147-Number-of-Ways-to-Divide-a-Long-Corridor/cpp-2147/) | | | +| 2148 | [Count Elements With Strictly Smaller and Greater Elements](https://leetcode.com/problems/count-elements-with-strictly-smaller-and-greater-elements/) | [无] | [C++](2001-2500/2148-Count-Elements-With-Strictly-Smaller-and-Greater-Elements/cpp-2148/) | | | +| 2149 | [Rearrange Array Elements by Sign](https://leetcode.com/problems/rearrange-array-elements-by-sign/) | [无] | [C++](2001-2500/2149-Rearrange-Array-Elements-by-Sign/cpp-2149/) | | | +| 2150 | [Find All Lonely Numbers in the Array](https://leetcode.com/problems/find-all-lonely-numbers-in-the-array/) | [无] | [C++](2001-2500/2150-Find-All-Lonely-Numbers-in-the-Array/cpp-2150/) | | | +| 2151 | [Maximum Good People Based on Statements](https://leetcode.com/problems/maximum-good-people-based-on-statements/) | [无] | [C++](2001-2500/2151-Maximum-Good-People-Based-on-Statements/cpp-2151/) | | | +| 2152 | [Minimum Number of Lines to Cover Points](https://leetcode.com/problems/minimum-number-of-lines-to-cover-points/) | [无] | [C++](2001-2500/2152-Minimum-Number-of-Lines-to-Cover-Points/cpp-2152/) | | | +| 2153 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 2154 | [Keep Multiplying Found Values by Two](https://leetcode.com/problems/keep-multiplying-found-values-by-two/) | [无] | [C++](2001-2500/2154-Keep-Multiplying-Found-Values-by-Two/cpp-2154/) | | | +| 2155 | [All Divisions With the Highest Score of a Binary Array](https://leetcode.com/problems/all-divisions-with-the-highest-score-of-a-binary-array/) | [无] | [C++](2001-2500/2155-All-Divisions-With-the-Highest-Score-of-a-Binary-Array/cpp-2155/) | | | +| 2156 | [Find Substring With Given Hash Value](https://leetcode.com/problems/find-substring-with-given-hash-value/) | [无] | [C++](2001-2500/2156-Find-Substring-With-Given-Hash-Value/cpp-2156/) | | | +| 2157 | [Groups of Strings](https://leetcode.com/problems/groups-of-strings/) | [无] | [C++](2001-2500/2157-Groups-of-Strings/cpp-2157/) | | | +| 2158 | [Amount of New Area Painted Each Day](https://leetcode.com/problems/amount-of-new-area-painted-each-day/) | [无] | [C++](2001-2500/2158-Amount-of-New-Area-Painted-Each-Day/cpp-2158/) | | | +| 2159 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 2160 | [Minimum Sum of Four Digit Number After Splitting Digits](https://leetcode.com/problems/minimum-sum-of-four-digit-number-after-splitting-digits/) | [无] | [C++](2001-2500/2160-Minimum-Sum-of-Four-Digit-Number-After-Splitting-Digits/cpp-2160/) | | | +| 2161 | [Partition Array According to Given Pivot](https://leetcode.com/problems/partition-array-according-to-given-pivot/) | [无] | [C++](2001-2500/2161-Partition-Array-According-to-Given-Pivot/cpp-2161/) | | | +| 2162 | [Minimum Cost to Set Cooking Time](https://leetcode.com/problems/minimum-cost-to-set-cooking-time/) | [无] | [C++](2001-2500/2162-Minimum-Cost-to-Set-Cooking-Time/cpp-2162/) | | | +| 2163 | [Minimum Difference in Sums After Removal of Elements](https://leetcode.com/problems/minimum-difference-in-sums-after-removal-of-elements/) | [无] | [C++](2001-2500/2163-Minimum-Difference-in-Sums-After-Removal-of-Elements/cpp-2163/) | | | +| 2164 | [Sort Even and Odd Indices Independently](https://leetcode.com/problems/sort-even-and-odd-indices-independently/) | [无] | [C++](2001-2500/2164-Sort-Even-and-Odd-Indices-Independently/cpp-2164/) | | | +| 2165 | [Smallest Value of the Rearranged Number](https://leetcode.com/problems/smallest-value-of-the-rearranged-number/) | [无] | [C++](2001-2500/2165-Smallest-Value-of-the-Rearranged-Number/cpp-2165/) | | | +| 2166 | [Design Bitset](https://leetcode.com/problems/design-bitset/) | [无] | [C++](2001-2500/2166-Design-Bitset/cpp-2166/) | | | +| 2167 | [Minimum Time to Remove All Cars Containing Illegal Goods](https://leetcode.com/problems/minimum-time-to-remove-all-cars-containing-illegal-goods/) | [无] | [C++](2001-2500/2167-Minimum-Time-to-Remove-All-Cars-Containing-Illegal-Goods/cpp-2167/) | | | +| 2168 | [Unique Substrings With Equal Digit Frequency](https://leetcode.com/problems/unique-substrings-with-equal-digit-frequency/) | [无] | [C++](2001-2500/2168-Unique-Substrings-With-Equal-Digit-Frequency/cpp-2168/) | | | +| 2169 | [Count Operations to Obtain Zero](https://leetcode.com/problems/count-operations-to-obtain-zero/) | [无] | [C++](2001-2500/2169-Count-Operations-to-Obtain-Zero/cpp-2169/) | | | +| 2170 | [Minimum Operations to Make the Array Alternating](https://leetcode.com/problems/minimum-operations-to-make-the-array-alternating/) | [无] | [C++](2001-2500/2170-Minimum-Operations-to-Make-the-Array-Alternating/cpp-2170/) | | | +| 2171 | [Removing Minimum Number of Magic Beans](https://leetcode.com/problems/removing-minimum-number-of-magic-beans/) | [无] | [C++](2001-2500/2171-Removing-Minimum-Number-of-Magic-Beans/cpp-2171/) | | | +| 2172 | [Maximum AND Sum of Array](https://leetcode.com/problems/maximum-and-sum-of-array/) | [无] | [C++](2001-2500/2172-Maximum-AND-Sum-of-Array/cpp-2172/) | | | +| 2173 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 2174 | [Remove All Ones With Row and Column Flips II](https://leetcode.com/problems/remove-all-ones-with-row-and-column-flips-ii/) | [无] | [C++](2001-2500/2174-Remove-All-Ones-With-Row-and-Column-Flips-II/cpp-2174/) | | | +| 2175 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 2176 | [Count Equal and Divisible Pairs in an Array](https://leetcode.com/problems/count-equal-and-divisible-pairs-in-an-array/) | [无] | [C++](2001-2500/2176-Count-Equal-and-Divisible-Pairs-in-an-Array/cpp-2176/) | | | +| 2177 | [Find Three Consecutive Integers That Sum to a Given Number](https://leetcode.com/problems/find-three-consecutive-integers-that-sum-to-a-given-number/) | [无] | [C++](2001-2500/2177-Find-Three-Consecutive-Integers-That-Sum-to-a-Given-Number/cpp-2177/) | | | +| 2178 | [Maximum Split of Positive Even Integers](https://leetcode.com/problems/maximum-split-of-positive-even-integers/) | [无] | [C++](2001-2500/2178-Maximum-Split-of-Positive-Even-Integers/cpp-2178/) | | | +| 2179 | [Count Good Triplets in an Array](https://leetcode.com/problems/count-good-triplets-in-an-array/) | [无] | [C++](2001-2500/2179-Count-Good-Triplets-in-an-Array/cpp-2179/) | | | +| 2180 | [Count Integers With Even Digit Sum](https://leetcode.com/problems/count-integers-with-even-digit-sum/) | [无] | [C++](2001-2500/2180-Count-Integers-With-Even-Digit-Sum/cpp-2180/) | | | +| 2181 | [Merge Nodes in Between Zeros](https://leetcode.com/problems/merge-nodes-in-between-zeros/) | [无] | [C++](2001-2500/2181-Merge-Nodes-in-Between-Zeros/cpp-2181/) | | | +| 2182 | [Construct String With Repeat Limit](https://leetcode.com/problems/construct-string-with-repeat-limit/) | [C++](2001-2500/2182-Construct-String-With-Repeat-Limit/cpp-2182/) | | | | +| 2183 | [Count Array Pairs Divisible by K](https://leetcode.com/problems/count-array-pairs-divisible-by-k/) | [无] | [C++](2001-2500/2183-Count-Array-Pairs-Divisible/cpp-2183/) | | | +| 2184 | [Number of Ways to Build Sturdy Brick Wall](https://leetcode.com/problems/number-of-ways-to-build-sturdy-brick-wall/) | [无] | [C++](2001-2500/2184-Number-of-Ways-to-Build-Sturdy-Brick-Wall/cpp-2184/) | | | +| 2185 | [Counting Words With a Given Prefix](https://leetcode.com/problems/counting-words-with-a-given-prefix/) | [无] | [C++](2001-2500/2185-Counting-Words-With-a-Given-Prefix/cpp-2185/) | | | +| 2186 | [Minimum Number of Steps to Make Two Strings Anagram II](https://leetcode.com/problems/minimum-number-of-steps-to-make-two-strings-anagram-ii/) | [无] | [C++](2001-2500/2186-Minimum-Number-of-Steps-to-Make-Two-Strings-Anagram-II/cpp-2186/) | | | +| 2187 | [Minimum Time to Complete Trips](https://leetcode.com/problems/minimum-time-to-complete-trips/) | [无] | [C++](2001-2500/2187-Minimum-Time-to-Complete-Trips/cpp-2187/) | | | +| 2188 | [Minimum Time to Finish the Race](https://leetcode.com/problems/minimum-time-to-finish-the-race/) | [无] | [C++](2001-2500/2188-Minimum-Time-to-Finish-the-Race/cpp-2188/) | | | +| 2189 | [Number of Ways to Build House of Cards](https://leetcode.com/problems/number-of-ways-to-build-house-of-cards/) | [无] | [C++](2001-2500/2189-Number-of-Ways-to-Build-House-of-Cards/cpp-2189/) | | | +| 2190 | [Most Frequent Number Following Key In an Array](https://leetcode.com/problems/most-frequent-number-following-key-in-an-array/) | [无] | [C++](2001-2500/2190-Most-Frequent-Number-Following-Key-In-an-Array/cpp-2190/) | | | +| 2191 | [Sort the Jumbled Numbers](https://leetcode.com/problems/sort-the-jumbled-numbers/) | [无] | [C++](2001-2500/2191-Sort-the-Jumbled-Numbers/cpp-2191/) | | | +| 2192 | [All Ancestors of a Node in a Directed Acyclic Graph](https://leetcode.com/problems/all-ancestors-of-a-node-in-a-directed-acyclic-graph/) | [无] | [C++](2001-2500/2192-All-Ancestors-of-a-Node-in-a-Directed-Acyclic-Graph/cpp-2192/) | | | +| 2193 | [Minimum Number of Moves to Make Palindrome](https://leetcode.com/problems/minimum-number-of-moves-to-make-palindrome/) | [无] | [C++](2001-2500/2193-Minimum-Number-of-Moves-to-Make-Palindrome/cpp-2193/) | | | +| 2194 | [Cells in a Range on an Excel Sheet](https://leetcode.com/problems/cells-in-a-range-on-an-excel-sheet/) | [无] | [C++](2001-2500/2194-Cells-in-a-Range-on-an-Excel-Sheet/cpp-2194/) | | | +| 2195 | [Append K Integers With Minimal Sum](https://leetcode.com/problems/append-k-integers-with-minimal-sum/) | [无] | [C++](2001-2500/2195-Append-K-Integers-With-Minimal-Sum/cpp-2195/) | | | +| 2196 | [Create Binary Tree From Descriptions](https://leetcode.com/problems/create-binary-tree-from-descriptions/) | [无] | [C++](2001-2500/2196-Create-Binary-Tree-From-Descriptions/cpp-2196/) | | | +| 2197 | [Replace Non-Coprime Numbers in Array](https://leetcode.com/problems/replace-non-coprime-numbers-in-array/) | [无] | [C++](2001-2500/2197-Replace-Non-Coprime-Numbers-in-Array/cpp-2197/) | | | +| 2198 | [Number of Single Divisor Triplets](https://leetcode.com/problems/number-of-single-divisor-triplets/) | [无] | [C++](2001-2500/2198-Number-of-Single-Divisor-Triplets/cpp-2198/) | | | +| 2199 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 2200 | [Find All K-Distant Indices in an Array](https://leetcode.com/problems/find-all-k-distant-indices-in-an-array/) | [无] | [C++](2001-2500/2200-Find-All-K-Distant-Indices-in-an-Array/cpp-2200/) | | | +| 2201 | [Count Artifacts That Can Be Extracted](https://leetcode.com/problems/count-artifacts-that-can-be-extracted/) | [无] | [C++](2001-2500/2201-Count-Artifacts-That-Can-Be-Extracted/cpp-2201/) | | | +| 2202 | [Maximize the Topmost Element After K Moves](https://leetcode.com/problems/maximize-the-topmost-element-after-k-moves/) | [无] | [C++](2001-2500/2202-Maximize-the-Topmost-Element-After-K-Moves/cpp-2202/) | | | +| 2203 | [Minimum Weighted Subgraph With the Required Paths](https://leetcode.com/problems/minimum-weighted-subgraph-with-the-required-paths/) | [无] | [C++](2001-2500/2203-Minimum-Weighted-Subgraph-With-the-Required-Paths/cpp-2203/) | | | +| 2204 | [Distance to a Cycle in Undirected Graph](https://leetcode.com/problems/distance-to-a-cycle-in-undirected-graph/) | [无] | [C++](2001-2500/2204-Distance-to-a-Cycle-in-Undirected-Graph/cpp-2204/) | | | +| 2205 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 2206 | [Divide Array Into Equal Pairs](https://leetcode.com/problems/divide-array-into-equal-pairs/) | [无] | [C++](2001-2500/2206-Divide-Array-Into-Equal-Pairs/cpp-2206/) | | | +| 2207 | [Maximize Number of Subsequences in a String](https://leetcode.com/problems/maximize-number-of-subsequences-in-a-string/) | [无] | [C++](2001-2500/2207-Maximize-Number-of-Subsequences-in-a-String/cpp-2207/) | | | +| 2208 | [Minimum Operations to Halve Array Sum](https://leetcode.com/problems/minimum-operations-to-halve-array-sum/) | [无] | [C++](2001-2500/2208-Minimum-Operations-to-Halve-Array-Sum/cpp-2208/) | | | +| 2209 | [Minimum White Tiles After Covering With Carpets](https://leetcode.com/problems/minimum-white-tiles-after-covering-with-carpets/) | [无] | [C++](2001-2500/2209-Minimum-White-Tiles-After-Covering-With-Carpets/cpp-2209/) | | | +| 2210 | [Count Hills and Valleys in an Array](https://leetcode.com/problems/count-hills-and-valleys-in-an-array/) | [无] | [C++](2001-2500/2210-Count-Hills-and-Valleys-in-an-Array/cpp-2210/) | | | +| 2211 | [Count Collisions on a Road](https://leetcode.com/problems/count-collisions-on-a-road/) | [无] | [C++](2001-2500/2211-Count-Collisions-on-a-Road/cpp-2211/) | | | +| 2212 | [Maximum Points in an Archery Competition](https://leetcode.com/problems/maximum-points-in-an-archery-competition/) | [无] | [C++](2001-2500/2212-Maximum-Points-in-an-Archery-Competition/cpp-2212/) | | | +| 2213 | [Longest Substring of One Repeating Character](https://leetcode.com/problems/longest-substring-of-one-repeating-character/) | [无] | [C++](2001-2500/2213-Longest-Substring-of-One-Repeating-Character/cpp-2213/) | | | +| 2214 | [Minimum Health to Beat Game](https://leetcode.com/problems/minimum-health-to-beat-game/) | [无] | [C++](2001-2500/2214-Minimum-Health-to-Beat-Game/cpp-2214/)| | | +| 2215 | [Find the Difference of Two Arrays](https://leetcode.com/problems/find-the-difference-of-two-arrays/) | [无] | [C++](2001-2500/2215-Find-the-Difference-of-Two-Arrays/cpp-2215/) | | | +| 2216 | [Minimum Deletions to Make Array Beautiful](https://leetcode.com/problems/minimum-deletions-to-make-array-beautiful/) | [无] | [C++](2001-2500/2216-Minimum-Deletions-to-Make-Array-Beautiful/cpp-2216/) | | | +| 2217 | [Find Palindrome With Fixed Length](https://leetcode.com/problems/find-palindrome-with-fixed-length/) | [无] | [C++](2001-2500/2217-Find-Palindrome-With-Fixed-Length/cpp-2217/) | | | +| 2218 | [Maximum Value of K Coins From Piles](https://leetcode.com/problems/maximum-value-of-k-coins-from-piles/) | [无] | [C++](2001-2500/2218-Maximum-Value-of-K-Coins-From-Piles/cpp-2218/) | | | +| 2219 | [Maximum Sum Score of Array](https://leetcode.com/problems/maximum-sum-score-of-array/) | [无] | [C++](2001-2500/2219-Maximum-Sum-Score-of-Array/cpp-2219/) | | | +| 2220 | [Minimum Bit Flips to Convert Number](https://leetcode.com/problems/minimum-bit-flips-to-convert-number/) | [无] | [C++](2001-2500/2220-Minimum-Bit-Flips-to-Convert-Number/cpp-2220/) | | | +| 2221 | [Find Triangular Sum of an Array](https://leetcode.com/problems/find-triangular-sum-of-an-array/) | [无] | [C++](2001-2500/2221-Find-Triangular-Sum-of-an-Array/cpp-2221/) | | | +| 2222 | [Number of Ways to Select Buildings](https://leetcode.com/problems/number-of-ways-to-select-buildings/) | [无] | [C++](2001-2500/2222-Number-of-Ways-to-Select-Buildings/cpp-2222/) | | | +| 2223 | [Sum of Scores of Built Strings](https://leetcode.com/problems/sum-of-scores-of-built-strings/) | [无] | [C++](2001-2500/2223-Sum-of-Scores-of-Built-Strings/cpp-2223/) | | | +| 2224 | [Minimum Number of Operations to Convert Time](https://leetcode.com/problems/minimum-number-of-operations-to-convert-time/) | [无] | [C++](2001-2500/2224-Minimum-Number-of-Operations-to-Convert-Time/cpp-2224/) | | | +| 2225 | [Find Players With Zero or One Losses](https://leetcode.com/problems/find-players-with-zero-or-one-losses/) | [无] | [C++](2001-2500/2225-Find-Players-With-Zero-or-One-Losses/cpp-2225/) | | | +| 2226 | [Maximum Candies Allocated to K Children](https://leetcode.com/problems/maximum-candies-allocated-to-k-children/) | [无] | [C++](2001-2500/2226-Maximum-Candies-Allocated-to-K-Children/cpp-2226/) | | | +| 2227 | [Encrypt and Decrypt Strings](https://leetcode.com/problems/encrypt-and-decrypt-strings/) | [无] | [C++](2001-2500/2227-Encrypt-and-Decrypt-Strings/cpp-2227/) | | | +| 2228 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 2229 | [Check if an Array Is Consecutive](https://leetcode.com/problems/check-if-an-array-is-consecutive/) | [无] | [C++](2001-2500/2229-Check-if-an-Array-Is-Consecutive/cpp-2229/) | | | +| 2230 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 2231 | [Largest Number After Digit Swaps by Parity](https://leetcode.com/problems/largest-number-after-digit-swaps-by-parity/) | [无] | [C++](2001-2500/2231-Largest-Number-After-Digit-Swaps-by-Parity/cpp-2231/) | | | +| 2232 | [Minimize Result by Adding Parentheses to Expression](https://leetcode.com/problems/minimize-result-by-adding-parentheses-to-expression/) | [无] | [C++](2001-2500/2232-Minimize-Result-by-Adding-Parentheses-to-Expression/cpp-2232/) | | | +| 2233 | [Maximum Product After K Increments](https://leetcode.com/problems/maximum-product-after-k-increments/) | [无] | [C++](2001-2500/2233-Maximum-Product-After-K-Increments/cpp-2233/) | | | +| 2234 | [Maximum Total Beauty of the Gardens](https://leetcode.com/problems/maximum-total-beauty-of-the-gardens/) | [无] | [C++](2001-2500/2234-Maximum-Total-Beauty-of-the-Gardens/cpp-2234/) | | | +| 2235 | [Add Two Integers](https://leetcode.com/problems/add-two-integers/) | [无] | [C++](2001-2500/2235-Add-Two-Integers/cpp-2235/) | | | +| 2236 | [Root Equals Sum of Children](https://leetcode.com/problems/root-equals-sum-of-children/) | [无] | [C++](2001-2500/2236-Root-Equals-Sum-of-Children/cpp-2236/) | | | +| 2237 | [Count Positions on Street With Required Brightness](https://leetcode.com/problems/count-positions-on-street-with-required-brightness/) | [无] | [C++](2001-2500/2237-Count-Positions-on-Street-With-Required-Brightness/cpp-2237/) | | | +| 2238 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 2239 | [Find Closest Number to Zero](https://leetcode.com/problems/find-closest-number-to-zero/) | [无] | [C++](2001-2500/2239-Find-Closest-Number-to-Zero/cpp-2239/) | | | +| 2240 | [Number of Ways to Buy Pens and Pencils](https://leetcode.com/problems/number-of-ways-to-buy-pens-and-pencils/) | [无] | [C++](2001-2500/2240-Number-of-Ways-to-Buy-Pens-and-Pencils/cpp-2240/) | | | +| 2241 | [Design an ATM Machine](https://leetcode.com/problems/design-an-atm-machine/) | [无] | [C++](2001-2500/2241-Design-an-ATM-Machine/cpp-2241/) | | | +| 2242 | [Maximum Score of a Node Sequence](https://leetcode.com/problems/maximum-score-of-a-node-sequence/) | [无] | [C++](2001-2500/2242-Maximum-Score-of-a-Node-Sequence/cpp-2242/) | | | +| 2243 | [Calculate Digit Sum of a String](https://leetcode.com/problems/calculate-digit-sum-of-a-string/) | [无] | [C++](2001-2500/2243-Calculate-Digit-Sum-of-a-String/cpp-2243/) | | | +| 2244 | [Minimum Rounds to Complete All Tasks](https://leetcode.com/problems/minimum-rounds-to-complete-all-tasks/) | [无] | [C++](2001-2500/2244-Minimum-Rounds-to-Complete-All-Tasks/cpp-2244/) | | | +| 2245 | [Maximum Trailing Zeros in a Cornered Path](https://leetcode.com/problems/maximum-trailing-zeros-in-a-cornered-path/) | [无] | [C++](2001-2500/2245-Maximum-Trailing-Zeros-in-a-Cornered-Path/cpp-2245/) | | | +| 2246 | [Longest Path With Different Adjacent Characters](https://leetcode.com/problems/longest-path-with-different-adjacent-characters/) | [无] | [C++](2001-2500/2246-Longest-Path-With-Different-Adjacent-Characters/cpp-2246/) | | | +| 2247 | [Maximum Cost of Trip With K Highways](https://leetcode.com/problems/maximum-cost-of-trip-with-k-highways/) | [无] | [C++](2001-2500/2247-Maximum-Cost-of-Trip-With-K-Highways/cpp-2247/) | | | +| 2248 | [Intersection of Multiple Arrays](https://leetcode.com/problems/intersection-of-multiple-arrays/) | [无] | [C++](2001-2500/2248-Intersection-of-Multiple-Arrays/cpp-2248/) | | | +| 2249 | [Count Lattice Points Inside a Circle](https://leetcode.com/problems/count-lattice-points-inside-a-circle/) | [无] | [C++](2001-2500/2249-Count-Lattice-Points-Inside-a-Circle/cpp-2249/) | | | +| 2250 | [Count Number of Rectangles Containing Each Point](https://leetcode.com/problems/count-number-of-rectangles-containing-each-point/) | [无] | [C++](2001-2500/2250-Count-Number-of-Rectangles-Containing-Each-Point/cpp-2250/) | | | +| 2251 | [Number of Flowers in Full Bloom](https://leetcode.com/problems/number-of-flowers-in-full-bloom/) | [无] | [C++](2001-2500/2251-Number-of-Flowers-in-Full-Bloom/cpp-2251/) | | | +| 2252 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 2253 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 2254 | [Design Video Sharing Platform](https://leetcode.com/problems/design-video-sharing-platform/) | [无] | [C++](2001-2500/2254-Design-Video-Sharing-Platform/cpp-2254/) | | | +| 2255 | [Count Prefixes of a Given String](https://leetcode.com/problems/count-prefixes-of-a-given-string/) | [无] | [C++](2001-2500/2255-Count-Prefixes-of-a-Given-String/cpp-2255/) | | | +| 2256 | [Minimum Average Difference](https://leetcode.com/problems/minimum-average-difference/) | [无] | [C++](2001-2500/2256-Minimum-Average-Difference/cpp-2256/) | | | +| 2257 | [Count Unguarded Cells in the Grid](https://leetcode.com/problems/count-unguarded-cells-in-the-grid/) | [无] | [C++](2001-2500/2257-Count-Unguarded-Cells-in-the-Grid/cpp-2257/) | | | +| 2258 | [Escape the Spreading Fire](https://leetcode.com/problems/escape-the-spreading-fire/) | [无] | [C++](2001-2500/2258-Escape-the-Spreading-Fire/cpp-2258/) | | | +| 2259 | [Remove Digit From Number to Maximize Result](https://leetcode.com/problems/remove-digit-from-number-to-maximize-result/) | [无] | [C++](2001-2500/2259-Remove-Digit-From-Number-to-Maximize-Result/cpp-2259/) | | | +| 2260 | [Minimum Consecutive Cards to Pick Up](https://leetcode.com/problems/minimum-consecutive-cards-to-pick-up/) | [无] | [C++](2001-2500/2260-Minimum-Consecutive-Cards-to-Pick-Up/cpp-2260/) | | | +| 2261 | [K Divisible Elements Subarrays](https://leetcode.com/problems/k-divisible-elements-subarrays/) | [无] | [C++](2001-2500/2261-K-Divisible-Elements-Subarrays/cpp-2261/) | | | +| 2262 | [Total Appeal of A String](https://leetcode.com/problems/total-appeal-of-a-string/) | [无] | [C++](2001-2500/2262-Total-Appeal-of-A-String/cpp-2262/) | | | +| 2263 | [Make Array Non-decreasing or Non-increasing](https://leetcode.com/problems/make-array-non-decreasing-or-non-increasing/) | [无] | [C++](2001-2500/2263-Make-Array-Non-decreasing-or-Non-increasing/cpp-2263/) | | | +| 2264 | [Largest 3-Same-Digit Number in String](https://leetcode.com/problems/largest-3-same-digit-number-in-string/) | [无] | [C++](2001-2500/2264-Largest-3-Same-Digit-Number-in-String/cpp-2264/) | | | +| 2265 | [Count Nodes Equal to Average of Subtree](https://leetcode.com/problems/count-nodes-equal-to-average-of-subtree/) | [无] | [C++](2001-2500/2265-Count-Nodes-Equal-to-Average-of-Subtree/cpp-2265/) | | | +| 2266 | [Count Number of Texts](https://leetcode.com/problems/count-number-of-texts/) | [无] | [C++](2001-2500/2266-Count-Number-of-Texts/cpp-2266/) | | | +| 2267 | [Check if There Is a Valid Parentheses String Path](https://leetcode.com/problems/check-if-there-is-a-valid-parentheses-string-path/) | [无] | [C++](2001-2500/2267-Check-if-There-Is-a-Valid-Parentheses-String-Path/cpp-2267/) | | | +| 2268 | [Minimum Number of Keypresses](https://leetcode.com/problems/minimum-number-of-keypresses/) | [无] | [C++](2001-2500/2268-Minimum-Number-of-Keypresses/cpp-2268/) | | | +| 2269 | [Find the K-Beauty of a Number](https://leetcode.com/problems/find-the-k-beauty-of-a-number/) | [无] | [C++](2001-2500/2269-Find-the-K-Beauty-of-a-Number/cpp-2269/) | | | +| 2270 | [Number of Ways to Split Array](https://leetcode.com/problems/number-of-ways-to-split-array/) | [无] | [C++](2001-2500/2270-Number-of-Ways-to-Split-Array/cpp-2270/) | | | +| 2271 | [Maximum White Tiles Covered by a Carpet](https://leetcode.com/problems/maximum-white-tiles-covered-by-a-carpet/) | [无] | [C++](2001-2500/2271-Maximum-White-Tiles-Covered-by-a-Carpet/cpp-2271/) | | | +| 2272 | | [Substring With Largest Variance](https://leetcode.com/problems/substring-with-largest-variance/description/) | [无] | [C++](2001-2500/2272-Substring-With-Largest-Variance/cpp-2272/) | | +| 2273 | [Find Resultant Array After Removing Anagrams](https://leetcode.com/problems/find-resultant-array-after-removing-anagrams/) | [无] | [C++](2001-2500/2273-Find-Resultant-Array-After-Removing-Anagrams/cpp-2273/) | | | +| 2274 | [Maximum Consecutive Floors Without Special Floors](https://leetcode.com/problems/maximum-consecutive-floors-without-special-floors/) | [无] | [C++](2001-2500/2274-Maximum-Consecutive-Floors-Without-Special-Floors/cpp-2274/) | | | +| 2275 | [Largest Combination With Bitwise AND Greater Than Zero](https://leetcode.com/problems/largest-combination-with-bitwise-and-greater-than-zero/) | [无] | [C++](2001-2500/2275-Largest-Combination-With-Bitwise-AND-Greater-Than-Zero/cpp-2275/) | | | +| 2276 | [Count Integers in Intervals](https://leetcode.com/problems/count-integers-in-intervals/) | [无] | [C++](2001-2500/2276-Count-Integers-in-Intervals/cpp-2276/) | | | +| 2277 | [Closest Node to Path in Tree](https://leetcode.com/problems/closest-node-to-path-in-tree/) | [无] | [C++](2001-2500/2277-Closest-Node-to-Path-in-Tree/cpp-2277/) | | | +| 2278 | [Percentage of Letter in String](https://leetcode.com/problems/percentage-of-letter-in-string/) | [无] | [C++](2001-2500/2278-Percentage-of-Letter-in-String/cpp-2278/) | | | +| 2279 | [Maximum Bags With Full Capacity of Rocks](https://leetcode.com/problems/maximum-bags-with-full-capacity-of-rocks/) | [无] | [C++](2001-2500/2279-Maximum-Bags-With-Full-Capacity-of-Rocks/cpp-2279/) | | | +| 2280 | [Minimum Lines to Represent a Line Chart](https://leetcode.com/problems/minimum-lines-to-represent-a-line-chart/) | [无] | [C++](2001-2500/2280-Minimum-Lines-to-Represent-a-Line-Chart/cpp-2280/) | | | +| 2281 | [Sum of Total Strength of Wizards](https://leetcode.com/problems/sum-of-total-strength-of-wizards/) | [无] | [C++](2001-2500/2281-Sum-of-Total-Strength-of-Wizards/cpp-2281/) | | | +| | | | | | | +| 2283 | [Check if Number Has Equal Digit Count and Digit Value](https://leetcode.com/problems/check-if-number-has-equal-digit-count-and-digit-value/) | [无] | [C++](2001-2500/2283-Check-if-Number-Has-Equal-Digit-Count-and-Digit-Value/cpp-2283/) | | | +| 2284 | [Sender With Largest Word Count](https://leetcode.com/problems/sender-with-largest-word-count/) | [无] | [C++](2001-2500/2284-Sender-With-Largest-Word-Count/cpp-2284/) | | | +| 2285 | [Maximum Total Importance of Roads](https://leetcode.com/problems/maximum-total-importance-of-roads/) | [无] | [C++](2001-2500/2285-Maximum-Total-Importance-of-Roads/cpp-2285/) | | | +| 2286 | [Booking Concert Tickets in Groups](https://leetcode.com/problems/booking-concert-tickets-in-groups/) | [无] | [C++](2001-2500/2286-Booking-Concert-Tickets-in-Groups/cpp-2286/) | | | +| 2287 | [Rearrange Characters to Make Target String](https://leetcode.com/problems/rearrange-characters-to-make-target-string/) | [无] | [C++](2001-2500/2287-Rearrange-Characters-to-Make-Target-String/cpp-2287/) | | | +| 2288 | [Apply Discount to Prices](https://leetcode.com/problems/apply-discount-to-prices/) | [无] | [C++](2001-2500/2288-Apply-Discount-to-Prices/cpp-2288/) | | | +| 2289 | [Steps to Make Array Non-decreasing](https://leetcode.com/problems/steps-to-make-array-non-decreasing/) | [无]
[缺:用 C++ STL list] | [C++](2001-2500/2289-Steps-to-Make-Array-Non-decreasing/cpp-2289/) | | | +| 2290 | [Minimum Obstacle Removal to Reach Corner](https://leetcode.com/problems/minimum-obstacle-removal-to-reach-corner/) | [无] | [C++](2001-2500/2290-Minimum-Obstacle-Removal-to-Reach-Corner/cpp-2290/) | | | +| 2291 | [Maximum Profit From Trading Stocks](https://leetcode.com/problems/maximum-profit-from-trading-stocks/) | [无] | [C++](2001-2500/2291-Maximum-Profit-From-Trading-Stocks/cpp-2291/) | | | +| 2292 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 2293 | [Min Max Game](https://leetcode.com/problems/min-max-game/) | [无] | [C++](2001-2500/2293-Min-Max-Game/cpp-2293/) | | | +| 2294 | [Partition Array Such That Maximum Difference Is K](https://leetcode.com/problems/partition-array-such-that-maximum-difference-is-k/) | [无] | [C++](2001-2500/2294-Partition-Array-Such-That-Maximum-Difference-Is-K/cpp-2294/) | | | +| 2295 | [Replace Elements in an Array](https://leetcode.com/problems/replace-elements-in-an-array/) | [无] | [C++](2001-2500/2295-Replace-Elements-in-an-Array/cpp-2295/) | | | +| 2296 | [Design a Text Editor](https://leetcode.com/problems/design-a-text-editor/) | [无] | [C++](2001-2500/2296-Design-a-Text-Editor/cpp-2296/) | | | +| 2297 | [Jump Game IX](https://leetcode.com/problems/jump-game-ix/) | [无] | [C++](2001-2500/2297-Jump-Game-IX/cpp-2297/) | | | +| 2298 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 2299 | [Strong Password Checker II](https://leetcode.com/problems/strong-password-checker-ii/) | [无] | [C++](2001-2500/2299-Strong-Password-Checker-II/cpp-2299/) | | | +| 2300 | [Successful Pairs of Spells and Potions](https://leetcode.com/problems/successful-pairs-of-spells-and-potions/) | [无] | [C++](2001-2500/2300-Successful-Pairs-of-Spells-and-Potions/cpp-2300/) | | | +| 2301 | [Match Substring After Replacement](https://leetcode.com/problems/match-substring-after-replacement/) | [无] | [C++](2001-2500/2301-Match-Substring-After-Replacement/cpp-2301/) | | | +| 2302 | [Count Subarrays With Score Less Than K](https://leetcode.com/problems/count-subarrays-with-score-less-than-k/) | [无] | [C++](2001-2500/2302-Count-Subarrays-With-Score-Less-Than-K/cpp-2302/) | | | +| 2303 | [Calculate Amount Paid in Taxes](https://leetcode.com/problems/calculate-amount-paid-in-taxes/) | [无] | [C++](2001-2500/2303-Calculate-Amount-Paid-in-Taxes/cpp-2303/) | | | +| 2304 | [Minimum Path Cost in a Grid](https://leetcode.com/problems/minimum-path-cost-in-a-grid/) | [无] | [C++](2001-2500/2304-Minimum-Path-Cost-in-a-Grid/cpp-2304/) | | | +| 2305 | [Fair Distribution of Cookies](https://leetcode.com/problems/fair-distribution-of-cookies/) | [无] | [C++](2001-2500/2305-Fair-Distribution-of-Cookies/cpp-2305/) | | | +| 2306 | [Naming a Company](https://leetcode.com/problems/naming-a-company/) | [无] | [C++](2001-2500/2306-Naming-a-Company/cpp-2306/) | | | +| | | | | | | +| 2308 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 2309 | [Greatest English Letter in Upper and Lower Case](https://leetcode.com/problems/greatest-english-letter-in-upper-and-lower-case/) | [无] | [C++](2001-2500/2309-Greatest-English-Letter-in-Upper-and-Lower-Case/cpp-2309/) | | | +| 2310 | [Sum of Numbers With Units Digit K](https://leetcode.com/problems/sum-of-numbers-with-units-digit-k/) | [无] | [C++](2001-2500/2310-Sum-of-Numbers-With-Units-Digit-K/cpp-2310/) | | | +| | | | | | | +| 2312 | [Selling Pieces of Wood](https://leetcode.com/problems/selling-pieces-of-wood/) | [无] | [C++](2001-2500/2312-Selling-Pieces-of-Wood/cpp-2312/) | | | +| 2313 | [Minimum Flips in Binary Tree to Get Result](https://leetcode.com/problems/minimum-flips-in-binary-tree-to-get-result/) | [无] | [C++](2001-2500/2313-Minimum-Flips-in-Binary-Tree-to-Get-Result/cpp-2313/) | | | +| 2314 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 2315 | [Count Asterisks](https://leetcode.com/problems/count-asterisks/) | [无] | [C++](2001-2500/2315-Count-Asterisks/cpp-2315/) | | | +| 2316 | [Count Unreachable Pairs of Nodes in an Undirected Graph](https://leetcode.com/problems/count-unreachable-pairs-of-nodes-in-an-undirected-graph/) | [无] | [C++](2001-2500/2316-Count-Unreachable-Pairs-of-Nodes-in-an-Undirected-Graph/cpp-2316/) | | | +| 2317 | [Maximum XOR After Operations](https://leetcode.com/problems/maximum-xor-after-operations/) | [无] | [C++](2001-2500/2317-Maximum-XOR-After-Operations/cpp-2317/) | | | +| 2318 | [Number of Distinct Roll Sequences](https://leetcode.com/problems/number-of-distinct-roll-sequences/) | [无] | [C++](2001-2500/2318-Number-of-Distinct-Roll-Sequences/cpp-2318/) | | | +| 2319 | [Check if Matrix Is X-Matrix](https://leetcode.com/problems/check-if-matrix-is-x-matrix/) | [无] | [C++](2001-2500/2319-Check-if-Matrix-Is-X-Matrix/cpp-2319/) | | | +| 2320 | [Count Number of Ways to Place Houses](https://leetcode.com/problems/count-number-of-ways-to-place-houses/) | [无] | [C++](2001-2500/2320-Count-Number-of-Ways-to-Place-Houses/cpp-2320/) | | | +| 2321 | [Maximum Score Of Spliced Array](https://leetcode.com/problems/maximum-score-of-spliced-array/) | [无] | [C++](2001-2500/2321-Maximum-Score-Of-Spliced-Array/cpp-2321/) | | | +| 2322 | [Minimum Score After Removals on a Tree](https://leetcode.com/problems/minimum-score-after-removals-on-a-tree/) | [无] | [C++](2001-2500/2322-Minimum-Score-After-Removals-on-a-Tree/cpp-2322/) | | | +| 2323 | [Find Minimum Time to Finish All Jobs II](https://leetcode.com/problems/find-minimum-time-to-finish-all-jobs-ii/) | [无] | [C++](2001-2500/2323-Find-Minimum-Time-to-Finish-All-Jobs-II/cpp-2323/) | | | +| 2324 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 2325 | [Decode the Message](https://leetcode.com/problems/decode-the-message/) | [无] | [C++](2001-2500/2325-Decode-the-Message/cpp-2325/) | | | +| 2326 | [Spiral Matrix IV](https://leetcode.com/problems/spiral-matrix-iv/) | [无] | [C++](2001-2500/2326-Spiral-Matrix-IV/cpp-2326/) | | | +| 2327 | [Number of People Aware of a Secret](https://leetcode.com/problems/number-of-people-aware-of-a-secret/) | [无] | [C++](2001-2500/2327-Number-of-People-Aware-of-a-Secret/cpp-2327/) | | | +| 2328 | [Number of Increasing Paths in a Grid](https://leetcode.com/problems/number-of-increasing-paths-in-a-grid/) | [无] | [C++](2001-2500/2328-Number-of-Increasing-Paths-in-a-Grid/cpp-2328/) | | | +| 2329 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 2330 | [Valid Palindrome IV](https://leetcode.com/problems/valid-palindrome-iv/) | [无] | [C++](2001-2500/2330-Valid-Palindrome-IV/cpp-2330/) | | | +| 2331 | [Evaluate Boolean Binary Tree](https://leetcode.com/problems/evaluate-boolean-binary-tree/) | [无] | [C++](2001-2500/2331-Evaluate-Boolean-Binary-Tree/cpp-2331/) | | | +| 2332 | [The Latest Time to Catch a Bus](https://leetcode.com/problems/the-latest-time-to-catch-a-bus/) | [无] | [C++](2001-2500/2332-The-Latest-Time-to-Catch-a-Bus/cpp-2332/) | | | +| 2333 | [Minimum Sum of Squared Difference](https://leetcode.com/problems/minimum-sum-of-squared-difference/) | [无] | [C++](2001-2500/2333-Minimum-Sum-of-Squared-Difference/cpp-2333/) | | | +| 2334 | [Subarray With Elements Greater Than Varying Threshold](https://leetcode.com/problems/subarray-with-elements-greater-than-varying-threshold/) | [无] | [C++](2001-2500/2334-Subarray-With-Elements-Greater-Than-Varying-Threshold/cpp-2334/) | | | +| 2335 | [Minimum Amount of Time to Fill Cups](https://leetcode.com/problems/minimum-amount-of-time-to-fill-cups/) | [无] | [C++](2001-2500/2335-Minimum-Amount-of-Time-to-Fill-Cups/cpp-2335/) | | | +| 2336 | [Smallest Number in Infinite Set](https://leetcode.com/problems/smallest-number-in-infinite-set/) | [无] | [C++](2001-2500/2336-Smallest-Number-in-Infinite-Set/cpp-2336/) | | | +| 2337 | [Move Pieces to Obtain a String](https://leetcode.com/problems/move-pieces-to-obtain-a-string/) | [无] | [C++](2001-2500/2337-Move-Pieces-to-Obtain-a-String/cpp-2337/) | | | +| 2338 | [Count the Number of Ideal Arrays](https://leetcode.com/problems/count-the-number-of-ideal-arrays/) | [无] | [C++](2001-2500/2338-Count-the-Number-of-Ideal-Arrays/cpp-2338/) | | | +| 2339 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 2340 | [Minimum Adjacent Swaps to Make a Valid Array](https://leetcode.com/problems/minimum-adjacent-swaps-to-make-a-valid-array/) | [无] | [C++](2001-2500/2340-Minimum-Adjacent-Swaps-to-Make-a-Valid-Array/cpp-2340/) | | | +| 2341 | [Maximum Number of Pairs in Array](https://leetcode.com/problems/maximum-number-of-pairs-in-array/) | [无] | [C++](2001-2500/2341-Maximum-Number-of-Pairs-in-Array/cpp-2341/) | | | +| 2342 | [Max Sum of a Pair With Equal Sum of Digits](https://leetcode.com/problems/max-sum-of-a-pair-with-equal-sum-of-digits/) | [无] | [C++](2001-2500/2342-Max-Sum-of-a-Pair-With-Equal-Sum-of-Digits/cpp-2342/) | | | +| 2343 | [Query Kth Smallest Trimmed Number](https://leetcode.com/problems/query-kth-smallest-trimmed-number/) | [无] | [C++](2001-2500/2343-Query-Kth-Smallest-Trimmed-Number/cpp-2343/) | | | +| 2344 | [Minimum Deletions to Make Array Divisible](https://leetcode.com/problems/minimum-deletions-to-make-array-divisible/) | [无] | [C++](2001-2500/2344-Minimum-Deletions-to-Make-Array-Divisible/cpp-2344/) | | | +| 2345 | [Finding the Number of Visible Mountains](https://leetcode.com/problems/finding-the-number-of-visible-mountains/) | [无] | [C++](2001-2500/2345-Finding-the-Number-of-Visible-Mountains/cpp-2345/) | | | +| 2346 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 2347 | [Best Poker Hand](https://leetcode.com/problems/best-poker-hand/) | [无] | [C++](2001-2500/2347-Best-Poker-Hand/cpp-2347/) | | | +| 2348 | [Number of Zero-Filled Subarrays](https://leetcode.com/problems/number-of-zero-filled-subarrays/) | [无] | [C++](2001-2500/2348-Number-of-Zero-Filled-Subarrays/cpp-2348/) | | | +| 2349 | [Design a Number Container System](https://leetcode.com/problems/design-a-number-container-system/) | [无] | [C++](2001-2500/2349-Design-a-Number-Container-System/cpp-2349/) | | | +| 2350 | [Shortest Impossible Sequence of Rolls](https://leetcode.com/problems/shortest-impossible-sequence-of-rolls/) | [无] | [C++](2001-2500/2350-Shortest-Impossible-Sequence-of-Rolls/cpp-2350/) | | | +| 2351 | [First Letter to Appear Twice](https://leetcode.com/problems/first-letter-to-appear-twice/) | [无] | [C++](2001-2500/2351-First-Letter-to-Appear-Twice/cpp-2351/) | | | +| 2352 | [Equal Row and Column Pairs](https://leetcode.com/problems/equal-row-and-column-pairs/) | [无] | [C++](2001-2500/2352-Equal-Row-and-Column-Pairs/cpp-2352/) | | | +| 2353 | [Design a Food Rating System](https://leetcode.com/problems/design-a-food-rating-system/) | [无] | [C++](2001-2500/2353-Design-a-Food-Rating-System/cpp-2353/) | | | +| 2354 | [Number of Excellent Pairs](https://leetcode.com/problems/number-of-excellent-pairs/) | [无] | [C++](2001-2500/2354-Number-of-Excellent-Pairs/cpp-2354/) | | | +| | | | | | | +| 2356 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 2357 | [Make Array Zero by Subtracting Equal Amounts](https://leetcode.com/problems/make-array-zero-by-subtracting-equal-amounts/) | [无] | [C++](2001-2500/2357-Make-Array-Zero-by-Subtracting-Equal-Amounts/cpp-2357/) | | | +| 2358 | [Maximum Number of Groups Entering a Competition](https://leetcode.com/problems/maximum-number-of-groups-entering-a-competition/) | [无] | [C++](2001-2500/2358-Maximum-Number-of-Groups-Entering-a-Competition/cpp-2358/) | | | +| 2359 | [Find Closest Node to Given Two Nodes](https://leetcode.com/problems/find-closest-node-to-given-two-nodes/) | [无] | [C++](2001-2500/2359-Find-Closest-Node-to-Given-Two-Nodes/cpp-2359/) | | | +| 2360 | [Longest Cycle in a Graph](https://leetcode.com/problems/longest-cycle-in-a-graph/) | [无] | [C++](2001-2500/2360-Longest-Cycle-in-a-Graph/cpp-2360/) | | | +| 2361 | [Minimum Costs Using the Train Line](https://leetcode.com/problems/minimum-costs-using-the-train-line/) | [无] | [C++](2001-2500/2361-Minimum-Costs-Using-the-Train-Line/cpp-2361/) | | | +| 2362 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 2363 | [Merge Similar Items](https://leetcode.com/problems/merge-similar-items/) | [无] | [C++](2001-2500/2363-Merge-Similar-Items/cpp-2363/) | | | +| 2364 | [Count Number of Bad Pairs](https://leetcode.com/problems/count-number-of-bad-pairs/) | [无] | [C++](2001-2500/2364-Count-Number-of-Bad-Pairs/cpp-2364/) | | | +| 2365 | [Task Scheduler II](https://leetcode.com/problems/task-scheduler-ii/) | [无] | [C++](2001-2500/2365-Task-Scheduler-II/cpp-2365/) | | | +| 2366 | [Minimum Replacements to Sort the Array](https://leetcode.com/problems/minimum-replacements-to-sort-the-array/) | [无] | [C++](2001-2500/2366-Minimum-Replacements-to-Sort-the-Array/cpp-2366/) | | | +| 2367 | [Number of Arithmetic Triplets](https://leetcode.com/problems/number-of-arithmetic-triplets/) | [无] | [C++](2001-2500/2367-Number-of-Arithmetic-Triplets/cpp-2367/) | | | +| 2368 | [Reachable Nodes With Restrictions](https://leetcode.com/problems/reachable-nodes-with-restrictions/) | [无] | [C++](2001-2500/2368-Reachable-Nodes-With-Restrictions/cpp-2368/) | | | +| 2369 | [Check if There is a Valid Partition For The Array](https://leetcode.com/problems/check-if-there-is-a-valid-partition-for-the-array/) | [无] | [C++](2001-2500/2369-Check-if-There-is-a-Valid-Partition-For-The-Array/cpp-2369/) | | | +| 2370 | [Longest Ideal Subsequence](https://leetcode.com/problems/longest-ideal-subsequence/) | [无] | [C++](2001-2500/2370-Longest-Ideal-Subsequence/cpp-2370/) | | | +| | | | | | | +| 2372 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 2373 | [Largest Local Values in a Matrix](https://leetcode.com/problems/largest-local-values-in-a-matrix/) | [无] | [C++](2001-2500/2373-Largest-Local-Values-in-a-Matrix/cpp-2373/) | | | +| 2374 | [Node With Highest Edge Score](https://leetcode.com/problems/node-with-highest-edge-score/) | [无] | [C++](2001-2500/2374-Node-With-Highest-Edge-Score/cpp-2374/) | | | +| 2375 | [Construct Smallest Number From DI String](https://leetcode.com/problems/construct-smallest-number-from-di-string/) | [无] | [C++](2001-2500/2375-Construct-Smallest-Number-From-DI-String/cpp-2375/) | | | +| 2376 | [Count Special Integers](https://leetcode.com/problems/count-special-integers/) | [无] | [C++](2001-2500/2376-Count-Special-Integers/cpp-2376/) | | | +| 2377 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 2378 | [Choose Edges to Maximize Score in a Tree](https://leetcode.com/problems/choose-edges-to-maximize-score-in-a-tree/) | [无] | [C++](2001-2500/2378-Choose-Edges-to-Maximize-Score-in-a-Tree/cpp-2378/) | | | +| 2379 | [Minimum Recolors to Get K Consecutive Black Blocks](https://leetcode.com/problems/minimum-recolors-to-get-k-consecutive-black-blocks/) | [无] | [C++](2001-2500/2379-Minimum-Recolors-to-Get-K-Consecutive-Black-Blocks/cpp-2379/) | | | +| 2380 | [Time Needed to Rearrange a Binary String](https://leetcode.com/problems/time-needed-to-rearrange-a-binary-string/) | [无] | [C++](2001-2500/2380-Time-Needed-to-Rearrange-a-Binary-String/cpp-2380/) | | | +| 2381 | [Shifting Letters II](https://leetcode.com/problems/shifting-letters-ii/) | [无] | [C++](2001-2500/2381-Shifting-Letters-II/cpp-2381/) | | | +| 2382 | [Maximum Segment Sum After Removals](https://leetcode.com/problems/maximum-segment-sum-after-removals/) | [无] | [C++](2001-2500/2382-Maximum-Segment-Sum-After-Removals/cpp-2382/) | | | +| 2383 | [Minimum Hours of Training to Win a Competition](https://leetcode.com/problems/minimum-hours-of-training-to-win-a-competition/) | [无] | [C++](2001-2500/2383-Minimum-Hours-of-Training-to-Win-a-Competition/cpp-2383/) | | | +| 2384 | [Largest Palindromic Number](https://leetcode.com/problems/largest-palindromic-number/) | [无] | [C++](2001-2500/2384-Largest-Palindromic-Number/cpp-2384/) | | | +| 2385 | [Amount of Time for Binary Tree to Be Infected](https://leetcode.com/problems/amount-of-time-for-binary-tree-to-be-infected/) | [无] | [C++](2001-2500/2385-Amount-of-Time-for-Binary-Tree-to-Be-Infected/cpp-2385/) | | | +| | | | | | | +| 2387 | [Median of a Row Wise Sorted Matrix](https://leetcode.com/problems/median-of-a-row-wise-sorted-matrix/) | [无] | [C++](2001-2500/2387-Median-of-a-Row-Wise-Sorted-Matrix/cpp-2387/) | | | +| 2388 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 2389 | [Longest Subsequence With Limited Sum](https://leetcode.com/problems/longest-subsequence-with-limited-sum/) | [无] | [C++](2001-2500/2389-Longest-Subsequence-With-Limited-Sum/cpp-2389/) | | | +| 2390 | [Removing Stars From a String](https://leetcode.com/problems/removing-stars-from-a-string/) | [无] | [C++](2001-2500/2390-Removing-Stars-From-a-String/cpp-2390/) | | | +| 2391 | [Minimum Amount of Time to Collect Garbage](https://leetcode.com/problems/minimum-amount-of-time-to-collect-garbage/) | [无] | [C++](2001-2500/2391-Minimum-Amount-of-Time-to-Collect-Garbage/cpp-2391/) | | | +| 2392 | [Build a Matrix With Conditions](https://leetcode.com/problems/build-a-matrix-with-conditions/) | [无] | [C++](2001-2500/2392-Build-a-Matrix-With-Conditions/cpp-2392/) | | | +| 2393 | [Count Strictly Increasing Subarrays](https://leetcode.com/problems/count-strictly-increasing-subarrays/) | [无] | [C++](2001-2500/2393-Count-Strictly-Increasing-Subarrays/cpp-2393/) | | | +| 2394 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 2395 | [Find Subarrays With Equal Sum](https://leetcode.com/problems/find-subarrays-with-equal-sum/) | [无] | [C++](2001-2500/2395-Find-Subarrays-With-Equal-Sum/cpp-2395/) | | | +| 2396 | [Strictly Palindromic Number](https://leetcode.com/problems/strictly-palindromic-number/) | [无] | [C++](2001-2500/2396-Strictly-Palindromic-Number/cpp-2396/) | | | +| 2397 | [Maximum Rows Covered by Columns](https://leetcode.com/problems/maximum-rows-covered-by-columns/) | [无] | [C++](2001-2500/2397-Maximum-Rows-Covered-by-Columns/cpp-2397/) | | | +| 2398 | [Maximum Number of Robots Within Budget](https://leetcode.com/problems/maximum-number-of-robots-within-budget/) | [无][缺:滑动窗口] | [C++](2001-2500/2398-Maximum-Number-of-Robots-Within-Budget/cpp-2398/) | | | +| 2399 | [Check Distances Between Same Letters](https://leetcode.com/problems/check-distances-between-same-letters/) | [无] | [C++](2001-2500/2399-Check-Distances-Between-Same-Letters/cpp-2399/) | | | +| 2400 | [Number of Ways to Reach a Position After Exactly k Steps](https://leetcode.com/problems/number-of-ways-to-reach-a-position-after-exactly-k-steps/) | [无][缺:数学解] | [C++](2001-2500/2400-Number-of-Ways-to-Reach-a-Position-After-Exactly-k-Steps/cpp-2400/) | | | +| 2401 | [Longest Nice Subarray](https://leetcode.com/problems/longest-nice-subarray/) | [无] | [C++](2001-2500/2401-Longest-Nice-Subarray/cpp-2401/) | | | +| 2402 | [Meeting Rooms III](https://leetcode.com/problems/meeting-rooms-iii/) | [无] | [C++](2001-2500/2402-Meeting-Rooms-III/cpp-2402/) | | | +| 2403 | [Minimum Time to Kill All Monsters](https://leetcode.com/problems/minimum-time-to-kill-all-monsters/) | [无] | [C++](2001-2500/2403-Minimum-Time-to-Kill-All-Monsters/cpp-2403/) | | | +| 2404 | [Most Frequent Even Element](https://leetcode.com/problems/most-frequent-even-element/) | [无] | [C++](2001-2500/2404-Most-Frequent-Even-Element/cpp-2404/) | | | +| 2405 | [Optimal Partition of String](https://leetcode.com/problems/optimal-partition-of-string/) | [无] | [C++](2001-2500/2405-Optimal-Partition-of-String/cpp-2405/) | | | +| 2406 | [Divide Intervals Into Minimum Number of Groups](https://leetcode.com/problems/divide-intervals-into-minimum-number-of-groups/) | [无] | [C++](2001-2500/2406-Divide-Intervals-Into-Minimum-Number-of-Groups/cpp-2406/) | | | +| 2407 | [Longest Increasing Subsequence II](https://leetcode.com/problems/longest-increasing-subsequence-ii/) | [无] | [C++](2001-2500/2407-Longest-Increasing-Subsequence-II/cpp2407/) | | | +| 2408 | [Design SQL](https://leetcode.com/problems/design-sql/) | [无] | [C++](2001-2500/2408-Design-SQL/cpp2408/) | | | +| 2409 | [Count Days Spent Together](https://leetcode.com/problems/count-days-spent-together/) | [无] | [C++](2001-2500/2409-Count-Days-Spent-Together/cpp2409/) | | | +| 2410 | [Maximum Matching of Players With Trainers](https://leetcode.com/problems/maximum-matching-of-players-with-trainers/) | [无] | [C++](2001-2500/2410-Maximum-Matching-of-Players-With-Trainers/cpp2410/) | | | +| 2411 | [Smallest Subarrays With Maximum Bitwise OR](https://leetcode.com/problems/smallest-subarrays-with-maximum-bitwise-or/) | [无][缺:O(n) 算法] | [C++](2001-2500/2411-Smallest-Subarrays-With-Maximum-Bitwise-OR/cpp2411/) | | | +| 2412 | [Minimum Money Required Before Transactions](https://leetcode.com/problems/minimum-money-required-before-transactions/description/) | [无] [缺:不用 sort] | [C++](2001-2500/2412-Minimum-Money-Required-Before-Transactions/cpp-2412/) | | | +| 2413 | [Smallest Even Multiple](https://leetcode.com/problems/smallest-even-multiple/) | [无] | [C++](2001-2500/2413-Smallest-Even-Multiple/cpp-2413/) | | | +| 2414 | [Length of the Longest Alphabetical Continuous Substring](https://leetcode.com/problems/length-of-the-longest-alphabetical-continuous-substring/) | [无] | [C++](2001-2500/2414-Length-of-the-Longest-Alphabetical-Continuous-Substring/cpp-2414/) | | | +| 2415 | [Reverse Odd Levels of Binary Tree](https://leetcode.com/problems/reverse-odd-levels-of-binary-tree/) | [无] | [C++](2001-2500/2415-Reverse-Odd-Levels-of-Binary-Tree/cpp-2415/) | | | +| 2416 | [Sum of Prefix Scores of Strings](https://leetcode.com/problems/sum-of-prefix-scores-of-strings/) | [无] | [C++](2001-2500/2416-Sum-of-Prefix-Scores-of-Strings/cpp-2416/) | | | +| 2417 | [Closest Fair Integer](https://leetcode.com/problems/closest-fair-integer/) | [无] | [C++](2001-2500/2417-Closest-Fair-Integer/cpp-2417/) | | | +| 2418 | [Sort the People](https://leetcode.com/problems/sort-the-people/) | [无] | [C++](2001-2500/2418-Sort-the-People/cpp-2418/) | | | +| 2419 | [Longest Subarray With Maximum Bitwise AND](https://leetcode.com/problems/longest-subarray-with-maximum-bitwise-and/) | [无] | [C++](2001-2500/2419-Longest-Subarray-With-Maximum-Bitwise-AND/cpp-2419/) | | | +| 2420 | [Find All Good Indices](https://leetcode.com/problems/find-all-good-indices/) | [无] | [C++](2001-2500/2420-Find-All-Good-Indices/cpp-2420/) | | | +| 2421 | [Number of Good Paths](https://leetcode.com/problems/number-of-good-paths/) | [无] | [C++](2001-2500/2421-Number-of-Good-Paths/cpp-2421/) | | | +| 2422 | [Merge Operations to Turn Array Into a Palindrome](https://leetcode.com/problems/merge-operations-to-turn-array-into-a-palindrome/) | [无] | [C++](2001-2500/2422-Merge-Operations-to-Turn-Array-Into-a-Palindrome/cpp-2422/) | | | +| 2423 | [Remove Letter To Equalize Frequency](https://leetcode.com/problems/remove-letter-to-equalize-frequency/) | [无] | [C++](2001-2500/2423-Remove-Letter-To-Equalize-Frequency/cpp-2423/) | | | +| 2424 | [Longest Uploaded Prefix](https://leetcode.com/problems/longest-uploaded-prefix/) | [无] | [C++](2001-2500/2424-Longest-Uploaded-Prefix/cpp-2424/) | | | +| 2425 | [Bitwise XOR of All Pairings](https://leetcode.com/problems/bitwise-xor-of-all-pairings/) | [无] | [C++](2001-2500/2425-Bitwise-XOR-of-All-Pairings/cpp-2425/) | | | +| 2426 | [Number of Pairs Satisfying Inequality](https://leetcode.com/problems/number-of-pairs-satisfying-inequality/) | [无]
[缺:493 问题整理] | [C++](2001-2500/2426-Number-of-Pairs-Satisfying-Inequality/cpp-2426/) | | | +| 2427 | [Number of Common Factors](https://leetcode.com/problems/number-of-common-factors/) | [无] | [C++](2001-2500/2427-Number-of-Common-Factors/cpp-2427/) | | | +| 2428 | [Maximum Sum of an Hourglass](https://leetcode.com/problems/maximum-sum-of-an-hourglass/) | [无] | [C++](2001-2500/2428-Maximum-Sum-of-an-Hourglass/cpp-2428/) | | | +| 2429 | [Minimize XOR](https://leetcode.com/problems/minimize-xor/) | [无] | [C++](2001-2500/2429-Minimize-XOR/cpp-2429/) | | | +| 2430 | [Maximum Deletions on a String](https://leetcode.com/problems/maximum-deletions-on-a-string/) | [无] | [C++](2001-2500/2430-Maximum-Deletions-on-a-String/cpp-2430/) | | | +| 2431 | [Maximize Total Tastiness of Purchased Fruits](https://leetcode.com/problems/maximize-total-tastiness-of-purchased-fruits/) | [无] | [C++](2001-2500/2431-Maximize-Total-Tastiness-of-Purchased-Fruits/cpp-2431/) | | | +| 2432 | [The Employee That Worked on the Longest Task](https://leetcode.com/problems/the-employee-that-worked-on-the-longest-task/) | [无] | [C++](2001-2500/2432-The-Employee-That-Worked-on-the-Longest-Task/cpp-2432/) | | | +| 2433 | [Find The Original Array of Prefix Xor](https://leetcode.com/problems/find-the-original-array-of-prefix-xor/) | [无] | [C++](2001-2500/2433-Find-The-Original-Array-of-Prefix-Xor/cpp-2433/) | | | +| 2434 | [Using a Robot to Print the Lexicographically Smallest String](https://leetcode.com/problems/using-a-robot-to-print-the-lexicographically-smallest-string/) | [无] | [C++](2001-2500/2434-Using-a-Robot-to-Print-the-Lexicographically-Smallest-String/cpp-2434/) | | | +| 2435 | [Paths in Matrix Whose Sum Is Divisible by K](https://leetcode.com/problems/paths-in-matrix-whose-sum-is-divisible-by-k/) | [无] | [C++](2001-2500/2435-Paths-in-Matrix-Whose-Sum-Is-Divisible-by-K/cpp-2435/) | | | +| 2436 | [Minimum Split Into Subarrays With GCD Greater Than One](https://leetcode.com/problems/minimum-split-into-subarrays-with-gcd-greater-than-one/) | [无] | [C++](2001-2500/2436-Minimum-Split-Into-Subarrays-With-GCD-Greater-Than-One/cpp-2436/) | | | +| 2437 | [Number of Valid Clock Times](https://leetcode.com/problems/number-of-valid-clock-times/) | [无] | [C++](2001-2500/2437-Number-of-Valid-Clock-Times/cpp-2437/) | | | +| 2438 | [Range Product Queries of Powers](https://leetcode.com/problems/range-product-queries-of-powers/) | [无] | [C++](2001-2500/2438-Range-Product-Queries-of-Powers/cpp-2438/) | | | +| 2439 | [Minimize Maximum of Array](https://leetcode.com/problems/minimize-maximum-of-array/) | [无] | [C++](2001-2500/2439-Minimize-Maximum-of-Array/cpp-2439/) | | | +| 2440 | [Create Components With Same Value](https://leetcode.com/problems/create-components-with-same-value/) | [无] | [C++](2001-2500/2440-Create-Components-With-Same-Value/cpp-2440/) | | | +| 2441 | [Largest Positive Integer That Exists With Its Negative](https://leetcode.com/problems/largest-positive-integer-that-exists-with-its-negative/) | [无] | [C++](2001-2500/2441-Largest-Positive-Integer-That-Exists-With-Its-Negative/cpp-2441/) | | | +| 2442 | [Count Number of Distinct Integers After Reverse Operations](https://leetcode.com/problems/count-number-of-distinct-integers-after-reverse-operations/) | [无] | [C++](2001-2500/2442-Count-Number-of-Distinct-Integers-After-Reverse-Operations/cpp-2442/) | | | +| 2443 | [Sum of Number and Its Reverse](https://leetcode.com/problems/sum-of-number-and-its-reverse/) | [无] | [C++](2001-2500/2443-Sum-of-Number-and-Its-Reverse/cpp-2443/) | | | +| 2444 | [Count Subarrays With Fixed Bounds](https://leetcode.com/problems/count-subarrays-with-fixed-bounds/) | [无] | [C++](2001-2500/2444-Count-Subarrays-With-Fixed-Bounds/cpp-2444/) | | | +| 2445 | [Number of Nodes With Value One](https://leetcode.com/problems/number-of-nodes-with-value-one/) | [无] | [C++](2001-2500/2445-Number-of-Nodes-With-Value-One/cpp-2445/) | | | +| 2446 | [Determine if Two Events Have Conflict](https://leetcode.com/problems/determine-if-two-events-have-conflict/) | [无] | [C++](2001-2500/2446-Determine-if-Two-Events-Have-Conflict/cpp-2446/) | | | +| 2447 | [Number of Subarrays With GCD Equal to K](https://leetcode.com/problems/number-of-subarrays-with-gcd-equal-to-k/) | [无] | [C++](2001-2500/2447-Number-of-Subarrays-With-GCD-Equal-to-K/cpp-2447/) | | | +| 2448 | [Minimum Cost to Make Array Equal](https://leetcode.com/problems/minimum-cost-to-make-array-equal/) | [无] | [C++](2001-2500/2448-Minimum-Cost-to-Make-Array-Equal/cpp-2448/) | | | +| 2449 | [Minimum Number of Operations to Make Arrays Similar](https://leetcode.com/problems/minimum-number-of-operations-to-make-arrays-similar/) | [无] | [C++](2001-2500/2449-Minimum-Number-of-Operations-to-Make-Arrays-Similar/cpp-2449/) | | | +| 2450 | [Number of Distinct Binary Strings After Applying Operations](https://leetcode.com/problems/number-of-distinct-binary-strings-after-applying-operations/) | [无] | [C++](2001-2500/2450-Number-of-Distinct-Binary-Strings-After-Applying-Operations/cpp-2450/) | | | +| 2451 | [Odd String Difference](https://leetcode.com/problems/odd-string-difference/) | [无] | [C++](2001-2500/2451-Odd-String-Difference/cpp-2451/) | | | +| 2452 | [Words Within Two Edits of Dictionary](https://leetcode.com/problems/words-within-two-edits-of-dictionary/) | [无] | [C++](2001-2500/2452-Words-Within-Two-Edits-of-Dictionary/cpp-2452/) | | | +| 2453 | [Destroy Sequential Targets](https://leetcode.com/problems/destroy-sequential-targets/) | [无] | [C++](2001-2500/2453-Destroy-Sequential-Targets/cpp-2453/) | | | +| 2454 | [Next Greater Element IV](https://leetcode.com/problems/next-greater-element-iv/) | [无]
[缺:O(n) 解法] | [C++](2001-2500/2454-Next-Greater-Element-IV/cpp-2454/) | | | +| 2455 | [Average Value of Even Numbers That Are Divisible by Three](https://leetcode.com/problems/average-value-of-even-numbers-that-are-divisible-by-three/) | [无] | [C++](2001-2500/2455-Average-Value-of-Even-Numbers-That-Are-Divisible-by-Three/cpp-2455/) | | | +| 2456 | [Most Popular Video Creator](https://leetcode.com/problems/most-popular-video-creator/) | [无] | [C++](2001-2500/2456-Most-Popular-Video-Creator/cpp-2456/) | | | +| 2457 | [Minimum Addition to Make Integer Beautiful](https://leetcode.com/problems/minimum-addition-to-make-integer-beautiful/) | [无] | [C++](2001-2500/2457-Minimum-Addition-to-Make-Integer-Beautiful/cpp-2457/) | | | +| 2458 | [Height of Binary Tree After Subtree Removal Queries](https://leetcode.com/problems/height-of-binary-tree-after-subtree-removal-queries/) | [无] | [C++](2001-2500/2458-Height-of-Binary-Tree-After-Subtree-Removal-Queries/cpp-2458/) | | | +| 2459 | [Sort Array by Moving Items to Empty Space](https://leetcode.com/problems/sort-array-by-moving-items-to-empty-space/description/) | [无] | [C++](2001-2500/2459-Sort-Array-by-Moving-Items-to-Empty-Space/cpp-2459/) | | | +| 2460 | [Apply Operations to an Array](https://leetcode.com/problems/apply-operations-to-an-array/) | [无] | [C++](2001-2500/2460-Apply-Operations-to-an-Array/cpp-2460/) | | | +| 2461 | [Maximum Sum of Distinct Subarrays With Length K](https://leetcode.com/problems/maximum-sum-of-distinct-subarrays-with-length-k/) | [无] | [C++](2001-2500/2461-Maximum-Sum-of-Distinct-Subarrays-With-Length-K/cpp-2461/) | | | +| 2462 | [Total Cost to Hire K Workers](https://leetcode.com/problems/total-cost-to-hire-k-workers/) | [无] | [C++](2001-2500/2462-Total-Cost-to-Hire-K-Workers/cpp-2462/) | | | +| 2463 | [Minimum Total Distance Traveled](https://leetcode.com/problems/minimum-total-distance-traveled/) | [无] | [C++](2001-2500/2463-Minimum-Total-Distance-Traveled/cpp-2463/) | | | +| 2464 | [Minimum Subarrays in a Valid Split](https://leetcode.com/problems/minimum-subarrays-in-a-valid-split/description/) | [无] | [C++](2001-2500/2464-Minimum-Subarrays-in-a-Valid-Split/cpp-2464/) | | | +| 2465 | [Number of Distinct Averages](https://leetcode.com/problems/number-of-distinct-averages/) | [无] | [C++](2001-2500/2465-Number-of-Distinct-Averages/cpp-2465/) | | | +| 2466 | [Count Ways To Build Good Strings](https://leetcode.com/problems/count-ways-to-build-good-strings/) | [无] | [C++](2001-2500/2466-Count-Ways-To-Build-Good-Strings/cpp-2466/) | | | +| 2467 | [Most Profitable Path in a Tree](https://leetcode.com/problems/most-profitable-path-in-a-tree/) | [无] | [C++](2001-2500/2467-Most-Profitable-Path-in-a-Tree/cpp-2467/) | | | +| 2468 | [Split Message Based on Limit](https://leetcode.com/problems/split-message-based-on-limit/) | [无] | [C++](2001-2500/2468-Split-Message-Based-on-Limit/cpp-2468/) | | | +| 2469 | [Convert the Temperature](https://leetcode.com/problems/convert-the-temperature/) | [无] | [C++](2001-2500/2469-Convert-the-Temperature/cpp-2469/) | | | +| 2470 | [Number of Subarrays With LCM Equal to K](https://leetcode.com/problems/number-of-subarrays-with-lcm-equal-to-k/) | [无] | [C++](2001-2500/2470-Number-of-Subarrays-With-LCM-Equal-to-K/cpp-2470/) | | | +| 2471 | [Minimum Number of Operations to Sort a Binary Tree by Level](https://leetcode.com/problems/minimum-number-of-operations-to-sort-a-binary-tree-by-level/) | [无] | [C++](2001-2500/2471-Minimum-Number-of-Operations-to-Sort-a-Binary-Tree-by-Level/cpp-2471/) | | | +| 2472 | [Maximum Number of Non-overlapping Palindrome Substrings](https://leetcode.com/problems/maximum-number-of-non-overlapping-palindrome-substrings/) | [无] | [C++](2001-2500/2472-Maximum-Number-of-Non-overlapping-Palindrome-Substrings/cpp-2472/) | | | +| 2473 | [Minimum Cost to Buy Apples](https://leetcode.com/problems/minimum-cost-to-buy-apples/description/) | [无] | [C++](2001-2500/2473-Minimum-Cost-to-Buy-Apples/cpp-2473/) | | | +| 2474 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 2475 | [Number of Unequal Triplets in Array](https://leetcode.com/problems/number-of-unequal-triplets-in-array/) | [无] | [C++](2001-2500/2475-Number-of-Unequal-Triplets-in-Array/cpp-2475/) | | | +| 2476 | [Closest Nodes Queries in a Binary Search Tree](https://leetcode.com/problems/closest-nodes-queries-in-a-binary-search-tree/) | [无] | [C++](2001-2500/2476-Closest-Nodes-Queries-in-a-Binary-Search-Tree/cpp-2476/) | | | +| 2477 | [Minimum Fuel Cost to Report to the Capital](https://leetcode.com/problems/minimum-fuel-cost-to-report-to-the-capital/) | [无] | [C++](2001-2500/2477-Minimum-Fuel-Cost-to-Report-to-the-Capital/cpp-2477/) | | | +| 2478 | [Number of Beautiful Partitions](https://leetcode.com/problems/number-of-beautiful-partitions/) | [无] | [C++](2001-2500/2478-Number-of-Beautiful-Partitions/cpp-2478/) | | | +| 2479 | [Maximum XOR of Two Non-Overlapping Subtrees](https://leetcode.com/problems/maximum-xor-of-two-non-overlapping-subtrees/description/) | [无] | [C++](2001-2500/2479-Maximum-XOR-of-Two-Non-Overlapping-Subtrees/cpp-2479/) | | | +| 2480 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 2481 | [Minimum Cuts to Divide a Circle](https://leetcode.com/problems/minimum-cuts-to-divide-a-circle/) | [无] | [C++](2001-2500/2481-Minimum-Cuts-to-Divide-a-Circle/cpp-2481/) | | | +| 2482 | [Difference Between Ones and Zeros in Row and Column](https://leetcode.com/problems/difference-between-ones-and-zeros-in-row-and-column/) | [无] | [C++](2001-2500/2482-Difference-Between-Ones-and-Zeros-in-Row-and-Column/cpp-2482/) | | | +| 2483 | [Minimum Penalty for a Shop](https://leetcode.com/problems/minimum-penalty-for-a-shop/) | [无] | [C++](2001-2500/2483-Minimum-Penalty-for-a-Shop/cpp-2483/) | | | +| 2484 | [Count Palindromic Subsequences](https://leetcode.com/problems/count-palindromic-subsequences/) | [无] | [C++](2001-2500/2484-Count-Palindromic-Subsequences/cpp-2484/) | | | +| 2485 | [Find the Pivot Integer](https://leetcode.com/problems/find-the-pivot-integer/) | [无] | [C++](2001-2500/2485-Find-the-Pivot-Integer/cpp-2485/) | | | +| 2486 | [Append Characters to String to Make Subsequence](https://leetcode.com/problems/append-characters-to-string-to-make-subsequence/) | [无] | [C++](2001-2500/2486-Append-Characters-to-String-to-Make-Subsequence/cpp-2486/) | | | +| 2487 | [Remove Nodes From Linked List](https://leetcode.com/problems/remove-nodes-from-linked-list/) | [无] | [C++](2001-2500/2487-Remove-Nodes-From-Linked-List/cpp-2487/) | | | +| 2488 | [Count Subarrays With Median K](https://leetcode.com/problems/count-subarrays-with-median-k/) | [无] | [C++](2001-2500/2488-Count-Subarrays-With-Median-K/cpp-2488/) | | | +| 2489 | [Number of Substrings With Fixed Ratio](https://leetcode.com/problems/number-of-substrings-with-fixed-ratio/description/) | [无] | [C++](2001-2500/2489-Number-of-Substrings-With-Fixed-Ratio/cpp-2489/) | | | +| 2490 | [Circular Sentence](https://leetcode.com/problems/circular-sentence/) | [无] | [C++](2001-2500/2490-Circular-Sentence/cpp-2490/) | | | +| 2491 | [Divide Players Into Teams of Equal Skill](https://leetcode.com/problems/divide-players-into-teams-of-equal-skill/) | [无] | [C++](2001-2500/2491-Divide-Players-Into-Teams-of-Equal-Skill/cpp-2491/) | | | +| 2492 | [Minimum Score of a Path Between Two Cities](https://leetcode.com/problems/minimum-score-of-a-path-between-two-cities/) | [无] | [C++](2001-2500/2492-Minimum-Score-of-a-Path-Between-Two-Cities/cpp-2492/) | | | +| 2493 | [Divide Nodes Into the Maximum Number of Groups](https://leetcode.com/problems/divide-nodes-into-the-maximum-number-of-groups/) | [无] | [C++](2001-2500/2493-Divide-Nodes-Into-the-Maximum-Number-of-Groups/cpp-2493/) | | | +| 2494 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 2495 | [Number of Subarrays Having Even Product](https://leetcode.com/problems/number-of-subarrays-having-even-product/description/) | [无] | [C++](2001-2500/2495-Number-of-Subarrays-Having-Even-Product/cpp-2495) | | | +| 2496 | [Maximum Value of a String in an Array](https://leetcode.com/problems/maximum-value-of-a-string-in-an-array/) | [无] | [C++](2001-2500/2496-Maximum-Value-of-a-String-in-an-Array/cpp-2496) | | | +| 2497 | [Maximum Star Sum of a Graph](https://leetcode.com/problems/maximum-star-sum-of-a-graph/) | [无] | [C++](2001-2500/2497-Maximum-Star-Sum-of-a-Graph/cpp-2497) | | | +| 2498 | [Frog Jump II](https://leetcode.com/problems/frog-jump-ii/) | [无] | [C++](2001-2500/2498-Frog-Jump-II/cpp-2498/) | | | +| 2499 | [Minimum Total Cost to Make Arrays Unequal](https://leetcode.com/problems/minimum-total-cost-to-make-arrays-unequal/description/) | [无] | [C++](2001-2500/2499-Minimum-Total-Cost-to-Make-Arrays-Unequal/cpp-2499/) | | | +| 2500 | [Delete Greatest Value in Each Row](https://leetcode.com/problems/delete-greatest-value-in-each-row/) | [无] | [C++](2001-2500/2500-Delete-Greatest-Value-in-Each-Row/cpp-2500/) | | | +| 2501 | [Longest Square Streak in an Array](https://leetcode.com/problems/longest-square-streak-in-an-array/) | [无] | [C++](2501-3000/2501-Longest-Square-Streak-in-an-Array/cpp-2501/) | | | +| 2502 | [Design Memory Allocator](https://leetcode.com/problems/design-memory-allocator/) | [无] | [C++](2501-3000/2502-Design-Memory-Allocator/cpp-2502/) | | | +| 2503 | [Maximum Number of Points From Grid Queries](https://leetcode.com/problems/maximum-number-of-points-from-grid-queries/) | [无] | [C++](2501-3000/2503-Maximum-Number-of-Points-From-Grid-Queries/cpp-2503/) | | | +| 2504 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 2505 | [Bitwise OR of All Subsequence Sums](https://leetcode.com/problems/bitwise-or-of-all-subsequence-sums/description/) | [无] | [C++](2501-3000/2505-Bitwise-OR-of-All-Subsequence-Sums/cpp-2505/) | | | +| 2506 | [Count Pairs Of Similar Strings](https://leetcode.com/problems/count-pairs-of-similar-strings/) | [无] | [C++](2501-3000/2506-Count-Pairs-Of-Similar-Strings/cpp-2506/) | | | +| 2507 | [Smallest Value After Replacing With Sum of Prime Factors](https://leetcode.com/problems/smallest-value-after-replacing-with-sum-of-prime-factors/) | [无] | [C++](2501-3000/2507-Smallest-Value-After-Replacing-With-Sum-of-Prime-Factors/cpp-2507/) | | | +| 2508 | [Add Edges to Make Degrees of All Nodes Even](https://leetcode.com/problems/add-edges-to-make-degrees-of-all-nodes-even/) | [无] | [C++](2501-3000/2508-Add-Edges-to-Make-Degrees-of-All-Nodes-Even/cpp-2508/) | | | +| 2509 | [Cycle Length Queries in a Tree](https://leetcode.com/problems/cycle-length-queries-in-a-tree/) | [无] | [C++](2501-3000/2509-Cycle-Length-Queries-in-a-Tree/cpp-2509/) | | | +| 2510 | [Check if There is a Path With Equal Number of 0's And 1's](https://leetcode.com/problems/check-if-there-is-a-path-with-equal-number-of-0s-and-1s/description/) | [无] | [C++](2501-3000/2510-Check-if-There-is-a-Path-With-Equal-Number-of-0s-And-1s/cpp-2510/) | | | +| 2511 | [Maximum Enemy Forts That Can Be Captured](https://leetcode.com/problems/maximum-enemy-forts-that-can-be-captured/) | [无] | [C++](2501-3000/2511-Maximum-Enemy-Forts-That-Can-Be-Captured/cpp-2511/) | | | +| 2512 | [Reward Top K Students](https://leetcode.com/problems/reward-top-k-students/) | [无] | [C++](2501-3000/2512-Reward-Top-K-Students/cpp-2512/) | | | +| 2513 | [Minimize the Maximum of Two Arrays](https://leetcode.com/problems/minimize-the-maximum-of-two-arrays/) | [无] | [C++](2501-3000/2513-Minimize-the-Maximum-of-Two-Arrays/cpp-2513/) | | | +| 2514 | [Count Anagrams](https://leetcode.com/problems/count-anagrams/) | [无] | [C++](2501-3000/2514-Count-Anagrams/cpp-2514/) | | | +| 2515 | [Shortest Distance to Target String in a Circular Array](https://leetcode.com/problems/shortest-distance-to-target-string-in-a-circular-array/) | [无] | [C++](2501-3000/2515-Shortest-Distance-to-Target-String-in-a-Circular-Array/cpp-2515/) | | | +| 2516 | [Take K of Each Character From Left and Right](2001-2500/2516-Take-K-of-Each-Character-From-Left-and-Right/cpp-2516/) | [无] | [C++](2501-3000/2516-Take-K-of-Each-Character-From-Left-and-Right/cpp-2516/) | | | +| 2517 | [Maximum Tastiness of Candy Basket](2001-2500/2517-Maximum-Tastiness-of-Candy-Basket/cpp-2517/) | [无] | [C++](2501-3000/2517-Maximum-Tastiness-of-Candy-Basket/cpp-2517/) | | | +| 2518 | [Number of Great Partitions](https://leetcode.com/problems/number-of-great-partitions/) | [无] | [C++](2501-3000/2518-Number-of-Great-Partitions/cpp-2518/) | | | +| 2519 | [Count the Number of K-Big Indices](https://leetcode.com/problems/count-the-number-of-k-big-indices/description/) | [无] | [C++](2501-3000/2519-Count-the-Number-of-K-Big-Indices/cpp-2519/) | | | +| 2520 | [Count the Digits That Divide a Number](https://leetcode.com/problems/count-the-digits-that-divide-a-number/) | [无] | [C++](2501-3000/2520-Count-the-Digits-That-Divide-a-Number/cpp-2520/) | | | +| 2521 | [Distinct Prime Factors of Product of Array](https://leetcode.com/problems/distinct-prime-factors-of-product-of-array/) | [无] | [C++](2501-3000/2521-Distinct-Prime-Factors-of-Product-of-Array/cpp-2521/) | | | +| 2522 | [Partition String Into Substrings With Values at Most K](https://leetcode.com/problems/partition-string-into-substrings-with-values-at-most-k/) | [无] | [C++](2501-3000/2522-Partition-String-Into-Substrings-With-Values-at-Most-K/cpp-2522/) | | | +| 2523 | [Closest Prime Numbers in Range](https://leetcode.com/problems/closest-prime-numbers-in-range/) | [无] | [C++](2501-3000/2523-Closest-Prime-Numbers-in-Range/cpp-2523/) | | | +| 2524 | [Maximum Frequency Score of a Subarray](https://leetcode.com/problems/maximum-frequency-score-of-a-subarray/description/) | [无] | [C++](2501-3000/2524-Maximum-Frequency-Score-of-a-Subarray/cpp-2524/) | | | +| 2525 | [Categorize Box According to Criteria](https://leetcode.com/problems/categorize-box-according-to-criteria/) | [无] | [C++](2501-3000/2525-Categorize-Box-According-to-Criteria/cpp-2525/) | | | +| 2526 | [Find Consecutive Integers from a Data Stream](https://leetcode.com/problems/find-consecutive-integers-from-a-data-stream/) | [无] | [C++](2501-3000/2526-Find-Consecutive-Integers-from-a-Data-Stream/cpp-2526/) | | | +| 2527 | [Find Xor-Beauty of Array](https://leetcode.com/problems/find-xor-beauty-of-array/) | [无] | [C++](2501-3000/2527-Find-Xor-Beauty-of-Array/cpp-2527/) | | | +| 2528 | [Maximize the Minimum Powered City](https://leetcode.com/problems/maximize-the-minimum-powered-city/) | [无] | [C++](2501-3000/2528-Maximize-the-Minimum-Powered-City/cpp-2528/) | | | +| 2529 | [Maximum Count of Positive Integer and Negative Integer](https://leetcode.com/problems/maximum-count-of-positive-integer-and-negative-integer/) | [无] | [C++](2501-3000/2529-Maximum-Count-of-Positive-Integer-and-Negative-Integer/cpp-2529/) | | | +| 2530 | [Maximal Score After Applying K Operations](https://leetcode.com/problems/maximal-score-after-applying-k-operations/) | [无] | [C++](2501-3000/2530-Maximal-Score-After-Applying-K-Operations/cpp-2530/) | | | +| 2531 | [Make Number of Distinct Characters Equal](https://leetcode.com/problems/make-number-of-distinct-characters-equal/) | [无] | [C++](2501-3000/2531-Make-Number-of-Distinct-Characters-Equal/cpp-2531/) | | | +| 2532 | [Time to Cross a Bridge](https://leetcode.com/problems/time-to-cross-a-bridge/description/) | [无] | [C++](2501-3000/2532-Time-to-Cross-a-Bridge/cpp-2532/) | | | +| 2533 | [Number of Good Binary Strings](https://leetcode.com/problems/number-of-good-binary-strings/) | [无] | [C++](2501-3000/2533-Number-of-Good-Binary-Strings/cpp-2533/) | | | +| 2534 | [Time Taken to Cross the Door](https://leetcode.com/problems/time-taken-to-cross-the-door/description/) | [无] | [C++](2501-3000/2534-Time-Taken-to-Cross-the-Door/cpp-2534/) | | | +| 2535 | [Difference Between Element Sum and Digit Sum of an Array](https://leetcode.com/problems/difference-between-element-sum-and-digit-sum-of-an-array/) | [无] | [C++](2501-3000/2535-Difference-Between-Element-Sum-and-Digit-Sum-of-an-Array/cpp-2535/) | | | +| 2536 | [Increment Submatrices by One](https://leetcode.com/problems/increment-submatrices-by-one/) | [无] | [C++](2501-3000/2536-Increment-Submatrices-by-One/cpp-2536/) | | | +| 2537 | [Count the Number of Good Subarrays](https://leetcode.com/problems/count-the-number-of-good-subarrays/) | [无] | [C++](2501-3000/2537-Count-the-Number-of-Good-Subarrays/cpp-2537/) | | | +| | | | | | | +| 2539 | [Count the Number of Good Subsequences](https://leetcode.com/problems/count-the-number-of-good-subsequences/) | [无] | [C++](2501-3000/2539-Count-the-Number-of-Good-Subsequences/cpp-2539/) | | | +| 2540 | [Minimum Common Value](https://leetcode.com/problems/minimum-common-value/) | [无] | [C++](2501-3000/2540-Minimum-Common-Value/cpp-2540/) | | | +| 2541 | [Minimum Operations to Make Array Equal II](https://leetcode.com/problems/minimum-operations-to-make-array-equal-ii/) | [无] | [C++](2501-3000/2541-Minimum-Operations-to-Make-Array-Equal-II/cpp-2541/) | | | +| 2542 | [Maximum Subsequence Score](https://leetcode.com/problems/maximum-subsequence-score/) | [无] | [C++](2501-3000/2542-Maximum-Subsequence-Score/cpp-2542/) | | | +| 2543 | [Check if Point Is Reachable](https://leetcode.com/problems/check-if-point-is-reachable/description/) | [无] | [C++](2501-3000/2543-Check-if-Point-Is-Reachable/cpp-2543/) | | | +| 2544 | [Alternating Digit Sum](https://leetcode.com/problems/alternating-digit-sum/) | [无] | [C++](2501-3000/2544-Alternating-Digit-Sum/cpp-2544/) | | | +| 2545 | [Sort the Students by Their Kth Score](https://leetcode.com/problems/sort-the-students-by-their-kth-score/) | [无] | [C++](2501-3000/2545-Sort-the-Students-by-Their-Kth-Score/cpp-2545/) | | | +| 2546 | [Apply Bitwise Operations to Make Strings Equal](https://leetcode.com/problems/apply-bitwise-operations-to-make-strings-equal/) | [无] | [C++](2501-3000/2546-Apply-Bitwise-Operations-to-Make-Strings-Equal/cpp-2546/) | | | +| 2547 | [Minimum Cost to Split an Array](https://leetcode.com/problems/minimum-cost-to-split-an-array/) | [无] | [C++](2501-3000/2547-Minimum-Cost-to-Split-an-Array/cpp-2547/) | | | +| 2548 | [Maximum Price to Fill a Bag](https://leetcode.com/problems/maximum-price-to-fill-a-bag/) | [无] | [C++](2501-3000/2548-Maximum-Price-to-Fill-a-Bag/cpp-2548/) | | | +| 2549 | [Count Distinct Numbers on Board](https://leetcode.com/problems/count-distinct-numbers-on-board/) | [无] | [C++](2501-3000/2549-Count-Distinct-Numbers-on-Board/cpp-2549/) | | | +| 2550 | [Count Collisions of Monkeys on a Polygon](https://leetcode.com/problems/count-collisions-of-monkeys-on-a-polygon/) | [无] | [C++](2501-3000/2550-Count-Collisions-of-Monkeys-on-a-Polygon/cpp-2550/) | | | +| 2551 | [Put Marbles in Bags](https://leetcode.com/problems/put-marbles-in-bags/) | [无] | [C++](2501-3000/2551-Put-Marbles-in-Bags/cpp-2551/) | | | +| | | | | | | +| 2553 | [Separate the Digits in an Array](https://leetcode.com/problems/separate-the-digits-in-an-array/) | [无] | [C++](2501-3000/2553-Separate-the-Digits-in-an-Array/cpp-2553/) | | | +| 2554 | [Maximum Number of Integers to Choose From a Range I](https://leetcode.com/problems/maximum-number-of-integers-to-choose-from-a-range-i/) | [无] | [C++](2501-3000/2554-Maximum-Number-of-Integers-to-Choose-From-a-Range-I/cpp-2554/) | | | +| 2555 | [Maximize Win From Two Segments](https://leetcode.com/problems/maximize-win-from-two-segments/) | [无] | [C++](2501-3000/2555-Maximize-Win-From-Two-Segments/cpp-2555/) | | | +| 2556 | [Disconnect Path in a Binary Matrix by at Most One Flip](https://leetcode.com/problems/disconnect-path-in-a-binary-matrix-by-at-most-one-flip/) | [无] | [C++](2501-3000/2556-Disconnect-Path-in-a-Binary-Matrix-by-at-Most-One-Flip/cpp-2556/) | | | +| 2557 | [Maximum Number of Integers to Choose From a Range II](https://leetcode.com/problems/maximum-number-of-integers-to-choose-from-a-range-ii/description/) | [无] | [C++](2501-3000/2557-Maximum-Number-of-Integers-to-Choose-From-a-Range-II/cpp-2557/) | | | +| 2558 | [Take Gifts From the Richest Pile](https://leetcode.com/problems/take-gifts-from-the-richest-pile/) | [无] | [C++](2501-3000/2558-Take-Gifts-From-the-Richest-Pile/cpp-2558/) | | | +| 2559 | [Count Vowel Strings in Ranges](https://leetcode.com/problems/count-vowel-strings-in-ranges/) | [无] | [C++](2501-3000/2559-Count-Vowel-Strings-in-Ranges/cpp-2559/) | | | +| 2560 | [House Robber IV](https://leetcode.com/problems/house-robber-iv/) | [无] | [C++](2501-3000/2560-House-Robber-IV/cpp-2560/) | | | +| 2561 | [Rearranging Fruits](https://leetcode.com/problems/rearranging-fruits/) | [无] | [C++](2501-3000/2561-Rearranging-Fruits/cpp-2561/) | | | +| 2562 | [Find the Array Concatenation Value](https://leetcode.com/problems/find-the-array-concatenation-value/) | [无] | [C++](2501-3000/2562-Find-the-Array-Concatenation-Value/cpp-2562/) | | | +| 2563 | [Count the Number of Fair Pairs](https://leetcode.com/problems/count-the-number-of-fair-pairs/) | [无] | [C++](2501-3000/2563-Count-the-Number-of-Fair-Pairs/cpp-2563/) | | | +| 2564 | [Substring XOR Queries](https://leetcode.com/problems/substring-xor-queries/) | [无] | [C++](2501-3000/2564-Substring-XOR-Queries/cpp-2564/) | | | +| 2565 | [Subsequence With the Minimum Score](https://leetcode.com/problems/subsequence-with-the-minimum-score/) | [无] | [C++](2501-3000/2565-Subsequence-With-the-Minimum-Score/cpp-2565/) | | | +| 2566 | [Maximum Difference by Remapping a Digit](https://leetcode.com/problems/maximum-difference-by-remapping-a-digit/) | [无] | [C++](2501-3000/2566-Maximum-Difference-by-Remapping-a-Digit/cpp-2566/) | | | +| 2567 | [Minimum Score by Changing Two Elements](https://leetcode.com/problems/minimum-score-by-changing-two-elements/) | [无] | [C++](2501-3000/2567-Minimum-Score-by-Changing-Two-Elements/cpp-2567/) | | | +| 2568 | [Minimum Impossible OR](https://leetcode.com/problems/minimum-impossible-or/) | [无] | [C++](2501-3000/2568-Minimum-Impossible-OR/cpp-2568/) | | | +| 2569 | [Handling Sum Queries After Update](https://leetcode.com/problems/handling-sum-queries-after-update/) | [无] | [C++](2501-3000/2569-Handling-Sum-Queries-After-Update/cpp-2569/) | | | +| 2570 | [Merge Two 2D Arrays by Summing Values](https://leetcode.com/problems/merge-two-2d-arrays-by-summing-values/) | [无] | [C++](2501-3000/2570-Merge-Two-2D-Arrays-by-Summing-Values/cpp-2570/) | | | +| 2571 | [Minimum Operations to Reduce an Integer to 0](https://leetcode.com/problems/minimum-operations-to-reduce-an-integer-to-0/) | [无] | [C++](2501-3000/2571-Minimum-Operations-to-Reduce-an-Integer-to-0/cpp-2571/) | | | +| 2572 | [Count the Number of Square-Free Subsets](https://leetcode.com/problems/count-the-number-of-square-free-subsets/) | [无] | [C++](2501-3000/2572-Count-the-Number-of-Square-Free-Subsets/cpp-2572/) | | | +| 2573 | [Find the String with LCP](https://leetcode.com/problems/find-the-string-with-lcp/) | [无] | [C++](2501-3000/2573-Find-the-String-with-LCP/cpp-2573/) | | | +| 2574 | [Left and Right Sum Differences](https://leetcode.com/problems/left-and-right-sum-differences/) | [无] | [C++](2501-3000/2574-Left-and-Right-Sum-Differences/cpp-2574/) | | | +| 2575 | [Find the Divisibility Array of a String](https://leetcode.com/problems/find-the-divisibility-array-of-a-string/) | [无] | [C++](2501-3000/2575-Find-the-Divisibility-Array-of-a-String/cpp-2575/) | | | +| 2576 | [Find the Maximum Number of Marked Indices](https://leetcode.com/problems/find-the-maximum-number-of-marked-indices/) | [无] | [C++](2501-3000/2576-Find-the-Maximum-Number-of-Marked-Indices/cpp-2576/) | | | +| 2577 | [Minimum Time to Visit a Cell In a Grid](https://leetcode.com/problems/minimum-time-to-visit-a-cell-in-a-grid/) | [无] | [C++](2501-3000/2577-Minimum-Time-to-Visit-a-Cell-In-a-Grid/cpp-2577/) | | | +| 2578 | [Split With Minimum Sum](https://leetcode.com/problems/split-with-minimum-sum/) | [无] | [C++](2501-3000/2578-Split-With-Minimum-Sum/cpp-2578/) | | | +| 2579 | [Count Total Number of Colored Cells](https://leetcode.com/problems/count-total-number-of-colored-cells/) | [无] | [C++](2501-3000/2579-Count-Total-Number-of-Colored-Cells/cpp-2579/) | | | +| 2580 | [Count Ways to Group Overlapping Ranges](https://leetcode.com/problems/count-ways-to-group-overlapping-ranges/) | [无] | [C++](2501-3000/2580-Count-Ways-to-Group-Overlapping-Ranges/cpp-2580/) | | | +| 2581 | [Count Number of Possible Root Nodes](https://leetcode.com/problems/count-number-of-possible-root-nodes/) | [无] | [C++](2501-3000/2581-Count-Number-of-Possible-Root-Nodes/cpp-2581/) | | | +| 2582 | [Pass the Pillow](https://leetcode.com/problems/pass-the-pillow/) | [无] | [C++](2501-3000/2582-Pass-the-Pillow/cpp-2582/) | | | +| 2583 | [Kth Largest Sum in a Binary Tree](https://leetcode.com/problems/kth-largest-sum-in-a-binary-tree/) | [无] | [C++](2501-3000/2583-Kth-Largest-Sum-in-a-Binary-Tree/cpp-2583/) | | | +| 2584 | [Split the Array to Make Coprime Products](https://leetcode.com/problems/split-the-array-to-make-coprime-products/) | [无] | [C++](2501-3000/2584-Split-the-Array-to-Make-Coprime-Products/cpp-2584/) | | | +| 2585 | [Number of Ways to Earn Points](https://leetcode.com/problems/number-of-ways-to-earn-points/) | [无] | [C++](2501-3000/2585-Number-of-Ways-to-Earn-Points/cpp-2585/) | | | +| 2586 | [Count the Number of Vowel Strings in Range](https://leetcode.com/problems/count-the-number-of-vowel-strings-in-range/) | [无] | [C++](2501-3000/2586-Count-the-Number-of-Vowel-Strings-in-Range/cpp-2586/) | | | +| 2587 | [Rearrange Array to Maximize Prefix Score](https://leetcode.com/problems/rearrange-array-to-maximize-prefix-score/) | [无] | [C++](2501-3000/2587-Rearrange-Array-to-Maximize-Prefix-Score/cpp-2587/) | | | +| 2588 | [Count the Number of Beautiful Subarrays](https://leetcode.com/problems/count-the-number-of-beautiful-subarrays/) | [无] | [C++](2501-3000/2588-Count-the-Number-of-Beautiful-Subarrays/cpp-2588/) | | | +| 2589 | [Minimum Time to Complete All Tasks](https://leetcode.com/problems/minimum-time-to-complete-all-tasks/) | [无] | [C++](2501-3000/2589-Minimum-Time-to-Complete-All-Tasks/cpp-2589/) | | | +| 2590 | [Design a Todo List](https://leetcode.com/problems/design-a-todo-list/description/) | [无] | [C++](2501-3000/2590-Design-a-Todo-List/cpp-2590/) | | | +| 2591 | [Distribute Money to Maximum Children](https://leetcode.com/problems/distribute-money-to-maximum-children/) | [无] | [C++](2501-3000/2591-Distribute-Money-to-Maximum-Children/cpp-2591/) | | | +| 2592 | [Maximize Greatness of an Array](https://leetcode.com/problems/maximize-greatness-of-an-array/) | [无] | [C++](2501-3000/2592-Maximize-Greatness-of-an-Array/cpp-2592/) | | | +| 2593 | [Find Score of an Array After Marking All Elements](https://leetcode.com/problems/find-score-of-an-array-after-marking-all-elements/) | [无] | [C++](2501-3000/2593-Find-Score-of-an-Array-After-Marking-All-Elements/cpp-2593/) | | | +| 2594 | [Minimum Time to Repair Cars](https://leetcode.com/problems/minimum-time-to-repair-cars/) | [无] | [C++](2501-3000/2594-Minimum-Time-to-Repair-Cars/cpp-2594/) | | | +| 2595 | [Number of Even and Odd Bits](https://leetcode.com/problems/number-of-even-and-odd-bits/) | [无] | [C++](2501-3000/2595-Number-of-Even-and-Odd-Bits/cpp-2595/) | | | +| 2596 | [Check Knight Tour Configuration](https://leetcode.com/problems/check-knight-tour-configuration/) | [无] | [C++](2501-3000/2596-Check-Knight-Tour-Configuration/cpp-2596/) | | | +| 2597 | [The Number of Beautiful Subsets](https://leetcode.com/problems/the-number-of-beautiful-subsets/) | [无] | [C++](2501-3000/2597-The-Number-of-Beautiful-Subsets/cpp-2597/) | | | +| 2598 | [Smallest Missing Non-negative Integer After Operations](https://leetcode.com/problems/smallest-missing-non-negative-integer-after-operations/) | [无] | [C++](2501-3000/2598-Smallest-Missing-Non-negative-Integer-After-Operations/cpp-2598/) | | | +| 2599 | [Make the Prefix Sum Non-negative](https://leetcode.com/problems/make-the-prefix-sum-non-negative/description/) | [无] | [C++](2501-3000/2599-Make-the-Prefix-Sum-Non-negative/cpp-2599/) | | | +| 2600 | [K Items With the Maximum Sum](https://leetcode.com/problems/k-items-with-the-maximum-sum/) | [无] | [C++](2501-3000/2600-K-Items-With-the-Maximum-Sum/cpp-2600/) | | | +| 2601 | [Prime Subtraction Operation](https://leetcode.com/problems/prime-subtraction-operation/) | [无] | [C++](2501-3000/2601-Prime-Subtraction-Operation/cpp-2601/) | | | +| 2602 | [Minimum Operations to Make All Array Elements Equal](https://leetcode.com/problems/minimum-operations-to-make-all-array-elements-equal/description/) | [无] | [C++](2501-3000/2602-Minimum-Operations-to-Make-All-Array-Elements-Equal/cpp-2602/) | | | +| 2603 | [Collect Coins in a Tree](https://leetcode.com/problems/collect-coins-in-a-tree/description/) | [无] | [C++](2501-3000/2603-Collect-Coins-in-a-Tree/cpp-2603/) | | | +| 2604 | [Minimum Time to Eat All Grains](https://leetcode.com/problems/minimum-time-to-eat-all-grains/description/) | [无] | [C++](2501-3000/2604-Minimum-Time-to-Eat-All-Grains/cpp-2604/) | | | +| 2605 | [Form Smallest Number From Two Digit Arrays](https://leetcode.com/problems/form-smallest-number-from-two-digit-arrays/) | [无] | [C++](2501-3000/2605-Form-Smallest-Number-From-Two-Digit-Arrays/cpp-2605/) | | | +| 2606 | [Find the Substring With Maximum Cost](https://leetcode.com/problems/find-the-substring-with-maximum-cost/) | [无] | [C++](2501-3000/2606-Find-the-Substring-With-Maximum-Cost/cpp-2606/) | | | +| 2607 | [Make K-Subarray Sums Equal](https://leetcode.com/problems/make-k-subarray-sums-equal/) | [无] | [C++](2501-3000/2607-Make-K-Subarray-Sums-Equal/cpp-2607/) | | | +| 2608 | [Shortest Cycle in a Graph](https://leetcode.com/problems/shortest-cycle-in-a-graph/) | [无] | [C++](2501-3000/2608-Shortest-Cycle-in-a-Graph/cpp-2608/) | | | +| 2609 | [Find the Longest Balanced Substring of a Binary String](https://leetcode.com/problems/find-the-longest-balanced-substring-of-a-binary-string/) | [无] | [C++](2501-3000/2609-Find-the-Longest-Balanced-Substring-of-a-Binary-String/cpp-2609/) | | | +| 2610 | [Convert an Array Into a 2D Array With Conditions](https://leetcode.com/problems/convert-an-array-into-a-2d-array-with-conditions/) | [无] | [C++](2501-3000/2610-Convert-an-Array-Into-a-2D-Array-With-Conditions/cpp-2610/) | | | +| 2611 | [Mice and Cheese](https://leetcode.com/problems/mice-and-cheese/) | [无] | [C++](2501-3000/2611-Mice-and-Cheese/cpp-2611/) | | | +| 2612 | [Minimum Reverse Operations](https://leetcode.com/problems/minimum-reverse-operations/) | [无] | [C++](2501-3000/2612-Minimum-Reverse-Operations/cpp-2612/) | | | +| | | | | | | +| 2614 | [Prime In Diagonal](https://leetcode.com/problems/prime-in-diagonal/) | [无] | [C++](2501-3000/2614-Prime-In-Diagonal/cpp-2614/) | | | +| 2615 | [Sum of Distances](https://leetcode.com/problems/sum-of-distances/) | [无] | [C++](2501-3000/2615-Sum-of-Distances/cpp-2615/) | | | +| 2616 | [Minimize the Maximum Difference of Pairs](https://leetcode.com/problems/minimize-the-maximum-difference-of-pairs/) | [无] | [C++](2501-3000/2616-Minimize-the-Maximum-Difference-of-Pairs/cpp-2616/) | | | +| 2617 | [Minimum Number of Visited Cells in a Grid](https://leetcode.com/problems/minimum-number-of-visited-cells-in-a-grid/) | [无] | [C++](2501-3000/2617-Minimum-Number-of-Visited-Cells-in-a-Grid/cpp-2617/) | | | +| 2618 | JavaScript Problem | - | - | - | - | +| 2619 | JavaScript Problem | - | - | - | - | +| 2620 | JavaScript Problem | - | - | - | - | +| 2621 | JavaScript Problem | - | - | - | - | +| 2622 | JavaScript Problem | - | - | - | - | +| 2623 | JavaScript Problem | - | - | - | - | +| 2624 | JavaScript Problem | - | - | - | - | +| 2625 | JavaScript Problem | - | - | - | - | +| 2626 | JavaScript Problem | - | - | - | - | +| 2627 | JavaScript Problem | - | - | - | - | +| 2628 | JavaScript Problem | - | - | - | - | +| 2629 | JavaScript Problem | - | - | - | - | +| 2630 | JavaScript Problem | - | - | - | - | +| 2631 | JavaScript Problem | - | - | - | - | +| 2632 | JavaScript Problem | - | - | - | - | +| 2633 | JavaScript Problem | - | - | - | - | +| 2634 | JavaScript Problem | - | - | - | - | +| 2635 | JavaScript Problem | - | - | - | - | +| 2636 | JavaScript Problem | - | - | - | - | +| 2637 | JavaScript Problem | - | - | - | - | +| 2638 | [Count the Number of K-Free Subsets](https://leetcode.com/problems/count-the-number-of-k-free-subsets/description/) | [无] | [C++](2501-3000/2638-Count-the-Number-of-K-Free-Subsets/cpp-2638/) | | | +| 2639 | [Find the Width of Columns of a Grid](https://leetcode.com/problems/find-the-width-of-columns-of-a-grid/) | [无] | [C++](2501-3000/2639-Find-the-Width-of-Columns-of-a-Grid/cpp-2639/) | | | +| 2640 | [Find the Score of All Prefixes of an Array](https://leetcode.com/problems/find-the-score-of-all-prefixes-of-an-array/) | [无] | [C++](2501-3000/2640-Find-the-Score-of-All-Prefixes-of-an-Array/cpp-2640/) | | | +| 2641 | [Cousins in Binary Tree II](https://leetcode.com/problems/cousins-in-binary-tree-ii/) | [无] | [C++](2501-3000/2641-Cousins-in-Binary-Tree-II/cpp-2641/) | | | +| 2642 | [Design Graph With Shortest Path Calculator](https://leetcode.com/problems/design-graph-with-shortest-path-calculator/) | [无] | [C++](2501-3000/2642-Design-Graph-With-Shortest-Path-Calculator/cpp-2642/) | | | +| 2643 | [Row With Maximum Ones](https://leetcode.com/problems/row-with-maximum-ones/) | [无] | [C++](2501-3000/2643-Row-With-Maximum-Ones/cpp-2643/) | | | +| 2644 | [Find the Maximum Divisibility Score](https://leetcode.com/problems/find-the-maximum-divisibility-score/) | [无] | [C++](2501-3000/2644-Find-the-Maximum-Divisibility-Score/cpp-2644/) | | | +| 2645 | [Minimum Additions to Make Valid String](https://leetcode.com/problems/minimum-additions-to-make-valid-string/) | [无] | [C++](2501-3000/2645-Minimum-Additions-to-Make-Valid-String/cpp-2645/) | | | +| 2646 | [Minimize the Total Price of the Trips](https://leetcode.com/problems/minimize-the-total-price-of-the-trips/) | [无] | [C++](2501-3000/2646-Minimize-the-Total-Price-of-the-Trips/cpp-2646/) | | | +| 2647 | [Color the Triangle Red](https://leetcode.com/problems/color-the-triangle-red/description/) | [无] | [C++](2501-3000/2647-Color-the-Triangle-Red/cpp-2647/) | | | +| 2648 | JavaScript Problem | - | - | - | - | +| 2649 | JavaScript Problem | - | - | - | - | +| 2650 | JavaScript Problem | - | - | - | - | +| 2651 | [Calculate Delayed Arrival Time](https://leetcode.com/problems/calculate-delayed-arrival-time/) | [无] | [C++](2501-3000/2651-Calculate-Delayed-Arrival-Time/cpp-2651/) | | | +| 2652 | [Sum Multiples](https://leetcode.com/problems/sum-multiples/) | [无] | [C++](2501-3000/2652-Sum-Multiples/cpp-2652/) | | | +| 2653 | [Sliding Subarray Beauty](https://leetcode.com/problems/sliding-subarray-beauty/) | [无] | [C++](2501-3000/2653-Sliding-Subarray-Beauty/cpp-2653/) | | | +| 2654 | [Minimum Number of Operations to Make All Array Elements Equal to 1](https://leetcode.com/problems/minimum-number-of-operations-to-make-all-array-elements-equal-to-1/) | [无] | [C++](2501-3000/2654-Minimum-Number-of-Operations-to-Make-All-Array-Elements-Equal-to-1/cpp-2654/) | | | +| 2655 | [Find Maximal Uncovered Ranges](https://leetcode.com/problems/find-maximal-uncovered-ranges/description/) | [无] | [C++](2501-3000/2655-Find-Maximal-Uncovered-Ranges/cpp-2655/) | | | +| 2656 | [Maximum Sum With Exactly K Elements](https://leetcode.com/problems/maximum-sum-with-exactly-k-elements/) | [无] | [C++](2501-3000/2656-Maximum-Sum-With-Exactly-K-Elements/cpp-2656/) | | | +| 2657 | [Find the Prefix Common Array of Two Arrays](https://leetcode.com/problems/find-the-prefix-common-array-of-two-arrays/) | [无] | [C++](2501-3000/2657-Find-the-Prefix-Common-Array-of-Two-Arrays/cpp-2657/) | | | +| 2658 | [Maximum Number of Fish in a Grid](https://leetcode.com/problems/maximum-number-of-fish-in-a-grid/) | [无] | [C++](2501-3000/2658-Maximum-Number-of-Fish-in-a-Grid/cpp-2658/) | | | +| 2659 | [Make Array Empty](https://leetcode.com/problems/make-array-empty/) | [无] | [C++](2501-3000/2659-Make-Array-Empty/cpp-2659/) | | | +| 2660 | [Determine the Winner of a Bowling Game](https://leetcode.com/problems/determine-the-winner-of-a-bowling-game/) | [无] | [C++](2501-3000/2660-Determine-the-Winner-of-a-Bowling-Game/cpp-2660/) | | | +| 2661 | [First Completely Painted Row or Column](https://leetcode.com/problems/first-completely-painted-row-or-column/) | [无] | [C++](2501-3000/2661-First-Completely-Painted-Row-or-Column/cpp-2661/) | | | +| 2662 | [Minimum Cost of a Path With Special Roads](https://leetcode.com/problems/minimum-cost-of-a-path-with-special-roads/) | [无] | [C++](2501-3000/2662-Minimum-Cost-of-a-Path-With-Special-Roads/cpp-2662/) | | | +| 2663 | [Lexicographically Smallest Beautiful String](https://leetcode.com/problems/lexicographically-smallest-beautiful-string/) | [无] | [C++](2501-3000/2663-Lexicographically-Smallest-Beautiful-String/cpp-2663/) | | | +| 2664 | [The Knight’s Tour](https://leetcode.com/problems/the-knights-tour/) | [无] | [C++](2501-3000/2664-The-Knights-Tour/cpp-2664/) | | | +| 2665 | JavaScript Problem | - | - | - | - | +| 2666 | JavaScript Problem | - | - | - | - | +| 2667 | JavaScript Problem | - | - | - | - | +| 2668 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 2669 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 2670 | [Find the Distinct Difference Array](https://leetcode.com/problems/find-the-distinct-difference-array/) | [无] | [C++](2501-3000/2670-Find-the-Distinct-Difference-Array/cpp-2670/) | | | +| 2671 | [Frequency Tracker](https://leetcode.com/problems/frequency-tracker/) | [无] | [C++](2501-3000/2671-Frequency-Tracker/cpp-2671/) | | | +| 2672 | [Number of Adjacent Elements With the Same Color](https://leetcode.com/problems/number-of-adjacent-elements-with-the-same-color/) | [无] | [C++](2501-3000/2672-Number-of-Adjacent-Elements-With-the-Same-Color/cpp-2672/) | | | +| 2673 | [Make Costs of Paths Equal in a Binary Tree](https://leetcode.com/problems/make-costs-of-paths-equal-in-a-binary-tree/) | [无] | [C++](2501-3000/2673-Make-Costs-of-Paths-Equal-in-a-Binary-Tree/cpp-2673/) | | | +| 2674 | [Split a Circular Linked List](https://leetcode.com/problems/split-a-circular-linked-list/description/) | [无] | [C++](2501-3000/2674-Split-a-Circular-Linked-List/cpp-2674/) | | | +| 2675 | JavaScript Problem | - | - | - | - | +| 2676 | JavaScript Problem | - | - | - | - | +| 2677 | JavaScript Problem | - | - | - | - | +| 2678 | [Number of Senior Citizens](https://leetcode.com/problems/number-of-senior-citizens/) | [无] | [C++](2501-3000/2678-Number-of-Senior-Citizens/cpp-2678/) | | | +| 2679 | [Sum in a Matrix](https://leetcode.com/problems/sum-in-a-matrix/) | [无] | [C++](2501-3000/2679-Sum-in-a-Matrix/cpp-2679/) | | | +| 2680 | [Maximum OR](https://leetcode.com/problems/maximum-or/) | [无] | [C++](2501-3000/2680-Maximum-OR/cpp-2680/) | | | +| 2681 | [Power of Heroes](https://leetcode.com/problems/power-of-heroes/) | [无] | [C++](2501-3000/2681-Power-of-Heroes/cpp-2681/) | | | +| 2682 | [Find the Losers of the Circular Game](https://leetcode.com/problems/find-the-losers-of-the-circular-game/) | [无] | [C++](2501-3000/2682-Find-the-Losers-of-the-Circular-Game/cpp-2682/) | | | +| 2683 | [Neighboring Bitwise XOR](https://leetcode.com/problems/neighboring-bitwise-xor/) | [无] | [C++](2501-3000/2683-Neighboring-Bitwise-XOR/cpp-2683/) | | | +| 2684 | [Maximum Number of Moves in a Grid](https://leetcode.com/problems/maximum-number-of-moves-in-a-grid/) | [无] | [C++](2501-3000/2684-Maximum-Number-of-Moves-in-a-Grid/cpp-2684/) | | | +| 2685 | [Count the Number of Complete Components](https://leetcode.com/problems/count-the-number-of-complete-components/) | [无] | [C++](2501-3000/2685-Count-the-Number-of-Complete-Components/cpp-2685/) | | | +| 2686 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 2687 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 2688 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 2689 | [Extract Kth Character From The Rope Tree](https://leetcode.com/problems/extract-kth-character-from-the-rope-tree/) | [无] | [C++](2501-3000/2689-Extract-Kth-Character-From-The-Rope-Tree/cpp-2689/) | | | +| 2690 | JavaScript Problem | - | - | - | - | +| 2691 | JavaScript Problem | - | - | - | - | +| 2692 | JavaScript Problem | - | - | - | - | +| 2693 | JavaScript Problem | - | - | - | - | +| 2694 | JavaScript Problem | - | - | - | - | +| 2695 | JavaScript Problem | - | - | - | - | +| 2696 | [Minimum String Length After Removing Substrings](https://leetcode.com/problems/minimum-string-length-after-removing-substrings/) | [无] | [C++](2501-3000/2696-Minimum-String-Length-After-Removing-Substrings/cpp-2696/) | | | +| 2697 | [Lexicographically Smallest Palindrome](https://leetcode.com/problems/lexicographically-smallest-palindrome/) | [无] | [C++](2501-3000/2697-Lexicographically-Smallest-Palindrome/cpp-2697/) | | | +| 2698 | [Find the Punishment Number of an Integer](https://leetcode.com/problems/find-the-punishment-number-of-an-integer/) | [无] | [C++](2501-3000/2698-Find-the-Punishment-Number-of-an-Integer/cpp-2698/) | | | +| 2699 | [Modify Graph Edge Weights](https://leetcode.com/problems/modify-graph-edge-weights/) | [无] | [C++](2501-3000/2699-Modify-Graph-Edge-Weights/cpp-2699/) | | | +| 2700 | JavaScript Problem | - | - | - | - | +| 2701 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 2702 | [Minimum Operations to Make Numbers Non-positive](https://leetcode.com/problems/minimum-operations-to-make-numbers-non-positive/description/) | [无] | [C++](2501-3000/2702-Minimum-Operations-to-Make-Numbers-Non-positive/cpp-2702/) | | | +| 2703 | JavaScript Problem | - | - | - | - | +| 2704 | JavaScript Problem | - | - | - | - | +| 2705 | JavaScript Problem | - | - | - | - | +| 2706 | [Buy Two Chocolates](https://leetcode.com/problems/buy-two-chocolates/) | [无] | [C++](2501-3000/2706-Buy-Two-Chocolates/cpp-2706/) | | | +| 2707 | [Extra Characters in a String](https://leetcode.com/problems/extra-characters-in-a-string/) | [无] | [C++](2501-3000/2707-Extra-Characters-in-a-String/cpp-2707/) | | | +| 2708 | [Maximum Strength of a Group](https://leetcode.com/problems/maximum-strength-of-a-group/) | [无] | [C++](2501-3000/2708-Maximum-Strength-of-a-Group/cpp-2708/) | | | +| 2709 | [Greatest Common Divisor Traversal](https://leetcode.com/problems/greatest-common-divisor-traversal/) | [无] | [C++](2501-3000/2709-Greatest-Common-Divisor-Traversal/cpp-2709/) | | | +| 2710 | [Remove Trailing Zeros From a String](https://leetcode.com/problems/remove-trailing-zeros-from-a-string/) | [无] | [C++](2501-3000/2710-Remove-Trailing-Zeros-From-a-String/cpp-2710/) | | | +| 2711 | [Difference of Number of Distinct Values on Diagonals](https://leetcode.com/problems/difference-of-number-of-distinct-values-on-diagonals/) | [无] | [C++](2501-3000/2711-Difference-of-Number-of-Distinct-Values-on-Diagonals/cpp-2711/) | | | +| 2712 | [Minimum Cost to Make All Characters Equal](https://leetcode.com/problems/minimum-cost-to-make-all-characters-equal/) | [无] | [C++](2501-3000/2712-Minimum-Cost-to-Make-All-Characters-Equal/cpp-2712/) | | | +| 2713 | [Maximum Strictly Increasing Cells in a Matrix](https://leetcode.com/problems/maximum-strictly-increasing-cells-in-a-matrix/) | [无] | [C++](2501-3000/2713-Maximum-Strictly-Increasing-Cells-in-a-Matrix/cpp-2713/) | | | +| 2714 | [Find Shortest Path with K Hops](https://leetcode.com/problems/find-shortest-path-with-k-hops/description/) | [无] | [C++](2501-3000/2714-Find-Shortest-Path-with-K-Hops/cpp-2714/) | | | +| 2715 | JavaScript Problem | - | - | - | - | +| 2716 | [Minimize String Length](https://leetcode.com/problems/minimize-string-length/) | [无] | [C++](2501-3000/2716-Minimize-String-Length/cpp-2716/) | | | +| 2717 | [Semi-Ordered Permutation](https://leetcode.com/problems/semi-ordered-permutation/) | [无] | [C++](2501-3000/2717-Semi-Ordered-Permutation/cpp-2717/) | | | +| 2718 | [Sum of Matrix After Queries](https://leetcode.com/problems/sum-of-matrix-after-queries/) | [无] | [C++](2501-3000/2718-Sum-of-Matrix-After-Queries/cpp-2718/) | | | +| 2719 | [Count of Integers](https://leetcode.com/problems/count-of-integers/) | [无] | [C++](2501-3000/2719-Count-of-Integers/cpp-2719/) | | | +| 2720 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 2721 | JavaScript Problem | - | - | - | - | +| 2722 | JavaScript Problem | - | - | - | - | +| 2723 | JavaScript Problem | - | - | - | - | +| 2724 | JavaScript Problem | - | - | - | - | +| 2725 | JavaScript Problem | - | - | - | - | +| 2726 | JavaScript Problem | - | - | - | - | +| 2727 | JavaScript Problem | - | - | - | - | +| 2728 | [Count Houses in a Circular Street](https://leetcode.com/problems/count-houses-in-a-circular-street/description/) | [无] | [C++](2501-3000/2728-Count-Houses-in-a-Circular-Street/cpp-2728/) | | | +| 2729 | [Check if The Number is Fascinating](https://leetcode.com/problems/check-if-the-number-is-fascinating/) | [无] | [C++](2501-3000/2729-Check-if-The-Number-is-Fascinating/cpp-2729/) | | | +| 2730 | [Find the Longest Semi-Repetitive Substring](https://leetcode.com/problems/find-the-longest-semi-repetitive-substring/) | [无] | [C++](2501-3000/2730-Find-the-Longest-Semi-Repetitive-Substring/cpp-2730/) | | | +| 2731 | [Movement of Robots](https://leetcode.com/problems/movement-of-robots/) | [无] | [C++](2501-3000/2731-Movement-of-Robots/cpp-2731/) | | | +| 2732 | [Find a Good Subset of the Matrix](https://leetcode.com/problems/find-a-good-subset-of-the-matrix/) | [无] | [C++](2501-3000/2732-Find-a-Good-Subset-of-the-Matrix/cpp-2732/) | | | +| 2733 | [Neither Minimum nor Maximum](https://leetcode.com/problems/neither-minimum-nor-maximum/) | [无] | [C++](2501-3000/2733-Neither-Minimum-nor-Maximum/cpp-2733/) | | | +| 2734 | [Lexicographically Smallest String After Substring Operation](https://leetcode.com/problems/lexicographically-smallest-string-after-substring-operation/) | [无] | [C++](2501-3000/2734-Lexicographically-Smallest-String-After-Substring-Operation/cpp-2734/) | | | +| 2735 | [Collecting Chocolates](https://leetcode.com/problems/collecting-chocolates/) | [无] | [C++](2501-3000/2735-Collecting-Chocolates/cpp-2735/) | | | +| 2736 | [Maximum Sum Queries](https://leetcode.com/problems/maximum-sum-queries/) | [无] | [C++](2501-3000/2736-Maximum-Sum-Queries/cpp-2736/) | | | +| 2737 | [Find the Closest Marked Node](https://leetcode.com/problems/find-the-closest-marked-node/) | [无] | [C++](2501-3000/2737-Find-the-Closest-Marked-Node/cpp-2737/) | | | +| 2738 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| 2739 | [Total Distance Traveled](https://leetcode.com/problems/total-distance-traveled/) | [无] | [C++](2501-3000/2739-Total-Distance-Traveled/cpp-2739/) | | | +| 2740 | [Find the Value of the Partition](https://leetcode.com/problems/find-the-value-of-the-partition/) | [无] | [C++](2501-3000/2740-Find-the-Value-of-the-Partition/cpp-2740/) | | | +| 2741 | [Special Permutations](https://leetcode.com/problems/special-permutations/) | [无] | [C++](2501-3000/2741-Special-Permutations/cpp-2741/) | | | +| 2742 | [Painting the Walls](https://leetcode.com/problems/painting-the-walls/) | [无] | [C++](2501-3000/2742-Painting-the-Walls/cpp-2742/) | | | +| 2743 | [Count Substrings Without Repeating Character](https://leetcode.com/problems/count-substrings-without-repeating-character/description/) | [无] | [C++](2501-3000/2743-Count-Substrings-Without-Repeating-Character/cpp-2743/) | | | +| 2744 | [Find Maximum Number of String Pairs](https://leetcode.com/problems/find-maximum-number-of-string-pairs/) | [无] | [C++](2501-3000/2744-Find-Maximum-Number-of-String-Pairs/cpp-2744/) | | | +| 2745 | [Construct the Longest New String](https://leetcode.com/problems/construct-the-longest-new-string/) | [无] | [C++](2501-3000/2745-Construct-the-Longest-New-String/cpp-2745/) | | | +| 2746 | [Decremental String Concatenation](https://leetcode.com/problems/decremental-string-concatenation/) | [无] | [C++](2501-3000/2746-Decremental-String-Concatenation/cpp-2746/) | | | +| 2747 | [Count Zero Request Servers](https://leetcode.com/problems/count-zero-request-servers/) | [无] | [C++](2501-3000/2747-Count-Zero-Request-Servers/cpp-2747/) | | | +| 2748 | [Number of Beautiful Pairs](https://leetcode.com/problems/number-of-beautiful-pairs/) | [无] | [C++](2501-3000/2748-Number-of-Beautiful-Pairs/cpp-2748/) | | | +| 2749 | [Minimum Operations to Make the Integer Zero](https://leetcode.com/problems/minimum-operations-to-make-the-integer-zero/) | [无] | [C++](2501-3000/2749-Minimum-Operations-to-Make-the-Integer-Zero/cpp-2749/) | | | +| 2750 | [Ways to Split Array Into Good Subarrays](https://leetcode.com/problems/ways-to-split-array-into-good-subarrays/) | [无] | [C++](2501-3000/2750-Ways-to-Split-Array-Into-Good-Subarrays/cpp-2750/) | | | +| 2751 | [Robot Collisions](https://leetcode.com/problems/robot-collisions/) | [无] | [C++](2501-3000/2751-Robot-Collisions/cpp-2751/) | | | +| 2752 | Database Problem: [Link](https://github.com/liuyubobobo/Play-Leetcode-Database/) | - | - | - | - | +| | | | | | | +| 2754 | JavaScript Problem | - | - | - | - | +| 2755 | JavaScript Problem | - | - | - | - | +| 2756 | JavaScript Problem | - | - | - | - | +| 2757 | JavaScript Problem | - | - | - | - | +| 2758 | JavaScript Problem | - | - | - | - | +| 2759 | JavaScript Problem | - | - | - | - | +| 2760 | [Longest Even Odd Subarray With Threshold](https://leetcode.com/problems/longest-even-odd-subarray-with-threshold/) | [无] | [C++](2501-3000/2760-Longest-Even-Odd-Subarray-With-Threshold/cpp-2760/) | | | +| 2761 | [Prime Pairs With Target Sum](https://leetcode.com/problems/prime-pairs-with-target-sum/) | [无] | [C++](2501-3000/2761-Prime-Pairs-With-Target-Sum/cpp-2761/) | | | +| 2762 | [Continuous Subarrays](https://leetcode.com/problems/continuous-subarrays/) | [无] | [C++](2501-3000/2762-Continuous-Subarrays/cpp-2762/) | | | +| 2763 | [Sum of Imbalance Numbers of All Subarrays](https://leetcode.com/problems/sum-of-imbalance-numbers-of-all-subarrays/) | [无] | [C++](2501-3000/2763-Sum-of-Imbalance-Numbers-of-All-Subarrays/cpp-2763/) | | | +| | | | | | | +| 2849 | [Determine if a Cell Is Reachable at a Given Time](https://leetcode.com/problems/determine-if-a-cell-is-reachable-at-a-given-time/) | [无] | [C++](2501-3000/2849-Determine-if-a-Cell-Is-Reachable-at-a-Given-Time/cpp-2849/) | | | | | | | | | | -| 811 | [Subdomain Visit Count](https://leetcode.com/problems/subdomain-visit-count/description/) | [solution](https://leetcode.com/problems/subdomain-visit-count/solution/) | [C++](0811-Subdomain-Visit-Count/cpp-0811/) | | | \ No newline at end of file + +### 力扣中文站比赛 [传送门](LC/) + +### 力扣中文站其他比赛 [传送门](Others/) diff --git a/zsxq.jpg b/zsxq.jpg new file mode 100644 index 00000000..1004670d Binary files /dev/null and b/zsxq.jpg differ