实际上,接受的答案将花费每个查询的线性时间。虽然 a仍然是一个更好的选择(具有恒定的摊销时间),但如果您重新排列数组以便对其进行排序,则HashMap
可以比使用数组的线性时间做得更好。postalCode
这允许您执行O(log(n))
二进制搜索。
例子:
final int[] orderedPostCode = { 1000, 2000, 2300, 8500, 9000, 9200, 9300, 9700 };
final String[] orderedCities = { "Brussel", "Antwerpen", "Turnhout", "Kortrijk", "Gent", "Dendermonde", "Aalst", "Oudenaarde" };
final int code = Integer.parseInt(JOptionPane.showInputDialog("Give a postal code"));
final int codePos = Arrays.binarySearch(orderedPostCode, code);
if (codePos < 0) {
JOptionPane.showMessageDialog(null, "Postal code not found", "Error", JOptionPane.ERROR_MESSAGE);
}
else {
JOptionPane.showMessageDialog(null, "City: " + orderedCities[codePos]);
}
这导致了一个有趣的后续问题:如何以快速二进制搜索所需的方式对任意一组邮政编码和城市进行排序:
int[] postalCode = {9300,2000,1000,9200,9000,8500,9700,2300};
String[] city = {"Aalst","Antwerpen","Brussel","Dendermonde","Gent","Kortrijk","Oudenaarde","Turnhout"};
int[] orderedPostCode = Arrays.copyOf(postalCode, postalCode.length);
Arrays.sort(orderedPostCode);
String[] orderedCities = rearrangeCities(city, postalCode, orderedPostCode);
System.out.println(Arrays.toString(orderedPostCode));
System.out.println(Arrays.toString(orderedCities));
// Will print the arrays of the first example
这是rearrangeCities
实现O(n²)
:
private static String[] rearrangeCities(String[] cities, int[] postalCode, int[] orderedPostCode) {
final String[] orderedCities = new String[cities.length];
for (int newPos = 0; newPos < orderedPostCode.length; newPos++) {
final int curPostalCode = orderedPostCode[newPos];
for (int oldPos = 0; oldPos < postalCode.length; oldPos++) {
if (postalCode[oldPos] == curPostalCode) {
orderedCities[newPos] = cities[oldPos];
break;
}
}
}
return orderedCities;
}
由于您的目标是提高您对 Java 数组的了解,我相信这些都是很好的示例。