Search Insert Position
Question:
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.
Example 1:
Input: [1,3,5,6], 5
Output: 2
Example 2:
Input: [1,3,5,6], 2
Output: 1
Example 3:
Input: [1,3,5,6], 7
Output: 4
Example 4:
Input: [1,3,5,6], 0
Output: 0
解法代碼
public class LeetCode35 {
public int searchInsert(int[] nums, int target) {
if (nums == null || nums.length == 0) {
return 0;
}
int left = 0;
int right = nums.length - 1;
int mid = -1;
while (left <= right) {
// 防止溢出
mid = left + (right - left) / 2;
// 二分查找
if (nums[mid] > target) {
right = mid - 1;
} else if (nums[mid] < target) {
// 此種情況,如果需要插入target,插入位置應該是mid的下一個位置,所以使用++mid
left = ++mid;
} else {
// 匹配到值,跳出循環,返回mid
break;
}
}
return mid;
}
}
測試代碼
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import com.kay.pro.alog.LeetCode35;
@RunWith(Parameterized.class)
public class LeetCode35Test {
private LeetCode35 leetCode;
private int[] nums;
private int target;
private int ret;
public LeetCode35Test(int[] nums, int target, int ret) {
this.nums = nums;
this.target = target;
this.ret = ret;
}
@Before
public void before() {
leetCode = new LeetCode35();
}
@Parameters
public static Collection<?> reverserArrays() {
return Arrays.asList(new Object[][]{
{new int[]{1,3,5,6}, 5, 2},
{new int[]{1,3,5,6}, 2, 1},
{new int[]{1,3,5,6}, 7, 4},
{new int[]{1}, 1, 0}
});
}
@Test
public void leetCode33() {
assertEquals(ret, leetCode.searchInsert(nums, target));
}
}
Output:
Time And Space Complexity
Time:
二分查找時間復雜度
Space:不需要使用額外的存儲空間,原地替換
Tips
簡單的二分查找,注意
nums[mid] < target
找到插入位置的時候,應該是在mid的下一個位置插入,所以此處用的是left = ++mid;
而不是left = mid + 1;
。