leetcode math类型题目解题总结

天大地大妈咪最大 提交于 2020-12-12 10:05:15

2. Add Two Numbers https://leetcode.com/problems/add-two-numbers/description/

class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode result(-1);
        ListNode* current = &result;
        int add = 0;
        while(l1!=NULL || l2!=NULL){
            int val1 = 0;
            int val2 = 0;
            if(l1!=NULL){
                val1 = l1->val;
                l1 = l1->next;
            }
            if(l2!=NULL){
                val2 = l2->val;
                l2 = l2->next;
            }
            current->next = new ListNode((val1+val2+add)%10);
            add = (val1+val2+add)/10;
            current = current->next;
        }
        if(add == 1)
            current->next = new ListNode(1);
        return result.next;
    }
};
View Code

 

7. Reverse Integer https://leetcode.com/problems/reverse-integer/description/

class Solution {
public:
    int reverse(int x) {
        int res = 0;
        while(x!=0){
            if(res>INT_MAX/10||res<INT_MIN/10){
                return 0;
            }
            res = res*10 + x%10;
            x = x/10;
        }
        return res;
    }
};
View Code

 

8. String to Integer (atoi) https://leetcode.com/problems/string-to-integer-atoi/description/

class Solution {
public:
    int myAtoi(string str) {
        long result = 0;
        int indicator = 1;
        for(int i = 0; i<str.size();)
        {
            i = str.find_first_not_of(' ');
            if(str[i] == '-' || str[i] == '+')
                indicator = (str[i++] == '-')? -1 : 1;
            while('0'<= str[i] && str[i] <= '9') 
            {
                result = result*10 + (str[i++]-'0');
                if(result*indicator >= INT_MAX) return INT_MAX;
                if(result*indicator <= INT_MIN) return INT_MIN;                
            }
            return result*indicator;
        }
        return 0;
    }
};
View Code

学习怎么将代码写得优雅

 

9. Palindrome Number https://leetcode.com/problems/palindrome-number/description/

class Solution {
public:
    bool isPalindrome(int x) {
        if(x<0|| (x!=0 &&x%10==0)) return false;
        int sum=0;
        while(x>sum)
        {
            sum = sum*10+x%10;
            x = x/10;
        }
        return (x==sum)||(x==sum/10);
    }
};
View Code
bool isPalindrome(int x) {
        if(x<0)
            return false;
        
        int y = x,z=0;
        
        while(y){
            z*=10;
            z+=(y%10);
            y=y/10;
        }
        
        if(x==z)
            return true;
        
        return false;
    }
View Code

优化方法、倒置整个数或是只倒置一半

 

12. Integer to Roman https://leetcode.com/problems/integer-to-roman/description/

class Solution {
public:
    string intToRoman(int num) {
        string M[] = {"", "M", "MM", "MMM"};
        string C[] = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
        string X[] = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
        string I[] = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
        return M[num/1000] + C[(num%1000)/100] + X[(num%100)/10] + I[num%10];
    }
};
View Code

 

13. Roman to Integer https://leetcode.com/problems/roman-to-integer/description/

class Solution {
public:
    int romanToInt(string s) {
        map<char,int> m = {{'I',1},{'V',5},{'X',10},{'L',50},{'C',100},{'D',500},{'M',1000}};
        int result = 0;
        int i=0;
        for(;i<s.size()-1;i++){
            if(m[s[i]]<m[s[i+1]]){
                result = result + m[s[i+1]] - m[s[i]]; 
                i = i+1;
            }else{
                result = result + m[s[i]];
            }
        }
        if(i == s.size()-1)
            result = result+m[s[i]];
        return result;
    }
};
View Code

 

29. Divide Two Integers https://leetcode.com/problems/divide-two-integers/description/

