-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Three_Sum.cpp
91 lines (82 loc) · 1.68 KB
/
Three_Sum.cpp
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/*
Description :
Three Sum Problem - In this problem, user will provide an array and we
have find wether there is any "three" numbers are
present in the array who's sum is equal to the target
provided. If it is present then it will show true else
it will show false.
*/
#include <bits/stdc++.h>
using namespace std;
int main()
{
// n= size of an array
int n;
cout << "Enter the size of an array : " << endl;
cin >> n;
//target = the number who's sum we have find.
int target;
cout << "Enter the target you want to set : " cin >> target;
//n size of array
vector<int> a(n);
//taking input in the array
cout << "Enter " << n << " number of elements : " << emdl;
for (auto &i : a)
{
cin >> i;
}
bool found = false;
//sorting the array
sort(a.begin(), a.end());
for (int i = 0; i < n; i++)
{
int low = i + 1, high = n - 1;
while (low < high)
{
int current = a[i] + a[low] + a[high];
if (current == target)
{
found = true;
}
if (current < target)
{
low++;
}
else
{
high--;
}
}
}
if (found)
{
cout << "True : Target value is present !";
}
else
{
cout << "False : Target value is not present !";
}
}
/*
Time Complexity : O(n*n)
Space Complexity : O(n)
Test Cases :
Test Case 1:
Input :
Enter the size of an array :
6
Enter the target you want to set :
24
Enter 6 number of elements :
102 3 6 9 34 24
Output : True : Target value is present !
Test Case 2:
Input :
Enter the size of an array :
6
Enter the target you want to set :
24
Enter 6 number of elements :
2 3 6 9 3 25
Output : False : Target value is not present !
*/