Topic
不重复打印排序数组中相加和为给定值的所有二元组和三元组
Java code
Package com.lizhouwei.chapter8;/** * @Description: Does not duplicate all two and triples that are added in the sorted array and for a given value * @Author: Lizhouwei * @CreateDate: 2018/ 5/7 21:27 * @Modify by: * @ModifyDate: */public class Chapter8_9 {public void Printuniquepair (int[] arr, int k) { if (arr = = NULL | | Arr.length < 2) {return; } int left = 0; int right = Arr.length-1; while (left < right) {if (Arr[left] + arr[right] < k) {left++; } else if (Arr[left] + arr[right] > k) {right--; } else {if (left = = 0 | | arr[left]! = Arr[left-1]) {System.out.println (Arr[left] + " , "+ arr[right]); left++; right--; }}}} public void Printuniquetriad (int[] arr, int. K) {for (int i = 0; i < arr.length -2; i++) {if (i = = 0 | | arr[i]! = Arr[i-1]) {printrest (arr, I, i + 1, arr.Length-1, K-arr[i]); }}} public void Printrest (int[] arr, int. Pre, int left, int. right, int k) {while (left < right) {if (Arr[left] + arr[right] < k) {left++; } else if (Arr[left] + arr[right] > k) {right--; } else {if (left = = Pre | | arr[left]! = Arr[left-1]) {System.out.println (Arr[pre] + "," + Arr[left] + "," + arr[right]); left++; right--; }}}}//test public static void main (string[] args) {chapter8_9 chapter = new Chapter8_ 9 (); Int[] arr = {-8,-4,-3, 0, 1, 2, 4, 5, 6, 9}; System.out.println ("Array arr = {-8,-4,-3, 0, 1, 2, 4, 5, 6, 9} and 10 tuples of two:"); Chapter.printuniquepair (arr, 10); System.out.println ("Array arr = {-8,-4,-3, 0, 1, 2, 4, 5, 6, 9} and the ternary group of 10:"); Chapter.printuniquetriad (arr, 10); }}
Results
The Programmer Code Interview guide, chapter eighth, array and matrix issues do not repeat all two-tuple and ternary groups that are added in the sorted array and for the given values