LeetCode Summary Math

============================ Math ====================================


343. Integer Break(给定一个数n,拆成乘积最大的一堆数)
要三不要二 要二不要一

约数倍数
365. Water and Jug Problem(容器量出指定水)
Discuss: 转换成了GCD


400. Nth Digit(第n个数字)



取数
390. Elimination Game(1-n排成一列,隔一个划掉一个,求最后)
Discuss: 公式+回溯
return n == 1 ? 1 : 2 * (1 + n / 2 - lastRemaining(n / 2));
置换 排列 组合 
1. next_permutation直接用
2. 不能用的话,就是确定要交换的区间,和,被交换的数,循环交换->递归
3. 冗余->排序
这个人总结了所有的置换题目,如下
https://discuss.leetcode.com/topic/46162/a-general-approach-to-backtracking-questions-in-java-subsets-permutations-combination-sum-palindrome-partioning
31. Next Permutation
求下一个置换的方法(700年前的方法)
在当前序列中,从尾端往前寻找两个相邻元素,前一个记为first,后一个记为second,并且满足first 小于 second。
然后再从尾端寻找另一个元素number,如果满足first 小于number,即将第first个元素与number元素对调,
并将second元素之后(包括second)的所有元素颠倒排序,即求出下一个序列
example:
6,3,4,9,8,7,1
此时 first = 4,second = 9
从尾巴到前找到第一个大于first的数字,就是7
交换4和7,即上面的swap函数,此时序列变成6,3,7,9,8,4,1
再将second=9以及以后的序列重新排序,让其从小到大排序,使得整体最小,即reverse一下(因为此时肯定是递减序列)
得到最终的结果:6,3,7,1,4,8,9
英文版:
Find the largest index k such that nums[k] < nums[k + 1]. If no such index exists, the permutation 
is sorted in descending order, just reverse it to ascending order and we are done. For example, 
the next permutation of [3, 2, 1] is [1, 2, 3].
Find the largest index l greater than k such that nums[k] < nums[l].
Swap the value of nums[k] with that of nums[l].
Reverse the sequence from nums[k + 1] up to and including the final element nums[nums.size() - 1].
60. Permutation Sequence(返回第k个置换)
46. Permutations(找到给定数集的置换,数distinct)
Mine: 用了next_permutation
47. Permutations II(有冗余)
Mine: sort,然后next_permutation
Discuss: sort, 递归进行交换,递归时设置交换的区间,然后循环该区间进行交换和递归。
        for (int k = i; k < j; k++) 
{if (i != k && num[i] == num[k]) continue;swap(num[i], num[k]);recursion(num, i+1, j, res);}
77. Combinations(C(n,k))
Mine: 回溯。 void generateCombine(int n, int k, int start , int index)

找到出现次数超过n/p次的数
169. Majority Element(找到出现次数最多的数 more than n/2 times.)
229. Majority Element II( more than n/3 times. )
S1(Mine):map
S2(Discuss):新的方法,原来没见过
Boyer–Moore majority vote algorithm(处理多余一半的数)
若出现的数是记录的数,cnt++,否则cnt--
Initialize an element m and a counter i with i = 0
For each element x of the input sequence:
If i = 0, then assign m = x and i = 1
else if m = x, then assign i = i + 1
else assign i = i ? 1
Return m
n/3时候需要2个来记录

直线
要点:截距,斜率,没有截距的情况
149. Max Points on a Line(在2D平面上,找到最多的点在一条直线上)
S(Discuss): 用map统计每个斜率出现的次数,找到次数最多的就是结果。

小数/分数
166. Fraction to Recurring Decimal(给两个整数,就他们做分子分母时的小数形式)
S1(Mine): 能整除就直接小数;不能整除找循环节,余数重复出现就是循环节。

判断是不是某种定义的数
202. Happy Number(平方求和之类)
S(Mine): 直接模拟
258. Add Digits(各位数字相加,直至1位数)
S(Mine): 模拟
263. Ugly Number(因子只有 2,3,5)
S(Mine): 模拟
264. Ugly Number II(找到第n个ugly number)
S1: 优先队列实现小根堆+set判断重复
S2: 使用set和lower_bound
在set里加入1,然后每次从set里选择lower_bound,+1,再分别*2,*3,*5加入到set里面
ugly.insert(1);long long int minUgly=0;
        for(int i=1;i<=n;i++)
        {
            minUgly=*ugly.lower_bound(minUgly+1);
            ugly.insert(minUgly*2);ugly.insert(minUgly*3);ugly.insert(minUgly*5);
        }
313. Super Ugly Number(找到第n个丑数)
S(Discuss): 从已有的uply数生成,之前的丑数*一个质数
Every ugly number is constructed from multiply a previous ugly number by one of the primes in the list. 
If current ugly number is ugly[i] , Index[j] is the index of the smallest of all ugly numbers that we 
already constructed , such that prime[j]*ugly[index[j]] is not found yet.
9. Palindrome Number(判断整数是不是回文)
S1(Mine): %10 /10 各取一个,比对相同


找到所有某种数
204. Count Primes(找到所有比n小的质数)
S(Mine): 筛子法:用bool数组标记是否为质数,从2开始,把他们所有的倍数标记成false(非质数)。
357. Count Numbers with Unique Digits(找到数字相同的所有数)
Let f(k) = count of numbers with unique digits with length equals k.
f(1) = 10, ..., f(k) = 9 * 9 * 8 * ... (9 - k + 2) [The first factor is 9 because a number cannot start with 0].




指数/开方
231. Power of Two(计算2的指数)
326. Power of Three(判断是否是3的指数)
367. Valid Perfect Square
Discuss: 牛顿法求平方根
50. Pow(x, n)
S(Discuss): 注意处理n<0时,把指数n拆成二进制表示,如1+2+4+8+32,等等。
double r = 1, base = x;
        while (n!=0)
        {if (n%2) r*=base; base*=base; n/=2;}
69. Sqrt(x)
S1(Mine): 直接找到平方根,使得差小于某个小数。
double k=1.0;
        while(fabs(k*k-n)>1e-3) {k=(k+n/k)/2;}
S2(Discuss): newton method: x[k+1] = 1/2 * (x[k]+n/x[k])
最简洁的方法: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division
long r = x;
while (r*r > x) r = (r + x/r) / 2;
S3(Discuss): 二分。找东西,二分最合适了
372. Super Pow(指数用数组的形式给出,再模一个整数)
S(Discuss):  ab % k = (a%k)(b%k)%k; f(a,1234567) = f(a, 1234560) * f(a, 7) % k = f(f(a, 123456),10) * f(a,7)%k;


高精度
66. Plus One(高精度+1)
朴素,勿忘进位
43. Multiply Strings(高精度乘法)
ans[i+j]+=a[i]*b[j]; 记得进位
67. Add Binary(加法)


整数各种转换
注意: INT_MAX,INT_MIN
7. Reverse Integer(反转整数)
S1(Mine): *10 /10 %10 
8. String to Integer (atoi)(字符串->整数)
S1(Mine): 模拟,注意!!找不回处理INT_MAX,INT_MIN的情况。
S2(Discuss): discards all leading whitespaces, sign of the number, overflow, invalid input
12. Integer to Roman(罗马转整数)
S1(Mine): 用数组定义好各种大小的数用什么字母,直接转换。
13. Roman to Integer(罗马转整数)
S1(Mine): 数组字母定义整数,转换。

计算个数
172. Factorial Trailing Zeroes(计算末尾0的个数)
有几个5就几个0
233. Number of Digit One(计算1的个数)
根据一个公式来计算,我好像永远都推倒不出来这个公式
   int ones = 0;
        for(long long m = 1;m<=n;m*=10)
        {int a = n/m, b= n%m; ones += (a+8)/10*m +(a%10==1)*(b+1);}


面积,矩形
223. Rectangle Area(计算2个矩形的面积)
注意去掉重复部分
335. Self Crossing(给定往4个方向走的步数,判断是否相交)
很棒的题!很棒的题解!我没想出来!
S(Discuss): 对可能出现的情况进行分类:
           i-2
    case 1 : i-1┌─┐
                └─┼─>i
                 i-3
                 
                    i-2
    case 2 : i-1 ┌────┐
                 └─══>┘i-3
                 i  i-4      (i overlapped i-4)


    case 3 :    i-4
               ┌──┐ 
               │i<┼─┐
            i-3│ i-5│i-1
               └────┘
                i-2

