My code:
public class Solution {
public int searchInsert(int[] nums, int target) {
if (nums == null || nums.length == 0)
return 0;
int lo = 0;
int hi = nums.length - 1;
return BinarySearch(lo, hi, target, nums);
}
private int BinarySearch(int lo, int hi, int target, int[] nums) {
if (lo > hi)
return lo;
int mid = (lo + hi) / 2;
if (nums[mid] == target)
return mid;
else if (nums[mid] > target)
return BinarySearch(lo, mid - 1, target, nums);
else
return BinarySearch(mid + 1, hi, target, nums);
}
public static void main(String[] args) {
Solution test = new Solution();
int[] a = {1, 3, 5, 6};
System.out.println(test.searchInsert(a, 0));
}
}
My test result:
这次题目比较简单, 主要就是一个二分查找的实现。
这也算是我第一次实现 binary search. 主要一个细节,就是, lo > hi 的时候再返回lo。
**
总结: binary search
**
My code:
public class Solution {
public int searchInsert(int[] nums, int target) {
if (nums == null || nums.length == 0)
return 0;
int begin = 0;
int end = nums.length - 1;
while (begin <= end) {
int middle = begin + (end - begin) / 2;
if (nums[middle] < target)
begin = middle + 1;
else if (nums[middle] > target)
end = middle - 1;
else
return middle;
}
return begin;
}
}
这道题木还是比较简单的。
Anyway, Good luck, Richardo!
My code:
public class Solution {
public int searchInsert(int[] nums, int target) {
if (nums == null || nums.length == 0) {
return -1;
}
int begin = 0;
int end = nums.length - 1;
while (begin <= end) {
int mid = begin + (end - begin) / 2;
if (nums[mid] > target) {
end = mid - 1;
}
else if (nums[mid] < target) {
begin = mid + 1;
}
else {
return mid;
}
}
return begin;
}
}
简单题。
Anyway, Good luck, Richardo! -- 09/01/2016