codility java,我对Codility MissingInteger的Java解决方案有什么问题?

本文探讨了 Codility 的 Missing Integer 问题,该问题要求找到数组中缺失的最小正整数。作者提供的解决方案使用 TreeMap 存储数组元素,但测试失败。分析表明,正确解冑应直接迭代寻找第一个不在数组中的正整数,而不是依赖于数组索引。解决方案需优化以确保 O(n) 的时间复杂度和 O(n) 的空间复杂度。
摘要由CSDN通过智能技术生成

I am trying to solve the codility MissingInteger problem link:

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.

My solution is:

class Solution {

TreeMap all = new TreeMap();

public int solution(int[] A) {

for(int i=0; i

all.put(i+1,new Object());

for(int i=0; i

if(all.containsKey(A[i]))

all.remove(A[i]);

Iterator notOccur = all.keySet().iterator();

if(notOccur.hasNext())

return (int)notOccur.next();

return 1;

}

}

The test result is:

zIbzR.png

Can anyone explain me why I got this two wrong answers? Especially the first one, if there is only one element in the array, shouldn't the only right answer be 1?

解决方案

returns the minimal positive integer that does not occur in A.

So in an array with only one element, if that number is 1, you should return 2. If not, you should return 1.

I think you're probably misunderstanding the requirements a little. Your code is creating keys in a map based on the indexes of the given array, and then removing keys based on the values it finds there. This problem shouldn't have anything to do with the array's indexes: it should simply return the lowest possible positive integer that isn't a value in the given array.

So, for example, if you iterate from 1 to Integer.MAX_VALUE, inclusive, and return the first value that isn't in the given array, that would produce the correct answers. You'll need to figure out what data structures to use, to ensure that your solution scales at O(n).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值