【发布时间】:2020-04-24 10:52:52
【问题描述】:
我试图通过树集按降序对数组进行排序来找到数组的第三大元素,但是某些测试用例对于某些输入值失败,而大多数测试用例对于某些输入值通过。
我的代码:
// { 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;
}
}
Link to the question where you can run the code
请解释为什么这段代码未能通过给定的测试用例。
【问题讨论】:
-
从
Scanner获取数字时,只需将数字直接添加到TreeSet。然后使用方法descendingIterator()
标签: java arraylist comparator testcase treeset