【LeetCode】1. 盛最多水的容器:C#三种解法
生活随笔
收集整理的這篇文章主要介紹了
【LeetCode】1. 盛最多水的容器:C#三种解法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目:https://leetcode-cn.com/problems/container-with-most-water/
盛最多水的容器
難度:中等
給你 n 個非負整數 a1,a2,...,an,每個數代表坐標中的一個點 (i, ai) 。在坐標內畫 n 條垂直線,垂直線 i 的兩個端點分別為 (i, ai) 和 (i, 0)。找出其中的兩條線,使得它們與 x 軸共同構成的容器可以容納最多的水。
說明:你不能傾斜容器,且 n 的值至少為 2。
圖中垂直線代表輸入數組 [1,8,6,2,5,4,8,3,7]。在此情況下,容器能夠容納水(表示為藍色部分)的最大值為49。
示例:
輸入:[1,8,6,2,5,4,8,3,7] 輸出:49題解:
?第一種解法:暴力
public int MaxArea(int[] height){// 解法1:int res = 0;for (int i = 0; i < height.Length; i++){for (int j = i + 1; j < height.Length; j++){int thisArea = (j - i) * Math.Min(height[i], height[j]);res = Math.Max(res, thisArea);}}return res;}第二種解法:雙指針(左指針大于右指針,left++)
public int MaxArea(int[] height){int res = 0;int left = 0; int right = height.Length - 1;while (left < right){int thisArea = (right - left) * Math.Min(height[left], height[right]);res = Math.Max(res, thisArea);if (height[left] > height[right]) right--;else left++;}return res;}第三種解法:雙指針優化(左指針小于等于最小高度,left++)
結果:
源碼地址:https://github.com/amusement1234/LeetCode_CSharp
總結
以上是生活随笔為你收集整理的【LeetCode】1. 盛最多水的容器:C#三种解法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何做一个懂产品的程序员?
- 下一篇: .Net Core中的诊断日志Diagn