[日常刷题]leetcode第十六天

版权声明:希望各位多提意见多多互相交流哦~ https://blog.csdn.net/wait_for_taht_day5/article/details/82847232

171. Excel Sheet Column Number

Given a column title as appear in an Excel sheet, return its corresponding column number.

For example:

    A -> 1
    B -> 2
    C -> 3
    ...
    Z -> 26
    AA -> 27
    AB -> 28 
    ...

Example 1:

Input: "A"
Output: 1

Example 2:

Input: "AB"
Output: 28

Example 3:

Input: "ZY"
Output: 701

Solution in C++:

关键点:

  • 对字符串处理 && 26进制表示

思路:

  • 就是昨天那题的逆命题昨天还需要主要0-25对应,今天这题就是纯26进制转10进制。就是26进制的表示方式是自己定义的。
int titleToNumber(string s) {
        map<char,int> maps{{'A',1},{'B',2},{'C',3},{'D',4},{'E',5},{'F',6},{'G',7},{'H',8},{'I',9},{'J',10},{'K',11},{'L',12},{'M',13},                                  {'N',14},{'O',15},{'P',16},{'Q',17},{'R',18},{'S',19},{'T',20},{'U',21},{'V',22},{'W',23},{'X',24},{'Y',25},                                  {'Z',26}};
        size_t size = s.size();
        int sum = 0;
        for(int i = 0; i < size; ++i){
            sum = sum * 26 + maps[s[i]];
        }
        return sum;
    }

172. Factorial Trailing Zeroes

Given an integer n, return the number of trailing zeroes in n!.

Example 1:

Input: 3
Output: 0
Explanation: 3! = 6, no trailing zero.

Example 2:

Input: 5
Output: 1
Explanation: 5! = 120, one trailing zero.

Note: Your solution should be in logarithmic time complexity.

Solution in C++:

关键点:

  • 遍历步长>=2

思路:

  • 当看到复杂度要求logn的时候,就知道至少步长为2去遍历才行。然后最后的0来自于所乘得到的10的个数,但是10又来自于2和5;=>所以就是数n中含有2和5的倍乘个数,但是如果n包含5那么一定会包含2,=>所以会取其中的最小值,即只用求5的倍乘个数即可。这里的一个特殊情况是25 * 4 = 100,=>所以需要注意,5,55,55*5这些情况。就是要求n中因数包括5的个数,这里i会爆掉(5^13 > INT_MAX/5),所以需要注意类型为long long
int trailingZeroes(int n) {
        
        int result = 0;
        for(long long i = 5; n / i > 0; i *= 5)
            result += n/i;

        return result;
     
    }

175. Combine Two Tables(乱入mysql)

Table: Person

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| PersonId    | int     |
| FirstName   | varchar |
| LastName    | varchar |
+-------------+---------+
PersonId is the primary key column for this table.

Table: Address

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| AddressId   | int     |
| PersonId    | int     |
| City        | varchar |
| State       | varchar |
+-------------+---------+
AddressId is the primary key column for this table.

Write a SQL query for a report that provides the following information for each person in the Person table, regardless if there is an address for each of those people:

FirstName, LastName, City, State

Solution in C++:

关键点:

  • 没有匹配的也需要显示

思路:

  • 开始不写了运行一下还不知道是都需要显示,后来就知道用左连接去写查询了
select FirstName,LastName,City,State from Person LEFT JOIN Address ON Person.PersonId = Address.PersonId

小结

今天还是很有收获的,特别是在第二题上,让我感受到了一步一步优化的乐趣。然后由于没有点算法专题,最后乱入了一个mysql的题,我还以为算法要刷完了,一阵开心,后来一看911题。。。任重道远啊。

知识点

  • logn复杂度优化思路
  • mysql左连接查询

猜你喜欢

转载自blog.csdn.net/wait_for_taht_day5/article/details/82847232