(Python)LeetCode习题代码(部分)
1、关于特殊数字字符串等
1.1 Palindrome Number(#9)
题⽬翻译: 给定⼀个数字,要求判断这个数字是否为回⽂数字. ⽐如121就是回⽂数字,122就不是回⽂数字.
解题思路: 这道题很明显是⼀道数学题,计算⼀个数字是否是回⽂数字,我们其实就是将这个数字除以10,保留他的余数,下次将余数乘以10,加上这个数字再除以10的余数.
需要注意的点:
负数不是回⽂数字.
0是回⽂数字.
时间复杂度: logN
代码如下:
def isPalindrome( x):
if x<0or (x!=0and x%10==0):
return False
y =0
m=x
while x!=0:
y = y * 10 + x % 10
x = x//10
return (y==m )
2、正则匹配
2.1 String to Integer (atoi)(#8)
题⽬要求:
1. 字串为空或者全是空格,返回0;
2. 字串的前缀空格需要忽略掉;
3. 忽略掉前缀空格后,遇到的第⼀个字符,如果是‘+’或‘-’号,继续往后读;如果是数字,则开始处理数字;如果不是前⾯的2种,返回0;
4. 处理数字的过程中,如果之后的字符⾮数字,就停⽌转换,返回当前值;
5. 在上述处理过程中,如果转换出的值超出了int型的范围,就返回int的最⼤值或最⼩值
代码如下:
import re
def myAtoi(self,str):
s =str.strip()
i = re.findall('(^[\+\-0]*\d+)\D*',s)
try:
result =''.join(i)
Max_index = 2**31-1
Min_index = -2**31
if int(result)>Max_index:
return Max_index
elif int(result)<Min_index:
return Min_index
return int(result)
except:
return0
3 集合List
3.1 Reverse Integer(#7)
新闻网站页面设计模板题⽬要求:
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
代码如下:
def reverse(self, x):
str='%d'%x
a=[]
if str[0]=='-':
a.append("-")
for m in list(range(-1, -len(str), -1)):
a.append(str[m])
result= int(''.join(a))
else:
for m in list(range(-1,-(len(str)+1),-1)):
a.append(str[m])
result = int(''.join(a))
if result >2**31-1or result <-2**31:
return0
else:
return result
under rotated3.2 ZigZag Conversion(#6)
题⽬如下:
The string “PAYPALISHIRING” is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line: “PAHNAPLSIIGYIR”
思路:
⽤下⾓标的⽅法判断太⿇烦,⽽且会出现各种情况,尤其是最后⼀次循环以及第⼀⾏和最后⼀⾏特殊处理的情况,因此不合适。
采⽤List集合⽅法,新建List[“”,”“,”“,”“] (共nunRows个),将每个字符利⽤循环读⼀个存进⼀个,最后集体读出。
代码如下:
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
if numRows == 1or len(s)<numRows:
hololensreturn s
L=['']*numRows
index,step = 0,1
for x in s:
L[index] +=x
if index ==0:
step = 1
elif index ==numRows-1:
step =-1
index +=step
return"".join(L)
3.3 Longest Common Prefix(#14)
Write a function to find the longest common prefix string amongst an array of strings.
返回⼀系列中字符串的最⼤公约数前缀。
最开始是⽤的list.pop()⽅法,但⼀直pop到最后⼀个列表元素时就不能在⽤这个⽅法,需要继续判断,⽐较⿇烦。
另⼀种是利⽤min(map(len,strs))⽅法求得字符串最⼤公约数前缀的长度n。然后循环前n个字符判断是否相等。
另⼀种⽅法更加强⼤。利⽤了zip()、set()集合的特点,并利⽤了可选参数。代码如下:
def longestCommonPrefix( strs):
sz, ret = zip(*strs), ""
print(sz)
for c in sz:
print(c)
if len(set(c)) > 1: break
ret += c[0]
print( ret)
longestCommonPrefix(["as","asd","asdff"])
# 其中sz是对应压缩的⼀种特殊格式,输出为<zip object at 0x000002113DC2F288>
# 需要对应读出
3.4 Remove Duplicates from Sorted Array(#26)
Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
克鲁斯卡尔是谁Do not allocate extra space for another array, you must do this in place with constant memory.
For example,
Given input array nums = [1,1,2],
Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn’t matter what you leave beyond the new length.
解析:删除掉重复的元素,并且不能⽣成额外的数组。最后⽣成数组的长度。
思路:利⽤前后的元素⽐较,相同就删掉,不同元素下标加⼀继续⽐较。
代码如下:
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums)==0:
return0
i,tmp=0,None
while i <len(nums):
if tmp!=nums[i]:
tmp=nums[i]
i=i+1
else:
del nums[i]
return len(nums)
3.5 Remove Element(#27)
Given an array and a value, remove all instances of that value in place and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
The order of elements can be changed. It doesn’t matter what you leave beyond the new length.
Example:
Given input array nums = [3,2,2,3], val = 3
Your function should return length = 2, with the first two elements of nums being 2.
解析:删除给定元素,并返回长度。不能产⽣额外空间。跟上⼀题类似。
class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:
rtype: int
"""
if len(nums)==0:
return0
i=0
while i<len(nums):
if val!=nums[i]:
i=i+1
else:
del nums[i]
return len(nums)
3.6 Implement strStr()(#28)
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
解析:当haystack 中包含needle 时,返回needle出现的下标。若不出现则返回-1
思路:遍历needle中的字符,判断与haystack第⼀个元素是否相同,若相同则继续遍历needle,若不同则删除haystack第⼀个元素,记录删除了⼏次,并让遍历needle的下标归回到0。循环。最后返回删除的次数。
代码如下:
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if len(haystack)==0and len(needle)==0:
return0
if needle not in haystack:
return -1python基础代码大全加翻译
i,j=0,0
m = list(haystack)
n=list(needle)
while i < len(needle):
if needle[i]!=m[i]:
del m[0]
j=j+1
什么水果含有vai=0
else:
i=i+1
return j
4 字典 Dic
4.1 Two Sum(#1)
题⽬如下:
Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
返回下标
代码如下:
**python版本**
def twoSum(nums,target):
if len(nums) <= 1:
return False
buff_dict = {}
for i in range(len(nums)):
if nums[i] in buff_dict:
print([buff_dict[nums[i]], i+1])
#return [buff_dict[nums[i]], i + 1]
else:
buff_dict[target - nums[i]] = i +1
**JAVA版本**
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论