package leetcode; import java.util.*; public class ConsistentHash { public List> consistentHashing(int n) { // Write your code here PriorityQueue> pq = new PriorityQueue>(n, new Comparator>() { public int compare(ArrayList o1, ArrayList o2) { int diff = (o1.get(1) - o1.get(0)) - (o2.get(1) - o2.get(0)); if(diff == 0){ return o1.get(2) - o2.get(2); } else if (diff < 0) { return 1; } else{ return -1; } } }); pq.add(new ArrayList(Arrays.asList(0,359,1))); int maxId = 2; while(maxId <= n){ ArrayList range = pq.poll(); int x = range.get(0); int y = range.get(1); int id = range.get(2); ArrayList first = new ArrayList(Arrays.asList(x,(x+y)/2,id)); ArrayList second = new ArrayList(Arrays.asList((x+y)/2+1,y,maxId++)); pq.offer(first); pq.offer(second); } List> ret = new ArrayList>(); while(!pq.isEmpty()){ ret.add(pq.poll()); } Collections.sort(ret, new Comparator>() { public int compare(List o1, List o2) { return o1.get(0) - o2.get(0); } }); return ret; } public static void main(String[] args) { ConsistentHash ch = new ConsistentHash(); for(List a:ch.consistentHashing(6)){ System.out.println(a); } } }