[英]What data structure would be best for this in Java and how could I implement it efficiently?
这是针对代码战的编码挑战。 挑战的条件:考虑一个序列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);
}
}
}
我很好奇我可以在这里使用其他哪些结构来提高效率,因为我显然缺少解决此问题所需的知识。
似乎“双线性序列”是众所周知的。 您可能需要调查对该问题的第一个答复:
代码使用C#,并使用SortedSet (我相信Java也可用),并使用IEnumerable
和yield return
惰性求值,我认为可以使用Java( https://codurance.com/ 2018/11/26 / the-functional-style-part-7 / )
您可以将数字存储在HashMap中以存储数字。 使用x作为键,并使用(Y或Z)作为值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.