相关疑难解决方法(0)

找到给定序列中不存在的最小正整数

我试图解决下面提供的Codility中的问题,

写一个函数:

class Solution { public int solution(int[] A); }
Run Code Online (Sandbox Code Playgroud)

在给定N个整数的数组A的情况下,返回A中不存在的最小正整数(大于0).

例如,给定A = [1,3,6,4,1,2],函数应返回5.

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

Given A = [?1, ?3], the function should return 1.
Run Code Online (Sandbox Code Playgroud)

假使,假设:

N是[1..100,000]范围内的整数; 数组A的每个元素都是[-1,000,000..1,000,000]范围内的整数.复杂:

预期的最坏情况时间复杂度是O(N); 预期的最坏情况空间复杂度是O(N)(不计算输入参数所需的存储空间).

我写下面的解决方案,性能很低,但是,我看不到这个bug.

public static int solution(int[] A) {

        Set<Integer> set = new TreeSet<>();

        for (int a : A) {
            set.add(a);
        }

        int N = set.size();

        int[] C = new int[N];

        int index = 0;

        for (int a : set) {
            C[index++] …
Run Code Online (Sandbox Code Playgroud)

java algorithm

11
推荐指数
21
解决办法
3万
查看次数

标签 统计

algorithm ×1

java ×1