Magical Thoughts

Two pointers to solve the problem of holding the most water
In fact, it's a bit similar to the rule-taking method to solve a problem with two variables (personal understanding).

public:
    int maxArea(vector<int>& height) {
        int a=0,b;
        int ans=0;
        b=height.size()-1;
        while(a<b)
        {
            
        if(height[a]<height[b])
            
        {     ans=max(ans,(b-a)*height[a]) ; a++;}
            else
            {      ans=max(ans,(b-a)*height[b])  ;b--;}
            
        }
        return ans;
    }
};

Summation of three numbers
Violence, but my initial idea was o (n_), which led to the output containing repetitive answers in different order, and then to see others sort and press the whole array back and forth with double pointers, it suddenly dawned on me.

public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        vector<vector<int>> ans;
        int n = nums.size();
        
        sort(nums.begin(),nums.end());
        for(int i = 0; i < n; ++i){
            if(i > 0 && nums[i] == nums[i-1]){
                continue;
            }
            
            int l = i + 1;
            int r = n - 1;
            
            while(l < r){
                while(l > i+1 && l < r && nums[l] == nums[l-1]){
                    l++;
                }
                while(r < n-2 &&  l < r && nums[r] == nums[r+1]){
                    r--;
                }
                if(l < r){
                    int sum = nums[i] + nums[l] + nums[r];
                    if(sum == 0){
                        vector<int> t;
                        t.push_back(nums[i]);
                        t.push_back(nums[l]);
                        t.push_back(nums[r]);
                        ans.push_back(t);
                        l++;
                        r--;
                    }else if(sum < 0){
                        l++;
                    }else{
                        r--;
                    }
                }
            }
        }
        
        return ans;
    }
};

Posted by shadiadiph on Mon, 30 Sep 2019 21:21:18 -0700