C#次大数的函数

本文介绍了一种查找数组中次大数值的算法实现,并通过C#代码详细展示了该算法的具体步骤。首先找到最大值,然后从剩余元素中找出次大值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

好像昨天看了个博客,提到次大数函数。想了想写了一个备忘。

None.gifpublic int GetSecMax(int[] dataset)
ExpandedBlockStart.gifContractedBlock.gif    
dot.gif{
InBlock.gif        
if (dataset == null || dataset.Length == 1)
InBlock.gif            
throw new Exception("空或只有一个数");          //一个无解异常
InBlock.gif

InBlock.gif        
int Max = dataset[0];
InBlock.gif        
int secMax;
InBlock.gif        
bool hasMax = false;
InBlock.gif
InBlock.gif        
for (int i = 1; i < dataset.Length; i++)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
if (!hasMax && (Max != dataset[i]))
InBlock.gif                hasMax 
= true;
InBlock.gif            
if (Max < dataset[i])
InBlock.gif                Max 
= dataset[i];
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
if (hasMax)                                         //有解
ExpandedSubBlockStart.gifContractedSubBlock.gif
        dot.gif{
InBlock.gif            secMax 
= Max;
InBlock.gif            
bool hasSecMax = false;
InBlock.gif            
for (int j = 0; j < dataset.Length; j++)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
if (!hasSecMax)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    
if (dataset[j] < Max)
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
dot.gif{
InBlock.gif                        secMax 
= dataset[j];
InBlock.gif                        hasSecMax 
= true;
ExpandedSubBlockEnd.gif                    }

ExpandedSubBlockEnd.gif                }

InBlock.gif                
else
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif
InBlock.gif                    
if((secMax < dataset[j]) && (dataset[j] < Max))
InBlock.gif                        secMax 
= dataset[j];
ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

InBlock.gif
InBlock.gif            
return secMax;
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
throw new Exception("无解");  
InBlock.gif
ExpandedBlockEnd.gif    }

转载于:https://www.cnblogs.com/shichao/archive/2007/01/12/618418.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值