# 牛客网 - 剑指Offer（中）

### 23. 二叉搜索树的后序遍历序列

``````public class Solution {
public boolean VerifySquenceOfBST(int [] sequence) {
int len = sequence.length;
if (len == 0) {
return false;
} else if (len > 2) {
return vertifyBST(sequence);
}
return true;
}

public boolean vertifyBST(int [] sequence) {
int len = sequence.length;
if (len > 2) {
int index = -1; // 记录断开的位置
int root = sequence[len - 1];
for (int i = 0; i < len; i++) {
if (index == -1 && sequence[i] > root) {
index = i;
}
if (index != -1 && sequence[i] < root) {
return false;
}
}
if (index == -1) {
return true;
}
int arr2Len = len - index - 1;
int [] arr1 = new int[index];
int [] arr2 = new int[arr2Len];
System.arraycopy(sequence, 0, arr1, 0, index);
System.arraycopy(sequence, index, arr2, 0, arr2Len);
return vertifyBST(arr1) && vertifyBST(arr2);
}
return true;
}
}
``````

### 24. 二叉树中和为某一值得路径

``````import java.util.ArrayList;
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;

public TreeNode(int val) {
this.val = val;

}

}
*/
public class Solution {

public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
ArrayList<ArrayList<Integer>> resList =  new ArrayList<ArrayList<Integer>>();
if (root == null) {
return resList;
}
int rootVal = root.val;
if (rootVal > target) {
return resList;
} else if (rootVal == target) {
ArrayList<Integer> path = new ArrayList<Integer>();
} else {
TreeNode left = root.left;
TreeNode right = root.right;
if (left != null) {
ArrayList<Integer> temp = new ArrayList<Integer>();
buildPath(left, target - rootVal, resList, temp);
}
if (right != null) {
ArrayList<Integer> temp = new ArrayList<Integer>();
buildPath(right, target - rootVal, resList, temp);
}
}
return resList;
}

public void buildPath(TreeNode node, int target, ArrayList<ArrayList<Integer>> resList,
ArrayList<Integer> path) {
int val = node.val;
TreeNode left = node.left;
TreeNode right = node.right;
if (val > target) {
return;
}
if (left == null && right == null) {
if (val == target) {
}
return;
}
if (left != null) {
ArrayList<Integer> temp = new ArrayList<Integer>();
buildPath(left, target - val, resList, temp);
}
if (right != null) {
ArrayList<Integer> temp = new ArrayList<Integer>();
buildPath(right, target - val, resList, temp);
}
}
}
``````

### 25. 复杂链表的复制 (我的复杂度爆炸了)

``````/*
public class RandomListNode {
int label;
RandomListNode next = null;
RandomListNode random = null;

RandomListNode(int label) {
this.label = label;
}
}
*/
public class Solution {
{
return null;
}
while(p != null) {
RandomListNode temp = new RandomListNode(p.label);
temp.next = p.next;
p.next = temp;
p = temp.next;

}
while (q != null) {
if (q.random != null) {
q.next.random = q.random.next;
q = q.next.next;
}
}
while(q.next != null) {
q.next = q.next.next;
q = q.next;
}
return q;
}
}
``````

### 26. 二叉搜索树与双向链表

``````import java.util.Queue;

/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;

public TreeNode(int val) {
this.val = val;

}
}
*/
public class Solution {

/**
* ① 中序遍历进队列
* ② 出队并构造双向链表
* @param pRootOfTree
* @return
*/
public TreeNode Convert(TreeNode pRootOfTree) {
if (pRootOfTree == null) {
return null;
}
initQueue(queue, pRootOfTree); // 创建队列
while (!queue.isEmpty()) {
TreeNode nodeSmall = queue.poll();
if (queue.isEmpty()) {
break;
}
TreeNode nodeLarge = queue.peek();
nodeSmall.right = nodeLarge;
nodeLarge.left = nodeSmall;
}
}

public void initQueue(Queue queue, TreeNode node) {
if (node.left != null) {
initQueue(queue, node.left);
}
queue.offer(node);
if (node.right != null) {
initQueue(queue, node.right);
}
}
}
``````

### 28. 数组中出现超过一半的数字

``````import java.util.HashMap;
import java.util.Map;

public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
int len = array.length;
int half = len / 2;
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < len; i++) {
map.put(array[i], map.containsKey(array[i]) ?
(int) map.get(array[i]) + 1 : 1
);
if ((int)map.get(array[i]) > half) {
return array[i];
}
}
return 0;
}
}
``````

### 29. 最小的k个数

``````import java.util.ArrayList;

public class Solution {
public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
int len = input.length;
ArrayList<Integer> res = new ArrayList<Integer>();
if (k > len) {
return res;
}
int temp;
int min;
for (int i = 0; i < k; i++) {
for (int j = i; j < len; j++) {
if (input[j] < input[i]) {
temp = input[i];
input[i] = input[j];
input[j] = temp;
}
}
}
return res;
}
}
``````

### 30. 连续子数组的最大和

HZ偶尔会拿些专业问题来忽悠那些非计算机专业的同学。今天测试组开完会后,他又发话了:在古老的一维模式识别中,常常需要计算连续子向量的最大和,当向量全为正数的时候,问题很好解决。但是,如果向量中包含负数,是否应该包含某个负数,并期望旁边的正数会弥补它呢？例如:{6,-3,-2,7,-15,1,2,2},连续子向量的最大和为8(从第0个开始,到第3个为止)。你会不会被他忽悠住？(子向量的长度至少是1)

``````public class Solution {
public int FindGreatestSumOfSubArray(int[] array) {
int len = array.length;
int max = array[0];
if (len == 1) {
return max;
}
for (int i = 0; i < len; i++) {
int sum = 0;
for (int j = i; j < len; j++) {
sum += array[j];
max = sum > max ? sum : max;
}
}
return max;
}
}
``````

### 31. 整数中1出现的次数（从1到n整数中1出现的次数）

``````public class Solution {
public int NumberOf1Between1AndN_Solution(int n) {
String str = "";
int len;
int sum = 0;
for (int i = 1; i <= n; i++) {
str = String.valueOf(i);
len = str.length();
for (int j = 0; j < len; j++) {
if (str.charAt(j) == '1') {
sum++;
}
}
}
return sum;
}
}
``````

### 32. 把数组排成最小的数

``````import java.util.*;

public class Solution {
public String PrintMinNumber(int [] numbers) {
int len = numbers.length;
String[] strArr = new String[len];
StringBuilder builder = new StringBuilder();
for (int i = 0; i < len; i++) {
strArr[i] = String.valueOf(numbers[i]);
}
Arrays.sort(strArr, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
StringBuilder sb1 = new StringBuilder()
.append(o1)
.append(o2);
StringBuilder sb2 = new StringBuilder()
.append(o2)
.append(o1);
return sb1.toString().compareTo(sb2.toString());
}
});
for (int i = 0; i < len; i++) {
builder.append(strArr[i]);
}
return builder.toString();
}
}

``````

### 33. 丑数

``````/**
* 先比较 1*2， 1*3， 1*5  ——> 再比较 2*2, 1*3, 1*5, 以此类推
*/
public class Solution {

private final int[] base = new int[]{2, 3, 5};

public int GetUglyNumber_Solution(int index) {
if (index == 0) {
return 0;
}
int[] res = new int[index];
int[] p = new int[]{0, 0, 0}; // 记录3个待比较数的 根基的位置
int[] num = new int[]{2, 3, 5}; // 待比较的三个数
res[0] = 1;
int cur = 1;
while (cur < index) {
int m = getMin(num);
if (res[cur - 1] < num[m]) {
res[cur++] = num[m];
}
num[m] = res[ ++p[m]] * base[m];
}
return res[index - 1];
}

public int getMin(int[] num){
int min = Math.min(num[0], num[1]);
min = Math.min(min, num[2]);
for (int i = 0; i < 3; i++) {
if (min == num[i]) {
return i;
}
}
return 0;
}
}
``````

### 34. 第一个只出现一次的字符

``````public class Solution {
public int FirstNotRepeatingChar(String str) {
int len = str.length();
for (int i = 0; i < len; i++) {
char c = str.charAt(i);
if (str.indexOf(String.valueOf(c)) == str.lastIndexOf(String.valueOf(c))) {
return str.indexOf(String.valueOf(c));
}
}
return -1;
}
}
``````

### 36. 两个链表的第一个公共节点

