-
Notifications
You must be signed in to change notification settings - Fork 0
/
Find the Pivot Integer.cpp
76 lines (55 loc) · 1.37 KB
/
Find the Pivot Integer.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
class Solution {
public:
int firstHalf(int start, int mid) {
int sum = 0;
for (int i = start; i <= mid; ++i) {
sum += i;
}
return sum;
}
int secondHalf(int mid, int end) {
int sum = 0;
for (int i = mid; i <= end; ++i) {
sum += i;
}
return sum;
}
int pivotInteger(int n) {
int start = 0;
int end = n;
while (start <= end) {
int mid = start + (end - start) / 2;
int sum1 = firstHalf(1, mid);
int sum2 = secondHalf(mid, n);
if (sum1 == sum2) {
return mid;
} else if (sum1 > sum2) {
end = mid - 1;
} else {
start = mid + 1;
}
}
return -1;
}
};
//approach 2
class Solution {
public:
int pivotInteger(int n) {
if(n ==1 ){
return 1;
}
int total_sum = (n*(n+1))/2;
int prefix_sum = 0 ;
for(int i = 1; i < n ; i++){
prefix_sum += i;
if(prefix_sum == (total_sum+i)/2.0 ){
return i;
}
if(prefix_sum > ceil((total_sum+i)/2.0) ){
break;
}
}
return -1;
}
};