The Minimum Absolute Difference Algorithm of an Array
- 时间:2020-09-19 10:45:07
- 分类:网络文摘
- 阅读:130 次
Given an array of distinct integers arr, find all pairs of elements with the minimum absolute difference of any two elements. Return a list of pairs in ascending order(with respect to pairs), each pair [a, b] follows
a, b are from arr
a < b
b – a equals to the minimum absolute difference of any two elements in arrExample 1:
Input: arr = [4,2,1,3]
Output: [[1,2],[2,3],[3,4]]
Explanation: The minimum absolute difference is 1. List all pairs with difference equal to 1 in ascending order.Example 2:
Input: arr = [1,3,6,10,15]
Output: [[1,3]]Example 3:
Input: arr = [3,8,-10,23,19,-4,-14,27]
Output: [[-14,-10],[19,23],[23,27]]Constraints:
2 <= arr.length <= 10^5
-10^6 <= arr[i] <= 10^6Hints:
Find the minimum absolute difference between two elements in the array.
The minimum absolute difference must be a difference between two consecutive elements in the sorted array.
Finding Minimum Absolute Difference in a Sorted Array
Of course, we can bruteforce the array for each possible pair, and then we can compare and record the minimum pairs that have the smallest absolute difference values. However, this cost O(N^2), which is not the most efficient algorithm.
If we sort the array (which we can, in O(NLogN) time), then we can do another O(N) loop to compare only the adjacent elements because there is no need to compare non-neighbour pairs as they will not be the smallest minimum absolute difference pair.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | class Solution { public: vector<vector<int>> minimumAbsDifference(vector<int>& arr) { vector<vector<int>> r; sort(begin(arr), end(arr)); int D = INT_MAX; for (int i = 1; i < arr.size(); ++ i) { int d = arr[i] - arr[i - 1]; if (d < D) { r.clear(); D = d; r.push_back({arr[i - 1], arr[i]}); } else if (d == D) { r.push_back({arr[i - 1], arr[i]}); } } return r; } }; |
class Solution {
public:
vector<vector<int>> minimumAbsDifference(vector<int>& arr) {
vector<vector<int>> r;
sort(begin(arr), end(arr));
int D = INT_MAX;
for (int i = 1; i < arr.size(); ++ i) {
int d = arr[i] - arr[i - 1];
if (d < D) {
r.clear();
D = d;
r.push_back({arr[i - 1], arr[i]});
} else if (d == D) {
r.push_back({arr[i - 1], arr[i]});
}
}
return r;
}
};Then, if the current difference value is smaller, then we clear the result vector, record the minimum value, and push the current pair. If we find a equal pair, we simply push it to the back of the result vector. O(1) constant space is required.
–EOF (The Ultimate Computing & Technology Blog) —
推荐阅读:豆腐味美又养生,做一道家常菜让你胃口大开 女性在特殊时期饮食需要注意,不能吃这些食物 此菜肴脆嫩爽口肉香浓郁且色香味俱全,为冬季百吃不厌的佳肴 枸杞子吃法正确才能更好吸收营养,但人在出现状况时最好别吃它 土豆是一种非常普通的蔬菜,但其营养保健价值令人难以置信 大家别忘了喝碗营养丰富的腊八粥,它对女性朋友的好处尤其多 经常吃一点柚子好处多,柚子皮的作用也不少,以后别再浪费啦 牛奶是常见的营养饮品,如果选择不对,既浪费钱还影响健康 香蕉对身体健康有很多好处,教你用香蕉做一道美味粥吧 香菇与洋葱搭配在一起营养全面,使得保健功效会更好
- 评论列表
-
- 添加评论