알고리즘/LeetCode
2465. Number of Distinct Averages
앤테바
2022. 12. 23. 11:55
반응형
문제)
2465. Number of Distinct Averages
You are given a 0-indexed integer array nums of even length.
As long as nums is not empty, you must repetitively:
- Find the minimum number in nums and remove it.
- Find the maximum number in nums and remove it.
- Calculate the average of the two removed numbers.
The average of two numbers a and b is (a + b) / 2.
- For example, the average of 2 and 3 is (2 + 3) / 2 = 2.5.
Return the number of distinct averages calculated using the above process.
Note that when there is a tie for a minimum or maximum number, any can be removed.
Example 1:
Input: nums = [4,1,4,0,3,5]
Output: 2
Explanation:
1. Remove 0 and 5, and the average is (0 + 5) / 2 = 2.5. Now, nums = [4,1,4,3].
2. Remove 1 and 4. The average is (1 + 4) / 2 = 2.5, and nums = [4,3].
3. Remove 3 and 4, and the average is (3 + 4) / 2 = 3.5.
Since there are 2 distinct numbers among 2.5, 2.5, and 3.5, we return 2.
Example 2:
Input: nums = [1,100]
Output: 1
Explanation:
There is only one average to be calculated after removing 1 and 100, so we return 1.
Constraints:
- 2 <= nums.length <= 100
- nums.length is even.
- 0 <= nums[i] <= 100
솔루션1)
- 오름차순 정렬해서 제일 왼쪽은 min val, 제일 오른쪽은 max val을 쉽게 구할 수 있음
class Solution:
def distinctAverages(self, nums: List[int]) -> int:
nums.sort()
avgs = []
while nums:
avg = (nums[0] + nums[-1]) / 2
avgs.append(avg)
del nums[0]
nums.pop()
return len(set(avgs))
솔루션2)
- 솔루션1 최적화
: 리스트의 원소를 삭제하지 않고 left, right 인덱스 이동
: 불필요한 나누기 2 연산 제거
class Solution:
def distinctAverages(self, nums: List[int]) -> int:
nums.sort()
l, r = 0, len(nums) - 1
averages = []
while l < r:
averages.append(nums[l] + nums[r])
l += 1
r -= 1
return len(set(averages))
반응형