2015-03-23搜狐实习笔试题目

题目如下:


下面是我写的一些解答,有更好的做法或者写法欢迎指正。

(1)

#include<iostream>
#include<algorithm>
#include<vector>
#include<cstdlib>
using namespace std;
/*
 *  (1) A数组是否有重复元素或者说前后值相差为1
 *  (2) A数组是否有序
 *
 */
void slove(int A[],int len){
	//assert(A!=NULL);
	int lastValue=A[0];
	sort(A,A+len);
	for(int i=0;i<len;i++){
	   if(i==0){
		   cout<<0<<"-"<<(A[0]>1?A[0]-1:0)<<endl;
	   }else{
		   if(A[i]-1<=lastValue){
			   lastValue=A[i];
			   continue;
		   }else{
		   cout<<lastValue+1<<"-"<<A[i]-1<<endl;
		   lastValue=A[i];
		   }
	   }
	}
	if(lastValue<100){
		cout<<lastValue+1<<"-"<<100<<endl;
	}
}

int main(){
	int testA[]={4,4,4,27};
	slove(testA,4);
}
(2) 递归写法
#include<iostream>
//int sumValue=0;
using namespace std;

#define len 7
void sum(int A[],int min,int max,int i,int &sumValue){
	if(i<=len){
		if(A[i]>=min&&A[i]<max){
			sumValue+=A[i];
			sum(A,min,A[i],i*2,sumValue);
			sum(A,A[i],max,i*2+1,sumValue);
		}else if(A[i]<min){
			//右子树
			sum(A,min,max,i*2+1,sumValue);
		}else if(A[i]>=max){
			//左子树
			sum(A,min,max,i*2,sumValue);
		}
	}
}
int main()
{
	/*                                5
	 *                             /     \
	 *                          3        8
	 *                        /   \     /   \
	 *                      1     4  7   10
	 *
	 */
  int A[]={0,5,3,8,1,4,7,10};
  int sumValue=0;
  sum(A,3,7,1,sumValue);
  cout<<"sumValue="<<sumValue<<endl;
}
(4) 二分查找的变种,稍稍改进一下二分搜索时间复杂度log(n)

#include<iostream>
using namespace std;
int binarySearch(int A[],int l,int r,int s){
	if(l<=r){
		int mid=l+(r-l)/2;
		if(A[mid]<s){
			//右子树查找
			if(mid+1<=r&&A[mid]<s&&A[mid+1]>=s)  //相邻的加判断
				return A[mid];
		  else if(mid+1>r&&A[mid]<s) return A[mid];  //处理一下特殊情况
		  else
			   return binarySearch(A,mid+1,r,s);
		}else{
           if(mid-1>=l&&A[mid-1]<s&&A[mid]>=s)
        	   return A[mid-1];
           else
        	   return binarySearch(A,l,mid-1,s);
		}
	}
	return -1; //找不到就返回-1
}

int main()
{
   int A[]={5,6,7,8};
   int val;
   if((val=binarySearch(A,0,3,10))!=-1){
	   cout<<val<<endl;
   }else{
	   cout<<"在数组中没有找到合适的值"<<endl;
   }
}



评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值