题目描述:
给一个正整数数列 nums,一个跳数 jump,及幸存数量 left。
运算过程为:从索引0的位置开始向后跳,中间跳过 J 个数字,命中索引为 J+1 的数字,该数被敲出,并从该点起跳,以此类推,直到幸存 left 个数为止,然后返回幸存数之和。
约束条件:
1. 0是第一个起跳点;
2. 起跳点和命中点之间间隔 jump 个数字,已被敲出的数字不计入在内;
3. 跳到末尾时无缝从头开始(循环查找),并可以多次循环;
4. 若起始时 left > len(nums) 则无需跳数处理过程;
5. 方法设计:
* @param nums 正整数数列,长度范围 [1, 10000]
* @param jump 跳数,范围 [1, 10000]
* @param left 幸存数量,范围 [0, 10000]
* @return 幸存数之和
int sumOfLeft(int[] nums, int jump, int left)
输入描述:
1. 第一行输入正整数数列;
2. 第二行输入跳数;
3. 第三行输入幸存数量;
输出描述:
输出幸存数之和
示例1:
输入
1, 2, 3, 4, 5, 6, 7, 8, 9
4
3
输出
13
说明:从1(索引0)开始起跳,中间跳过4个数字,因此依次删除6, 2, 8, 5, 4, 7。剩余1, 3, 9返回和为13;
C++源码:
#include <iostream>
#include <vector>
#include <numeric>
using namespace std;
int sumOfLeft(vector<int>& nums, int jump, int left) {
int jumpstep = 0;
if (left > nums.size()) {
return accumulate(nums.begin(), nums.end(), 0);
}
while (left != nums.size()) {
jumpstep += (jump + 1);
while (jumpstep >= nums.size()) {
jumpstep -= nums.size();
}
nums.erase(nums.begin() + jumpstep);
jumpstep -= 1;
}
return accumulate(nums.begin(), nums.end(), 0);
}
int main() {
//vector<int> nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
//int jump = 4;
//int left = 3;
vector<int> nums;
int num,jump,left;
while (cin >> num)
{
nums.push_back(num);
if (cin.get() == '\n') break; // 读取换行符,结束输入
}
cin >> jump;
cin >> left;
int result = sumOfLeft(nums, jump, left);
cout << "Remaining numbers: ";
for (int num : nums) {
cout << num << " ";
}
cout << endl;
cout << "Sum of remaining numbers: " << result << endl;
system("pause");
return 0;
}