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
Post a Comment