• Codility经典算法题之九:MissingInteger


    Task description:

    This is a demo task.

    Write a function:

    that, given an array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A.

    For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5.

    Given A = [1, 2, 3], the function should return 4.

    Given A = [−1, −3], the function should return 1.

    Assume that:

    Complexity:

    Solution:python

    def solution(p):
        maxv = max(p)
        if maxv <= 0 :
            return 1
        else:
            for i in range(1,maxv+1):
                if i not in p:
                    return i
            return maxv+1

    java

    import java.util.Arrays;
        class Solution {
            //TODO int 放不下-1000000~1000000
            public int solution(int[] A) {
                Arrays.sort(A);
                int maxv = A[A.length - 1];
                if (maxv <= 0) {
                    return 1;
                } else {
                    int i;
                    for (i = 1; i < (maxv + 1); i++)
                        if (!check(A, i))
                            return i;
                }
                return maxv + 1;
    
            }
    
            boolean check(int[] A, int b) {
                for (int i = 0; i < A.length; i++) {
                    if (b == A[i])
                        return true;
                }
                return false;
            }
        }
     
  • 相关阅读:
    1351. 统计有序矩阵中的负数
    剑指 Offer 56
    39. 组合总和
    1619. 删除某些元素后的数组均值
    1380. 矩阵中的幸运数
    216. 组合总和 III
    面试题 08.03. 魔术索引
    1518. 换酒问题
    Xcode多进程调试:WKWebView
    Xcode编译WebKit
  • 原文地址:https://www.cnblogs.com/chenglc/p/9358952.html
Copyright © 2020-2023  润新知