Codility每周一课:L4 Counting Elements(P4.3)

4734220-cc5fff3d0deb569e.png
0.png

P4.3 MissingInteger
Find the smallest positive integer that does not occur in a given sequence.

  • P4.3 缺失的整数
    寻找在给定的数组中未出现的最小的正整数

编写函数:

def solution(A)

A是由N个整数组成的数组,返回A中未出现的最小的正整数。

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

假定:

  1. N是区间[1,100000]内的整数;
  2. 数组A的每个元素都是区间[-1000000,1000000]内的整数;
  • 解题思路

对于需要遍历,或者查询等问题,最好的解决办法就是转化为字典;

  • Python3代码
# -*- coding:utf-8 -*-
# &Author  AnFany
# Lesson 4:Counting Elements
# P 4.3 MissingInteger


def solution(A):
    """
    返回数组A中未出现的最小的正整数
    :param A: 数组
    :return: 未出现的最小的正整数
    """
    x_dict = {i: 0 for i in A}
    length = len(x_dict)
    for i in range(1, len(x_dict) + 1):
        if i not in x_dict:
            return i
    return length + 1
  • 结果
4734220-bf7da1f834323261
image

点击获得更多编程练习题。欢迎Follow,感谢Star!!! 扫描关注微信公众号pythonfan,获取更多。

4734220-3a38d3c2af6073bb
image
4734220-28f0bd9ed8f73937
image

猜你喜欢

转载自blog.csdn.net/weixin_33796177/article/details/86815319