前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >3。leetcode在2N的数组中找出

3。leetcode在2N的数组中找出

作者头像
py3study
发布2020-01-02 17:02:02
6760
发布2020-01-02 17:02:02
举报
文章被收录于专栏:python3python3

1.题目: In a array A of size 2N, there are N+1 unique elements, and exactly one of these elements is repeated N times.

Return the element repeated N times. 例一:

代码语言:javascript
复制
Input: [1,2,3,3]
Output: 3

例二:

代码语言:javascript
复制
Input: [2,1,2,5,3,2]
Output: 2

注意:

代码语言:javascript
复制
4 <= A.length <= 10000
0 <= A[i] < 10000
A.length is even
  1. 我的解法:
代码语言:javascript
复制
class Solution:
    def repeatedNTimes(self, A: List[int]) -> int:
        n = len(A)
        for i in range(0, n):
            if A[i] in (A[i+1:]):
                return A[i]

Runtime: 48 ms, faster than 88.03% of Python3 online submissions for N-Repeated Element in Size 2N Array. Memory Usage: 14.3 MB, less than 5.12% of Python3 online submissions for N-Repeated Element in Size 2N Array.

  1. 优秀解法:
代码语言:javascript
复制
 def repeatedNTimes(self, A):
        """
        :type A: List[int]
        :rtype: int
        """
        return int((sum(A)-sum(set(A))) // (len(A)//2-1))

有重复的和减去没有重复的和 再除以长度除以2再减1就是重复的项。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-10-14 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档