gpt4 book ai didi

c# - 从 C# 中的唯一(独立)元素获取索引

转载 作者:行者123 更新时间:2023-12-04 22:39:12 24 4
gpt4 key购买 nike

我想获得独立元素的索引。元素本身可能更频繁地出现在列表中(一个接一个或混合出现)。单个元素的指示是前驱和后继不等于当前元素。有没有一种优雅的方法来做到这一点?

示例 :

1.  A
2. A
3. A
4. B
5. B
6. A
7. B
8. B
9. C
10. B

结果:
6,9,10

最佳答案

简单地迭代项目并检查该条件

char[] items = { 'A', 'A', 'A', 'B', 'B', 'A', 'B', 'B', 'C', 'B' };
for (int i = 0; i < items.Length; i++)
{
if (i == 0)
{
// in case of the first element you only have to validate against the next
if (items[i] != items[i + 1])
Console.WriteLine(i + 1);
}
else if (i == items.Length - 1)
{
// in case of the last element you only have to validate against the previous
if (items[i] != items[i - 1])
Console.WriteLine(i + 1);
}
else
{
// validate against previous and next element
if (items[i] != items[i - 1] && items[i] != items[i + 1])
Console.WriteLine(i + 1);
}
}

https://dotnetfiddle.net/kWmqu7

关于c# - 从 C# 中的唯一(独立)元素获取索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58501276/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com