当前位置:  首页>> 技术小册>> 数据结构与算法(中)

难度:
Hard

题意:

  1. 给定n个区间
  2. 求一个最小集合,使得每个区间,集合中至少有两个数在区间里面

思路:

  • 这题是贪心题
  • 先对区间右端点排序。再从右端点小的开始贪心。每次先判断当前集合中是否有两个数在这个区间中,如果有,直接跳过,没有,从右端点开始往集合丢数,直到有两个数在这个区间中
  • 直观的解释就是,为了满足前面的区间的条件,而丢进集合的数一定是越大越好,这样跟后面的区间共用一个数的几率会更大

解法:

  1. class Solution {
  2. public int intersectionSizeTwo(int[][] intervals) {
  3. Integer[] array = new Integer[intervals.length];
  4. for (int i = 0;i < array.length;i++) {
  5. array[i] = i;
  6. }
  7. Arrays.sort(array, new Comparator<Integer>() {
  8. @Override
  9. public int compare(Integer o1, Integer o2) {
  10. return Integer.compare(intervals[o1][1], intervals[o2][1]);
  11. }
  12. });
  13. List<Integer> result = new ArrayList<Integer>();
  14. int[] t = new int[2];
  15. for (int i = 0;i < array.length;i++) {
  16. int n = 0;
  17. if (result.size() > 0 && result.get(result.size() - 1) >= intervals[array[i]][0]) {
  18. t[n++] = result.get(result.size() - 1);
  19. }
  20. if (result.size() > 1 && result.get(result.size() - 2) >= intervals[array[i]][0]) {
  21. t[n++] = result.get(result.size() - 2);
  22. }
  23. int res = n;
  24. int j = intervals[array[i]][1];
  25. while (n != 2) {
  26. boolean found = false;
  27. for (int k = 0;k < n;k++) {
  28. if (t[k] == j) {
  29. found = true;
  30. break;
  31. }
  32. }
  33. if (found) {
  34. j--;
  35. } else {
  36. t[n++] = j--;
  37. }
  38. }
  39. if (res == 0) {
  40. result.add(t[1]);
  41. result.add(t[0]);
  42. }
  43. if (res == 1) {
  44. result.add(t[1]);
  45. }
  46. }
  47. return result.size();
  48. }
  49. }

该分类下的相关小册推荐: