LeetCode 2345. Finding the Number of Visible Mountains
原题链接在这里:https://leetcode.com/problems/finding-the-number-of-visible-mountains/description/
题目:
You are given a 0-indexed 2D integer array peaks
where peaks[i] = [xi, yi]
states that mountain i
has a peak at coordinates (xi, yi)
. A mountain can be described as a right-angled isosceles triangle, with its base along the x
-axis and a right angle at its peak. More formally, the gradients of ascending and descending the mountain are 1
and -1
respectively.
A mountain is considered visible if its peak does not lie within another mountain (including the border of other mountains).
Return the number of visible mountains.
Example 1:
Input: peaks = [[2,2],[6,3],[5,4]] Output: 2 Explanation: The diagram above shows the mountains. - Mountain 0 is visible since its peak does not lie within another mountain or its sides. - Mountain 1 is not visible since its peak lies within the side of mountain 2. - Mountain 2 is visible since its peak does not lie within another mountain or its sides. There are 2 mountains that are visible.
Example 2:
Input: peaks = [[1,3],[1,3]] Output: 0 Explanation: The diagram above shows the mountains (they completely overlap). Both mountains are not visible since their peaks lie within each other.
Constraints:
1 <= peaks.length <= 105
peaks[i].length == 2
1 <= xi, yi <= 105
题解:
Write some examples and we can find the pattern that if we sort the peaks, first ascending based on its left start point, then descending on its right end point.
When iterate from left to right, whenever we encounter a bigger right end point, we find a visible mountain.
Note there could be duplicate, thus check if the current and the next peak are the same, if yes, continue.
Time Complexity: O(nlogn). n = peask.length.
Space: O(n). sort worst case uses O(n) space.
AC Java:
1 class Solution { 2 public int visibleMountains(int[][] peaks) { 3 if(peaks == null || peaks.length == 0){ 4 return 0; 5 } 6 7 int n = peaks.length; 8 Arrays.sort(peaks, (a, b) -> { 9 if(a[0] - a[1] == b[0] - b[1]){ 10 return b[0] + b[1] - a[0] - a[1]; 11 } 12 13 return a[0] - a[1] - (b[0] - b[1]); 14 }); 15 16 int res = 0; 17 int maxEnd = Integer.MIN_VALUE; 18 for(int i = 0; i < n; i++){ 19 int x = peaks[i][0]; 20 int y = peaks[i][1]; 21 if(x + y > maxEnd){ 22 maxEnd = x + y; 23 if(i < n - 1 && Arrays.equals(peaks[i], peaks[i + 1])){ 24 continue; 25 } 26 27 res++; 28 } 29 } 30 31 return res; 32 } 33 }
AC Python:
1 class Solution: 2 def visibleMountains(self, peaks: List[List[int]]) -> int: 3 n = len(peaks) 4 5 peaks.sort(key = lambda x: (x[0] - x[1], -(x[0] + x[1]))) 6 7 res = 0 8 maxEnd = -inf 9 10 for i, (x, y) in enumerate(peaks): 11 if x + y > maxEnd: 12 maxEnd = x + y 13 14 if i < n - 1 and peaks[i] == peaks[i+1]: 15 continue 16 17 res += 1 18 19 return res