``````import java.util.*;
/*
public class ListNode {
int val;
ListNode next = null;

ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
HashMap<Integer, ListNode> map = new HashMap<Integer, ListNode>();
return null;
}
}
}
}
return null;
}
}
``````

### 37. 数字在排序数组中出现的次数

``````public class Solution {
public int GetNumberOfK(int [] array , int k) {
int len = array.length;
int times = 0;
for (int i = 0; i < len; i++) {
if (array[i] == k) {
times++;
} else if (times != 0) {
break;
}
}
return times;
}
}
``````

### 38. 二叉树的深度

``````/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;

public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public int TreeDepth(TreeNode root) {
if (root == null) {
return 0;
}else if (root.left == null && root.right == null) {
return 1;
} else {
return Math.max(TreeDepth(root.left), TreeDepth(root.right)) + 1;
}
}
}
``````

### 39. 平衡二叉树

``````public class Solution {
public boolean IsBalanced_Solution(TreeNode root) {
if (root == null) {
return true;
}
if (Math.abs(getDepth(root.left) - getDepth(root.right)) < 2) {
return IsBalanced_Solution(root.left) && IsBalanced_Solution(root.right);
} else {
return false;
}
}

private int getDepth(TreeNode node) {
if (node == null) {
return 0;
} else if (node.left == null && node.right == null) {
return 1;
} else {
return Math.max(getDepth(node.left), getDepth(node.right)) + 1;
}
}
}
``````

### 40. 数组中只出现一次的数字

``````import java.util.*;

//num1,num2分别为长度为1的数组。传出参数
//将num1[0],num2[0]设置为返回结果
public class Solution {
public void FindNumsAppearOnce(int [] array,int num1[] , int num2[]) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
int len = array.length;
for (int i = 0; i < len; i++) {
map.put(array[i], map.containsKey(array[i])? 2 : 1);
}
boolean isFirst = true;
for (Map.Entry entry: map.entrySet()){
int num = (int)entry.getValue();
if (num == 1) {
if (isFirst == true) {
num1[0] = (int)entry.getKey();
isFirst = false;
} else {
num2[0] = (int)entry.getKey();
}
}
}
}
}
``````

### 41. 和为S的连续正数序列

``````输出所有和为S的连续正数序列。序列内按照从小至大的顺序，序列间按照开始数字从小到大的顺序
``````
``````import java.util.ArrayList;
public class Solution {
public ArrayList<ArrayList<Integer>> FindContinuousSequence(int sum) {
ArrayList<ArrayList<Integer>> resList = new ArrayList<ArrayList<Integer>>();
int tail = 2;
while (head <= sum / 2) {
}
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = head; i <= tail; i++) {
}
}
}
return resList;
}
}
``````

### 42. 和为S的两个数字

``````import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> FindNumbersWithSum(int [] array,int sum) {
int len = array.length;
if (len < 2) {
return new ArrayList<Integer>();
}
ArrayList<ArrayList<Integer>> resList = new ArrayList<ArrayList<Integer>>();
for (int i = 0; array[i] < sum / 2; i++) {
int tailIndex = i + 1;
int tail;
while (addSum <= sum && tailIndex < len) {
tail = array[tailIndex++];
ArrayList<Integer> list = new ArrayList<Integer>();
break;
}
}
}
len = resList.size();
int res = 0;
if (len > 0) {
res = resList.get(0).get(0) * resList.get(0).get(1);
} else {
return  new ArrayList<Integer>();
}
int resIndex = 0;
for (int i = 1; i < len; i++) {
int total = resList.get(i).get(0) * resList.get(i).get(1);
if (res > total) {
resIndex = i;
res = total;
}
}
return resList.get(resIndex);

}
}
``````

### 43. 坐旋转字符串

``````public class Solution {
public String LeftRotateString(String str,int n) {
int len = str.length();
if (len == 0) return str;
n %= len;
StringBuilder builder = new StringBuilder();
String str1 = str.substring(0, n);
String str2 = str.substring(n, len);
return builder.append(str2)
.append(str1)
.toString();
}
}
``````

### 44. 翻转单词顺序列

``````public class Solution {
public String ReverseSentence(String str) {
String[] arr = str.split(" ");
int len = arr.length;
if (len == 0) return str;
StringBuilder builder = new StringBuilder();
for (int i = len - 1; i >= 0; i--) {
String splitStr = arr[i];
builder.append(splitStr);
if (i != 0) {
builder.append(" ");
}
}
return builder.toString();
}
}
``````
原文作者：JYGod丶
原文地址: https://www.jianshu.com/p/7a389886a4bc
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。