LeetCode之Find Anagram Mappings(K

2019-01-01  本文已影响0人  糕冷羊

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


方法:
外层遍历A中元素,内层遍历B中元素,当A[i]与B[j]相等时输出j并退出内层循环,A全部遍历后所有输出即为结果,时间复杂度为O(n*n),空间复杂度为O(1)。另外一种方法是将B中元素添加到map结构中,遍历A中元素通过map获取在B中的index,时间复杂度为O(n),空间复杂度为O(n)。

具体实现:

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 ,")
    }
}

有问题随时沟通

具体代码实现可以参考Github

上一篇下一篇

猜你喜欢

热点阅读