模拟数组/向量中的兵跳
simulating pawn jump in the array/vector
假设我们有一个大小为n的向量a
Pawn从A[0]开始,跳到A[0]指向的索引:A[0]的值告诉它如何移动,即:如果索引为6。
A[6]=1 -> move 1 to the right, to A[7]
A[6]=-2 -> move 2 to the left, to A[4]
如果pawn得到到最后一个索引,并且它是正的,则pawn退出作用域例子:
A 0 | 1 | 1 | 3 | 4 | 5 2 -1 4 1 4 2
每个元素包含的最大值为1 000 000和N <100万。函数应该返回4。
TASK:编写一个函数int arrayJmp ( const vector<int> &A )
,如果pawn永远不会离开表返回-1,如果它将跳出数组返回移动数。最坏情况下复杂度应该是0 (n)。你可以在下面找到我的答案。这样对吗?
您是否可以互换使用'表','数组'和'矢量' ?
请求很简单:
if ((i = array[ index ]) < 0 || i >= sizeof(array)) ;//out of bounds
otherwise i is within bounds
#include <iostream>
#include <vector>
int jump_array(const std::vector<int>& vector)
{
int index = 0;
int old_index = 0;
int size = vector.size();
int count = 0;
do
{
old_index = index;
index += vector[index];
if(count >= size)
{
return -1;
}
else
{
count++;
}
}
while(index < size);
return vector[old_index];
}
int main()
{
std::vector<int> vector;
vector.push_back(2);
vector.push_back(-1);
vector.push_back(4);
vector.push_back(1);
vector.push_back(4);
vector.push_back(2);
std::cout << jump_array(vector);
}
#include <algorithm>
void myfunction (int &i) { // function:
i=1000001;
}
int arrayJmp ( const vector<int> &A ) {
int N=A.size();
vector<int> indexes;
for_each (indexes.begin(), indexes.end(), myfunction);
int index=0;
while(std::find(indexes.begin(), indexes.end(), index) == indexes.end()){
indexes.push_back(index);
index+=A[index];
if (index==(N-1)&&A[index]>0) return indexes.size()+1;
}
return -1;
}
相关文章:
- 如何在向量数组中插入元素?
- 不同大小的向量数组的大小 cpp
- 很好的语法来获取对向量/数组数据的大小引用?
- 指向 c++ 中的向量数组并将其发送到函数的指针
- 初始化向量数组,其中每个向量的大小为 0
- 在这里,当我们比较 if(vc[i]==vc1[i]) 时,它是向量数组. 实际上比较的值是多少,
- 如何使用结构体的向量数组?
- C++:向量数组
- 在C++中通过引用传递向量数组
- 向量数组"Cannot access memory at address"
- 构造不同类型的C++向量数组
- 向量数组的均值和众数 - 如何对函数进行较小的改进
- C++:初始化(新)一个不同初始大小的向量数组
- 五个中三个最大参数的平均值,不使用排序算法或向量/数组
- 销毁C++中的向量数组
- 继承向量/数组/列表并更改其大小
- 如何输出属于向量数组的结构字符串
- 如何通过引用传递向量数组
- 在向量数组中获得前五个最大的结果
- 为什么"new vector<int>[5]"不创建向量数组?