java - I have to count the all the possible pair from left to right in array.How I can do it effectively? -


//below implementation how improve that?

    int[] numbers = { 1, 5, 23, 2, 1, 6, 3, 1, 8, 12, 3 };     int count = 0;     int length = numbers.length;       for(int i=0; i<length; i++){         for(int j= i+1;j<length; j++ ){             if(j!=i && numbers[i]==numbers[j]){                 count+=1;             }         }     } 

solution in o(n):

public static void main(string[] args) {     int[] numbers = { 1, 5, 23, 2, 1, 6, 3, 1, 8, 12, 3 };     int count = 0;     map<integer, integer> elements = new hashmap<>();     (int = 0; < numbers.length; i++) {         integer e = elements.get(numbers[i]);         if (e == null){             e = 0;         }         count += e;         elements.put(numbers[i], e+1);      }     system.out.println("count: "+count); } 

Comments

Popular posts from this blog

c - Bitwise operation with (signed) enum value -

xslt - Unnest parent nodes by child node -

YouTubePlayerFragment cannot be cast to android.support.v4.app.Fragment -