leetcode-数组

11. Container With Most Water

//?
class Solution {
public:
    int maxArea(vector<int>& height) {
        int maxarea = 0;
        int l = 0, r = height.size()-1;
        if(height.size()<2) return maxarea;

        while(l<r){
            maxarea = max(maxarea, min(height[l],height[r])*(r-l));
            if(height[l]<height[r])
                l++;
            else
                r--;
        }
                
        return maxarea;
    }
};
//Brute Force --Time Limit Exceed
/*class Solution {
public:
    int maxArea(vector<int>& height) {
        int maxarea = 0;
        if(height.size()<2) return maxarea;
        for(int i=0; i<height.size()-1; i++){
            for(int j=i+1; j<height.size(); j++)
                maxarea = max(maxarea, min(height[i],height[j])*(j-i));
        }
        return maxarea;
    }
};*/

 

16. 3Sum Closest //最接近target的 三数和

class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
        if(nums.size()<3) return 0;
        if(nums.size() == 3) return nums[0]+nums[1]+nums[2];
        sort(nums.begin(), nums.end());
        //int diff = abs(nums[0]+nums[1]+nums[2]-target);
        int diff = INT_MAX;
        //int sum = 0, front, end, ret=diff;
        int sum = 0, front, end, ret=0;
        for(int i=0; i<nums.size(); i++){
            front = i+1;
            end = nums.size()-1;
            while(front<end){
                sum = nums[i]+nums[front]+nums[end];
                if(sum == target) return target;
                if(abs(sum-target)<diff){
                    diff = abs(sum-target);
                    ret = sum;
                }
                (sum > target) ? end-- : front++;
            }
        }
        return ret;
    }
};

  

猜你喜欢

转载自www.cnblogs.com/feliz/p/11145194.html