|
| 1 | +import java.util.ArrayList; |
| 2 | +import java.util.Collections; |
| 3 | +import java.util.Comparator; |
| 4 | +import java.util.List; |
| 5 | + |
| 6 | +/** |
| 7 | + * Suppose you are given two lists of n points, one list p1, p2, ..., pn on the line y = 0 and the other |
| 8 | + * list q1, q2, ..., qn on the line y = 1. Imagine a set of n line segments connecting each point pi to qi. |
| 9 | + * Write an algorithm to determine how many pairs of the line segments intersect. |
| 10 | + */ |
| 11 | +class LPoint { |
| 12 | + int x; |
| 13 | + int y; |
| 14 | + public LPoint(int x, int y) { |
| 15 | + this.x = x; |
| 16 | + this.y = y; |
| 17 | + } |
| 18 | +} |
| 19 | +public class DailyCoding194 { |
| 20 | + public static void main(String[] args) { |
| 21 | + System.out.println(numInversions(new int[]{2,4,1,3,5}) == 3); |
| 22 | + System.out.println(numInversions(new int[]{1, 20, 6, 4, 5}) == 5); |
| 23 | + } |
| 24 | + public static int intersections(int[] p, int[] q) { |
| 25 | + List<LPoint> points = new ArrayList<>(); |
| 26 | + for (int i=0; i<p.length; i++) { |
| 27 | + points.add(new LPoint(p[i], q[i])); |
| 28 | + } |
| 29 | + Collections.sort(points, (o1, o2) -> { |
| 30 | + if (o1.x == o2.x) { |
| 31 | + return 0; |
| 32 | + } else if (o1.x > o2.x) { |
| 33 | + return 1; |
| 34 | + } else { |
| 35 | + return -1; |
| 36 | + } |
| 37 | + }); |
| 38 | + int[] sorted = new int[q.length]; |
| 39 | + for (int i=0; i<points.size(); i++) { |
| 40 | + sorted[i] = points.get(i).y; |
| 41 | + } |
| 42 | + return numInversions(sorted); |
| 43 | + } |
| 44 | + public static int numInversions(int[] arr) { |
| 45 | + return mergeSort(arr, 0, arr.length-1); |
| 46 | + } |
| 47 | + public static int mergeSort(int[] arr, int start, int end) { |
| 48 | + int count = 0; |
| 49 | + if (start < end) { |
| 50 | + int mid = (start + end)/2; |
| 51 | + count += mergeSort(arr, start, mid); |
| 52 | + count += mergeSort(arr, mid+1, end); |
| 53 | + count += merge(arr, start, mid, end); |
| 54 | + } |
| 55 | + return count; |
| 56 | + } |
| 57 | + public static int merge(int[] arr, int start, int mid, int end) { |
| 58 | + int n = end-start+1; |
| 59 | + int[] tmp = new int[n]; |
| 60 | + int l = start, r = mid+1; |
| 61 | + int k = 0, count = 0; |
| 62 | + while (l <= mid && r<=end) { |
| 63 | + if (arr[l] <= arr[r]) { |
| 64 | + tmp[k] = arr[l]; |
| 65 | + l++; |
| 66 | + k++; |
| 67 | + } else { |
| 68 | + count += (mid - l + 1); |
| 69 | + tmp[k] = arr[r]; |
| 70 | + r++; |
| 71 | + k++; |
| 72 | + } |
| 73 | + } |
| 74 | + while (l <= mid) { |
| 75 | + tmp[k] = arr[l]; |
| 76 | + k++; |
| 77 | + l++; |
| 78 | + } |
| 79 | + while (r<=end) { |
| 80 | + tmp[k] = arr[r]; |
| 81 | + r++; |
| 82 | + k++; |
| 83 | + } |
| 84 | + for (int i=start; i<=end; i++) { |
| 85 | + arr[i] = tmp[i-start]; |
| 86 | + } |
| 87 | + return count; |
| 88 | + } |
| 89 | +} |
0 commit comments