17. 二分查找
非常直接和简单,用递归实现二分查找,空间复杂度O(logn),时间复杂度O(logn)
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param nums int整型一维数组
* @param target int整型
* @return int整型
*/
public int search (int[] nums, int target) {
// write code here
return research(nums, 0, nums.length-1, target);
}
public int research(int[] nums, int begin, int end, int target){
if(begin>end) return -1;
if(begin==end&&nums[begin]!=target) return -1;
int mid = (begin+end)/2;
if(nums[mid]==target) return mid;
else if(nums[mid] < target) return research(nums,mid+1,end,target);
else return research(nums,begin,mid,target);
}
}
emmm,是可以不用递归,空间复杂度为O(1)
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param nums int整型一维数组
* @param target int整型
* @return int整型
*/
public int search (int[] nums, int target) {
// write code here
int l = 0;
int r = nums.length-1;
while(l<=r){
int mid = (l+r)/2;
if(nums[mid] == target) return mid;
else if(nums[mid] < target) l = mid+1;
else r = mid-1;
}
//if(l==r&&nums[l]==target) return l;
return -1;
}
}
18 二维数组中的查找
最简单的做法应该是把二维数组转换成一维,然后排序后用二分查找,这样时间复杂度O(mnlog(mn)+log(MN)),空间复杂度O(mn);
或者逐行二分查找,时间复杂度O(mlogn),空间复杂度O(1);
另一个最初想到的就是划分四个块,每次排除掉1/4,时间复杂度O(logm*logn),空间复杂度O(1);
最优的解法是
a.首先从数组左下角搜索.
b.如果当前数字大于target,那么查找往上移一位,如果当前数字小于target,那么查找往右移一位。
c.查找到target,返回true; 如果越界,返回false;
从左下或者右上角开始都可以,太妙了,之前算法课后练习看过这题但是忘了,这样的做法时间复杂度O(m+n),空间复杂度O(1)
public class Solution {
public boolean Find(int target, int [][] array) {
int x = array.length -1;
int y = 0;
int y2 = array[0].length -1;
while(x>=0&&y<=y2){
if(array[x][y] == target) return true;
else if(array[x][y] < target) y = y+1;
else x = x - 1;
}
return false;
}
}