gpt4 book ai didi

java - 我怎样才能找到Java中数组的最小覆盖前缀?

转载 作者:搜寻专家 更新时间:2023-10-31 08:07:32 24 4
gpt4 key购买 nike

Find the first covering prefix of a given array.

A non-empty zero-indexed array A consisting of N integers is given. The first covering prefix of array A is the smallest integer P such that and such that every value that occurs in array A also occurs in sequence.

For example, the first covering prefix of array A with A[0]=2, A[1]=2, A[2]=1, A[3]=0, A[4]=1 is 3, because sequence A[0], A[1], A[2], A[3] equal to 2, 2, 1, 0 contains all values that occur in array A.

我的解决方案是

int ps ( int[] A ) 
{
int largestvalue=0;
int index=0;

for(each element in Array){
if(A[i]>largestvalue)
{
largestvalue=A[i];
index=i;
}
}

for(each element in Array)
{
if(A[i]==index)
index=i;
}
return index;
}

但这只适用于这个输入,这不是一个通用的解决方案。

最佳答案

100% 完成以下内容。

public int ps (int[] a)
{
var length = a.Length;
var temp = new HashSet<int>();
var result = 0;

for (int i=0; i<length; i++)
{
if (!temp.Contains(a[i]))
{
temp.Add(a[i]);
result = i;
}
}
return result;
}

关于java - 我怎样才能找到Java中数组的最小覆盖前缀?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5627966/

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