43
43
44
44
<!-- 这里可写通用的实现逻辑 -->
45
45
46
+ ** 方法一:一次遍历**
47
+
48
+ 我们定义一个变量 $d$ 来记录当前最小的距离,初始时 $d=\infty$。然后我们遍历数组,对于每个元素 $x$,我们计算 $y=|x|$,如果 $y \lt d$ 或者 $y=d$ 且 $x \gt ans$,我们就更新答案 $ans=x$ 和 $d=y$。
49
+
50
+ 遍历结束后返回答案即可。
51
+
52
+ 时间复杂度 $O(n)$,其中 $n$ 是数组的长度。空间复杂度 $O(1)$。
53
+
46
54
<!-- tabs:start -->
47
55
48
56
### ** Python3**
52
60
``` python
53
61
class Solution :
54
62
def findClosestNumber (self , nums : List[int ]) -> int :
55
- ans, d = 0 , 1000000
56
- for v in nums:
57
- if (t := abs (v )) < d or (t == d and v > ans):
58
- ans, d = v, t
63
+ ans, d = 0 , inf
64
+ for x in nums:
65
+ if (y := abs (x )) < d or (y == d and x > ans):
66
+ ans, d = x, y
59
67
return ans
60
68
```
61
69
@@ -66,12 +74,12 @@ class Solution:
66
74
``` java
67
75
class Solution {
68
76
public int findClosestNumber (int [] nums ) {
69
- int ans = 0 , d = 1000000 ;
70
- for (int v : nums) {
71
- int t = Math . abs(v );
72
- if (t < d || (t == d && v > ans)) {
73
- ans = v ;
74
- d = t ;
77
+ int ans = 0 , d = 1 << 30 ;
78
+ for (int x : nums) {
79
+ int y = Math . abs(x );
80
+ if (y < d || (y == d && x > ans)) {
81
+ ans = x ;
82
+ d = y ;
75
83
}
76
84
}
77
85
return ans;
@@ -85,12 +93,12 @@ class Solution {
85
93
class Solution {
86
94
public:
87
95
int findClosestNumber(vector<int >& nums) {
88
- int ans = 0, d = 1e6 ;
89
- for (int& v : nums) {
90
- int t = abs(v );
91
- if (t < d || (t == d && v > ans)) {
92
- ans = v ;
93
- d = t ;
96
+ int ans = 0, d = 1 << 30 ;
97
+ for (int x : nums) {
98
+ int y = abs(x );
99
+ if (y < d || (y == d && x > ans)) {
100
+ ans = x ;
101
+ d = y ;
94
102
}
95
103
}
96
104
return ans;
@@ -102,11 +110,10 @@ public:
102
110
103
111
```go
104
112
func findClosestNumber(nums []int) int {
105
- ans, d := 0, 1000000
106
- for _, v := range nums {
107
- t := abs(v)
108
- if t < d || (t == d && v > ans) {
109
- ans, d = v, t
113
+ ans, d := 0, 1<<30
114
+ for _, x := range nums {
115
+ if y := abs(x); y < d || (y == d && x > ans) {
116
+ ans, d = x, y
110
117
}
111
118
}
112
119
return ans
@@ -123,7 +130,16 @@ func abs(x int) int {
123
130
### ** TypeScript**
124
131
125
132
``` ts
126
-
133
+ function findClosestNumber(nums : number []): number {
134
+ let [ans, d] = [0 , 1 << 30 ];
135
+ for (const x of nums ) {
136
+ const y = Math .abs (x );
137
+ if (y < d || (y == d && x > ans )) {
138
+ [ans , d ] = [x , y ];
139
+ }
140
+ }
141
+ return ans ;
142
+ }
127
143
```
128
144
129
145
### ** ...**
0 commit comments