LeetCode - Algorithms - 35. Search Insert Position

Problem

35. Search Insert Position

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

You may assume no duplicates in the array.

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public int searchInsert(int[] nums, int target) {
int left=0, right=nums.length-1;
int mid=0;
while(left<=right) {
mid = (left+right)/2;
if (nums[mid]>target) {
right = mid-1;
}
else if (nums[mid]<target){
left = mid+1;
}
else
return mid;
}
if (target>nums[mid])
return mid+1;
else
return mid;
}
}

Submission Detail

  • 62 / 62 test cases passed.
  • Runtime: 0 ms, faster than 100.00% of Java online submissions for Search Insert Position.
  • Memory Usage: 38.9 MB, less than 100.00% of Java online submissions for Search Insert Position.