当前位置:网站首页>【1200. 最小絕對差】
【1200. 最小絕對差】
2022-07-04 20:56:00 【千北@】
來源:力扣(LeetCode)
描述:
給你個整數數組 arr,其中每個元素都 不相同。
請你找到所有具有最小絕對差的元素對,並且按昇序的順序返回。
示例 1:
輸入:arr = [4,2,1,3]
輸出:[[1,2],[2,3],[3,4]]
示例 2:
輸入:arr = [1,3,6,10,15]
輸出:[[1,3]]
示例 3:
輸入:arr = [3,8,-10,23,19,-4,-14,27]
輸出:[[-14,-10],[19,23],[23,27]]
提示:
- 2 <= arr.length <= 105
- -106 <= arr[i] <= 106
方法:排序 + 一次遍曆
思路與算法

代碼:
class Solution {
public:
vector<vector<int>> minimumAbsDifference(vector<int>& arr) {
int n = arr.size();
sort(arr.begin(), arr.end());
int best = INT_MAX;
vector<vector<int>> ans;
for (int i = 0; i < n - 1; ++i) {
if (int delta = arr[i + 1] - arr[i]; delta < best) {
best = delta;
ans = {
{
arr[i], arr[i + 1]}};
}
else if (delta == best) {
ans.emplace_back(initializer_list<int>{
arr[i], arr[i + 1]});
}
}
return ans;
}
};
執行用時:52 ms, 在所有 C++ 提交中擊敗了98.35%的用戶
內存消耗:31.3 MB, 在所有 C++ 提交中擊敗了86.32%的用戶
author:LeetCode-Solution
边栏推荐
- What if the win11 shared file cannot be opened? The solution of win11 shared file cannot be opened
- 奏响青春的乐章
- Form组件常用校验规则-1(持续更新中~)
- vim异步问题
- mysql语句执行详解
- Length of the longest integrable subarray
- 【观察】联想:3X(1+N)智慧办公解决方案,释放办公生产力“乘数效应”
- Why is TCP three handshakes and four waves
- Go notes (3) usage of go language FMT package
- idea插件
猜你喜欢
随机推荐
NLP, vision, chip What is the development direction of AI? Release of the outlook report of Qingyuan Association [download attached]
扩展你的KUBECTL功能
[in-depth learning] review pytoch's 19 loss functions
精选综述 | 用于白内障分级/分类的机器学习技术
Win11无法将值写入注册表项如何解决?
Flet tutorial 04 basic introduction to filledtonalbutton (tutorial includes source code)
看腾讯大老如何做接口自动化测试
What if win11u disk refuses access? An effective solution to win11u disk access denial
After inserting a picture into word, there is a blank line above the picture, and the layout changes after deletion
Is it safe for Great Wall Securities to open an account? Stock account opening process online account opening
idea配置标准注释
Leetcode+ 81 - 85 monotone stack topic
Flet教程之 05 OutlinedButton基础入门(教程含源码)
强化学习-学习笔记2 | 价值学习
Common verification rules of form components -1 (continuously updating ~)
Function analysis and source code of hash guessing game system development
What if the WiFi of win11 system always drops? Solution of WiFi total drop in win11 system
FS8B711S14电动红酒开瓶器单片机IC方案开发专用集成IC
Win11系统wifi总掉线怎么办?Win11系统wifi总掉线的解决方法
mysql语句执行详解










