牛客网第六天的训练

基础题:数组中重复的数字

题目描述:在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。
因为范围是0到n-1,所以我们可以再开一个数组用来标记,初始化为1,如果出现过则置为-1,如果再次访问发现是-1,说明已经重复了,然后就好了。

class Solution {
public:
    // Parameters:
    //        numbers:     an array of integers
    //        length:      the length of array numbers
    //        duplication: (Output) the duplicated number in the array number
    // Return value:       true if the input is valid, and there are some duplications in the array number
    //                     otherwise false
    bool duplicate(int numbers[], int length, int* duplication) {
     	int a[1<<11]={1};
        for(int i=0;i<length;++i)						//遍历这个字符串
        {
            if(a[numbers[i]]==-1) 						//如果发现为-1,说明已经出现过了
            {
                *duplication=numbers[i];
                return true;
                break;
            }
            a[numbers[i]]=-1;							//把他标记一下
        }
        return false;
    }
};

进阶题: NowCoder的遭遇

题目描述:NowCoder的老家住在工业区,日耗电量非常大。是政府的眼中钉肉中刺,但又没办法,这里头住的可都是纳税大户呀。
今年7月,又传来了不幸的消息,政府要在7、8月对该区进行拉闸限电。但迫于压力,限电制度规则不会太抠门,政府决定从7月1日停电,然后隔一天到7月3日再停电,再隔两天到7月6日停电,一次下去,每次都比上一次晚一天。
NowCoder可是软件专业的学生,怎么离得开计算机。如果停电,就“英雄无用武之地”了。呵呵。
所以他开始盘算起自己回家的日子了,他想知道自己到家后到底要经历多少天倒霉的停电。你能帮他算一算吗?

题目给的数据都再7、8月之间,所以只考虑7、8月的情况就好了。

#include<iostream>
#include<algorithm>
#include<cstring> 
using namespace std;
void print_table();
int num[63];										//7、8月一共62天,放再一个数字里
int main()
{
	print_table();								//然后把停电的日子标记起来
	int a,b,day,ans;							//day代表回家的那一天
	while(~scanf("%d/%d",&a,&b))
	{
		if(!a&&!b) break;
		ans=0,day=0;
		if(a==8) day+=31;				//如果是8月,直接加31天
		day+=b;								//然后再把日期加上,就是回家的日子
		for(int i=day;i<63;++i)			//从回家的这一天开始到最后一天开始遍历
		{
			if(num[i]) ans++;
		}
		cout<<ans<<endl;
	}
	return 0;
}
void print_table()									//给7、8月停电的日子打表
{
	memset(num,0,sizeof(num));
	int m=0,k=1;										//m为第几天,k为每次中间增加的天数
	while(m<63)											
	{
		m+=k;
		num[m]=1;
		k++;
	}	
}

猜你喜欢

转载自blog.csdn.net/q1122333/article/details/83040845