Saturday, April 18, 2015

Leader - EquiLeader

Here is another codility problem solution from the codility lessons (EquiLeader -Find the index S such that the leaders of the sequences A[0], A[1], ..., A[S] and A[S + 1], A[S + 2], ..., A[N - 1] are the same. ) due to the copy rights I can't copy the content of the problem here so to view the problem description click here.




// you can also use imports, for example:
// import java.util.*;

// you can use System.out.println for debugging purposes, e.g.
// System.out.println("this is a debug message");

class Solution {
 public int solution(int[] A) {
  // write your code in Java SE 8


  Integer[] equi = findEquiLeader(A);
  if (equi == null) return 0;
  else {
   int equiLeader = equi[0];
   int count = equi[1];
   int startCount = 0;
   int equileaderCount = 0;
   for (int i = 0; i < A.length; i++) {
    if (A[i] == equiLeader) startCount++;

    if (startCount > (i + 1) / 2 && (count - startCount) > (A.length - (i + 1)) / 2) {
     equileaderCount++;
    }
   }
   return equileaderCount;
  }

 }
 private Integer[] findEquiLeader(int[] A) {
  int len = A.length;
  int size = 0;
  Integer value = null;
  for (int i = 0; i < A.length; i++) {
   if (size == 0) {
    value = A[i];
    size++;
   } else {
    if (value == A[i]) {
     size++;
    } else {
     size--;
    }
   }
  }
  if (size > 0) {
   int count = 0;
   for (int i: A) {
    if (i == value) count++;
   }
   if (count > A.length / 2) {


    return new Integer[] {
     value, count
    };

   }


  }

  return null;

 }


}



///Using Hashmap

class Solution {
    public int solution(int[] A) {
        // write your code in Java SE 8
        HashMap< Integer,Integer> hm = new HashMap();
        for( int i: A)
        {
            if(hm.containsKey(i))
                hm.put(i,hm.get(i)+1);
            else
                 hm.put(i,1);
        }
        int maxNum=0;
        int maxCount=0;
        for(int j: hm.keySet())
        {
            int currentCount=hm.get(j);
            if(maxCount< currentCount)
            {
                maxCount=currentCount;
                maxNum=j;
            }
        }
        //System.out.println(maxCount+" "+maxNum);
        int countOfMax=maxCount;
        int firstPart=0;
        int equiLeader=0;
        for(int i =0;i< A.length-1;i++)
        {
            if(A[i]==maxNum)
            {
                countOfMax--;
                firstPart++;
            }
          
            if((A.length-(i+1))/2< countOfMax&&(i+1)/2< firstPart)
            {
                equiLeader++;
            }
        }
        return equiLeader;
    }
}

No comments:

Post a Comment