移动零
cpp
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int l = 0;
for (int i = 0; i < nums.size(); i++) {
if (nums[i] != 0) {
swap(nums[i], nums[l]);
l++;
}
}
}
};
判断子序列
cpp
class Solution {
public:
bool isSubsequence(string s, string t) {
if (s.size() == 0) {
return true;
}
if (s.size() > t.size()) {
return false;
}
int currS = 0, currT = 0;
while (currT < t.size() && currS < s.size()) {
if (s[currS] == t[currT]) {
currS++;
}
currT++;
}
return currS == s.size() && currT <= t.size();
}
};
盛最多水的容器
cpp
class Solution {
public:
int maxArea(vector<int>& height) {
int left = 0, right = height.size() - 1;
int maxV = 0;
while (left < right) {
int w = right - left;
int h = min(height[left], height[right]);
maxV = max(maxV, h * w);
if (height[left] <= height[right]) {
left++;
} else {
right--;
}
}
return maxV;
}
};
K和数对的最大数目
cpp
class Solution {
public:
int maxOperations(vector<int>& nums, int k) {
int count = 0;
int left = 0, right = nums.size() - 1;
sort(nums.begin(), nums.end());
while (left < right) {
if (nums[left] + nums[right] == k) {
count++;
left++;
right--;
} else if (nums[left] + nums[right] < k) {
left++;
} else {
right--;
}
}
return count;
}
};