自己不怎麼關注算法,但是面試的時候常有一些公司就會給算法題目,目的也很直接,自己每日一練就好。
【題目】騰訊面試題:給你10 分鐘時間,根據上排給出十個數,在其下排填出對應的十個數,要求下排每個數都是先前上排那十個數在下排出現的次數。上排的十個數如下:[0,1,2,3,4,5,6,7,8,9]
【思路】使用純 c來實現。 條件1,數組b內所有數字加起來爲10; 動態調整數組b內的數值。 因爲時間先後的原因,會導致先前統計個數出現的次數不正確。
#include <stdio.h>
#include <string.h>
static int a[10] = {0,1,2,3,4,5,6,7,8,9,};
static int b[10] = {0,0,0,0,0,0,0,0,0,0};
int check = 1;
int Right();
int do_justment(int num);
void do_check(int num);
int main (){
int i;
while((!Right()) || check){
for(i = 0;i <10; i++)
do_justment(a[i]);
for(i = 0 ;i<10;i++);
do_check(a[i]);
}
for(i = 0 ;i<10;i++)
printf("%d,",b[i]);
}
// 如果不滿足條件 底下數字加起來爲10,則返回0
int Right(){
int i ;
int count = 0;
for( i = 0; i < 10; i++)
count = count + b[i];
if( count == 10 )
return 1;
else
return 0;
}
// 動態調整數組b中的數據。
int do_justment(int num){
int i = 0;
int count = 0;
// 計算 num 出現的次數。
for( i = 0; i<10; i++)
if( b[i] == num)
count++;
if( count > 9)
count = 9;
b[num] = count;
return 0;
}
// 再次驗證一遍,防止出現 9000000001 類似的情況,即因爲調整時間前後的差別導致
// 一開始統計的次數後來被改變。
void do_check(int num){
int i = 0;
int count = 0;
for( i = 0; i<10; i++)
if( b[i] == num)
count++;
if(count != b[num])
check = 1;
else check = 0;
}