Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 5d9f83a

Browse files
author
konstantin
committed
Merge remote-tracking branch 'origin/master'
2 parents 3bad7bf + d658f9b commit 5d9f83a

File tree

1 file changed

+10
-12
lines changed

1 file changed

+10
-12
lines changed

‎src/medium/287. Find the Duplicate Number .kt‎

Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -9,27 +9,25 @@ import TwoPointersTopic
99
* 287. Find the Duplicate Number
1010
* https://leetcode.com/problems/find-the-duplicate-number/
1111
*
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.
1413
There is only one repeated number in nums, return this repeated number.
15-
1614
You must solve the problem without modifying the array nums and uses only constant extra space.
1715
*/
1816

1917
class Medium287 : ArraysTopic, TwoPointersTopic, BinaryTreeTopic, BitManipulationTopic {
2018

2119
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>()
2622
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
3225
}
3326
return 0
3427
}
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)))
3533
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /