35.Search Insert Position
题目链接:https://leetcode.com/problems/search-insert-position/description/
题目大意:一串升序数组和target,如果在数组中能找到target,则返回下标值;如果找不到,则返回应插入的位置下标值。
解法一:利用二分查找,查找是否有target,如果有则返回,否则在最后得到的low值就是应该插入的位置或是low+1该插入的位置。代码如下(耗时7ms):
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public int searchInsert(int[] nums, int target) { 2 int low = 0, high = nums.length - 1; 3 while(low < high) { 4 int mid = (low + high) / 2; 5 if(nums[mid] < target) { 6 low = mid + 1; 7 } 8 else if(nums[mid] > target) { 9 high = mid - 1; 10 } 11 else { 12 return mid; 13 } 14 } 15 if(nums[low] < target) { 16 return low + 1; 17 } 18 else { 19 return low; 20 } 21 }
解法二:直接暴力,逐一便利查看target是否存在于数组中,如果存在则返回下标值,如果不存在则返回应插入的位置。代码如下(耗时6ms):
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public int searchInsert(int[] nums, int target) { 2 3 for(int i = 0; i < nums.length; i++) { 4 if(target < nums[i]) { 5 if(i > 0) { 6 return i; 7 } 8 else { 9 return 0; 10 } 11 } 12 else if(target == nums[i]) { 13 return i; 14 } 15 } 16 if(nums[nums.length - 1] < target) { 17 return nums.length; 18 } 19 return 0; 20 }