码迷,mamicode.com
首页 > 其他好文 > 详细

Set Mismatch

时间:2017-09-09 16:27:02      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:elf   logs   error:   object   ret   col   代码   match   ges   

    这道题是简单题

  题目:

    技术分享

 

  思路:

     1、我的思路:for循环1到n的自然数,nums列表删除i,如果捕获到异常,就在后面nums后面添加i,最后返回nums。但是这样做复杂度太高,程序运行会超时,所以需要改进

    2、另外加入一个列表b,循环nums列表对应b[i] + 1,最后遍历b列表,返回b[i]等于2和0的i值

  代码:

    1、超时代码:

 1 class Solution(object):
 2     def findErrorNums(self, nums):
 3         """
 4         :type nums: List[int]
 5         :rtype: List[int]
 6         """
 7         
 8         for i in range(1,len(nums)+1):
 9             try:
10                 nums.remove(i)
11  
12             except ValueError:
13                 nums.append(i)
14         return nums

 

    2、通过代码:

  

 1 class Solution(object):
 2     def findErrorNums(self, nums):
 3         """
 4         :type nums: List[int]
 5         :rtype: List[int]
 6         """
 7         
 8         a = len(nums)
 9         b = [0] * (a+1)
10         for i in nums:
11             b[i] += 1
12         for i in range(1, a+1):
13             if b[i] == 2: c = i
14             if b[i] == 0: d = i
15         return c, d

 

Set Mismatch

标签:elf   logs   error:   object   ret   col   代码   match   ges   

原文地址:http://www.cnblogs.com/liuxinzhi/p/7498393.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!