Skip to content

Commit c7aa1ff

Browse files
author
Linh Chu
committedOct 20, 2017
Added Week3 p1 and p2
1 parent 4adffb4 commit c7aa1ff

File tree

2 files changed

+78
-0
lines changed

2 files changed

+78
-0
lines changed
 

‎Week 3/week3_problem1.cpp

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
#include <iostream>
2+
#include <vector>
3+
#include <algorithm>
4+
5+
using namespace std;
6+
7+
int main() {
8+
int N;
9+
int Q;
10+
int cc = 0;
11+
while(cin >> N && ++cc) {
12+
cin >> Q;
13+
vector<int> data(N);
14+
for(int i = 0; i < N; i++) {
15+
cin >> data[i];
16+
}
17+
if (!Q)
18+
continue;
19+
sort(data.begin(), data.end());
20+
cout << "CASE# " << cc << ":\n";
21+
for (int i = 0; i < Q; i++) {
22+
int q;
23+
cin >> q;
24+
auto it = lower_bound(data.begin(), data.end(), q);
25+
if (*it == q)
26+
cout << q << " found at " << it - data.begin() + 1 << '\n';
27+
else
28+
cout << q << " not found\n";
29+
}
30+
}
31+
}

‎Week 3/week3_problem2.cpp

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
#include <iostream>
2+
#include <vector>
3+
4+
using namespace std;
5+
6+
class Solution {
7+
public:
8+
bool searchMatrix(vector<vector<int>>& matrix, int target) {
9+
int N, M;
10+
if (matrix.size() == 0) return false;
11+
N = matrix.size();
12+
M = matrix[0].size();
13+
long long low, high;
14+
low = 0; high = N * M - 1;
15+
16+
while (low <= high) {
17+
long long mid = (low + high) / 2;
18+
if (matrix[mid/M][mid%M] == target) return true;
19+
else if (matrix[mid/M][mid%M] < target) {
20+
low = mid + 1;
21+
} else {
22+
high = mid - 1;
23+
}
24+
}
25+
26+
return false;
27+
}
28+
};
29+
30+
31+
int main(){
32+
int N, M;
33+
cin >> N >> M;
34+
vector<vector<int> > table(N);
35+
for (int i = 0; i < N; i++){
36+
table[i].resize(M);
37+
for (int j = 0; j < M; j++) {
38+
cin >> table[i][j];
39+
}
40+
}
41+
int t;
42+
cin >> t;
43+
Solution solution;
44+
cout << solution.searchMatrix(table, t) << '\n';
45+
}
46+
47+

0 commit comments

Comments
 (0)
Please sign in to comment.