题目简述:找到买一件物品的用户买的最多的另外一件物品。
例子:cus1 item1 cus2 item2 cus3 item3 cus2 item1 cus3 item4 cus1 item2 cus1 item4
当输入item1,则输出item2,因为有cus1和cus2买了item1,所以检查cus1和cus2一共买了什么,除了item1外有item2 和item4,item2数量为2,item4为1,所以输出为item2
具体代码如下:(当时写的代码,未优化)
import java.util.Scanner;
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();
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);
}
}
}
总结:这道题思路应该来说很简单,就看怎么实现效率更高了,此方法效率不高,应该属于最笨的方法了。