假设我有一个名为sequence的int数组 [1, 3, 2, 4, 3, 5, 4, 6, 1, 3]
我想看看 1
存在于数组中的第一个之外,如果存在,我想在数组中获取它的索引。
到目前为止,我已经做到了:
// Get the first and second number of the sequence array
int firstNumberIndex = 0;
int firstNumber = sequence[0];
int secondNumber = sequence[1];
// Check that firstNumber < secondNumber
if (firstNumber < secondNumber) {
// Remove firstNumber from the sequence array
instance = removeElement(sequence, firstNumberIndex);
// Check whether another instance of firstNumber exists in sequence array
if (contains(sequence, firstNumber)) {
// Here, I would like to get the index of the other instance of '1', for example
}
}
2条答案
按热度按时间slsn1g291#
与原始执行速度相比,更倾向于可读性:
观看现场演示。
index
将0
如果不存在第二次出现。gt0wga4j2#
快速回答使用哈希:
输出:
{1=[0, 8], 3=[1, 4, 9], 2=[2], 4=[3, 6], 5=[5], 6=[7]}
所以它为序列中的每一个值都给出了找到这个值的所有索引,这些索引可能大于或不大于op所要求的值。这些值按遇到的顺序返回(感谢linkedhashmap),并对索引进行排序。总的来说,它在时间上是o(序列长度)。