假设我有一个值为{0,1,1,0,1,1,1}的数组列表 这里,连续序列中值1的最大重复是3。 我如何找到最大数量。
List<String> list = new ArrayList<String>();
for (int i=0;i<5;i++)
{
System.out.println("Enter value");
x = in.nextLine();
list.add(""+x);
}
Map<String, Integer> countMap = new HashMap<>();
for (String word : list) {
Integer count = countMap.get(word);
if(count == null) {
count = 0;
}
countMap.put(word, (count.intValue()+1));
}
这给出了相同值的总计数,但我需要最大连续值。
答案 0 :(得分:1)
public static void main(String args[]) throws IOException{
List<String> list = new ArrayList<String>();
List<String> temp = new ArrayList<String>();
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(r);
for (int i=0;i<15;i++)
{
System.out.println("Enter value");
String x=br.readLine();
list.add(x);
}
LinkedHashMap<String, Integer> lhm=new LinkedHashMap<String, Integer>();
for(String str1:list){
int flag=0;
for(Entry<String, Integer> entry:lhm.entrySet()){
if(entry.getKey().equals(str1)){
flag=1;
break;
}}
if(flag==0){
lhm.put(str1, 1);
}
}
int maxCount = 1;
int currCount = 1;
for (int i=1;i<list.size();++i) {
if (list.get(i).equals(list.get(i-1))) {
++currCount;
if(list.size()==i+1){
maxCount = Math.max(lhm.get(list.get(i)), currCount);
lhm.put(list.get(i), maxCount);
}
} else {
maxCount = Math.max(lhm.get(list.get(i-1)), currCount);
lhm.put(list.get(i-1), maxCount);
currCount = 1;
}
}
for(Entry<String, Integer> entry:lhm.entrySet()){
System.out.println("Maximum Sequential occurrence of element- "+entry.getKey()+" is- "+entry.getValue());//display result
}
}
上面的代码将打印列表中所有元素的最大连续出现次数。
答案 1 :(得分:0)
怎么样:
// Initialize to 1 because first element is equal to itself.
int maxCount = 1;
int currCount = 1;
for (int i=1;i<list.size();++i) {
if (list.get(i).equals(list.get(i-1))) {
++currCount;
} else {
currCount = 1;
}
maxCount = Math.max(maxCount, currCount);
}
return maxCount;
这会迭代您的序列并找到最长的连续序列。