Re: [閒聊] 每日leetcode

作者: SecondRun (雨夜琴聲)   2024-06-13 09:05:45
2037. Minimum Number of Moves to Seat Everyone
有 n 個座位和 n 個學生在一個房間裡。給你一個長度為 n 的 seats 陣列,其中 seats[i] 是第 i 個座位的位置。同樣地,給你一個長度為 n 的 students 陣列,其中 students[j] 是第 j 個學生的位置。
你可以進行以下任意次數的移動:
增加或減少第 i 個學生的位置 1 (即,將第 i 個學生從位置 x 移動到 x + 1 或 x - 1)
返回將每個學生移動到一個座位的最小移動次數,使得沒有兩個學生在同一個座位上。
請注意,一開始可能有多個座位或學生位於相同位置。
Example 1:
Input: seats = [3,1,5], students = [2,7,4]
Output: 4
Explanation: The students are moved as follows:
- The first student is moved from from position 2 to position 1 using 1 move.
- The second student is moved from from position 7 to position 5 using 2 moves.
- The third student is moved from from position 4 to position 3 using 1 move.
In total, 1 + 2 + 1 = 4 moves were used.
思考: 貪婪
C# code:
public class Solution {
public int MinMovesToSeat(int[] seats, int[] students) {
Array.Sort(seats);
Array.Sort(students);
int result = 0;
int len = seats.Length;
for (int i=0; i<len; i++)
{
result += Math.Abs(seats[i] - students[i]);
}
return result;
}
}
作者: DJYOSHITAKA (Evans)   2024-06-13 09:42:00
別捲了

Links booklink

Contact Us: admin [ a t ] ucptt.com