Created
October 6, 2019 20:06
-
-
Save doanphihai/06473a945316e1ee96bfef11e6ab24a4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Rare { | |
public static int nthMostRare(int[] elements, int n) { | |
final Map<Integer, Integer> map = new HashMap<>(); | |
for (int i: elements) | |
{ | |
map.compute(i, (k, v) -> { | |
if (k == null) { | |
return 1; | |
} else { | |
if (v == null) return 1; | |
return v+1; | |
} | |
}); | |
} | |
Map<Integer, Integer> remap = sortByValue(map); | |
System.out.println(remap); | |
return (Integer) remap.keySet().toArray()[n-1]; | |
} | |
public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) { | |
List<Map.Entry<K, V>> list = new ArrayList<>(map.entrySet()); | |
list.sort(Map.Entry.comparingByValue()); | |
Map<K, V> result = new LinkedHashMap<>(); | |
for (Map.Entry<K, V> entry : list) { | |
result.put(entry.getKey(), entry.getValue()); | |
} | |
return result; | |
} | |
public static void main(String[] args) { | |
int x = nthMostRare(new int[] { 5, 4, 3, 2, 1, 5, 4, 3, 2, 5, 4, 3, 5, 4, 5 }, 2); | |
System.out.println(x); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment