重复 N 次的元素

题目描述:

在大小为 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

提示:

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

这是我的解决代码C++

#include <iostream>
#include <map>
#include <vector>
#include <set>
#include <array>
using namespace std;

class Solution
{
public:
    int repeatedNTimes(vector<int>& A)
    {
        int Asize = A.size()/2;
        map<int,int> map1;
        vector<int>::iterator iter = A.begin();
        for(iter; iter!=A.end(); iter++)
        {
            int key = (*iter);
            map<int,int>::iterator iter2;
            iter2 = map1.find(key);
            if(iter2!=map1.end())
            {
                int second = iter2->second;
                if( (second+1) == Asize)
                {
                    return key;

                }
                else
                {
                    map1[key]=second+1;
                }
            }
            else
            {
                map1[key]=1;
            }

        }
        return 0;
    }

};

还有更吊的,

public static int repeatedNTimes(int[] A) {
        Arrays.sort(A);
        return A[A.length/2]==A[A.length-1]?A[A.length/2]:A[A.length/2-1];
    }

想了一下,这他妈才是算法啊。

猜你喜欢

转载自blog.csdn.net/yangmingsen1999/article/details/85399817