Find Closest Number to Zero - Leetcode 2239 - Arrays & Strings (Python)

preview_player
Показать описание


Please check my playlists for free DSA problem solutions:

My Favorite Courses:

Data Structures & Algorithms:

Python:

Web Dev / Full Stack:

Cloud Development:

Game Development:

SQL & Data Science:

Machine Learning & AI:
Рекомендации по теме
Комментарии
Автор

Master Data Structures & Algorithms For FREE at AlgoMap.io!

GregHogg
Автор

Bro deserves an Oscar for explaining us time and space complexity just like that I a few minutes ❤❤

AffectionateSnowman-vwiq
Автор

Thank you so much keeping things free, please keep them free, helps a lot for 3rd world people.

parmeshwarrathod
Автор

Why not max() for the cases with multiple abs values?

egh
Автор

This is a fantastic explanation of the problem. Thank you, Greg!

bloxymath
Автор

Wouldn't it be better to use one "for" loop?

def func(nums):
closest = nums[0]
for x in nums:
if abs(x) < abs(closest):
closest = x
elif abs(x) == abs(closest) and x > closest:
closest = x
return closest

АртурИванов-ъв
Автор

If the abs values of nums[i] and abs(closest) are equal, closest can simply be considered as the abs(nums[i]) and returned.

Here's my JS code:

var findClosestNumber = function (nums) {
let closest = nums[0];

for (var i = 1; i < nums.length; i++) {
if (Math.abs(nums[i]) < Math.abs(closest )) {
closest = nums[i];
} else if (Math.abs(nums[i] == Math.abs(closest ))) {
closest = Math.abs(nums[i]);
}
}
return closest ;
}

bhuvanachandrag
Автор

Hi @GregHogg, Thank you for taking time and making these awesome videos. These are my first preference as help. I just wanted to add that, shouldn't we be looping from nums[1:] instead of nums[0]. Since we will be checking again if it's the closest one!

Adding my code here for your ref:

class Solution:
# Time complexity: O(n) and space complexity is O(1)
def findClosestNumber(self, nums: List[int]) -> int:
closest = nums[0]

for n in nums[1:]:
if abs(n) < abs(closest):
closest = n

if closest < 0 and abs(closest) in nums:
return abs(closest)
else:
return closest

Can you please clarify? Looking forward for your response.

Cheers,
Sonica

Sona-ykus
Автор

Thank you so much for the videos. Can you tell me why did the time complexity change from O(2n) to O(n)?

Surajmenon
Автор

my solution approach:
minimum_distance = min([abs(num) for num in nums])
if minimum_distance in nums:
return minimum_distance
else:
return -minimum_distance

qian
Автор

I'm new to programming but isn't {return min(nums, key=lambda x: (abs(x), -x))} faster or using the function like this make it slower ?

ahmedhossam
Автор

I managed to solve this one on my own, interesting how our solutions differed :0

russiachan
Автор

hey i wanted to ask you how you have improved your math skills i would like to learn from you ?

SanjayB-vygx
Автор

my JS code. i abandon loop early if i find distance of zero and try to avoid calls to Math.abs().

function closest(arr)
{
let n = arr.length;
let clos = Math.abs(arr[0]);
let index = 0;

for( let i = 1; clos && i < n; i++ )
{
let curr;

curr = arr[i];

if( curr > -clos && curr < clos )
{
index = i;
clos = Math.abs(curr);
}
else if( curr == clos && curr > 0 )
index = i;
}

return arr[index];
}

mazthespaz
Автор

Thanks, i love your ig videos
This is my code in ts
function findClosestNumber(nums: number[]): number {
let closest = nums[0];
for (const i in nums) {
if (Math.abs(nums[i]) < Math.abs(closest)) closest = nums[i];
else if (closest < 0 && Math.abs(closest) == nums[i]) closest = nums[i];
}
return closest;
}

josuevallejo
Автор

greg can you please make a video about question no 1509 in leetcode i cant understand the question only 😢 Question - Minimum Difference Between Largest and Smallest Value in Three Moves

AffectionateSnowman-vwiq
Автор

One pass? On a phone, didn't get to check all edge cases.

def closest(arr):
if len(arr) == 1:
return arr[0]
dist = abs(0 - arr[0])
res = arr[0]
for i in range(1, len(arr)):
curr = abs(0 - arr[i])
if curr == dist:
res = max(res, arr[i])
elif curr < dist:
dist = curr
res = arr[i]
return res


arr = [-2, -4, 1, 2, 8] # 1
# arr = [-2, 1, -1]
print(closest(arr)) # 1

tomislam
Автор

Not the fastest approach in PHP but done using a sort

<?php

$array = [-4, -2, 1, 4, 8];
usort($array, function ($a, $b) {
$distA = abs($a);
$distB = abs($b);
if ($distA === $distB) {
return ($a > $b) ? -1 : 1;
}

return ($distA > $distB) ? 1 : -1;
});
echo current($array);

warpcode
Автор

We can return abs (closest) and avoid using last condition?

khorshedkhorshed
Автор

gonna cheat:

return x: abs(x)==abs(a[0]), sorted(a, key=abs))))

DrDeuteron