58
58
59
59
<!-- 这里可写通用的实现逻辑 -->
60
60
61
- 长度为 ` 2N ` ,共 ` N+1 ` 个不同元素,其中一个元素出现 ` N ` 次,说明其它元素各不相同。
61
+ ** 方法一:哈希表 **
62
62
63
- 遍历数组,只要出现重复元素,它就是我们要找的重复 ` N ` 次的元素。
63
+ 由于数组 $nums$ 一共有 $2n$ 个元素,其中有 $n + 1$ 个不同的元素,且有一个元素重复了 $n$ 次,说明数组中的其余 $n$ 个元素都是不同的。
64
+
65
+ 因此,我们只需要遍历数组 $nums$,用哈希表 $s$ 记录遍历过的元素。当遍历到某个元素 $x$ 时,如果 $x$ 在哈希表 $s$ 中已经存在,说明 $x$ 是重复的元素,直接返回 $x$ 即可。
66
+
67
+ 时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 $nums$ 的长度。
64
68
65
69
<!-- tabs:start -->
66
70
72
76
class Solution :
73
77
def repeatedNTimes (self , nums : List[int ]) -> int :
74
78
s = set ()
75
- for num in nums:
76
- if num in s:
77
- return num
78
- s.add(num )
79
+ for x in nums:
80
+ if x in s:
81
+ return x
82
+ s.add(x )
79
83
```
80
84
81
85
### ** Java**
@@ -85,14 +89,12 @@ class Solution:
85
89
``` java
86
90
class Solution {
87
91
public int repeatedNTimes (int [] nums ) {
88
- Set<Integer > s = new HashSet<> ();
89
- for (int num : nums ) {
90
- if (s . contains(num )) {
91
- return num ;
92
+ Set<Integer > s = new HashSet<> (nums . length / 2 + 1 );
93
+ for (int i = 0 ;; ++ i ) {
94
+ if (! s . add(nums[i] )) {
95
+ return nums[i] ;
92
96
}
93
- s. add(num);
94
97
}
95
- return - 1 ;
96
98
}
97
99
}
98
100
```
@@ -104,17 +106,44 @@ class Solution {
104
106
public:
105
107
int repeatedNTimes(vector<int >& nums) {
106
108
unordered_set<int > s;
107
- for (auto& num : nums ) {
108
- if (s.find(num) != s.end( )) {
109
- return num ;
109
+ for (int i = 0;; ++i ) {
110
+ if (s.count(nums [ i ] )) {
111
+ return nums [ i ] ;
110
112
}
111
- s.insert(num );
113
+ s.insert(nums [ i ] );
112
114
}
113
- return -1;
114
115
}
115
116
};
116
117
```
117
118
119
+ ### **Go**
120
+
121
+ ```go
122
+ func repeatedNTimes(nums []int) int {
123
+ s := map[int]bool{}
124
+ for i := 0; ; i++ {
125
+ if s[nums[i]] {
126
+ return nums[i]
127
+ }
128
+ s[nums[i]] = true
129
+ }
130
+ }
131
+ ```
132
+
133
+ ### ** TypeScript**
134
+
135
+ ``` ts
136
+ function repeatedNTimes(nums : number []): number {
137
+ const s: Set <number > = new Set ();
138
+ for (const x of nums ) {
139
+ if (s .has (x )) {
140
+ return x ;
141
+ }
142
+ s .add (x );
143
+ }
144
+ }
145
+ ```
146
+
118
147
### ** JavaScript**
119
148
120
149
``` js
@@ -124,13 +153,12 @@ public:
124
153
*/
125
154
var repeatedNTimes = function (nums ) {
126
155
const s = new Set ();
127
- for (const num of nums) {
128
- if (s.has(num )) {
129
- return num ;
156
+ for (const x of nums) {
157
+ if (s .has (x )) {
158
+ return x ;
130
159
}
131
- s.add(num );
160
+ s .add (x );
132
161
}
133
- return -1;
134
162
};
135
163
```
136
164
0 commit comments