简体   繁体   English

通过按降序对 TreeSet 进行排序来查找数组的第三大元素

[英]Finding the third largest element of an array by sorting it through TreeSet in a decreasing order

I am trying to find the third largest element of an array by sorting it through treeset in a decreasing order, but some of the test cases fail for certain input values and most of it pass for certain input values.我试图通过按降序对树集进行排序来找到数组的第三大元素,但是某些测试用例对于某些输入值失败,并且大多数测试用例对于某些输入值都通过。

My code:我的代码:

// { Driver Code Starts
import java.util.Scanner;
import java.util.*;
import java.io.*;

class ThirdLargestElement
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        int t = sc.nextInt();
        while(t>0)
        {
            long n =sc.nextLong();
            Long arr[] = new Long[(int)n];
            for(long i=0;i<n;i++)
                arr[(int)i] = sc.nextLong();
            GfG g = new GfG();
            System.out.println(g.thirdLargest(arr));
        t--;
        }
    }
}// } Driver Code Ends
class GfG
{
    long thirdLargest(Long a[])
    {
    // Your code here
        if(a.length<3)
            return -1;
        else{
            TreeSet<Long> ts=new TreeSet<Long>(new myComparator());
            for(long i:a)
                ts.add(i);
            ArrayList<Long> al=new ArrayList<Long>(ts);
            return al.get(2);
        }
    }
}
class myComparator implements Comparator{
    public int compare(Object obj1,Object obj2){
        Long a=(Long) obj1;
        Long b=(Long) obj2;
        if(a<b)
            return 1;
        else if(a>b)
            return -1;
        else 
            return 0;
    }
}

The testcase it failed:它失败的测试用例: 在此处输入图像描述

Link to the question where you can run the code 链接到可以运行代码的问题

Please explain why this code failed to pass the given test case.请解释为什么这段代码未能通过给定的测试用例。

You can directly add elements to TreeSet and get third largest number using stream,您可以直接向TreeSet添加元素并使用stream获得第三大数字,

while(t>0)
{
    long n =sc.nextLong();
    TreeSet<Long> ts=new TreeSet<>(Comparator.comparingLong(Long::longValue).reversed());
    for(long i=0;i<n;i++)
        ts.add(sc.nextLong());
    long thirdLast = ts.stream()
            .limit(3)
            .skip(2)
            .mapToLong(e->e)
            .findAny().orElse(0l);

    System.out.println(thirdLast);
    t--;
}

Try This one试试这个

class GfG {
    long thirdLargest(Long a[]) {
        Arrays.sort(a);
        List<Long> numbers = Arrays.asList(a);
        Collections.reverse(numbers);
        return numbers.size() >= 3 ? numbers.get(2) : -1;
    }
}

The question states: 问题指出:

the function thirdLargest... takes two argument. function thirdLargest...需要两个参数。 The first argument is the array a[] and the second argument is the size of the array (n).第一个参数是数组 a[],第二个参数是数组的大小 (n)。

Although the question states that the array is...尽管问题表明数组是...

an array of distinct elements一组不同的元素

the test cases indicate that we are dealing with an array of integers.测试用例表明我们正在处理一个整数数组。

Personally, I don't see the need for the second method parameter, because in java an array is an object and has a length member.就我个人而言,我认为不需要第二个方法参数,因为在 java 中,一个数组是 object 并且有一个length成员。 So my implementation below only takes one parameter, namely an array of int .所以我下面的实现只需要一个参数,即一个int数组。 Maybe the people at geeksforgeeks.org simply converted a question that was originally for the C language to java, since, in C, it is difficult to determine the size of any array.也许geeksforgeeks.org的人只是简单地将一个原本针对C 语言的问题转换为java,因为在C 中,很难确定任何数组的大小。

Each element in a TreeSet must be an object, so we need to convert the elements in the int array to Integer objects. TreeSet中的每个元素必须是一个 object,因此我们需要将int数组中的元素转换为Integer对象。 Autoboxing will do this automatically, n.netheless my code below contains an explicit conversion. 自动装箱会自动执行此操作,尽管我下面的代码包含显式转换。 So in the method I create a TreeSet .所以在方法中我创建了一个TreeSet Since class Integer implements interface Comparable , the default TreeSet constructor is sufficient.由于 class Integer实现接口Comparable ,默认的TreeSet构造函数就足够了。 I add all the elements of the int array to the TreeSet , then obtain a descending iterator and then iterate to the third element returned by the iterator, which is the value that the method needs to return.我将int数组的所有元素添加到TreeSet中,然后获取一个降序迭代器,然后迭代到迭代器返回的第三个元素,这就是该方法需要返回的值。

    int thirdLargest(int[] arr) {
        int third = -1;
        if (arr != null  &&  arr.length > 2) {
            TreeSet<Integer> set = new TreeSet<Integer>();
            for (int elem : arr) {
                set.add(Integer.valueOf(elem));
            }
            Iterator<Integer> iter = set.descendingIterator();
            if (iter.hasNext()) {
                iter.next();
                if (iter.hasNext()) {
                    iter.next();
                    if (iter.hasNext()) {
                        third = iter.next().intValue();
                    }
                }
            }
        }
        return third;
    }

Of-course, if you want to ignore the conditions imposed by the original question, you could get the third largest element using the stream API当然,如果你想忽略原题强加的条件,你可以使用stream API得到第三大元素

IntStream.of(2, 4, 1, 3, 5)
         .boxed()
         .sorted(Collections.reverseOrder())
         .collect(Collectors.toList()).get(2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM