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), 不是最優(yōu),在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')