You are given an integer array nums and a non-negative integer k. In one operation, you can increase or decrease any element by 1.
Return the minimum number of operations needed to make the median of
numsequal to k.
The median of an array is defined as the middle element of the array when it is sorted in non-decreasing order. If there are two choices for a median, the larger of the two values is taken.
Input: nums =[2,5,6,8,5], k =4Output: 2Explanation:
We can subtract one from `nums[1]` and `nums[4]` to obtain `[2, 4, 6, 8, 4]`.The median of the resulting array is equal to `k`.
To make the median equal to k, we only need to change the value at the median index to k. The minimum number of operations is the sum of absolute differences between k and the current median value. For an odd-length array, the median is the middle element after sorting; for even-length, it’s the larger of the two middle elements.
classSolution {
public:int minOperations(vector<int>& nums, int k) {
sort(nums.begin(), nums.end());
int n = nums.size();
int m = n /2;
returnabs(nums[m] - k);
}
};
1
2
3
4
5
6
7
8
funcminOperations(nums []int, kint) int {
sort.Ints(nums)
m:= len(nums) /2ifnums[m] > k {
returnnums[m] -k }
returnk-nums[m]
}
1
2
3
4
5
6
7
classSolution {
publicintminOperations(int[] nums, int k) {
Arrays.sort(nums);
int m = nums.length/ 2;
return Math.abs(nums[m]- k);
}
}
1
2
3
4
5
6
7
classSolution {
funminOperations(nums: IntArray, k: Int): Int {
nums.sort()
val m = nums.size / 2return kotlin.math.abs(nums[m] - k)
}
}