Add other solution for find pick along the array
This commit is contained in:
33
findPeak.go
Normal file
33
findPeak.go
Normal file
@@ -0,0 +1,33 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
// FindPeak finds the peak element in the array
|
||||
func findPeak(arr []int) int {
|
||||
n := len(arr)
|
||||
|
||||
// first or last element is peak element
|
||||
if n == 1 {
|
||||
return 0
|
||||
}
|
||||
if arr[0] >= arr[1] {
|
||||
return 0
|
||||
}
|
||||
if arr[n-1] >= arr[n-2] {
|
||||
return n - 1
|
||||
}
|
||||
|
||||
// check for ever other element
|
||||
for i := 1; i < n-1; i++ {
|
||||
// check if the neighbors are smaller
|
||||
if arr[i] >= arr[i-1] && arr[i] >= arr[i+1] {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return -1 // inficating no peak found
|
||||
}
|
||||
|
||||
func main() {
|
||||
arr := []int{1, 3, 20, 4, 1, 21, 0}
|
||||
fmt.Println("Index of a peak point is", findPeak(arr))
|
||||
}
|
||||
Reference in New Issue
Block a user