Find Closest Number to Zero LeetCode solution in Python

1
class Solution:
2

3
def findClosestNumber1(self, nums: List[int]) -> int:
4
return min(nums, key=lambda x: (abs(x), -x))
5

6
def findClosestNumber2(self, nums: List[int]) -> int:
7
return min(nums, key=lambda x: abs(x - 0.1))
8

9
def findClosestNumber3(self, nums: List[int]) -> int:
10
return max((-abs(x), x) for x in nums)[1]
11

12
def findClosestNumber4(self, nums: List[int]) -> int:
13
return -min(zip(map(abs, nums), map(neg, nums)))[1]
14

15
def findClosestNumber5(self, nums: List[int]) -> int:
16
a = min(map(abs, nums))
17
return a if a in nums else -a
18

19
def findClosestNumber6(self, nums: List[int]) -> int:
20
a = abs(min(nums, key=abs))
21
return a if a in nums else -a
22

23
def findClosestNumber7(self, nums: List[int]) -> int:
24
x = min(nums, key=abs)
25
return x if x >= 0 or -x not in nums else -x
26

27
def findClosestNumber8(self, nums: List[int]) -> int:
28
return min(sorted(nums, reverse=True), key=abs)
29

30
def findClosestNumber9(self, nums: List[int]) -> int:
31
a = abs(nums[0])
32
for x in nums:
33
if x < 0:
34
x = -x
35
if x < a:
36
a = x
37
return a if a in nums else -a
38

39
def findClosestNumberA(self, nums: List[int]) -> int:
40
pos = 999999
41
neg = -pos
42
for x in nums:
43
if x < 0:
44
if x > neg:
45
neg = x
46
elif x < pos:
47
pos = x
48
return pos if pos <= -neg else neg
49

50
def findClosestNumberB(self, nums: List[int]) -> int:
51
pos = 999999
52
neg = -pos
53
for x in nums:
54
if x < pos and neg < x:
55
if x < 0:
56
neg = x
57
else:
58
pos = x
59
return pos if pos <= -neg else neg
60

61
def findClosestNumberC(self, nums: List[int]) -> int:
62
pos = 999999
63
neg = -pos
64
for x in nums:
65
if neg < x and x < pos:
66
if x < 0:
67
neg = x
68
else:
69
pos = x
70
return pos if pos <= -neg else neg
71

72
def findClosestNumberD(self, nums: List[int]) -> int:
73
pos = 999999
74
neg = -pos
75
for x in nums:
76
if neg < x < pos:
77
if x < 0:
78
neg = x
79
else:
80
pos = x
81
return pos if pos <= -neg else neg
82

83
def findClosestNumber(
84
self, nums: List[int], timess=defaultdict(lambda: [0] * 10), testcase=[0]
85
) -> int:
86
name = "findClosestNumber"
87
solutions = [
88
getattr(self, s) for s in dir(self) if s.startswith(name) and s != name
89
]
90
expect = dummy = object()
91
from time import perf_counter as time
92

93
for i in range(10):
94
shuffle(solutions)
95
for solution in solutions:
96
start = time()
97
result = solution(nums)
98
end = time()
99
if expect is dummy:
100
expect = result
101
assert result == expect
102
timess[solution.__name__][i] += end - start
103
testcase[0] += 1
104
if testcase[0] == 224:
105
for name, times in sorted(timess.items(), key=lambda nt: sorted(nt[1])):
106
print(name, *(f"{t*1e3:6.2f} ms" for t in sorted(times)[:3]))
107
return
108
return result

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0