📌  相关文章
📜  从右侧可以看到的元素数量

📅  最后修改于: 2021-04-26 17:48:22             🧑  作者: Mango

给定整数数组,将元素视为建筑物的高度,找到可以从右侧看到的建筑物数量。
例子:

Input : height[] = {2, 6, 2, 4, 0, 1}
Output : 3
we can see only 3 building i.e with height 1, 4 and 6.

Input : height[] = {4, 8, 2, 0, 0, 5}
Output : 2

这个问题似乎是从右边找到最长的递增子序列,但实际上不是。如果遇到到目前为止发现的任何具有更高高度的建筑物,我们只需要增加计数即可。
下面是上述方法的实现。

C++
// CPP program to find number of elements
// that can be seen from right side.
#include 
using namespace std;
 
int numberOfElements(int height[], int n)
{
    int max_so_far = 0;
    int coun = 0;
 
    for (int i = n - 1; i >= 0; i--) {
        if (height[i] > max_so_far) {
            max_so_far = height[i];
            coun++;
        }
    }
    return coun;
}
 
// Driver code
int main()
{
    int n = 6;
    int height[] = { 4, 8, 2, 0, 0, 5 };
    cout << numberOfElements(height, n);
    return 0;
}


Java
// Java program to find number of elements
// that can be seen from right side.
import java.util.*;
class Solution
{
  
static int numberOfElements(int height[], int n)
{
    int max_so_far = 0;
    int coun = 0;
  
    for (int i = n - 1; i >= 0; i--) {
        if (height[i] > max_so_far) {
            max_so_far = height[i];
            coun++;
        }
    }
    return coun;
}
 
// Driver code
public static void main(String args[])
{
    int n = 6;
    int height[] = { 4, 8, 2, 0, 0, 5 };
    System.out.println( numberOfElements(height, n));
   
}
 
}
//contributed by Arnab Kundu


Python3
# Python3 program to find
# number of elements
# that can be seen from right side
 
def numberOfElements(height, n):
     
    max_so_far = 0
    coun = 0
     
    for i in range(n-1,-1,-1):
        if height[i] > max_so_far:
            max_so_far = height[i]
            coun = coun + 1
    return coun
 
#Driver code
if __name__=='__main__':
    n = 6
    height = [4, 8, 2, 0, 0, 5]
    print(numberOfElements(height, n))
     
# This code is contributed by
# Shashank_Sharma


C#
// C# program to find number of elements
// that can be seen from right side.
using System;
 
class GFG
{
public static int numberOfElements(int []height,
                                   int n)
{
    int max_so_far = 0;
    int coun = 0;
 
    for (int i = n - 1; i >= 0; i--)
    {
        if (height[i] > max_so_far)
        {
            max_so_far = height[i];
            coun++;
        }
    }
    return coun;
}
 
// Driver code
public static void Main()
{
    int n = 6;
    int []height = { 4, 8, 2, 0, 0, 5 };
    Console.WriteLine(numberOfElements(height, n));
}
}
 
// This code is contributed by Soumik


PHP
= 0; $i--)
    {
        if ($height[$i] > $max_so_far)
        {
            $max_so_far = $height[$i];
            $coun++;
        }
    }
    return $coun;
}
 
// Driver code
$n = 6;
$height = array(4, 8, 2, 0, 0, 5 );
echo numberOfElements($height, $n);
 
// This code is contributed
// by Akanksha Rai


Javascript


输出:
2