4.28LeetCode

4.28LeetCode

38. Count and Say

  1. 报数
    emmmmm.题目比较难读懂,读懂很简单啦。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
public:
string countAndSay(int n) {
string res="1";
for(int i=1;i<n;i++)
res=next(res);
return res;
}
string next(string n) {
int i=0;
string res;
while(i<n.length()){
char temp=n[i];
int num=1;
while(1){
if(i+1!=n.length()&&n[i+1]==n[i])
{
num++;
i++;
}
else break;
}
res+=to_string(num);
res+=temp;
i++;
}
return res;
}
};

237. Delete Node in a Linked List

  1. 删除链表中的节点
    感觉还是思路被桎梏了哈哈,说到删除节点第一时间想的永远是让被删除的前一个结点next指向被删除的next,为什么不换个思路去重新生成从被删除开始之后的整个链表呢
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
void deleteNode(ListNode* node) {
ListNode* p=node;
while(p->next){
p->val=p->next->val;
p=p->next;
}
while(node->next!=p)
node=node->next;
node->next=nullptr;
return;
}
};

88. Merge Sorted Array

  1. 合并两个有序数组
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
int i=0,j=0;
vector<int> temp;
while(i<m&&j<n){
if(nums1[i]<=nums2[j])
{
temp.push_back(nums1[i]);
i++;
}else{
temp.push_back(nums2[j]);
j++;
}
}
if(i!=m){
while(i!=m){
temp.push_back(nums1[i]);
i++;
}
}
if(j!=n){
while(j!=n){
temp.push_back(nums2[j]);
j++;
}
}
i=0;
for(int it:temp){
nums1[i]=it;
i++;
}
return;
}
};

70. Climbing Stairs

爬楼梯
斐波那契数列。。

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
int climbStairs(int n) {
if(n==1) return 1;
vector<int> dp;
dp.resize(n);
dp[0]=1;dp[1]=2;
for(int i=2;i<n;i++)
dp[i]=dp[i-1]+dp[i-2];
return dp[n-1];
}
};

53. Maximum Subarray

  1. 最大子序和
    这题实在是太难了。。。想了一上午都没想明白,说到底还是自己太菜了。。。到现在也只是勉强能理解标准答案。
    评论区大佬解答:这道题难度不该是easy 这道题的一开始我想到的是暴力的滑窗去做,复杂度O(n^2),显然达不到题目中要求的复杂度 这道题根据题目关键词,“最大”“连续”,可以判断是一道动态规划,附上这道题目的wiki链接https://zh.wikipedia.org/wiki/%E6%9C%80%E5%A4%A7%E5%AD%90%E6%95%B0%E5%88%97%E9%97%AE%E9%A2%98 方法如下:
    1.定义一个函数f(n),以第n个数为结束点的子数列的最大和,存在一个递推关系f(n) = max(f(n-1) + A[n], A[n]);
    2.将这些最大和保存下来后,取最大的那个就是,最大子数组和。因为最大连续子数组 等价于 最大的以n个数为结束点的子数列和
1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int tempmax,res;
res=nums[0];
tempmax=0;
for(int i=0;i<nums.size();i++){
tempmax=max(tempmax+nums[i],nums[i]);
res=max(res,tempmax);
}
return res;
}
};

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×