# 11 Container With Most Water[M

2019-03-18  本文已影响0人  BinaryWoodB

Description

tags: Array, Two Pointer

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.


image.png

The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.

Example:

Input: [1,8,6,2,5,4,8,3,7]
Output: 49

Solution

class Solution {
public:
    int maxArea(vector<int>& height) {
        int l = 0, r = height.size()-1;
        int V = 0;
        while (l < r) {
            int tempV = min(height[l], height[r]) * (r - l);
            V = max(tempV, V);
            if (height[l] <= height[r]) {
                l++;
            } else {
                r--;
            }
        }

        return V;
    }
};

Analysis

Points

  1. map::lower_bound(key), map::upper_bound(key)
  1. String的拼接
string str1 = "hello ";
string str2 = "world!";
string res1 = str1 + str2; // res1 = "hello world!"
string str1 += str2; // str1 = "hello world!"
string res2 = str1.append(str2); // res2 = "hello world!"
上一篇 下一篇

猜你喜欢

热点阅读