【每日一题Day73】LC2037使每位学生都有座位的最少移动次数 | 排序+贪心

简介: 思路:要使总移动次数最少,那么要将每个学生移动至离其最近的座位,因此将座位和学生的位置进行升序排序,每个学生需要的移动次数即为对应位置相减,累加返回最终结果

使每位学生都有座位的最少移动次数【LC2037】


There are n seats and n students in a room. You are given an array seats of length n, where seats[i] is the position of the ith seat. You are also given the array students of length n, where students[j] is the position of the jth student.


You may perform the following move any number of times:


Increase or decrease the position of the ith student by 1 (i.e., moving the ith student from position x to x + 1 or x - 1)

Return the minimum number of moves required to move each student to a seat such that no two students are in the same seat.


Note that there may be multiple seats or students in the same position at the beginning.


元旦快乐啦


  • 思路:要使总移动次数最少,那么要将每个学生移动至离其最近的座位,因此将座位和学生的位置进行升序排序,每个学生需要的移动次数即为对应位置相减,累加返回最终结果


  • 实现


class Solution {
    public int minMovesToSeat(int[] seats, int[] students) {
        Arrays.sort(seats);
        Arrays.sort(students);
        int res = 0;
        for (int i = 0; i < seats.length; i++){
            res += Math.abs(seats[i] - students[i]);
        }
        return res;
    }
}


。复杂度


  • 时间复杂度:O ( n )
  • 空间复杂度:O ( 1 )


  • 实现


class Solution {
    public int minMovesToSeat(int[] seats, int[] students) {
        Arrays.sort(seats);
        Arrays.sort(students);
        int res = 0;
        for (int i = 0; i < seats.length; i++){
            res += Math.abs(seats[i] - students[i]);
        }
        return res;
    }
}


。复杂度


  • 时间复杂度:O ( n )
  • 空间复杂度:O ( 1 )
目录
相关文章
|
9月前
|
算法 安全 测试技术
[组合数学]LeetCode:2954:统计感冒序列的数目
[组合数学]LeetCode:2954:统计感冒序列的数目
|
9月前
【每日一题Day356】LC2678老人的数目 | 字符串
【每日一题Day356】LC2678老人的数目 | 字符串
59 0
【Java每日一题,动态规划,零钱兑换模板题】硬币组合数量
【Java每日一题,动态规划,零钱兑换模板题】硬币组合数量
|
9月前
除夕日的每日一题(字符个数统计,多数元素)
除夕日的每日一题(字符个数统计,多数元素)
50 2
|
9月前
|
Serverless
每日一题(统计每个月兔子的总数,数列的和)
每日一题(统计每个月兔子的总数,数列的和)
51 0
|
9月前
【每日一题Day314】LC1921消灭怪物的最大数量 | 贪心+排序
【每日一题Day314】LC1921消灭怪物的最大数量 | 贪心+排序
61 0
|
9月前
【每日一题Day355】LC1402 做菜顺序 | 贪心+排序
【每日一题Day355】LC1402 做菜顺序 | 贪心+排序
59 0
|
9月前
|
存储 算法
【每日一题Day310】LC1654到家的最少跳跃次数 | BFS
【每日一题Day310】LC1654到家的最少跳跃次数 | BFS
58 0
【AcWing每日一题】3400. 统计次数
【AcWing每日一题】3400. 统计次数
68 0
|
存储
L1-049 天梯赛座位分配 (20 分)( for循环的深入理解+三维数组+错误分析)
L1-049 天梯赛座位分配 (20 分)( for循环的深入理解+三维数组+错误分析)
173 0