Python Algorithm
LeetCode
2037. Minimum Number of Moves to Seat Everyone
- There are n availabe seats and n students standing in a room. You are given an array [seats] of length n, where seats[i] is the position of the iᵗʰ seat. You are also given the array [students] of length n, where students[j] is the position of the jᵗʰ student.
- You may perform the following move any number of times:
- Increase or decrease the position of the iᵗʰ student by 1 (i.e., moving the iᵗʰ 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.
- Constraints
- n == seats.length == students.length
- 1 ≤ n ≤ 100
- 1 ≤ seats[i], students[j] ≤ 100
class Solution:
def minMovesToSeat(self, seats: List[int], students: List[int]) -> int:
# sorting!
answer = 0
seats = sorted(seats)
students = sorted(students)
for seat, student in zip(seats, students):
# move 계산해서 answer에 더해주기
answer += abs(seat - student)
return answer
class Solution:
def minMovesToSeat(self, seats: List[int], students: List[int]) -> int:
answer = 0
seats.sort()
students.sort()
for i in range(len(seats)):
answer += abs(seats[i] - students[i])
return answer
2053. Kth Distinct String in an Array
- A distinct string is a string that is present only once in an array.
- Given an array of strings [arr], and an integer k, return the kᵗʰ distinct string present in [arr]. If there are fewer than k distinct strings, return an empty string "".
- Note that the strings are considered in the order in which they appear in the array.
- Constraints
- 1 ≤ k ≤ arr.length ≤ 1000
- 1 ≤ arr[i].length ≤ 5
- arr[i] consists of lowercase English letters.
class Solution:
def kthDistinct(self, arr: List[str], k: int) -> str:
c = Counter(arr)
candidates = [x for x in arr if c[x] == 1]
if k <= len(candidates):
return candidates[k-1]
return ""
class Solution:
def kthDistinct(self, arr: List[str], k: int) -> str:
c = Counter(arr)
answer = []
for key, value in c.items():
if value == 1:
answer.append(key)
if len(answer) >= k:
return answer[k-1]
return ""
class Solution:
def kthDistinct(self, arr: List[str], k: int) -> str:
c = Counter(arr)
answer = [key for key, value in c.items() if value == 1]
if len(answer) >= k:
return answer[k-1]
return ""
https://leetcode.com/problems/minimum-number-of-moves-to-seat-everyone/
https://leetcode.com/problems/kth-distinct-string-in-an-array/
'지난 공부기록 > 알고리즘 풀이' 카테고리의 다른 글
| Python - Algorithm #57 (0) | 2024.09.25 |
|---|---|
| Python - Algorithm #56 (0) | 2024.09.24 |
| Python - Algorithm #54 (0) | 2024.09.20 |
| Python - Algorithm #53 (0) | 2024.09.19 |
| Python - Algorithm #52 (0) | 2024.09.13 |