当前位置:网站首页>LeetCode 1200.最小绝对差
LeetCode 1200.最小绝对差
2022-07-05 05:45:00 【Tisfy】
【LetMeFly】1200.最小绝对差
力扣题目链接:https://leetcode.cn/problems/minimum-absolute-difference/
给你个整数数组 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 <= 10^5
-10^6 <= arr[i] <= 10^6
方法一:排序
这道题的数据范围是 1 0 5 10^5 105,因此无法 O ( n 2 ) O(n^2) O(n2)暴力
其实也不难,因为排序后“最小绝对差的元素对”一定相邻
所以我们直接排序即可,然后进行两次遍历
第一次求出绝对值只差的最小值,第二次把绝对值之差等于最小值的pair放入答案中即可。
- 时间复杂度 O ( n log n ) O(n\log n) O(nlogn),其中 n n n 是数组 arr \textit{arr} arr 的长度
- 空间复杂度 O ( log n ) O(\log n) O(logn),皆为排序所至
AC代码
C++
class Solution {
public:
vector<vector<int>> minimumAbsDifference(vector<int>& arr) {
sort(arr.begin(), arr.end());
int m = arr[1] - arr[0];
for (int i = 1; i < arr.size(); i++) {
m = min(m, arr[i] - arr[i - 1]);
}
vector<vector<int>> ans;
for (int i = 1; i < arr.size(); i++) {
if (arr[i] - arr[i - 1] == m) {
ans.push_back({
arr[i - 1], arr[i]});
}
}
return ans;
}
};
同步发文于CSDN,原创不易,转载请附上原文链接哦~
Tisfy:https://letmefly.blog.csdn.net/article/details/125609898
边栏推荐
- Use of room database
- Common optimization methods
- kubeadm系列-00-overview
- One question per day 1765 The highest point in the map
- Typical use cases for knapsacks, queues, and stacks
- CF1637E Best Pair
- Daily question 2006 Number of pairs whose absolute value of difference is k
- 剑指 Offer 05. 替换空格
- How many checks does kubedm series-01-preflight have
- Haut OJ 2021 freshmen week II reflection summary
猜你喜欢
【云原生】微服务之Feign自定义配置的记录
Corridor and bridge distribution (csp-s-2021-t1) popular problem solution
Implement an iterative stack
【实战技能】如何做好技术培训?
浅谈JVM(面试常考)
Introduction et expérience de wazuh open source host Security Solution
Sword finger offer 05 Replace spaces
Little known skills of Task Manager
Smart construction site "hydropower energy consumption online monitoring system"
剑指 Offer 09. 用两个栈实现队列
随机推荐
lxml. etree. XMLSyntaxError: Opening and ending tag mismatch: meta line 6 and head, line 8, column 8
智慧工地“水电能耗在线监测系统”
Remote upgrade afraid of cutting beard? Explain FOTA safety upgrade in detail
EOJ 2021.10 E. XOR tree
Educational Codeforces Round 116 (Rated for Div. 2) E. Arena
Codeforces Round #716 (Div. 2) D. Cut and Stick
【实战技能】非技术背景经理的技术管理
sync. Interpretation of mutex source code
[jailhouse article] performance measurements for hypervisors on embedded ARM processors
YOLOv5-Shufflenetv2
Wazuh開源主機安全解决方案的簡介與使用體驗
Educational codeforces round 109 (rated for Div. 2) C. robot collisions D. armchairs
CF1637E Best Pair
How many checks does kubedm series-01-preflight have
剑指 Offer 53 - II. 0~n-1中缺失的数字
Talking about JVM (frequent interview)
过拟合与正则化
用STM32点个灯
R语言【数据集的导入导出】
Gbase database helps the development of digital finance in the Bay Area