問題: 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))
}
複製程式碼
有問題隨時溝通