5 回答
TA贡献1802条经验 获得超10个赞
这里一个简单的方法就是迭代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) {
if (curr == null) {
curr = val;
count = 1;
}
else if (curr != val) {
System.out.print("(" + curr + ", " + count + ")");
curr = val;
count = 1;
}
else {
++count;
}
}
System.out.print("(" + curr + ", " + count + ")");
System.out.print("}");
{(20, 2)(30, 1)(40, 2)(20, 3)}
TA贡献1807条经验 获得超9个赞
Set<Integer> distinctSet = new HashSet<>(answerSheerPacketList);
HashSet<Integer,Integer> elementCountSet=new HashSet<>();
for (Integer element: distinctSet) {
elementCountSet.put(element,Collections.frequency(answerSheerPacketList, element));
}
TA贡献1818条经验 获得超7个赞
这是计算数组中连续元素运行的经典问题。arr
为简洁起见,我已将数组重命名为代码。
int run = 1; for (int i = 0; i < n; ++i) { // n is the size of array if (i + 1 < n && arr[i] == arr[i + 1]) { run++; // increment run if consecutive elements are equal } else { System.out.println(arr[i] + "=" + run + ", "); run = 1; // reset run if they are not equal } }
在性能方面,这种方法是渐近最优的并且在O(n)中运行,其中n是数组中元素的数量。
添加回答
举报