假设我们有一个数组:
array = [1, 0, 0, 0, 1, 0, 1, 1, 1];
我们希望找到一个重复数字的“运行”,其中至少连续三个。在这种情况下,它将是0,0,0和1,1,1的集合。
如何确定哪些索引包含三个或更多的“运行”?
答案 0 :(得分:0)
创建
HashMap<Integer, Integer> result = new HashMap<Integer, Integer>();
迭代你的数组存储数组值作为键,并将值的计数作为hashmap中的值:
for (int i: arrayToCount) {
Integer count = result.get(i);
if (count == null)
result.put(i, new Integer(1));
else
result.put(i, new Integer(count+1));
}
迭代HashMap并返回您的值。
答案 1 :(得分:0)
package algorithms;
import java.util.HashMap;
public class CountOfDupes {
HashMap<Integer, Integer> myMap = new HashMap<Integer, Integer>();
void incrementDupeCounter(int[] arr){
int curVal;
for (int rec : arr){
if (myMap.containsKey(rec)) {
curVal = myMap.get(rec);
myMap.put(rec, curVal + 1);
} else {
myMap.put(rec, 1);
}
}
}
void printRunEntries(){
for (HashMap.Entry<Integer, Integer> entry : myMap.entrySet()) {
if (entry.getValue() >= 3){
System.out.println(entry.getKey() + "/" + entry.getValue());
}
}
}
public static void main(String[] args) {
int arr[] = {1, 0, 0, 0, 1, 0, 1, 1, 1};
CountOfDupes cd = new CountOfDupes();
cd.incrementDupeCounter(arr);
cd.printRunEntries();
}
}
答案 2 :(得分:0)
运行class以保存运行信息
class Run {
int first,last,length,value;
public Run(int value, int first, int last){
this.value = value;
this.first = first;
this.last = last;
length = last - first + 1;
}
public int value(){return value;}
public int first(){return first;}
public int last(){return last;}
public int length(){return length;}
}
示例测试代码
int[] array = new int[]{1, 0, 0, 0, 1, 0, 1, 1, 1};
ArrayList<Run> runs = new ArrayList<Run>();
for(int i=0; i<array.length-2; i++){
if(array[i+1]==array[i]){
int j = i + 1;
int count = 2;
while(array[j+1] == array[i] && j<array.length - 1){
count++;
j++;
}
if(count>2){
runs.add(new Run(array[i], i, j));
}
i = j;
}
}
for(Run r : runs){
System.out.println("There is a run of " + r.length() +
" " + r.value() + "'s from index " + r.first() +
" to " + r.last() + ".");
}