-
[Leetcode] 961. N-Repeated Element in Size 2N ArrayAlgorithm/LeetCode 2021. 8. 22. 16:35
You are given an integer array nums with the following properties:
- nums.length == 2 * n.
- nums contains n + 1 unique elements.
- Exactly one element of nums is repeated n times.
Return the element that is repeated n times.
Example 1:
Input: nums = [1,2,3,3] Output: 3
Example 2:
Input: nums = [2,1,2,5,3,2] Output: 2
Example 3:
Input: nums = [5,1,5,2,5,3,5,4] Output: 5
Constraints:
- 2 <= n <= 5000
- nums.length == 2 * n
- 0 <= nums[i] <= 104
- nums contains n + 1 unique elements and one of them is repeated exactly n times.
### my solution : 시간초과 class Solution: def repeatedNTimes(self, nums: List[int]) -> int: lennums = int( len(nums)/2 ) A = dict( zip( nums, [nums.count(i) for i in nums] ) ) bb = {v:k for k,v in A.items()} return bb.get(lennums) # 해설 : key, value 탐색을 위해서 dict 을 순회하는 로직에서 # 시간을 많이 잡아먹었다.
### recommended solution import collections class Solution(object): def repeatedNTimes(self, A): count = collections.Counter(A) for k in count: if count[k] > 1: return k ### value count 를 dict 자료구조에 저장한 것까지는 동일. ### 탐색하는 로직을 쓰지 않고 dict.values() 에서 드러나는 정답의 패턴으로 문제를 해결.
'Algorithm > LeetCode' 카테고리의 다른 글
[Leetcode] 1742. Maximum Number of Balls in a Box (0) 2021.09.23 [Leetcode] 1748. Sum of Unique Elements (0) 2021.08.22 [LeetCode]#682. Baseball Game (0) 2021.08.13 [Leetcode] 844. Backspace String Compare (0) 2021.08.13 [Leetcode] 1598. Crawler Log Folder (0) 2021.08.13