class Solution {
public:
int minElements(vector<int>& nums, int limit, int goal) {
}
};
1785. 构成特定和需要添加的最少元素
给你一个整数数组 nums
,和两个整数 limit
与 goal
。数组 nums
有一条重要属性:abs(nums[i]) <= limit
。
返回使数组元素总和等于 goal
所需要向数组中添加的 最少元素数量 ,添加元素 不应改变 数组中 abs(nums[i]) <= limit
这一属性。
注意,如果 x >= 0
,那么 abs(x)
等于 x
;否则,等于 -x
。
示例 1:
输入:nums = [1,-1,1], limit = 3, goal = -4 输出:2 解释:可以将 -2 和 -3 添加到数组中,数组的元素总和变为 1 - 1 + 1 - 2 - 3 = -4 。
示例 2:
输入:nums = [1,-10,9,1], limit = 100, goal = 0 输出:1
提示:
1 <= nums.length <= 105
1 <= limit <= 106
-limit <= nums[i] <= limit
-109 <= goal <= 109
原站题解
java 解法, 执行用时: 1 ms, 内存消耗: 54.1 MB, 提交时间: 2022-12-16 09:32:43
class Solution { public int minElements(int[] nums, int limit, int goal) { long sum = 0; for (int x : nums) { sum += x; } long diff = Math.abs(sum - goal); return (int) ((diff + limit - 1) / limit); } }
javascript 解法, 执行用时: 84 ms, 内存消耗: 51.9 MB, 提交时间: 2022-12-16 09:32:24
/** * @param {number[]} nums * @param {number} limit * @param {number} goal * @return {number} */ var minElements = function(nums, limit, goal) { const sum = _.sum(nums); const diff = Math.abs(sum - goal); return Math.abs(Math.floor((diff + limit - 1) / limit)); };
golang 解法, 执行用时: 92 ms, 内存消耗: 7.9 MB, 提交时间: 2022-12-16 09:32:08
func minElements(nums []int, limit, goal int) int { sum := 0 for _, x := range nums { sum += x } diff := abs(sum - goal) return (diff + limit - 1) / limit } func abs(x int) int { if x < 0 { return -x } return x }
cpp 解法, 执行用时: 96 ms, 内存消耗: 71.6 MB, 提交时间: 2022-12-16 09:31:55
class Solution { public: int minElements(vector<int>& nums, int limit, int goal) { long long sum = 0; for (auto x : nums) { sum += x; } long long diff = abs(sum - goal); return (diff + limit - 1) / limit; } };
python3 解法, 执行用时: 72 ms, 内存消耗: 24.4 MB, 提交时间: 2022-12-16 09:31:11
class Solution: def minElements(self, nums: List[int], limit: int, goal: int) -> int: return (abs(sum(nums) - goal) + limit - 1) // limit