-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQ29.cpp
More file actions
72 lines (52 loc) · 1.62 KB
/
Q29.cpp
File metadata and controls
72 lines (52 loc) · 1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// 29.Write a program to find all pairs in an array whose sum is equal to a given number.: Example 1: Input: nums = [2,7,11,15], target = 9 , Output: [0,1].
#include <iostream>
using namespace std;
void findPairsBruteForce(int nums[], int n, int target) {
bool foundPair = false;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (nums[i] + nums[j] == target) {
cout << "[" << i << ", " << j << "]" << endl;
foundPair = true;
}
}
}
if (!foundPair) {
cout << "No pairs found!" << endl;
}
}
int main() {
int nums[] = {2, 7, 11, 15};
int n = sizeof(nums) / sizeof(nums[0]);
int target = 9;
cout << "Pairs with sum " << target << ":" << endl;
findPairsBruteForce(nums, n, target);
return 0;
}
#include <iostream>
using namespace std;
void findPairsHashMap(int nums[], int n, int target) {
bool foundPair = false;
bool seen[1000] = {false};
for (int i = 0; i < n; i++) {
int complement = target - nums[i];
if (complement >= 0 && complement < 1000 && seen[complement]) {
cout << "[" << complement << ", " << nums[i] << "]" << endl;
foundPair = true;
}
if (nums[i] >= 0 && nums[i] < 1000) {
seen[nums[i]] = true;
}
}
if (!foundPair) {
cout << "No pairs found!" << endl;
}
}
int main() {
int nums[] = {2, 7, 11, 15};
int n = sizeof(nums) / sizeof(nums[0]);
int target = 9;
cout << "Pairs with sum " << target << ":" << endl;
findPairsHashMap(nums, n, target);
return 0;
}