Algo_3_Two_Pointer
學習算法
Leetcode 167
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
int left = 0;
int right = numbers.size()-1;
int total = 0;
while(left < right){
total = numbers[left] + numbers[right];
if(total == target ){
return {left+1,right+1};
}else if(total > target) {
right--;
}else{
left++;
}
}
return {-1,-1};
}
};
Leetcode 125
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
bool isPalindrome(string s)
{
int start = 0;
int end = s.size() - 1;
while (start <= end)
{
if (!isalnum(s[start]))
{
start++;
continue;
}
if (!isalnum(s[end]))
{
end--;
continue;
}
if (tolower(s[start]) != tolower(s[end]))
{
return false;
}else{
start++;
end--;
}
}
return true;
}
};
Leetcode 15
思路
- 使用i指針指向頭
- 分別使用slow和fast快慢指針去尋找和nums[i]相加為0的數
- 判斷假設當前數字和前一個相同,直接移動slow,避免出現重複答案
while (nums[slow] == nums[slow - 1] && slow < fast) {
slow++;
}
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
vector<vector<int>> threeSum(vector<int> &nums)
{
vector<vector<int>> res;
sort(nums.begin(), nums.end());
for (int i = 0; i < nums.size(); i++)
{
if (i > 0 && nums[i] == nums[i - 1])
{
continue;
}
int slow = i + 1;
int fast = nums.size() - 1;
while (slow < fast)
{
int total = nums[i] + nums[slow] + nums[fast];
if (total > 0)
{
fast--;
}
else if (total < 0)
{
slow++;
}
else
{
res.push_back({nums[i], nums[slow], nums[fast]});
slow++;
while (nums[slow] == nums[slow - 1] && slow < fast)
{
slow++;
}
}
}
}
return res;
}
};
Leetcode 11
class Solution {
public:
int maxArea(vector<int>& height) {
int r = height.size()-1;
int l = 0;
int w = 0;
while(l < r) {
w = max(w, (r-l)*min(height[l],height[r]));
height[l] < height[r] ? l++ : r--;
}
return w;
}
};
Leetcode 42
class Solution {
public:
int trap(vector<int>& height) {
int l = 0;
int r = height.size()-1;
int w = 0;
int lmax = height[l];
int rmax = height[r];
while(l < r){
if(lmax < rmax){
l++;
lmax = max(lmax,height[l]);
w += lmax - height[l];
}else{
r--;
rmax = max(rmax,height[r]);
w += rmax - height[r];
}
}
return w;
}
};