今天开始刷题啦,坚持住哟!
使用二分法的前提是数组有序且无重复元素。
704.二分查找
第一遍代码如下:
java
class Solution {
public int search(int[] nums, int target) {
int left=0;
int right=nums.length-1;
while(left<=right){
int mid = (right-left)/2;
if (nums[mid]>target){
right=mid-1;
}else if(nums[mid]<target){
left=mid+1;
}else if(nums[mid]==target){
return mid;
}
}
return -1;
}
}
存在错误:
-
没有考虑target小于nums[0]和大于nums[length-1]
-
mid计算错误,且没有防止溢出,以下是两种正确写法
java
int mid = left + ((right - left) / 2);
java
int mid = left + ((right - left) >> 1);
第二遍代码如下:
java
class Solution {
public int search(int[] nums, int target) {
if (target < nums[0] || target > nums[nums.length - 1]) {
return -1;
}
int left=0;
int right=nums.length-1;
while(left<=right){
int mid = left+((right-left)/2);
if (nums[mid]>target){
right=mid-1;
}else if(nums[mid]<target){
left=mid+1;
}else if(nums[mid]==target){
return mid;
}
}
return -1;
}
}
测试通过!
35.搜索插入位置
第一遍代码:
java
class Solution {
public int searchInsert(int[] nums, int target) {
int left = 0;
int right = nums.length-1;
while(left<=right){
int mid = left + ((right - left)/2);
if (nums[mid]==target){
return mid;
}else if(nums[mid]>target){
right = mid -1;
}else{
left=mid+1;
}
}
return right+1;
}
}
测试通过!