Java面試題集(第六部分)(136-150)

摘要:這一部分主要是數據結構算法相關的面試題目,雖然只有15道題目,但是包含的信息量還是很大的,很多題目背後的解題思路和算法是非常值得玩味的。

136、給出下面的二叉樹先序、中序、後序遍歷的序列?


答:先序序列:ABDEGHCF;中序序列:DBGEHACF;後序序列:DGHEBFCA。

補充:二叉樹也稱爲二分樹,它是樹形結構的一種,其特點是每個結點至多有二棵子樹,並且二叉樹的子樹有左右之分,其次序不能任意顛倒。二叉樹的遍歷序列按照訪問根節點的順序分爲先序(先訪問根節點,接下來先序訪問左子樹,再先序訪問右子樹)、中序(先中序訪問左子樹,然後訪問根節點,最後中序訪問右子樹)和後序(先後序訪問左子樹,再後序訪問右子樹,最後訪問根節點)。如果知道一棵二叉樹的先序和中序序列或者中序和後序序列,那麼也可以還原出該二叉樹。

例如,已知二叉樹的先序序列爲:xefdzmhqsk,中序序列爲:fezdmxqhks,那麼還原出該二叉樹應該如下圖所示:

 

137、你知道的排序算法都哪些?用Java寫一個排序系統。

答:穩定的排序算法有:插入排序、選擇排序、冒泡排序、雞尾酒排序、歸併排序、二叉樹排序、基數排序等;不穩定排序算法包括:希爾排序、堆排序、快速排序等。

下面是關於排序算法的一個列表:


下面按照策略模式給出一個排序系統,實現了冒泡、歸併和快速排序。

Sorter.java

[java] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. package com.jackfrued.util;  
  2.    
  3. import java.util.Comparator;  
  4.    
  5. /** 
  6.  * 排序器接口(策略模式: 將算法封裝到具有共同接口的獨立的類中使得它們可以相互替換) 
  7.  */  
  8. public interfaceSorter {  
  9.     
  10.    /** 
  11.     * 排序 
  12.     * @param list 待排序的數組 
  13.     */  
  14.    public <T extends Comparable<T>>void sort(T[] list);  
  15.     
  16.    /** 
  17.     * 排序 
  18.     * @param list 待排序的數組 
  19.     * @param comp 比較兩個對象的比較器 
  20.     */  
  21.    public <T> void sort(T[] list,Comparator<T> comp);  
  22. }  

 

BubbleSorter.java

[java] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. package com.jackfrued.util;  
  2.    
  3. import java.util.Comparator;  
  4.    
  5. /** 
  6.  * 冒泡排序 
  7.  */  
  8. public classBubbleSorter implements Sorter {  
  9.    
  10.    @Override  
  11.    public <T extends Comparable<T>>voidsort(T[] list) {  
  12.       boolean swapped = true;  
  13.       for(int i = 1; i < list.length && swapped;i++) {  
  14.         swapped= false;  
  15.         for(int j = 0; j < list.length - i; j++) {  
  16.            if(list[j].compareTo(list[j+ 1]) > 0 ) {  
  17.               Ttemp = list[j];  
  18.               list[j]= list[j + 1];  
  19.               list[j+ 1] = temp;  
  20.               swapped= true;  
  21.            }  
  22.         }  
  23.       }  
  24.    }  
  25.    
  26.    @Override  
  27.    public <T> void sort(T[] list,Comparator<T> comp) {  
  28.       boolean swapped = true;  
  29.       for(int i = 1; i < list.length && swapped;i++) {  
  30.         swapped= false;  
  31.         for(int j = 0; j < list.length - i; j++) {  
  32.            if(comp.compare(list[j],list[j + 1]) > 0 ) {  
  33.               Ttemp = list[j];  
  34.               list[j]= list[j + 1];  
  35.               list[j+ 1] = temp;  
  36.               swapped= true;  
  37.            }  
  38.         }  
  39.       }  
  40.    }   
  41. }  

 

MergeSorter.java

[java] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. package com.jackfrued.util;  
  2.    
  3. import java.util.Comparator;  
  4.    
  5. /** 
  6.  * 歸併排序 
  7.  * 歸併排序是建立在歸併操作上的一種有效的排序算法。 
  8.  * 該算法是採用分治法(divide-and-conquer)的一個非常典型的應用, 
  9.  * 先將待排序的序列劃分成一個一個的元素,再進行兩兩歸併, 
  10.  * 在歸併的過程中保持歸併之後的序列仍然有序。 
  11.  */  
  12. public classMergeSorter implements Sorter {  
  13.    
  14.    @Override  
  15.    public <T extends Comparable<T>>voidsort(T[] list) {  
  16.       T[]temp = (T[]) newComparable[list.length];  
  17.       mSort(list,temp, 0, list.length- 1);  
  18.    }  
  19.     
  20.    private <T extends Comparable<T>>voidmSort(T[] list, T[] temp, int low, inthigh) {  
  21.       if(low == high) {  
  22.         return ;  
  23.       }  
  24.       else {  
  25.         int mid = low + ((high -low) >> 1);  
  26.         mSort(list,temp, low, mid);  
  27.         mSort(list,temp, mid + 1, high);  
  28.         merge(list,temp, low, mid + 1, high);  
  29.       }  
  30.    }  
  31.     
  32.    private <T extends Comparable<T>>voidmerge(T[] list, T[] temp, int left, intright, intlast) {  
  33.       int j = 0;   
  34.         int lowIndex = left;   
  35.        int mid = right - 1;   
  36.         int n = last - lowIndex + 1;   
  37.         while (left <= mid && right <= last){   
  38.             if (list[left].compareTo(list[right]) < 0){   
  39.                 temp[j++] = list[left++];   
  40.             } else {   
  41.                 temp[j++] = list[right++];   
  42.             }   
  43.         }   
  44.         while (left <= mid) {   
  45.             temp[j++] = list[left++];   
  46.         }   
  47.         while (right <= last) {   
  48.             temp[j++] = list[right++];   
  49.         }   
  50.         for (j = 0; j < n; j++) {   
  51.             list[lowIndex + j] = temp[j];   
  52.         }   
  53.    }  
  54.    
  55.    @Override  
  56.    public <T> void sort(T[] list,Comparator<T> comp) {  
  57.       T[]temp = (T[]) newComparable[list.length];  
  58.       mSort(list,temp, 0, list.length- 1, comp);  
  59.    }  
  60.     
  61.    private <T> void mSort(T[] list, T[]temp, intlow, inthigh, Comparator<T> comp) {  
  62.       if(low == high) {  
  63.         return ;  
  64.       }  
  65.       else {  
  66.         int mid = low + ((high -low) >> 1);  
  67.         mSort(list,temp, low, mid, comp);  
  68.         mSort(list,temp, mid + 1, high, comp);  
  69.         merge(list,temp, low, mid + 1, high, comp);  
  70.       }  
  71.    }  
  72.     
  73.    private <T> void merge(T[] list, T[]temp, intleft, intright, intlast, Comparator<T> comp) {  
  74.       int j = 0;   
  75.         int lowIndex = left;   
  76.         int mid = right - 1;   
  77.         int n = last - lowIndex + 1;   
  78.         while (left <= mid && right <= last){   
  79.             if (comp.compare(list[left], list[right]) <0) {   
  80.                 temp[j++] = list[left++];   
  81.             } else {   
  82.                 temp[j++] = list[right++];   
  83.             }   
  84.         }   
  85.         while (left <= mid) {   
  86.             temp[j++] = list[left++];   
  87.         }   
  88.         while (right <= last) {   
  89.             temp[j++] = list[right++];   
  90.         }   
  91.         for (j = 0; j < n; j++) {   
  92.             list[lowIndex + j] = temp[j];   
  93.         }   
  94.    }  
  95.    
  96. }  

 

QuickSorter.java

[java] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. package com.jackfrued.util;  
  2.    
  3. import java.util.Comparator;  
  4.    
  5. /** 
  6.  * 快速排序 
  7.  * 快速排序是使用分治法(divide-and-conquer)依選定的樞軸 
  8.  * 將待排序序列劃分成兩個子序列,其中一個子序列的元素都小於樞軸, 
  9.  * 另一個子序列的元素都大於或等於樞軸,然後對子序列重複上面的方法, 
  10.  * 直到子序列中只有一個元素爲止 
  11.  */  
  12. public classQuickSorter implements Sorter {  
  13.    
  14.    @Override  
  15.    public <T extends Comparable<T>>voidsort(T[] list) {  
  16.       quickSort(list,0, list.length- 1);  
  17.    }  
  18.    
  19.    @Override  
  20.    public <T> void sort(T[] list,Comparator<T> comp) {  
  21.       quickSort(list,0, list.length- 1, comp);  
  22.    }  
  23.    
  24.    private <T extends Comparable<T>>voidquickSort(T[] list, int first, intlast) {  
  25.       if (last > first) {  
  26.         int pivotIndex =partition(list, first, last);  
  27.         quickSort(list,first, pivotIndex - 1);  
  28.         quickSort(list,pivotIndex, last);  
  29.       }  
  30.    }  
  31.     
  32.    private <T> void quickSort(T[] list, int first, int last,Comparator<T> comp) {  
  33.       if (last > first) {  
  34.         int pivotIndex =partition(list, first, last, comp);  
  35.         quickSort(list,first, pivotIndex - 1, comp);  
  36.         quickSort(list,pivotIndex, last, comp);  
  37.       }  
  38.    }  
  39.    
  40.    private <T extends Comparable<T>>intpartition(T[] list, int first, intlast) {  
  41.       Tpivot = list[first];  
  42.       int low = first + 1;  
  43.       int high = last;  
  44.    
  45.       while (high > low) {  
  46.         while (low <= high&& list[low].compareTo(pivot) <= 0) {  
  47.            low++;  
  48.         }  
  49.         while (low <= high&& list[high].compareTo(pivot) >= 0) {  
  50.            high–;  
  51.         }  
  52.         if (high > low) {  
  53.            Ttemp = list[high];  
  54.            list[high]= list[low];  
  55.            list[low]= temp;  
  56.         }  
  57.       }  
  58.    
  59.       while (high > first&& list[high].compareTo(pivot) >= 0) {  
  60.         high–;  
  61.       }  
  62.       if (pivot.compareTo(list[high])> 0) {  
  63.         list[first]= list[high];  
  64.         list[high]= pivot;  
  65.         return high;  
  66.       }  
  67.       else {  
  68.         return low;  
  69.       }  
  70.    }  
  71.    
  72.    private <T> int partition(T[] list, int first, int last,Comparator<T> comp) {  
  73.       Tpivot = list[first];  
  74.       int low = first + 1;  
  75.       int high = last;  
  76.    
  77.       while (high > low) {  
  78.         while (low <= high&& comp.compare(list[low], pivot) <= 0) {  
  79.            low++;  
  80.         }  
  81.         while (low <= high&& comp.compare(list[high], pivot) >= 0) {  
  82.            high–;  
  83.         }  
  84.         if (high > low) {  
  85.            Ttemp = list[high];  
  86.             list[high] = list[low];  
  87.            list[low]= temp;  
  88.         }  
  89.       }  
  90.    
  91.       while (high > first&& comp.compare(list[high], pivot) >= 0) {  
  92.         high–;  
  93.       }  
  94.       if (comp.compare(pivot,list[high]) > 0) {  
  95.         list[first]= list[high];  
  96.         list[high]= pivot;  
  97.         return high;  
  98.       }  
  99.       else {  
  100.         return low;  
  101.       }  
  102.    }  
  103.     
  104. }  

 

138、寫一個二分查找(折半搜索)的算法。

答:折半搜索,也稱二分查找算法、二分搜索,是一種在有序數組中查找某一特定元素的搜索算法。搜素過程從數組的中間元素開始,如果中間元素正好是要查找的元素,則搜素過程結束;如果某一特定元素大於或者小於中間元素,則在數組大於或小於中間元素的那一半中查找,而且跟開始一樣從中間元素開始比較。如果在某一步驟數組爲空,則代表找不到。這種搜索算法每一次比較都使搜索範圍縮小一半。

[java] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. package com.jackfrued.util;  
  2.    
  3. import java.util.Comparator;  
  4.    
  5. public classMyUtil {  
  6.    
  7.    public static <T extends Comparable<T>>int binarySearch(T[] x, T key) {  
  8.       return binarySearch(x,0, x.length- 1, key);  
  9.    }  
  10.     
  11.    public static <T> int binarySearch(T[] x, T key, Comparator<T> comp) {  
  12.       int low = 0;  
  13.       int high = x.length - 1;  
  14.       while (low <= high) {  
  15.           int mid = (low + high) >>> 1;  
  16.           int cmp = comp.compare(x[mid], key);  
  17.           if (cmp < 0) {  
  18.             low= mid + 1;  
  19.           }  
  20.           else if (cmp > 0) {  
  21.             high= mid - 1;  
  22.           }  
  23.           else {  
  24.             return mid;  
  25.           }  
  26.       }  
  27.       return -1;  
  28.    }  
  29.     
  30.    private static<T extends Comparable<T>>intbinarySearch(T[] x, int low, inthigh, T key) {  
  31.       if(low <= high) {  
  32.         int mid = low + ((high -low) >> 1);  
  33.         if(key.compareTo(x[mid])== 0) {  
  34.            return mid;  
  35.         }  
  36.         else if(key.compareTo(x[mid])< 0) {  
  37.            return binarySearch(x,low, mid - 1, key);  
  38.         }  
  39.         else {  
  40.            return binarySearch(x,mid + 1, high, key);  
  41.         }  
  42.       }  
  43.       return -1;  
  44.    }  
  45. }  

說明:兩個版本一個用遞歸實現,一個用循環實現。需要注意的是計算中間位置時不應該使用(high+ low) / 2的方式,因爲加法運算可能導致整數越界,這裏應該使用一下三種方式之一:low+ (high – low) / 2或low + (high – low) >> 1或(low + high) >>> 1(注:>>>是邏輯右移,不帶符號位的右移)

 

139、統計一篇英文文章中單詞個數。

答:

[java] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. import java.io.FileReader;  
  2.    
  3. public class WordCounting {  
  4.    
  5.    publicstatic void main(String[] args) {  
  6.      try(FileReader fr = new FileReader(“a.txt”)) {  
  7.         intcounter = 0;  
  8.         booleanstate = false;  
  9.         intcurrentChar;  
  10.         while((currentChar= fr.read()) != -1) {  
  11.           if(currentChar== ‘ ’ || currentChar == ‘\n’  
  12.              ||currentChar == ’\t’ || currentChar == ‘\r’) {  
  13.              state= false;  
  14.           }  
  15.           elseif(!state) {  
  16.              state= true;  
  17.              counter++;  
  18.           }  
  19.         }  
  20.         System.out.println(counter);  
  21.      }  
  22.      catch(Exceptione) {  
  23.         e.printStackTrace();  
  24.      }  
  25.    }  
  26. }  

補充:這個程序可能有很多種寫法,這裏選擇的是Dennis M. Ritchie和Brian W. Kernighan老師在他們不朽的著作《The C Programming Language》中給出的代碼,向兩位老師致敬。下面的代碼也是如此。

 

140、輸入年月日,計算該日期是這一年的第幾天。

答:

