Enter an incrementing sorted array and a number s, look for two numbers in the array, and yes their sum is exactly s, if there are many pairs of numbers and equals s, the output of the two numbers is the smallest.
Two kinds of problem solving step 1: Consider the case with the smallest product:
Public arraylist<integer> findnumberswithsum (int [] array,int sum) {Arraylist<arraylist<integer> ;> lists = new arraylist<> (); for (int i=0;i<array.length;i++) {arraylist<integer> list = new arraylist<> (); for (int j=i+1;j<array.length;j++) {if (Array[i] + array[j] = = sum) {list.add (Array[i]) ; List.add (Array[j]); List.add (array[i] * array[j]); }} if (!list.isempty ()) Lists.add (list); } if (Lists.size () ==0) return new arraylist<integer> (); if (Lists.size () ==1) return Lists.get (0); Collections.sort (lists, new comparator<arraylist<integer>> () {@Override public int com Pare (arraylist<integer> O1, arraylist<integer> O2) {return O1.get (2). CompareTo (O2.get (2)); } }); arraylist<integer> result = new arraylist<> (); arraylist<integer> temp = lists.get (0); for (int i=0;i<temp.size () -1;i++) {Result.add (Temp.get (i)); } return result; }
2: Order increment according to the elements of the array, regardless of product
Public arraylist<integer> findnumberswithsum (int [] array,int sum) { arraylist<integer> list = new Arraylist<integer> (); if (array = = NULL | | Array.Length < 2) { return list; } int i=0,j=array.length-1; while (i<j) { if (array[i]+array[j]==sum) { list.add (array[i]); List.add (Array[j]); return list; } else if (array[i]+array[j]>sum) { j--; } else{ i++; } } return list; }
Enter an incrementing sorted array and a number s, look for two numbers in the array, and yes their sum is exactly s, if there are many pairs of numbers and equals s, the output of the two numbers is the smallest.