50
题目描述:
实现 pow(x, n) ,即计算 x 的 n 次幂函数(即,xn)。
示例:
解答:
class Solution:
def myPow(self, x: float, n: int) -> float:
'''
#递归
def cal_pow(x, n):
if n == 0:
return 1.0
if n % 2 == 0:
y = cal_pow(x, n//2)
return y * y
else:
return cal_pow(x, n - 1) * x
if n < 0:
return 1/cal_pow(x, -n)
return cal_pow(x, n)
'''
#迭代
def cal_pow(x, n):
res = 1.0
power = x
while n:
if n & 1 == 1:
res *= power
power *= power
n >>= 1
return res
if n >= 0:
return cal_pow(x, n)
else:
return 1/cal_pow(x, -n)
61
题目描述:
给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。
示例:
解答:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def rotateRight(self, head: ListNode, k: int) -> ListNode:
if not head:
return None
orig_head, cnt = head, 1 #cnt如果会遍历到none,就从0开始计数(右开空间),如果遍历到最后有效位,就从1开始(右闭空间)
while head.next: # head遍历到了最后一位
head, cnt = head.next, cnt+1 # cnt若从1开始,且紧跟着head,那么pointer最终停到哪,cnt就包括到哪。是完全相同的
head.next = orig_head # 首尾连接上
step = cnt - k % cnt-1 # 计算有效移动步数
while step > 0:
orig_head, step = orig_head.next, step - 1
new_head, orig_head.next = orig_head.next, None
return new_head
503
题目描述:
给定一个循环数组(最后一个元素的下一个元素是数组的第一个元素),输出每个元素的下一个更大元素。数字 x 的下一个更大的元素是按数组遍历顺序,这个数字之后的第一个比它更大的数,这意味着你应该循环地搜索它的下一个更大的数。如果不存在,则输出 -1。
示例:
解答:
nums_length = len(nums)
res_list = [-1 for _ in range(nums_length)]
stack = list()
double_nums = nums + nums
for index, num in enumerate(double_nums):
while stack and nums[stack[-1]] < num:
res_list[stack[-1]] = num
stack.pop()
if index < nums_length:
stack.append(index)
return res_list
1093
题目描述:
我们对 0 到 255 之间的整数进行采样,并将结果存储在数组 count 中:count[k] 就是整数 k 的采样个数。
我们以 浮点数 数组的形式,分别返回样本的最小值、最大值、平均值、中位数和众数。其中,众数是保证唯一的。
我们先来回顾一下中位数的知识:
如果样本中的元素有序,并且元素数量为奇数时,中位数为最中间的那个元素;
如果样本中的元素有序,并且元素数量为偶数时,中位数为中间的两个元素的平均值。
示例:
解答:
class Solution:
def sampleStats(self, count: List[int]) -> List[float]:
res = [257,0,0,0,0]
total,c,f = sum(count),0,0
for i in range(256):
if count[i]!=0:
c+=count[i]
res[0] = min(res[0],i)
res[1] = max(res[1],i)
res[2] += i*count[i]
res[4] = i if count[i]>count[res[4]] else res[4]
if c>=total/2 and f==0:
if (total&1)==1:
res[3] = i
elif c-1>=total/2:
res[3] = i
else:
j = i+1
while count[j]==0:j+=1
res[3] = (i+j)/2
f=1
res[2] = res[2]/total
return res
1248
题目描述:
给你一个整数数组 nums 和一个整数 k。
如果某个 连续 子数组中恰好有 k 个奇数数字,我们就认为这个子数组是「优美子数组」。
请返回这个数组中「优美子数组」的数目。
示例:
解答:
class Solution:
def numberOfSubarrays(self, nums: List[int], k: int) -> int:
tmp = [] # 存连续偶数个数的子序列
n = 1 # 从1开始计数,将来计算的时候就不用加1了
for i in nums:
if i % 2 == 0:
n += 1
else: # 发现一个奇数就存入连续偶数的个数
tmp.append(n)
n = 1
tmp.append(n) # 循环结束后还要把最后一个n加进来
if len(tmp) < k+1: # k个奇数,tmp里至少要有k+1个元素
return 0 # 凑不够k个奇数返回0
res = 0
for i in range(k, len(tmp)): # 将k个奇数两侧的偶数数量相乘,加在一起
res += tmp[i] * tmp[i-k]
return res