Title:
There is a number in the array that appears more than half the length of the array. Please find this number. For example, enter an array of length 9 {1,2,3,2,2,2,5,4,2}. Since the number 2 appears five times in the array, more than half the length of the array, output 2. Output 0 if it does not exist.
Resolution:
Seeing this problem, i first thought of sorting the array first, and then i went through it to find the numbers that match the meaning of the problem in the ordered array. This method is feasible, but this method is too obvious, and the sorting time complexity is greater than O (n), so the interviewer will not agree with it. So i thought of using the ith number and i+1 number for comparison. If they are the same, write down the number and add one to the counter. If they are different, then subtract one. When the counter is zero, write down the number again. After one pass of traversal, if the counter is zero, there is no such number. Otherwise, it can exist. Repeat the traversal, compare the recorded number with all the numbers in the array. Finally, if they are the same If the number of is greater than the length of the array, it will return the number, otherwise it will return 0. The time complexity of this method is O (n)
Now I have written down the codes of both methods and shared them with you.
Method 1 Code:
1 int MoreThanHalfNum_Solution(int *arr,int len) 2 { 3 int i,j,flag = 1,count = 1; 4 for (i=0; i<len-1; i++) //Sort array 5 { 6 for (j=0; j<len-1-i; j++) 7 { 8 if (arr[j]>arr[j+1]) 9 { 10 int tmp = arr[j]; 11 arr[j] = arr[j+1]; 12 arr[j+1] = tmp; 13 flag = 0; 14 } 15 } 16 if (flag) 17 break; 18 } 19 for (i = 0; i<len; i++) //Go through it to find out whether there is a number that matches the meaning of the question 20 { 21 if (arr[i] == arr[i+1]) 22 { 23 j = i; 24 count++; 25 if (count>(len>>1)) 26 { 27 return arr[j]; 28 } 29 } 30 else 31 { 32 count = 1; 33 } 34 } 35 return 0; 36 }
Method 2 Code:
1 int MoreThanHalfNum_Solution(int *arr,int len) 2 { 3 int i = 1; 4 int k = 0; 5 int count = 1; 6 while (i<len) 7 { 8 if (arr[i]==arr[k]) 9 { 10 k = i; //Record current location 11 count++; 12 } 13 else 14 { 15 count--;//If it is different, the counter will be reduced by 1 16 if (count == 0) 17 { 18 count = 1; 19 k = i; 20 } 21 } 22 i++; 23 } 24 if (count) 25 { 26 count = 0; 27 for (i=0; i<len; i++) 28 { 29 if(arr[k]==arr[i]) 30 count++; 31 } 32 if (count>len/2) 33 return arr[k]; 34 else 35 return 0; 36 } 37 else 38 return 0; 39 }
CSDN blog address: http://blog.csdn.net/qq_38646470