From 39bd375b16b579963abe8d4067dce4f0ec42e6ce Mon Sep 17 00:00:00 2001 From: Manish Date: Thu, 2 Mar 2023 12:15:45 +1100 Subject: [PATCH] Design Pattern 3: Two Pointers | Problem: Squares of a Sorted Array --- 3_squares_of_a_sorted_array.cpp | 47 +++++++++++++++++++++++++++++++++ CMakeLists.txt | 2 ++ 2 files changed, 49 insertions(+) create mode 100644 3_squares_of_a_sorted_array.cpp diff --git a/3_squares_of_a_sorted_array.cpp b/3_squares_of_a_sorted_array.cpp new file mode 100644 index 0000000..a983b88 --- /dev/null +++ b/3_squares_of_a_sorted_array.cpp @@ -0,0 +1,47 @@ +/* Problem source: https://leetcode.com/problems/squares-of-a-sorted-array/ + */ + +#include +#include + +template inline T absolute(T num) { + return num > -num ? num : -num; +} + +template inline T square(T num) { return num * num; } + +template +std::vector &solution(const std::vector &sorted_input) { + std::vector *result = new std::vector(sorted_input.size()); + std::vector &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 &result = solution(std::vector{-4, -1, 0, 3, 10}); + for (const int num : result) + std::cout << num << ", "; + std::cout << std::endl; + delete &result; +} \ No newline at end of file diff --git a/CMakeLists.txt b/CMakeLists.txt index d06b453..3c7fde9 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -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)