Given an array arr of integers, check if there exists two integers N and M such that N is the double of M ( i.e. N = 2 * M).
More formally check if there exists two indices i and j such that :
i != j
0 <= i, j < arr.length
arr[i] == 2 * arr[j]
Constraints:
2 <= arr.length <= 500
-10^3 <= arr[i] <= 10^3
func checkIfExist(arr []int) bool {
e := len(arr)
for l := 0; l < e; l++ {
for r := e - 1; r > l; r-- {
switch {
case arr[l] == 0 && arr[r] == 0:
return true
case arr[l] == 0 && arr[r] != 0 || arr[r] == 0 && arr[l] != 0:
break
case arr[l]%arr[r] == 0 || arr[r]%arr[l] == 0:
if arr[l]/arr[r] == 2 || arr[r]/arr[l] == 2 {
return true
}
}
}
}
return false
}
func checkIfExist(arr []int) bool {
container := make(map[int]int, len(arr))
for i := 0; i < len(arr); i++ {
if _, ok := container[arr[i]*2]; ok {
return true
}else if _, ok := container[arr[i]/2]; ok && arr[i]%2 == 0 {
return true
} else {
container[arr[i]] = i
}
}
return false
}
func checkIfExist(arr []int) bool {
for i := 0; i < len(arr); i++ {
for j := i + 1; j < len(arr); j++ {
if arr[i] == arr[j] * 2 || arr[j] == arr[i] * 2 {
return true
}
}
}
return false
}
func checkIfExist(arr []int) bool {
ch := make(chan bool)
go checker(arr, ch)
return <-ch
}
func checker(arr []int, ch chan bool) {
e := len(arr)
for l := 0; l < e; l++ {
for r := e - 1; r > l; r-- {
switch {
case arr[l] == 0 && arr[r] == 0:
ch <- true
case arr[l] == 0 && arr[r] != 0 || arr[r] == 0 && arr[l] != 0:
break
case arr[l]%arr[r] == 0 || arr[r]%arr[l] == 0:
if arr[l]/arr[r] == 2 || arr[r]/arr[l] == 2 {
ch <- true
}
}
}
}
ch <- false
}
https://go.dev/play/p/NzR5mkdBz3M
func checkIfExist(arr []int) bool {
e := len(arr)
for l := 0; l < e; l++ {
for r := e - 1; r > l; r-- {
switch {
case arr[l]*2 == arr[r] || arr[r]*2 == arr[l]:
return true
}
}
}
return false
}
Arrays 101 Code from Java to Go(In-Place Array Operations Introduction) (0) | 2022.03.05 |
---|---|
Arrays101 Valid Mountain Array in GO (0) | 2022.03.04 |
Arrays 101 Code from Java to Go(Search in an Array) (0) | 2022.03.02 |
Array101 Remove Duplicates from Sorted Array in GO (0) | 2022.03.01 |
Leetcode Array101 Remove Element in GO (0) | 2022.02.27 |
댓글 영역