算法
二分法查找:
代码块
public static boolean binarySearch(List<Integer> list, Integer matchItem) {
int size = list.size();
if (size == 1) {
return list.get(0).equals(matchItem);
} if (size == 2) {
return list.get(0).equals(matchItem) || list.get(1).equals(matchItem);
}
int binaryIndex = size/2;
Integer binaryItem = list.get(binaryIndex);
if (binaryItem < matchItem) {
return binarySearch(list.subList(binaryIndex+1 , size), matchItem);
} else if (binaryItem > matchItem) {
return binarySearch(list.subList(0 , binaryIndex), matchItem);
} else {
return true;
}
}
快速排序:
代码块
1 public static void quickSort(List<Integer> list, int s, int e) { 2 if (s == e) { 3 return; 4 } 5 int start = s; 6 int end = e; 7 Integer mark = list.get(start); 8 int markindex = start; 9 boolean markEnd = true; 10 while (start != end){ 11 if (markEnd) { 12 Integer endItem = list.get(end); 13 if (mark <= endItem) { 14 end--; 15 continue; 16 } else { 17 Integer temp = endItem; 18 list.set(end, mark); 19 list.set(markindex, temp); 20 markindex = end; 21 markEnd = false; 22 continue; 23 } 24 } else { 25 Integer startItem = list.get(start); 26 if (mark >= startItem) { 27 start++; 28 continue; 29 } else { 30 Integer temp = startItem; 31 list.set(start, mark); 32 list.set(markindex, temp); 33 markindex = start; 34 markEnd = true; 35 continue; 36 } 37 } 38 } 39 if (markindex == s) { 40 quickSort(list, s+1, e); 41 return; 42 } 43 if (markindex == e) { 44 quickSort(list, s, e-1); 45 return; 46 } 47 quickSort(list, s, markindex-1); 48 quickSort(list, markindex+1, e); 49 }
取余数算法
//常用做法
int value = 999;
int n = 10;
int remainder = value % n;
//高效做法
int remainder = value & (n - 1)
//JDK HashMap 取key在数组中位置采用的就是位移算法
/**
* Implements Map.get and related methods.
*
* @param hash hash for key
* @param key the key
* @return the node, or null if none
*/
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
if ((e = first.next) != null) {
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
布隆过滤器
https://hackernoon.com/probabilistic-data-structures-bloom-filter-5374112a7832
guava实现:https://juejin.im/post/5cc5aa7ce51d456e431adac5
匹配w在数组x,y,z是否存在 如果都为1 则可能存在,可能不存在,只要有一个为0,肯定不存在;
使用场景:头条,抖音推荐视频中,如何过滤调用户已经看过的视频了?用户看过的视频通通过布隆过滤器结构保存,新的视频 如果匹配,则用户可能看过,可能没有看过;如果没有匹配上,则用户肯定没有看过,则可以把该视频推荐的用户;可能
会导致有一些视频用户没有看过也过滤掉了,但是概率低,但是推荐的视频用户是肯定没有看过的,满足是场景。

浙公网安备 33010602011771号