模拟数组/向量中的兵跳

simulating pawn jump in the array/vector

本文关键字:向量 数组 模拟      更新时间:2023-10-16

假设我们有一个大小为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;
}