[java] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. import java.util.Scanner;  
  2.    
  3. public classDayCounting {  
  4.    
  5.    public static void main(String[] args) {  
  6.       int[][] data = {  
  7.            {31,2831303130313130313031},  
  8.            {31,2931303130313130313031}  
  9.       };  
  10.       Scannersc = newScanner(System.in);  
  11.       System.out.print(”請輸入年月日(1980 11 28): ”);  
  12.       int year = sc.nextInt();  
  13.       int month = sc.nextInt();  
  14.       int date = sc.nextInt();  
  15.       int[] daysOfMonth =  
  16. data[(year % 4 == 0 && year % 100 != 0 || year % 400 == 0)?1 : 0];  
  17.       int sum = 0;  
  18.       for(int i = 0; i < month -1; i++) {  
  19.         sum+= daysOfMonth[i];  
  20.       }  
  21.       sum+= date;  
  22.       System.out.println(sum);  
  23.       sc.close();  
  24.    }  
  25. }  

 

141、約瑟夫環:15個基督教徒和15個非教徒在海上遇險,必須將其中一半的人投入海中,其餘的人才能倖免於難,於是30個人圍成一圈,從某一個人開始從1報數,報到9的人就扔進大海,他後面的人繼續從1開始報數,重複上面的規則,直到剩下15個人爲止。結果由於上帝的保佑,15個基督教徒最後都倖免於難,問原來這些人是怎麼排列的,哪些位置是基督教徒,哪些位置是非教徒。

答:

[java] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. public classJosephu {  
  2.    private static final int DEAD_NUM = 9;  
  3.     
  4.    public static void main(String[] args) {  
  5.       boolean[] persons = new boolean[30];  
  6.       for(int i = 0; i < persons.length; i++) {  
  7.         persons[i]= true;  
  8.       }  
  9.        
  10.       int counter = 0;  
  11.       int claimNumber = 0;  
  12.       int index = 0;  
  13.       while(counter < 15) {  
  14.         if(persons[index]) {  
  15.            claimNumber++;  
  16.            if(claimNumber == DEAD_NUM) {  
  17.               counter++;  
  18.               claimNumber= 0;  
  19.               persons[index]= false;  
  20.            }  
  21.         }  
  22.         index++;  
  23.         if(index >= persons.length) {  
  24.            index= 0;  
  25.          }  
  26.       }  
  27.       for(boolean p : persons) {  
  28.         if(p) {  
  29.            System.out.print(”基”);  
  30.         }  
  31.         else {  
  32.            System.out.print(”非”);  
  33.         }  
  34.       }  
  35.    }  
  36. }  

 

142、迴文素數:所謂迴文數就是順着讀和倒着讀一樣的數(例如:11,121,1991…),迴文素數就是既是迴文數又是素數(只能被1和自身整除的數)的數。編程找出11~9999之間的迴文素數。

答:

[java] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. public classPalindromicPrimeNumber {  
  2.    
  3.    public static void main(String[] args) {  
  4.       for(int i = 11; i <= 9999;i++) {  
  5.         if(isPrime(i)&& isPalindromic(i)) {  
  6.            System.out.println(i);  
  7.         }  
  8.       }  
  9.    }  
  10.     
  11.    public static boolean isPrime(int n) {  
  12.       for(int i = 2; i <= Math.sqrt(n);i++) {  
  13.          if(n % i == 0) {  
  14.            return false;  
  15.         }  
  16.       }  
  17.       return true;  
  18.    }  
  19.     
  20.    public static boolean isPalindromic(int n) {  
  21.       int temp = n;  
  22.       int sum = 0;  
  23.       while(temp > 0) {  
  24.         sum= sum * 10 + temp % 10;  
  25.         temp/= 10;  
  26.       }  
  27.       return sum == n;  
  28.    }  
  29. }  

 

143、全排列:給出五個數字12345的所有排列。

答:

