Code with more than half of the number of occurrences in the array (c)
Address: http://blog.csdn.net/caroline_wendy
Question: a number in the array appears more than half the length of the array. Please find this number.
1. UseQuick Sort)ToMedian (middle) and index (INDEX)Match, output the median value, and check whether it meets the requirements.
2. Use the count method for sequential comparison.
Code:
Method 1:
/** Main. CPP ** created on: 2014.6.12 * Author: Spike * // * eclipse CDT, GCC 4.8.1 */# include <stdio. h> # include <stdlib. h> int randominrange (INT min, int max) {int random = rand () % (max-min + 1) + min; return random;} void swap (int * num1, int * num2) {int temp = * num1; * num1 = * num2; * num2 = temp;} int partition (INT data [], int length, int start, int end) {If (Data = NULL | length <= 0 | start <0 | End> = length) {return-1;} int Index = randominrange (START, end); swap (& Data [Index], & Data [end]); int small = start-1; for (Index = start; index <end; ++ index) {If (data [Index] <data [end]) {++ small; if (small! = Index) Swap (& Data [Index], & Data [small]) ;}}++ small; swap (& Data [small], & Data [end]); return small;} bool checkmorethanhalf (int * numbers, int length, int number) {int times = 0; For (INT I = 0; I <length; ++ I) {If (numbers [I] = Number) + + times;} If (times * 2 <= length) {return false;} return true ;} int morethanhalfnum (int * numbers, int length) {If (numbers = NULL | length <= 0) return 0; int middle = Len Duration> 1; int start = 0; int end = length-1; int Index = partition (numbers, length, start, end); While (index! = Middle) {If (index> middle) {// the front part of the number multiple end = index-1; Index = partition (numbers, length, start, end );} else {start = index + 1; Index = partition (numbers, length, index + 1, start) ;}} int result = numbers [Middle]; If (! Checkmorethanhalf (numbers, length, result) return 0; return result;} int main (void) {int STR [] = {1, 2, 3, 4, 4, 4, 5, 4, 4}; int result = morethanhalfnum (STR, 9); printf ("reuslt = % d \ n", result); Return 0 ;}
Method 2:
/* * main.cpp * * Created on: 2014.6.12 * Author: Spike *//*eclipse cdt, gcc 4.8.1*/#include <stdio.h>#include <stdlib.h>bool CheckMoreThanHalf (int* numbers, int length, int number) {int times = 0;for (int i=0; i<length; ++i) {if (numbers[i] == number)times++;}if (times*2 < length)return false;return true;}int MoreThanHalfNum (int* numbers, int length) {if (numbers == NULL || length <= 0)return 0;int result = numbers[0];int times = 1;for (int i=0; i<length; ++i) {if (times == 0) {result = numbers[i];times = 1;}if (numbers[i] == result) times++;else times--;}if (!CheckMoreThanHalf(numbers, length, result))return 0;return result;}int main(void){ int str[] = {1, 2, 3, 2, 2, 2, 5, 2, 4}; int result = MoreThanHalfNum(str, 9); printf("reuslt = %d\n", result); return 0;}
Output:
reuslt = 4