LeetCode 961. N-Repeated Element in Size 2N Array

灰太狼 2021-03-28 12:39 503阅读 0赞

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 1:

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

Example 2:

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

Example 3:

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

Note:

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

题目描述:求一个长度为 2N 数组中重复 N 次的元素值

题目分析:很简单,把每一个出现过的不同元素进行统计,重复次数大于等于 2 的元素即为我们所求。

python 代码:

  1. class Solution(object): def repeatedNTimes(self, A): """ :type A: List[int] :rtype: int """ A_length = len(A) for i in range(A_length): if A.count(A[i]) >= 2: return A[i] else: continue

C++ 代码:

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

发表评论

表情:
评论列表 (有 0 条评论,503人围观)

还没有评论,来说两句吧...

相关阅读