Search Insert Position Solutions in Java
Number 35
Difficulty Easy
Acceptance 42.7%
Link LeetCode
Solutions
Java solution by haoel/leetcode
// Source : https://oj.leetcode.com/problems/search-insert-position/// Inspired by : http://www.jiuzhang.com/solutions/search-insert-position/// Author : Lei Cao// Date : 2015-10-03package searchInsertPosition;public class searchInsertPosition {public int searchInsert(int[] nums, int target) {int i = searchInsertI(nums, target);int j = searchInsertII(nums, target);if (i == j) {return i;}return -1;}// Find the first position >= targetprivate int searchInsertI(int[] nums, int target) {if (nums == null || nums.length == 0) {return 0;}int start = 0;int end = nums.length - 1;while (start + 1 < end) {int mid = start + (end - start) / 2;if (nums[mid] == target) {return mid;} else if (nums[mid] < target) {start = mid;} else {end = mid;}}if (nums[start] >= target) {return start;}if (nums[end] >= target) {return end;}return end + 1;}// Find the last position < target, return + 1// 1,2,3,5,6private int searchInsertII(int[] nums, int target) {if (nums == null || nums.length == 0) {return 0;}if (target < nums[0]) {return 0;}int start = 0;int end = nums.length - 1;while (start + 1 < end) {int mid = start + (end - start) / 2;if (nums[mid] == target) {return mid;} else if (nums[mid] < target) {start = mid;} else {end = mid;}}if (nums[end] == target) {return end;} else if (nums[end] < target) {return end + 1;} else if (nums[start] == target) {return start;}return start + 1;}}