Untitled
unknown
plain_text
9 months ago
1.7 kB
7
Indexable
package ARRAYS;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Oceanview {
/**
*There are n buildings in a row. You are given an integer array heights of size n, where heights[i] represents the height of the i-th building. A building has an ocean view if all the buildings to its right are shorter.
* Return an array of indices of buildings that have an ocean view, sorted in increasing order.
*
* Examples:
* Input: heights = [4,2,3,1]
* Output: [0,2,3]
* Explanation: Building 1 (0-indexed) does not have an ocean view because building 2 is taller.
*
* Input: heights = [4,3,2,1]
* Output: [0,1,2,3]
* Explanation: All the buildings have an ocean view.
*/
public static List<Integer> checkOceanView(int[] heights){
List<Integer> nums = new ArrayList<>();
for (int i = 0; i < heights.length; i++) {
boolean isOceanView = true;
for (int j = i + 1; j < heights.length; j++) {
if (heights[i] <= heights[j]) {
isOceanView = false;
break;
}
}
if (isOceanView) {
nums.add(i);
}
}
return nums;
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("ENTER ARRAY SIZE -> ");
int size = s.nextInt();
System.out.print("ENTER ARRAY ELEMENTS -> ");
int[] arr = new int [size];
for (int i = 0; i < size; i++) {
arr[i] = s.nextInt();
}
System.out.print("View -> -> " + checkOceanView(arr));
}
}
Editor is loading...
Leave a Comment