本文主要是介绍Container With Most Water (Java实现),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
当看见这道题时想到的一个答案就是暴力破解,附上代码<span style="font-size:18px;"><span style="font-size:18px;">package com.alibaba;import java.util.Scanner;public class Solution
{public int maxArea(int[] height){int maxCapacity = 0;for(int i = 0; i < height.length - 1; i++){for(int j = i + 1; j < height.length; j++ ){if(maxCapacity < Math.min(height[i], height[j]) * (j - i))maxCapacity = Math.min(height[i], height[j]) * (j - i);}}return maxCapacity;}public static void main(String[] args){Solution s = new Solution();Scanner in = new Scanner(System.in);int num = in.nextInt() + 1;int[] height = new int[num];for(int i = 1; i < num; i++){height[i] = num;}in.close();s.maxArea(height);}
}</span></span>
结果提交之后出现Time limit exceeded;然后想了一个O(n)的算法。附上代码
<span style="font-size:18px;"><span style="font-size:18px;">package com.alibaba;import java.util.Scanner;public class Solution
{public int maxArea(int[] height){if (height.length < 2)return 0;int maxCapacity = 0;int l = 0, r = height.length - 1;while (l < r){int tmp = Math.min(height[l], height[r]) * (r - l);if (maxCapacity < tmp)maxCapacity = tmp;if (height[l] < height[r])l++;elser--;}return maxCapacity;}public static void main(String[] args){Solution s = new Solution();Scanner in = new Scanner(System.in);int num = in.nextInt();int[] height = new int[num];for (int i = 0; i < num; i++){height[i] = num;}in.close();s.maxArea(height);}
}</span>
</span>
这样就可以顺利通过了。
这篇关于Container With Most Water (Java实现)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!