class Solution {
public:
    int divide(int dividend, int divisor) {
        long long m = abs((long long)dividend), n = abs((long long)divisor), res = 0;
        int sign = ((dividend < 0) ^ (divisor < 0)) ? -1 : 1;
        while (m >= n) {
            long long t = n, p = 1;
            while (m >= (t << 1)) {
                p <<= 1;
                t <<= 1;
            }
            res += p;
            m -= t;
        }
        if (res == (long long)INT_MAX+1 && sign==1) return INT_MAX;
        return sign > 0 ? res : -res;
    }
};
View Code

如果是INT_MIN除以-1,则会溢出,必须返回INT_MAX

学习一下代码的简洁写法

 

43. Multiply Strings https://leetcode.com/problems/multiply-strings/description/

class Solution {
public:
string mul(string s, char c) {
    int add = 0;
    for (int i = s.size() - 1; i >= 0; i--) {
        int r = ((s[i] - '0')*(c - '0') + add) % 10;
        add = ((s[i] - '0')*(c - '0') + add) / 10;
        s[i] = r + '0';
    }
    if (add != 0)
        s.insert(s.begin(), add + '0');
    return s;
}

string add(string num1, string num2) {
    string result = "";
    int pos1 = num1.size() - 1;
    int pos2 = num2.size() - 1;
    int add = 0;
    while (pos1 >= 0 || pos2 >= 0) {
        int n1 = 0;
        int n2 = 0;
        if (pos1 >= 0) {
            n1 = num1[pos1--]-'0';
        }
        if (pos2 >= 0) {
            n2 = num2[pos2--]-'0';
        }
        int r = (n1 + n2 + add) % 10;
        add = (n1 + n2 + add) / 10;
        result.insert(result.begin(),r+'0');
    }
    if(add!=0)
        result.insert(result.begin(), add + '0');
    return result;
}

string multiply(string num1, string num2) {
    string result = "";
    for (int i = 0; i < num2.size(); i++) {
        result = add(result,mul(num1, num2[i]));
        result.insert(result.end(), '0');
    }
    result.erase(result.end()-1);
    int pos = 0;
    while(pos<result.size()&&result[pos]=='0'){
        pos++;
    }
    result.erase(result.begin(),result.begin()+pos);
    if(result == "")
        return "0";
    return result;
}
};
View Code

 

 50. Pow(x, n) https://leetcode.com/problems/powx-n/description/

class Solution {
public:
    double myPow(double x, int n) {
        if(n==0) return 1;
    if(n==1) return x;
    if(n==-1) return 1.0/x;
    double tmp = myPow(x, n/2);
    if(n%2==0) {
        return tmp*tmp;
    }
    if(n>0) {
        return tmp*tmp*x;
    }
    return tmp*tmp/x;
    }
};
View Code

 

 60. Permutation Sequence https://leetcode.com/problems/permutation-sequence/description/

class Solution {
public:
    int getn(int n) {
    int result = 1;
    for (int i = 1; i <= n; ++i)
        result = result * i;
    return result;
}
string getPermutation(int n, int k) {
    --k;
    map<int, int> m = { {1,1},{2,1},{3,1},{4,1},{5,1},{6,1},{7,1},{8,1},{9,1} };
    string result = "";
    for (int i = 1; i <= n; ++i) {
        int pos;
        //除的方式到最后两项就不成立了,当剩余两项的时候,直接赋值
        if (n - i > 1)
            pos = k / (getn(n - i)) + 1;
        else if (n - i == 1)
            pos = k + 1;
        else if (n - i == 0)
            pos = 1;
        int j = 0;
        //寻找第pos个数,如果遇到map中第二个数为0,则表示该数已经被用过了
        for (; j < pos; ++j) {
            if (m[j+1] == 0)
                ++pos;
        }
        result += to_string(j);
        m[j] = 0;
        if(n - i > 1)
            k = k % getn(n - i);
    }
    return result;
}
};
View Code

 

 66. Plus One https://leetcode.com/problems/plus-one/description/

