博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode268. Missing Number
阅读量:2241 次
发布时间:2019-05-09

本文共 621 字,大约阅读时间需要 2 分钟。

Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.

Example 1:

Input: [3,0,1]Output: 2

Example 2:

Input: [9,6,4,2,3,5,7,0,1]Output: 8

Note:

Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?


思路: 既然列表中的数字是从0开始,一直数到列表的长度为止,中间只缺了一个数,那么用和去减列表的和就可以了.(这道题有bug,输入不符合规范也能算出来答案)想起小时候第一节奥数课背的求和公式:首项加末项乘以项数除以二=.=

class Solution(object):    def missingNumber(self, nums):        """        :type nums: List[int]        :rtype: int        """        return (1+len(nums))*(len(nums))//2-sum(nums)

 

转载地址:http://msrbb.baihongyu.com/

你可能感兴趣的文章
Java实现简单的递归操作
查看>>
Struts2工作原理和执行流程图
查看>>
在线预览Word,Excel~
查看>>
hibernate延迟加载(get和load的区别)
查看>>
关于文件拷贝效率问题
查看>>
MyBatis分页插件PageHelper的使用
查看>>
【MyBatis学习01】宏观上把握MyBatis框架
查看>>
【MyBatis学习02】走进MyBatis的世界
查看>>
【MyBatis学习03】原始dao开发方法及其弊端
查看>>
【MyBatis学习04】mapper代理方法开发dao
查看>>
【MyBatis学习05】SqlMapConfig.xml文件中的配置总结
查看>>
【MyBatis学习06】输入映射和输出映射
查看>>
【MyBatis学习07】动态sql
查看>>
【MyBatis学习08】高级映射之一对一查询
查看>>
【MyBatis学习09】高级映射之一对多查询
查看>>
【MyBatis学习10】高级映射之多对多查询
查看>>
【MyBatis学习11】MyBatis中的延迟加载
查看>>
【MyBatis学习12】MyBatis中的一级缓存
查看>>
【MyBatis学习13】MyBatis中的二级缓存
查看>>
【MyBatis学习14】MyBatis和Spring整合
查看>>