-
-
Save goh-chunlin/bf80067b1a9f676a65bd5206241d8e2e to your computer and use it in GitHub Desktop.
Search Insertion Position - Recursion
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
public int SearchInsert(int[] nums, int target) { | |
return Search(nums, target, 0, nums.Length - 1); | |
} | |
private int Search(int[] nums, int target, int startingIndex, int endingIndex) { | |
int middleIndex = startingIndex + (endingIndex + 1 - startingIndex) / 2; | |
if (startingIndex == endingIndex) { | |
if (target <= nums[startingIndex]) { | |
return startingIndex; | |
} else { | |
return startingIndex + 1; | |
} | |
} | |
else if (endingIndex - startingIndex == 1) { | |
if (target <= nums[startingIndex]) { | |
return startingIndex; | |
} else if (target <= nums[endingIndex]) { | |
return endingIndex; | |
} else { | |
return endingIndex + 1; | |
} | |
} | |
else if (target == nums[middleIndex]) | |
{ | |
return middleIndex; | |
} | |
else if (target < nums[middleIndex]) { | |
return Search(nums, target, startingIndex, middleIndex); | |
} else { | |
return Search(nums, target, middleIndex, endingIndex); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment