From 9190e5ba1c56b1cd3691fd2ae255bd25f299bbba Mon Sep 17 00:00:00 2001 From: Eat-Swap Date: Wed, 15 Jun 2022 14:25:45 +0800 Subject: [PATCH] add: 220615-CN --- cpp/2206/220615-CN.cpp | 31 +++++++++++++++++++++++++++++++ cpp/2206/CMakeLists.txt | 2 +- 2 files changed, 32 insertions(+), 1 deletion(-) create mode 100644 cpp/2206/220615-CN.cpp diff --git a/cpp/2206/220615-CN.cpp b/cpp/2206/220615-CN.cpp new file mode 100644 index 0000000..24654d6 --- /dev/null +++ b/cpp/2206/220615-CN.cpp @@ -0,0 +1,31 @@ +#include +#include + +/** + * 719. Find K-th Smallest Pair Distance + * The distance of a pair of integers a and b is defined as the absolute difference between a and b. + * Given an integer array nums and an integer k, return the kth smallest distance among all the pairs nums[i] and nums[j] where 0 <= i < j < nums.length. + */ + +class Solution { +public: + static int smallestDistancePair(std::vector& nums, int k) { + const int n = nums.size(); + std::sort(nums.begin(), nums.end()); + int L = 0, R = nums.back(); + while (L < R) { + int M = (L + R) >> 1; + int i = 0, c = 0; + for (int j = 0; j < n; ++j) { + while (nums[j] - nums[i] > M) + ++i; + c += j - i; + } + if (c >= k) + R = M; + else + L = M + 1; + } + return L; + } +}; diff --git a/cpp/2206/CMakeLists.txt b/cpp/2206/CMakeLists.txt index 9f31d6f..3c4ac2a 100644 --- a/cpp/2206/CMakeLists.txt +++ b/cpp/2206/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2206) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2206 220615.cpp) +ADD_EXECUTABLE(2206 220615-CN.cpp)