制定策略,判断输赢
找规律,从0,1,开始试几个数
397. Integer Replacement(给定n,三种操作n/2,n-1,n+1;最少的步骤到1)
Discuss1: 转成二进制方便查看,每次操作尽可能多的去掉1的个数。详细见.cpp文件
(1)偶数,除以2  (2) n=3,或者 n-1 比 n+1减少的1多 -> n-1  (3)否则n+1
Discuss2:
if n is even, you get no choice, just replace it with n / 2.
if n is odd, If n + 1 % 4 == 0, replace n with n + 1 will short the path. Otherwise, replace n with n - 1 is always the right direction.
292. Nim Game(取1,2,3,能否赢)
Mine: 找规律 %4==0
Discuss:Theorem: The first one who got the number that is multiple of 4 (i.e. n % 4
== 0) will lost, otherwise he/she will win.


位运算
很多运算不让用的时候,首先想到位运算。
某个数出现次数不同时,位运算。
29. Divide Two Integers(除两个整数,不许用乘法,除法和模运算)
S(Discuss): 使用位运算,注意overflow的情况,有点像除数k进制
每次看除数k移动几位<=left, 然后就记录移动的位数累计到结果

268. Missing Number(一串数,找到缺少的那个)
S1(Mine): 从0-n求和,再减去nums[i],最后的差就是缺的数
S2(Discuss): 
xor操作,a xor b xor b = a,对下标和数都xor
xor = xor ^ i ^ nums[i];
136. Single Number(所有数都出现两遍,除了一个数,找出来这个数)
S1(Mine): 直接记录次数,枚举
S2(Discuss): 位运算,A XOR A = 0,所以把所有的值xor一遍,剩下的结果就是出现一次的数。result ^=A[i];
137. Single Number II(所有数都出现3遍,只有一个1遍,找出来)
260. Single Number III(2个元素出现1次,其他都出现两次,知道2个元素)
Disucss: 位运算 xor


187. Repeated DNA Sequences(找到重复出现,长度为10的子串)
S1(Mine): 直接枚举,速度很慢很慢。
S2(Discuss): 位运算,最快,用4个数来代表ATCG,hash时候使用位运算;用map记录个数
S3(Discuss): map/set,一个记录是否出现过,一个记录结果,也很慢
89. Gray Code(连续的code,只差1位二进制数,求n位的gray code)
Discuss: n=3,可以从n=2生成。00,01,11,10 -> (000,001,011,010 ) (110,111,101,100).
2->3: 在2的所有code前面分别加0和1,就生成了3. ans[j]+ (1<<(i-1))
201. Bitwise AND of Numbers Range
318. Maximum Product of Word Lengths(一组单词,找到没有共同字母的两单词,是其长度乘积最大)
看到没有共同的字母,就想到转换成位运算的与预算。
把单词转换成数26位二进制数,然后两两与运算,结果为0的,就是没有共同字母,更新乘积。
Discuss: val |= 1<<(words[i].charAt(j)-'a');这种形式比我的简洁。1移动xx位,再求或。

393. UTF-8 Validation(验证UTF8)
先把分的几类的上下限的二进制对应的十进制算出来;
然后判断在哪类的范围内即可。

342. Power of Four(判断一个数是否是4的指数)
Discuss: n^(n-1)==0,n一定是2的指数;
First, Any number passes "n^(n-1)==0" must be powers of 2.
Second, all numbers above could be further categorized to 2 class. 
A: all numbers that are 2^(2k+1) and 
B: all numbers that 2^(2k).
Third, we could show that 2^(2k+1)-1 could not pass the test of (n-1)%3==0. 
(by induction) So all A are ruled out, leaving only B, which is power of 4.

Greedy
134. Gas Station
Discuss:
1. If car starts at A and can not reach B. Any station between A and B
can not reach B.(B is the first station that A can not reach.)
If the total number of gas is bigger than the total number of cost. There must be a solution.
2. Every time a fail happens, accumulate the amount of gas that is needed to overcome the fail. 
After looping through the stations, if the gas left is more than gas needed, then we have a 
solution, otherwise not.
135. Candy
Discuss: 2 rounds
1. First round: 正向找一遍大的rate比旁边的大一
2. Second round: 反向再找一遍,两个选项选最大的:
              (1) 自己     (2) 旁边比自己小的大一
316. Remove Duplicate Letters(删除字符串中的冗余字符,结果是字典序最小的)


392. Is Subsequence(判断s是否是t的子串)
s一个指针,遍历t,若s[ps]==t[i],ps++,最后ps等于s的末尾,则true
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值