@@ -9,27 +9,25 @@ import TwoPointersTopic
9
9
* 287. Find the Duplicate Number
10
10
* https://leetcode.com/problems/find-the-duplicate-number/
11
11
*
12
- * Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive.
13
-
12
+ Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive.
14
13
There is only one repeated number in nums, return this repeated number.
15
-
16
14
You must solve the problem without modifying the array nums and uses only constant extra space.
17
15
*/
18
16
19
17
class Medium287 : ArraysTopic , TwoPointersTopic , BinaryTreeTopic , BitManipulationTopic {
20
18
21
19
fun findDuplicate (nums : IntArray ): Int {
22
- if (nums.size == 1 ) {
23
- return nums[0 ]
24
- }
25
- val map = HashMap <Int ,Int >()
20
+ if (nums.size == 1 ) return nums.first()
21
+ val map = HashMap <Int , Boolean >()
26
22
nums.forEach {
27
- if (map.getOrDefault(it, 0 ) == 1 ) {
28
- return it
29
- } else {
30
- map.set(it, 1 )
31
- }
23
+ if (map[it] == true ) return it
24
+ map[it] = true
32
25
}
33
26
return 0
34
27
}
28
+ }
29
+
30
+ fun main () {
31
+ println (Medium287 ().findDuplicate(intArrayOf(1 , 3 , 4 , 2 , 2 )))
32
+ println (Medium287 ().findDuplicate(intArrayOf(3 , 1 , 3 , 4 , 2 )))
35
33
}
0 commit comments