Last active
September 24, 2018 06:07
-
-
Save namtx/f4a1e5c813393e3123941f9fb16271a4 to your computer and use it in GitHub Desktop.
fair-candy-swap (https://leetcode.com/problems/fair-candy-swap/description/)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"sort" | |
) | |
func main() { | |
A := []int{32, 38, 8, 1, 9} | |
B := []int{68, 92} | |
fmt.Println(fairCandySwap(A, B)) | |
// fairCandySwap(A, B) | |
} | |
func fairCandySwap(A []int, B []int) []int { | |
sumA := 0 | |
sumB := 0 | |
for _, c := range A { | |
sumA += c | |
} | |
for _, c := range B { | |
sumB += c | |
} | |
sort.Ints(A) | |
sort.Ints(B) | |
i := 0 | |
j := 0 | |
diff := sumA - sumB | |
for i < len(A) && j < len(B) { | |
if A[i]-B[j] == diff/2 { | |
return []int{A[i], B[j]} | |
} | |
if diff > 0 { | |
if A[i]-B[j] < diff/2 { | |
i++ | |
} else { | |
j++ | |
} | |
} else { | |
if A[i]-B[j] > diff/2 { | |
j++ | |
} else { | |
i++ | |
} | |
} | |
} | |
return []int{} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
) | |
func main() { | |
A := []int{32, 38, 8, 1, 9} | |
B := []int{68, 92} | |
fmt.Println(fairCandySwap(A, B)) | |
// fairCandySwap(A, B) | |
} | |
func fairCandySwap(A []int, B []int) []int { | |
sumA, sumB := 0, 0 | |
inA := map[int]struct{}{} | |
for _, a := range A { | |
sumA += a | |
inA[a] = struct{}{} | |
} | |
for _, b := range B { | |
sumB += b | |
} | |
m := (sumA - sumB) / 2 | |
a, b := 0, 0 | |
for _, b := range B { | |
a = b + m | |
if _, ok := inA[a]; ok { | |
break | |
} | |
} | |
return []int{a, b} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment