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:
這次題目比較簡單馅扣, 主要就是一個(gè)二分查找的實(shí)現(xiàn)。
這也算是我第一次實(shí)現(xiàn) binary search. 主要一個(gè)細(xì)節(jié)徒坡,就是羞酗, lo > hi 的時(shí)候再返回lo。
**
總結(jié): 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