-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathalgo.go
More file actions
57 lines (48 loc) · 892 Bytes
/
algo.go
File metadata and controls
57 lines (48 loc) · 892 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package main
func Sum(x int, y int) int {
return x + y
}
// 3:1
func Duplicate(nums []int) (int, bool) {
for i := 0; i < len(nums); i++ {
for nums[i] != i {
if (nums[i] == nums[nums[i]]) {
return nums[i], true
}
nums[i], nums[nums[i]] = nums[nums[i]], nums[i]
}
}
return -1, false
}
// 3:2
func Duplication(nums []int) int {
length := len(nums)
start := 1
end := length - 1
for end >= start {
middle := ((end - start) / 2) + start
count := countRange(nums, length, start, middle)
if end == start {
if count > 1 {
return start
} else {
break
}
}
if count > middle - start + 1 {
end = middle
} else {
start = middle + 1
}
}
return -1
}
func countRange(nums []int, length int, start int, end int) int {
count := 0
for i := 0; i < length; i++ {
if nums[i] >= start && nums[i] <= end {
count++
}
}
return count
}