Fork me on GitHub

找一对数

输入n个整数,找出其中两个数,他们之和等于整数m 如果存在输出 true 不存在输出false
我这里用的是二分查找以及双指针

双指针

二分查找

public class Main {
 
	public static boolean sumSearch(int arr[], int a) {
		int i = 0;
		int j = arr.length - 1;
		Arrays.sort(arr);
		while (i < j) {
			if (arr[j] + arr[i] < a) {
				i++;
			} else if (arr[j] + arr[i] > a) {
				j--;
			} else if (arr[j] + arr[i] == a)
				return true;
		}
		return false;
	}
 
	public static boolean sumBinarySearch(int arr[], int a) {
		Arrays.sort(arr);
		for (int x = 0; x < arr.length; x++) {
			int y = x + 1;
			int z = arr.length - 1;
			int temp = a - arr[x];
			while (y <= z) {
				if (temp < arr[(y + z) / 2])
					z = (y + z) / 2 - 1;
				else if (temp > arr[(y + z) / 2])
					y = (y + z) / 2 + 1;
				else if (temp == arr[(y + z) / 2])
					return true;
			}
		}
		return false;
	}
 
	public static void main(String[] args) {
		int A[] = { 5, 2, 6, 2, 3, 2 };
		System.out.println(sumSearch(A, 10));
		System.out.println(sumBinarySearch(A, 10));
	}
}
posted @ 2019-07-08 11:05  cznczai  阅读(172)  评论(0编辑  收藏  举报