Design Pattern 3: Two Pointers | Problem: Squares of a Sorted Array

main
Manish 1 year ago
parent 269bb657a6
commit 39bd375b16

@ -0,0 +1,47 @@
/* Problem source: https://leetcode.com/problems/squares-of-a-sorted-array/
*/
#include <iostream>
#include <vector>
template <typename T> inline T absolute(T num) {
return num > -num ? num : -num;
}
template <typename T> inline T square(T num) { return num * num; }
template <typename T>
std::vector<T> &solution(const std::vector<T> &sorted_input) {
std::vector<T> *result = new std::vector<T>(sorted_input.size());
std::vector<T> &sorted_output = *result;
unsigned long long p1 = 0, p2 = 1;
while (p2 < sorted_input.size()) {
if (absolute(sorted_input[p2]) <= absolute(sorted_input[p1]))
p1 = p2++;
else
break;
}
// std::cout << sorted_input[p1] << ", " << sorted_input[p2] << "\n";
unsigned long long output_p = 0;
while (p1 < p2 && p2 < sorted_input.size()) {
if (absolute(sorted_input[p1]) < absolute(sorted_input[p2]))
sorted_output[output_p++] = (square(sorted_input[p1--]));
else
sorted_output[output_p++] = square(sorted_input[p2++]);
}
while (p1 < p2)
sorted_output[output_p++] = square(sorted_input[p1--]);
while (p2 < sorted_input.size())
sorted_output[output_p++] = square(sorted_input[p2++]);
return sorted_output;
}
int main() {
std::vector<int> &result = solution(std::vector{-4, -1, 0, 3, 10});
for (const int num : result)
std::cout << num << ", ";
std::cout << std::endl;
delete &result;
}

@ -10,3 +10,5 @@ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -Werror -g")
add_executable(1_longest_substring_with_k_distinct_characters 1_longest_substring_with_k_distinct_characters.cpp)
add_executable(2_num_of_islands 2_num_of_islands.cpp)
add_executable(3_squares_of_a_sorted_array 3_squares_of_a_sorted_array.cpp)

Loading…
Cancel
Save