LeetCode 658. Find K Closest Elements

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

Рекомендации по теме
Комментарии
Автор

great solution but i have one doubt....
why cant we use absolute difference of x, a[mid] and a[mid+k], x. Instead you use
if(x-a[mid]<a[mid+k]-x)
how cant we use absolute differnce???

elanchezian
Автор

What is the Time Complexity for this solution ?

jayitaroy
Автор

This explanation was so bad I think I'm actually dumber after it.

Phaze
Автор

Can you identify what is wrong in my solution:

boolean possible(int arr[], int mid, int k, int x)
{
return x - arr[mid]<=arr[mid+k-1] - x;
}

public List<Integer> findClosestElements(int[] arr, int k, int x) {

ArrayList<Integer> al = new ArrayList<>(k);
if(arr.length==1)
{
al.add(arr[0]);
return al;
}
int left = 0;
int right = arr.length - k;

int bestAns = -1;

while(left <= right)
{

int mid = left + (right - left) / 2;
if(possible(arr, mid, k, x))
{
bestAns = mid;
right = mid - 1;
}
else
{
left = mid + 1;
}
}

for( int i =bestAns ; i<bestAns+k ; ++i)
al.add(arr[i]);
return al;
}

rohansirohia
Автор

Watching this video is wastage of time. Extremely bad explanation

zhunzargulhane
Автор

why you are using arr[mid+k] it should be arr[mid] to arr[mid+k-1] why you are going out of range here.

paragroy
Автор

what was that at 6:43 !! you well deserve the dislikes

ahmadalk