class Solution {
public:
    vector<int> plusOne(vector<int>& digits) {
        int i=digits.size()-1;
        for(;i>=0;i--){
            if(digits[i] == 9){
                digits[i] = 0;
            }else{
                digits[i] = digits[i]+1;
                break;
            }
        }
        if(i == -1)
            digits.insert(digits.begin(),1);
        return digits;
    }
};
View Code

 

67. Add Binary https://leetcode.com/problems/add-binary/description/

class Solution {
public:
    string addBinary(string a, string b) {
                string ret = "";
                int carry = 0;
                for (int i = a.size() - 1, j = b.size() - 1; i >= 0 || j >= 0; i--, j--) {
                        int m = (i >= 0 && a[i] == '1');
                        int n = (j >= 0 && b[j] == '1');
                        ret = to_string((m + n + carry) & 0x1) + ret;
                        carry = (m + n + carry) >> 1;
                }
                return carry ? '1' + ret : ret;
        }

};
View Code

 

69. Sqrt(x) https://leetcode.com/problems/sqrtx/description/

class Solution {
public:
    int mySqrt(int x) {
        long long pos1 = 0;
        long long pos2 = x;
        long long result = x;
        while(pos1<pos2){
            long long middle = (pos1+pos2)/2+1;
            if(middle*middle == result)
                return middle;
            else if(middle*middle < result){
                pos1 = middle;
            }else{
                pos2 = middle-1;
            }
        }
        return pos1;
    }
};
View Code

 

166. Fraction to Recurring Decimal https://leetcode.com/problems/fraction-to-recurring-decimal/description/

class Solution {
public:
    string fractionToDecimal(int numerator, int denominator) {
        if (!numerator) return "0";
        string res;
        if (numerator < 0 ^ denominator < 0) res += '-';
        long numer = numerator < 0 ? (long)numerator * (-1) : (long)numerator;
        long denom = denominator < 0 ? (long)denominator * (-1) : (long)denominator;
        long integral = numer / denom;
        res += to_string(integral);
        long rmd = numer % denom;
        if (!rmd) return res;
        res += '.';
        rmd *= 10;
        unordered_map<long, long> mp; 
        while (rmd) {
            long quotient = rmd / denom;
            if (mp.find(rmd) != mp.end()) { 
                res.insert(mp[rmd], 1, '(');
                res += ')';
                break;
            }
            mp[rmd] = res.size();
            res += to_string(quotient);
            rmd = (rmd % denom) * 10;
        }
        return res;
    }
};
View Code

 

168. Excel Sheet Column Title https://leetcode.com/problems/excel-sheet-column-title/description/

class Solution {
public:
    string convertToTitle(int n) {
        string res;
    char tmp;
    while (n) {
        n -= 1;
        tmp = 'A' + n % 26;
        res = tmp + res;
        n /= 26;
    }
    return res;
    }
};
View Code

 

171. Excel Sheet Column Number https://leetcode.com/problems/excel-sheet-column-number/description/

class Solution {
public:
    int titleToNumber(string s) {
        int result = 0;
    int times = 0;
    for (int i = s.size() - 1; i >= 0; i--) {
        result = result + (s[i] - 'A' + 1)*pow(26, times++);
    }
    return result;
    }
};
View Code

 

172. Factorial Trailing Zeroes https://leetcode.com/problems/factorial-trailing-zeroes/description/

class Solution {
public:
    int trailingZeroes(int n) {
        int result = 0;
    for (long long t = 5; t <= n; t= t*5) {
        result += n / t;
    }
    return result;
    }
};
View Code

 

204. Count Primes https://leetcode.com/problems/count-primes/description/

class Solution {
public:
    int countPrimes(int n) {
        bool* isPrime = new bool[n];
        for(int i = 2; i < n; i++){
            isPrime[i] = true;
        }
        for(int i = 2; i*i < n; i++){
            if (!isPrime[i])
                continue;
            for(int j = i * i; j < n; j += i){
                isPrime[j] = false;
            }
        }
        int count = 0;
   for (int i = 2; i < n; i++) {
      if (isPrime[i]) count++;
   }
   return count;
    }
};
View Code

 

