Arraylist找到连续重复元素的数量

我试图在数组列表中找到重复元素的COUNT。例如,如果名为“answerSheerPacketList”列表的数组包含值{20,20,30,40,40,20,20,20},我需要显示输出{20=2,30=1,40=2,20=3}

Map<String, Integer> hm = new HashMap<String, Integer>();for (String a : answerSheerPacketList) {

    Integer j = hm.getinsAnswerSheetId(a);
    hm.put(a, (j == null) ? 1 : j + 1);}

    // displaying the occurrence of elements in the arraylistfor(Map.Entry<String, Integer> val : hm.entrySet()){

     System.out.println("Element " + val.getKey() + " " 
    "occurs" + ": " + val.getValue()+ " times");}

当我执行上面的代码我得到输出,{20=5,30=1,40=2}但我想得到一个输出{20=2,30=1,40=2,20=3}


墨色风雨
浏览 1503回答 5
5回答

守候你守候我

这里一个简单的方法就是迭代arraylist一次,然后随着我们继续记录:List<Integer> list = new ArrayList<>();list.add(20);list.add(20);list.add(30);list.add(40);list.add(40);list.add(20);list.add(20);list.add(20);Integer curr = null;int count = 0;System.out.print("{");for (int val : list) {&nbsp; &nbsp; if (curr == null) {&nbsp; &nbsp; &nbsp; &nbsp; curr = val;&nbsp; &nbsp; &nbsp; &nbsp; count = 1;&nbsp; &nbsp; }&nbsp; &nbsp; else if (curr != val) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.print("(" + curr + ", " + count + ")");&nbsp; &nbsp; &nbsp; &nbsp; curr = val;&nbsp; &nbsp; &nbsp; &nbsp; count = 1;&nbsp; &nbsp; }&nbsp; &nbsp; else {&nbsp; &nbsp; &nbsp; &nbsp; ++count;&nbsp; &nbsp; }}System.out.print("(" + curr + ", " + count + ")");System.out.print("}");{(20, 2)(30, 1)(40, 2)(20, 3)}

函数式编程

Set<Integer> distinctSet = new HashSet<>(answerSheerPacketList);&nbsp; &nbsp; HashSet<Integer,Integer> elementCountSet=new HashSet<>();&nbsp; &nbsp; for (Integer element: distinctSet) {&nbsp; &nbsp; elementCountSet.put(element,Collections.frequency(answerSheerPacketList, element));&nbsp; &nbsp; }

qq_笑_17

这是计算数组中连续元素运行的经典问题。arr为简洁起见,我已将数组重命名为代码。&nbsp;&nbsp;&nbsp;&nbsp;int&nbsp;run&nbsp;=&nbsp;1; &nbsp;&nbsp;&nbsp;&nbsp;for&nbsp;(int&nbsp;i&nbsp;=&nbsp;0;&nbsp;i&nbsp;<&nbsp;n;&nbsp;++i)&nbsp;{&nbsp;&nbsp;&nbsp;//&nbsp;n&nbsp;is&nbsp;the&nbsp;size&nbsp;of&nbsp;array &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;(i&nbsp;+&nbsp;1&nbsp;<&nbsp;n&nbsp;&&&nbsp;arr[i]&nbsp;==&nbsp;arr[i&nbsp;+&nbsp;1])&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;run++;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;increment&nbsp;run&nbsp;if&nbsp;consecutive&nbsp;elements&nbsp;are&nbsp;equal &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}&nbsp;else&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;System.out.println(arr[i]&nbsp;+&nbsp;"="&nbsp;+&nbsp;run&nbsp;+&nbsp;",&nbsp;"); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;run&nbsp;=&nbsp;1;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;reset&nbsp;run&nbsp;if&nbsp;they&nbsp;are&nbsp;not&nbsp;equal &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;}在性能方面,这种方法是渐近最优的并且在O(n)中运行,其中n是数组中元素的数量。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java