1. 문제(원본)
Given the array nums, for each nums[i] find out how many numbers in the array are smaller than it. That is, for each nums[i] you have to count the number of valid j's such that j != i and nums[j] < nums[i].
Return the answer in an array.
Example 1:
Input: nums = [8,1,2,2,3] Output: [4,0,1,1,3] Explanation: For nums[0]=8 there exist four smaller numbers than it (1, 2, 2 and 3). For nums[1]=1 does not exist any smaller number than it. For nums[2]=2 there exist one smaller number than it (1). For nums[3]=2 there exist one smaller number than it (1). For nums[4]=3 there exist three smaller numbers than it (1, 2 and 2).
Example 2:
Input: nums = [6,5,4,8] Output: [2,1,0,3]
Example 3:
Input: nums = [7,7,7,7] Output: [0,0,0,0]
Constraints:
- 2 <= nums.length <= 500
- 0 <= nums[i] <= 100
2. 문제
Int형 배열의 각 인덱스의 값 보다 작은 수를 카운트하여 새로운 Int배열을 반환한다.
3. 나의 답
class Solution {
func smallerNumbersThanCurrent(_ nums: [Int]) -> [Int] {
var result: [Int] = []
for target in nums {
var count = 0
for check in nums where target > check {
count += 1
}
result.append(count)
}
return result
}
}
4. 다른 유저의 답
#1
class Solution {
func smallerNumbersThanCurrent(_ nums: [Int]) -> [Int] {
let dict = nums.sorted().enumerated().reduce(into: [Int: Int](), { $0[$1.1] = min($0[$1.1, default: Int.max], $1.0) })
return nums.map({ dict[$0, default: 0] })
}
}
5. 마무리
어려운 문제는 아니였지만 어떻게 해서 조금 더 간략화 할 수 있을까 하는 문제였던 것 같다.
다른 유저의 답변들이 너무 길었던 것에 비래 한 유저만이 진짜 많이 간략화 하였는데 사용한 함수들을 배열을 정말 잘 활용한 것 같은 생각이 들었다.
많은 도움이 되었다.
'알고리즘 > 해결' 카테고리의 다른 글
LeetCode1290. Convert Binary Number in a Linked List to Integer (0) | 2020.03.15 |
---|---|
LeetCode1323. Maximum 69 Number (0) | 2020.03.08 |
LeetCode1221. Split a String in Balanced Strings (0) | 2020.02.23 |
LeetCode771. Jewels and Stones (0) | 2020.02.23 |
LeetCode1351. Count Negative Numbers in a Sorted Matrix (0) | 2020.02.16 |