【问题标题】:Missing integer variation - O(n) solution needed [closed]缺少整数变化 - 需要 O(n) 解决方案 [关闭]
【发布时间】:2014-07-28 19:00:51
【问题描述】:

问题来自 Codility 编程培训,听起来如下: 我们有一个包含 n 个(范围从 1 到 100,000)个元素的数组 (A[]),这些是我们的参数。数组的元素是从 -2,147,483,648 到 2,147,483,647 的整数,我们需要找到不在数组中的最小正整数。当然,这可以在 O(n*log n) 中轻松完成,方法是对它们全部排序并遍历排序后的数组,寻找丢失的正数(最后一个操作在我的解决方案中具有 O(n) 最差时间复杂度)。但是根据 Codility 的说法,这个整个问题可以在 O(n) 中完成,我看不出有任何方法可以做到这一点。有人可以提供一些提示让我摆脱困境吗?

PS 这是一个我不能复制的问题的详细描述的链接 - https://codility.com/c/intro/demo35UEXH-EAT

【问题讨论】:

  • 可以分配 O(n) 大小的临时存储空间吗?
  • 要求正确算法的问题不适用于 SO,请尝试 codegolf.stackexchange.com。也就是说,您可以迭代数组,直到找到第一个正整数并将结果初始化为该数字;然后当你发现一个小于当前结果的数字时迭代其余的修改结果。
  • 这个问题似乎跑题了,因为它要求的是“最佳算法”
  • 收盘范围太广是怎么回事?该问题包含一个准确而正式的问题陈述:如何在 O(n) 中做一件特定的事情。一般来说,当代码次于算法时,我有时会看到算法问题被关闭,但不明白为什么:它仍然是一个编程问题,algorithm 标签有 85.5k 个问题,tour 建议“软件算法”已开启-topic 作为四个复选标记中的第二个。如果这里不欢迎此类问题,请告诉我原因。

标签: algorithm


【解决方案1】:

根据鸽巢原理,至少有一个数字 1, 2, ..., n+1 不在数组中。 让我们创建一个大小为 n+1 的布尔数组 b 来存储这些数字是否存在。

现在,我们处理输入数组。如果我们找到一个从 1 到 n+1 的数字,我们在b 中标记相应的条目。如果我们看到的数字不符合这些范围,只需将其丢弃并继续下一个。两种情况都是每个输入条目 O(1),总共 O(n)。

在处理完输入后,我们可以在 O(n) 中轻松找到布尔数组 b 中的第一个未标记条目。

【讨论】:

  • @sammy333:这个概念不会使解决方案无效:输入数字可以是任何有符号的int32s,但我们只对12、..的出现感兴趣., n + 1 其中之一,因为其中之一肯定是答案。
  • N 是 [1..100,000] 范围内的整数;数组 A 的每个元素都是 [−2,147,483,648..2,147,483,647] 范围内的整数。仅当数组中的最大元素为 100,000 时,您的解决方案才有效。
  • @Cristian 但是 answer 总是从 1 到 100,001,这就是我们使用的事实。请再读一遍。
  • 如何检查数组 A 中的数字是否存在?使用contains 会导致性能不佳...
  • 这个数组怎么样:[1, 299999] N = 2。那么,我应该创建一个大小为 3 的布尔数组吗?如何从这个布尔数组返回正确的结果2
【解决方案2】:

100% 使用 Java 的简单解决方案。

请注意,它是 O(nlogn) 解决方案,但会给出 100% 的结果。

public static int solution(final int[] A) 
{   
   Arrays.sort(A);
   int min = 1;

   // Starting from 1 (min), compare all elements, if it does not match 
   // that would the missing number.
   for (int i : A) {
     if (i == min) {
       min++;
     }
   }

   return min;
}

【讨论】:

  • 比发布的其他解决方案更简单、性能更高。非常好!
  • 非常简单,对我理解问题很有帮助
  • 由于排序,这是 O(n log n) 而不是 O(n)。
  • 我知道这是 o(nlogn) 解决方案,但它给出了 100% 的结果。
  • 这是一个聪明的。对于一个小的改进,我们可以在if (i == min)之后添加另一个分支-如果i > min,我们可以立即返回min
【解决方案3】:

今天写了这篇文章,得到了 100/100。不是最优雅的解决方案,但易于理解 -

public int solution(int[] A) {
    int max = A.length;
    int threshold = 1;
    boolean[] bitmap = new boolean[max + 1];

    //populate bitmap and also find highest positive int in input list.
    for (int i = 0; i < A.length; i++) {
        if (A[i] > 0 && A[i] <= max) {
            bitmap[A[i]] = true;
        }

        if (A[i] > threshold) {
            threshold = A[i];
        }
    }

    //find the first positive number in bitmap that is false.
    for (int i = 1; i < bitmap.length; i++) {
        if (!bitmap[i]) {
            return i;
        }
    }

    //this is to handle the case when input array is not missing any element.
    return (threshold+1);
}

【讨论】:

  • 有人否决所有解决方案?在我的例子中,cmets 包含在代码中。
【解决方案4】:

简单的 Java 解决方案。在正确性和性能方面得分 100/100。

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

}

【讨论】:

    【解决方案5】:

    构建所有值的哈希表。对于数字 1 到 n + 1,检查它们是否在哈希表中。至少其中一个不是。打印出最小的数字。

    这是 O(n) 的预期时间(你可以得到with high probability)。请参阅@Gassa 的答案,了解如何避免使用哈希表来支持大小为 O(n) 的查找表。

    【讨论】:

    • 无需散列:因为我们知道答案在前 n+1 个正整数中,我们可以只考虑它们并丢弃其他所有内容。详情见我的回答。
    • @Gassa 有趣的是,我的大脑没能做出这么简单的进展
    【解决方案6】:
    public int solutionMissingInteger(int[] A) {
        int solution = 1;
        HashSet<Integer> hashSet = new HashSet<>();
    
        for(int i=0; i<A.length; ++i){
            if(A[i]<1) continue;
            if(hashSet.add(A[i])){
                //this int was not handled before
                while(hashSet.contains(solution)){
                    solution++;
                }
            }
        }
    
        return solution;
    }
    

    【讨论】:

    • 谢谢玛丽安,这个答案在 Swift 3 中也给了我 100%。
    【解决方案7】:

    100% Javascript

    function solution(A) {
            // write your code in JavaScript (Node.js 4.0.0)
            var max = 0;
            var array = [];
            for (var i = 0; i < A.length; i++) {
                if (A[i] > 0) {
                    if (A[i] > max) {
                        max = A[i];
                    }
                    array[A[i]] = 0;
                }
            }
            var min = max;
            if (max < 1) {
                return 1;
            }
            for (var j = 1; j < max; j++) {
                if (typeof array[j] === 'undefined') {
                    return j
                }
            }
            if (min === max) {
                return max + 1;
            }
        }
    

    【讨论】:

    • 您可以删除最小相关行。将 max 分配给 min 后,max 变量没有变化。
    【解决方案8】:

    JavaScript 100%

    function solution(A) {
      let sortedOb = {};
      let biggest = 0;
    
      A.forEach(el => {
        if (el > 0) {
          sortedOb[el] = 0;
          biggest = el > biggest ? el : biggest;
        }
      });
      let arr = Object.keys(sortedOb).map(el => +el);
      if (arr.length == 0) return 1;
    
      for(let i = 1; i <= biggest; i++) {
        if (sortedOb[i] === undefined) return i;
      }
      return biggest + 1;
    }
    

    【讨论】:

      【解决方案9】:

      C# 得分 100%,

      说明:使用查找表存储输入数组中已经看到的值,我们只关心输入数组中大于 0 且小于或等于长度的值

          public static int solution(int[] A)
          {
              var lookUpArray = new bool[A.Length];
      
              for (int i = 0; i < A.Length; i++)
                  if (A[i] > 0 && A[i] <= A.Length)
                      lookUpArray[A[i] - 1] = true;
      
              for (int i = 0; i < lookUpArray.Length; i++)
                  if (!lookUpArray[i])
                      return i + 1;
      
              return A.Length + 1;
          }
      

      【讨论】:

      • 这个数组能用吗? [1, 233444]
      【解决方案10】:

      这是我的解决方案是 Swift 4

      public func solution(_ A: inout [Int]) -> Int {
      
          var minNum = 1
          var hashSet = Set<Int>()
      
          for int in A {
              if int > 0 {
                  hashSet.insert(int)
              }
          }
      
          while hashSet.contains(minNum) {
              minNum += 1
          }
      
          return minNum
      
      }
      
      var array = [1,3,6]
      
      solution(&array)
      

      // 答案:2

      【讨论】:

      • 您能否提供更多信息,说明为什么这会回答 OP 的原始问题?
      【解决方案11】:

      100%:Python 排序例程不被视为作弊...

      def solution(A):
          """
          Sort the array then loop till the value is higher than expected
          """
          missing = 1
          for elem in sorted(A):
              if elem == missing:
                  missing += 1
              if elem > missing:
                  break
          return missing
      

      【讨论】:

      • 本身不像作弊。请争论这是怎么回事O(n)
      • 实际上不是 O(n+n) 吗?第一个进行排序,然后第二次传递排序结果。我的评论只是观察到 Codility 不会因为使用排序例程来解决这个问题而受到惩罚。
      • 排序是 O(n) 吗?不适用于基于比较的排序:Ω(nlogn)。
      • 摘要 here 可能还有 here 如果你真的想知道 python2 的排序是如何实现的。
      • 谢谢,但不是重点:请争论如何使用 python 排序 O(n)
      【解决方案12】:

      它对我有用。不是 O(n),而是简单一点:

      import java.util.stream.*;
      class Solution {
          public int solution(int[] A) {
              A = IntStream.of(A)
                  .filter(x->x>0)
                  .distinct()
                  .sorted()
                  .toArray();
      
              int min = 1;
              for(int val : A)
              {
                  if(val==min)
                      min++;
                  else
                      return min;
              }
              return min;
          }
      }
      

      【讨论】:

      • 这不是“预计最坏情况时间复杂度为 O(N)”
      【解决方案13】:

      我的解决方案。 100%。在 Java 中。

      import java.util.ArrayList;
      import java.util.Arrays;
      import java.util.List;
      
      public class Solution {
          public int solution(int[] A) {
              Arrays.sort(A);
              ArrayList<Integer> positive = new ArrayList<>();
              for (int i = 0; i < A.length; i++) {
                  if(A[i] > 0)
                      positive.add(A[i]);
              }
              if(positive.isEmpty()) return 1;
              if(positive.get(0) > 1) return 1;
      
              for(int i = 0; i < positive.size() - 1; i++) {
                  if(positive.get(i + 1) - positive.get(i) > 1)
                      return positive.get(i) + 1;
              }
      
              return positive.get(positive.size() - 1) + 1;
          }
          public static void main(String[] args) {
              Solution solution = new Solution();
              int[] A = {-5,1,2,3,4,6,7,8,9,5};
              System.out.println(solution.solution(A)); 
          }
      }
      

      【讨论】:

      • 我将您的解决方案提交给 coditily,他们评估为 100% 正确,恭喜!
      【解决方案14】:

      javascript 100% 100% 首先对数组进行排序,您只需要扫描正元素,找到 1 的索引(如果数组中没有 1,则答案为 1)。然后搜索 1 之后的元素,直到找到缺失的数字。

      function solution(A) {
      // write your code in JavaScript (Node.js 6.4.0)
      
         var missing = 1;
         // sort the array.
         A.sort(function(a, b) { return a-b });
      
         // try to find the 1 in sorted array if there is no 1 so answer is 1
         if ( A.indexOf(1) == -1) { return 1; }
      
         // just search positive numbers to find missing number 
         for ( var i = A.indexOf(1); i < A.length; i++) {
            if ( A[i] != missing) {
              missing++;
              if ( A[i] != missing ) { return missing; }
            }
         }
      
         // if cant find any missing number return next integer number
         return missing + 1;
      }
      

      【讨论】:

      【解决方案15】:

      我相信解决方案比使用 n (100,000) 个元素的布尔数组“标记”相应的值更复杂。大小为 n 的布尔数组不会“直接”映射到可能的值范围(-2,147,483,648 到 2,147,483,647)。 我编写的这个 Java 示例尝试通过根据它们与最大值的偏移量映射值来映射 100K 行。它还执行取模以将结果数组减小到与样本元素长度相同的大小。

      /** 
       * 
       * This algorithm calculates the values from the min value and mods this offset with the size of the 100K sample size. 
       * This routine performs 3 scans. 
       * 1. Find the min/max
       * 2. Record the offsets for the positive integers
       * 3. Scan the offsets to find missing value.
       * 
       * @author Paul Goddard
       *
       */
      public class SmallestPositiveIntMissing {
          static int ARRAY_SIZE = 100000;
          public static int solve(int[] array) {
              int answer = -1;
              Maxmin maxmin = getMaxmin(array);
              int range = maxmin.max - maxmin.min;
              System.out.println("min:   " + maxmin.min);
              System.out.println("max:   " + maxmin.max);
              System.out.println("range: " + range);
              Integer[] values = new Integer[ARRAY_SIZE];
              if (range == ARRAY_SIZE) {
                  System.out.println("No gaps");
                  return maxmin.max + 1;
              }
              for (int val: array) {
                  if (val > 0) {
                      int offset = val - maxmin.min;
                      int index = offset % ARRAY_SIZE;
                      values[index] = val;
                  } 
              }
              for (int i = 0; i < ARRAY_SIZE; i++) {
                  if (values[i] == null) {
                      int missing = maxmin.min + i;
                      System.out.println("Missing: " + missing);
                      answer = missing;
                      break;
                  }
              }
              return answer;
          }
      
          public static Maxmin getMaxmin(int[] array) {
              int max = Integer.MIN_VALUE;
              int min = Integer.MAX_VALUE;
              for (int val:array) {
                  if (val >=0) {
                      if (val > max) max = val;
                      if (val < min) min = val;
                  }
              }
              return new Maxmin(max,min);
          }
      
          public static void main(String[] args) {
              int[] A = arrayBuilder();
              System.out.println("Min not in array: " + solve(A));
          }
      
          public static int[] arrayBuilder() {
      
              int[] array = new int[ARRAY_SIZE];
              Random random = new Random();
      
              System.out.println("array: ");
              for (int i=0;i < ARRAY_SIZE; i++) {
                  array[i] = random.nextInt();
                  System.out.print(array[i] + ", ");
              }
              System.out.println(" array done.");
      
              return array;
          }
      
      }
      class Maxmin {
          int max;
          int min;
          Maxmin(int max, int min) {
              this.max = max;
              this.min = min;
          }
      }
      

      【讨论】:

        【解决方案16】:

        Sweet Swift 版本。 100% 正确

        public func solution(inout A : [Int]) -> Int {
            //Create a Hash table
            var H = [Int:Bool]()
            // Create the minimum possible return value
            var high = 1
            //Iterate
            for i in 0..<A.count {
                // Get the highest element
                high = A[i] > high ? A[i] : high
                // Fill hash table
                if (A[i] > 0){
                    H[A[i]] = true
                }
            }
            // iterate through possible values on the hash table
            for j in 1...high {
                // If you could not find it on the hash, return it
                if H[j] != true {
                    return j
                } else {
                    // If you went through all values on the hash
                    // and can't find it, return the next higher value
                    // e.g.: [1,2,3,4] returns 5
                    if (j == high) {
                        return high + 1
                    }
                }
            }
            return high
        }
        

        【讨论】:

          【解决方案17】:
          int[] copy = new int[A.length];
                  for (int i : A)
                  {
                      if (i > 0 && i <= A.length)
                      {
                          copy[i - 1] = 1;
                      }
                  }
                  for (int i = 0; i < copy.length; i++)
                  {
                      if (copy[i] == 0)
                      {
                          return i + 1;
                      }
                  }
                  return A.length + 1;
          

          【讨论】:

            【解决方案18】:

            斯威夫特 3 - 100%

            public func solution(_ A : inout [Int]) -> Int {
            // write your code in Swift 3.0 (Linux)
            
            var solution = 1
            var hashSet = Set<Int>()
            
                for int in A
                {
                    if int > 0
                    {
                        hashSet.insert(int)
            
                        while hashSet.contains(solution)
                        {
                            solution += 1
                        }
                    }
                }
            
                return solution
            }
            

            感谢上面玛丽安的回答。

            【讨论】:

            • 你们怎么能想出这么漂亮的答案?
            【解决方案19】:

            这是我使用 python 的解决方案:

            def solution(A):
                m = max(A)
            
                if m <= 0:
                    return 1
            
                if m == 1:
                    return 2
            
                # Build a sorted list with all elements in A
                s = sorted(list(set(A)))
            
                b = 0
            
                # Iterate over the unique list trying to find integers not existing in A
                for i in xrange(len(s)):
                    x = s[i]
            
                    # If the current element is lte 0, just skip it
                    if x <= 0:
                        continue;
            
                    b = b + 1
            
                    # If the current element is not equal to the current position,
                    # it means that the current position is missing from A
                    if x != b:
                        return b
            
                return m + 1
            

            得分 100%/100% https://codility.com/demo/results/demoDCU7CA-SBR/

            【讨论】:

            • 啊,Python的美感消失了。一个简单的两班轮也给 100%;丢弃负数并创建一个集合(无需显式排序)A = set([a if a&gt;0 else 0 for a in A]),然后只需使用 1...N 数组 diff = set(range(1, len(A)+2)).difference(A)return min(diff) 获取集合差异。
            • 怎么样:solution = lambda arr=[]: next(iter([i for i in range(1, len(arr) + 2) if i not in set(arr)])) or 1
            【解决方案20】:
            1. 创建一个长度为 N+1 的二进制数组 bin(C 使用基于 0 的索引)

            2. 遍历二进制数组O(n)

            3. 如果 A[i] 在 bin 范围内,则将索引 A[i] 处的 bin 条目标记为存在或真。
            4. 再次遍历二进制数组
            5. 任何不存在或为假的 bin 条目的索引是您缺失的整数

            ~

            #include<stdio.h>
            #include<stdlib.h>
            #include<stdbool.h>
            
            int solution(int A[], int N) {
                // write your code in C99 (gcc 6.2.0)
                int i;
                bool *bin = (bool *)calloc((N+1),sizeof(bool));
            
                for (i = 0; i < N; i++)
                {
                    if (A[i] > 0 && A[i] < N+1)
                    {
                        bin[A[i]] = true;
                    }
                }
            
                for (i = 1; i < N+1; i++)
                {
                    if (bin[i] == false)
                    {
                        break;
                    }
                }
            
                return i;
            }
            

            【讨论】:

            • 即使您的帖子也回答了 OP 的问题。请不仅提供有效的 sn-p。但请解释发生了什么,为什么它会做它应该做的等等。
            • 这个解是 O(n^2)
            • 请解释一下如何?这实际上是 O(n)。
            【解决方案21】:

            可能会有所帮助,我正在使用算术级数来计算总和,并使用二进制搜索来获取元素。用几百个值的数组检查效果很好。由于在第 2 步中有一个 for 循环和迭代,所以 O(n/2) 或更少

            def Missingelement (A):
                B = [x for x in range(1,max(A)+1,1)]
                n1 = len(B) - 1
                begin = 0
                end = (n1)//2
                result = 0
                print(A)
                print(B)
                if (len(A) < len(B)):
                    for i in range(2,n1,2):
                        if BinSum(A,begin,end) > BinSum(B,begin,end) :
                           end = (end + begin)//2
                           if (end - begin) <= 1 :
                            result=B[begin + 1 ]    
                        elif BinSum(A,begin,end) == BinSum(B,begin,end):
                            r = end - begin
                            begin = end 
                            end = (end + r)
            
                        if begin == end :
                            result=B[begin + 1 ]    
                return result         
            
            
            def BinSum(C,begin,end):
                n = (end - begin)
            
                if end >= len(C): 
                    end = len(C) - 1
                sum =  n*((C[begin]+C[end])/2)
                return sum                
            
            
            def main():
                A=[1,2,3,5,6,7,9,10,11,12,14,15]
                print ("smallest number missing is ",Missingelement(A))
            if __name__ == '__main__': main()
            

            【讨论】:

              【解决方案22】:

              C 代码,实际上,这可以用于任何编程语言,而无需更改任何逻辑。

              逻辑是N 的总和是N*(N+1)/2

              int solution(int A[], int N) {
              
                  // write your code in C99
                  long long sum=0;
                  long long i;
                  long long Nsum=0;
              
                  for(i=0;i<N;i++){
                      sum=sum + (long long)A[i];
                  }
              
                  if (N%2==0){
                      Nsum= (N+1)*((N+2)/2);
                      return (int)(Nsum-sum);
                  }
                  else{
                      Nsum= ((N+1)/2)*(N+2);
                      return (int)(Nsum-sum);
                  }    
              
              }
              

              这给出了 100/100 的分数。

              【讨论】:

              • 此技术仅适用于数组中仅缺少 1 个数字的情况。这不是这里的情况。
              【解决方案23】:

              此解决方案在测试中获得 100/100:

              class Solution {
                  public int solution(int[] A) {
              
                      int x = 0;
                      while (x < A.length) {
                          // Keep swapping the values into the matching array positions.
                          if (A[x] > 0 && A[x] <= A.length && A[A[x]-1] != A[x])  {
                              swap(A, x, A[x] - 1);
                          } else {
                              x++; // Just need to increment when current element and position match.
                          }
                      }
              
                      for (int y=0; y < A.length; y++) {
                          // Find first element that doesn't match position.
                          // Array is 0 based while numbers are 1 based.
                          if (A[y] != y + 1)  {
                              return y + 1;
                          }
                      }
              
                      return A.length + 1;
                  }
              
                  private void swap (int[] a, int i, int j) {
                      int t = a[i];
                      a[i] = a[j];
                      a[j] = t;
                  }
              }
              

              【讨论】:

                【解决方案24】:

                100% 在 PHP https://codility.com/demo/results/trainingKFXWKW-56V/

                function solution($A){
                    $A = array_unique($A);
                    sort($A);
                    if (empty($A)) return 1;
                    if (max($A) <= 0) return 1;
                    if (max($A) == 1) return 2;
                    if (in_array(1, $A)) {
                    $A = array_slice($A, array_search(1, $A)); // from 0 to the end
                    array_unshift($A, 0); // Explanation 6a
                    if ( max($A) == array_search(max($A), $A)) return max($A) + 1; // Explanation 6b
                        for ($i = 1; $i <= count($A); $i++){
                                if ($A[$i] != $i) return $i; // Explanation 6c
                        }
                    } else {
                        return 1;
                    }
                }
                

                // 解释

                1. 删除所有重复项
                2. 从最小值到最大值排序
                3. 如果数组为空返回1
                4. 如果数组的最大值为零或更小,则返回 1
                5. 如果数组的最大值为 1,则返回 2 //下一个正整数
                6. 所有其他情况: 6a) 将数组从值 1 拆分到末尾,并在第一个数字前添加 0 6b) 如果数组的最后一个元素的值是数组的最大值,那么数组是升序的,所以我们返回 max + 1 // 下一个正整数 6c) 如果数组不是升序的,我们通过一个函数找到一个缺失的数字: 如果元素的键不是元素的值,但它应该是 (A = [0=>0, 1=>1,2=> 3,...]),我们返回键,因为我们希望键和值相等。

                【讨论】:

                • 请正确格式化您的代码,并添加一些有关此代码应如何回答初始问题的信息。
                【解决方案25】:

                这是我的解决方案,它在评估中的收益率为 88%——时间为 O(n),正确性 100%,性能 75%。记住 - 可以有一个包含所有负数或超过 100,000 的数字的数组。上述大多数解决方案(使用实际代码)产生的分数要低得多,或者根本不起作用。其他的似乎与 Codility 上提出的缺失整数问题无关。

                int compare( const void * arg1, const void * arg2 )
                {
                    return *((int*)arg1) - *((int*)arg2);
                }
                
                solution( int A[], int N )
                {
                    // Make a copy of the original array
                    // So as not to disrupt it's contents.
                    int * A2 = (int*)malloc( sizeof(int) * N );
                    memcpy( A2, A1, sizeof(int) * N );
                
                    // Quick sort it.
                    qsort( &A2[0], N, sizeof(int), compare );
                
                    // Start out with a minimum of 1 (lowest positive number)
                    int min = 1;
                    int i = 0;
                
                    // Skip past any negative or 0 numbers.
                    while( (A2[i] < 0) && (i < N )
                    {
                        i++;
                    }
                
                    // A variable to tell if we found the current minimum
                    int found;
                    while( i < N )
                    {
                        // We have not yet found the current minimum
                        found = 0;
                        while( (A2[i] == min) && (i < N) )
                        {
                            // We have found the current minimum
                            found = 1;
                            // move past all in the array that are that minimum
                            i++;
                        }
                        // If we are at the end of the array
                        if( i == N )
                        {
                            // Increment min once more and get out.
                            min++;
                            break;
                        }
                        // If we found the current minimum in the array
                        if( found == 1 )
                        {
                            // progress to the next minimum
                            min++;
                        }
                        else
                        {
                            // We did not find the current minimum - it is missing
                            // Get out - the current minimum is the missing one
                            break;
                        }
                    }
                
                    // Always free memory.
                    free( A2 );
                    return min;
                }
                

                【讨论】:

                  【解决方案26】:

                  我的 100/100 解决方案

                    public int solution(int[] A) {
                          Arrays.sort(A);
                          for (int i = 1; i < 1_000_000; i++) {
                              if (Arrays.binarySearch(A, i) < 0){
                                  return i;
                              }
                          }
                          return -1;
                      }
                  

                  【讨论】:

                    【解决方案27】:
                        static int spn(int[] array)
                        {
                            int returnValue = 1;
                            int currentCandidate = 2147483647;
                    
                            foreach (int item in array)
                            {
                                if (item > 0)
                                {
                                    if (item < currentCandidate)
                                    {
                                        currentCandidate = item;
                                    }
                                    if (item <= returnValue)
                                    {
                                        returnValue++;
                                    } 
                                }
                            }
                    
                            return returnValue;
                        }
                    

                    【讨论】:

                    • 试着解释一下,至少有点你的答案。此外,就最坏情况的复杂性而言,您的解决方案肯定不是最优的。
                    猜你喜欢
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 2023-04-04
                    • 1970-01-01
                    • 2022-07-17
                    • 1970-01-01
                    • 1970-01-01
                    相关资源
                    最近更新 更多