java求数组中最大值拓展--求老二
来源:互联网 发布:tinycore linux有啥用 编辑:程序博客网 时间:2024/06/06 06:03
对一批数据进行排序,然后找出其中的最大最小值。
1)求数组中的最大值
方法1:遍历数组,比对数据。
public static int getMax(int[] array){int max = 0 ;for (int i : array) {max = max > i ? max : i;}return max;}
方法2:先对数组排序,然后寻找最后一个元素
public static int getMaxBySort(int[] array){int max = 0 ;Arrays.sort(array);max = array[array.length-1];//取得最后一个元素return max;}
两者就性能方面方法一较第二种高,因为Arrays.sort涉及元素移位操作(swap方法)
现在出现了一个新问题,假设我要找的是数组中第二大的元素呢,元素允许并列,类如
5,3,3,5,2这里边最大的是5,第二大的是3
思路:
方法1:允许元素并列求第二大,那我们给并列元素筛选出来不就行了吗,而set的特性是元素不重复
可以先将数组排序,然后依次存入set中(LinkedList按照保存顺序存储),于是就有了
public static int getSecond(int[] array){ int second = 0 ; Arrays.sort(array); Set<Integer> set = new LinkedHashSet<Integer>(); for (Integer num : array) { set.add(num); } Integer[] array1 = set.toArray(new Integer[0]); second = array1[array1.length-2]; System.out.println(second); return second; }方法2:删除重复元素并升序排列,这些都是TreeSet可以做到的
public static int getSecondByTreeSet(int[] array){int second = 0 ;List<Integer> dataList = Arrays.asList(new Integer[0]);TreeSet<Integer> set = new TreeSet<Integer>(dataList);second = set.lower(set.last());return second;}哈哈,这样就方便多了啊
- java求数组中最大值拓展--求老二
- java数组中求最大值
- java中数组求最大值、最小值、平均值。
- Java语言中,求数组中的最大值
- java求数组中最大值最小值
- 数组中求最大值
- 求数组中最大值
- 求数组中最大值
- java 数组求最大值
- C++ 求数组中最大值
- java数组、求最大值问题
- java递归求数组最大值
- Java 递归求数组最大值
- Java 中一个int型数组的求最大值最小值
- javascript中数组中求最大值
- 数组中求一组数的最大值
- 求数组中数对的最大值
- :求数组中最大值和下标
- ASP.NET 的session对象
- LVS
- (Ubuntu 12.04) Eclipse debug时遇到的问题: can't connect to vm
- document.all.item的解释
- Android Activty使用示例【慢慢更新】
- java求数组中最大值拓展--求老二
- android的底部多tab的效果
- JAVA深复制(深克隆)与浅复制(浅克隆)
- ProxyServlet代理
- 我对linux理解之alsa一
- Linux关于总线、设备、驱动的注册顺序
- MySQL加DRBD只能算是实时备份
- asp 包含文件 './../function/conn.asp' 不能用 '..' 表示父目录。
- 示波器基础知识100问