某家超市有一种促销手段,购买金额超过一定阈值就随机给一个贴花。贴花有不同种类的,种类以编号表示,编号是一个1到100之间的数字。当收集到连续编号的三张贴花时,就可以换一个小礼物。
小明经常去某家超市购物,积攒了不少贴花,你帮他看看,能换多少小礼物。
输入格式:
首先是一个正整数N(1<N<100),表示小明手上的贴花的数量。 然后是N个正整数Pi(1<=Pi<=100),每个数字表示一张贴花的编号。
输出格式:
输出一个数字,表示小明可以换的小礼物的数量。如果不能换小礼物,就输出0。
输入样例:
6
3 2 4 6 6 4
输出样例:
1
2 3 4是一个组合,之后剩下的4 6 6不是连续的编号
这里的使用map集合解决,其实数组更加方便,但是有点浪费内存
import java.util.*;
public class Main {
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
int n= sc.nextInt(),count=0;
TreeMap<Integer,Integer> tm=new TreeMap<>();
for (int i = 0; i < n; i++) {
int a= sc.nextInt();
if (tm.get(a)!=null)tm.put(a,tm.get(a)+1);
else tm.put(a,1);
}
Set<Integer> set = tm.keySet();
int index=0,temp=0,first=0,last=0;
//index用来标记每次读取三个的记录
for (Integer integer : set) {
if (index==0)first=integer;//first用来记录前一个数据
else if (index==2)last=integer;//last记录最后一个数据
else temp=integer;
if (temp-first==1&&last-temp==1){
int min=Math.min(tm.get(temp),tm.get(first));
min=Math.min(min,tm.get(last));
count+=min;//min用来记录最小值,即最多能换几次
}
index++;
if (index>2)index=0;
}
System.out.println(count);
}
}