數組中有一個數字出現的次數超過數組長度的一半(C、Python)

C語言python

 1 /*
 2 -----------------------------------
 3 動態分配須要的內存大小
 4 輸入數組元素的值
 5 經過函數調用,傳地址對數組排序
 6 循環每一個元素,當循環比較某個值時,若是有相等的,計數加1,比較完成後,和cn比較,若是大於cn,那麼說明找到,退出循環
 7 -----------------------------------
 8 */
 9 
10 # include <stdio.h>
11 # include <malloc.h>
12 
13 void findnum(int * arr, int n)
14 { 15 int i, j, count, cn; 16 count = 0; 17 cn = n/2; 18 19 for (i=0; i<n; i++) //雙重for循環,統計元素個數 20  { 21 for (j=0; j<n; j++) 22  { 23 if (arr[i] == arr[j]) 24 count++; 25  } 26 27 if (count > cn) 28  { 29 printf("超過長度一半的數字是:%d\n", arr[i]); 30 break; 31  } 32 else if (i==n-1) 33  { 34 printf("無超過長度一半的數字!\n"); 35 break; 36  } 37 count = 0; 38  } 39 return; 40 } 41 42 int main(void) 43 { 44 int len, i; 45 int * pArr; 46 char ch; 47 48 do { 49 50 printf("請輸入數字個數:"); 51 scanf("%d", &len); //輸入元素個數 52 printf("請輸入%d個數字(以空格分隔):", len); 53 pArr = (int *)malloc(sizeof(int)*len); //動態分配內存 54 for (i=0; i<len; i++) //輸入值 55 scanf("%d", &pArr[i]); 56 printf("動態數組元素爲:\n"); 57 for (i=0; i<len; i++) //輸出值 58 printf("%d ", pArr[i]); 59 printf("\n"); 60 61 findnum(pArr, len); //調用查找函數 62 free(pArr); //釋放動態分配的內存 63 64 printf("\n你想繼續麼(Y/N):"); //詢問是否繼續 65 flushall(); //清除緩存 66 scanf(" %c", &ch); 67 //printf("%c\n", ch); 68 69 70 }while ('y'==ch || 'Y'==ch); //若是輸入的是Y或者y,表示繼續 71 72 return 0; 73 } 74 75 /* 76 在Vc++6.0中的輸出結果爲: 77 ----------------------------------- 78 79 請輸入數字個數:5 80 請輸入5個數字(以空格分隔):1 2 3 4 5 81 動態數組元素爲: 82 1 2 3 4 5 83 無超過長度一半的數字! 84 你想繼續麼(Y/N):y 85 請輸入數字個數:5 86 請輸入5個數字(以空格分隔):1 1 1 2 3 87 動態數組元素爲: 88 1 1 1 2 3 89 超過長度一半的數字是:1 90 你想繼續麼(Y/N):n 91 Press any key to continue 92 93 ----------------------------------- 94 */

 

Python:c++

li = [1,2,3,4,5,2,2,2,2,2]
def findn(li):
    for i in li:
        if li.count(i)>len(li)/2:
            return i
n = findn(li)
print(n)
相關文章
相關標籤/搜索