您的位置:首页 > 其它

LeetCode 53~54

2018-03-28 10:52 260 查看

LeetCode 53. Maximum Subarray

题目:

https://leetcode.com/problems/maximum-subarray/description/

题意:

给定一个序列(至少含有 1 个数),从该序列中寻找一个连续的子序列,使得子序列的和最大。

例如,给定序列 [-2,1,-3,4,-1,2,1,-5,4],

连续子序列 [4,-1,2,1] 的和最大,为 6。

扩展练习:

若你已实现复杂度为 O(n) 的解法,尝试使用更为精妙的分治法求解。

思路:

目前会两种写法:动态规划和尺取。

动态规划:定义dp[i]dp[i]为以第ii,最后取dpdp数组中的最大值即可

尺取法:用一个变量temptemp不断的累加遍历到的数字,表示子序列的和,如果temp<0temp<0,那么一定对后面的子序列做出了负贡献,那么直接丢弃此时的值。在这个过程中记录temptemp的最大值就是答案

代码:

动态规划:

class Solution {
public:
int maxSubArray(vector<int>& nums) {
int ans = 0;
vector<int> dp(nums.size(), 0);
for(int i = 0; i < nums.size(); ++i)
{
if(i == 0) ans = dp[i] = nums[i];
else dp[i] = max(dp[i-1] + nums[i], nums[i]);
if(dp[i] > ans) ans = dp[i];
}
return ans;
}
};


尺取法:

class Solution {
public:
int maxSubArray(vector<int>& nums) {
int ans = 0, temp = 0;
for(int i = 0; i < nums.size(); ++i)
{
temp += nums[i];
if(i == 0) ans = temp;
else ans = max(ans, temp);
if(temp < 0) temp = 0;
}
return ans;
}
};


LeetCode 54. Spiral Matrix

题目:

https://leetcode.com/problems/spiral-matrix/description/

题意:

给出一个 m x n 的矩阵(m 行, n 列),请按照顺时针螺旋顺序返回元素。

例如,给出以下矩阵:

[

[ 1, 2, 3 ],

[ 4, 5, 6 ],

[ 7, 8, 9 ]

]

应该返回 [1,2,3,6,9,8,7,4,5]。

思路:

模拟就好了,没什么好说的

代码:

class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> ans;
if(matrix.size() == 0) return ans;
int left = 0, right = matrix[0].size()-1;
int top = 0, bottom = matrix.size()-1;
while(left <= right && top <= bottom)
{
for(int i = lef
a251
t; i <= right; ++i)
ans.emplace_back(matrix[top][i]);
for(int i = top+1; i < bottom; ++i)
ans.emplace_back(matrix[i][right]);
if(top < bottom)
{
for(int i = right; i >= left; --i)
ans.emplace_back(matrix[bottom][i]);
}
if(left < right)
{
for(int i = bottom-1; i > top; --i)
ans.emplace_back(matrix[i][left]);
}
++left, --right, ++top, --bottom;
}
return ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: