在数组中找出和为某值的数对
题目要求:
给定一个数组和一个数字,找出数组中所有和为数字的数对,并返回总个数。
思路:
1、直观的就是直接暴力遍历,找出所有数对然后判断是否符合,时间复杂度为O(n^2)
2、将数组排序,然后通过两端夹击的方法,当和大于预期值,后面的数字下标向前移动一格,如果小于,则前面的数字下标向前移动一格…
代码实现:
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
int[] array = {4,9,8,1,3,7,5,0,16,2,15,6,11,15};
System.out.println(Solution(array,15));
}
private static int result = 0 ;
public static int Solution(int [] array,int sum) {
Arrays.sort(array);
int i = 0;
int j = array.length - 1;
while(i<j){
int temp = array[i] + array[j];
if(temp<sum){
i++;
continue;
}else if(temp>sum){
j--;
continue;
}else{
result++;
i++;
j--;
}
}
return result;
}
}