试图解决SPOJ SUMFOUR,获得TLE测试用例10

时间:2019-03-15 02:12:41

标签: java algorithm debugging

一直在尝试解决https://www.spoj.com/problems/SUMFOUR/

我正在尝试使用两个for循环进行加法运算,并使用一个hashmap来检查可用性。我相信我的代码是n ^ 2。有人可以帮助我提高效率。

import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.util.*;

    class Main {
        public static void main(String args[]) throws Exception, java.lang.Exception {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            int len = Integer.parseInt(br.readLine());
            long arr[][] = new long[len][4];
            for (int i = 0; i < arr.length; i++) {
                String line[] = br.readLine().split(" ");
                arr[i][0] = Long.parseLong(line[0]);
                arr[i][1] = Long.parseLong(line[1]);
                arr[i][2] = Long.parseLong(line[2]);
                arr[i][3] = Long.parseLong(line[3]);
            }
            long index = 0l;
            HashMap<Long, Integer> map = new HashMap<>();
            for (int i = 0; i < len; i++) {
                for (int j = 0; j < len; j++) {
                    index = arr[i][0] + arr[j][1];
                    if (map.containsKey(index)) {
                        map.put(index, map.get(index) + 1);
                    } else
                        map.put(index, 1);
                }
            }
            int count = 0;
            for (int i = 0; i < len; i++) {
                for (int j = 0; j < len; j++) {
                    index = (arr[i][2] + arr[j][3]) * -1;
                    if (map.containsKey(index)) {
                        count = count + map.get((index));
                    }
                }
            }
            System.out.println(count);
        }
    }

0 个答案:

没有答案