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

标签 java arrays algorithm

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/

相关文章:

java - 从数组列表中返回某个 'type'的对象

java - ViewScope bean 支持 JSF ajax 调用吗?

java - 对于数组中的键进行二分查找,lo 或 hi 的最终值是多少?

javascript - jQuery 遍历循环删除元素

algorithm - 算法复杂度计算估计的基本操作的性能特征

java - 从包含周名和时间的字符串中解析时间

java - 在 ConstraintValidatorContext 上设置插值模板和消息模板

javascript - 等待多个 for-each 语句完成

algorithm - 数组中最接近的乘法值

c++ - 最大化 AND