哪种数据结构最适合Java,我如何有效地实现它?

时间:2019-05-14 00:48:30

标签: java algorithm

这是针对代码战的编码挑战。挑战条件: 考虑一个序列u,其中u的定义如下:

The number u(0) = 1 is the first one in u.
For each x in u, then y = 2 * x + 1 and z = 3 * x + 1 must be in u too.
There are no other numbers in u.
Ex: u = [1, 3, 4, 7, 9, 10, 13, 15, 19, 21, 22, 27, ...]

1 gives 3 and 4, then 3 gives 7 and 10, 4 gives 9 and 13, then 7 gives 15 and 22 and so on...

Task:
Given parameter n the function dbl_linear (or dblLinear...) returns the element u(n) of the ordered (with <) sequence u (so, there are no duplicates).

我只生成250000个数字的幼稚实现:

import java.util.List;
import java.util.ArrayList;
import java.util.TreeSet;
import java.util.Set;
import java.util.HashSet;

class DoubleLinear {
        private static Set<Integer> nums;
        private static Set<Integer> seen;

        public static int dblLinear (int n) {
                nums = new TreeSet<>();
                seen = new HashSet<>();
                nums.add(1);
                for (int i = 0; i < 17; i++) {
                        generateNumbers();
                }
                List<Integer> numList = new ArrayList(nums);
                return numList.get(n);
        }

        public static void generateNumbers () {
                for (int x : new TreeSet<Integer>(nums)) {
                        if (seen.contains(x)) continue;
                        if (nums.size() >= 250000) break; 
                        int y = (2*x) + 1, z = (3*x) + 1;
                        if (y > 0) nums.add(y);
                        if (z > 0) nums.add(z);
                        seen.add(x);
                }
        }
}

我很好奇我可以在这里使用其他哪些结构来提高效率,因为我显然缺少解决这一问题所需的知识。

2 个答案:

答案 0 :(得分:3)

似乎“双线性序列”是众所周知的。您可能需要调查对该问题的第一个答复:

Double linear sequence gives odd results

代码使用C#,并使用 SortedSet (我相信Java也可用),并使用带有IEnumerableyield return的惰性评估,我认为可以使用Java(https://codurance.com/2018/11/26/the-functional-style-part-7/

完成

答案 1 :(得分:-1)

您可以将数字存储在HashMap中以存储数字。 使用x作为键,并使用(Y或Z)作为值。