- package com.algorithm.hash;
-
- public class alg1 {
- public static void main(String argv[]) {
- int[] array1 = {10,2,7,4,5,6,3,8,9,1};
- int[] array2 = {1,2,3,4,5,6,7,8,9,10};
- int[] array3 = {1,2,3,4,5,6,7,8,9,10};
- alg1.execute1(array1, 8);
- alg1.execute2(array2, 8);
- alg1.execute3(array3, 8);
- }
-
-
-
- private static void execute1(int[] array, int m) {
- int size = array.length;
- int hash[] = new int[size];
- for(int i = 0; i < size; i++) {
- hash[array[i]%size] = 1;
- }
-
- for(int i = 0; i < size; i++) {
- int tmp = m - array[i];
- if((tmp > array[i]) && (hash[tmp%size] == 1)){
- System.out.println(array[i] + " " + tmp);
- }
- }
- }
-
-
-
- private static void execute2(int[] array, int m) {
- for(int i = 0; i < array.length; i++) {
- int tmp = m - array[i];
- if (tmp > array[i]) {
- if (binarySearch(array, tmp) != -1) {
- System.out.println(array[i] + " " + tmp);
- }
- }
- }
- }
- private static int binarySearch(int[] array, int key) {
- if (array.length == 0) {
- return -1;
- }
-
- int first = 0;
- int last = array.length -1;
-
- int mid;
- while(first <= last) {
- mid = (first + last) / 2;
- if (array[mid] == key) {
- return mid;
- } else if (array[mid] < key) {
- first = mid + 1;
- } else {
- last = mid -1;
- }
- }
- return -1;
- }
-
-
-
- private static void execute3(int[] array, int m) {
- int first = 0;
- int last = array.length -1;
- int sum = 0;
- while(first < last ) {
- sum = array[first] + array[last];
- if (sum == m) {
- System.out.println(array[first] + " " + array[last]);
- first++;
- last--;
- } else if (sum < m) {
- first++;
- } else {
- last--;
- }
- }
- }
-
java实现 数组中两个元素相加等于指定数的所有组合,布布扣,bubuko.com
java实现 数组中两个元素相加等于指定数的所有组合