zoukankan      html  css  js  c++  java
  • 最大数

    /*

    题目:最大数
    内容:

    [12,127,85,66,27,34,15,344,156,344,29,47,....]

    这是某设备测量到的工程数据。

    因工程要求,需要找出最大的5个值。

    一般的想法是对它排序,输出前5个。但当数据较多时,这样做很浪费时间。因为对输出数据以外的数据进行排序并非工程要求,即便是要输出的5个数字,也并不要求按大小顺序,只要找到5个就可以。

    以下的代码采用了另外的思路。考虑如果手里已经抓着5个最大数,再来一个数据怎么办呢?让它和手里的数据比,如果比哪个大,就抢占它的座位,让那个被挤出来的再自己找位子,....

    import java.util.*;
    public class B23
    {
    public static List<Integer> max5(List<Integer> lst)
    {
    if(lst.size()<=5) return lst;

    int a = _______________________; // 填空
    List<Integer> b = max5(lst);

    for(int i=0; i<b.size(); i++)
    {
    int t = b.get(i);
    if(a>t)
    {
    __________________; // 填空
    a = t;
    }
    }

    return b;
    }

    public static void main(String[] args)
    {
    List<Integer> lst = new Vector<Integer>();
    lst.addAll(Arrays.asList(12,127,85,66,27,34,15,344,156,344,29,47));
    System.out.println(max5(lst));
    }
    }


    请分析代码逻辑,并推测划线处的代码。

    答案写在 “解答.txt” 文件中

    注意:只写划线处应该填的内容,划线前后的内容不要抄写。
    */

     1 import java.util.Arrays;
     2 import java.util.List;
     3 import java.util.Vector;
     4 
     5 public class pro29
     6 {
     7     public static List<Integer> max5(List<Integer> lst)
     8     {
     9         if(lst.size()<=5) return lst;
    10         
    11         int a = lst.remove(0);  // 填空
    12         List<Integer> b = max5(lst);
    13         
    14         for(int i=0; i<b.size(); i++)
    15         {
    16             int t = b.get(i);
    17             if(a>t)
    18             {
    19                 b.set(i, a);  // 填空
    20                 a = t;  
    21             }
    22         }
    23         
    24         return b;
    25     }
    26     
    27     public static void main(String[] args)
    28     {
    29         List<Integer> lst = new Vector<Integer>();
    30         lst.addAll(Arrays.asList(12,127,85,66,27,34,15,344,156,344,29,47));        
    31         System.out.println(max5(lst));
    32     }
    33 }

    /*
    static <T> List<T> asList(T... a)
    返回一个受指定数组支持的固定大小的列表。
    boolean addAll(Collection<? extends E> c)
    追加指定 collection 中的所有元素到此列表的结尾,顺序是指定 collection 的迭代器返回这些元素的顺序(可选操作)。
    E get(int index)
    返回列表中指定位置的元素。
    E set(int index, E element)
    用指定元素替换列表中指定位置的元素(可选操作)。
    */

  • 相关阅读:
    LeetCode OJ 107. Binary Tree Level Order Traversal II
    LeetCode OJ 116. Populating Next Right Pointers in Each Node
    LeetCode OJ 108. Convert Sorted Array to Binary Search Tree
    LeetCode OJ 105. Construct Binary Tree from Preorder and Inorder Traversal
    LeetCode OJ 98. Validate Binary Search Tree
    老程序员解Bug的通用套路
    转载 四年努力,梦归阿里,和大家聊聊成长感悟
    转载面试感悟----一名3年工作经验的程序员应该具备的技能
    Web Service和Servlet的区别
    关于spring xml文件中的xmlns,xsi:schemaLocation
  • 原文地址:https://www.cnblogs.com/wsxjbky/p/3059037.html
Copyright © 2011-2022 走看看