-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathFlippingAnImage.cpp
More file actions
72 lines (68 loc) · 1.86 KB
/
Copy pathFlippingAnImage.cpp
File metadata and controls
72 lines (68 loc) · 1.86 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
// Best solution
// First we iterate through each row and find the start and end pointer for each
// then we check if the start of array is equal to end of array
// If yes, we'll reverse the values in both elements
// After Flipping and inverting the image only those values which were equal for start and end
// pointer will change
class Solution
{
public:
vector<vector<int>> flipAndInvertImage(vector<vector<int>> &A)
{
for (int i = 0; i < A.size(); i++)
{
int start = 0;
int end = A.size() - 1;
while (start <= end)
{
if (A[i][start] == A[i][end])
{
A[i][start] = 1 - A[i][start];
A[i][end] = A[i][start];
}
start++;
end--;
}
}
return A;
}
};
// Time Complexity - O(n)
// Space Complexity - O(1)
// Other solution (Long solution)
// first flip the image and then invert the elements there itself
class Solution
{
public:
vector<vector<int>> flipAndInvertImage(vector<vector<int>> &A)
{
// flip image
for (int i = 0; i < A.size(); i++)
{
int start = 0;
int n = A[i].size() - 1;
while (start <= n)
{
if (A[i][start] == 0)
A[i][start] = 1;
else
A[i][start] = 0;
if (start != n)
{
if (A[i][n] == 1)
A[i][n] = 0;
else
A[i][n] = 1;
}
int temp = A[i][start];
A[i][start] = A[i][n];
A[i][n] = temp;
start++;
n--;
}
}
return A;
}
};
// Time Complexity - O(n)
// Space Complexity - O(1)