leetcode上共有easy题目 道,其中部分题目及解法如下表格所示:
序号 | 题目编号及名称 | 题目描述 | 代码实现 |
---|---|---|---|
1 | 1. 两数之和 | https://leetcode.cn/problems/two-sum/ | C++ |
2 | 9. 回文数 | https://leetcode.cn/problems/palindrome-number/ | C++ |
3 | 13. 罗马数字转整数 | https://leetcode.cn/problems/roman-to-integer/ | C++ |
1.两数之和:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> hash_table;
for (int i = 0; i < nums.size(); ++i) {
unordered_map<int, int>::iterator it = hash_table.find(target - nums[i]);
if (it != hash_table.end()) {
return {it->second, i};
}
hash_table[nums[i]] = i;
}
return {};
}
};
9.回文数:
class Solution {
public:
bool isPalindrome(int x) {
// 负数不是回文数,0~9之间的数是回文数
if (x < 0) return false;
else if (x < 10) return true;
// 首先找到最高位,e.g. 121 / 100 = 1;
int div = 1;
while (x / div >= 10) div *= 10;
int y = x;
while (x > 0) {
int low_bit = x % 10; // e.g. 121 % 10 = 1
int high_bit = y / div; // e.g. 121 / 100 = 1
if (low_bit != high_bit) return false;
x /= 10; // e.g. 121 / 10 = 12
y %= div; // e.g. 121 % 100 = 21
div /= 10; // e.g. 100 / 10 = 10
}
return true;
}
};
13.罗马数字转整数:
class Solution {
private:
unordered_map<char, int> hash_table = {
{'I', 1},
{'V', 5},
{'X', 10},
{'L', 50},
{'C', 100},
{'D', 500},
{'M', 1000}
};
public:
int romanToInt(string s) {
int res = 0;
int n = s.length();
for (int i = 0; i < n; ++i) {
int value = hash_table[s[i]];
if (i < n - 1 && value < hash_table[s[i+1]]) {
res -= value;
} else {
res += value;
}
}
return res;
}
};