defcheck(mid: int) -> int: # 計算距離 <= mid 的 pair 數量 res = left = 0 for right, x inenumerate(nums): # 枚舉右端點 right while x - nums[left] > mid: # 移動左端點直到滿足條件為止 left += 1 res += right - left # (left, right), (left+1, right), ..., (right-1, right) 距離都小於等於 mid return res # 對答案做二分搜尋 return bisect_left(range(nums[n-1] - nums[0]), k, key=check)
classSolution { public: intsmallestDistancePair(vector<int>& nums, int k){ int n = nums.size(); sort(nums.begin(), nums.end()); // 由小到大排序
function<int(int)> check = [&](int mid) { // 計算距離 <= mid 的 pair 數量 int res = 0, l = 0; for (int r = 0; r < n; r++) { // 枚舉右端點 r while (nums[r] - nums[l] > mid) { // 移動左端點直到滿足條件為止 l++; } res += r - l; // (l, r), (l+1, r), ..., (r-1, r) 距離都小於等於 mid } return res; };
// 對答案做二分搜尋 int left = 0, right = nums[n-1] - nums[0]; while (left <= right) { int mid = left + (right - left) / 2; if (check(mid) >= k) right = mid - 1; else left = mid + 1; } return left; } };
寫在最後
PROMPT
masterpiece, best quality, high quality,extremely detailed CG unity 8k wallpaper, extremely detailed, High Detail, colors,
(1girl, solo), (idol, idol costume), long hair, black hair, dress, bow, standing, detached sleeves, white dress, hand on hip, curtains, pointing, pointing at self, stage, on stage,
A young girl wearing a lavish purple dress with puffy sleeves and a layered skirt, Her hair is styled in twin tails with purple bows, The background is a dark blue curtain, She is smiling and posing cutely,
雖然程式碼可能就短短幾行,但寫 Hard 的解題紀錄除了相比於 Easy 和 Medium 需要花更多的時間外,也需要注意到更多東西。但在完整闡述思考過程後,還是有助於自己釐清思路。