908.最小差值I
链接:908.最小差值I
难度:Easy
标签:数组、数学
简介:在对 nums 中的每个索引最多应用一次上述操作后,返回 nums 的最低 分数 。
题解 1 - cpp
- 编辑时间:2022-03-23
- 执行用时:20ms
- 内存消耗:15.1MB
- 编程语言:cpp
- 解法介绍:排序后获得最大最小值进行比较。
class Solution {
   public:
    int smallestRangeI(vector<int>& nums, int k) {
        sort(nums.begin(), nums.end());
        int n = nums.size(), nmin = nums[0], nmax = nums[n - 1],
            mid = (nmax + nmin) / 2;
        if (mid - k > nmin)
            nmin += k;
        else
            nmin = mid;
        if (mid + k < nmax)
            nmax -= k;
        else
            nmax = mid;
        return nmax - nmin;
    }
};
题解 2 - go
- 编辑时间:2022-04-30
- 执行用时:12ms
- 内存消耗:5.9MB
- 编程语言:go
- 解法介绍:查看最大最小值。
func smallestRangeI(nums []int, k int) int {
  n := len(nums)
  if n == 1 {
    return 0
  }
  var (
    min = nums[0]
    max = nums[0]
  )
  for _, val := range nums {
    if min > val {
      min = val
    }
    if max < val {
      max = val
    }
  }
  mid := (min + max) >> 1
  if mid-min <= k {
    min = mid
  } else {
    min += k
  }
  if max-mid <= k {
    max = mid
  } else {
    max -= k
  }
  return max - min
}
题解 3 - python
- 编辑时间:2024-10-20
- 执行用时:12ms
- 内存消耗:17.36MB
- 编程语言:python
- 解法介绍:排序后直接判断最大值和最小值。
class Solution:
    def smallestRangeI(self, nums: List[int], k: int) -> int:
        nums.sort()
        return max(nums[-1] - 2 * k - nums[0], 0)