[leetcode/lintcode 题解] 一致性哈希 II · Consistent Hashing II
Posted on 2020-07-15 10:06 九章算法 阅读(314) 评论(0) 收藏 举报【题目描述】
create(int n, int k)
addMachine(int machine_id)
getMachineIdByHashCode(int hashcode)
在线评测地址:
https://www.lintcode.com/problem/consistent-hashing-ii/?utm_source=sc-bky-zq
【样例】
输入: create(100, 3) addMachine(1) getMachineIdByHashCode(4) addMachine(2) getMachineIdByHashCode(61) getMachineIdByHashCode(91) 输出: [77,83,86] 1 [15,35,93] 1 2
输入: create(10, 5) addMachine(1) getMachineIdByHashCode(4) addMachine(2) getMachineIdByHashCode(0) getMachineIdByHashCode(1) getMachineIdByHashCode(2) getMachineIdByHashCode(3) getMachineIdByHashCode(4) getMachineIdByHashCode(5) 输出: [2,3,5,6,7] 1 [0,1,4,8,9] 2 2 1 1 2 1
【题解】
public class Solution { public int n, k; public Set<Integer> ids = null; public Map<Integer, List<Integer>> machines = null; // @param n a positive integer // @param k a positive integer // @return a Solution object public static Solution create(int n, int k) { // Write your code here Solution solution = new Solution(); solution.n = n; solution.k = k; solution.ids = new TreeSet<Integer>(); solution.machines = new HashMap<Integer, List<Integer>>(); return solution; } // @param machine_id an integer // @return a list of shard ids public List<Integer> addMachine(int machine_id) { // Write your code here Random ra = new Random(); List<Integer> random_nums = new ArrayList<Integer>(); for (int i = 0; i < k; ++i) { int index = ra.nextInt(n); while (ids.contains(index)) index = ra.nextInt(n); ids.add(index); random_nums.add(index); } Collections.sort(random_nums); machines.put(machine_id, random_nums); return random_nums; } // @param hashcode an integer // @return a machine id public int getMachineIdByHashCode(int hashcode) { // Write your code here int distance = n + 1; int machine_id = 0; for (Map.Entry<Integer, List<Integer>> entry : machines.entrySet()) { int key = entry.getKey(); List<Integer> random_nums = entry.getValue(); for (Integer num : random_nums) { int d = num - hashcode; if (d < 0) d += n; if (d < distance) { distance = d; machine_id = key; } } } return machine_id; } }
https://www.jiuzhang.com/solution/longest-palindromic-substring/?utm_source=sc-bky-zq