【数学】C026_最小差值II(线性扫描)

一、题目描述

Given an array A of integers, for each integer A[i] we need to 
choose either x = -K or x = K, and add x to A[i] (only once).

After this process, we have some array B.

Return the smallest possible difference between 
the maximum value of B and the minimum value of B.

Example 1:
Input: A = [1], K = 0
Output: 0
Explanation: B = [1]

Example 2:
Input: A = [0,10], K = 2
Output: 6
Explanation: B = [2,8]

Example 3:
Input: A = [1,3,6], K = 3
Output: 3
Explanation: B = [4,6,3]
 

Note:
1 <= A.length <= 10000
0 <= A[i] <= 10000
0 <= K <= 10000

二、题解

(1) 线性扫描:

先将数组nums进行排序,然后以i为分界点,把数组分为两个区间,他们分别为:

  • A[0]...A[i]
  • A[i+1]...A[N-1]N为数组的元素的个数)

由上可得,以i为对称轴,分别将数组的两端的元素加上/减去K他们得到的状态为

  • 最大值:A[N-1]-k / A[i]+K
  • 最小值:A[0]+K / A[i+1]-K

基于以上的分析,我们只需要对最大最小值的两种可能进行比较即可得出真正的最大最小值,也就得到本次扫描的最小的最大值与最小值之差。

public int smallestRangeII(int[] A, int K) {
  Arrays.sort(A);
  int N = A.length;
  int ans = A[N-1] - A[0];
  int a = 0, b = 0;

  for (int i = 0; i < N - 1; i++) {
    a = A[i] + K;
    b = A[i+1] - K;
    int mayBeMax = Math.max(a, A[N-1]-K);
    int mayBeMin = Math.min(b, A[0]+K);
    ans = Math.min(ans, mayBeMax-mayBeMin);
  }
  return ans;
}

复杂度分析

  • 时间复杂度:O(N logN);Max(O(N logN), O(N)),其中NA的长度。
  • 空间复杂度:O(1),只使用了常数级别的额外空间。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值