[Leetcode 35]Search Insert Position

Input: nums = [1,3,5,6], target = 5
Output: 2
Input: nums = [1,3,5,6], target = 2
Output: 1
Input: nums = [1,3,5,6], target = 7
Output: 4
Input: nums = [1,3,5,6], target = 0
Output: 0
Input: nums = [1], target = 0
Output: 0
  • 1 <= nums.length <= 104
  • -104 <= nums[i] <= 104
  • nums contains distinct values sorted in ascending order.
  • -104 <= target <= 104
int searchInsert(int* nums, int numsSize, int target){
unsigned int lo = 0;
unsigned int hi = numsSize - 1;
unsigned int mid;
while(lo < hi){
mid = (lo + hi) >> 1; // (lo+hi)/2
if(nums[mid] == target)
return mid;
if(nums[mid] < target){
lo = mid + 1;
}else{
hi = mid;
}
}
// when lo == hi
if(nums[lo] < target)
return lo + 1;
else
return lo;
}

--

--

--

Hi I am Samuel

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

How to use a framework like WSJF to inform and order work for maximum economic benefit

Working with AWS DynamoDB using Lambda and C#

Announcement of the implementation of the Gift function

5 Powerful Tips for Bash Scripting

Demo

Publishing an Android App (Part 2)

Google ReCaptcha v2 in native Xamarin.Forms apps

What Is Bash And Why Should You Learn It As A Developer

[Database] Concept of View vs Divide and Conquer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Samuel Liu

Samuel Liu

Hi I am Samuel

More from Medium

Demystifying arrays: Array data structure

Demystifying arrays: An attempt to get a better understanding of array data structure

Recursion Explained Using Brian McKnight and A Lawnmower

Leetcode — Isomorphic Strings — Easy

Intro to Big O Notation