Problem Description
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.
Analysis
- Going through the array
- Try to find an index i where nums[i] == target and return the i
- If step 2 failed, try to find an index i where nums[i] > target. Notieced that the array is sorted and if we have to insert a digit before nums[i], the index of the digit should be i as well, then we have to break from the loop, otherwise the position will be wrong
- There is a possibility that the target is bigger than the biggest one in the array, then the index to insert should be the value of nums.length.
Right Code
1 | public int searchInsert(int[] nums, int target) { |