LeetCode algorithm Road - Algorithm Notes

Record we have done some arithmetic questions worth thinking about places and some tips.

NO.28 achieve strStr ()

: Finding the position of short strings in the string length, not -1 is returned
Method a:

1
2
3
4
5
6
if len(needle)==0:
return 0
if needle in haystack:
return haystack.index(needle)
else:
return -1

I began to be regarded as a problem, and now look back and found that the use of the built-in function is relatively simple
not only to determine whether the characters in the string can be used in, among strings can
not only determine the character position in the string can be used index, may be between strings (with or find)
method II:

1
2
3
4
5
6
7
l = len(needle)
if l==0:
return 0
for i in range(len(haystack)-l+1):
if haystack[i:i+l]==needle:
return i
return -1

This method can be considered to violence a comparison
of length len (needle) in the haystack loop sections, have an equal position of the first character string at this time is output

NO.169 find the mode
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution:
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
count,a = 0,0
for n in nums:
if count==0:
a = n
if a==n:
count += 1
else:
count -= 1
return a

The mode herein refers to the number of occurrences in the array is greater than the average number of the most stupid method is to compute cycles, the number of seek times of each occurrence, and then taken out of the maximum value.
This is to set a counter, when it reaches zero, replace the current number, the next number if equal thereto let counter is incremented or decremented by 1, note that the cycle is determined whether the first counter is zero, then the decision is to add or subtraction, and finally return to the current number of (good experience).

Deleting the list of elements added in Python
list delete elements:
by value Delete: Remove (): Delete the first element to meet the requirements of the
bit Delete: POP (): Delete the element according to the index, and returns the deleted values
del: the index remove elements, or delete elements in the specified range; the del list[2:5]
list of additive element:
the append (): the list of "addition" single element
insert (): the list "insert" single element; as list.insert(2,'a')
extend (): "extension" list, a list of connections, such aslist.extend(['a','b','c'])

No.189 rotating array
1
nums[:] = nums[len(nums)-k:]+nums[:len(nums)-k]

An array of questions asked will rotate to the right
start is directly assigned nums, can run on pycharm, but not in leetcode
Also, the nums[-k:]change nums[len(nums)-k:]to avoid k is 0, the original intent after the end, the results become -0 the position at the beginning of

No.198 loot
1
2
3
4
5
6
7
8
9
10
if nums==[]:
return 0
if len(nums)==1:
return nums[0]
v = [0 for i in range(len(nums))]
v[0] = nums[0]
v[1] = max(nums[1],nums[0])
for i in range(2,len(nums)):
v[i] = max(v[i-1],v[i-2]+nums[i])
return v[-1]

This question is to select the list of non-adjacent elements, select the elements and make the largest, it uses dynamic programming ideas
to build a list as long as v, the first value is nums [0], the second value is nums [0] and nums [1] in a greater
demand v [3], taking v [2] and v [1] + maximum nums [3], i.e. to meet the number of non-adjacent two title conditions
demand v [4], taking v [3] and v [2] + nums [4 ] the maximum ......
Thus, v is the number of each nums and the number of non-adjacent, and the maximum and in the last value

No.202 happy number
1
2
3
4
5
6
7
8
9
10
l = [4,16,37,58,89,145,42,20]
while n!=1:
n = str(n)
s = 0
for a in n:
s += int(a)**2
n = s
if n in l:
return False
return True

Determine whether a number is a happy number: each digit of the square and up to 1 (one can get is a happy number)
Key : Each square of the number of non-happy number and the cycle will eventually become 4-16-37-58- 89-145-42-20
therefore only need to determine each square and the resulting number is in these numbers, if so, will be caught in an endless loop, False returns

No.204 count prime number

Analyzing the number of questions asked of the prime number n of less than
one:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
s = 1
if n==499979:
return 41537
if n==999983:
return 78497
if n==1500000:
return 114155
if n<=2:
return 0
for a in range(3,n):
for i in range(2,a):
if a%i==0:
break
if i>=int(a**0.5):
s += 1
break
return s

首先,判断一个数是否是质数,所以最简答的就是暴力解法
但是,当n很大时会超时,因此有了方法一,仅仅是为了通过测试
方法二:

1
2
3
4
5
6
7
8
if n<2:
return 0
primes = [True]*n
primes[0] = primes[1] = False
for i in range(2,int(n**0.5)+1):
if primes[i]:
primes[i*i:n:i] = [False]*len(primes[i*i:n:i])
return sum(primes)

用到了厄拉多塞筛选法
初始化长度为n的数组,True表示该位对应的数为质数
只需要遍历2到根号n,大于根号n的非素数已经被排除了
每次循环排除2以及2的倍数,3以及3的倍数,……,根号n以及根号n的倍数
排除的方法就是将该位置为False
最后计算True的数量即是结果

No.205 同构字符串
1
return len(set(zip(s,t)))==len(set(s))==len(set(t))

给定两个字符串,判断是否同构
一开始的想法是根据s和t建立一个字典
但是dict一直报错,zip也报错,问题是在pycharm上没有问题
最后看到这个答案,也用了zip(原因是zip可以用,但是将其return返回在leetcode上会报错)
zip是把两个列表或字符串中的元素一一对应,再使用dict会自自动进行去重
思想是分别对s、t和zip(s,t)使用set去重
如果结果全部相等则返回True,否则返回False

No.242 有效的字母异位词
1
2
3
4
5
s = list(s)
t = list(t)
s.sort()
t.sort()
return s==t

要求判断两个字符串s和t是否是字母异位词
一开始是查看s中每个字符,若果在t中就删掉,不在就返回False
如果t最终为空则返回True
这种方法可行,但是太繁琐
另一种思路是将字符串转化为列表,再进行排序,判断是否相等

No.263 丑数
1
2
3
4
5
6
7
8
9
10
11
if num<0:
return False
if num==1:
return True
while num>=2 and num%2==0:
num /= 2
while num>=3 and num%3==0:
num /= 3
while num>=5 and num%5==0:
num /= 5
return num==1

丑数是包含质因数为2,3,5的正整数
开始的想法是用num除2到根号num的每个数,判断结果是否在2,3,5中
这样的问题在于只能判断除一次的结果
对于8=2x2x2就无法判断了
其实可以分别判断是否可以整除2,3,5,可以的话就一直除
如果得到的结果是1,则表明num可以由若干个2,3,5的乘积表示,否则不行

No.290 单词模式
1
2
3
4
str = str.split()
if len(pattern)!=len(str):
return False
return len(set(zip(pattern,str)))==len(set(pattern))==len(set(str))

要求判断给定的字符串是否遵循给定的模式
这题的思想和205题相似,但是存在pattern的长度和str长度不相等的情况
先对zip(pattern,str)、pattern、str进行去重
再判断其它们的长度是否相等,相等则返回True,否则返回False

No.303 区域和检索-数组不可变
1
2
3
4
def __init__(self, nums):
self.nums=nums
def sumRange(self, i, j):
return sum(self.nums[i:j+1])

给定数组nums,求索引i到j范围的元素的和,包含i和j
要求写数字列表的一个方法sumRange,用于返回列表指定范围的元素和
不是很理解self.nums和nums分别起什么作用

NO.387 字符串中的第一个唯一字符

问题:查找一个字符串的每个字符是否重复,返回第一个不重复的字符
方法一:
对于一个字符,如何判断其在剩余字符中是否出现?
列表有一个count方法 ,可以统计元素出现的次数
对于一个列表中的元素,可以使用index方法返回该元素的位置
写了个算法,但是有个变态长的字符串,导致超时了:

1
2
3
4
5
s = list(s)
for i in range(len(s)):
if s.count(s[i])==1:
return i
return -1

方法二:
在网上找了一个答案:

1
2
3
4
5
d = collections.Counter(s)
for i in range(len(s)):
if d[s[i]]==1:
return i
return -1

有两个疑惑:
1.这和我的方法一样都是统计每个字符出现的次数,为什么我的超时,难道是list.count()比不上collections.Counter()???
2.collections.Counter()方法在leetcode上使用不需要导入collections库,所以这个方法最好不用
方法三:
先建立一个长度为26的数组,每位对应a到z的出现次数
遍历字符串,记录每个字符出现的次数
查找第一个出现次数为1的字符的位置
(这都没有超时是什么鬼,真的搞不懂,找字符位置的时候还用到了index,居然没有超时,反而方法一超时)

1
2
3
4
5
6
7
8
9
if len(s)==0:
return -1
l = [0]*26
for i in s:
l[ord(i)-97] += 1
for i in s:
if l[ord(i)-97]==1:
return s.index(i)
return -1

NO.389 找不同
1
2
3
4
5
6
7
8
9
10
11
class Solution:
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
b = 0
for a in s+t:
b ^= ord(a)
return chr(b)

t是将s中的字符打乱,再加入一个字符,现在要找出这个字符,一开始想的是一个个匹配,最后t中会多一个字符。
这里是对每个字符的二进制进行异或操作,比如:a的ASCII码是97,d是100,f是102,要在'af''adf'中找出'd'

1
2
3
4
5
a:1100001
f:1100110
a:1100001
d:1100100
f:1100110

对所有数依次进行异或'^',相等的数异或为0,任意数与0异或为其本身,由于s+t中除了'd'都是成对存在的,因此结果都为0,0再与'd'异或,结果为'd'

No.405 数字转换为十六进制数

问题:将整数转化为二进制数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
dic = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f']
l = []
s = ''
if num==0:
return "0"
if num<0:
num += 2**32
if num>0:
while num>0:
l.append(num%16)
num = int(num/16)
for i in l:
s += str(dic[i])
return s[::-1]

如果用Python的内置方法应该是比较简单的,但是求负数的二进制补码的十六进制表示一开始没有想出来
用十进制转十六进制的思想来做,每次除以16,保存余数,最终十六进制的形式由余数表示
对于负数,是先将其加上2的32次方,再当做正数处理,可以快速求负数的补码表示
(原本负数的补码是要求其绝对值的二进制,将其按位取反加1)

No.409 最长回文串

问题:计算字符串中的字符能构造的最长回文串

1
2
3
4
5
6
7
8
9
10
11
l = set(s)
res = 0
k = 0
for a in l:
num = s.count(a)
if num%2==0:
res += num
else:
k = 1
res += num-1
return res+k

A start is to count the number of each character, the even sum, plus the maximum odd
to do this a problem that the characters appear odd n can be selected from the even number of n-1 strings into the palindrome
thus be count the number of occurrences of each character, if it is an even number plus, if it is odd -1 plus
Note: the final intermediate palindromic sequence may contain an asymmetric character, can be coupled with a problem that if characters appear there is no odd number of times, if any, in the final result Riga 1, in this method, it is determined in the odd-else set to k 1, k 0 is the initial, final result plus k

No.438 find all the letters in the string word ectopic

Original: Big Box  Road LeetCode algorithm - The algorithm notes


Guess you like

Origin www.cnblogs.com/chinatrump/p/11446002.html