908. Smallest Range I*

908. Smallest Range I*

https://leetcode.com/problems/smallest-range-i/

题目描述

Given an array A of integers, for each integer A[i] we may choose any x with -K <= x <= K, and add x to A[i].

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: 0
Explanation: B = [3,3,3] or B = [4,4,4]

Note:

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

C++ 实现 1

在这里插入图片描述
将每个 A[i] 加上 -K <= x <= K 的范围画出来, 会发现 B 中的最小值要和最大值尽可能小, 就必须要 B 中的最小值要尽可能大, 而 B 中的最大值要尽可能小. 如下图:

class Solution {
public:
    int smallestRangeI(vector<int>& A, int K) {
        std::sort(A.begin(), A.end());
        int a = A[0] + K, b = A.back() - K;
        if (a >= b) return 0;
        return std::abs(a - b);
    }
};

C++ 实现 2

从实现 1 可以知道, 只需要 A 中的最大和最小值即可, 可以用 O ( N ) O(N) 的方法找到, 而无需对数组进行排序. 代码来自 LeetCode Submission.

class Solution {
public:
    int smallestRangeI(vector<int>& A, int K) {
        int _min = A[0], _max = A[0];
        for(auto x: A){
            _min = min(_min, x);
            _max = max(_max, x);
        }
        return _min + K >= _max - K ? 0: _max - _min - 2*K;
    }
};
发布了352 篇原创文章 · 获赞 7 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Eric_1993/article/details/104566556
今日推荐