LeetCode之N-Repeated Element in Size 2N Array(Kotlin)

问题: 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.git

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
复制代码

方法: 由于有一半的元素都是相同元素,若是但愿该元素不相邻,则最极端状况也只能是一个间隔一个,因此必存在一组三元素中存在两个相同元素,根据这一规则遍历全部元素则能够获得该相同元素,算法时间复杂度为O(n),空间复杂度为O(1),还有一种经过Map判断重复元素的算法,时间复杂度为O(n),空间复杂度为O(n)。github

具体实现:算法

class NRepeatedElementInSize2NArray {
    fun repeatedNTimes(A: IntArray): Int {
        for(index in 0..A.lastIndex - 2) {
            if (A[index] == A[index + 1] || A[index] == A[index + 2]) {
                return A[index]
            }
        }
        return A[A.lastIndex]
    }
}

fun main(args: Array<String>) {
    val input = intArrayOf(2, 1, 2, 5, 3, 2)
    val nRepeatedElementInSize2NArray = NRepeatedElementInSize2NArray()
    println(nRepeatedElementInSize2NArray.repeatedNTimes(input))
}
复制代码

有问题随时沟通bash

具体代码实现能够参考Githubui

相关文章
相关标签/搜索