今天主要还是双指针以及一道模拟题,模拟题比较有趣,具体题目以及代码如下:
# 977.有序数组的平方
class Solution:
def sortedSquares(self, nums: list) -> list:
left = 0
right = len(nums) - 1
res = []
while right >= left:
if nums[right]*nums[right] > nums[left]*nums[left]:
res.append(nums[right]*nums[right])
right -= 1
else:
res.append(nums[left]*nums[left])
left += 1
return res[::-1]
# 209.长度最小的子数组
# 审题没申明白,是>=target的最短连续子数组
def minSubArrayLen(target: int, nums: list) -> int:
slow = 0
fast = 0
ans = 0
l = len(nums)
if sum(nums) < target: return 0
while fast <= len(nums) - 1:
ans += nums[fast]
while ans >= target:
l = min(l, fast - slow + 1)
ans -= nums[slow]
slow += 1
fast += 1
# print(fast, slow, ans)
return l if ans <= target else 0
target = 11
nums = [1,2,3,4,5]
print(minSubArrayLen(target, nums))
# 59.螺旋矩阵II 模拟
# 左闭右开,遍历节点,最后一个节点留给下一个
# 转几圈?n/2圈,如果n为odd,留下中间那个
class Solution:
def generate(self, n):
nums = [[0] * n for _ in range(n)]
x, y = 0, 0
loop, mid = n//2, n//2
count = 1
for offset in range(1, loop+1):
for i in range(y, n - offset):# left to right
nums[x][i] = count
count += 1
for i in range(x, n-offset):# up to down
nums[i][n - offset] = count
count += 1
for i in range(n - offset, y, -1):# right to left
nums[n - offset][i] = count
count += 1
for i in range(n - offset, x, -1):# down to up
nums[i][y] = count
count += 1
x += 1
y += 1
if n % 2 != 0:
nums[mid][mid] = count
return nums
此外,和一个网友讨论了P-R曲线的画法,明确了TP FP FN FP的涵义,按照链接的数据经过修正,弄了一个画P-R曲线的程序:
import collections
import numpy as np
from matplotlib import pyplot as plt
import numpy
l = list(range(1,21))
positive = [1,2,4,5,6,9,11,13,17,19]
score = [0.9,0.8,0.7,0.6,0.55,0.54,0.53,0.52,0.51,0.505,
0.4,0.39,0.38,0.37,0.36,0.35,0.34,0.33,0.30,0.1]
class_d = collections.defaultdict(int)
score_d = collections.defaultdict(float)
for i in l:
if i in positive:
class_d[i] = 1
else:
class_d[i] = 0
score_d[i] = score[i-1]
# print(class_d.items())
# print(score_d.items())
def get_pr(class_d,score_d,thresh):
tp = 0
fp = 0
fn = 0
tn = 0
for i in score_d.keys():
if score_d[i] >= thresh and class_d[i] == 1:
tp += 1
elif score_d[i] >= thresh and class_d[i] == 0:
fp += 1
elif score_d[i] < thresh and class_d[i] == 1:
tn += 1
elif score_d[i] < thresh and class_d[i] == 0:
fn += 1
return tp,fp,fn,tn
# pp = []
# rr = []
# for thre in np.linspace(0.0,0.9,100):
# tp,fp,fn,tn = get_pr(class_d,score_d,thre)
# # print(tp/(tp+fp),tp/(tp+fn))
# pp.append(tp/(tp+fp))
# rr.append(tp/(tp+fn))
# plt.plot(rr, pp)
# plt.ylim(0,1.2)
# plt.show()
pp = []
rr = []
fpr = []
tpr = []
epsilon = 0.0000001
for thre in np.linspace(0.0,0.9,100):
# thre = i/10
tp,fp,fn,tn = get_pr(class_d,score_d,thre)
pp.append(tp/(tp+fp+epsilon))
rr.append(tp/(tp+fn+epsilon))
fpr.append(fp/(tn+fp+epsilon))
tpr.append(tp/(tp+fn+epsilon))
plt.plot(rr, pp,'r')
plt.plot(fpr, tpr,'g')
plt.show()