Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions Topic1_Arrays/Day2207/excercise_3.cpp
Original file line number Diff line number Diff line change
@@ -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<int>& nums1, int m, vector<int>& nums2, int n) {
vector<int> 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++;
}
}
};
18 changes: 18 additions & 0 deletions Topic1_Arrays/Day2207/exercise_1.cpp
Original file line number Diff line number Diff line change
@@ -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 <bits/stdc++.h>
class Solution {
public:
void twoSum(vector<int>& nums, int target) {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thử thêm hướng sử dụng với Hashmap để giảm độ phức tạp

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};
}
};

30 changes: 30 additions & 0 deletions Topic1_Arrays/Day2207/exercise_2.cpp
Original file line number Diff line number Diff line change
@@ -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<vector<char>>& 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<vector<char>>& 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;
}
};