LeetCode #961 N-Repeated Element in Size 2N Array 重复 N 次的元素

961 N-Repeated Element in Size 2N Array 重复 N 次的元素

Description:
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.

Example:

Example 1:

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

Example 2:

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

Example 3:

Input: [5,1,5,2,5,3,5,4]
Output: 5

Note:

4 <= A.length <= 10000
0 <= A[i] < 10000
A.length is even

题目描述:
在大小为 2N 的数组 A 中有 N+1 个不同的元素,其中有一个元素重复了 N 次。

返回重复了 N 次的那个元素。

示例 :

示例 1:

输入:[1,2,3,3]
输出:3

示例 2:

输入:[2,1,2,5,3,2]
输出:2

示例 3:

输入:[5,1,5,2,5,3,5,4]
输出:5

提示:

4 <= A.length <= 10000
0 <= A[i] < 10000
A.length 为偶数

思路:

要么连续两个数中有重复值, 要么重复值间隔出现, 要么只有 4个元素的时候, 出现在数组的最后一个
时间复杂度O(n), 空间复杂度O(1)

代码:
C++:

class Solution 
{
public:
    int repeatedNTimes(vector<int>& A) 
    {
        for (int i = 0; i < A.size() - 2; i++) if (A[i] == A[i + 1] or A[i] == A[i + 2]) return A[i];
        return A[A.size() - 1];
    }
};

Java:

class Solution {
    public int repeatedNTimes(int[] A) {
        for (int i = 0; i < A.length - 2; i++) if (A[i] == A[i + 1] || A[i] == A[i + 2]) return A[i];
        return A[A.length - 1];
    }
}

Python:

class Solution:
    def repeatedNTimes(self, A: List[int]) -> int:
        return sorted(A)[len(A) // 2] if sorted(A)[0] != sorted(A)[1] else sorted(A)[0]
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容