Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 求序列元素值的算法_Java_Algorithm_Methods_Sequence_Sequences - Fatal编程技术网

Java 求序列元素值的算法

Java 求序列元素值的算法,java,algorithm,methods,sequence,sequences,Java,Algorithm,Methods,Sequence,Sequences,有以下顺序: 1010010001000001 如何定义一个方法,该方法获取序列元素的索引并返回值(0或1)​​这个元素是什么 public Element getValue(int index) {} 也许需要使用递归?如果有任何想法,我将不胜感激 小点表示这一系列将继续下去。因此,以下是您的解决方案: 让我们考虑基于1的索引。你注意到1出现在索引1处,(1+2)=3,(1+2+3)=6,(1+2+3+4)=10等等。我们有一个公式。它的n*(n+1)/2 因此,对于给定的索引(现在这是基于

有以下顺序:

1010010001000001

如何定义一个方法,该方法获取序列元素的索引并返回值(0或1)​​这个元素是什么

public Element getValue(int index) {}

也许需要使用递归?如果有任何想法,我将不胜感激

小点表示这一系列将继续下去。因此,以下是您的解决方案:

让我们考虑基于1的索引。你注意到1出现在索引1处,(1+2)=3,(1+2+3)=6,(1+2+3+4)=10等等。我们有一个公式。它的n*(n+1)/2

因此,对于给定的索引(现在这是基于0的,因为java数组从索引0开始),请执行以下操作:

index = index + 1;   // now it is 1 based index and our formula would fit in nicely.
index = index * 2;
sqroot = integer part of square root of index;
if( sqroot * (sqroot+1) == index)
  print 1;
else 
  print 0;

此外,不需要递归,因为这是O(1)解决方案(不考虑平方根函数的复杂性)

如果
索引+1
是一个函数,则返回
1
。x是三角形,当且仅当8x+1是正方形时。所以索引+1是三角形,如果和oly如果8*index+9是正方形

public int getValue(int index) {
    int i = (int)Math.round( Math.sqrt(8*index + 9));
    if (i*i == 8*index+9)
        return 1;
    else
        return 0;
}

如何存储您的序列?如果你知道这一点,那么答案将是微不足道的。许多数据结构允许通过索引(数组、列表、字符串)进行访问检查
index+1
是否为三角形编号: