Leetcode百题整理:Find Anagram Mappings & Hamming Distance

Find Anagram Mappings

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.

一刷:Python

python list内置了index函数,可以直接返回所包含元素的坐标,因此提交如下代码:

class Solution(object):
    def anagramMappings(self, A, B):
        """
        :type A: List[int]
        :type B: List[int]
        :rtype: List[int]
        """
        
        ans = []
        
        for item in A:
            ans.append(B.index(item))
            
        return ans

此方法可简写为一行代码如下:

return [B.index(a) for a in A]

提交后通过.

查阅discussion,有人已然给出此方法的复杂度分析为o(N^2), 不是最优,在discussion中找到如下几种方法:

方法一:作者lee215

先将listA遍历一遍,建立一个字典记录每个元素以及index的数值:

def anagramMappings(self, A, B):
        d = {b:i for i,b in enumerate(B)}
        return [d[a] for a in A]

方法二:作者weidairpi
使用defaultdict:

from collections import defaultdict
class Solution(object):
    def anagramMappings(self, A, B):
        """
        :type A: List[int]
        :type B: List[int]
        :rtype: List[int]
        """
        pool=defaultdict(list)
        for i,b in enumerate(B): pool[b].append(i)
        return [pool[a].pop() for a in A]

Hamming Distance

考察二进制

一刷:C++(后补)

二刷:python

python将数字转化为二进制的方法有:

format(int,'b')
bin(int)

转化为二进制后取异或运算,记录字符中‘1’的个数

class Solution(object):
    def hammingDistance(self, x, y):
        """
        :type x: int
        :type y: int
        :rtype: int
        """
        
        return format(x^y,'b').count('1')

你可能感兴趣的:(Leetcode百题整理:Find Anagram Mappings & Hamming Distance)