当前位置:网站首页>【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
边栏推荐
- Fleet tutorial 08 introduction to AppBar toolbar Basics (tutorial includes source code)
- hash 表的概念及应用
- tcp为啥是三次握手和四次挥手
- word中插入图片后,图片上方有一空行,且删除后布局变乱
- Win11亮度被锁定怎么办?Win11亮度被锁定的解决方法
- GVM使用
- Why is TCP three handshakes and four waves
- Go notes (1) go language introduction and characteristics
- 左右最值最大差问题
- Flet教程之 08 AppBar工具栏基础入门(教程含源码)
猜你喜欢
Selected review | machine learning technology for Cataract Classification / classification
6月“墨力原创作者计划”获奖名单公布!邀您共话国产数据库
FS8B711S14电动红酒开瓶器单片机IC方案开发专用集成IC
How does the computer save web pages to the desktop for use
Reinforcement learning - learning notes 2 | value learning
idea恢复默认快捷键
How does win11 search for wireless displays? Win11 method of finding wireless display device
Practice examples to understand JS strong cache negotiation cache
黄金k线图中的三角形有几种?
托管式服务网络:云原生时代的应用体系架构进化
随机推荐
acwing 3302. 表达式求值
word中插入圖片後,圖片上方有一空行,且删除後布局變亂
Flet tutorial 04 basic introduction to filledtonalbutton (tutorial includes source code)
NLP, vision, chip What is the development direction of AI? Release of the outlook report of Qingyuan Association [download attached]
Six stones programming: about code, there are six triumphs
go语言笔记(2)go一些简单运用
See how Tencent does interface automation testing
The concept and application of hash table
What if the win11 shared file cannot be opened? The solution of win11 shared file cannot be opened
Summary of the mistakes in the use of qpainter in QT gobang man-machine game
WinCC7.5 SP1如何通过交叉索引来寻找变量及其位置?
【ISMB2022教程】图表示学习的精准医疗,哈佛大学Marinka Zitnik主讲,附87页ppt
What if the brightness of win11 is locked? Solution to win11 brightness locking
vim异步问题
ICML 2022 | meta proposes a robust multi-objective Bayesian optimization method to effectively deal with input noise
【服务器数据恢复】某品牌服务器存储raid5数据恢复案例
Automatic generation of interface automatic test cases by actual operation
Why is the maximum speed the speed of light
MySQL statement execution details
Form组件常用校验规则-1(持续更新中~)