Devin
BAN USER
package com.company;
import java.util.*;
/**
* Created by ideven on 31/01/15.
*/
public class TopK {
int[] num={1,2,6,5,4,6,7,8,8,4,2,3,2,2,2,2,2,1,1,1,1};
public final int K=3;
Map<Integer,Integer> map= new HashMap<Integer,Integer>();
public void topK(){
for(int i=0;i<num.length;i++){
if(map.containsKey(num[i])){
int n=map.get(num[i]);
map.put(num[i],++n);
}
else{
map.put(num[i],1);
}
}
List<Map.Entry> list = new LinkedList<Map.Entry>(map.entrySet());
// Defined Custom Comparator here
Collections.sort(list, new Comparator() {
public int compare(Object o1, Object o2) {
return ((Comparable) ((Map.Entry) (o2)).getValue())
.compareTo(((Map.Entry) (o1)).getValue());
}
});
for(int k=0;k<K;k++){
System.out.println(list.get(k));
}
}
public static void main(String[] args){
TopK t= new TopK();
t.topK();
}
}
After sorting the array:
Basically there are two cases:
1) If the number of digits are even:
first two digits are multiplied with 10^(mid-1) each and added
second two digits are multiplied with 10^(mid -2) each and added and so on..
2)odd:
first digit is multiplied with 10^mid.. and so on as in 1 above
The theory is digit at highest place value should be least for both numbers..
import java.util.Arrays;
public class Minimum {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int arr[]={1,2,7,8,9};
Arrays.sort(arr);
int mid=arr.length/2;
int remainder=arr.length%2;
int power=mid;
int sum=0;
int count=0;
if(remainder==1)
{
sum+=arr[0]*Math.pow(10, power);
//System.out.println(sum);
power--;
for(int i=1;i<arr.length;i++)
{
count++;
sum+=arr[i]*Math.pow(10, power);
if(count==2)
{
power--;
count=0;
}
}
}
else if(remainder==0)
{power--;
for(int i=0;i<arr.length;i++)
{
count++;
sum+=arr[i]*Math.pow(10, power);
if(count==2)
{
power--;
count=0;
}
}
}
System.out.println(sum);
}
}
Hi
Here's the code
- Devin August 18, 2015