public class OnlineCTStores {
//avaliable store items
public static String[] ITEMS = {"Cactus", "T Shirt", "air", "Terracotta Necklace", "Coffee Mug", "Wood Crate Wall Storage", "Blanket", "Knife", "Copper Coffee and Tea Kettle", "Wall Art",
"Marble Clock", "Natural Bench", "Llama Valley Framed Print", "Gold Metal Frame Mirror", "Fork", "Star Wars game", "Barracuda", "Anchor", "Sunlight", "planet Saturn"};
//corresponding prices
public static double[] PRICES = {49.99, 13.99, 5.99, 14.99, 29.99, 11.50, 79.99, 23.80, 27.99, 39.44, 78.40, 299.30, 55.00, 176.89, 4.99, 67.00, 8.19, 50.00, 1500, 400};
public double findItemPrice(String item){
//TODO
return 0.0;
}
}
答案 0 :(得分:2)
为了更好的时间复杂性,您可以对ITEMS数组进行排序并调用二进制搜索功能。排序为O(nlogn),搜索为O(logn)。
public double findItemPrice(String item){
Arrays.sort(ITEMS);
int matchIndex = Arrays.binarySearch(ITEMS, item);
if (matchIndex == -1) throw new RuntimeException("Item price not found, " +
input);
return PRICES[matchIndex];
}
<强>更新强>
Arrays.sort()将修改现有数组。如果您想保持不变,您可能希望将其复制到新数组:
int[] copy = Arrays.copyOf(ITEMS, ITEMS.length);
答案 1 :(得分:1)
您应该使用地图来执行此操作。例如,如果您使用Map<String, Double>
,只需使用Map.get(input)
即可将价格加倍。您只需使用重复的Map
来电初始化Map.put(String, Double)
即可。这可以通过静态初始化来完成,例如:
Map<String, Double> itemPrices = new HashMap<>();
static {
itemPrices.put("Cactus", 49.99);
...
}
然后,您可以只说:double price = itemPrices.get("Cactus")
而不是方法来执行此操作。
但是,如果你真的必须继续使用带有同步索引的数组,那么你可以像这样编写你的方法:
public static double findItemPrice(String input) {
int matchIndex = -1;
for (int i = 0; i < ITEMS.length; i++)
if (input.equals(ITEMS[i])) {
matchIndex = i;
break;
}
if (matchIndex == -1) throw new RuntimeException("String not found, " + input);
return PRICES[matchIndex];
}