• leetcode 908. 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
    

    思路:找A数组的最大值和最小值,然后算差值,然后用+x去减少这个差值。明显答案就是看2K能不能覆盖这个差值呗

    class Solution {
    public:
        int smallestRangeI(vector<int>& A, int K) {
            int a = INT_MAX;
            int b = INT_MIN;
            for (int i = 0; i < A.size(); ++i) {
                a = min(a, A[i]);
                b = max(b, A[i]);
            }
            if (a == b) return 0;
            if (b - a <= 2*K) return 0;
            else {
                return b - a - 2*K;
            }
        }
    };
    
  • 相关阅读:
    尝试制作了一个Panorama
    Python小游戏之猜数字
    Java基础-多线程学习目录
    Java8学习笔记目录
    Guava学习笔记目录
    Angular4学习笔记-目录汇总
    Springboot学习笔记
    JavaWeb-Tomcat阀
    JavaWeb-Tomcat安全域
    JavaWeb-Servlet基础
  • 原文地址:https://www.cnblogs.com/pk28/p/9695778.html
Copyright © 2020-2023  润新知