找到缺少的整数(Codility测试)

时间:2015-03-14 17:07:57

标签: java algorithm

我在Codility上遇到了一个非常奇怪的问题,这里有任务描述:

Write a function:

class Solution { public int solution(int[] A); }  

that, given a non-empty zero-indexed array A of N integers, returns the minimal positive integer that does not occur in A.

For example, given:

    A[0] = 1
    A[1] = 3
    A[2] = 6
    A[3] = 4
    A[4] = 1
    A[5] = 2

the function should return 5.

Assume that:
N is an integer within the range [1..100,000];
each element of array A is an integer within the range [−2,147,483,648..2,147,483,647].

Complexity:
expected worst-case time complexity is O(N);
expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
Elements of input arrays can be modified.

还有我的代码:

class Solution {
    public int solution(int[] A) {
        SortedSet set = new TreeSet();
        for (int i = 0; i < A.length; i++)
            if (A[i] > 0)
                set.add(A[i]);
        Iterator it = set.iterator();
        int previous = 0, element = 0;
        try { previous = (int)it.next(); }
        catch (NoSuchElementException e) { return 1; }
        while (it.hasNext()) {
            element = (int)it.next();
            if (element!=(previous+1)) break;
            previous=element;
        }
        if (previous+1 < 1) return 1;
        return previous+1;
    }
}

代码分析:

http://i.stack.imgur.com/IlMxP.png

我试图找出为什么我的代码只在该测试中提供了错误的输出,是否有人能够帮助我?

提前致谢!

8 个答案:

答案 0 :(得分:2)

你得到了

  

得到3预期1

如果输入是A = [2],则输出

错误。在这种情况下,previous设置为2,while循环不会进入,并且该方法返回previous + 1。这是3,但正确的答案是1

答案 1 :(得分:1)

我找到了使用binarySearch得分为100/100的解决方案。

代码如下:

anova(fm3)
## Analysis of Variance Table
## Response: Reaction
##            Df Sum Sq Mean Sq F value    Pr(>F)    
## Days        1 162703  162703  71.464 9.894e-15 ***
## Residuals 178 405252    2277                      

答案 2 :(得分:1)

另一个复杂度为 O(n) 的答案:

 int solution(int A[]) {
    int smallestPostive=0;
    int maxPositive = 0;
    for (int number: A) { //Find maximum positive
        if (number> maxPositive) {
            maxPositive = number;
        }
    }
    if (maxPositive == 0) { // if all numbers are negative, just return 1
        return smallestPostive+1;
    }
    int[] data = new int[maxPositive]; //new array with all elements up to max number as indexes
    for (int element: A) {  // when you encounter a +ve number, mark it in the array
        if (element> 0)
            data[element-1] = 1;
    }
    for (int count=0; count<maxPositive;count++) {
        if (data[count] == 0) {  // find the unmarked smallest element
            smallestPostive = count+1;
            break;
        }
    }
return smallestPostive==0?maxPositive+1:smallestPostive; //if nothing is marked return max positive +1
}

答案 3 :(得分:0)

因为我们知道绝对最小值只能是1,所以我们可以从那里开始。

   import java.util.Arrays;
    class Solution {
        public int solution(int[] A) {
            Arrays.sort(A);     
            int min = 1; 

            for (int i = 0; i < A.length; i++){
                if(A[i]== min){
                    min++;
                }
            }   
            //min = ( min <= 0 ) ? 1:min;
            return min;    
        }
    }

答案 4 :(得分:0)

我的解决方案得分为100/100

// you can also use imports, for example:
// import java.util.*;

// you can write to stdout for debugging purposes, e.g.
// System.out.println("this is a debug message");
import java.util.Arrays;

class Solution {

    public int solution(int[] A) {

        int smallest = 1;

        Arrays.sort(A);
        for (int i = 0; i < A.length; i++) {

            if (A[i] == smallest) {

                smallest++;
            }
        }

        return smallest;
    }
}

最差的时间在“ large_2”测试用例上,为0.292s。

我会说很好。

如果您需要向我解释,以便我扩大答案:)

干杯。

答案 5 :(得分:0)

我通过将所有数据添加到hashSet并使用数组索引来检查hashset做了类似的事情。也有一些边缘情况。由于键集是一组,因此您还可以通过添加到哈希图并使用数组索引按顺序查找日期来获得相同的结果。

https://app.codility.com/demo/results/trainingVHZNXJ-68S/

 public int solution(int[] A) {
    Set<Integer> set = new HashSet<Integer>();
    for (int i = 0; i < A.length; i++) {
      set.add(A[i]);
    }

    int max = 0, missing = -1;
    for (int i = 1; i <= A.length; i++) {
      max = i;
      if (!set.contains(i)) {
        missing = i;
        break;
      }
    }
    return missing == -1 ? max + 1 : missing;
  }

答案 6 :(得分:0)

    import java.util.*;
    
    class Solution {
    
        public int solution(int[] A) {
            // write your code in Java SE 8
            Arrays.sort( A );
    
            //Print array to confirm
            int smallestVal = 1;
            int len = A.length;
            int prev=0;
    
            for(int i=0; i<len; i++){
                // Filtering all values less than 1 AND filtering the duplicates
                if( A[i] >= 1 && prev != A[i]){
                    if(smallestVal == A[i]){
                        smallestVal++;
                    }else{
                        return smallestVal;
                    }
                    prev = A[i];
                }
            }
            return smallestVal;
        }
    
        public static void main(String[] args) {
            Solution sol = new Solution();
            sol.testOutput(new int[]{-9, 1, 2},3);
            sol.testOutput(new int[]{-9, 2},1);
            sol.testOutput(new int[]{92,93,0,-100},1);
            sol.testOutput(new int[]{-1000000},1);
            sol.testOutput(new int[]{-5,6,-3,7,3,10,1000,-4000},1);
            sol.testOutput(new int[]{999999,-1000000,999998,-999999,-999998,1000000},1);
            sol.testOutput(new int[]{4,6,1,0,-9,10,0,-4},2);
            sol.testOutput(new int[]{-1},1);
            sol.testOutput(new int[]{1},2);
            sol.testOutput(new int[]{1000},1);
            sol.testOutput(new int[]{9,10, 12,1000000},1);
            sol.testOutput(new int[]{1, 3, 6, 4, 1, 2},5);
            sol.testOutput(new int[]{0, 2, 3},1);
            sol.testOutput(new int[]{-1,-3,-10,-100},1);
            sol.testOutput(new int[]{100, 98, 93,78,84, 34,0,1,2,102,130,123,150,200,199,185,149},3);
            sol.testOutput(new int[]{10,9,8,8,7,6,5,4,3,2,1,0,20,19,18,17,16,15,14,13,12},11);
        }
    
        private void testOutput(int[] in, int exp){
            Solution sol = new Solution();
            if(sol.solution(in) == exp){
                System.out.println("PASS");
            }else{
                System.out.println("Expected/Got:"+exp+" / " + sol.solution(in));
            }
        }
    }

答案 7 :(得分:0)

这里是我使用 Python 的 100% O(N) 复杂度解决方案。

def solution(A):
    smallest = 1
    B = {a for a in A}

    while(smallest in B):
        smallest += 1

    return smallest