[#3516] feat(go): add golang solution
This commit is contained in:
3
problems/3516-find-closest-person/go/go.mod
Normal file
3
problems/3516-find-closest-person/go/go.mod
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
module leetcode-3516
|
||||||
|
|
||||||
|
go 1.18
|
71
problems/3516-find-closest-person/go/main.go
Normal file
71
problems/3516-find-closest-person/go/main.go
Normal file
@@ -0,0 +1,71 @@
|
|||||||
|
// LeetCode 3516: Find Closest Person
|
||||||
|
// 難度: Easy
|
||||||
|
// 日期: 2025-09-04
|
||||||
|
|
||||||
|
package main
|
||||||
|
|
||||||
|
import "fmt"
|
||||||
|
|
||||||
|
// TODO: 實作解法
|
||||||
|
func findClosest(x, y, z int) int {
|
||||||
|
distanceX := abs(x - z)
|
||||||
|
distanceY := abs(y - z)
|
||||||
|
|
||||||
|
if distanceX == distanceY{
|
||||||
|
return 0
|
||||||
|
}else if distanceX > distanceY{
|
||||||
|
return 2
|
||||||
|
}else{
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func abs(n int) int{
|
||||||
|
if n < 0 {
|
||||||
|
return -n
|
||||||
|
}
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
testCase1()
|
||||||
|
testCase2()
|
||||||
|
testCase3()
|
||||||
|
}
|
||||||
|
|
||||||
|
// 基本測試案例 - Example 1
|
||||||
|
func testCase1() {
|
||||||
|
// Input: x = 2, y = 7, z = 4
|
||||||
|
// Expected: 1 (Person 1 距離較近: |2-4| = 2 < |7-4| = 3)
|
||||||
|
actual := findClosest(2, 7, 4)
|
||||||
|
expected := 1
|
||||||
|
fmt.Printf("Test 1: Input(2, 7, 4) Expected: %d, Actual: %d, Result: %s\n",
|
||||||
|
expected, actual, getResult(actual == expected))
|
||||||
|
}
|
||||||
|
|
||||||
|
// 基本測試案例 - Example 2
|
||||||
|
func testCase2() {
|
||||||
|
// Input: x = 2, y = 5, z = 6
|
||||||
|
// Expected: 2 (Person 2 距離較近: |5-6| = 1 < |2-6| = 4)
|
||||||
|
actual := findClosest(2, 5, 6)
|
||||||
|
expected := 2
|
||||||
|
fmt.Printf("Test 2: Input(2, 5, 6) Expected: %d, Actual: %d, Result: %s\n",
|
||||||
|
expected, actual, getResult(actual == expected))
|
||||||
|
}
|
||||||
|
|
||||||
|
// 基本測試案例 - Example 3
|
||||||
|
func testCase3() {
|
||||||
|
// Input: x = 1, y = 5, z = 3
|
||||||
|
// Expected: 0 (距離相等: |1-3| = 2 = |5-3| = 2)
|
||||||
|
actual := findClosest(1, 5, 3)
|
||||||
|
expected := 0
|
||||||
|
fmt.Printf("Test 3: Input(1, 5, 3) Expected: %d, Actual: %d, Result: %s\n",
|
||||||
|
expected, actual, getResult(actual == expected))
|
||||||
|
}
|
||||||
|
|
||||||
|
func getResult(pass bool) string {
|
||||||
|
if pass {
|
||||||
|
return "PASS"
|
||||||
|
}
|
||||||
|
return "FAIL"
|
||||||
|
}
|
Reference in New Issue
Block a user