中级农民
- 积分
- 110
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2013-2-6
- 最后登录
- 1970-1-1
|
- public static int findMinStop(int g, int d, int[][] gasStations) {
- if (g >= d) return 0;
- if (gasStations == null || gasStations.length == 0) return -1;
- for (int i = 0; i < gasStations.length; i++) {
- gasStations[i][0] = d - gasStations[i][0];
- }
- int[] maxReach = new int[gasStations.length + 1];
- maxReach[0] = g;
- Arrays.sort(gasStations, new Comparator<int[]>() {
- @Override
- public int compare(int[] o1, int[] o2) {
- return o1[0] - o2[0];
- }
- });
- int res = 0;
- HashSet<Integer> visited = new HashSet<>();
- while (res < maxReach.length - 1 && maxReach[res] < d) {
- maxReach[res + 1] = maxReach[res] + findLargestWithOutRepeat(gasStations, visited, maxReach[res]);
- res++;
- }
- System.out.println(visited);
- return maxReach[res] < d ? -1 : res;
- }
- //O(N)
- private static int findLargestWithOutRepeat(int[][] gasStations, Set<Integer> visited, int maxDis) {
- int max = 0;
- int maxIndex = -1;
- for (int i = 0; i < gasStations.length; i++) {
- if (gasStations[i][0] > maxDis) {
- break;
- }
- if (visited.contains(i)) continue;
- if (gasStations[i][1] > max) {
- max = gasStations[i][1];
- maxIndex = i;
- }
- }
- visited.add(maxIndex);
- return max;
- }
- public static void main(String[] args) {
- int[][] test = {{24,10},{25, 1},{26,12}};
- System.out.println(findMinStop(10, 34, test));
- }
复制代码
草草写了一下 抛砖引玉 希望同学能贡献标答 |
|