对于不在A中的元素,全部排在最后,同时按照整数大小进行排序。
1条回答 默认 最新
- 农夫丶果园 2020-06-08 10:23关注
我的思路是这样的 , 把A中元素放在一个链表数组中, 每个位置都是一个多节点或单节点的链表 , 这样重复元素就可以直接插在链表中 , A中顺序也能得到保障 , 具体看代码把 , 应该比较好理解
```public static void main(String[] args) {
ArrayList listA = new ArrayList<>();
ArrayList listB = new ArrayList<>();
for (int i = 0; i < 100; i++) { // 保证A中元素一定出现在B中
listA.add(i);
listB.add(i);
}
Random random = new Random();
for (int i = 0; i < 50; i++) { // 增加五十个200以内的随机整数
listB.add(random.nextInt(200));
}
// 打乱集合
Collections.shuffle(listA);
Collections.shuffle(listB);
System.out.println("============== element in A ==============");
listA.forEach(a -> System.out.print(a + ","));
System.out.println("\n============== element in B ==============");
listB.forEach(a -> System.out.print(a + ","));
listB = sort(listA,listB);
System.out.println("\n============== element in sorted B ==============");
listB.forEach(a -> System.out.print(a + ","));
}/** * * @param listA 100 size, non repeat * @param listB 1000 size, has all element of A and other element, element repeatable */ static ArrayList<Integer> sort(ArrayList<Integer> listA, ArrayList<Integer> listB) { // 头集合, 存放在A中的元素 ArrayList<Integer> headList = new ArrayList<>(); // 尾集合, 存放不在A中的元素 ArrayList<Integer> tailList = new ArrayList<>(); // A中元素对应的下标位置, 即顺序 Map<Integer,Integer> eleIndexMap = new HashMap<>(listA.size()); Integer ele = null; for (int i = 0; i < listA.size(); i++) { ele = listA.get(i); eleIndexMap.put(ele, i); } // 链表数组 Node[] nodes = new Node[listA.size()]; Node node = null; Integer index = null; for (int i = 0; i < listB.size(); i++) { ele = listB.get(i); // 获取元素在A中的下标 index = eleIndexMap.get(ele); if (index == null) { // 该元素不在A中 tailList.add(ele); continue; } // 在A中则取出链表数组中对应位置的头节点 node = nodes[index]; if (node == null) { // 第一次出现, 添加到数组中 nodes[index] = new Node(ele); } else { // 不是第一次出现则找到该位置的链表的尾节点, 添加到尾节点之后 while (true) { if (node.next == null) { break; } node = node.next; } node.next = new Node(ele); } } for (Node nod : nodes) { while (nod != null) { headList.add(nod.ele); nod = nod.next; } } Collections.sort(tailList); headList.addAll(tailList); return headList; } static class Node { Node next; Integer ele; public Node(Integer ele) { this.ele = ele; } }
解决 无用评论 打赏 举报
悬赏问题
- ¥17 pro*C预编译“闪回查询”报错SCN不能识别
- ¥15 微信会员卡接入微信支付商户号收款
- ¥15 如何获取烟草零售终端数据
- ¥15 数学建模招标中位数问题
- ¥15 phython路径名过长报错 不知道什么问题
- ¥15 深度学习中模型转换该怎么实现
- ¥15 HLs设计手写数字识别程序编译通不过
- ¥15 Stata外部命令安装问题求帮助!
- ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
- ¥15 TYPCE母转母,插入认方向