沉迷于奇奇怪怪的东西过久已经不会写算法了...不管学什么基础还是要打好的,先回来刷一波LeetCode省得出去给学校丢人
C++ Main
1. 两数之和(简单):
知识点:创建map, map.count, map[]
首先想到的是暴力O(n^2),查看了下题解发现可以用map优化到O(n)
默认框架差点把我这个STL学艺不精的人吓懵了
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> nap;
for(int i=0;i<nums.size();i++)
{
int complement = target - nums[i];
if(nap.count(complement))
return {nap[complement], i};
nap[nums[i]] = i;
}
return {};
}
};
2. 两数相加(中等):
知识点:链表,指针,高精度加法
思路就是高精度加法运算。官方JAVA解答没有用指针,此处C++稍作修改。
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* cur = new ListNode(0);
ListNode* dummyHead = cur, *a = l1, *b = l2;
int carry = 0;
while(a != NULL || b != NULL){
int x = (a != NULL) ? a->val : 0;
int y = (b != NULL) ? b->val : 0;
int sum = x + y + carry;
carry = sum / 10;
cur->next = new ListNode(sum % 10);
cur = cur->next;
if(a != NULL) a = a->next;
if(b != NULL) b = b->next;
}
if(carry != 0)
cur->next = new ListNode(1);
return dummyHead->next;
}
};
7. 反转整数(简单):
知识点:整数拆分,int范围和溢出
需要注意abs(INT_MIN) < 0
class Solution {
public:
int reverse(int x) {
int x_abs = abs(x);
if(x_abs <= 0)
return 0;
int fuhao = x_abs / x;
long long int ans = 0;
while(x_abs) {
int c = x_abs % 10;
x_abs /= 10;
ans *= 10;
ans += c;
//cout << ans<<" ";
if(ans > INT_MAX)
return 0;
}
return fuhao * ans;
}
};
9. 回文数(简单):
知识点:整数拆分
class Solution {
public:
bool isPalindrome(int x) {
if(x < 0)
return 0;
int wei[11] = {-1};
int cnt = 0;
while(x) {
wei[++cnt] = x % 10;
x /= 10;
}
for(int i = 1; i <= cnt-i+1; i++)
if(wei[i] != wei[cnt - i + 1])
return 0;
return 1;
}
};
26. 删除排序数组中的重复项(简单)
知识点:vector.size、unique、sort、erase
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
vector<int>::iterator end;
sort(nums.begin(), nums.end());
end = unique(nums.begin(),nums.end());
nums.erase(end,nums.end());
return nums.size();
}
};
27. 移除元素(简单):
知识点:vector的iterator、erase
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
for(vector<int>::iterator it=nums.begin(); it!=nums.end();) {
if(*it == val)
it = nums.erase(it);
else
it++;
}
return nums.size();
}
};
35. 搜索插入位置(简单):
知识点:vector的iterator
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int cnt = -1;//因为位置从0开始所以cnt初始化为-1
for(vector<int>::iterator it = nums.begin();it != nums.end();) {
cnt++;
if(*it >= target)
return cnt;
else
it++;
}
return cnt+1;
}
};