Problem 36:二叉搜索树转双向链表
TreeNode head = null;
TreeNode pre = null;
public TreeNode convert(TreeNode root){
inOrder(root);
return head;
}
public void inOrder(TreeNode node){
if(node == null) return ;
inOrder(node.left);
node.left = pre;
if(pre != null)
pre.right = node;
pre = node;
if(head == null)
head = node;
inOrder(node.right);
}
Problem 37:序列化二叉树
private String deserializeStr;
String Serialize(TreeNode root) {
if (root == null)
return "#";
return root.val + " " + Serialize(root.left) + " " + Serialize(root.right);
}
TreeNode Deserialize(String str) {
deserializeStr = str;
return Deserialize();
}
TreeNode Deserialize() {
if (deserializeStr.length() == 0)
return null;
int index = deserializeStr.indexOf(" ");
String node = index == -1 ? deserializeStr : deserializeStr.substring(0, index);
deserializeStr = index == -1 ? "" : deserializeStr.substring(index + 1);
if (node.equals("#"))
return null;
int val = Integer.valueOf(node);
TreeNode t = new TreeNode(val);
t.left = Deserialize();
t.right = Deserialize();
return t;
}
Problem 38:字符串的排列
public ArrayList<String> Permutation(String str) {
ArrayList<String> list = new ArrayList();
if(str.length() == 0) return list;
Permutation(str.toCharArray(), list, 0);
Collections.sort(list);
return list;
}
public void Permutation(char[] ch, ArrayList<String> list, int i){
if(i == ch.length - 1){
if(!list.contains(new String(ch)))
list.add(new String(ch));
}else{
for(int j = i; j < ch.length; j++){
swap(ch,i,j);
Permutation(ch,list,i+1);
swap(ch,i,j);
}
}
}
public void swap(char[] arr, int i, int j){
char temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
Problem 39:数组中出现次数超过一半的数字
public int MoreThanHalfNum_Solution(int [] arr) {
if(arr == null || arr.length == 0) return 0;
HashMap<Integer, Integer> map = new HashMap();
for(int i = 0; i < arr.length; i++){
if(map.containsKey(arr[i]))
map.put(arr[i], map.get(arr[i])+1);
else
map.put(arr[i],1);
}
for(Map.Entry<Integer,Integer> entry : map.entrySet())
if(entry.getValue() > arr.length/2)
return entry.getKey();
return 0;
}
Problem 40:最小的K个数
利用构造大顶堆的堆排序
public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
ArrayList<Integer> list = new ArrayList();
if(input == null || input.length == 0 || k > input.length) return list;
heap(input);
for(int i = 0; i < k; i++)
list.add(input[i]);
return list;
}
public void heap(int[] arr){
buildMaxHeap(arr);
for(int i = arr.length - 1; i > 0; i--){
swap(arr,0,i);
adjustHeap(arr,0,i);
}
}
public void buildMaxHeap(int[] arr){
for(int i = arr.length / 2 - 1; i >= 0; i--){
adjustHeap(arr,i,arr.length);
}
}
public void adjustHeap(int[] arr, int i, int length){
int father = arr[i];
for(int child = 2*i+1; child < length; child = 2*child+1){
if(child+1 < length && arr[child] < arr[child+1])
child++;
if(father < arr[child]){
swap(arr,i,child);
i = child;
}
}
}
public void swap(int[] arr, int i, int j){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}