Leetcode - 287. Find the Duplicate Number
Leetcode - 287. Find the Duplicate Number
Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive.
There is only one repeated number in nums, return this repeated number.
You must solve the problem without modifying the array nums and uses only constant extra space.
Solution (Without Using Constant Space)
1
2
3
4
5
6
7
8
9
10
11
12
func findDuplicate(nums []int) int {
numMap := make(map[int]int)
for _, num := range nums{
_, ok := numMap[num]
if !ok{
numMap[num]++
}else{
return num
}
}
return -1
}
Solution (Constant Space/Best Practice)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
func findDuplicate(nums []int) int {
i := 0
for i<len(nums){
indexWhereItShouldBe := nums[i]-1
if nums[i]!=nums[indexWhereItShouldBe]{
nums[i], nums[indexWhereItShouldBe] = nums[indexWhereItShouldBe], nums[i]
}else{
fmt.Println(i,indexWhereItShouldBe )
if i != indexWhereItShouldBe {
return nums[i]
}
i++
}
}
fmt.Println(nums)
return -1
}
This post is licensed under CC BY 4.0 by the author.