从一组数中找到第二大的数/从一组数中找到不小于第二大数的数字的个数
来源:互联网 发布:c语言函数库apk 编辑:程序博客网 时间:2024/05/17 01:12
如题:1.从一组数中找到第二大的数,假设这组数无序,存储在数组中
#include "stdafx.h"#include<iostream>using namespace std;int findTheSecondLargeNum(int arr[],int length){ int maxValue = arr[0]; int secondValue= arr[0]; bool flag = false; if (length < 2) { return -1; } for (int i = 1; i < length; ++i) { if ((arr[i] < maxValue) && (flag == false))//consider the reverse order situation { secondValue = arr[i]; flag = true; } else if((arr[i] > secondValue)&&(arr[i] < maxValue)) { secondValue = arr[i]; } else if (arr[i] > maxValue) { secondValue = maxValue; maxValue = arr[i]; flag = true; } } if(flag == false) { cout<<"the array does not fit "<<endl; return -1; } return secondValue;}void main(){ int arr[] = {6,5,4,3,2,1}; int length = sizeof(arr)/sizeof(int); int result; result = findTheSecondLargeNum(arr,length); cout<<"the second large number is "<<result<<endl; system("pause")输出:the second large number is 5输出:the second large number is 5输出:the second large number is 5输出:the second large number is 5
输出:the second large number is 5
如题:2.从一组数中找到不小于第二大数的数字的个数,假设这组数无序,存储在数组中。
#include "stdafx.h"#include<iostream>using namespace std;int findTheSecondLargeNum(int arr[],int length){ int maxValue = arr[0]; int secondValue= arr[0]; int maxCount = 1; int secondCount = 0; bool flag = false; if (length < 2) { cout<<"there isn't the second larger number!"; return -1; } for (int i = 1; i < length; ++i) { if ((arr[i] < maxValue) && (flag == false)) { secondValue = arr[i]; flag = true; secondCount = 1; } else if((arr[i] >= secondValue)&&(arr[i] < maxValue)) { secondValue = arr[i]; ++secondCount; } else if(arr[i] == maxValue) { ++maxCount; } else if (arr[i] > maxValue) { secondValue = maxValue; maxValue = arr[i]; secondCount = maxCount; maxCount = 1; flag = true; } } if(flag == false) { cout<<"the array does not fit "<<endl; return -1; } return maxCount + secondCount;}void main(){ int arr[] = {-1,2,8,3,5,8,4,6,9,7,5,1,8,2,6}; int length = sizeof(arr)/sizeof(int); int result; result = findTheSecondLargeNum(arr,length); cout<<"There are "<<result<<" numbers larger than the second larger number"<<endl; system("pause");}
输出: There are 4 numbers larger than the second larger number
- 从一组数中找到第二大的数/从一组数中找到不小于第二大数的数字的个数
- 找到第二大的数
- 一种找到一组数中标记点的算法
- 删除一组数中重复的数字
- 找出一组数中个数超过一半的数
- 输出一组数里面第二大的值
- 从一组无序的整数中找出前N大的数
- 怎样从一个数组中找到第二大的元素
- 寻找一组数中最小的k个数
- 查找算法——找到序列中第二大的数(修正版)
- 查找算法——找到序列中第二大的数
- 打印一组数字中最大数及出现的次数
- C语言找一组数中单独出现的数字
- 【c++】在一组数中找出最小值的第二小的值
- 输入一组数据,在输入一个数,找到比它大的并排序
- 数组中求一组数的最大值
- 求一组数的第二小的数据
- 从10G个数中找到中数
- Mondrian
- Oracle DB2
- Intent 调用系统中经常用到的组件
- SQL Server 树型结构查询指定节点 SQL Server 树型结构查询的排序
- tools used by various tasks
- 从一组数中找到第二大的数/从一组数中找到不小于第二大数的数字的个数
- C++及C中的 string char指针及char数组
- HTML5究竟好在哪儿
- Report Designer wizard
- struts2.2.1文件下载及中文乱码问题解决
- JS变量也要注意初始化
- linux脚本之 for循环方式
- Git + gitosis + repo安装配置
- ignore SIGCHLD信号