您的位置:首页 > 职场人生

剑指offer面试题28-29

2016-07-25 17:16 489 查看
      实现剑指offer的面试题28、29:

//面试题28: 字符串的排列
class Permutation
{
public:
void get_permutation(char *str,char* begin)
{
if(str==nullptr)
return;
if(*begin == '\0')
{
cout<<str<<endl;
return;
}
for(char* p=begin;*p!='\0';p++)
{
//没有到达末尾
exchange(*p,*begin); //先交换
get_permutation(str,begin+1);  //注意!起始位置没变
exchange(*p,*begin); //再交换回来,为下次调用做准备
}

}
void exchange(char& a,char& b) //交换两者的数据
{
char tem=a;
a=b;
b=tem;
}
};

//面试题29:找出数组中出现次数超过一半的数字
class More_thanhaft_num
{
public:
int find_num(int *istr,int len)    //该方法要改变原数组的内容
{
if(istr==nullptr||len<=0)
return NULL;
int start=0;
int end=len;
int i=partition(istr,len,0,len);
while(i!=len/2)
{
if(i>len/2)
{
end=i;
i=partition(istr,len,start,end);
}
else
{
start=i+1;
i=partition(istr,len,start,end);
}
}

return istr[i];
}
int find_num2(int *istr,int len)   //不改变原数组
{
int count=1;
int result=istr[0];
for(int i=1;i<len;i++)
{
if(count==0)
{
result=istr[i];
count++;
}
else if(result!=istr[i])
count--;
else
count++;
}
return result;
}

int partition(int *p,int len,int start,int end)  //一般end不取
{
if(start>=end)
return NULL;

int i=start;
int j=end;// end不取,end-1为基准
int judge=p[end-1];
while(true)
{
while(true)
{
if(i+1==j)
return i;
else if(p[i]<=judge)
i++;
else
break;
}
j--;
while(true)
{
if(i==j)
return i;
else if(p[j]>judge)
j--;
else
break;
}
//交换左右两边的数据
int tem=p[i];
p[i]=p[j];
p[j]=tem;
++i;
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: