LeetCode之Find Anagram Mappings(Kotlin)

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值