20250624java面试总结
算法题:一个rpc请求,输入是map<String,List>
key是商品类别字符串(good/travel/hotel)
value是商品id
如果商品数量过多或者类别过多,会导致rpc请求耗时过长,出现尖刺,为了平滑请求时间,如果key超过3个或者value超过3个,则进行请求拆分,
输出为:List<Map<String, List>
示例:
输入:
{
“good”:[1,2,3,4],
“travel”:[11,12,13,14],
“hotel”:[21,22,23]
}
输出为:[
{ “good”:[1,2,3],
“travel”:[11,12,13],
“hotel”:[21,22,23]
},
{
“good”:[4],
“travel”:[14]
}
]
示例代码:
public class SliceRpcRequest {public static void main(String[] args) {Map<String,List<Long>> request = new HashMap<>();request.put("good", Arrays.asList(1L,2L,3L,4L,5L,6L));request.put("travel", Arrays.asList(99L,92L,93L,94L,95L,96L,97L,98L));request.put("hotel", Arrays.asList(88L));request.put("ticket", Arrays.asList(1000L,10000L, 1233424L,123434L));List<Map<String,List<Long>>> res = sliceRequest(request);for (int i = 0; i < res.size(); i++) {Map<String, List<Long>> map = res.get(i);System.out.println("=========");for (Map.Entry<String,List<Long>> entry : map.entrySet()) {System.out.println(entry.getKey() + ":" + Arrays.toString(entry.getValue().toArray()));}}}public static List<Map<String, List<Long>>> sliceRequest(Map<String, List<Long>> request) {List<Map<String, List<Long>>> list = new ArrayList<>();int index = 0;// // good:1,2,3,4,5,6// // travel: 99,92,93,94,95,96,97,98// // hotel: 88// // ticket: 1000, 10000, 1233424, 123434for (Map.Entry<String, List<Long>> entry : request.entrySet()) {String key = entry.getKey();List<Long> value = entry.getValue();Map<String, List<Long>> map = get(list, index);while(map.size() >= 3) {map = get(list, ++index);}if (value.size() <= 3) {map.put(key, value);} else {List<List<Long>> valueList = sliceValue(value);Map<String, List<Long>> tmpMap = map;int tmpIndex = index;for (int i = 0; i < valueList.size(); i++) {tmpMap.put(key, valueList.get(i));tmpMap = get(list, ++tmpIndex);}}}return list;}public static Map<String, List<Long>> get(List<Map<String, List<Long>>> list, int index) {if (list.size() == index) {Map<String, List<Long>> map = new HashMap<>(16);list.add(map);return map;}return list.get(index);}public static List<List<Long>> sliceValue(List<Long> value) {if (value.size() <= 3) {return Arrays.asList(value);}List<List<Long>> res = new ArrayList<>();for(int i = 0;i < value.size();i++) {int endIndex = Math.min(i + 3, value.size());res.add(value.subList(i, endIndex));i = endIndex-1;}return res;}