1. 문제(원본)
Given two integer arrays startTime and endTime and given an integer queryTime.
The ith student started doing their homework at the time startTime[i] and finished it at time endTime[i].
Return the number of students doing their homework at time queryTime. More formally, return the number of students where queryTime lays in the interval [startTime[i], endTime[i]] inclusive.
Example 1:
Input: startTime = [1,2,3], endTime = [3,2,7], queryTime = 4 Output: 1 Explanation: We have 3 students where: The first student started doing homework at time 1 and finished at time 3 and wasn't doing anything at time 4. The second student started doing homework at time 2 and finished at time 2 and also wasn't doing anything at time 4. The third student started doing homework at time 3 and finished at time 7 and was the only student doing homework at time 4.
Example 2:
Input: startTime = [4], endTime = [4], queryTime = 4 Output: 1 Explanation: The only student was doing their homework at the queryTime.
Example 3:
Input: startTime = [4], endTime = [4], queryTime = 5 Output: 0
Example 4:
Input: startTime = [1,1,1,1], endTime = [1,3,2,4], queryTime = 7 Output: 0
Example 5:
Input: startTime = [9,8,7,6,5,4,3,2,1], endTime = [10,10,10,10,10,10,10,10,10], queryTime = 5 Output: 5
Constraints:
- startTime.length == endTime.length
- 1 <= startTime.length <= 100
- 1 <= startTime[i] <= endTime[i] <= 1000
- 1 <= queryTime <= 1000
2. 문제
각각의 학생의 숙제 시간에 querytime이 포함된 학생의 수를 구하라
3. 나의 답
class Solution {
func busyStudent(_ startTime: [Int], _ endTime: [Int], _ queryTime: Int) -> Int {
var count = 0
for index in 0..<startTime.count
where startTime[index] <= queryTime && endTime[index] >= queryTime {
count += 1
}
return count
}
}
4. 다른 유저의 답
#1
class Solution {
func busyStudent(_ startTime: [Int], _ endTime: [Int], _ queryTime: Int) -> Int {
return startTime.enumerated().reduce(into: Int(0), { if queryTime >= $1.1 && queryTime <= endTime[$1.0] { $0 += 1 } })
}
}
5. 마무리
이번에도 역시나 reduce의 활용을 했으면 어땠나 하는 생각이 든다.
문제 해결 후 다른 유저의 답변을 확인해보니 1문장으로 끝낸 유저가 있어 코드 분석을 해보고 이러한 방법도 있구나 하는 생각을 할 수 있었다. 문제해결에는 다양한 방법이 있는데 지금까지 문제를 풀어나가며 다른 유저들의 답변도 보는 것이 많은 도움이 되는 것 같다.
'알고리즘 > 해결' 카테고리의 다른 글
LeetCode1464. Maximum Product of Two Elements in an Array (0) | 2020.06.05 |
---|---|
LeetCode1389. Create Target Array in the Given Order (0) | 2020.06.05 |
LeetCode1431. Kids With the Greatest Number of Candies (0) | 2020.05.18 |
LeetCode821. Shortest Distance to a Character (0) | 2020.04.20 |
LeetCode226. Invert Binary Tree (0) | 2020.04.14 |