剑指offer面试题28-29

16 篇文章 0 订阅

      实现剑指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;
		}
	}
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值