26.二叉搜索樹與雙向鏈表
模仿中序遍歷的思路,但是這次是從右向左進行。
public class Solution {
TreeNode temp = null;
public TreeNode Convert(TreeNode pRootOfTree) {
if(pRootOfTree==null){
return null;
}
Convert(pRootOfTree.right);
if(temp==null){
temp = pRootOfTree;
}else{
temp.left = pRootOfTree;
pRootOfTree.right = temp;
temp = pRootOfTree;
}
Convert(pRootOfTree.left);
return temp;
}
}
27.字符串的排列
import java.util.ArrayList;
import java.util.*;
public class Solution {
ArrayList<String> res = new ArrayList();
public ArrayList<String> Permutation(String str) {
ArrayList<String> res = new ArrayList();
int len = str.length();
if(len==0){
return res;
}
char []cha = str.toCharArray();
getres(cha,0,len,res);
Collections.sort(res);
return res;
}
public ArrayList<String> getres(char[] cha,int i ,int len,ArrayList list){
if(i==len-1){
String temp = String.valueOf(cha);
if(!list.contains(temp)){
list.add(temp);
}
}else{
for(int j = i;j<len;j++){
swap(cha,i,j);
getres(cha,i+1,len,list);
swap(cha,i,j);
}
}
return list;
}
public void swap(char cha[],int i ,int j){
char x = cha[i];
cha[i] = cha[j];
cha[j] = x;
}
}
28.數組中超過出現次數超過一半的數字
排序之後,如存在這樣的數,取中位數就是答案,然後驗證出現的次數是否符合超過半數的設定。
import java.util.*;
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
Arrays.sort(array);
int len = array.length;
int mid = len/2;
int res = array[mid];
int count = 0;
for(int x :array){
if(x==res){
count++;
}
}
if(count>mid){
return res;
}else{
return 0;
}
}
}
29.最小的K個數
考察的應該是堆排序,後續會添加上。
import java.util.*;
public class Solution {
public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
ArrayList<Integer> arr = new ArrayList();
int len = input.length;
if(len==0||k>len){
return arr;
}
Arrays.sort(input);
int i =0;
while(k>0){
arr.add(input[i]);
i++;
k--;
}
return arr;
}
}
30.連續子數組的最大和
能讓整體的和更大的方式,就是之前數的和爲整數,如果爲負數,就拋棄之前所有的數,以當前數作爲起點。
public class Solution {
public int FindGreatestSumOfSubArray(int[] array) {
int res = array[0];
int temp = array[0];
for(int i =1;i<array.length;i++){
if(temp>=0){
temp = temp+array[i];
}else{
temp = array[i];
}
if(temp>res){
res = temp;
}
}
return res;
}
}