兩點問題很常與數組一同出現,假設是一個數組問題,且大體解答思路是數組內坐標的移動,例如遍歷,這時可以考慮是兩點問題 兩點問題的關鍵:定義好兩點的位置和走法
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.
給定n個非負整數a1,a2,…,an,其中每個表示坐標(i,ai)處的點。 繪制n條垂直線,使得線i的兩個端點在(i,ai)和(i,0)。 找到兩條線,其與x軸一起形成容器,使得容器包含最多的水。
注意:您不能傾斜容器,n至少為2。
代碼 第一種做法是:
public class Solution { public int maxArea(int[] height) { int max = 0; for(int i=0; i<height.length; i++){ for(int j=0; j<i; j++){ int w, h; if(height[i] > height[j]) w = height[j]; else w = height[i]; h = i - j; if(w * h > max) max = w * h; } } return max; }}但是這種解法,大概是230ms,會超時
第二種做法:
public class Solution { public int maxArea(int[] height) { int max = 0, left = 0, right = height.length - 1; for(int i=0; i<height.length; i++){ max = Math.max(max, Math.min(height[left], height[right]) * (right - left) ); if(height[left] < height[right]) left++; else right--; } return max; }}定義了兩個點,left和right,left從數組頭開始,right從數組尾開始 容量等于:width * height(即left 和 right的高度較小值 * right 和 left 的橫坐標距離) 然后逐步縮短橫坐標距離,目的是嘗試 減少width,增加height,會不會得到更大的容量
Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
For example, Given input array nums = [1,1,2],
Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn’t matter what you leave beyond the new length.
給定一個排序數組,刪除重復的位置,使每個元素只出現一次并返回新的長度。 不要為另一個數組分配額外的空間,必須使用常量內存來做到這一點。
例如, 給定輸入數組nums = [1,1,2] 您的函數應返回length = 2,num的前兩個元素分別為1和2。
代碼:
public int removeDuplicates(int[] A) { if (A.length==0) return 0; int j=0; for (int i=0; i<A.length; i++) if (A[i]!=A[j]) A[++j]=A[i]; return ++j; }i 用于遍歷數組,j用于記錄不同的數的個數
Given an array and a value, remove all instances of that value in place and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
The order of elements can be changed. It doesn’t matter what you leave beyond the new length.
Example: Given input array nums = [3,2,2,3], val = 3
Your function should return length = 2, with the first two elements of nums being 2.
給定數組和值,原位刪除該值的所有實例,并返回新長度。
不要為另一個數組分配額外的空間,必須使用常量內存來做到這一點。
可以更改元素的順序。 沒有什么你離開超出了新的長度。
例: 給定輸入數組nums = [3,2,2,3],val = 3
您的函數應返回length = 2,num的前兩個元素為2。
代碼
public class Solution { public int removeElement(int[] nums, int val) { int j =0; for(int i=0; i<nums.length; i++){ if(val != nums[i]){ int tmp = nums[j]; nums[j++] = nums[i]; nums[i] = tmp; } } return j; }}i用于遍歷數組,j用于記錄數組中不同于val的數的個數,且把這些數往前移動
新聞熱點
疑難解答