leetcode中数学类/数组类题目_MaYingColdPlay的博客-CSDN博客1.整数反转思路:两种方法,1是把数字转化为字符串,用字符串倒序遍历的方式,需要开辟额外空间。2是用➗10取余数的方法。https://leetcode-cn.com/problems/reverse-integer/solution/hua-jie-suan-fa-7-zheng-shu-fan-zhuan-by-guanpengc/...https://blog.csdn.net/MaYingColdPlay/article/details/106610056?spm=1001.2014.3001.5502

5868 可互换矩形的数组

力扣https://leetcode-cn.com/problems/number-of-pairs-of-interchangeable-rectangles/

我真是太蠢了,居然用的是遍历做的。后来剪纸了一下,都超时。下面贴一下我的代码。

class Solution:def interchangeableRectangles(self, rectangles: List[List[int]]) -> int:cnt = 0for i in range(len(rectangles)):w1,h1 = rectangles[i][0],rectangles[i][1]for j in range(i+1,len(rectangles)):w2,h2 = rectangles[j][0],rectangles[j][1]if w1/h1 == w2/h2:cnt=cnt+1return cnt
class Solution:def interchangeableRectangles(self, rectangles: List[List[int]]) -> int:cnt=0dp=[[False for _ in range(len(rectangles))] for _ in range(len(rectangles))]for i in range(len(rectangles)):w1, h1 = rectangles[i][0], rectangles[i][1]for j in range(i + 1, len(rectangles)):if i>=1:if dp[i - 1][j] == True and dp[i - 1][j - 1] == True and dp[i][j-1]== True:dp[i][j] = Truecnt = cnt + 1else:w2, h2 = rectangles[j][0], rectangles[j][1]if w1 / h1 == w2 / h2:dp[i][j] = Truecnt = cnt +1else:w2, h2 = rectangles[j][0], rectangles[j][1]if w1 / h1 == w2 / h2:dp[i][j] = Truecnt = cnt + 1return cnt

其实用组合公式就可以了,反思一下自己为啥没想到

class Solution:def interchangeableRectangles(self, rectangles: List[List[int]]) -> int:#遍历数组,有多少个不同的比值dic={}for i in range(len(rectangles)):w=rectangles[i][0]h=rectangles[i][1]value = w/h if value not in dic.keys():dic[value]=1else:dic[value]=dic[value]+1res=0for key in dic.keys():cur_v=dic[key]cur_res=cur_v*(cur_v-1)/2res=res+cur_resreturn int(res)

5877. 检测正方形

我的凌乱解法,只能通过4个case。

class DetectSquares(object):def __init__(self):self.dic_x={}self.dic_y={}def add(self, point):""":type point: List[int]:rtype: None"""x=point[0]y=point[1]if x not in self.dic_x:self.dic_x[x]=[y]else:self.dic_x[x].append(y)if y not in self.dic_y:self.dic_y[y]=[x]else:self.dic_y[y].append(x)def count(self, point):""":type point: List[int]:rtype: int"""x=point[0]y=point[1]print("x,y",point,self.dic_x,self.dic_y)if x in self.dic_x and y in self.dic_y:y_match=self.dic_x[x]x_match=self.dic_y[y]y_match_helper={}x_match_helper={}for y_m in y_match:if abs(y-y_m) not in y_match_helper:y_match_helper[abs(y-y_m)]=1else:y_match_helper[abs(y-y_m)]=y_match_helper[abs(y-y_m)]+1for x_m in x_match:if abs(x-x_m) not in x_match_helper:x_match_helper[abs(x-x_m)]=1else:x_match_helper[abs(x-x_m)]=x_match_helper[abs(x-x_m)]+1print("x",x_match_helper)print("y",y_match_helper)for key in x_match_helper and y_match_helper:duijiao_x=abs(x-key)duijiao_y=abs(y-key)if duijiao_x in self.dic_x and duijiao_y in self.dic_y:return max(x_match_helper[key],y_match_helper[key])return 0
# Your DetectSquares object will be instantiated and called as such:
# obj = DetectSquares()
# obj.add(point)
# param_2 = obj.count(point)

大佬的找对角线的清晰的方法

class DetectSquares:def __init__(self):self.hashmap = collections.defaultdict(int)self.v = set()def add(self, point: List[int]) -> None:x,y = point[0],point[1]self.hashmap[(x,y)] += 1self.v.add((x,y))def count(self, point: List[int]) -> int:# 枚举对角线ans = 0x1,y1 = point[0],point[1]for x2,y2 in self.v:if x2 == x1 or y2 == y1:continueif (x1,y2) in self.v and (x2,y1) in self.v:d1,d2 = abs(y2 - y1),abs(x2 - x1)if d1 == d2:temp = 1temp *= self.hashmap[(x2,y2)]temp *= self.hashmap[(x1,y2)]temp *= self.hashmap[(x2,y1)]ans += tempreturn ans# Your DetectSquares object will be instantiated and called as such:
# obj = DetectSquares()
# obj.add(point)
# param_2 = obj.count(point)

31. 下一个排列

class Solution(object):def nextPermutation(self, nums):""":type nums: List[int]:rtype: None Do not return anything, modify nums in-place instead."""#从后往前遍历,找到nums[i]<nums[i+1]的第一个元素i=len(nums)-2while i>=0 and nums[i]>=nums[i+1]:i=i-1#从后往前遍历,找到nums[j]>nums[i]的第一个元素if i>=0:j=len(nums)-1while j>i and nums[i]>=nums[j]:j=j-1#交换nums[i],nums[j]=nums[j],nums[i]#从i+1到最后升序排列left=i+1right=len(nums)-1while left<right:nums[left],nums[right]=nums[right],nums[left]left=left+1right=right-1return nums

60 排列序列

力扣https://leetcode-cn.com/problems/permutation-sequence/solution/python3-chao-xiang-xi-duo-jie-fa-by-ting-ting-28-3/

264. 丑数 II

最小堆+广搜(接雨水2也是)

class Solution(object):def nthUglyNumber(self, n):""":type n: int:rtype: int"""#从小到大生成丑数#生成规则:每次弹出最小的数,乘以 2/3/5if n==1:return 1blist=[2,3,5]import heapqalist=[]heapq.heappush(alist,1)res=[]while len(res)<n:min_val=heapq.heappop(alist)if min_val not in res:res.append(min_val)for val in blist:new=min_val*val if new not in alist:heapq.heappush(alist,new)return res[-1]

解法2:多路归并

279. 完全平方数

373. 查找和最小的K对数字

解法1:堆排序

解法2:多路归并

668. 乘法表中第k小的数

204. 计数质数

枚举

class Solution {public int countPrimes(int n) {int cnt = 0;for (int i = 2; i < n; i++) {if (isPrime(i)) {cnt++;}}return cnt;}private boolean isPrime(int num) {int max = (int)Math.sqrt(num);for (int i = 2; i <= max; i++) {if (num % i == 0) {return false;}}return true;}
}作者:sweetiee
链接:https://leetcode-cn.com/problems/count-primes/solution/kuai-lai-miao-dong-shai-zhi-shu-by-sweetiee/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

埃氏筛

class Solution {public int countPrimes(int n) {boolean[] isPrim = new boolean[n];Arrays.fill(isPrim, true);// 从 2 开始枚举到 sqrt(n)。for (int i = 2; i * i < n; i++) {// 如果当前是素数if (isPrim[i]) {// 就把从 i*i 开始,i 的所有倍数都设置为 false。for (int j = i * i; j < n; j+=i) {isPrim[j] = false;}}}// 计数int cnt = 0;for (int i = 2; i < n; i++) {if (isPrim[i]) {cnt++;}}return cnt;}
}作者:sweetiee
链接:https://leetcode-cn.com/problems/count-primes/solution/kuai-lai-miao-dong-shai-zhi-shu-by-sweetiee/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
#埃式筛:先把所有的数(2到n)标记为质数,然后从2开始,把它的倍数标记为合数
# leetcode submit region begin(Prohibit modification and deletion)
class Solution:def countPrimes(self, n):is_primes = [1 for _ in range(n)]for i in range(2, n):if is_primes[i] == 1:for j in range(2 * i, n, i):# 将它的倍数设为0is_primes[j] = 0count = 0for i in range(2, n):if is_primes[i] == 1:count += 1return count
n=10
res=Solution().countPrimes(n)
print(res)

1447. 最简分数

辗转相除法求最大公约数

辗转相除法(求最大公约数)_阿不灌的拉的博客-CSDN博客

求最大公约数(辗转相除法)_ACfun-CSDN博客_辗转相除法求最大公约数

class Solution:def simplifiedFractions(self, n: int) -> List[str]:# n = 5# ["1/2","1/3","1/4","2/3","3/4"] ['1/5','2/5','3/5','4/5']if n==1:return []def gcd(a,b):while a>0 and b>0:if a>b:a=a%belse:b=b%a return a+b#递归,当前值加上n-1def cal_x(x):cur_res=[]cur_res.append(str(1) + '/' + str(x))for i in range(2,x):if gcd(x,i)==1:cur_res.append(str(i)+'/'+str(x))return cur_resreturn self.simplifiedFractions(n-1)+cal_x(n)

求最小公倍数

6019. 替换数组中的非互质数

栈+最大公约数和最小公倍数

class Solution:def replaceNonCoprimes(self, nums: List[int]) -> List[int]:stack=[]def gcd(a1,a2):#找最大公约数while a1>0 and a2>0:if a1>a2:a1=a1%a2 else:a2=a2%a1return a1+a2def check(stack):while len(stack)>=2 and gcd(stack[-1],stack[-2])>1:lcm=stack[-1]*stack[-2]//gcd(stack[-1],stack[-2])stack.pop()stack.pop()stack.append(lcm)for i in range(len(nums)):if stack and gcd(nums[i],stack[-1])>1:lcm=nums[i]*stack[-1]//gcd(nums[i],stack[-1])stack.pop()stack.append(lcm)else:stack.append(nums[i])#检查栈中是不是前后有非互质数check(stack)return stack

6015. 统计可以被 K 整除的下标对数目

最大公因数

k 剩下的质因数就是 y必须包含的质因数

class Solution(object):def coutPairs(self, nums, k):""":type nums: List[int]:type k: int:rtype: int"""# k/gcd(k,nums[i]),是nums[j]的一个因子def gcd(x,y):while x>0 and y>0:if x>y:x=x%yelse:y=y%x return x+yalist=[]res=0for i in range(len(nums)):a=gcd(nums[i],k)alist.append(a)print(alist)maps=Counter(alist)maps_list=list(maps.keys())#组合,不同的key两两组合(m*n),相同的key自己内部组合c(2,n),for i in range(len(maps_list)):if maps_list[i]*maps_list[i] % k==0:res+=maps[maps_list[i]]*(maps[maps_list[i]]-1)/2for j in range(i+1,len(maps_list)):if maps_list[i]*maps_list[j] % k==0:res+=maps[maps_list[i]]*maps[maps_list[j]]return res

5994. 查找给定哈希值的子串

取余运算性质

正序遍历:超时

class Solution(object):def subStrHash(self, s, power, modulo, k, hashValue):""":type s: str:type power: int:type modulo: int:type k: int:type hashValue: int:rtype: str"""#计算长度为k的子串的哈希值#查找indexalist=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']#先把power计算存到数组里power_i=[0 for _ in range(k)]power_i[0]=1for i in range(1,k):power_i[i]=power_i[i-1]*power#第一组cur_s=s[:k]cur=0for j in range(k):index=alist.index(cur_s[j])+1p=power_i[j]cur+=index*pif cur%modulo==hashValue:return cur_spre=0nexts=kwhile nexts<len(s):index=alist.index(s[nexts])+1p=power_i[k-1]cur=(cur-(alist.index(s[pre])+1))/power + index*p if cur%modulo==hashValue:return s[pre+1:nexts+1]pre+=1nexts+=1

取模运算满足分配律

class Solution(object):def subStrHash(self, s, power, modulo, k, hashValue):""":type s: str:type power: int:type modulo: int:type k: int:type hashValue: int:rtype: str"""#除数不好取模,数量太大会超时#因此用倒叙遍历的方法,从后往前遍历。乘法的取模满足交换律#先把幂运算结果保存下来power_i=[0 for _ in range(k)]power_i[0]=1%modulofor i in range(1,k):power_i[i]=power_i[i-1]*power%modulo#查找indexalist=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']res=[]#最后一组cur_s=s[len(s)-k:]cur_res=0for i in range(k):index=alist.index(cur_s[i])+1p=power_i[i]cur_res=cur_res+index*pcur_res=cur_res%moduloif cur_res == hashValue:res.append(cur_s)#倒叙遍历remove_index=len(s)-1new_index=len(s)-1-kwhile new_index>=0:new_value=alist.index(s[new_index])+1remove_value=(alist.index(s[remove_index])+1)*power_i[k-1]# cur_res=(cur_res-remove_value)*power+new_value # if cur_res%modulo == hashValue:#     res.append(s[new_index:remove_index])cur_res=((cur_res-remove_value)*power+new_value)%moduloif cur_res== hashValue:res.append(s[new_index:remove_index])# return s[new_index:remove_index]new_index=new_index-1remove_index=remove_index-1return res[-1]

2063. 所有子字符串中的元音

滑动窗口,超时

class Solution:def countVowels(self, word: str) -> int:alist=['a','e','i','o','u']cnt=0#双指针left=-1while left<len(word)-1:flag=0left+=1right=left+1cur=word[left]if cur in alist:cnt+=1flag=1while right<len(word):cur=word[right]if cur in alist or flag>0:if cur in alist:flag+=1cnt+=flagelse:cnt+=flagright+=1return cnt

组合数学

class Solution:def countVowels(self, word: str) -> int:res = 0meta = {'a', 'e', 'i', 'o', 'u'}n = len(word)for i, ch in enumerate(word):if ch in meta:res += (i + 1) * (n - i)return res作者:ya-li-ge
链接:https://leetcode-cn.com/problems/vowels-of-all-substrings/solution/zu-he-wen-ti-xun-huan-bian-li-python-jie-hoxq/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

828. 统计子串中的唯一字符

滑窗,超时

class Solution:def uniqueLetterString(self, s: str) -> int:count=0#滑动窗口left=-1while left<len(s)-1:left+=1cur=s[left]count+=1visited={}visited[cur]=1right=left+1while right<len(s):cur = s[right]if cur in visited:visited[cur]+=1else:visited[cur]=1cur_count=0for key in visited:if visited[key]==1:cur_count+=1count += cur_countright += 1return count

组合数学

class Solution:def uniqueLetterString(self, s: str) -> int:res=0#转化为:每个字母所在在子串,包含1个当前字母的子串个数。for i in range(len(s)):cur=s[i]#往左j=i-1while j>=0 and s[j]!=cur:j=j-1left_count=i-j #往右h=i+1while h<=len(s)-1 and s[h]!=cur:h=h+1right_count=h-i cur_count=left_count*right_countres+=cur_countreturn res

5986. 设置时间的最少代价

class Solution {
public:int minCostSetTime(int startAt, int moveCost, int pushCost, int targetSeconds) {int mins = targetSeconds / 60;int secs = targetSeconds % 60;int ans1 = calc(startAt, moveCost, pushCost, mins, secs);int ans2 = calc(startAt, moveCost, pushCost, mins - 1, secs + 60);return min(ans1, ans2);}int calc(int startAt, int moveCost, int pushCost, int mins, int secs) {/* 非法输入返回 */if (mins > 99 || mins < 0 || secs > 99) {return INT_MAX;}/* 转为字符串, 去除前导0 */string s = to_string(mins * 100 + secs);int ans = 0;/* 对每个数字进行处理 */for (int i = 0; i < s.size(); i++) {if (startAt == s[i] - '0') { /* 不需要额外moveCost */ans += pushCost;} else {ans += moveCost + pushCost;}startAt = s[i] - '0';}return ans;}
};作者:liu-xiang-3
链接:https://leetcode-cn.com/problems/minimum-cost-to-set-cooking-time/solution/cfen-lei-tao-lun-by-liu-xiang-3-sqem/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
class Solution:def minCostSetTime(self, startAt: int, moveCost: int, pushCost: int, targetSeconds: int) -> int:def cal(minute,second,startAt):if minute>99:return float('inf')#转化为四位target_time=[minute//10,minute%10,second//10,second%10]i=0cost=0#跳过最前面的0while i<=3 and target_time[i]==0:i+=1while i<=3:cur=target_time[i]if cur==startAt:cost=cost+pushCostelse:cost=cost+pushCost+moveCoststartAt=cur i+=1return costans1=float('inf')ans2=float("inf")#把targetSeconds转化为微波炉时间形式minute1=targetSeconds//60 second1=targetSeconds%60 ans1=cal(minute1,second1,startAt)#分钟数最大可以到99秒,当second1小于等于39的时候,可以把分钟(60秒)拿到秒位数上if second1<=39:second2=second1+60 minute2=minute1-1 ans2=cal(minute2,second2,startAt)return min(ans1,ans2)

233. 数字 1 的个数

暴力超时

排列组合找规律

力扣

1214有12个100,每个100有10个1,12*10=120

1200到1214,+low+1 (有0的情况所以要➕1)

1234有12个100,每个100有10个1,12*10=120

1200到1234有34个数,+10

以1214为例,计算十位为1时,的个数的时候,为什么不用乘法原理,左边*右边,即12*4,因为,考虑如918的情况,当左边小于12时,右边是可以大于4的。因此要先算高位可以组成多少个,再加上低位的。

if cur == 0:

res += high * digit

以1214为例,计算十位为1时。high实际上是十位左边可以取的值,digit是右边可以取的值,这里是排列组合乘法原理。high是比实际数小于等于的值,当取high时,右边的取值就是从0到9

class Solution:def countDigitOne(self, n: int) -> int:res = 0digit = 1#个位数cur = n % 10#从十位开始high = n // 10low = 0while high > 0 or cur > 0:if cur == 0:res += high * digitelif cur == 1:res += high * digit + low + 1else:res += high * digit + digit# 计算下一位上的1low = low + digit * curcur = high % 10high = high // 10digit = digit * 10return res

41.缺失的第一个正数

原地哈希

相似题目:剑指offer03,原地哈希

from typing import Listclass Solution:# 3 应该放在索引为 2 的地方# 4 应该放在索引为 3 的地方def firstMissingPositive(self, nums: List[int]) -> int:size = len(nums)for i in range(size):# 先判断这个数字是不是索引,然后判断这个数字是不是放在了正确的地方while 1 <= nums[i] <= size and nums[i] != nums[nums[i] - 1]:self.__swap(nums, i, nums[i] - 1)for i in range(size):if i + 1 != nums[i]:return i + 1return size + 1def __swap(self, nums, index1, index2):nums[index1], nums[index2] = nums[index2], nums[index1]作者:liweiwei1419
链接:https://leetcode-cn.com/problems/first-missing-positive/solution/tong-pai-xu-python-dai-ma-by-liweiwei1419/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

440. 字典序的第K小数字

按位计数排列

类似的题还有之前周赛的一次t2,下一个排列

力扣

class Solution {public int findKthNumber(int n, int k) {long cur = 1;k--;while(k > 0) {// 以cur为根的子树节点有nodes个int nodes = getNodes(n, cur);// 如果个数比k少,那么这个部分都可以直接跳过if(k >= nodes) {// 跳过全部k = k -nodes;// 往右移一位cur++;}// 如果数量比k多,那么我们要找的结果就一定是以cur下的子节点else {// 跳过当前结点k = k - 1;// 往下走一层cur = cur * 10;}}return (int)cur;}// 获得以cur为根结点的子树节点数量private int getNodes(int n, long cur) {long next = cur + 1;long totalNodes = 0;while(cur <= n) {// 一次性求出下一层的节点个数和,要是没满就用n来减,要是满了就用next减totalNodes += Math.min(n - cur + 1, next - cur);// 进入下一层next = next * 10;cur = cur * 10;}return (int)totalNodes;}
}作者:livorth-u
链接:https://leetcode-cn.com/problems/k-th-smallest-in-lexicographical-order/solution/by-livorth-u-zvxp/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

5253. 找到指定长度的回文数

周赛的时候调了半天没调出来。

class Solution(object):def kthPalindrome(self, queries, intLength):""":type queries: List[int]:type intLength: int:rtype: List[int]"""len1=9len2=9len3=9*10len4=9*10len5=9*10*10len6=9*10*10len7=9*10*10*10len8=9*10*10*10len9 = 9 * 10 * 10 * 10* 10len10 = 9 * 10 * 10 * 10 * 10len11 = 9 * 10 * 10 * 10 * 10* 10len12 = 9 * 10 * 10 * 10 * 10* 10len13 = 9 * 10 * 10 * 10 * 10 * 10* 10len14 = 9 * 10 * 10 * 10 * 10 * 10* 10len15 = 9 * 10 * 10 * 10 * 10 * 10 * 10* 10#先确定最外面的maps={1:0,2:0,3:1,4:1,5:2,6:2,7:3,8:3,9:4,10:4,11:5,12:5,13:6,14:6,15:7}def cal(i,intLength):cur_num=queries[i]cur_res=[str(0) for _ in range(intLength)]v0=maps[intLength]v1=10**v0tmp_count=0flag=Falsefor i in range(1,10):if i>1:flag=Truetmp_count=tmp_count+v1if cur_num<=tmp_count and flag==False:cur_res[0]=str(i)breakif cur_num<tmp_count and flag==True:cur_res[0] = str(i-1)cur_num=cur_num-(tmp_count-v1)breakif cur_num==tmp_count:cur_res[0] = str(i)cur_num = cur_num - (tmp_count - v1)#从第二位开始,还剩下cur_num个数#偶数遍历到intLength=intLength-2index=1while intLength>1:v0 = maps[intLength]v1 = 10 ** v0tmp_count = 0flag = Falsefor i in range(10):if i > 0:flag = Truetmp_count = tmp_count + v1if cur_num <= tmp_count and flag == False:cur_res[index] = str(i)breakif cur_num <= tmp_count and flag == True:cur_res[index] = str(i - 1)cur_num = cur_num - (tmp_count - v1)breakintLength = intLength - 2index = index+1#如果是偶数,判断最后两位,如果是奇数,判断最后一位if if_oushu==0:for i in range(10):cur_num = cur_num - 1if cur_num==0:cur_res[index] = str(i)right=len(cur_res)-1left=0while left<right:cur_res[right]=cur_res[left]right-=1left+=1print(cur_res)return ''.join(cur_res)res=[]if_oushu=0if intLength%2==0:if_oushu=1for i in range(len(queries)):res.append(int(cal(i,intLength)))return res
# queries = [2,4,6], intLength = 4
# queries = [231]
# intLength = 5
# queries =[1,2,3,4,5,90]
# intLength =3#分奇数偶数讨论,先确定前缀,偶数最后2个要特殊处理,奇数最后一个要特殊处理
#第一个前缀特殊处理,因为第一个前缀不能有前导0
#确定前缀的时候,要把count减去已经确定好的前缀的数量
queries =[2,4,6]
intLength =4
res=Solution().kthPalindrome(queries, intLength)
print(res)

找规律

class Solution {public long[] kthPalindrome(int[] queries, int intLength) {/*找规律生成:核心就是要找到n位数的回文数有多少个(越界判断)?+第k个回文数是什么?*/int len = queries.length;long[] res = new long[len];for(int i = 0; i < len; i++) {res[i] = getPalindrome(queries[i], (double)intLength);}return res;}/*返回生成第k小的n位回文数不难发现有以下规律:101, 111, 121, 131, 141, 151, 161, 171, 181, 191202, 212, 222, 232, 242, 252, 262, 272, 282, 292...909, 919, 929, ............................, 999可知3位数的回文数一共有90个只考虑左半部分(相当关键!!!)1.总结起来n位数回文总数为:n为奇数:9*10^(n/2);n为偶数:9*10^(n/2-1)进一步地:9*10^(ceil(n/2)-1)超过这个范围返回-1即可2.第k小的回文数实际上是奇数:10^(n/2)+k-1(+倒转+删掉中间位)偶数:10^(n/2-1)+k-1(+倒转)进一步地:10^(ceil(n/2)-1)+k-1*/private long getPalindrome(int k, double n) {// 超出有效的个数范围直接返回-1if(k > 9 * Math.pow(10, Math.ceil(n / 2) - 1)) {return -1;}// 先将前半部分转化成字符串long pre = (long)Math.pow(10, Math.ceil(n / 2) - 1) + k - 1;StringBuilder sb1 = new StringBuilder(String.valueOf(pre));StringBuilder sb2 = new StringBuilder(sb1);// 拼接后面部分sb2.append(sb1.reverse());// n为奇数还要去除中间的一位if((int)n % 2 == 1) {sb2.deleteCharAt((int)n / 2);}// 再将字符串转化为数字return Long.parseLong(sb2.toString());}
}

2195. 向数组中追加 K 个整数

等差数列

780 到达终点

逆向思维

class Solution {
public:bool reachingPoints(int sx, int sy, int tx, int ty) {if(sx > tx || sy > ty) return false;while(sx < tx && sy < ty) {if(tx > ty) tx %= ty;else ty %= tx;}if(tx == sx) { // ty = sy + k * tx, k >= 0return (ty - sy) % tx == 0; } else if(ty == sy) { // tx = sx + k * ty, k >= 0return (tx - sx) % ty == 0;}return false;}
};作者:hxf_wyh
链接:https://leetcode-cn.com/problems/reaching-points/solution/by-hxf_wyh-g9hj/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

357 计算各个位数不同的数字个数

排列组合

思路想错了

class Solution {public int countNumbersWithUniqueDigits(int n) {int res = 1;int product = 9;for (int i = 1; i < 10 && i <= n; i++) {res = product + res;product *= (10-i);}return res;}
}
class Solution(object):def countNumbersWithUniqueDigits(self, n):""":type n: int:rtype: int"""res = 1for i in range(1,n+1):#首位不能是0,有9种情况cur = 9cur_res = 9#从第二位开始,第二位是9种情况,第三位是8种情况for j in range(2,i+1):cur_res *= cur cur = cur - 1 # print(cur_res)res += cur_resreturn res

leetcode-数学题相关推荐

  1. LeetCode 41. First Missing Positive--Python 解法--数学题-找到不存在的最小正整数-O(1)空间复杂度

    题目地址:First Missing Positive - LeetCode Given an unsorted integer array, find the smallest missing po ...

  2. LeetCode 31. Next Permutation-- Python 解法--数学题--比当前数大的最小的数

    LeetCode 31. Next Permutation-- Python 解法–数学题–比当前数大的最小的数 此文首发于我的个人博客:LeetCode 31. Next Permutation-- ...

  3. LeetCode 202. Happy Number--Python解法--数学题

    此文首发于我的个人博客:LeetCode 202. Happy Number–Python解法–数学题 - zhang0peter的个人博客 LeetCode题解专栏:LeetCode题解 LeetC ...

  4. LeetCode 268. Missing Number--Python解法--数学题

    LeetCode 268. Missing Number–Python解法–数学题 LeetCode题解专栏:LeetCode题解 LeetCode 所有题目总结:LeetCode 所有题目总结 大部 ...

  5. LeetCode 974. Subarray Sums Divisible by K--Python解法--数学题--取模求余

    LeetCode 974. Subarray Sums Divisible by K–Python解法–数学题–取模求余 LeetCode题解专栏:LeetCode题解 LeetCode 所有题目总结 ...

  6. LeetCode 123. Best Time to Buy and Sell Stock III--Python解法--动态规划--数学题

    此文首发于我的个人博客:zhang0peter的个人博客 LeetCode题解文章分类:LeetCode题解文章集合 LeetCode 所有题目总结:LeetCode 所有题目总结 题目地址:Best ...

  7. LeetCode 319. Bulb Switcher--C++,java,python 1行解法--数学题

    LeetCode 319. Bulb Switcher–C++,java,python 1行解法 LeetCode题解专栏:LeetCode题解 LeetCode 所有题目总结:LeetCode 所有 ...

  8. LeetCode简单题之找出两数组的不同

    题目 给你两个下标从 0 开始的整数数组 nums1 和 nums2 ,请你返回一个长度为 2 的列表 answer ,其中: answer[0] 是 nums1 中所有 不 存在于 nums2 中的 ...

  9. LeetCode简单题之公平的糖果交换

    题目 爱丽丝和鲍勃拥有不同总数量的糖果.给你两个数组 aliceSizes 和 bobSizes ,aliceSizes[i] 是爱丽丝拥有的第 i 盒糖果中的糖果数量,bobSizes[j] 是鲍勃 ...

  10. LeetCode中等题之最优除法

    题目 给定一组正整数,相邻的整数之间将会进行浮点除法操作.例如, [2,3,4] -> 2 / 3 / 4 . 但是,你可以在任意位置添加任意数目的括号,来改变算数的优先级.你需要找出怎么添加括 ...

最新文章

  1. DataGrid入门经典(C#)
  2. 总结:Apache架构师30条架构原则
  3. ASP.NET 会话状态
  4. Windows8 Metro开发 (03) : AppBar控件之BottomAppBar
  5. 主机大师linux,113资讯网(www.113p.cn)评测:护卫神·主机大师 (Linux版)
  6. Python第二十二天 stat模块 os.chmod方法 os.stat方法 pwd grp模块
  7. centos 卸载软件_Linux系统配置及服务管理_第09章_软件管理
  8. docker下载慢,卡顿解决办法——免费安装人人都有的docker加速器
  9. [C++ rudiment][转]typedef 使用
  10. c语言:malloc函数的简介
  11. java获取上一天数据,java获取日历格式的日期数据
  12. catia需要java插件,catia中的带分析
  13. 虚拟机怎么查找服务器管理员,“你瞅瞅人王工家的VMware管理员~”
  14. java addslashes_PHP防止注入攻击
  15. 降维: 主成分分析(PCA) 局部线性嵌入(LLE)
  16. i2cdetect i2cdump i2cget i2cset用法
  17. 打印系统开发(66)——监控打印机的打印队列
  18. 牛客多校10 Train Wreck (模拟,思维题,优先队列重载小于号的操作)
  19. WPF 自定义各类按钮样式
  20. 如何知道计算机显卡内存,电脑显卡是什么 怎么查显卡显存【图文】

热门文章

  1. php会计科目,ThinkPHP+EasyUI之ComboTree中的会计科目树形菜单实现方法
  2. oracle 以1开头以9结尾_好的作文开头、结尾
  3. 分享153个ASP源码,总有一款适合您
  4. Redis 高级特性 布隆过滤器
  5. ROS 创建工作空间流程
  6. 可爱的二次元少女,风靡Z世代的美食UP主。
  7. thunderbird 的相关扩展收集
  8. 操作系统笔记——系统态和用户态
  9. 小区后面的步行街新开了一家豆腐店,傍晚在做地推活动
  10. android11 文件读写 访问 android/data 目录