1、合并排序,將兩個(gè)已經(jīng)排序的數(shù)組合并成一個(gè)數(shù)組,其中一個(gè)數(shù)組能容下兩個(gè)數(shù)組的所有元素;
public static int[] merge(int[] a,int [] b) {
int[] c = new int[a.length+b.length];
//i用于標(biāo)記數(shù)組a
int i=0;
//j用于標(biāo)記數(shù)組b
int j=0;
//用于標(biāo)記數(shù)組c
int k=0;
//a,b數(shù)組都有元素時(shí)
while(i<a.length && j<b.length) {
if(a[i]<b[j]) {
c[k++] = a[i++];
}else {
c[k++] = b[j++];
}
}
//若a有剩余
while(i<a.length) {
c[k++] = a[i++];
}
//若b有剩余
while(j<b.length) {
c[k++] = b[j++];
}
return c;
}
2、合并兩個(gè)已經(jīng)排序的單鏈表;
3、倒序打印一個(gè)單鏈表;
/**
* 遞歸方法逆序打印單鏈表
* @param head
*/
public static void printListReverse1(ListNode head)
{
if(head!=null)
{
if(head.next!=null)
{
printListReverse1(head.next);
}
}
System.out.println(head.val);
}
/**
* 使用棧逆序打印單鏈表
* @param head
*/
public static void printListReverse2(ListNode head)
{
Stack<Integer> stack=new Stack<Integer>();
while(head!=null)
{
stack.push(head.val);
head=head.next;
}
while(!stack.isEmpty())
{
System.out.println(stack.pop());
}
}
4、給定一個(gè)單鏈表的頭指針和一個(gè)指定節(jié)點(diǎn)的指針,在O(1)時(shí)間刪除該節(jié)點(diǎn);
5、找到鏈表倒數(shù)第K個(gè)節(jié)點(diǎn);
6、反轉(zhuǎn)單鏈表;
7、通過兩個(gè)棧實(shí)現(xiàn)一個(gè)隊(duì)列;
8、二分查找;
9、快速排序;
10、獲得一個(gè)int型的數(shù)中二進(jìn)制中的個(gè)數(shù);
11、輸入一個(gè)數(shù)組,實(shí)現(xiàn)一個(gè)函數(shù),讓所有奇數(shù)都在偶數(shù)前面;
public static void reorderOddEven(int[] array){
if(array==null||array.length<=0)
throw new RuntimeException("invalid array");
int begin=0;
int end=array.length-1;
while(begin<end){
while(begin<end&&(array[begin]&1)!=0)
begin++;
while(begin<end&&(array[end]&1)==0)
end--;
if(begin<end){
int temp=array[end];
array[end]=array[begin];
array[begin]=temp;
}
}
}
12、判斷一個(gè)字符串是否是另一個(gè)字符串的子串;
public static void main(String[] args) {
String test = "This is test for string";
System.out.println(test.indexOf("This")); //0
System.out.println(test.indexOf("is")); //2
System.out.println(test.indexOf("test")); //8
System.out.println(test.indexOf("for")); //13
System.out.println(test.indexOf("for string "));//-1
if (test.indexOf("This")!=-1){
//"只要test.indexOf('This')返回的值不是-1說明test字符串中包含字符串'This',相反如果包含返回的值必定是-1"
System.out.println("存在包含關(guān)系,因?yàn)榉祷氐闹挡坏扔?1");
}else{
System.out.println("不存在包含關(guān)系,因?yàn)榉祷氐闹档扔?1");
}
if (test.indexOf("this")!=-1){
//"只要test.indexOf('this')返回的值不是-1說明test字符串中包含字符串'this',相反如果包含返回的值必定是-1"
System.out.println("存在包含關(guān)系,因?yàn)榉祷氐闹挡坏扔?1");
}else{
System.out.println("不存在包含關(guān)系,因?yàn)榉祷氐闹档扔?1");
}
}
13、把一個(gè)int型數(shù)組中的數(shù)字拼成一個(gè)串,這個(gè)串代表的數(shù)字最小;
public String PrintMinNumber(int [] numbers) {
int n;
String s="";
ArrayList<Integer> list= new ArrayList<Integer>();
n=numbers.length;
for(int i=0;i<n;i++){
list.add(numbers[i]);
}
Collections.sort(list, new Comparator<Integer>(){
public int compare(Integer str1,Integer str2){
String s1=str1+""+str2;
String s2=str2+""+str1;
return s1.compareTo(s2);
}
});
for(int j:list){
s+=j;
}
return s;
}
14、輸入一顆二叉樹,輸出它的鏡像(每個(gè)節(jié)點(diǎn)的左右子節(jié)點(diǎn)交換位置);
15、輸入兩個(gè)鏈表,找到它們第一個(gè)公共節(jié)點(diǎn);