Skip to content

Instantly share code, notes, and snippets.

@Shivani13121007
Created December 16, 2021 09:59
Show Gist options
  • Save Shivani13121007/dae44d0560a0b6d650e7f0f235415bb1 to your computer and use it in GitHub Desktop.
Save Shivani13121007/dae44d0560a0b6d650e7f0f235415bb1 to your computer and use it in GitHub Desktop.
Target Index
#include <iostream>
#include<vector>
using namespace std;
int searchInsert(vector<int>& nums, int target)
{
int pivot, left = 0, right = nums.size() - 1;
while (left <= right) {
pivot = left + (right - left) / 2;
if (nums[pivot] == target) return pivot;
if (target < nums[pivot]) right = pivot - 1;
else left = pivot + 1;
}
return left;
}
int main()
{
int n;
cin>>n;
vector<int> arr(n,0);
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
int target;
cin>>target;
cout<<searchInsert(arr,target);
return 0;
}
import java.util.*;
public class Main{
public static int searchInsert(int[] nums, int target) {
int pivot, left = 0, right = nums.length - 1;
while (left <= right) {
pivot = left + (right - left) / 2;
if (nums[pivot] == target) return pivot;
if (target < nums[pivot]) right = pivot - 1;
else left = pivot + 1;
}
return left;
}
public static void main(String args[]) {
Scanner scn = new Scanner(System.in);
int n = scn.nextInt();
int[] arr = new int[n];
for(int i=0;i<n;i++)
{
arr[i] = scn.nextInt();
}
int target = scn.nextInt();
System.out.println(searchInsert(arr,target));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment