计算形成几何级数的三胞胎

时间:2018-10-10 15:30:03

标签: java

为您提供了一个数组,您需要找到多个索引(i,j,k)的三元组,以便对于给定的公共比率r和i

static long countTriplets(List<Long> arr, long commonRatio) {
        long cnt = 0;
        Map<Long, Long> map = new HashMap<>();
        Map<Long, Long> rMap = new HashMap<>();
        for (long n : arr) {
            if (n % commonRatio == 0) {
                long pre = n / commonRatio`enter code here`;
                Long cnt2 = rMap.get(pre);
                if (cnt2 != null)
                    cnt += cnt2;

                Long cnt1 = map.get(pre);
                if (cnt1 != null)
                    rMap.put(n, rMap.getOrDefault(n, 0L) + cnt1);
            }
            map.put(n, map.getOrDefault(n, 0L) + 1);
        }
        return cnt;
    }

1 个答案:

答案 0 :(得分:0)

import java.util.*;
class Main{
    static long countTriplets(List<Long> arr, long commonRatio) {
        long cnt = 0;
        Map<Long, Long> map = new HashMap<>();
        Map<Long, Long> rMap = new HashMap<>();
        for (long n : arr) {
            if (n % commonRatio == 0) {
                long pre = n / commonRatio;// here was the mistake 'enter code here'
                Long cnt2 = rMap.get(pre);
                if (cnt2 != null)
                    cnt += cnt2;

                Long cnt1 = map.get(pre);
                if (cnt1 != null)
                    rMap.put(n, rMap.getOrDefault(n, 0L) + cnt1);
            }
            map.put(n, map.getOrDefault(n, 0L) + 1);
        }
        return cnt;
    }
    public static void main(String args[]){
        ArrayList <Long> ls=new ArrayList<Long>();
        ls.add(1l);
        ls.add(4l);
        ls.add(16l);
        ls.add(64l);
        long r=4l;
        System.out.println(countTriplets(ls, r));
    }   
}