leetcode-Array篇easy难度之最小距离对

关键词

绝对值,最小距离

题目描述

https://leetcode.com/problems/minimum-absolute-difference/

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 arr
 

Example 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^6

博主第一次提交的代码

第二个循环可以优化的,哎我没想到

class Solution {
    public List> minimumAbsDifference(int[] arr) {
        int[] arrClone = arr.clone();
        Arrays.sort(arrClone);
        int minAbsolute = Integer.MAX_VALUE;
        for(int i = 1; i < arrClone.length ;i++){
            if( (arrClone[i] - arrClone[i-1]) < minAbsolute ) {
                minAbsolute = arrClone[i] - arrClone[i-1];
            }
        }
        List> result = new LinkedList();
        for(int i = 1; i < arrClone.length;i++){
            if( (arrClone[i] - arrClone[i-1]) == minAbsolute ) {
                List list = new ArrayList<>(2);
                list.add(arrClone[i-1]);
                list.add(arrClone[i]);
                result.add(list);
            }
        }
        return result;
    }
        
}

其他人优秀的解法

clear那段时间复杂度可以采用均摊分析法
https://leetcode.com/problems/minimum-absolute-difference/discuss/388289/Java-sorting-beats-100-explained

public List> minimumAbsDifference(int[] arr) {
        List> res = new ArrayList();
        //sort elements
        Arrays.sort(arr);
        //init our min difference value
        int min = Integer.MAX_VALUE;
        //start looping over array to find real min element. Each time we found smaller difference
        //we reset resulting list and start building it from scratch. If we found pair with the same
        //difference as min - add it to the resulting list
        for (int i = 0; i < arr.length - 1; i++) {
            int diff = arr[i + 1] - arr[i];
            if (diff < min) {
                min = diff;
                res.clear();
                res.add(Arrays.asList(arr[i], arr[i + 1]));
            } else if (diff == min) {
                res.add(Arrays.asList(arr[i], arr[i + 1]));
            }
        }
        return res;
    }

你可能感兴趣的:(leetcode-Array篇easy难度之最小距离对)