1.字符串反转
public static String reverse(String s){
char[] ch = s.toCharArray();
char temp;
for(int i = 0; i < ch.length / 2; i++) {
temp = ch[i];
ch[i] = ch[ch.length - 1 - i];
ch[ch.length - 1 - i] = temp;
}
return new String(ch);
// 直接用方法..
return new StringBuilder(s).reverse().toString();
}
2.链表反转
// 单向链表反转
class Node {
Node next;
Object value;
Node(Object v) { this.value = v; }
}
public static Node reverse(Node n) {
Node pre = null, next = null;
while (n != null) {
next = n.next;
n.next = pre; //完成反指
pre = n; //游标右移
n = next; //游标右移
}
return pre;
}
// 双向链表反转
class Node {
Node pre, next;
Object value;
Node(Object v) { this.value = v; }
}
public static Node reverse(Node n){
Node pre, next;
while (n != null) {
next = n.next;
n.next = pre; //反转
n.pre = next; //反转
pre = n; //游标右移
n = next; //游标右移
}
return pre;
}
3.二分查找
public static int binarySearch(int[] arr, int n) {
//先排个序. 此方法的实现是DualPivotQuicksort,双基准快排
Arrays.sort(arr);
int low = 0, high = arr.length - 1, mid;
while(low <= high){
mid = (low + high) / 2;
if (arr[mid] == n) {
return mid;
} else if (arr[mid] > n) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return -1;
}
4.最大子序列和
public static long maxSonSum(int[] arr) {
long thisSum = 0, maxSum = 0;
for (int i = 0; i < arr.length; i++) {
thisSum += arr[i];
if(thisSum > maxSum) {
maxSum = thisSum;
}
if(thisSum < 0) {
thisSum = 0;
}
}
return maxSum;
}
5.斐波那契数据第N项的值/前N项的和
// 递归:然后栈就溢出了 0.0
public static long fib(int n) {
if(n <= 0)
return 0;
if(n == 1)
return 1;
return fib(n - 1) + fib(n - 2);
}
//第N项的数值:
public static long fib(int n) {
// 1 1 2 3 5 8..
if (n < 1) {
return -1;
}
int a1 = 1, a2 = 1;
for (int i = 0; i < n - 2; i++) {
a2 = a1 + a2;
a1 = a2 - a1;
}
return a2;
}
// 前N项和:
public static long fibSum(int n) {
if (n < 1) {
return -1;
}
if (n == 1) {
return 1;
}
int a1 = 1, a2 = 1, sum = 2;
for (int i = 0; i < n - 2; i++) {
a2 = a1 + a2;
a1 = a2 - a1;
sum += a2;
}
return sum;
}
6.二叉树前中后序遍历
void pre(TreeNode node) {
if (node != null) {
sout(node.value); //前序写前面,中序写中间,后序写后面
pre(node.left);
pre(node.right);
}
}