961. repeated N times element

Links: https://leetcode-cn.com/problems/n-repeated-element-in-size-2n-array/solution/zhong-fu-n-ci-de-yuan-su-by-leetcode/

There are N + 1 different elements in an array A of size 2N, the element which has a repeated N times.

Return repeated N times of that element.

 

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
 

prompt:

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

1. The array is divided into 2, take the left part of the last element is compared with the previous element, if equal, the element is the answer, not equal, the right part is necessarily the answer, the right part of the same token, there is a possible answer is located just in the middle range of the array, the first two methods have included.

class Solution {
public:
    int repeatedNTimes(vector<int>& A) {
        sort(A.begin(), A.end());
        int n = A.size() / 2;
        if(A[n] == A[n + 1]) return A[n];
        else return A[n - 1];
    }
};

2. Because the total of n + 1 elements, a total of 2 * n elements, of which a number of elements n, i.e., the remaining number of elements 1 are determined to traverse.

class Solution {
public:
    int repeatedNTimes(vector<int>& A) {
       bool a[10010] = {false};
       int i;
       for(i = 0; i < A.size(); i++)
       {
           if(a[A[i]] == false) a[A[i]] = true;
           else break;
       }
       return A[i];
    }
};

 

Published 58 original articles · won praise 6 · views 7069

Guess you like

Origin blog.csdn.net/weixin_43569916/article/details/103883599