Go/Leet Code
Arrays101 Check If N and Its Double Exist in go
Gopythor
2022. 3. 2. 23:25
728x90
반응형
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
Code
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
}
- First I wanted to used switch for simplicity.
- So I made switch condition as l>r and l/r.
- But test cases has negative numbers.
- I changed all to check normal conditions for both positive and negative numbers.
- l is left as start of array and r is right as end of array.
Sample 0 ms submission
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
}
- I think this code is really clean
- First, If condition checks that there is arr[i]*2 value as a key of map.
- If not, Second, arr[i] will be devided by 2 also check remainder is zero because devide returns only quotient.
- Lastly, If there is no key, arr[i] value will be added in map with index(actually no meaning).
Sample 1 ms submission & Sample 2900 KB submission
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
}
- This code also is very simple.
- Just check if arr values are doubled compared to other values.
Go routine exercise
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
Modification code
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
}
728x90
반응형