LeetCode:Plus One, Add Binary, Sqrt(x), Climbing Stairs

Plus One
Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.

"""3 ms, beats 7.49%
time: O(n)
space: O(n), 也可以改进到O(1), 比如位数变化时直接在vector开头插入一个1也行。
"""
class Solution {
public:
    vector<int> plusOne(vector<int>& digits) {
        int plus = 1;
        for (int i=digits.size()-1; i>=0; i--){
            digits[i] += plus;
            if (digits[i] >= 10){
                plus = 1;
                digits[i] = digits[i] % 10;

                if(i==0)
                {
                    vector<int> result2(digits.size()+1, 1);
                    for (int j=1; j<result2.size(); j++)
                        result2[j] = digits[i-1];
                    return result2;
                    //digits.insert(digits.begin(),1);
                }
            }
            else
                plus = 0;
        }
        return digits;
    }
};

Add Binary
Given two binary strings, return their sum (also a binary string).

For example,
a = “11”
b = “1”
Return “100”.

"""一个不行的算法
terminate called after throwing an instance of 'std::out_of_range'
  what():  stoi
  10100000100100110110010000010101111011011001101110111111111101000000101111001110001111100001101
110101001011101110001111100110001010100001101011101010000011011011001011101111001100000011011110011
"""
class Solution {
public:
    string addBinary(string a, string b) {
        int ta = stoi(a);
        int tb = stoi(b);
        int sum = ta + tb;
        string result = "";
        int temp = 0;
        if (sum == 0)
            return "0";
        while(sum){
            temp = sum % 10;
            sum /= 10;
            if (temp >= 2)
            {
                temp = temp % 2;
                sum += 1;
            }
            result.insert(result.begin(), temp);
        }
        return result;
    }
};
"""6 ms, beats 5.55%
time: O(n_max)
space: O(n_max)
"""
class Solution {
public:
    string v2string(vector<int> result, int begin, int end){
        string s;
        for (int i=begin; i<=end; i++)
            s += to_string(result[i]);
        return s;
    }
    string addBinary(string a, string b) {
        int l = max(a.length(), b.length());
        vector<int> result(l+1, 1);
        int temp = 0;
        int id = 0;
        int aa = 0;
        int bb = 0;

        for(int i=l; i>=1; i--){
            id = l-i;
            if(int(a.length())-1-id>=0) //直接用a.length()有坑,似乎0会越界
                aa = a[a.length()-1-id] - '0';
            else
                aa = 0 ;
            if(int(b.length())-1-id>=0)
                bb = b[b.length()-1-id] - '0';
            else
                bb = 0 ;

            result[i] = aa + bb + temp;
            if (result[i] >=2 ){
                temp = 1;
                result[i] = result[i] % 2;
                if (i==1)
                    return v2string(result, 0, l);
            } 
            else
                temp = 0;
        } 

        return v2string(result, 1,l);
    }
};

感觉写的比较丑,看看discussion中更简洁的代码:

"""3 ms, beats 19.76
"""
class Solution {
public:
    string addBinary(string a, string b) 
    {
        string result = "";
        int apos = a.size() - 1;
        int bpos = b.size() - 1;
        int adigit, bdigit, carry = 0;

        while (apos >= 0 || bpos >= 0 || carry == 1)
        {
            adigit = bdigit = 0;

            if (apos >= 0) adigit = a[apos--] == '1';
            if (bpos >= 0) bdigit = b[bpos--] == '1';

            // Another way: the digit is 1 if adigit + bdigit + carry == 1 or == 3, but I noticed that
            // XOR is more concise:
            result = static_cast<char>(adigit ^ bdigit ^ carry + '0') + result; 
            carry = adigit + bdigit + carry >= 2;
        }

        return result;
    }
};
"""3 ms
"""
class Solution {
public:
    string addBinary(string a, string b)
    {
        string s = "";

        int c = 0, i = a.size() - 1, j = b.size() - 1;
        while(i >= 0 || j >= 0 || c == 1)
        {
            c += i >= 0 ? a[i --] - '0' : 0;
            c += j >= 0 ? b[j --] - '0' : 0;
            s = char(c % 2 + '0') + s;
            c /= 2;
        }

        return s;
    }
};

Sqrt(x)
Implement int sqrt(int x).

"""暴力搜索, 66 ms, beats 2.92%
time O(sqrt(n))
"""
class Solution {
public:
    int mySqrt(int x) {
        for (int i=0; i<=x; i++){
            if(i*i == x)
                return i;

            if(i*i > x || i*i<0)
                return i-1;
        }
    }
};

**更快的方法:
二分查找,O(log n)。26 ms, beats 15.11%。
牛顿法, 23 ms, beats 21.06%。**

Climbing Stairs
You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

"""简单的递归。过不了。
time O(2^n)
space O(n)
"""
class Solution {
public:
    int climbStairs(int n) {
        if (n==0)
            return 0;
        if (n==1)
            return 1;
        if (n==2)
            return 2;
        if (n>2)
            return climbStairs(n-1) +climbStairs(n-2);
    }
};
"""上述程序包含了太多重复计算。用vector保存中间结果:0 ms, beats 42.8%
时空都是O(n)
"""
class Solution {
public:
    int climb(int n, vector<int> & mem){
        if (n==1)
            return 1;
        if (n==2)
            return 2;
        if (mem[n]!=0)
            return mem[n];
        else{
            mem[n] = climb(n-1, mem) + climb(n-2, mem);
            return mem[n];
        }
    }
    int climbStairs(int n) {
        vector<int> mem (n+1,0);
        return climb(n, mem);
    }
};
"""Dynamic Programming或Fibonacci Number,其实就是递归转迭代,6 ms, BEATS 0.44%。比前面慢?
时间O(n)
空间O(1)
"""
class Solution {
public:
    int climbStairs(int n) {
        int a = 0;
        int b = 1;
        int c = 0;
        for(int i=1; i<=n; i++){
            c = a + b;
            a = b;
            b = c;
        }
        return c;
    }
};

其他有趣的方法:Binets Method, Fibonacci Formula(解析解,高中数学或者数学竞赛这些东西玩的特别6,可惜现在有点生疏了)。
pow method takes log(n)log(n) time.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值