Topic Description: Find the other item that the user buys the most.
Example: cus1 item1 cus2 item2 cus3 item3 cus2 item1 cus3 item4 item1 item2 cus1 item4
When item1 is input, item2 is output. Because item1 is purchased for cus1 and cus2, check what is purchased for cus1 and cus2. Besides item1, there are item2 and item4, and the number of item2 is 2, item4 is 1, so the output is item2
The Code is as follows: (the code written at the time was not optimized)
[Java]
Import java. util. collections;
Import java. util. StringTokenizer;
Import java. util. HashMap;
Import java. util. Map. Entry;
Public class Solution
{
Private String findMostlyBroughtItem (String [] shoppingRecordArray, String itemX)
{
// Your code is here
HashMap <String, Integer> map = new HashMap <String, Integer> ();
HashMap <String, String> map1 = new HashMap <String, String> ();
Int len = shoppingRecordArray. length;
For (int I = 0; I <len; I ++ ){
If (I % 2 = 0 ){
If (shoppingRecordArray [I + 1]. equals (itemX )){
Map1.put (shoppingRecordArray [I], "");
}
}
}
For (int I = 0; I <len; I ++ ){
If (I % 2 = 0 ){
For (Entry <String, String> e: map1.entrySet ()){
If (shoppingRecordArray [I]. equals (e. getKey ())){
If (shoppingRecordArray [I + 1]. equals (itemX )! = True ){
If (map. containsKey (shoppingRecordArray [I + 1]) {
Map. put (shoppingRecordArray [I + 1], map. get (shoppingRecordArray [I + 1]) + 1 );
} Else {
Map. put (shoppingRecordArray [I + 1], 1 );
}
}
}
}
}
}
Int max = 0;
String temp = "";
For (Entry <String, Integer> e: map. entrySet ()){
If (e. getValue ()> max ){
Max = e. getValue ();
Temp = e. getKey ();
}
}
If (map. isEmpty ()){
Return "None ";
} Else {
Return temp;
}
}
Public static void main (String [] args)
{
Solution solution = new Solution ();
Required bytes = new bytes (System. in );
While (iterator. hasNextLine ())
{
// Initialize the item X
String itemX = response. nextLine ();
// Initialize the shopping record array
String strLine2 = response. 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 );
}
}
}