当前位置:网站首页>【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
边栏推荐
猜你喜欢
实操自动生成接口自动化测试用例
Win11怎么搜索无线显示器?Win11查找无线显示器设备的方法
What should I do if my computer sharing printer refuses access
FS8B711S14电动红酒开瓶器单片机IC方案开发专用集成IC
精选综述 | 用于白内障分级/分类的机器学习技术
伦敦银走势图分析的新方法
So this is the BGP agreement
The concept and application of hash table
How does wincc7.5 SP1 find variables and their positions through cross indexing?
【观察】联想:3X(1+N)智慧办公解决方案,释放办公生产力“乘数效应”
随机推荐
What if win11u disk refuses access? An effective solution to win11u disk access denial
In the face of the same complex test task, why can the elder sort out the solution quickly? Ali's ten-year test engineers showed their skills
电脑共享打印机拒绝访问要怎么办
Qt五子棋人机对战画棋子之QPainter的使用误区总结
Flet教程之 04 FilledTonalButton基础入门(教程含源码)
二叉树的四种遍历方式以及中序后序、前序中序、前序后序、层序创建二叉树【专为力扣刷题而打造】
Function analysis and source code of hash guessing game system development
Implementation of redis distributed lock
BFC面试简述
接口設計時的一些建議
Reinforcement learning - learning notes 2 | value learning
电脑页面不能全屏怎么办?Win11页面不能全屏的解决方法
Go notes (1) go language introduction and characteristics
【解决方案】PaddlePaddle 2.x调用静态图模式
Go language notes (4) go common management commands
Hash哈希竞猜游戏系统开发如何开发丨哈希竞猜游戏系统开发(多套案例)
Go language notes (2) some simple applications of go
acwing 3302. Expression evaluation
Cdga | six principles that data governance has to adhere to
Four traversal methods of binary tree, as well as the creation of binary tree from middle order to post order, pre order to middle order, pre order to post order, and sequence [specially created for t