用unordered_set去重排序,时间复杂度为
O
(
n
)
O(n)
O(n)
对于数组中连续序列的第一个数,设置cnt初始为1,根据unordered_set查找该连续序列的长度
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
int ans = 0;
unordered_set<int> s;
for (int i = 0; i < nums.size(); ++ i) {
s.insert(nums[i]);
}
for (auto t : s) {
if (s.count(t - 1) == 0) {
int cnt = 1, cur = t;
while (s.count(cur + 1)) {
cur ++ ;
cnt ++ ;
}
ans = max(ans, cnt);
}
}
return ans;
}
};
统计0的数量,遇到非0元素,将当前元素向前移动(0的数量)
最后将数组的后(0的数量)个元素,修改为0即可
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int cnt = 0;
for (int i = 0; i < nums.size(); ++ i) {
if (nums[i] == 0) cnt ++ ;
else swap(nums[i], nums[i - cnt]);
}
for (int i = nums.size() - cnt; i < nums.size(); ++ i) {
nums[i] = 0;
}
return;
}
};
设置左右指针,每次移动数值较小的指针。因为此时,对于较小值来说,此时已经达到最优解。若移动数值较大指针,底面积将减小,而高度不变(由较小值决定),不可能出现更优解
而对于较大值来说,虽然底面积减小,但可能遇到比较小值大的值,出现更优解,直到自己成为较小值
只需在每次移动后,维护较大值即可
class Solution {
public:
int maxArea(vector<int>& height) {
int l = 0, r = height.size() - 1;
int ans = 0;
while (l < r) {
ans = max(ans, (r - l) * min(height[l], height[r]));
if (height[l] <= height[r]) l ++ ;
else r -- ;
}
return ans;
}
};