7.双指针(two pointer)

  1. Container With Most Water
      Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
    Note: You may not slant the container and n is at least 2.
    Input: [1,8,6,2,5,4,8,3,7]
    Output: 49
int maxArea(vector<int>& height) {
    int n=height.size();
    int ans = INT_MIN;
    int i=0, j=n-1;
    while(i<j){
        ans = max(ans, (j-i)*min(height[i], height[j]));
        if(height[i]<height[j]){
            i++;
        }else{
            j--;
        }
    }
    return ans;
}
  1. 3Sum
      Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
    Given array nums = [-1, 0, 1, 2, -1, -4],
    A solution set is:
    [
    [-1, 0, 1],
    [-1, -1, 2]
    ]
vector<vector<int>> threeSum(vector<int>& nums) {
    set<vector<int>> s;
    sort(nums.begin(), nums.end());
    int n=nums.size();
    for(int i=0;i<=n-3;i++){
        int l=i+1, r=n-1, sum = -nums[i];
        while(l<r){
            if(nums[l]+nums[r]<sum){
                l++;
            }else if(nums[l]+nums[r]>sum){
                r--;
            }else{
                s.insert({nums[i], nums[l], nums[r]});
                l++;
                r--;
            }
        }
    }
    vector<vector<int>> ans;
    for(auto a: s) ans.push_back(a);
    return ans;
}
  1. Trapping Rain Water
      Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
    Input: [0,1,0,2,1,0,1,3,2,1,2,1]
    Output: 6
int trap(vector<int>& height) {
    int n=height.size();
    if(n<=2) return 0;
    int leftMax = height[0];
    int rightMax = height[n-1];
    int ans=0;
    int L=1, R=n-2;
    while(L<=R){
        if(leftMax<=rightMax){
            ans+=max(leftMax-height[L], 0);
            leftMax = max(leftMax, height[L++]);
        }else{
            ans+=max(rightMax-height[R], 0);
            rightMax = max(rightMax, height[R--]);
        }
    }
    return ans;
}
原文地址:https://www.cnblogs.com/wangzi199/p/13601482.html