223. Rectangle Area https://leetcode.com/problems/rectangle-area/description/

class Solution {
public:
    int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
        int area1 = abs(D-B)*abs(C-A);
        int area2 = abs(H-F)*abs(G-E);
        if(C<E || A>G || H<B || F>D)
            return area1+area2;
        int lengthright = min(C,G);
        int lengthleft = max(A,E);
        int hightop = min(D,H);
        int highbuttom = max(F,B);
        int area3 = abs(lengthright-lengthleft)*abs(hightop-highbuttom);
        return area1+area2-area3;
    }
};
View Code

 

231. Power of Two https://leetcode.com/problems/power-of-two/description/

class Solution {
public:
    bool isPowerOfTwo(int n) {
        return n > 0 && !(n & (n - 1));
    }
};
View Code

 

258. Add Digits https://leetcode.com/problems/add-digits/description/

class Solution {
public:
    int addDigits(int num) {
        while(num>=10){
            int result = 0;
            while(num>0){
                result = result + num%10;
                num = num/10;
            }
            num = result;
        }
        return num;
    }
};
View Code

 

263. Ugly Number https://leetcode.com/problems/ugly-number/description/

class Solution {
public:
    bool isUgly(int num) {
        if(num == 0) return false;
        while(num!=1){
            bool div = false;
            if(num%2==0){
                num = num/2;
                div = true;
            }
            if(num%3==0){
                num = num/3;
                div = true;
            }
            if(num%5==0){
                num = num/5;
                div = true;
            }
            if(div==false)
                return false;
        }
        return true;
    }
};
View Code

 

264. Ugly Number II https://leetcode.com/problems/ugly-number-ii/description/

class Solution {
public:
    int nthUglyNumber(int n) {
        if (n<=0) return -1;
        vector<int> q(n);
        int t2(0),t3(0),t5(0);
        q[0]=1;
        for (int i=1;i<n;++i){
            q[i]=min(q[t2]*2,min(q[t3]*3,q[t5]*5));
            if (q[i]==q[t2]*2) ++t2;
            if (q[i]==q[t3]*3) ++t3;
            if (q[i]==q[t5]*5) ++t5;
        }
        return q[n-1];
    }
};
View Code

思路记住,维护3个pos,分别表示乘以3个质数后大于当前最大uglynumber的最小数,之后需要更新pos

 

 279. Perfect Squares https://leetcode.com/problems/perfect-squares/description/

两种动态规划的思路

class Solution {
public:
    int numSquares(int n) {
        vector<int> dp(1, 0);
        while (dp.size() <= n) {
            int m = dp.size(), val = INT_MAX;
            for (int i = 1; i * i <= m; ++i) {
                val = min(val, dp[m - i * i] + 1);
            }
            dp.push_back(val);
        }
        return dp.back();
    }
};
View Code
class Solution {
public:
    int numSquares(int n) {
        vector<int> dp(n + 1, INT_MAX);
        dp[0] = 0;
        for (int i = 0; i <= n; ++i) {
            for (int j = 1; i + j * j <= n; ++j) {
                dp[i + j * j] = min(dp[i + j * j], dp[i] + 1);
            }
        }
        return dp.back();
    }
};
View Code

 

313. Super Ugly Number https://leetcode.com/problems/super-ugly-number/description/

class Solution {
public:
    int nthSuperUglyNumber(int n, vector<int>& primes) {
        vector<int> index(primes.size(), 0);
    vector<int> v = { 1 };
    for (int i = 0; i<n-1; i++) {
        int mi = INT_MAX;
        for (int i = 0; i<primes.size(); i++) {
            mi = min(mi, primes[i] * v[index[i]]);
        }
        v.push_back(mi);
        for (int i = 0; i<primes.size(); i++) {
            while (primes[i] * v[index[i]]<=mi)
                index[i]++;
        }
    }
    return v.back();
    }
};
View Code

 

