PermCheck codility。 O(N)时间复杂度

时间:2014-11-09 17:26:52

标签: c# performance algorithm time-complexity

嗨我有PermCheck codility的这个解决方案。以下是包含问题的链接:https://codility.com/demo/results/demo73YNCU-8FK/

我得到了100%,但我的时间复杂度为O(N * log(N))或O(N)。 我怎么能使这个代码O(N)?你能简单介绍一下代码O(N)的原因吗?三江源。

此处代码为快捷方式:

    Array.Sort(A);
    if(A[0] == 1 && A.Length == 1) return 1;
    if(A[0] != 1) return 0;

    int n = 0;
    for(int i = 0; i < A.Length; i++)
    {    
        if(i < A.Length - 1)
        {
            if(A[i+1] == A[i] + 1)
            {
                n += 1;
            }
            else 
            {
                return 0;   
            }
        }

    }
    return 1;

5 个答案:

答案 0 :(得分:6)

创建一个与输入N相同大小的bool数组,并将所有元素保留为默认的false值。循环遍历输入的每个元素X.如果X大于N则返回false。如果array [N-1]为true,则返回false。否则将数组[N-1]设置为true。重复。这是O(N)。

说明:首先,如果你有一个排列,那么你需要元素1..N,但如果任何元素大于N,那么肯定会缺少一些元素。其次,如果一个元素出现两次,那就是一个问题,这就是为什么我们创建bool数组来记住已经看过的元素。

答案 1 :(得分:0)

这是我的100/100答案:

与@fejesjoco相同的想法

https://codility.com/demo/results/demoNR485D-33P/

您可以将int更改为long以获得性能。

    public int solution(int[] A)
    {
        // idea: add to set,dictionary. Count the size and compare to N.
        // dedupe data when needed. 
        var set = new HashSet<int>();
        var max = int.MinValue;

        foreach (var item in A)
        {
            if (set.Contains(item)) return 0;

            set.Add(item);
            if (item > max) max = item;
        }
        return set.Count == max ? 1 : 0;
    }

答案 2 :(得分:0)

这是我的解决方案,在正确性和性能方面得分为100%。

def解决方案(A):     arraylength = len(A)

if (arraylength > 100000):
    raise ValueError("Out of bound range")    

arr = sorted(A)

for i in range(arraylength):

    if (arr[i] != i+1):
        return 0

return 1 

答案 3 :(得分:0)

我知道很久以前就会问过这个问题,但是它仍然很活跃。

可能的解决方案:

public int solution(int[] A)
{
    return (Enumerable.Range(1, A.Length).Except(A).Count() == 0) ? 1 : 0;
}

答案 4 :(得分:-1)

快速解决方案100%

public func solution(_ A : inout [Int]) -> Int {
    // write your code in Swift 4.2.1 (Linux)

    let sorted = A.sorted()

    for (index, value) in sorted.enumerated() {

        if index+1 != value {

            return 0
        }
    }

    return 1
}