7-8 超市奖票兑换 (10 分)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_44547670/article/details/102760018

7-8 超市奖票兑换 (10 分)

某家超市有一种促销手段,购买金额超过一定金额就给一张随机编号奖票。编号是一个1到100之间的数字。当收集到连续编号的三张贴花时,就可以换一个小礼物。兑换完礼物后,该奖票就作废。

小明经常去某家超市购物,积攒了不少奖票,你帮他看看,能换多少小礼物。

输入格式:

首先是一个正整数N(1<N<100),表示小明手上的奖票的数量。 然后是N个正整数JP(1<=JP<=100),每个数字表示一张奖票的编号。

输出格式:

输出一个数字,表示小明可以换的小礼物的数量。如果不能换小礼物,就输出0。

输入样例:

在这里给出一组输入。例如:

6
3 2 4 6 6 4

输出样例:

在这里给出相应的输出。例如:
1

解答

import java.util.*;

public class Main {
	public static void main(String[] args) {
		Scanner in= new Scanner (System.in);
		int N = in.nextInt();
		int num[] = new int[N];
		
		for (int i = 0; i < N; i++) {
			num[i] = in.nextInt();
		}
		
		int cnt = 1;
		int prize = 0;
		int current;

		for (int i = 0; i < N - 1; i++) {
			for (int j = i + 1; j < N; j++) {
				if (num[i] > num[j]) {
					int tmp;
					tmp = num[i];
					num[i] = num[j];
					num[j] = tmp;
				}
			}
		}
		for(int i = 0; i < N - 2; i++) {
			current = num[i];
			for (int j = i + 1; j < N; j++) {
				if (num[j] == current + 1) {
					current = num[j];
					cnt++;
					if (cnt == 3) {
						prize++;
						num[j] = 0;
						num[j - 1] = 0;
						num[i] = 0;
						cnt = 1;
						break;
					}
				}
			}
		}
		
		System.out.println(prize);
		in.close();
	}
}

易出问题的地方:

  1. 如果获奖的数字要移除,需要将该处数组置为0,如果提前先排序,会好处理很多。
  2. cnt最初要设为1,后面的连续数字只要再找出两个就可以。

猜你喜欢

转载自blog.csdn.net/weixin_44547670/article/details/102760018