-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay45.java
More file actions
36 lines (31 loc) · 1.29 KB
/
Copy pathDay45.java
File metadata and controls
36 lines (31 loc) · 1.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/*Floor in a Sorted Array
Given a sorted array arr[] and an integer x, find the index (0-based) of the largest element in arr[] that is less than or equal to x. This element is called the floor of x. If such an element does not exist, return -1.
Note: In case of multiple occurrences of floor of x, return the index of the last occurrence.
Examples
Input: arr[] = [1, 2, 8, 10, 10, 12, 19], x = 5
Output: 1
Explanation: Largest number less than or equal to 5 is 2, whose index is 1.
Input: arr[] = [1, 2, 8, 10, 10, 12, 19], x = 11
Output: 4
Explanation: Largest Number less than or equal to 11 is 10, whose indices are 3 and 4. The index of last occurrence is 4.
Input: arr[] = [1, 2, 8, 10, 10, 12, 19], x = 0
Output: -1
Explanation: No element less than or equal to 0 is found. So, output is -1. */
/*class Solution {
static int findFloor(int[] arr, int x) {
int low = 0, high = arr.length - 1;
int ans = -1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] <= x) {
ans = mid; // possible floor
low = mid + 1; // move right to find last occurrence
} else {
high = mid - 1;
}
}
return ans;
}
}
*/
/*Optimal Approach (O(log n) Time, O(1) Space) */