查找算法

来源:互联网 发布:js判断是不是function 编辑:程序博客网 时间:2024/06/01 21:46

常用的查找算法不外乎顺序查找、二分查找、哈希表查找和二叉排序树查找,下边将分别介绍这几种查找算法。
一、顺序查找
顺序查找很简单,按照顺序对序列的元素依次进行比较,找到目标元素返回true,否则返回false,时间复杂度O(n)。
实现代码:

public class Solution {    public boolean find(int []arr, int target) {        for (int i = 0; i < arr.length; i++){            if (arr[i] == target)                return true;        }        return false;    }}

二、二分查找
使用二分查找的前提的给定的序列必须是已经排好序的序列,对序列进行折半查找,时间复杂度O(logn)
代码实现:
1、非递归版本

public class Solution {    public boolean binarySearch(int []arr, int target) {        int low = 0;        int high = arr.length - 1;        int mid;        while (low <= high){            mid = (low + high) / 2;            if (target < arr[mid])                high = mid - 1;            else if (target > arr[mid])                low = mid + 1;            else                return true;        }        return false;    }}

2、递归版本

public class Solution {    public boolean binarySearch(int []arr, int low, int high, int target) {        int mid = (low + high) / 2;        if (low <= high){            if (target == arr[mid])            return true;            else if (target > arr[mid])                return binarySearch(arr, mid + 1, high, target);            else                 return binarySearch(arr, 0, mid - 1, target);        }        return false;    }}

三、哈希表查找
采用键值映射的方式实现时间复杂度为O(1)的查找算法,通过key找到对应的value。

四、二叉排序树查找(B树查找)
构建二叉排序树实际上并不是为了排序,而是为了提高查找和增删的效率,使用它实现查找的时间复杂度也是O(logn)
代码实现
递归版本

public class Solution {    public boolean find(TreeNode root, int target) {        if (root == null)            return false;        if (target < root.val)            return find(root.left, target);        else if (target > root.val)            return find(root.right, target);        else             return true;    }}

非递归版本

public class Solution() {    public boolean find(TreeNode root, int target) {        while (root != null) {            if (target < root.val)                root = root.left;            else if (target > root.val)                root = root.right;            else                 return true;        }        return false;    }}
0 0