当前位置:网站首页>Leetcdoe 2037. Make each student have the minimum number of seat movements (yes, once)

Leetcdoe 2037. Make each student have the minimum number of seat movements (yes, once)

2022-06-12 10:27:00 I'm not xiaohaiwa~~~~

 Insert picture description here
There is... In a room n Seats and n Famous student , The room is represented by a number axis . Give you a length of n Array of seats , among seats[i] It's No i A seat . At the same time, give you a length of n Array of students , among students[j] It's No j The position of a student .

You can do the following any number of times :

  • Increase or decrease the number of i The position of a student , Each change is 1 ( That is to say, it will be i Students from position x Move to x + 1 perhaps x - 1)

Please go back to the place where all students have seats The minimum number of moves , And make sure no two students have the same seats .

Please note that , There may be more than one seat or more students at the beginning same Location .

Example 1:

 Input :seats = [3,1,5], students = [2,7,4]
 Output :4
 explain : Students move as follows :
-  The first student from position  2  Move to location  1 , Move  1  Time .
-  The second student from the position  7  Move to location  5 , Move  2  Time .
-  The third student from the position  4  Move to location  3 , Move  1  Time .
 in total  1 + 2 + 1 = 4  Secondary mobility .

Example 2:

 Input :seats = [4,1,5,9], students = [1,3,2,6]
 Output :7
 explain : Students move as follows :
-  The first student doesn't move .
-  The second student from the position  3  Move to location  4 , Move  1  Time .
-  The third student from the position  2  Move to location  5 , Move  3  Time .
-  The fourth student from the position  6  Move to location  9 , Move  3  Time .
 in total  0 + 1 + 3 + 3 = 7  Secondary mobility .

Example 3:

 Input :seats = [2,2,6,6], students = [1,3,2,6]
 Output :4
 explain : Students move as follows :
-  The first student from position  1  Move to location  2 , Move  1  Time .
-  The second student from the position  3  Move to location  6 , Move  3  Time .
-  The third student doesn't move .
-  The fourth student doesn't move .
 in total  1 + 3 + 0 + 0 = 4  Secondary mobility .

Tips :

  • n == seats.length == students.length
  • 1 <= n <= 100
  • 1 <= seats[i], students[j] <= 100

Main idea : Prioritize , Then find the absolute value
Code:

class Solution {
    
public:
    int minMovesToSeat(vector<int>& seats, vector<int>& students) {
    
        int res=0;
    
        sort(seats.begin(),seats.end());
        sort(students.begin(),students.end());
        
        for(int i=0;i<seats.size();i++)
        {
    
            res+=abs(students[i]-seats[i]);
        }
        return res;
    }
};
原网站

版权声明
本文为[I'm not xiaohaiwa~~~~]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/163/202206121020432455.html