Created
December 16, 2021 09:59
-
-
Save Shivani13121007/dae44d0560a0b6d650e7f0f235415bb1 to your computer and use it in GitHub Desktop.
Target Index
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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