-
[LeetCode] 1200. Minimum Absolute DifferenceLeetCode 2021. 12. 20. 11:46728x90
https://leetcode.com/problems/minimum-absolute-difference/
Minimum Absolute Difference - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
Minimum Absolute Difference - Easy

arr의 수들 중, 두 수의 차이가 가장 작은 짝들을 출력하는 문제다.
arr를 오름차순으로 sort해주면 arr[i]와 차이가 가장 작게 나는 수는 arr[i-1] 또는 arr[i+1] 이다.
arr[i-1]은 arr[i-1] 차례때 거치게 되니 arr[i] 와 arr[i+1] 만 고려하면 된다.
arr[i+1] - arr[i] 가 최소값 m 보다 작다면 결과값을 비우고 해당 짝을 추가해주자.
또는 최소값 m 과 같다면 짝만 추가하자.
전체 풀이 코드
class Solution { public: vector<vector<int>> minimumAbsDifference(vector<int>& arr) { vector<vector<int>> ret; int m=INT_MAX; sort(arr.begin(), arr.end()); for (int i=0; i<arr.size()-1; i++) { if (arr[i+1] - arr[i] < m) ret.clear(), m=arr[i+1]-arr[i]; if (arr[i+1] - arr[i] == m) ret.push_back({arr[i],arr[i+1]}); } return ret; } };'LeetCode' 카테고리의 다른 글
[LeetCode] 1015. Smallest Integer Divisible by K (0) 2021.12.30 [LeetCode] 116. Populating Next Right Pointers in Each Node (0) 2021.12.29 [LeetCode] 394. Decode String (0) 2021.12.19 [LeetCode] 1306. Jump Game III (0) 2021.12.09 [LeetCode] 563. Binary Tree Tilt (0) 2021.12.08