leetcode
leetcode 2701 ~ 2750
查询差绝对值的最小值

查询差绝对值的最小值

难度:

标签:

题目描述

The minimum absolute difference of an array a is defined as the minimum value of |a[i] - a[j]|, where 0 <= i < j < a.length and a[i] != a[j]. If all elements of a are the same, the minimum absolute difference is -1.

  • For example, the minimum absolute difference of the array [5,2,3,7,2] is |2 - 3| = 1. Note that it is not 0 because a[i] and a[j] must be different.

You are given an integer array nums and the array queries where queries[i] = [li, ri]. For each query i, compute the minimum absolute difference of the subarray nums[li...ri] containing the elements of nums between the 0-based indices li and ri (inclusive).

Return an array ans where ans[i] is the answer to the ith query.

A subarray is a contiguous sequence of elements in an array.

The value of |x| is defined as:

  • x if x >= 0.
  • -x if x < 0.

 

Example 1:

Input: nums = [1,3,4,8], queries = [[0,1],[1,2],[2,3],[0,3]]
Output: [2,1,4,1]
Explanation: The queries are processed as follows:
- queries[0] = [0,1]: The subarray is [1,3] and the minimum absolute difference is |1-3| = 2.
- queries[1] = [1,2]: The subarray is [3,4] and the minimum absolute difference is |3-4| = 1.
- queries[2] = [2,3]: The subarray is [4,8] and the minimum absolute difference is |4-8| = 4.
- queries[3] = [0,3]: The subarray is [1,3,4,8] and the minimum absolute difference is |3-4| = 1.

Example 2:

Input: nums = [4,5,2,2,7,10], queries = [[2,3],[0,2],[0,5],[3,5]]
Output: [-1,1,1,3]
Explanation: The queries are processed as follows:
- queries[0] = [2,3]: The subarray is [2,2] and the minimum absolute difference is -1 because all the
  elements are the same.
- queries[1] = [0,2]: The subarray is [4,5,2] and the minimum absolute difference is |4-5| = 1.
- queries[2] = [0,5]: The subarray is [4,5,2,2,7,10] and the minimum absolute difference is |4-5| = 1.
- queries[3] = [3,5]: The subarray is [2,7,10] and the minimum absolute difference is |7-10| = 3.

 

Constraints:

  • 2 <= nums.length <= 105
  • 1 <= nums[i] <= 100
  • 1 <= queries.length <= 2 * 104
  • 0 <= li < ri < nums.length

代码结果

运行时间: 1470 ms, 内存: 26.6 MB


/*
 * Problem Statement:
 * Given an array of integers 'nums' and an array of queries 'queries', where queries[i] = [li, ri].
 * For each query, compute the minimum absolute difference between any two distinct elements in the subarray nums[li...ri].
 * If all elements in the subarray are the same, return -1.
 */

import java.util.*;
import java.util.stream.*;

public class MinAbsoluteDifferenceStream {
    public int[] minDifference(int[] nums, int[][] queries) {
        return Arrays.stream(queries).mapToInt(query -> {
            int l = query[0];
            int r = query[1];
            Set<Integer> set = IntStream.rangeClosed(l, r).mapToObj(i -> nums[i]).collect(Collectors.toCollection(TreeSet::new));
            if (set.size() == 1) return -1;
            Iterator<Integer> it = set.iterator();
            int prev = it.next();
            int minDiff = Integer.MAX_VALUE;
            while (it.hasNext()) {
                int curr = it.next();
                minDiff = Math.min(minDiff, curr - prev);
                prev = curr;
            }
            return minDiff;
        }).toArray();
    }

    public static void main(String[] args) {
        MinAbsoluteDifferenceStream solution = new MinAbsoluteDifferenceStream();
        int[] nums = {4, 5, 2, 2, 7, 10};
        int[][] queries = {{2, 3}, {0, 2}, {0, 5}, {3, 5}};
        int[] result = solution.minDifference(nums, queries);
        System.out.println(Arrays.toString(result)); // Output: [-1, 1, 1, 3]
    }
}

解释

方法:

这个题解提供了两种方法来解决问题: 方法一:二分查找 1. 先用一个字典 idx 记录每个数字出现在 nums 中的所有位置 2. 对于每个查询 [l, r],遍历有序的数字键值,对每个数字 i: - 用二分查找判断 i 是否出现在区间 [l, r] 内 - 如果出现,更新相邻两数之差的最小值 t 3. 如果 t 没有被更新过,说明区间内所有数字相同,返回 -1,否则返回 t 方法二:前缀和 1. 用一个列表 s 记录到每个位置为止,每个数字出现的次数(前缀和) 2. 对于每个查询 [l, r],用 s[r+1] - s[l] 得到区间内每个数字的出现次数 3. 如果区间内只有一个不同的数字,返回 -1,否则计算并返回有序数字间的最小差值

时间复杂度:

方法一:O(n + m * log n) 方法二:O(n + m)

空间复杂度:

方法一:O(n) 方法二:O(n)

代码细节讲解

🦆
为什么在方法一中使用二分查找来判断数字是否出现在区间[l, r]内?为什么这种方法比直接遍历整个区间来查找数字是否更有效?
在方法一中使用二分查找,是因为每个数字在数组`nums`中的出现位置已经被储存在一个有序列表中(通过`idx`字典)。当我们需要判断一个数字是否在某个区间[l, r]内出现时,可以通过二分查找快速定位到这个范围内的第一个可能的位置,然后检查这个位置是否在给定的区间内。这比遍历整个区间来查找数字的效率要高,因为二分查找的时间复杂度是O(log n),而直接遍历区间的复杂度可能达到O(n),特别是当区间很大时。因此,使用二分查找可以显著提升查询效率。
🦆
在方法二中,前缀和是如何帮助我们快速计算区间内每个数字的出现次数的?具体是如何通过前缀和数组来计算的?
在方法二中,通过构建一个前缀和数组`s`,每个元素是一个计数器(Counter),记录从数组开始到当前位置所有数字的出现次数。要计算某个区间[l, r]内各数字的出现次数,可以利用前缀和的性质:`s[r+1] - s[l]`。这里`s[r+1]`代表从数组开始到位置r的所有数字出现次数,`s[l]`代表从数组开始到位置l之前的所有数字出现次数。两者相减得到的结果便是区间[l, r]内每个数字的精确出现次数。这种方法避免了对区间内每个元素的直接统计,能够在常数时间内完成计数,提高了效率。
🦆
在方法二中,如果区间内只有一个不同的数字返回-1,是基于什么考虑?
在方法二中返回-1的设计是为了处理特殊情况,即当查询的区间内只存在一种数字时。由题目要求是计算不同数字之间的最小差值,如果区间内只有一种数字,就不存在任何差值。因此,按照题目的逻辑,这种情况下应当返回-1,表示无法计算出有意义的差值。这样的处理符合题目求解差值的目的,也使得函数的返回结果具有明确的意义。

相关问题