简介
顺序查找
从头到尾依次查找。时间复杂度O(n).
代码
1 2 3 4 5 6 7 8 9 10 11 12
public int (int [] arr, int target) { int n = arr.length; int res = -1 ; for (int i = 0 ; i < n; i++){ if (arr[i] == target){ res = i; break ; } } return res; }
二分查找
如果数组已经排好序,或者根据前期搜索到元素某种星系,能够确定下一步的查找方向,就可以使用二分查找。二分查找的时间复杂度是O(log(n)).
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
public int search (int [] nums, int target) { int lo = 0 ,hi = nums.length - 1 ; int res = -1 ; while (lo <= hi){ int mid = lo + (hi - lo) /2 ; if ( nums[mid] < target){ lo = mid + 1 ; } else if ( target < nums[mid]){ hi = mid - 1 ; } else { res = mid; break ; } } return res; }
二叉搜索树
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x){ val = x;} } class BST { public TreeNode searchBST (TreeNode root, int val) { if ( root == null ) return root; while ( root != null ){ if ( root.val == val ) return root; if ( root.val > val ){ root = root.left; } else { root = root.right; } } return root; } public boolean isValidBST (TreeNode root) { if (root == null ) return true ; List<Integer> res = new ArrayList<>(); inorder(root, res); for (int i = 0 ; i < res.size() - 1 ; i++){ if ( res.get(i+ 1 ) <= res.get(i) ) return false ; } return true ; } private void inorder (TreeNode root, List<Integer> res) { if ( root == null ) return ; inorder(root.left, res); res.add(root.val); inorder(root.right, res); } public TreeNode insertIntoBST (TreeNode root, int val) { if (root == null ) return new TreeNode(val); if (val < root.val) root.left = insertIntoBST(root.left, val); else if (val > root.val) root.right = insertIntoBST(root.right, val); else x.val = val; return root; } } public TreeNode deleteNode (TreeNode root, int key) { if (root == null ) return null ; if (key < root.val) root.left = deleteNode(root.left, key); else if ( key > root.val) root.right = deleteNode(root.right, key); else { if (root.right == null ) return root.left; if (root.left == null ) return root.right; TreeNode t = root; root = min(t.right); root.right = deleteMin(t.right); root.left = t.left; } return root; } private TreeNode min (TreeNode root) { if (root.left == null ) return root; else return min(root.left); } private TreeNode deleteMin (TreeNode x) { if (x.left == null ) return x.right; x.left = deleteMin(x.left); return x; }
红黑树
B树
哈希表
Java中关于查找的数据结构
Set
Map
近期评论