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