两道面试算法题

来源:互联网 发布:c语言考研题库 编辑:程序博客网 时间:2024/06/08 16:19

最近面试 两道算法题 说难不难 要写全对也不容易 很惭愧 我没有一次写对

第一道:无序int数组 找到中位数

void swap(int &a,int &b){    int temp = a ;    a = b;    b = temp;}int get_kth_number(vector<int> &num,int k,int start,int end){    //类似于快排的一次划分     int pivot = num[start];    int i = start+1;    int j = end;    while(i<j){        int index = start;        while(num[i]>pivot&&i<j){            i++;        }//找到比i小的数 或者i>=j说明找不到了        while(num[j]<pivot&&i<j){            j--;        }        //如果i==j了 说明之前的循环找不到比pivot小的数 或者当前循环找不到比pivot大的数        //或者找到了比pivot大的数        if(i==j) break;        else swap(nums[i],nums[j]);    }    //一次划分结束    index = i;    if(index==k-1) return num[index];    else if(index>k-1){        return get_kth_number(num,start+k,start,index-1);    }    else{        return get_kth_number(num,end-k,index+1,end);    }int get_middle(vector<int> &num){    int middle = num.size()>>1;    return get_kth_number(num,middle,0,size-1);}

第二道:自己实现atoi(char *p,int err)

#define NULLPTR -1#define OVERFLOW -2int atoi(char *s, int& err) {    bool positive = true;    int res = 0;    if(s==NULL){        err = NULLPTR;        return -1;    }    char* pos = s;    while(*pos==' '){        pos++;    }    if(*pos=='+'){        positive = true;        pos++;    }    else if(*pos=='-'){        positive = false;        pos++;    }    while(*pos=='0'){        pos++;    }    if(strlen(pos)>=11) {        err= OVERFLOW;        return -1;    }    if(strlen(pos)==10){        if((positive&&strcmp(pos,"2147483647")>0)||(!positive&&strcmp(pos,"2147483648")>0){               err= OVERFLOW;            return -1;        }    }    while(pos<='9'&&pos>='0'){        //count++;        res=res*10+*pos-'0';        pos++;    }    retrun positive?res:-1*res;}
0 0
原创粉丝点击