在官网注册后,点击题库页面就可以看到所有可以刷的题目了
可以按照难度进行筛选、建议从简单难度的题上手
两数之和: https://leetcode-cn.com/problems/two-sum/
问题描述
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> res;
bool resolve = false;
for (int i = 0; i < nums.size() - 1; i ++) {
for (int j = i + 1; j < nums.size(); j ++){
if (nums[i] + nums[j] == target) {
res.push_back(i);
res.push_back(j);
resolve = true;
break;
}
}
if (resolve) {
break;
}
}
return res;
}
};
然后提交就可以看到统计信息了
leetcode题的答案不止一种,可以根据cpu和内存使用的反馈进行调优。
2的幂: https://leetcode-cn.com/problems/power-of-two/
class Solution {
public:
bool isPowerOfTwo(long n) {
return n != 0 && (n & (n -1)) == 0;
}
};
可以在题解界面查看其它同学的解题思路
4的幂: https://leetcode-cn.com/problems/power-of-four
class Solution {
public:
bool isPowerOfFour(long n) {
return n != 0 && (n & 0xAAAAAAAA) == 0 && (n & (n -1)) == 0;
}
};
斐波拉契数: https://leetcode-cn.com/problems/fibonacci-number/
class Solution {
public:
int fib(int n) {
if (n == 0) {
return 0;
}
if (n <= 2) {
return 1;
}
int a = 1, b = 1, i = 3, res = 0;
while (i <= n) {
res = a + b;
a = b;
b = res;
i ++;
}
return res;
}
};
移除元素: https://leetcode-cn.com/problems/remove-element/
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int find = 0;
int j = nums.size();
for (int i = 0; i < j; i ++) {
cout << "i: " << i << " num:" << nums[i] << endl;
if (nums[i] == val) {
find ++;
swap(nums[i], nums[j - 1]);
j --;
i --;
}
}
return nums.size() - find;
}
};
回文数:https://leetcode-cn.com/problems/palindrome-number/
class Solution {
public:
bool isPalindrome(int x) {
int from = x;
if (x < 0) {
return false;
}
vector<int> numBits;
while (from > 0) {
numBits.insert(numBits.begin(), from % 10);
from = from / 10;
}
int res = 0;
for (int i = 0; i < numBits.size(); i ++) {
res += numBits[i] * pow(10, i);
}
if (res == x) {
return true;
} else {
return false;
}
}
};
一些注意的点
leetcode已经支持c, c++, java, php等主流编程语言编写答案了,可以选择自己擅长的语言
可以在后台看到个人的答题报表