319. Bulb Switcher https://leetcode.com/problems/bulb-switcher/description/

class Solution {
public:
    int bulbSwitch(int n) {
        return sqrt(n);
    }
};
View Code

 

326. Power of Three https://leetcode.com/problems/power-of-three/description/

class Solution {
public:
    bool isPowerOfThree(int n) {
        if(n==0) return false;
        while(n%3==0){
            n = n/3;
        }
        if(n==1) return true;
        else return false;
    }
};
View Code

 

343. Integer Break https://leetcode.com/problems/integer-break/description/

class Solution {
public:
    int integerBreak(int n) {
        int result = 1;

        if (n <= 4) 
            return n == 4? 4: n-1;

        while (n > 4) {
            result *= 3;
            n -= 3;
        }

        return result * n;
    }
};
View Code

 

357. Count Numbers with Unique Digits https://leetcode.com/problems/count-numbers-with-unique-digits/description/

class Solution {
public:
    int permutation(int n, int r)
    {
        if(r == 0)
        {
            return 1;
        }else{
            return n * permutation(n - 1, r - 1);
        }
    }
    int countNumbersWithUniqueDigits(int n) {
        int sum = 1;
        if(n > 0)
        {
           int end = (n > 10)? 10 : n;
           for(int i = 0; i < end; i++)
           {
               sum += 9 * permutation(9, i);
           }
        }
        return sum;
    }
};
View Code

 

365. Water and Jug Problem https://leetcode.com/problems/water-and-jug-problem/description/

class Solution {
public:
    bool canMeasureWater(int x, int y, int z) {
        return z == 0 || (x + y >= z && z % gcd(x, y) == 0);
    }
    int gcd(int x, int y) {
        return y == 0 ? x : gcd(y, x % y);
    }
};
View Code

 

367. Valid Perfect Square https://leetcode.com/problems/valid-perfect-square/description/

class Solution {
public:
    bool isPerfectSquare(int num) {
        if(int(sqrt(num))*int(sqrt(num)) == num)
            return true;
        else 
            return false;
    }
};
View Code

 

368. Largest Divisible Subset https://leetcode.com/problems/largest-divisible-subset/description/

class Solution {
public:
    vector<int> largestDivisibleSubset(vector<int>& nums) {
        if(nums.size()==0) return vector<int>();
        sort(nums.begin(), nums.end());
    vector<int> v(nums.size(),1);
    vector<int> path(nums.size(), 0);
    int maxnum = 1;
    int maxpos = 0;
    for (int i = 1; i < nums.size(); i++) {
        for (int j = 0; j < i; j++) {
            if (nums[i] % nums[j] == 0 && v[i] < v[j] + 1) {
                v[i] = v[j] + 1;
                path[i] = j;
                if (v[i] > maxnum) {
                    maxnum = v[i];
                    maxpos = i;
                }
            }
        }
    }
    vector<int> result;
    for (int i = 0; i < maxnum; i++) {
        result.push_back(nums[maxpos]);
        maxpos = path[maxpos];
    }
    return result;
    }
};
View Code

动态规划,n的子集的个数用v[n]表示,等于之前能被整除的最大数代表的子集+1,每次i渠道一个新值,就在前面寻找所有能被该数整除的数j,v[j]表示该数的子集数

还用到了path来保存路径

 

 372. Super Pow https://leetcode.com/problems/super-pow/description/

class Solution {
    const int base = 1337;
    int powmod(int a, int k) //a^k mod 1337 where 0 <= k <= 10
    {
        a %= base;
        int result = 1;
        for (int i = 0; i < k; ++i)
            result = (result * a) % base;
        return result;
    }
public:
    int superPow(int a, vector<int>& b) {
        if (b.empty()) return 1;
        int last_digit = b.back();
        b.pop_back();
        return powmod(superPow(a, b), 10) * powmod(a, last_digit) % base;
    }
};
View Code

 

 

 

 

 

 

8

9

29

50

60

66

69

204

231

264

279

313

319

357

368

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!