问题:
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:
4 <= A.length <= 10000
0 <= A[i] < 10000
A.length is even
方法:
因为有一半的元素都是相同元素,如果希望该元素不相邻,则最极端情况也只能是一个间隔一个,所以必存在一组三元素中存在两个相同元素,根据这一规则遍历所有元素则可以得到该相同元素,算法时间复杂度为O(n),空间复杂度为O(1),还有一种通过Map判断重复元素的算法,时间复杂度为O(n),空间复杂度为O(n)。
具体实现:
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))
}
有问题随时沟通