Skip to content

Instantly share code, notes, and snippets.

@tanglie1993
Created August 13, 2017 03:58
Show Gist options
  • Save tanglie1993/d16fab37e412e9e04731aaa4b279a80a to your computer and use it in GitHub Desktop.
Save tanglie1993/d16fab37e412e9e04731aaa4b279a80a to your computer and use it in GitHub Desktop.
NumberOfTasksRunning
public int[] numberOfTasks(int[] start, int[] end, int[] queries){
if(start == null || end == null || queries == null){
throw new IllegalArgumentException("input cannot be null!");
}
if(start.length != end.length){
throw new IllegalArgumentException("Length of start and end must be identical!");
}
Arrays.sort(start);
Arrays.sort(end);
int[] sortedQueries = Arrays.copyOf(queries, queries.length);
Arrays.sort(sortedQueries);
Map<Integer, Integer> resultMapping = new HashMap<>();
int[] result = new int[queries.length];
int startIndex = 0;
int endIndex = 0;
for (int sortedQuery : sortedQueries) {
for (; startIndex < start.length; startIndex++) {
if (start[startIndex] > sortedQuery) {
break;
}
}
for (; endIndex < end.length; endIndex++) {
if (end[endIndex] > sortedQuery) {
break;
}
}
resultMapping.put(sortedQuery, startIndex - endIndex);
}
for(int i = 0; i < queries.length; i++){
result[i] = resultMapping.get(queries[i]);
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment