歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux教程 >> 2012年華為校園招聘機試(成都)

2012年華為校園招聘機試(成都)

日期:2017/2/28 14:47:23   编辑:Linux教程

1:去掉一個數組裡的最大值與最小值,求數組元素的平均值。函數接口為:float avescore(float score[] ,int n)解析:此題比較簡單,循環一遍,記下數組的最大值與最小值以及總和,然後在求的總和裡面減掉最大值與最小值,再求平均數即可,時間復雜度為O(n),代碼不多,如下有兩種解法

解法一:

float avescore(float score[] ,int n)
{
float max=0,min=score[0],sum=0;
for(int i=0;i<n;i++)
{
sum+=score[i];
max=max<score[i]?score[i]:max;
min=min>score[i]?score[i]:min;
}
return (sum-max-min)/(n-2);
}

解法二<STL解決>

#include<iostream>
#include<algorithm>
#include<numeric>
using namespace std;
float avescore(float score[] ,int n)
{
float max=*max_element(score,score+n);
float min=*min_element(score,score+n);
return (accumulate(score,score+n,0.0)-max-min)/(n-2);
}

2: 對一個數組,將數組中偶數從大到小排序,奇數從小到大排序,奇數和偶數交叉著放且輸出數組第一位放奇數 若奇數和偶數不等長,則把剩下的直接放到數組中。

函數接口為:void sortArray(int a[],int n)

解析,本題思路先遍歷一遍數組,得出數組中的奇數個數與偶數個數,根據奇偶個數分別開辟空間再使用泛型算法對兩個數組進行排序,奇數數組根據題意應該從小到大排序,偶數數組應是從大到小進行排序,再將排好序的數組根據題意要求重新賦值到原數組裡,算法的空間復雜度O(n),不是很好的一個算法,開辟的空間要記得回收

#include<iostream>
#include<algorithm>
#include<functional>
using namespace std;
void sortArray(int score[] ,int n)
{
int maxO=0,maxE=0,oIndex=0,eIndex=0;
int *od=0,*ev=0;
for(int i=0;i<n;i++)
score[i]%2==0?++maxE:++maxO;
od=new int[maxO];
ev=new int[maxE];
for(int j=0;j<n;j++)
score[j]%2==0?ev[eIndex++]=score[j]:od[oIndex++]=score[j];
sort(od,od+maxO,less<int>());
sort(ev,ev+maxE,greater<int>());
oIndex=eIndex=0;
for(int k=0;k<n;k++)
if((k%2==0&&oIndex<maxO)||(k%2!=0&&eIndex>=maxE))
score[k]=od[oIndex++];
else if((k%2!=0&&eIndex<maxE)||(k%2==0&&oIndex>=maxO))
score[k]=ev[eIndex++];
free(od);
free(ev);
}

Copyright © Linux教程網 All Rights Reserved