zoukankan      html  css  js  c++  java
  • [LeetCode] 961. N-Repeated Element in Size 2N Array

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

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

    Analyse

    数组A一共2N个数,其中一个数出现了N次,整个数组A中共有N+1个不一样的数

    很容易用map写出一个版本,使用map计数,返回数量为N的那个数

    时间复杂度 (O(n)),n是A的size()

    空间复杂度 (O(n)),n是A的size()

    int repeatedNTimes(vector<int>& A) {
        map<int, int> _map;
        for(int val : A)
        {
            if (++_map[val] == (A.size()/2))
            {
                return val;
            }
        }
        return 0;
    }
    

    再进一步,要找到重复出现N次的那个数,由于其他数都是唯一的,只要找到重复出现2次的数就行了

    这个比之前的版本快那么一点点,本质上差异并不大

    时间复杂度 (O(n)),n是A的size()

    空间复杂度 (O(n)),n是A的size()

    int repeatedNTimes(vector<int>& A) {
        map<int, int> _map;
        for(int val : A)
        {
            if (++_map[val] == 2)
            {
                return val;
            }
        }
        return 0;
    }
    

    另一种办法是比较,从LeetCode上看到的

    If we ever find a repeated element, it must be the answer. Let's call this answer the major element.

    Consider all subarrays of length 4. There must be a major element in at least one such subarray.

    This is because either:

    • There is a major element in a length 2 subarray, or;
    • Every length 2 subarray has exactly 1 major element, which means that a length 4 subarray that begins at a major element will have 2 major elements.

    Thus, we only have to compare elements with their neighbors that are distance 1, 2, or 3 away.

    只要找到一个重复的值,这个值就是要找的

    至少有一个长度为4的子序列中存在重复的值

    LeetCode的讨论区回答说需要检查的子序列的长度可以减小到3

    时间复杂度 (O(n)),n是A的size()

    空间复杂度 (O(1))

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

    Reference

    1.https://leetcode.com/problems/n-repeated-element-in-size-2n-array/solution/

  • 相关阅读:
    Raspberry Pi(树莓派2代B型新手初体验)
    Webview内存泄漏解决办法
    学习日记(二)——自定义来电界面,监听来电广播,悬浮窗
    学习日记(一)----BaseActivity的写法
    学习记录---- viewpager里嵌套listview中adapter的写法
    listView的流畅性优化
    git 命令学习(二)
    git 命令学习(一)
    软件项目管理结课小结
    软件测试结课小结
  • 原文地址:https://www.cnblogs.com/arcsinw/p/10299378.html
Copyright © 2011-2022 走看看