java - Return the k elements of an array farthest from val -


method needs return k elements a[i] such abs(a[i] - val) k largest evaluation. code works integers greater val. fail if integers less val. can without importing other java.util.arrays? enlighten me? appreciated!

 public static int[] farthestk(int[] a, int val, int k) {// line should not change   int[] b = new int[a.length];   (int = 0; < b.length; i++) {      b[i] = math.abs(a[i] - val);   }   arrays.sort(b);   int[] c = new int[k];   int w = 0;   (int = b.length-1; > b.length-k-1; i--) {             c[w] = b[i] + val;      w++;        }   return c;     } 

test case:

  @test public void farthestktest() {          int[] = {-2, 4, -6, 7, 8, 13, 15};          int[] expected = {15, -6, 13, -2};          int[] actual = selector.farthestk(a, 4, 4);          assert.assertarrayequals(expected, actual);        }   there 1 failure:  1) farthestktest(selectortest)  arrays first differed @ element [1]; expected:<-6> was:<14>  failures!!!  tests run: 1,  failures: 1 

the top k problem can solved in many ways. in case add new parameter, doesn't matter.

the first , easiest one: sort array. time complexity: o(nlogn)

public static int[] farthestk(integer[] a, final int val, int k) {     arrays.sort(a, new java.util.comparator<integer>() {         @override         public int compare(integer o1, integer o2) {             return -math.abs(o1 - val) + math.abs(o2 - val);         }     });     int[] c = new int[k];     (int = 0; < k; i++) {         c[i] = a[i];     }     return c; } 

the second way: use heap save max k values, time complexity: o(nlogk)

/**  * use min heap save max k values. time complexity: o(nlogk)  */ public static int[] farthestkwithheap(integer[] a, final int val, int k) {     priorityqueue<integer> minheap = new priorityqueue<integer>(4,             new java.util.comparator<integer>() {                 @override                 public int compare(integer o1, integer o2) {                     return math.abs(o1 - val) - math.abs(o2 - val);                 }             });     (int : a) {         minheap.add(i);         if (minheap.size() > k) {             minheap.poll();         }     }     int[] c = new int[k];     (int = 0; < k; i++) {         c[i] = minheap.poll();     }     return c; } 

the third way: divide , conquer, quicksort. partition array 2 part, , find kth in 1 of them. time complexity: o(n + klogk) code little long, provide link here.

selection problem.


Comments

Popular posts from this blog

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

html - How to style widget with post count different than without post count -

url rewriting - How to redirect a http POST with urlrewritefilter -