問題: Given two lists Aand B, and B is an anagram of A. B is an anagram of A means B is made by randomizing the order of the elements in A. We want to find an index mapping P, from A to B. A mapping P[i] = j means the ith element in A appears in B at index j. These lists A and B may contain duplicates. If there are multiple answers, output any of them.git
方法: 外層遍歷A中元素,內層遍歷B中元素,當A[i]與B[j]相等時輸出j並退出內層循環,A所有遍歷後全部輸出即爲結果,時間複雜度爲O(n*n),空間複雜度爲O(1)。另一種方法是將B中元素添加到map結構中,遍歷A中元素經過map獲取在B中的index,時間複雜度爲O(n),空間複雜度爲O(n)。github
具體實現:bash
class FindAnagramMappings {
fun anagramMappings(A: IntArray, B: IntArray): IntArray {
val result = arrayListOf<Int>()
for (i in A.indices) {
for (j in B.indices) {
if (A[i] == B[j]) {
result.add(j)
break
}
}
}
return result.toIntArray()
}
}
fun main(args: Array<String>) {
val A = intArrayOf(12, 28, 46, 32, 50)
val B = intArrayOf(50, 12, 32, 46, 28)
val findAnagramMappings = FindAnagramMappings()
val result = findAnagramMappings.anagramMappings(A, B)
for (e in result) {
print("$e ,")
}
}
複製代碼
有問題隨時溝通app