Friday, September 19, 2014

Another Codility task

Bellow is a Java implementation for a solution of the CountDistinctSlices problem that you can find under tasks the Caterpillar method lesson through this link https://codility.com/programmers/lessons/13. This solution has 100% correctness and it suffers in the performance as it is 40%.

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;


public class Solution {

 public int solution(int m, int[] a) {
  if(a.length >= 1000000000) {
   return a.length;
  }
  int cursor = 0;
  int count = a.length;
  HashSet check = new HashSet();
  List temp = new ArrayList();
  for(int y : a) {
   if(y>m) {
    continue;
   }
   temp.add(y);
  }
  
  a = new int[temp.size()];
     int i = 0;
     for (Integer e : temp)  
         a[i++] = e.intValue();
  
  for(int y = 0 ; y < a.length ; y++) {
   
   if(check.add(a[y])) {
    if(check.size() == 1)
     continue;
    count++;
    if(y+1 == a.length) {
     check.clear();
     cursor++;
     y=cursor-1;
    }
   } else {
    check.clear();
    cursor++;
    if(cursor > a.length) {
     break;
    }
    y=cursor-1;
    continue;
   }
  }
  return count;
 }
}

No comments:

Post a Comment