zoukankan      html  css  js  c++  java
  • [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]
    思路:
    很明显答案就是容器里最大值与最小值的差值,如果这个值小于2K,那么结果就为0,当然需要注意只有一个元素的情况。这才是名副其实的EZ啊。
    Solution:
     1 class Solution {
     2 public:
     3     int smallestRangeI(vector<int>& A, int K) 
     4 {
     5         sort(A.begin(),A.end());
     6         int size = A.size();
     7         int result = 0;
     8         if(size>1)
     9         {
    10           result = A[size-1] - A[0];
    11         }
    12         result -=2*K;
    13         if(result<0)
    14         {
    15             result = 0;
    16         }
    17         return result;
    18     }
    19 };

    直接调用stl自带的sort排序,简直不用太爽。哈哈哈

  • 相关阅读:
    springIOC 原理
    jeesite异步分页
    yum
    乐观锁原理
    equlas(),hashcode(),hashset,hashmap
    链接收藏
    java单词
    jeesite优化
    SailingEase .NET Resources Tool (.NET 多语言资源编辑器)转
    C#基本语法
  • 原文地址:https://www.cnblogs.com/Swetchine/p/11154995.html
Copyright © 2011-2022 走看看