活跃农民
- 积分
- 806
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2019-2-1
- 最后登录
- 1970-1-1
|
本帖最后由 djmiss 于 2020-6-14 02:52 编辑
拿上面的java代码改了个O(n)解法:
- public class TestMS {
- private final static int MOD = 1_000_000_007;
- public TestMS() {
- }
-
- private int GCD(int a, int b) {
- if (a == 0 || b == 0) return a + b;
- return GCD(b, a%b);
- }
-
- private int solution(int[] X, int[] Y) {
- Map<Integer, Map<Integer, Integer>> map = new HashMap<>();
- for (int i = 0; i < X.length; i++) {
- int gcd = GCD(X[i], Y[i]);
- Map<Integer, Integer> subMap = map.getOrDefault(Y[i] / gcd, new HashMap<Integer, Integer>());
- subMap.put(X[i] / gcd, subMap.getOrDefault(X[i] / gcd, 0) + 1);
- map.putIfAbsent(Y[i] / gcd, subMap);
- }
-
- long count = 0L;
- for (Map.Entry<Integer, Map<Integer, Integer>> entry: map.entrySet()) {
- int denominator = entry.getKey();
- Map<Integer, Integer> subMap = entry.getValue();
- for (int numerator: subMap.keySet()) {
- int target = denominator - numerator;
- if (!subMap.containsKey(target)) continue;
- int c1 = subMap.get(numerator);
- int c2 = subMap.get(target);
- count += (target == numerator) ? (long)c1 * (c2 - 1) : (long)c1 * c2;
- }
- }
- return (int)((count / 2) % MOD);
- }
-
- private int bruteForce(int[] X, int[] Y) {
- long count = 0;
- for (int i = 0; i < X.length - 1; i++) {
- for (int j = i + 1; j < X.length; j++) {
- long divident = (long)X[i] * Y[j] + (long)X[j] * Y[i];
- long divisor = (long)Y[i] * Y[j];
- if (divident == divisor) {
- count++;
- }
- }
- }
- return (int) (count % MOD);
- }
- public static void main(String args[]) {
- TestMS test = new TestMS();
- System.out.println(test.solution(new int[]{1, 1 , 1}, new int[]{2, 2, 2}));
- System.out.println(test.bruteForce(new int[]{1, 1 , 1}, new int[]{2, 2, 2}));
- System.out.println(test.solution(new int[]{1, 2 , 3, 1, 2, 12, 8, 4}, new int[]{5, 10, 15, 2, 4, 15, 10, 5}));
- System.out.println(test.bruteForce(new int[]{1, 2 , 3, 1, 2, 12, 8, 4}, new int[]{5, 10, 15, 2, 4, 15, 10, 5}));
- System.out.println(test.solution(new int[]{500000000, 500000000}, new int[]{1000000000, 1000000000}));
- System.out.println(test.bruteForce(new int[]{500000000, 500000000}, new int[]{1000000000, 1000000000}));
-
- int maxLength = 100000;
- int[] x = new int[maxLength];
- int[] y = new int[maxLength];
- int nx = 1, ny = 2;
- for (int i = 0; i < maxLength; i++) {
- x[i] = nx; nx++;
- y[i] = ny; ny += 2;
- }
- long startTime = System.currentTimeMillis();
- System.out.println(test.solution(x, y) + ", time:" + (System.currentTimeMillis() - startTime));
- startTime = System.currentTimeMillis();
- System.out.println(test.bruteForce(x, y) + ", time:" + (System.currentTimeMillis() - startTime));
- }
- }
复制代码
|
|