diff --git a/Topic1_Arrays/Day2207/excercise_3.cpp b/Topic1_Arrays/Day2207/excercise_3.cpp new file mode 100644 index 0000000..6dc1b38 --- /dev/null +++ b/Topic1_Arrays/Day2207/excercise_3.cpp @@ -0,0 +1,31 @@ +// Use the two pointers technique to solve the problem +// Time complexity : O(m + n) +// Space complexity: O(m + n) (due to creating a new vector to store the output) + +class Solution { +public: + void merge(vector& nums1, int m, vector& nums2, int n) { + vector tmp; + tmp = nums1; + int pointer1 = 0, pointer2 = 0, index = 0; + while (pointer1 < m && pointer2 < n) { + if (tmp[pointer1] < nums2[pointer2]) { + nums1[index] = tmp[pointer1]; + pointer1++; index++; + } else { + nums1[index] = nums2[pointer2]; + pointer2++; index++; + } + } + while (pointer1 < m) { + nums1[index] = tmp[pointer1]; + pointer1++; + index++; + } + while (pointer2 < n) { + nums1[index] = nums2[pointer2]; + pointer2++; + index++; + } + } +}; \ No newline at end of file diff --git a/Topic1_Arrays/Day2207/exercise_1.cpp b/Topic1_Arrays/Day2207/exercise_1.cpp new file mode 100644 index 0000000..42e7f45 --- /dev/null +++ b/Topic1_Arrays/Day2207/exercise_1.cpp @@ -0,0 +1,18 @@ +// Use nested loop to calculate all the possible cases and find the answer +// Time complexity : O(n^2) +// Space complexity: O(1) (because no extra spaces are needed) +#include +class Solution { +public: + void 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}; + } + } + } + //return {-1, -1}; + } +}; + diff --git a/Topic1_Arrays/Day2207/exercise_2.cpp b/Topic1_Arrays/Day2207/exercise_2.cpp new file mode 100644 index 0000000..75f5553 --- /dev/null +++ b/Topic1_Arrays/Day2207/exercise_2.cpp @@ -0,0 +1,30 @@ +// Use DFS to count the number of islands +// Time complexity : O(n^2) +// Space complexity : O(n) (The number of recusive function calls in the call stack) +class Solution { +public: + int dx[4] = {-1, 0, 0, 1}; + int dy[4] = {0, -1, 1, 0}; + void loang(int i, int j, vector>& grid) { + grid[i][j] = '0'; + for (int k = 0; k < 4; k++) { + int i1 = i + dx[k], j1 = j + dy[k]; + if (i1 >= 0 && i1 < grid.size() && j1 >= 0 && j1 < grid[i].size() && + grid[i1][j1] == '1') { + loang(i1, j1, grid); + } + } + } + int numIslands(vector>& grid) { + int res = 0; + for (int i = 0; i < grid.size(); i++) { + for (int j = 0; j < grid[i].size(); j++) { + if (grid[i][j] == '1') { + loang(i, j, grid); + res++; + } + } + } + return res; + } +}; \ No newline at end of file