1.二维数组查找
public class Solution {
public boolean Find(int target, int [][] array) {
if (array == null) {
return false;
}
int row = 0;
int column = array[0].length-1;
while (row < array.length && column >= 0) {
if(array[row][column] == target) {
return true;
}
if(array[row][column] > target) {
column--;
} else {
row++;
}
}
return false;
}
}
2.替换空格
import java.util.*;
public class Solution {
public String replaceSpace (String s) {
if (s == null){
return s;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
if (String.valueOf(s.charAt(i)).equals(" ")) {
sb.append("%20");
}else {
sb.append(s.charAt(i));
}
}
return String.valueOf(sb);
}
}
3.输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
public class Solution {
ArrayList<Integer> list = new ArrayList<>();
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
if(listNode!=null)
{
this.printListFromTailToHead(listNode.next);
list.add(listNode.val);
}
return list;
}
}
4.两个栈实现队列
import java.util.Stack;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
stack1.push(node);
}
public int pop() {
while(stack2.isEmpty()){
while(!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
}
5 数组旋转
import java.util.ArrayList;
public class Solution {
public int minNumberInRotateArray(int [] array) {
if(array.length==0){
return 0;
}
for(int i=0;i<array.length-1;i++){
if((array[i]>array[i+1])){
return array[i+1];
}
}
return array[0];
}
}
6斐波那契数列
public class Solution {
public int Fibonacci(int n) {
int result=0;
int preOne=1;
int preTwo=0;
if(n==0) {
return preTwo;
}
if(n==1) {
return preOne;
}
for (int i = 2; i <= n; i++) {
result = preOne+preTwo;
preTwo = preOne;
preOne = result;
}
return result;
}
}
7 青蛙跳台阶
public class Solution {
public int jumpFloor(int target) {
if(target <= 0) return 0;
if(target == 1) return 1;
if(target == 2) return 2;
int one = 1;
int two = 2;
int result = 0;
for(int i = 2; i < target; i++){
result = one+ two;
one = two;
two = result;
}
return result;
}
}
8青蛙跳台阶2
public class Solution {
public int jumpFloorII(int target) {
if (target == 0||target == 1) {
return target;
} else {
return 2 * jumpFloorII(target - 1);
}
}
}
9 矩阵覆盖
public int rectCover(int target) {
if (target <= 0)
return 0;
if (target == 1 ) {
return 1;
}
if (target == 2 ) {
return 2;
}
int one=1;
int two=2;
int sum=0;
for(int i=2;i<target;i++){
sum=one+two;
one =two;
two=sum;
}
return sum;
}
}
10 二进制1个数
public class Solution {
public int NumberOf1(int n) {
int count = 0;
while (n != 0) {
count++;
n = (n-1) & n;
}
return count;
}
}