当前位置:网站首页>【1200. 最小绝对差】
【1200. 最小绝对差】
2022-07-04 19:36: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
边栏推荐
- How to adapt your games to different sizes of mobile screen
- 浏览器渲染页面过程
- idea配置标准注释
- Alibaba testers use UI automated testing to achieve element positioning
- From automation to digital twins, what can Tupo do?
- 精选综述 | 用于白内障分级/分类的机器学习技术
- Win11亮度被锁定怎么办?Win11亮度被锁定的解决方法
- Talking about cookies of client storage technology
- Flet教程之 04 FilledTonalButton基础入门(教程含源码)
- LeetCode 871. Minimum refueling times
猜你喜欢
电脑怎么保存网页到桌面上使用
字节测试工程师十年经验直击UI 自动化测试痛点
Every time I look at the interface documents of my colleagues, I get confused and have a lot of problems...
科普达人丨一文看懂阿里云的秘密武器“神龙架构”
Automatic generation of interface automatic test cases by actual operation
Practical examples of node strong cache and negotiation cache
RFID仓库管理系统解决方案有哪些功能模块
See how Tencent does interface automation testing
Win11亮度被锁定怎么办?Win11亮度被锁定的解决方法
Win11无法将值写入注册表项如何解决?
随机推荐
ICML 2022 | meta proposes a robust multi-objective Bayesian optimization method to effectively deal with input noise
九齐单片机NY8B062D单按键控制4种LED状态
Qt五子棋人机对战画棋子之QPainter的使用误区总结
BFC interview Brief
Flet tutorial 06 basic introduction to textbutton (tutorial includes source code)
Win11怎么搜索无线显示器?Win11查找无线显示器设备的方法
左右最值最大差问题
word中插入图片后,图片上方有一空行,且删除后布局变乱
Hands on deep learning (III) -- convolutional neural network CNN
精选综述 | 用于白内障分级/分类的机器学习技术
Go notes (3) usage of go language FMT package
What should I do if my computer sharing printer refuses access
Implementation of redis distributed lock
idea配置标准注释
伦敦银走势图分析的新方法
Advantages of semantic tags and block level inline elements
Managed service network: application architecture evolution in the cloud native Era
From automation to digital twins, what can Tupo do?
Flet教程之 04 FilledTonalButton基础入门(教程含源码)
【深度学习】一文看尽Pytorch之十九种损失函数