[java] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. public classFullPermutation {  
  2.    
  3.    public static void perm(int[] list) {  
  4.       perm(list,0);  
  5.    }  
  6.    
  7.    private static void perm(int[] list, int k) {  
  8.       if (k == list.length) {  
  9.         for (int i = 0; i < list.length; i++) {  
  10.            System.out.print(list[i]);  
  11.         }  
  12.          System.out.println();  
  13.       }else{  
  14.         for (int i = k; i < list.length; i++) {  
  15.            swap(list,k, i);  
  16.            perm(list,k + 1);  
  17.            swap(list,k, i);  
  18.         }  
  19.       }  
  20.    }  
  21.    
  22.    private static void swap(int[] list, int pos1, int pos2) {  
  23.       int temp = list[pos1];  
  24.       list[pos1]= list[pos2];  
  25.       list[pos2]= temp;  
  26.    }  
  27.    
  28.    public static void main(String[] args) {  
  29.       int[] x = {12345};  
  30.       perm(x);  
  31.    }  
  32. }  
  33.    

144、對於一個有N個整數元素的一維數組,找出它的子數組(數組中下標連續的元素組成的數組)之和的最大值。

答:下面給出幾個例子(最大子數組用粗體表示):

1) 數組:{ 1, -2, 3,5, -3, 2 },結果是:8

2) 數組:{ 0, -2, 35-12 },結果是:9

3) 數組:{ -9, -2,-3, -5, -3 },結果是:-2

可以使用動態規劃的思想求解:

[java] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. public classMaxSum {  
  2.    
  3.    private static int max(int x, int y) {  
  4.       return x > y? x: y;  
  5.    }  
  6.     
  7.    public static int maxSum(int[] array) {  
  8.       int n = array.length;  
  9.       int[] start = new int[n];  
  10.       int[] all = new int[n];  
  11.       all[n- 1] = start[n - 1] = array[n - 1];  
  12.       for(int i = n - 2; i >= 0;i–) {  
  13.         start[i]= max(array[i], array[i] + start[i + 1]);  
  14.         all[i]= max(start[i], all[i + 1]);  
  15.       }  
  16.       return all[0];  
  17.    }  
  18.     
  19.    public static void main(String[] args) {  
  20.       int[] x1 = { 1, -235,-32 };  
  21.       int[] x2 = { 0, -235,-12 };  
  22.       int[] x3 = { -9, -2, -3,-5, -3 };  
  23.       System.out.println(maxSum(x1));   // 8  
  24.       System.out.println(maxSum(x2));   // 9  
  25.       System.out.println(maxSum(x3));   //-2  
  26.    }  
  27. }  

 

145、用遞歸實現字符串倒轉

答:

[java] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. public classStringReverse {  
  2.    
  3.    public static String reverse(StringoriginStr) {  
  4.       if(originStr == null || originStr.length()== 1) {  
  5.         return originStr;  
  6.       }  
  7.       return reverse(originStr.substring(1))+ originStr.charAt(0);  
  8.    }  
  9.     
  10.    public static void main(String[] args) {  
  11.       System.out.println(reverse(”hello”));  
  12.    }  
  13. }  
  14.    

146、輸入一個正整數,將其分解爲素數的乘積。

答:

[java] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. public classDecomposeInteger {  
  2.    
  3.    private static List<Integer> list = newArrayList<Integer>();  
  4.     
  5.    public static void main(String[] args) {  
  6.       System.out.print(”請輸入一個數: ”);  
  7.       Scannersc = newScanner(System.in);  
  8.       int n = sc.nextInt();  
  9.       decomposeNumber(n);  
  10.       System.out.print(n + ” = ”);  
  11.       for(int i = 0; i < list.size() - 1; i++) {  
  12.         System.out.print(list.get(i) + ” * ”);  
  13.       }  
  14.       System.out.println(list.get(list.size() - 1));  
  15.    }  
  16.     
  17.    public static void decomposeNumber(int n) {  
  18.       if(isPrime(n)) {  
  19.         list.add(n);  
  20.         list.add(1);  
  21.       }  
  22.       else {  
  23.         doIt(n,(int)Math.sqrt(n));  
  24.       }  
  25.    }  
  26.     
  27.    public static void doIt(int n, int div) {  
  28.       if(isPrime(div)&& n % div == 0) {  
  29.         list.add(div);  
  30.         decomposeNumber(n/ div);  
  31.       }  
  32.       else {  
  33.         doIt(n,div - 1);  
  34.       }  
  35.    }  
  36.    
  37.    public static boolean isPrime(int n) {  
  38.       for(int i = 2; i <= Math.sqrt(n);i++) {  
  39.         if(n % i == 0) {  
  40.            return false;  
  41.         }  
  42.       }  
  43.       return true;  
  44.    }  
  45. }  

 

