The title is as follows: The existing array length is n+1, which is stored in 1 to n-2, in a variable order, with two numbers appearing two times, now to find out the two numbers. Example A={2, 3, 1, 4, 5, 2, 4},
This array has a length of 7 and holds 1 to 5, but 2 and 4 appear two times, the program outputs 2 and 4
Method 1 Brute force looks for the main idea: for the number of I in the array, find all the integers at the end of the i+1, a number that appears two times before the second occurrence can be found after the first time.
time Complexity O (n^2)
#include <stdio.h>void find_duplicates (int* num, int start, int end) {int size = End-start+1;int i = 0;int j = 0;for (i = 0; i<size; i++) {for (j=i+1; j<size; J + +) {if (num[i] = = Num[j]) printf ("%d\n", Num[i]);}} void Main () {int a[]={5,2,4,3,1,3,2};find_duplicates (A, 0, 6);}
Method 2: XOR (XOR)
main idea: Because the limit is 1 to n number, and each number appears at least once, you can first set all the integers in the array xor, and then the result and 1, 2, 3 、、、 N xor again,
This gives an XOR result of the two repeated occurrences of the integer x. Then the main way is to distinguish between the two, for the XOR result X, its binary representation has 0 and 1 composition, the nature of the difference or,
In the binary representation of x, those occurrences of 0 are the result of two duplicates corresponding to 1 or 0, and the presence of 1 is only one possibility: two numbers correspond to one 0 and one is 1. With this feature,
We can pick a specific position (where x is 1) and divide the original array into two parts, and the part I corresponds to the number of 1 for that particular position, and Part II corresponds to the number of 0 for that particular position.
This translates the problem into: Find a repeating number in each section.
Time Complexity O (n)
Code:
#include <stdio.h>void find_duplicates (int* num, int start, int end) {int size = End-start+1;int Bit_flag = 0;int i=0; for (i=0; i<size; i++) {bit_flag ^= num[i];} for (I=1; i<size-1; i++) {Bit_flag ^= i;} int division_bit = Bit_flag & ~ (bit_flag-1), int a = 0;int B = 0;for (i=0; i<size; i++) {if (Num[i] & Division_bit) A ^= num[i];elseb ^= num[i]; }for (i=1; i<size-1; i++) {if (I & Division_bit) a ^= i;elseb ^= i;} printf ("Duplicate numbers a=%d \ t b=%d\n", A, b);} void Main () {int a[]={5,2,4,3,1,3,2};find_duplicates (A, 0, 6);}
Method 2 Run the result:
Reprint Please specify source Warnon:)
Find two occurrences of a number in an array