链接:
https://leetcode-cn.com/problems/smallest-range-i/
描述:
代码:
class Solution {
public:
int smallestRangeI(vector<int>& nums, int k) {
int minNum = *min_element(nums.begin(), nums.end());
int maxNum = *max_element(nums.begin(), nums.end());
return maxNum - minNum <= 2 * k ? 0 : maxNum - minNum - 2 * k;
}
};
代码解析:
min_element(求数组中最小的值)
max_element(求数组中最大的值)
当最大和最小相距小于2k:
此时返回零
当最大和最小相距大于2k
此时返回:maxNum - minNum - 2 * k;