查找算法
来源:互联网 发布: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
- 查找算法(静态查找)
- 查找算法 二分查找
- 查找算法:二分查找
- 查找算法 - 二分法查找
- 算法--查找--二分查找
- 算法--查找--差值查找
- 查找算法:二分法查找
- 查找算法---二分查找
- 查找算法
- 查找算法
- 查找算法
- 查找算法
- 查找算法
- 查找算法
- 查找算法
- 查找算法
- 查找算法
- 查找算法:
- SpringMVC从Controller跳转到另一个Controller
- Activiti工作流(一)之基本操作介绍
- Bundle.setClassLoader()方法解析 BootClassLoader PathClassLoader
- Linux 下五个最佳的 FPS 游戏发布啦!
- 一个android app打开另外一个app,并传替数据(个人学习笔记)
- 查找算法
- ms sql server 去除某个字段的某个字符
- CSS标准文档流
- WattOS:一个稳又快的轻量级 Linux 发行版
- 修复《文件夹的复制--递归算法》博客中的BUG
- Linux基础之IO重定向及管道详解(涉及tr、tee命令)
- 【九度】由前序和中序构造二叉树并求后序遍历
- 转载:SSL/TLS协议运行机制的概述
- 什么样的DevOps技能是团队需要的?