双指针问题,解题技巧:
class Solution {
public:
int maxArea(vector<int>& height) {
//双指针算法
int ans = 0;
int left =0;
int right=height.size()-1;
while(left<right)
{
int minH =min(height[left],height[right]);
ans =max(ans,(right-left)*minH);
if(height[left]>height[right])
{
right--;
}
else
{
left++;
}
}
return ans;
}
};
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
int n = nums.size();
sort(nums.begin(), nums.end());
vector<vector<int>> ans;
for(int i=0;i<n-2;i++)
{
if(i>0&&nums[i]==nums[i-1])
{
continue;
}
int right=n-1;
for(int left =i+1;left<nums.size();left++)
{
if(left>i+1&&nums[left-1]==nums[left])
{
continue;
}
while(left<right&&nums[left]+nums[right]+nums[i]>0)
{
right--;
}
if(left==right)
{
break;
}
if(nums[left]+nums[right]+nums[i]==0)
{
ans.push_back({nums[i],nums[left],nums[right]});
}
}
}
return ans;
}
};
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
if(head==nullptr)
{
return head;
}
ListNode* node =new ListNode(0,head); //找一个梢兵
ListNode* left =node;
ListNode* right =left;
ListNode* deletNode=nullptr;
for(int i=0;i<n;i++)
{
right=right->next;
if(right==nullptr)
{
break;
}
}
while(right!=nullptr&&right->next!=nullptr)
{
left=left->next;
right=right->next;
}
deletNode=left->next;
left->next=deletNode->next;
deletNode->next=nullptr;
head=node->next;
delete node;
return head;
}
};
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int ans =nums.size();
if(ans==0||ans==1)
{
return ans;
}
int left =0;
for(int right=1;right<nums.size();right++)
{
if(nums[left]!=nums[right])
{
nums[++left]=nums[right];
}
}
return left+1;
}
};
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int n =nums.size();
if(n==0)
{
return 0;
}
int left =0;
for(int right=0;right<n;right++)
{
if(nums[right]!=val)
{
nums[left++]=nums[right];
}
}
return left;
}
};
int strStr(string haystack, string needle) {
int ret =-1;
int flag =1;
int n=haystack.size();
int m=needle.size();
for(int i=0;i<=n-m;i++)
{
flag = 1;
for(int j=0;j<needle.size();j++)
{
if(haystack[i+j]!=needle[j])
{
flag=0;
break;
}
}
if(flag)
{
return i;
}
}
return ret;
}
};