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')
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 今年7月-10月,中消协针对北京卫视、天津卫视等33家卫视的购物栏目及中视购物、央广购物等12家专业购物频道,开展...
    东方简书阅读 4,179评论 0 0
  • Alembic中容器的层级关系 上面说了,下面继续 层级是Alembic的核心概念,并反映在容器的结构上。为了此章...
    N景波阅读 5,020评论 0 1
  • 我做了一个梦,是那样令人向往的一个梦。 梦里我到了那个自己一直向往和渴望的地方。 那儿,所有的热情被燃起。 每一个...
    赵英俊的小英俊阅读 3,211评论 0 0
  • 一个月后,他卸下缠绕在眼部的厚厚纱布,从医院里走出来。他像获得新生的婴儿,再一次张开眼睛看见世界。绿色的树,红色的...
    作家明至阅读 1,891评论 0 1
  • 爱的艺术 瓦尔登湖 如何高效阅读一本书 复活
    行可2019阅读 1,130评论 0 0

友情链接更多精彩内容