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);
}
}
}
Amazon第一题
最新推荐文章于 2021-03-08 03:45:25 发布