425. Find Floor of an Element in Sorted Array

EasyBinary SearchArrayBinary Search

Given a sorted array nums of distinct integers and an integer target, return the largest element in nums that is less than or equal to target. Return -1 if no such element exists.

Input: A sorted distinct integer array nums and integer target.

Output: The floor value (largest element <= target), or -1.

Examples

Example 1
Input: [1,3,5,7,9], 6
Output: 5
Explanation: Elements <= 6: {1,3,5}. Largest is 5.
Example 2
Input: [1,3,5,7,9], 0
Output: -1
Explanation: No element <= 0 exists. Return -1.
Example 3
Input: [2,4,6,8,10], 6
Output: 6
Explanation: 6 is in the array; floor(6)=6.

Constraints

Asked by

TCSInfosysWiproCognizantCapgemini
Solve this problem in the editor →