1、二分查找数组
一、二分查找必须是有序的数组,因此没有顺序要先排序。排序
二、每次位移>>1至关于除以2动态规划
三、找到就返回下标,没找到返回-1while
int binarySearch(int a[], int key) { int length = a.length; int cursor, start = 0, end = length - 1;//闭区间[0,r] while (start < end) { cursor = start + ((end - start) >> 1);//向下取整 if (a[cursor] < key) start = cursor + 1; else end = cursor; } if (a[end] == key) return end; return -1; }
2、动态规划new
一、最大连续子序列之和return
给定一个整数序列,a0, a1, a2, …… , an(项能够为负数),求其中最大的子序列和。void
public void main() { int[] num = new int[]{-101, 9, -4, 3, -5, 120, -5, -220}; // int[] num = new int[]{-2, 11, -4, 13, -5, -2}; int s = 0;//开始 int e = 0;//结束 int max = 0;//总和 int temp = 0; int ts = 0; for (int i = 0; i < num.length; i++) { temp = temp + num[i]; if (temp < 0) { ts = i + 1; temp = 0; } else { if (temp > max) { s = ts; e = i; max = temp; } } } System.out.println("maxsum=" + max + ",start:" + s + ",end=" + e); }
打印结果:maxsum=123,start:1,end=5tar