One, the problem description
Given an integer array (the elements in the array can be duplicated), and a specified value. Prints all integer pairs of the sum of the two numbers in the array for the specified value
Second, algorithm analysis
There are two ways to solve this problem. Method one with the help of sort, method two adopt HashSet
Method One:
Sort the integer array first, then define two pointers left and right after sorting. Left points to the first element in a sorted array, right points to the last element in the sorted array
Arr[left]+arr[right] is compared with the given element, if the former is large, right--, if the former is small, left++, if equal, the sum of the pairs of integers is found as the element of the specified value.
This method takes the order, the time complexity of sorting is O (Nlogn), and the time complexity of scanning the entire array after sorting is O (N). So the total time complexity is O (NLOGN). Space Complexity of O (1)
Method Two:
Iterate through an array of integers, and solve its suplement (Expectedsum-arr[i]) for each element in an integer array. suplement is the specified value minus the array element.
If the element's suplement is not in HashSet, the element is added to the hashset.
If the element's suplement is in HashSet, it indicates that a pair of integers has been found for the element with the specified value.
This method uses the HashSet, so the space complexity is O (n), because only need to scan the integer array, so the time complexity of O (n)
Three, complete code implementation:
Importjava.util.Arrays;ImportJava.util.HashSet; Public classExpectsumoftwonumber { Public Static voidExpectsum_bysort (int[] arr,intexpectsum) { if(arr = =NULL|| Arr.length = = 0) return; Arrays.sort (arr); intleft = 0, right = arr.length-1; while(Left <Right ) { if(Arr[left] + arr[right] >expectsum) right--; Else if(Arr[left] + Arr[right] <expectsum) left++; Else//Equal{System.out.println (Arr[left]+ "+" + arr[right] + "=" +expectsum); Left++; Right--; } } } Public Static voidExpectsum_byset (int[] arr,intexpectsum) { if(arr = =NULL|| Arr.length = = 0) return; HashSet<Integer> intsets =NewHashset<integer>(arr.length); intsuplement; for(intI:arr) {suplement= Expectsum-i; if(!intsets.contains (suplement)) {Intsets.add (i); }Else{System.out.println (i+ "+" + suplement + "=" +expectsum); } } } //Hapjin Test Public Static voidMain (string[] args) {int[] arr = {2,7,4,9,3}; intExpectsum = 11; Expectsum_byset (arr, expectsum); System.out.println ("************"); Expectsum_bysort (arr, expectsum); System.out.println ("----------------"); int[] arr2 = {3,7,9,1,2,8,5,6,10,5}; intEXPECTSUM2 = 10; Expectsum_byset (ARR2, expectSum2); System.out.println ("**********"); Expectsum_bysort (ARR2, expectSum2); }}
Original: http://www.cnblogs.com/hapjin/p/5746659.html
Finds all integer pairs of two numbers in the array that are the sum of the specified values