当前位置:网站首页>[daily question] 1200 Minimum absolute difference

[daily question] 1200 Minimum absolute difference

2022-07-05 13:14:00 Wang Liuliu's it daily

1200. Minimum absolute difference
Simple questions
Here's an array of integers arr, Each of these elements is inequality .

Please find all the elements with the least absolute difference , And return in ascending order .

 Insert picture description here

Sort + simulation :
Yes arr Sort , It is easy to know that the minimum value of the difference must occur in the sorting array adjacent Between elements , At this point, we can sort the array by traversing and using variables min Record the minimum value of the current difference to count the answers .

class Solution {
    
    public List<List<Integer>> minimumAbsDifference(int[] arr) {
    
        Arrays.sort(arr);
        List<List<Integer>> ans = new ArrayList<>();
        int n = arr.length, min = arr[1] - arr[0];
        for (int i = 0; i < n - 1; i++) {
    
            int cur = arr[i + 1] - arr[i];
            if (cur < min) {
    
                ans.clear();
                min = cur;
            }
            if (cur == min) {
    
                List<Integer> temp = new ArrayList<>();
                temp.add(arr[i]); 
                temp.add(arr[i + 1]);
                ans.add(temp);
            }
        }
        return ans;
    }
}
原网站

版权声明
本文为[Wang Liuliu's it daily]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/186/202207051256007924.html