首页 > 其他分享 >LeetCode 2345. Finding the Number of Visible Mountains

LeetCode 2345. Finding the Number of Visible Mountains

时间:2024-03-01 13:25:00浏览次数:25  
标签:2345 Mountains peaks mountain int Number visible its 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

类似Buildings With an Ocean View.

标签:2345,Mountains,peaks,mountain,int,Number,visible,its,mountains
From: https://www.cnblogs.com/Dylan-Java-NYC/p/18046756

相关文章

  • [LeetCode] 2864. Maximum Odd Binary Number
    Youaregivenabinarystringsthatcontainsatleastone'1'.Youhavetorearrangethebitsinsuchawaythattheresultingbinarynumberisthemaximumoddbinarynumberthatcanbecreatedfromthiscombination.Returnastringrepresentin......
  • Codeforces 441E Valera and Number
    首先看到\(\times2\)\(+1\)和最后答案的计算方式,能想到看成二进制来处理。考虑到\(\times2\)就是在最后加了一个\(0\)。不妨倒过来看,\(\times2\)就相当于舍弃了最低位。于是可以考虑\(\text{DP}\),\(f_{i,j}\)为考虑后面的\(i\)个操作,目前\(+\)的值为\(j\)的......
  • react错误:Uncaught Error: Too many re-renders. React limits the number of renders
    react错误:UncaughtError:Toomanyre-renders.Reactlimitsthenumberofrenderstopreventaninfiniteloop. 信铁寒胜:更改页面数据时未放到useEffect方法内,导致页面一直在刷新。  原因1:错误写法:<divclassName='article_item'onClick={toArticleDetail......
  • 机器学习策略篇:详解单一数字评估指标(Single number evaluation metric)
    单一数字评估指标无论是调整超参数,或者是尝试不同的学习算法,或者在搭建机器学习系统时尝试不同手段,会发现,如果有一个单实数评估指标,进展会快得多,它可以快速告诉,新尝试的手段比之前的手段好还是差。所以当团队开始进行机器学习项目时,经常推荐他们为问题设置一个单实数评估指标。......
  • SciTech-Mathmatics-automatic equation Numbering / \tag{E} / \label{E} / \ref{
    https://discourse.devontechnologies.com/t/numbering-and-tagging-equations-in-mathjax/69524/2IwentaroundincirclestryingtofigureouthowtonumberandtagequationsinMathJaxinDT3.TheMathJaxDocsshowshowtodoautomaticequationnumbering21......
  • Number【数字】
    定义:数字类型是顾名思义是用来存储数值的,需要记住的是,如果改变了数字数据类型的值,将重新分配内存空间。Python支持三种不同的数值类型:整型(int)-通常被称为是整型或整数,是正或负整数,不带小数点。Python3整型是没有限制大小的,可以当作Long类型使用,所以Python3没有Long......
  • [Rust] Create an array of numbers by using Range
    fnmain(){leta=0..100;ifa.len()>=100{println!("Wow,that'sabigarray!");}else{println!("Meh,Ieatarrayslikethatforbreakfast.");panic!("Arraynotbigenough,more......
  • A smart way to invert a number
    /*Thisismyhomeworktodaytojudgeanumberwhetherit'sapalindrome//Mostofususearraytosolvetheproblem,butIfindawaydonotneedanarray.*/include<stdio.h>intmain(intargc,constchar*argv[]){intx,m,n=0;printf(&quo......
  • isNaN()和Number.NaN()
    都是判断一个值是不是NaN。isNaN()会尝试执行Number()将值转成数值,然后对转换后的结果是否是NaN进行判断。isNaN(true)//false因为Number(true)值为1,而1不是NaN,所以返回falseisNaN(undefined);//true因为Number(undefined)值为NaN,所以返回trueisNaN({});......
  • vue中花括号表达式,string类型除以number类型返回NaN值
    bug:数据为0时,el-progress的color还是有颜色,应该是没有颜色的第一步解决:设置动态color<el-progress:show-text="false":percentage="(oilCarOccupationNum/totalNum)*100":color="oilCarOccupationNum?'......