diff --git a/cpp/2207/220704-CN.cpp b/cpp/2207/220704-CN.cpp new file mode 100644 index 0000000..57ddda1 --- /dev/null +++ b/cpp/2207/220704-CN.cpp @@ -0,0 +1,42 @@ +#include +#include +#include + +/** + * 1200. Minimum Absolute Difference + * Given an array of distinct integers arr, find all pairs of elements with the minimum absolute difference of any two elements. + * Return a list of pairs in ascending order(with respect to pairs), each pair [a, b] follows + * a, b are from arr + * a < b + * b - a equals to the minimum absolute difference of any two elements in arr + */ + +class Solution { +public: + static std::vector> minimumAbsDifference(const std::vector& arr) { + std::set s; + int min_diff = 0x7FFFFFFF; + for (int i : arr) { + const auto [it, ok] = s.insert(i); + if (!ok) + continue; + if (it != s.begin()) + min_diff = std::min(min_diff, std::abs(*std::prev(it) - i)); + if (std::next(it) != s.end()) + min_diff = std::min(min_diff, std::abs(*std::next(it) - i)); + } + std::vector> ret; + int prev = -0x3FFFFFFF; + for (int i : s) { + if (i - prev == min_diff) + ret.push_back({prev, i}); + prev = i; + } + return ret; + } +}; + +int main() { + auto r = Solution::minimumAbsDifference({3,8,-10,23,19,-4,-14,27}); + return 0; +} diff --git a/cpp/2207/CMakeLists.txt b/cpp/2207/CMakeLists.txt index e9bb72e..282f09d 100644 --- a/cpp/2207/CMakeLists.txt +++ b/cpp/2207/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2207) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2207 220703.cpp) +ADD_EXECUTABLE(2207 220704-CN.cpp)