性能优化练习
发布于: 2020 年 12 月 12 日
有两个单向链表(链表长度分别为 m,n),这两个单向链表有可能在某个元素合并,也可能不合并,如下图所示的这样。现在给定两个链表的头指针,在不修改链表的情况下,如何快速地判断这两个链表是否合并?如果合并,找到合并的元素,也就是图中的 x 元素。
请用代码(或伪代码)描述算法,并给出时间复杂度。
public class LinkedListCheck { private static int BOUND = 26; private static LinkedList<String> aLinkedList = Lists.newLinkedList(); private static LinkedList<String> bLinkedList = Lists.newLinkedList();
String[] letterArray = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n" ,"o","p","q","r","s","t","u","v","w","x","y","z"};
public LinkedListCheck() { init(13,15); }
private void init(int m, int n) { aLinkedList.add("a"); aLinkedList.add("b"); aLinkedList.add("x"); aLinkedList.add("y"); aLinkedList.add("z");
bLinkedList.add("d"); bLinkedList.add("e"); bLinkedList.add("f"); bLinkedList.add("x"); bLinkedList.add("y"); bLinkedList.add("z");// buildLinked(aLinkedList, m);// buildLinked(bLinkedList, n); System.out.println(aLinkedList.toString()); System.out.println(bLinkedList.toString()); }
private void buildLinked(LinkedList<String> linkedList, int size) { for (int i = 0; i < size; i++) { Random random = new Random(); int index = random.nextInt(BOUND); linkedList.add(letterArray[index]); } }
private String findItem() { int m = aLinkedList.size(); int n = bLinkedList.size(); Map<String, Integer> resultMapA = Maps.newHashMap(); Map<String, Integer> resultMapB = Maps.newHashMap(); for (int i = 0; i < m || i < n; i++) { String a = null; if (i<m) { a = aLinkedList.get(i); } String b = null; if (i<n) { b = bLinkedList.get(i); } String resultA = null; if (StringUtils.isNotBlank(a)) { resultA = processMap(resultMapA, resultMapB, a); } if(resultA!=null) { return resultA; } else { String resultB = null; if (StringUtils.isNotBlank(b)) { resultB = processMap(resultMapB, resultMapA, b); } if(resultB!=null) { return resultB; } } } return null; }
private String processMap(Map<String, Integer> storeMap, Map<String, Integer> targetMap, String targetValue) { Integer value = targetMap.getOrDefault(targetValue, 0); if (value.intValue()>=1) { return targetValue; } else { Integer tempValue = storeMap.getOrDefault(targetValue, 0); storeMap.put(targetValue, ++tempValue); } return null; }
public static void main(String[] args) { LinkedListCheck linkedListCheck = new LinkedListCheck(); System.out.println("合并元素是:"+linkedListCheck.findItem()); }}复制代码
结果如下:
时间复杂度:O(n)[a, b, x, y, z][d, e, f, x, y, z]合并元素是:x复制代码
划线
评论
复制
发布于: 2020 年 12 月 12 日阅读数: 27
版权声明: 本文为 InfoQ 作者【Mars】的原创文章。
原文链接:【http://xie.infoq.cn/article/64dc4ccd3740a4c38bcda701b】。
本文遵守【CC-BY 4.0】协议,转载请保留原文出处及本版权声明。
Mars
关注
还未添加个人签名 2018.06.12 加入
还未添加个人简介











评论