LeetCode Hot 100:普通数组
53. 最大子数组和
思路 1:动态规划
class Solution
{
public:int maxSubArray(vector<int> &nums){// 特判if (nums.empty())return 0;if (nums.size() == 1)return nums[0];int n = nums.size();// 状态数组vector<int> dp(n + 1, 0);// dp[i]: 以第i个元素结尾,连续子数组的最大和int maxSum = INT_MIN;// 状态转移for (int i = 1; i <= n; i++){if (dp[i - 1] > 0)dp[i] = dp[i - 1] + nums[i - 1];elsedp[i] = nums[i - 1];maxSum = max(maxSum, dp[i]);}return maxSum;}
};
空间优化:
class Solution
{
public:int maxSubArray(vector<int> &nums){// 特判if (nums.empty())return 0;if (nums.size() == 1)return nums[0];int n = nums.size();int pre = 0, cur = 0, maxSum = INT_MIN;for (int i = 0; i < n; i++){if (pre > 0)cur = pre + nums[i];elsecur = nums[i];pre = cur;maxSum = max(maxSum, cur);}return maxSum;}
};
56. 合并区间
思路 1:排序
class Solution {
public:vector<vector<int>> merge(vector<vector<int>>& intervals) {if (intervals.empty())return {};sort(intervals.begin(), intervals.end(),[](const vector<int>& i1, const vector<int>& i2) {return i1[0] < i2[0];});vector<vector<int>> ans;for (vector<int>& interval : intervals) {int left = interval[0], right = interval[1];if (ans.empty() || ans.back()[1] < left)ans.push_back({left, right});elseans.back()[1] = max(ans.back()[1], right);}return ans;}
};
189. 轮转数组
思路 1:辅助数组
class Solution {
public:void rotate(vector<int>& nums, int k) {int n = nums.size();k %= n;vector<int> ans(nums.begin() + n - k, nums.end());for (int i = 0; i < n - k; i++)ans.push_back(nums[i]);nums = ans;}
};
思路 2:数组翻转
class Solution {
public:void rotate(vector<int>& nums, int k) {k %= nums.size();reverse(nums.begin(), nums.end());reverse(nums.begin(), nums.begin() + k);reverse(nums.begin() + k, nums.end());}
};
238. 除自身以外数组的乘积
思路 1:前后缀分解
class Solution {
public:vector<int> productExceptSelf(vector<int>& nums) {int n = nums.size();vector<int> pre(n);pre[0] = nums[0];for (int i = 1; i < n; i++)pre[i] = pre[i - 1] * nums[i];vector<int> suf(n);suf[n - 1] = nums[n - 1];for (int i = n - 2; i >= 0; i--)suf[i] = suf[i + 1] * nums[i];vector<int> ans(n);for (int i = 0; i < n; i++) {int left = i == 0 ? 1 : pre[i - 1];int right = i == n - 1 ? 1 : suf[i + 1];ans[i] = left * right;}return ans;}
};
空间优化:
class Solution {
public:vector<int> productExceptSelf(vector<int>& nums) {int n = nums.size();vector<int> ans(n);ans[0] = 1;for (int i = 1; i < n; i++)ans[i] = ans[i - 1] * nums[i - 1];int mult = 1;for (int i = n - 1; i >= 0; i--) {ans[i] = ans[i] * mult;mult *= nums[i];}return ans;}
};
41. 缺失的第一个正数
思路 1:原地哈希
class Solution {
public:int firstMissingPositive(vector<int>& nums) {int n = nums.size();for (int i = 0; i < n; i++)while (nums[i] > 0 && nums[i] <= n && nums[nums[i] - 1] != nums[i])swap(nums[nums[i] - 1], nums[i]);for (int i = 0; i < n; i++)if (nums[i] != i + 1)return i + 1;return n + 1;}
};