Title Description
In addition to an array of integers in two numbers, the other numbers appear twice. Please write a program to find these two figures appear only.
Problem-solving ideas
First sort the array, since in addition to the two figures, other numbers appear twice, so after a previous number digit same array sorted, then, i = i + 2;
After a previous number digit not identical, it indicates that the number appears only once, or to add num1 num2, i ++;
code show as below
// num1, num2 respectively array of length 1. Outgoing parameters // will num1 [0], num2 [0 ] is set to return results public void FindNumsAppearOnce ( int [] Array, int num1 [], int num2 []) {
// bubble sort for ( int I = 0 ; I <be array.length; I ++ ) { for ( int J = 0; J <be array.length; J ++ ) { IF (Array [I]> Array [J]) { int TEMP = Array [I]; Array [I ] = Array [J]; Array [J] = TEMP; } } } For ( int I = 0; I < be array.length;) {
// If the two numbers before and after the same + 2 I IF (Array [I] == Array [I +. 1 ]) { I + = 2 ; }
// If the two numbers before and after the same, it is determined whether the original data num1 0, the number is assigned to put num1 [0], or assigned num2 [0] the else IF (Array [I]! = Array [I + 1'd ]) { IF (num1 [0] == 0 ) { [num1 0] = Array [I]; } the else { [num2 0] = Array [I]; } I ++ ; } } }
However, the above code is logic errors, if really is not repeated number is 0, then an error occurs in the digital num1 as a determination condition, improving the code as follows
public class FindNumsAppearOnce { ArrayList<Integer> list = new ArrayList<Integer>(); public void FindNumsAppearOnce(int [] array,int num1[] , int num2[]) { Arrays.sort(array); for(int i=0;i<array.length;i++){ if((i+1)<array.length && array[i]==array[i+1]){ i++; }else{ list.add(array[i]); } } num1[0]=list.get(0); num2[0]=list.get(1); } }