Skip to content

Commit

Permalink
find k closest numbers problem statement and neat solution
Browse files Browse the repository at this point in the history
  • Loading branch information
Sherali Obidov committed Aug 30, 2017
1 parent ac7b45b commit d9bd77f
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/problems/Medium.txt
Original file line number Diff line number Diff line change
Expand Up @@ -1705,3 +1705,17 @@ Follow up:
It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass?
Space complexity should be O(n).
Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.

145) Find K Closest Elements
Given a sorted array, two integers k and x, find the k closest elements to x in the array. The result should also be sorted in ascending order. If there is a tie, the smaller elements are always preferred.

Example 1:
Input: [1,2,3,4,5], k=4, x=3
Output: [1,2,3,4]
Example 2:
Input: [1,2,3,4,5], k=4, x=-1
Output: [1,2,3,4]
Note:
The value k is positive and will always be smaller than the length of the sorted array.
Length of the given array is positive and will not exceed 104
Absolute value of elements in the array and x will not exceed 104
30 changes: 30 additions & 0 deletions src/problems/medium/FindKClosestElements.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package problems.medium;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.PriorityQueue;

/**
* @author Sherali Obidov.
*/
public class FindKClosestElements {

public List<Integer> findClosestElements(List<Integer> arr, int k, int x) {
List<Integer> list= new ArrayList<>();
if(arr==null || arr.size()==0 || k==0)return list;

PriorityQueue<Integer> q= new PriorityQueue<>((a, b)-> {
int d= (Math.abs(x-a))-(Math.abs(x-b));
if(d==0)return a-b;
return d;
});
q.addAll(arr);
if(q.size()<k)return list;
for(int i=0; i<k; i++){
list.add(q.remove());
}
Collections.sort(list);
return list;
}
}
1 change: 1 addition & 0 deletions src/problems/medium/Permutations.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import java.util.ArrayList;
import java.util.List;
import java.util.PriorityQueue;

/**
* Created by sherxon on 1/12/17.
Expand Down

0 comments on commit d9bd77f

Please sign in to comment.