Week12 作业 A - 必做题 - 1( 给出n个数,找出出现至少(n+1)/2次的数)

一、题目描述

给出n个数,zjm想找出出现至少(n+1)/2次的数, 现在需要你帮忙找出这个数是多少?

Input

本题包含多组数据:
每组数据包含两行。
第一行一个数字N(1<=N<=999999) ,保证N为奇数。
第二行为N个用空格隔开的整数。
数据以EOF结束。

Output

对于每一组数据,你需要输出你找到的唯一的数。

Sample Input

5
1 3 2 3 3
11
1 1 1 1 1 5 5 5 5 5 5
7
1 1 1 1 1 1 1

Sample Output

3
5
1

二、思路概述

  • 先对这n个数字排序,然后遍历数组,每出现一个新的数字,就计算这个数字出现的次数,若找到了符号要求的数字,则输出。

三、完整代码

#include<iostream>
#include<algorithm>
using namespace std;
const int maxn=1e6+10;

int a[maxn];

int main(){
	int n;
	while(cin>>n){
		
		for(int i=0;i<n;i++){
			cin>>a[i];
			//a[i]=0;
		}
		
		sort(a,a+n);//排序
		
		int nn=(n+1)/2;
		int num=a[0];
		int ans;
		int cnt=0;
		//cout<<nn<<endl;
		for(int i=0;i<n;i++){
						
			if(num==a[i]){
				cnt++;
			}
			else{
				
				num=a[i];
				cnt=1;
			}
			
			if(cnt>=nn){
				ans=a[i];
			    //cout<<"yes"<<endl; 
				break;
			}
			//cout<<cnt<<endl;
		} 
		cout<<ans<<endl;
	}
	
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这个错误出现的原因是在使用单步指平滑法时,预测新值时的索引超出了已有据的范围。这可能是因为你设置的预测值量 `n_preds` 太大,超过了已有据的长度。 为了解决这个问题,你可以检查一下据的长度和预测值量,确保它们的值是合理的。另外,你也可以尝试缩小 `n_preds` 的值,看看是否能够正常运行。 下面是修改后的代码,包含了对据长度和预测值量的检查: ```python import pandas as pd from pyecharts import options as opts from pyecharts.charts import Line # 读取Excel文件 data = pd.read_excel('6004020918.xlsx') # 提取据 week = data['week'] need = data['need'] # 定义单步指平滑函 def single_exponential_smoothing(series, alpha, n_preds): result = [series[0]] for i in range(1, len(series) + n_preds): if i >= len(series): # 检查是否超出范围 if i - len(series) + 1 > n_preds: break # 预测新值 m = i - len(series) + 1 result.append(alpha * series[-1] + (1 - alpha) * result[-1]) else: # 更新指平滑值 result.append(alpha * series[i] + (1 - alpha) * result[i-1]) return result # 设置单步指平滑法参 alpha = 0.5 n_preds = 77 # 预测的值量 # 检查据长度和预测值量 data_length = len(need) if n_preds > data_length: n_preds = data_length # 进行单步指平滑预测 predictions = single_exponential_smoothing(need[:100], alpha, n_preds) # 创建折线图对象 line = Line() line.set_global_opts( title_opts=opts.TitleOpts(title='时间序列预测分析'), legend_opts=opts.LegendOpts(pos_top='5%'), tooltip_opts=opts.TooltipOpts(trigger="axis", axis_pointer_type="cross") ) # 添加预测值据 line.add_xaxis(week[100:100+n_preds]) line.add_yaxis('预测值', predictions, is_smooth=True, label_opts=opts.LabelOpts(is_show=False)) # 添加实际值据 line.add_yaxis('实际值', need[100:100+n_preds], is_smooth=True, label_opts=opts.LabelOpts(is_show=False)) # 生成HTML文件 line.render('time_series_forecast.html') ``` 请尝试运行修改后的代码,看看问题是否解决。如果问题仍然存在,请提供更多的信息,以便我能够帮助你解决问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值