diff --git a/leetcode/1301-1400/1362.Closest-Divisors/README.md b/leetcode/1301-1400/1362.Closest-Divisors/README.md index 202a9dc57..9d78299e4 100644 --- a/leetcode/1301-1400/1362.Closest-Divisors/README.md +++ b/leetcode/1301-1400/1362.Closest-Divisors/README.md @@ -1,28 +1,31 @@ # [1362.Closest Divisors][title] -> [!WARNING|style:flat] -> This question is temporarily unanswered if you have good ideas. Welcome to [Create Pull Request PR](https://github.com/kylesliu/awesome-golang-algorithm) - ## Description +Given an integer `num`, find the closest two integers in absolute difference whose product equals `num + 1` or `num + 2`. + +Return the two integers in any order. **Example 1:** ``` -Input: a = "11", b = "1" -Output: "100" +Input: num = 8 +Output: [3,3] +Explanation: For num + 1 = 9, the closest divisors are 3 & 3, for num + 2 = 10, the closest divisors are 2 & 5, hence 3 & 3 is chosen. ``` -## 题意 -> ... +**Example 2:** -## 题解 - -### 思路1 -> ... -Closest Divisors -```go +``` +Input: num = 123 +Output: [5,25] ``` +**Example 3:** + +``` +Input: num = 999 +Output: [40,25] +``` ## 结语 diff --git a/leetcode/1301-1400/1362.Closest-Divisors/Solution.go b/leetcode/1301-1400/1362.Closest-Divisors/Solution.go index d115ccf5e..e319fd782 100644 --- a/leetcode/1301-1400/1362.Closest-Divisors/Solution.go +++ b/leetcode/1301-1400/1362.Closest-Divisors/Solution.go @@ -1,5 +1,33 @@ package Solution -func Solution(x bool) bool { - return x +import "math" + +func factor(n int) (int, int) { + sn := int(math.Sqrt(float64(n))) + a, b := 1, n + for i := sn; i >= 1; i-- { + if n%i != 0 { + continue + } + a, b = i, n/i + break + } + return a, b +} + +func Solution(num int) []int { + a1, b1 := factor(num + 1) + a2, b2 := factor(num + 2) + diff1 := b1 - a1 + if diff1 < 0 { + diff1 = -diff1 + } + diff2 := b2 - a2 + if diff2 < 0 { + diff2 = -diff2 + } + if diff1 < diff2 { + return []int{a1, b1} + } + return []int{a2, b2} } diff --git a/leetcode/1301-1400/1362.Closest-Divisors/Solution_test.go b/leetcode/1301-1400/1362.Closest-Divisors/Solution_test.go index 14ff50eb4..bb7736beb 100644 --- a/leetcode/1301-1400/1362.Closest-Divisors/Solution_test.go +++ b/leetcode/1301-1400/1362.Closest-Divisors/Solution_test.go @@ -10,12 +10,12 @@ func TestSolution(t *testing.T) { // 测试用例 cases := []struct { name string - inputs bool - expect bool + inputs int + expect []int }{ - {"TestCase", true, true}, - {"TestCase", true, true}, - {"TestCase", false, false}, + {"TestCase1", 8, []int{3, 3}}, + {"TestCase2", 123, []int{5, 25}}, + {"TestCase3", 999, []int{25, 40}}, } // 开始测试 @@ -30,10 +30,10 @@ func TestSolution(t *testing.T) { } } -// 压力测试 +// 压力测试 func BenchmarkSolution(b *testing.B) { } -// 使用案列 +// 使用案列 func ExampleSolution() { }