Skip to content

Commit 91ecc45

Browse files
authored
Merge pull request #298 from 0xff-dev/2239
Add solution and test-cases for problem 2239
2 parents e5d1c39 + 26e2823 commit 91ecc45

File tree

3 files changed

+42
-21
lines changed

3 files changed

+42
-21
lines changed

leetcode/2201-2300/2239.Find-Closest-Number-to-Zero/README.md

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,30 @@
11
# [2239.Find Closest Number to Zero][title]
22

3-
> [!WARNING|style:flat]
4-
> This question is temporarily unanswered if you have good ideas. Welcome to [Create Pull Request PR](https://github.com/kylesliu/awesome-golang-algorithm)
5-
63
## Description
4+
Given an integer array `nums` of size n, return the number with the value **closest** to `0` in `nums`. If there are multiple answers, return the number with the `largest` value.
5+
76

87
**Example 1:**
98

109
```
11-
Input: a = "11", b = "1"
12-
Output: "100"
10+
Input: nums = [-4,-2,1,4,8]
11+
Output: 1
12+
Explanation:
13+
The distance from -4 to 0 is |-4| = 4.
14+
The distance from -2 to 0 is |-2| = 2.
15+
The distance from 1 to 0 is |1| = 1.
16+
The distance from 4 to 0 is |4| = 4.
17+
The distance from 8 to 0 is |8| = 8.
18+
Thus, the closest number to 0 in the array is 1.
1319
```
1420

15-
## 题意
16-
> ...
17-
18-
## 题解
21+
**Example 2:**
1922

20-
### 思路1
21-
> ...
22-
Find Closest Number to Zero
23-
```go
2423
```
25-
24+
Input: nums = [2,-1,1]
25+
Output: 1
26+
Explanation: 1 and -1 are both the closest numbers to 0, so 1 being larger is returned.
27+
```
2628

2729
## 结语
2830

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,24 @@
11
package Solution
22

3-
func Solution(x bool) bool {
4-
return x
3+
func Solution(nums []int) int {
4+
absMin, ans := -1, 0
5+
for idx := 0; idx < len(nums); idx++ {
6+
target := nums[idx]
7+
if target < 0 {
8+
target = -target
9+
}
10+
if absMin == -1 {
11+
// first
12+
absMin = target
13+
ans = nums[idx]
14+
continue
15+
}
16+
if target <= absMin {
17+
if target < absMin || ans < nums[idx] {
18+
ans = nums[idx]
19+
}
20+
absMin = target
21+
}
22+
}
23+
return ans
524
}

leetcode/2201-2300/2239.Find-Closest-Number-to-Zero/Solution_test.go

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,12 @@ func TestSolution(t *testing.T) {
1010
// 测试用例
1111
cases := []struct {
1212
name string
13-
inputs bool
14-
expect bool
13+
inputs []int
14+
expect int
1515
}{
16-
{"TestCase", true, true},
17-
{"TestCase", true, true},
18-
{"TestCase", false, false},
16+
{"TestCase1", []int{-4, -2, 1, 4, 8}, 1},
17+
{"TestCase2", []int{2, -1, 1}, 1},
18+
{"TestCase3", []int{-3, -2, -1, 0, 1, 2, 3}, 0},
1919
}
2020

2121
// 开始测试

0 commit comments

Comments
 (0)