LeetCode011 Container With Most Water

详细见:leetcode.com/problems/container-with-most-water/


Java Solution: github

package leetcode;


public class P011_ContainerWithMostWater {

	
	/**
	 * @author      zxwtry
	 * @email       zxwtry@qq.com
	 * @project     OJ
	 * @package     leetcode
	 * @file        P011_ContainerWithMostWater.java
	 * @type        Solution5
	 * @date        2016年12月8日 下午3:29:46
	 * @details     86.76% 8ms AC
	 */
	static class Solution5 {
		public int maxArea(int[] h) {
			if (h == null || h.length < 2) return 0;
			int l = 0, r = h.length - 1, ans = 0, k = 0;
			while (l < r) {
				ans = Math.max(Math.min(h[l], h[r]) * (r - l), ans);
				if (h[l] < h[r]) {
					k = l;
					while (k < r && h[k] <= h[l]) k ++;
					l = k;
				} else {
					k = r;
					while (k > l && h[k] <= h[r]) k --;
					r = k;
				}
			}
			return ans;
		}
	}
	
	
}

C Solution: github

/*
    url: leetcode.com/problems/container-with-most-water/
    13ms 18.14%
*/

#include <stdio.h>
#include <stdlib.h>

int maxArea(int* h, int s) {
    int l = 0, r = s - 1, a = 0, k = 0;
    while (l < r) {
        a = max(a, min(*(h + l), *(h + r)) * (r - l));
        if (*(h + l) > *(h + r)) {
            do {
                r --;
            } while (r > l && *(h + r) <= *(h + r + 1));
        } else {
            do {
                l ++;
            } while (l < r && *(h + l) <= *(h + l - 1));
        }
    }
    return a;
}
int main() {
    int h[] = {0, 5, 2, 3, 4, 1};
    int s = 6;
    printf("answer is %d\r\n", maxArea(h,s));
}

Python Solution: github

#coding=utf-8

'''
    url: leetcode.com/problems/container-with-most-water/
    @author:     zxwtry
    @email:      zxwtry@qq.com
    @date:       2017年3月27日
    @details:    Solution: AC 78ms 71.02%
'''

class Solution(object):
    def maxArea(self, h):
        """
        :type height: List[int]
        :rtype: int
        """
        l, r = 0, len(h) - 1
        a = 0
        while l < r:
            a = max(a, min(h[l], h[r]) * (r - l))
            if h[l] < h[r]:
                while True:
                    l += 1
                    if l >= r or h[l - 1] < h[l]: 
                        break
            else:
                while True:
                    r -= 1
                    if l >= r or h[r + 1] < h[r]:
                        break
        return a

if __name__ == "__main__":
    h = [1, 9, 2, 8, 3, 7, 4, 6]
    print(Solution().maxArea(h))




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值