Last active
July 10, 2017 09:04
-
-
Save why168/4ab336825e26d9d6bef705cb3f3b7a4d to your computer and use it in GitHub Desktop.
算法面试题
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Test | |
public void algorithm() throws Exception { | |
// input: | |
int n = 3, m = 4; | |
int[] start = new int[]{0, 5, 2}; | |
int[] end = new int[]{4, 7, 8}; | |
int[] query = new int[]{1, 9, 4, 3}; | |
// output: [1,0,1,2] | |
int[] results = number_of_tasks_running(start, end, n, query, m); | |
for (int number : results) { | |
System.out.println(number); | |
} | |
} | |
/** | |
* 对于每个点,遍历每个区间,看是否在区间内 | |
* | |
* @param start 开始的区间 | |
* @param end 结束的区间 | |
* @param n 区间数 | |
* @param query 查询的点 | |
* @param m 查询数 | |
* @return 返回该点在区间上出现的次数 | |
*/ | |
private int[] number_of_tasks_running(int start[], int end[], int n, int query[], int m) { | |
int[] results = new int[m]; | |
List<int[]> list = new ArrayList<>(); | |
for (int i = 0; i < n; i++) { | |
list.add(new int[]{start[i], end[i]}); | |
} | |
for (int i = 0; i < m; i++) { | |
int count = 0; | |
int number = query[i]; | |
for (int j = 0; j < n; j++) { | |
int[] ints = list.get(j); | |
int first = ints[0]; | |
int last = ints[1]; | |
// System.out.println("[" + first + "," + last + ")"); | |
if (first <= number && last > number) { | |
count++; | |
} | |
} | |
results[i] = count; | |
} | |
return results; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
面试题