035.Search Insert Positio

Solution 1: accepted 7ms

Normal iteration.
Time: O(n)
Space: O(1)

1
2
3
4
5
6
7
8
9
10
public int searchInsert(int[] nums, int target) {
int prev = Integer.MIN_VALUE;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == target)
return i;
else if (target > prev && target < nums[i])
return i;
}
return nums.length;
}

Solution 2: accepted 7ms

Binary search.
Time: O(logn)
Space: O(1)