这是我获取数组索引的代码,其值的总和对应于给定的目标值。目前最坏的情况是 O(N2) 算法。有什么改进的方法吗?
public class SumArrayTarget {
public static void main(String[] args) {
int[] arr = { 1, 2, 4, 6, 3, 5, 7 };
System.out.println("The indices are "+ Arrays.toString(sum(arr, 12)));
}
public static int[] sum(int[] arr, int target) {
int[] list = new int[2];
for (int i = 0; i < arr.length - 1; i++) {
int j = i+1;
while (j < arr.length) {
if (arr[i] + arr[j++] == target){
list[0]=i;
list[1]=j-1;
return list;
}
}
}
return list;
}
}