-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1228-MissingNumberInArithmeticProgression.go
More file actions
72 lines (61 loc) · 1.76 KB
/
1228-MissingNumberInArithmeticProgression.go
File metadata and controls
72 lines (61 loc) · 1.76 KB
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package main
// 1228. Missing Number In Arithmetic Progression
// In some array arr, the values were in arithmetic progression:
// the values arr[i + 1] - arr[i] are all equal for every 0 <= i < arr.length - 1.
// A value from arr was removed that was not the first or last value in the array.
// Given arr, return the removed value.
// Example 1:
// Input: arr = [5,7,11,13]
// Output: 9
// Explanation: The previous array was [5,7,9,11,13].
// Example 2:
// Input: arr = [15,13,12]
// Output: 14
// Explanation: The previous array was [15,14,13,12].
// Constraints:
// 3 <= arr.length <= 1000
// 0 <= arr[i] <= 10^5
// The given array is guaranteed to be a valid array.
import "fmt"
import "sort"
func missingNumber(arr []int) int {
n := len(arr)
diff := (arr[n-1] - arr[0]) / n
if diff == 0 {
return arr[0]
}
left, right := 0, n - 1
for left < right - 1 {
mid := left + (right - left) / 2
if arr[mid] == arr[left] + diff * (mid - left) {
left = mid
} else {
right = mid
}
}
return arr[left] + diff
}
func missingNumber1(arr []int) int {
n := len(arr)
diff := (arr[n-1] - arr[0]) / n
if diff == 0 {
return arr[0]
}
i := sort.Search(n, func(p int) bool {
return arr[p] != arr[0] + p * diff
})
return arr[i] - diff
}
func main() {
// Example 1:
// Input: arr = [5,7,11,13]
// Output: 9
// Explanation: The previous array was [5,7,9,11,13].
fmt.Println(missingNumber([]int{5,7,11,13})) // 9
// Example 2:
// Input: arr = [15,13,12]
// Output: 14
fmt.Println(missingNumber([]int{15,13,12})) // 14
fmt.Println(missingNumber1([]int{5,7,11,13})) // 9
fmt.Println(missingNumber1([]int{15,13,12})) // 14
}