简体   繁体   中英

Sort the list of Strings where String contains 4 numbers, by using Comparator

I am trying to solve the 4 sum question of data structures & algorithms which is on Geeks for Geeks: https://practice.geeksforgeeks.org/problems/find-all-four-sum-numbers/0

Here's my solution:

import java.util.*;
import java.lang.*;
import java.io.*;
class GFG
 {
     public static void solve(int[] a,int n,int k)
     {
         Arrays.sort(a);
         HashMap<Integer,List<int[]>> hs = new HashMap<>();
         HashSet<String> set = new HashSet<>();
         List<String> ss = new ArrayList<>();
         boolean flag=false;
         for(int i=0;i<n-1;i++)
         {
             for(int j=i+1;j<n;j++)
             {
                 int sum = a[i]+a[j];
                 if(hs.containsKey(k-sum))
                 {
                     List<int[]> indexes = hs.get(k-sum);
                      
                    for(int[] index : indexes)
                    {
                        int i1 = index[0];
                        int i2 = index[1];
                        if(i2<i && i1!=i && i1!=j && i2!=i && i2!=j)
                        {
                            
                            String s = new String(""+a[index[0]]+" "+a[index[1]]+" "+a[i]+" "+a[j]+" $");
                            flag=true;
                            if(!set.contains(s))
                                ss.add(s);
                            set.add(s);    
                        }
                    }
                 }
                 List<int[]> temp = hs.getOrDefault(sum,new ArrayList<>());
                 temp.add(new int[]{i,j});
                 hs.put(sum,temp);
             }
         }
         if(!flag)
         System.out.print(-1);
         else
         {
             Collections.sort(ss,(String a1,String b1)->{
                 String[] st1 = a1.split(" ");
                 String[] st2 = b1.split(" ");
                //  if(a1.compareTo(b1)==0)
                //     return 0;
                 for(int i=0;i<st1.length;i++)
                 {
                     if(st1[i].compareTo(st2[i])>0)
                     {
                         return 1;
                     }
                 }
                 return -1;
             });
             for(String s1 : ss)
                System.out.print(s1);
         }
         System.out.println();
     }
     
     
    public static void main (String[] args)
     {
     Scanner sc = new Scanner(System.in);
        int t=sc.nextInt();
        while(t-->0)
        {
            int n = sc.nextInt();
            int k = sc.nextInt();
            int[] a = new int[n];
            for(int i=0;i<n;i++)
                a[i]=sc.nextInt();
            solve(a,n,k);
        }
     }
}

The answer requires the strings to be sorted ie all the unique numbers should be in increasing order, I have generated a list of Strings but I am unable to sort them in increasing order,

For Ex:

Input: 27 179 88 84 3 51 54 99 32 60 76 68 39 12 26 86 94 39 95 70 34 78 67 1 97 2 17 92 52

Its Correct output is: 1 2 84 92 $1 3 76 99 $1 3 78 97 $1 12 67 99 $1 12 78 88 $1 17 67 94 $1 26 60 92 $1 26 68 84 $1 32 51 95 $1 32 52 94 $1 32 54 92 $1 32 60 86 $1 32 68 78 $1 32 70 76 $1 34 52 92 $1 34 60 84 $1 34 68 76 $1 39 51 88 $1 51 60 67 $2 3 86 88 $2 12 68 97 $2 12 70 95 $2 17 68 92 $2 17 76 84 $2 26 52 99 $2 26 54 97 $2 26 67 84 $2 32 51 94 $2 32 67 78 $2 34 51 92 $2 34 67 76 $2 39 39 99 $2 39 52 86 $2 39 54 84 $2 39 60 78 $2 39 68 70 $3 12 67 97 $3 12 70 94 $3 12 76 88 $3 12 78 86 $3 17 60 99 $3 17 67 92 $3 26 51 99 $3 32 52 92 $3 32 60 84 $3 32 68 76 $3 34 54 88 $3 39 51 86 $3 39 67 70 $3 52 54 70 $.........

My Code Output: Your Output is: 12 34 39 94 $17 26 39 97 $34 39 39 67 $17 39 39 84 $2 39 39 99 $26 34 51 68 $26 32 51 70 $12 32 51 84 $3 39 51 86 $1 39 51 88 $2 34 51 92 $2 32 51 94 $1 32 51 95 $12 17 51 99 $3 26 51 99 $34 39 52 54 $26 34 52 67 $......

How can I do that using Comparator, I have written some login of comparator but it is either giving wrong Output or it is giving some sort of error:

Runtime Error:
Runtime ErrorException in thread "main" java.lang.IllegalArgumentException: Comparison method violates its general contract!
    at java.base/java.util.TimSort.mergeLo(TimSort.java:781)
    at java.base/java.util.TimSort.mergeAt(TimSort.java:518)
    at java.base/java.util.TimSort.mergeCollapse(TimSort.java:448)
    at java.base/java.util.TimSort.sort(TimSort.java:245)
    at java.base/java.util.Arrays.sort(Arrays.java:1515)
    at java.base/java.util.ArrayList.sort(ArrayList.java:1749)
    at java.base/java.util.Collections.sort(Collections.java:179)
    at GFG.solve(File.java:46)
    at GFG.main(File.java:78)

Please Help,

Thanks

When implementing a Comparator<T> (which you do with the lambda expression in Collections.sort() ) you must follow a few rules. One rule is that the comperator must return -1 if the first must be before the second element, 1 if the first must be after the second element or 0 if they can appear in any order. Since you don't return 0 , this rule is violated.

A second tule violated by your implementation is that the compare() method has to be transitive , meaning if compare(A, B) == 0 and compare(B, C) == 0 then compare(A, C) == 0 . May sorting algorithms rely on that rule to be true, which is the likely reason for the IllegalArgumentException you see. For more details on how to correctly implement a Comparator check the JavaDoc .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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