java - Insert an element into an array sorted according to frequency, then sort the array by frequency again -
so asked asked write o(n) function, insertranked(int[] list, int item)
, insert element array sorted frequency (i have written boolean function check if int[] list
sorted frequency). after inserting element array, array sorted again frequency.
for example, insertranked([65, 65, 65, 65, 1, 1, 1, 8, 8, 987, 987, 2, 2, 40], 2)
should produce [65, 65, 65, 65, 1, 1, 1, 2, 2, 2, 8, 8, 987, 987, 40]
.
is possible in o(n)? have thought of storing elements , counts linkedhashmap
, using collections.sort()
time complexity of collections.sort()
o(n*log(n)).
here's 1 approach start off based on count.
import java.util.arraylist; import java.util.hashmap; import java.util.treemap; public class sortcount { public static void main(string[] args) { int nums[] = {([65, 65, 65, 65, 1, 1, 1, 8, 8, 987, 987, 2, 2, 40}; hashmap<integer,integer> counts = new hashmap<integer,integer>(); for(int = 0; < nums.length; i++) { if(counts.containskey(nums[ integer c = counts.get(nums[i]) + 1; counts.put(nums[i], c); } else { counts.put(nums[i],1); } } valuecomparator<integer,integer> bvc = new valuecomparator<integer,integer>(counts); treemap<integer,integer> sortedmap = new treemap<integer,integer>(bvc); sortedmap.putall(counts); arraylist<integer> output = new arraylist<integer>(); for(integer : sortedmap.keyset()) { for(int c = 0; c < sortedmap.get(i); c++) { output.add(i); } } system.out.println(output.tostring()); } } //which uses comparator class compare values in map: import java.util.comparator; import java.util.map; public class valuecomparator<t1,t2 extends comparable<t2>> implements comparator<t1> { map<t1,t2> base; public valuecomparator(map<t1,t2> base) { this.base = base; } @override public int compare(t1 k1, t1 k2) { t2 val1 = base.get(k1); t2 val2 = base.get(k2); return val1.compareto(val2); } }
Comments
Post a Comment