题目链接
https://leetcode.cn/problems/minimum-number-of-moves-to-seat-everyone/
题目大意
给两个长度相等的数组,求两个数组的元素的差的绝对值的和最小
解题思路
将两个数组从小到大排序,对应位置上元素相减,取其差的绝对值,再加起来
通过代码
class Solution {
public int minMovesToSeat(int[] seats, int[] students) {
Arrays.sort(seats);
Arrays.sort(students);
int ans = 0;
for (int i = 0; i < seats.length; i++) {
ans += (Math.abs(seats[i] - students[i]));
}
return ans;
}
}