在一个数组中找到最大的两个数
2014-02-28 10:43
232 查看
在一个给定数组中找出最大的两个数:
算法:
预设两个最大数int 来存储数组中两个最大的数,保证max1在遍历数组过程中相比max2,一直是最大的。在遍历过程中数组中的其他数只与max2比较,小于max2时,取代max2,再与max1比较,后来再确保max1始终比max2大。时间复杂度O(n),线性!
算法:
预设两个最大数int 来存储数组中两个最大的数,保证max1在遍历数组过程中相比max2,一直是最大的。在遍历过程中数组中的其他数只与max2比较,小于max2时,取代max2,再与max1比较,后来再确保max1始终比max2大。时间复杂度O(n),线性!
/* Try to find the 2 maximum number in an array */ #include <iostream> #include <algorithm> using namespace std; void compare(int & , int & ); int main (){ int a[8]={2,123,31,21,42,1,421,0}; int max1,max2; max1=a[0]; max2=a[1]; //Make sure that max1 always be the most largest number compare(max1,max2); //Traverse the array to assign number to max1 and max2; for (int i=2; i<8; ++i) { if (a[i]>max2) { max2=a[i]; compare(max1, max2); } } cout<<max1<<endl; cout<<max2<<endl; } void compare(int & max1, int & max2){ if (max2>max1) { swap(max1, max2); } }
相关文章推荐
- 1.将数组A中的内容和数组B中的内容进行交换。(数组一样大) 2.获取一个数二进制序列中所有的偶数位和奇数位,分别输出二进制序列。 3.将三个数按从大到小输出。 4.求两个数的最大公约数。
- 给一个整数数组,找到两个数使得他们的和等于一个给定的数 target(容易)
- 数组试题---在一个先增长后减小的数组中找到最大值 .
- 如何找到一个数组中的两个数,他们的和为0
- 在一个数组中找到连续的子数组最大的乘积
- 在一个无序数组中找到第K个最小或者最大的元素
- 如果给定一个数组arr[0,...N-1],要求找出相邻两个数的最大差值
- 一个数组中同时找到最大/最小值
- [面试题]在一个先增长后减小的数组中找到最大值
- 在数组中找到至少包含一个数字的子阵具有最大的乘积
- 在一个数组中找 差值最大的两个数 差值最小的两个数 推广到 点对
- 找出一个数组中两个数的最大差值和最小差值(最接近的数)
- 给定一个二进制数组,找到一个连续的0和1相等的最大子数组。
- 说你有一个数组,其中第i个元素是第i天给定股票的价格。设计一个算法来找到最大的利润,最多可以完成两个交易。
- 如何计算一个整形数组里的连续元素和的最大值?
- 课堂练习----一个整数数组中最大子数组的和(2)
- 定义一个二维数组,写函数来实现对该二维数组求最大值。(要求,用行指针为函数形参)
- 数组1--求一个数的最大子数组
- 返回一个二维整数数组中最大子数组的和(头尾相接)
- 数组中找到2,3,n个数等于一个值