翻转链表
public ListNode reverseList(ListNode head) {
ListNode pre = null;
ListNode iterator = head;
while(iterator != null){
//记录下一个值
ListNode next = iterator.next;
//后继改前驱
iterator.next = pre;
//记录前驱
pre = iterator;
//当前值改为下一个值
iterator = next;
}
return pre;
}
二分查找
public int binarySearch(int[] nums,int key,int left,int right){
if(key < nums[left] || key > nums[right] || left > right){
return -1;
}
int middle = (left + right) / 2;
if(nums[middle] > key){
//比关键字大则关键字在左区域
return binarySearch(nums, key, left, middle - 1);
}else if(nums[middle] < key){
//比关键字小则关键字在右区域
return binarySearch(nums, key, middle + 1, right);
}else {
return middle;
}
}
两个栈实现队列
class CQueue {
Stack<Integer> stack1;
Stack<Integer> stack2;
public CQueue() {
stack1 = new Stack();
stack2 = new Stack();
}
public void appendTail(int value) {
stack1.push(value);
}
public int deleteHead() {
//如果第二个栈为空 第一个栈写入
if (stack2.empty()) {
while(!stack1.empty()){
stack2.push(stack1.pop());
}
}
if(stack2.empty()){
return -1;
}
return stack2.pop();
}
}
斐波那契
动态规划
public int fib(int n) {
int MOD = 1000000007;
if(n == 0) {
return 0;
}else if(n == 0){
return 1;
}
int a = 0;
int b = 1;
for(int i = 2; i <= n; i++){
if (a > MOD){
a = a % MOD;
}
if (b > MOD){
b = b % MOD;
}
int c = b;
b = a + b;
a = c;
}
return b % MOD;
}
旋转数组的最小数字
二分法简化问题
public int minArray(int[] numbers) {
int low = 0;
int high = numbers.length - 1;
while (low < high) {
int mid = low + (high - low) / 2;
if (numbers[mid] < numbers[high]) {
high = mid;
} else if (numbers[mid] > numbers[high]) {
low = mid + 1;
} else {
high -= 1;
}
}
return numbers[low];
}