你能告诉我如何在整数数组中删除给定数字之前和之后的n个元素吗?例如,我们有1 2 2 4 2 2 2 9并且必须在数字#34; 4"之前和之后删除2个元素。所以它将离开1429.我试图想出一些东西,但......没什么。
var sequenceOfNums = Console.ReadLine().Split(' ').Select(int.Parse).ToList();
var specials = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
int bombNum = specialBombNum[0];
int power = specialBombNum[1];
for (int i = 0; i < sequenceOfNums.Count; i++) {
sequenceOfNums.RemoveRange(bombNum, sequenceOfNums.IndexOf(bombNum + power));
sequenceOfNums.Remove(bombNum);
}
答案 0 :(得分:0)
这应该有效:
var sequenceOfNums = new List<int> {1, 2, 2, 4, 2, 2, 2, 9};
int bombNum = 4;
int power = 2;
//Get the index of the special number
int locationOfSpecialNumber = sequenceOfNums.IndexOf(bombNum);
//Starting from (index of special number - [power]), remove [power] elements
sequenceOfNums.RemoveRange(locationOfSpecialNumber - power, power);
//Starting from (index of special number + 1), remove [power] elements.
//We subtract [power] from the starting index to account for the
//[power] elements we removed in the previous statement
sequenceOfNums.RemoveRange(locationOfSpecialNumber + 1 - power, power);