当前位置:网站首页>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
边栏推荐
猜你喜欢

Pointnet++ learning

【Jailhouse 文章】Jailhouse Hypervisor

Scope of inline symbol

CF1634E Fair Share

Educational Codeforces Round 116 (Rated for Div. 2) E. Arena

Palindrome (csp-s-2021-palin) solution

剑指 Offer 04. 二维数组中的查找

EOJ 2021.10 E. XOR tree

Introduction et expérience de wazuh open source host Security Solution

In this indifferent world, light crying
随机推荐
Simple knapsack, queue and stack with deque
Bit mask of bit operation
Fried chicken nuggets and fifa22
Detailed explanation of expression (csp-j 2021 expr) topic
全排列的代码 (递归写法)
Educational Codeforces Round 116 (Rated for Div. 2) E. Arena
Analysis of backdoor vulnerability in remote code execution penetration test / / phpstudy of national game title of national secondary vocational network security B module
Dynamic planning solution ideas and summary (30000 words)
The sum of the unique elements of the daily question
Corridor and bridge distribution (csp-s-2021-t1) popular problem solution
Introduction and experience of wazuh open source host security solution
Solution to the palindrome string (Luogu p5041 haoi2009)
R语言【数据集的导入导出】
Haut OJ 1401: praise energy
【实战技能】非技术背景经理的技术管理
Wazuh开源主机安全解决方案的简介与使用体验
个人开发的渗透测试工具Satania v1.2更新
Control unit
Sword finger offer 06 Print linked list from beginning to end
Hang wait lock vs spin lock (where both are used)