Python刷题:哈希表(一)

1.Single Number

    Given an array of integers, every element appears twice except for one. Find that single one. You algorithm should have a liner runtime complexity. Could you implement it without using extra memory?

    给定一个整数数组,所有的元素仅出现一次或两次。找出那个只出现过一次的元素。你的算法应当具有线性时间复杂度。你能实现该算法而不使用额外的空间吗?

程序:

def singleNum(nums):
	res = 0
	for num in nums:
		res = res ^ num
	return res

print(str(singleNum([1,1,3,2,3])))

2.Happy Number

    Write an algorithm to determine if a number is “happy”. A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1( where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1are happy numbers.

    写出一个算法用于判定一个数是否是快乐数。快乐数是一个有如下定义的数:过程由一个正整数开始,用其各位数字的平方和取代该数字,并重复该过程,直到数字等于1(停止),或者它永远也无法变为零。那么,可以实现变为零的数字为快乐数。

示例:

数字19为快乐数,12+92=82,82+22=68,62+82=100,12+02+02=1

程序:

def happy(n):
	a = set()
	while n not in a:
		a.add(n)
		n = sum([int(x) ** 2 for x in str(n)])
	return (n == 1)
	
if happy(18):
	print('a')
else:
	print('b')

 

3.Count Primes

    Count the number of prime numbers less than a non-negative number, n.

    统计小于非负整数n的质数数目。

程序:

def countPrimes(n):
	if n < 3:
		return 0
	res = [True] * n
	res[0]=res[1]=False
	for i in range(2,int(math.sqrt(n))+1):
		res[i*i:n:i] = [False] * len(res[I*i:n:i])
	return sum(res) 

4.Isomorphic Strings

    Given two strings s and t, determine if they are isomorphic.

    Two strings are isomorphic if the characters in s can be replaced to get t.

    All occurrences of a character must be replaced with character while preserving the order of characters.

    No two characters may map to the same character but a character may map to itself.

    给定两个字符串s和t,判断它们是否同构。

    如果s中的字符可以在被取代后得到t,两个字符串是同构的。

    字符的所有出现都必须用字符代替,并且要保持字符的顺序。

    不存在两个字符映射在同一个字符上,但是一个字符可以被映射到其本身。

示例:

给定“egg”、“add”,返回true。

给定“foo”、“bar”,返回false。

给定“paper”、“title”,返回true。

程序:

def isomorphic(s,t):
	return len(set(zip(s,t))) == len(set(s)) == len(set(t))

5.Vaild Anagram

    Given two strings s and t, write a function to determine if t is an anagram of s.

    给定两个字符串s和t,写一个函数判定t是否是s的字母顺序颠倒字。

示例:

s=’anagram’, t=’nagaram’,返回true;

s=’rat’, t=’car’,返回false。

程序:

def isAnagram(s,t):
	dic1 = {}
	dic2 = {}
	for i in s:
		dic1[i] = dic1.get(i,0)+1
	for i in t:
		dic2[i] = dic2.get(i,0)+1
	return dic1 == dic2

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值