算法题24

计算:
题目描述
小明给大家买糖。
员工一共n人(包括小明), 糖一共k种,第i位员工最喜欢糖a_i。
商店举行促销,全场糖买一送一(购买一瓶i,再赠送一瓶i)。
想让所有人(包括小明)都拿到他们最喜欢的糖,需要买几瓶。
第一行两个整数n,k,分别表示员工人数和糖种类数。
第二行n个整数,表示i号员工最喜欢的糖种类是a_i。*/
输入描述

输出描述

示例1:
输入

输出

        

代码:

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNextInt()) {
            int n = in.nextInt();
            int k = in.nextInt();
            int[] arr=new int[n];
            //标记数组
            int[] key=new int[k];
            for(int i=0;i<k;i++) {
            	key[i]=0;
            }
            for(int i=0;i<n;i++) {
            	arr[i]=in.nextInt();
            	for(int j=1;j<=k;j++) {
            		if(arr[i]==j) {
            			key[j-1]++;
            		}
            	}	
            }
            int res=0;
            for(int i=0;i<k;i++) {
            	if(key[i]%2==0) {
            		res=res+key[i]/2;
            	}else {
            		res=res+key[i]/2+1;
            	}
            }

            System.out.println(res);
        }
    }
}
/*6 2
1 2 1 2 1 2
4*/

第二种代码简洁的:

public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int k = sc.nextInt();
        int a;
        int sum = 0;
        Set<Integer> set = new HashSet<Integer>(n);
        for (int i = 0; i < n; i++) {
            a = sc.nextInt();
            if (set.contains(a)){
                set.remove(a);
                continue;
            }
            set.add(a);
            sum ++;
        }
        System.out.println(sum);
    }
/*6 2
1 2 1 2 1 2
4*/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值