Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
Example 1:
Input: nums = [1,3,5,6], target = 5
Output: 2
Approach
Java
public class SearchInsertPosition {public static void main(String[] args) {int[] nums = { 1, 3, 5, 6 };int target = 5;System.out.println(searchInsert(nums, target));}static int searchInsert(int[] nums, int target) {int low = 0, high = nums.length;// if target value is greater then last// element valueif (target > nums[nums.length - 1])return nums.length;// if target value is less than first element valueif (target < nums[0])return 0;// search for positionwhile (low <= high) {int mid = low + (high - low) / 2;if (nums[mid] == target)return mid;else if (nums[mid] > target)high = mid - 1;elselow = mid + 1;}return low;}}
C++
#include <bits/stdc++.h>using namespace std;int searchInsert(vector<int> &nums, int target){int low = 0, high = nums.size();//if target value is greater then last//element valueif (target > nums[nums.size() - 1])return nums.size();//if target value is less than first element valueif (target < nums[0])return 0;//search for positionwhile (low <= high){int mid = low + (high - low) / 2;if (nums[mid] == target)return mid;else if (nums[mid] > target)high = mid - 1;elselow = mid + 1;}return low;}int main(){vector<int> nums = {1, 3, 5, 6};int target = 5;cout << searchInsert(nums, target);return 0;}
No comments:
Post a Comment