Amazon第一题

package sean;

/* Enter your code here. Read input from STDIN. Print output to STDOUT */
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.StringTokenizer;

public class Solution 
{
	private String findMostlyBroughtItem(String[] shoppingRecordArray, String itemX) 
	{
		// your code is here
		// 购买了X的客户商品
		HashMap<String, ArrayList<String>> CustItemRec = new HashMap<String, ArrayList<String>>();
		int length = shoppingRecordArray.length;
		ArrayList<String> TarCust = new ArrayList<String>();
		for (int i = 0; i < length; i+=2) {
			String key = shoppingRecordArray[i];
			String item = shoppingRecordArray[i+1];
			if(item.equals(itemX))
			{
				TarCust.add(key);
			}
			if(CustItemRec.containsKey(key)==false)
			{
				ArrayList<String> temp = new ArrayList<String>();
				temp.add(item);
				CustItemRec.put(key, temp);
			}
			else
			{
				CustItemRec.get(key).add(item);
			}
		}
		if(TarCust.isEmpty()) // 没有人买X
		{
			return "None";
		}
		
		// 其它商品数量
		HashMap<String, Integer> ItemNum = new HashMap<String, Integer>();
		for (String tempCust : TarCust)
		{
			for (String tempItem : CustItemRec.get(tempCust))
			{
				if (tempItem.equals(itemX))
					continue;
				if ((ItemNum.containsKey(tempItem) == false))
				{
					ItemNum.put(tempItem, 1);
				}
				else
				{
					ItemNum.put(tempItem, ItemNum.get(tempItem)+1);
				}
			}
		}
		if(ItemNum.isEmpty()) // 只买X
		{
			return "None";
		}
		
		int NumMax = 0;
		String ItemMax = "";
		Set<Map.Entry<String, Integer>> entrySet = ItemNum.entrySet();
		for (Map.Entry<String, Integer> entry : entrySet)
		{
			
			int tempNum = entry.getValue();
			if (NumMax < tempNum)
			{
				NumMax = tempNum;
				ItemMax = entry.getKey();
			}
		}
		return ItemMax;
		
	}
	
	public static void main(String[] args) 
	{
		Solution solution = new Solution();
		Scanner scanner = new Scanner(System.in);
		
		while (scanner.hasNextLine()) 
		{
			//Initialize the item X
			String itemX = scanner.nextLine();
			
			//Initialize the shopping record array
			String strLine2 = scanner.nextLine();
			StringTokenizer stringTokenizer = new StringTokenizer(strLine2);
			int arrayLength = stringTokenizer.countTokens();
			String[] shoppingRecordArray = new String[arrayLength];
			for(int j = 0; j < arrayLength; j++)
			{
				shoppingRecordArray[j] = stringTokenizer.nextToken();
			}
			
			String mostlyBroughtItem = solution.findMostlyBroughtItem(shoppingRecordArray, itemX);
			System.out.println(mostlyBroughtItem);
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值