In an input array in Java, how do I find the number of pairs of values that are equal? -


i'm trying make o(nlogn) algorithm determines number of pairs of values in input array equal. thinking of doing storing each value of array in variable , continue comparing current value previous values , see if there's match , if there counter goes one.

int current value;  int previous value;      for(int j = 0; j < array.length; j++){         current value = array[k]         previous value = array[k-1] 

what i'm confused fact running time has o(nlogn) i'm wondering if that's right kind of method use problem or if there's better , more convenient way of doing this.

pseudo code:

n = array.length k - 1 n     if k == k-1      increment counter 1 

you can sort array , compare adjacent values, it's 1 option. you'll have complexity of o(n*log(n)) then.

another option track visited elements using temporary hashset , result hashmap counter pairs:

public static <t> map<t, integer> findpairs(list<t> elements) {     set<t> tracked = new hashset<>();     map<t, integer> result = new hashmap<>();     (t element : elements)         if (!tracked.add(element)) {             result.merge(element, 1, math::addexact);             tracked.remove(element);         }     return result; } 

this methods gives o(n) because insertion , removal hashset , hashmap o(1) on average, o(n) in worst case. if it's important have o(n*log(n)) in worst case should select first option select sorting algorithm accordingly. sorting algorithms have o(n2) worst case complexity.


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -