67、二进制求和:给定两个二进制字符串,返回他们的和(用二进制表示)。
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
def twoToTen(s):
s=s[::-1]
x=0
for i in range(len(s)):
x+=int(s[i])*(2**i)
return x
aa=twoToTen(a)
bb=twoToTen(b)
def tenToTwo(x):
if x==0:
return '0'
l=[]
while x>1:
l.append(x%2)
x=x//2
ll=[1]+l[::-1]
s=''
for i in ll:
s+=str(i)
return s
return tenToTwo(aa+bb)
复习了一下二进制和十进制的转化,二进制转十进制:倒序后s[i]*2的i次方求和,i为索引;十进制转二进制:x整除2取余,返回以1开头的字符串。
69、x的平方根:实现 int sqrt(int x)
函数。
计算并返回 x 的平方根,其中 x 是非负整数。
由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。
这道题有两种思路,先求平方根再取整、计算过程中取整。下面是二分法的计算代码。
class Solution:
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
left=0
right=x
while left<=right:
mid=(left+right)//2
if mid*mid<x:
left=mid+1
elif mid*mid>x:
right=mid-1
else:
return mid
return left-1
70、爬楼梯:
假设你正在爬楼梯。需要 n 步你才能到达楼顶。
每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?
注意:给定 n 是一个正整数。
class Solution:
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
if n==1:
return 1
if n==2:
return 2
f=1
g=2
i=3
while i<=n:
g=g+f
f=g-f
i+=1
return g 这道题的规律是前面新的数等于它前面两数之和,刚开始直接用了函数递归结果运行时间过长,然后参考的别人的这种方法。 83、删除排序列表中的重复元素,使得每个元素只出现一次
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None:
return head
cur=head
while cur.next:
if cur.val==cur.next.val:
cur.next=cur.next.next
else:
cur=cur.next
return head
这道题的链表操作比较简单,如果重复直接跳过连接到下一个元素即可。
88、合并两个有序数组:给定两个有序整数数组 nums1 和 nums2,将 nums2 合并到 nums1 中,使得 num1 成为一个有序数组。
class Solution:
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: void Do not return anything, modify nums1 in-place instead.
"""
nums1[m:m+n]=nums2
return nums1.sort()
刚看到这道题本来想用循环插入,后来做了半天逻辑总是出错,然后就百度了一下,然后就两行代码解决了。。还是应用不太熟练啊。。