在此记录自己做的所有PYTHON题的答案,我用的PY2。
更新的慢。毕竟脑子笨,比如其中range可以换成xrange
1.从排序数组中删除重复项
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
for i in range(len(nums)):
for j in range(i+1,len(nums)):
if nums[i] == nums[i+1]:
del nums[i+1]
else:
break
return len(nums)
买卖股票的最佳时机 II
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
zong = 0
for i in range(len(prices)-1):
if prices[i+1]>prices[i]:
zong+= (prices[i+1]-prices[i])
return zong
给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数。
class Solution(object):
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
k = k%len(nums)
nums[:] = nums[-k:]+nums[:-k]
给定一个整数数组,判断是否存在重复元素。
如果任何值在数组中出现至少两次,函数返回 true。如果数组中每个元素都不相同,则返回 false。
class Solution(object):
def containsDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
if len(set(nums)) == len(nums):
return False
else:
return True
给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.sort()
for i in range(len(nums)):
if len(nums) == 1:
return nums[0]
if nums[0] == nums[1]:
del nums[0]
del nums[0]
else:
return nums[0]
给定一个非负整数组成的非空数组,在该数的基础上加一,返回一个新的数组。
class Solution(object):
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
num = 1
for i in range(len(digits)):
num+=int(digits[i])*(10**(len(digits)-i-1))
return [int(i) for i in list(str(num))]
给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
j=0
for i in xrange(len(nums)):
if nums[j] == 0:
nums.append(nums.pop(j))
else:
j+=1
给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in xrange(len(nums)):
for j in xrange(i+1,len(nums)):
if nums[i]+nums[j] == target:
return [i,j]
判断一个 9x9 的数独是否有效。只需要根据以下规则,验证已经填入的数字是否有效即可。
class Solution(object):
def isValidSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: bool
"""
for i in xrange(9):
hang = board[i]
lie = []
for j in range(9):
lie.append(board[j][i])
for m in hang:
if hang.count(m)>1 and m!='.':
return False
for n in lie:
if lie.count(n)>1 and n!='.':
return False
for j in xrange(9):
if i%3==0 and j%3==0:
small = []
for p in range(i,i+3):
for q in range(j,j+3):
if board[p][q] != '.':
small.append(board[p][q])
if len(small) != len(list(set(small))):
print i,j,p,q
return False
return True
给定一个 n × n 的二维矩阵表示一个图像。
将图像顺时针旋转 90 度。
class Solution(object):
def rotate(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
n = len(matrix)
for i in range(n/2):
for j in range(i,n-i-1):
tmp = matrix[i][j]
print tmp
matrix[i][j]=matrix[n-j-1][i]
matrix[j][n-i-1],tmp = tmp,matrix[j][n-i-1]
matrix[n-i-1][n-j-1],tmp = tmp,matrix[n-i-1][n-j-1]
matrix[n-j-1][i]=tmp
请编写一个函数,其功能是将输入的字符串反转过来。
class Solution(object):
def reverseString(self, s):
"""
:type s: str
:rtype: str
"""
return str(s)[::-1]
颠倒整数
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
if str(x)[0] == '-':
num = int('-'+str(x)[1:][::-1])
else :
num = int(str(x)[::-1])
if num>2**31-1 or num<-2**31:
return 0
else:
return num
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
for i in range(len(s)):
if s[i] not in s[i+1:] and s[i] not in s[:i]:
return i
return -1
有效的字母异位词
class Solution(object):
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
if len(s) != len(t):
return False
while s:
tmp = s[0]
s=s.replace(tmp,'')
t=t.replace(tmp,'')
if len(s)!=len(t):
return False
return True
给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
class Solution(object):
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
s = filter(str.isalnum, str(s)).lower()
if s == s[::-1]:
return True
else:
return False
报数序列是指一个整数序列,按照其中的整数的顺序进行报数,得到下一个数。其前五项如下:
class Solution(object):
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
old = '1'
for i in range(n-1):
num = 1
value = ''
next = ''
while 1:
try:
if old[0]==old[1]:
num += 1
value = old[0]
else:
if value!='':
next+= str(num)+str(value)
else:
next+= str(num)+str(old[0])
num = 1
value = ''
old=old[1:]
except IndexError,e:
next += str(num)+str(old[0])
old = next
break
return old
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 “”。
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
rstr = ''
if strs == []:
return rstr
old = strs[0]
for i in range(len(old)): #i为第一个元素的遍历单个字符
for j in range(len(strs)):
try:
if old[i] == strs[j][i]:
pass
else:
return rstr
except:
return rstr
else:
rstr += old[i]
return rstr
请编写一个函数,使其可以删除某个链表中给定的(非末尾)节点,你将只被给定要求被删除的节点。
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def deleteNode(self, node):
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-place instead.
"""
node.val = node.next.val
node.next = node.next.next
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
dummy = ListNode(-1)
dummy.next = head
p = dummy
c = head
c2 = head
num = 0
while c2 is not None:
num+=1
c2=c2.next
for i in range(num-n+1):
if c.next is not None:
p=p.next
c=c.next
else:
p.next = None
return dummy.next
p.val = c.val
p.next=c.next
return dummy.next
反转链表
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
p = head
q = None
while p:
c = p.next
p.next = q
q = p
p = c
return q
将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if l1==None and l2==None:
return None
if l1==None:
return l2
if l2==None:
return l1
if l1.valreturn l1
if l2.valreturn l2
elif l1.val==l2.val:
l1.next = self.mergeTwoLists(l1.next,l2)
return l1
请判断一个链表是否为回文链表。
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
list1 = []
list2 = []
if head == None:
return True
while head:
list1.append(head.val)
list2.append(head.val)
head = head.next
list1.reverse()
if list1 == list2:
return True
else:
return False
给定一个链表,判断链表中是否有环。
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if head == None:
return False
try:
p1 =head
p2 = head.next
except:
return False
while p1:
if p1 == p2:
return True
else:
try:
p1 =p1.next
p2 = p2.next
p2 = p2 .next
except:
return False
return False
二叉树的最大深度
class Solution(object):
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root == None:
return 0
else:
return 1+max(self.maxDepth(root.left),self.maxDepth(root.right))