147、一個有n級的臺階,一次可以走1級、2級或3級,問走完n級臺階有多少種走法。

答:可以通過遞歸求解。

[java] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. public classGoSteps {  
  2.    
  3.    public static int countWays(int n) {   
  4.         if(n < 0) {   
  5.             return 0;   
  6.         }   
  7.         else if(n == 0) {   
  8.             return 1;   
  9.         }   
  10.         else {   
  11.             return countWays(n - 1) + countWays(n - 2) + countWays(n -3);   
  12.         }   
  13.    }   
  14.        
  15.    publicstaticvoidmain(String[] args) {   
  16.         System.out.println(countWays(5));   // 13    
  17.    }   
  18. }  

 

148、寫一個算法判斷一個英文單詞的所有字母是否全都不同(不區分大小寫)。

答:

[java] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. public classAllNotTheSame {  
  2.    
  3.    public static boolean judge(String str) {  
  4.       Stringtemp = str.toLowerCase();  
  5.       int[] letterCounter = new int[26];  
  6.       for(int i = 0; i <temp.length(); i++) {  
  7.         int index = temp.charAt(i)- ‘a’;  
  8.         letterCounter[index]++;  
  9.         if(letterCounter[index]> 1) {  
  10.            return false;  
  11.         }  
  12.       }  
  13.       return true;  
  14.    }  
  15.     
  16.    public static void main(String[] args) {  
  17.       System.out.println(judge(”hello”));  
  18.       System.out.print(judge(”smile”));  
  19.    }  
  20. }  


149、有一個已經排好序的整數數組,其中存在重複元素,請將重複元素刪除掉,例如,A= [1, 1, 2, 2, 3],處理之後的數組應當爲A= [1, 2, 3]。

答:

[java] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. import java.util.Arrays;  
  2.    
  3. public classRemoveDuplication {  
  4.    
  5.    public static int[] removeDuplicates(int a[]) {   
  6.         if(a.length <= 1) {   
  7.             return a;   
  8.         }   
  9.         int index = 0;   
  10.         for(int i = 1; i < a.length; i++) {   
  11.             if(a[index] != a[i]) {   
  12.                 a[++index] = a[i];   
  13.             }   
  14.         }   
  15.         int[] b = new int[index + 1];   
  16.         System.arraycopy(a, 0, b, 0, b.length);   
  17.         return b;   
  18.    }   
  19.        
  20.    publicstaticvoidmain(String[] args) {   
  21.         int[] a = {11223};   
  22.         a = removeDuplicates(a);   
  23.         System.out.println(Arrays.toString(a));   
  24.    }   
  25. }  

 

150、給一個數組,其中有一個重複元素佔半數以上,找出這個元素。

答:

[java] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. public classFindMost {  
  2.    
  3.    public static <T> T find(T[] x){  
  4.       Ttemp = null;  
  5.       for(int i = 0, nTimes = 0; i< x.length;i++) {  
  6.         if(nTimes == 0) {  
  7.            temp= x[i];  
  8.            nTimes= 1;  
  9.         }  
  10.         else {  
  11.            if(x[i].equals(temp)) {  
  12.               nTimes++;  
  13.            }  
  14.            else {  
  15.               nTimes–;  
  16.            }  
  17.         }  
  18.       }  
  19.       return temp;  
  20.    }  
  21.     
  22.    public static void main(String[] args) {  
  23.       String[]strs = {”hello”,“kiss”,“hello”,“hello”,“maybe”};  
  24.       System.out.println(find(strs));  
  25.    }  
  26. }  
發佈了59 篇原創文章 · 獲贊 180 · 訪問量 20萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章