Java面试题集(136-150)

136、给出下面的二叉树先序、中序、后序遍历的序列?


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

补充:二叉树也称为二分树,它是树形结构的一种,其特点是每个结点至多有二棵子树,并且二叉树的子树有左右之分,其次序不能任意颠倒。二叉树的遍历序列按照访问根节点的顺序分为先序(先访问根节点,接下来先序访问左子树,再先序访问右子树)、中序(先中序访问左子树,然后访问根节点,最后中序访问右子树)和后序(先后序访问左子树,再后序访问右子树,最后访问根节点)。如果知道一棵二叉树的先序和中序序列或者中序和后序序列,那么也可以还原出该二叉树。

例如,已知二叉树的先序序列为:xefdzmhqsk,中序序列为:fezdmxqhks,那么还原出该二叉树应该如下图所示:

 

137、你知道的排序算法都哪些?用Java写一个排序系统。

答:稳定的排序算法有:插入排序、选择排序、冒泡排序、鸡尾酒排序、归并排序、二叉树排序、基数排序等;不稳定排序算法包括:希尔排序、堆排序、快速排序等。

下面是关于排序算法的一个列表:


下面按照策略模式给出一个排序系统,实现了冒泡、归并和快速排序。

Sorter.java

[java]  view plain  copy
  1. package com.jackfrued.util;  
  2.    
  3. import java.util.Comparator;  
  4.    
  5. /** 
  6.  * 排序器接口(策略模式: 将算法封装到具有共同接口的独立的类中使得它们可以相互替换) 
  7.  * @author骆昊 
  8.  * 
  9.  */  
  10. public interface Sorter {  
  11.     
  12.    /** 
  13.     * 排序 
  14.     * @param list 待排序的数组 
  15.     */  
  16.    public <T extends Comparable<T>> void sort(T[] list);  
  17.     
  18.    /** 
  19.     * 排序 
  20.     * @param list 待排序的数组 
  21.     * @param comp 比较两个对象的比较器 
  22.     */  
  23.    public <T> void sort(T[] list, Comparator<T> comp);  
  24. }  

 

BubbleSorter.java

[java]  view plain  copy
  1. package com.jackfrued.util;  
  2.    
  3. import java.util.Comparator;  
  4.    
  5. /** 
  6.  * 冒泡排序 
  7.  * @author骆昊 
  8.  * 
  9.  */  
  10. public class BubbleSorter implements Sorter {  
  11.    
  12.    @Override  
  13.    public <T extends Comparable<T>> void sort(T[] list) {  
  14.       boolean swapped = true;  
  15.       for(int i = 1; i < list.length && swapped;i++) {  
  16.         swapped= false;  
  17.         for(int j = 0; j < list.length - i; j++) {  
  18.            if(list[j].compareTo(list[j+ 1]) > 0 ) {  
  19.               T temp = list[j];  
  20.               list[j]= list[j + 1];  
  21.               list[j+ 1] = temp;  
  22.               swapped= true;  
  23.            }  
  24.         }  
  25.       }  
  26.    }  
  27.    
  28.    @Override  
  29.    public <T> void sort(T[] list,Comparator<T> comp) {  
  30.       boolean swapped = true;  
  31.       for(int i = 1; i < list.length && swapped; i++) {  
  32.         swapped = false;  
  33.         for(int j = 0; j < list.length - i; j++) {  
  34.            if(comp.compare(list[j], list[j + 1]) > 0 ) {  
  35.               T temp = list[j];  
  36.               list[j]= list[j + 1];  
  37.               list[j+ 1] = temp;  
  38.               swapped= true;  
  39.            }  
  40.         }  
  41.       }  
  42.    }   
  43. }  

 

MergeSorter.java

[java]  view plain  copy
  1. package com.jackfrued.util;  
  2.    
  3. import java.util.Comparator;  
  4.    
  5. /** 
  6.  * 归并排序 
  7.  * 归并排序是建立在归并操作上的一种有效的排序算法。 
  8.  * 该算法是采用分治法(divide-and-conquer)的一个非常典型的应用, 
  9.  * 先将待排序的序列划分成一个一个的元素,再进行两两归并, 
  10.  * 在归并的过程中保持归并之后的序列仍然有序。 
  11.  * @author骆昊 
  12.  * 
  13.  */  
  14. public class MergeSorter implements Sorter {  
  15.    
  16.    @Override  
  17.    public <T extends Comparable<T>> void sort(T[] list) {  
  18.       T[] temp = (T[]) new Comparable[list.length];  
  19.       mSort(list,temp, 0, list.length- 1);  
  20.    }  
  21.     
  22.    private <T extends Comparable<T>> void mSort(T[] list, T[] temp, int low, int high) {  
  23.       if(low == high) {  
  24.         return ;  
  25.       }  
  26.       else {  
  27.         int mid = low + ((high -low) >> 1);  
  28.         mSort(list,temp, low, mid);  
  29.         mSort(list,temp, mid + 1, high);  
  30.         merge(list,temp, low, mid + 1, high);  
  31.       }  
  32.    }  
  33.     
  34.    private <T extends Comparable<T>> void merge(T[] list, T[] temp, int left, int right, int last) {  
  35.         int j = 0;   
  36.         int lowIndex = left;   
  37.         int mid = right - 1;   
  38.         int n = last - lowIndex + 1;   
  39.         while (left <= mid && right <= last){   
  40.             if (list[left].compareTo(list[right]) < 0){   
  41.                 temp[j++] = list[left++];   
  42.             } else {   
  43.                 temp[j++] = list[right++];   
  44.             }   
  45.         }   
  46.         while (left <= mid) {   
  47.             temp[j++] = list[left++];   
  48.         }   
  49.         while (right <= last) {   
  50.             temp[j++] = list[right++];   
  51.         }   
  52.         for (j = 0; j < n; j++) {   
  53.             list[lowIndex + j] = temp[j];   
  54.         }   
  55.    }  
  56.    
  57.    @Override  
  58.    public <T> void sort(T[] list, Comparator<T> comp) {  
  59.       T[]temp = (T[])new Comparable[list.length];  
  60.       mSort(list,temp, 0, list.length- 1, comp);  
  61.    }  
  62.     
  63.    private <T> void mSort(T[] list, T[] temp, int low, int high, Comparator<T> comp) {  
  64.       if(low == high) {  
  65.         return ;  
  66.       }  
  67.       else {  
  68.         int mid = low + ((high -low) >> 1);  
  69.         mSort(list,temp, low, mid, comp);  
  70.         mSort(list,temp, mid + 1, high, comp);  
  71.         merge(list,temp, low, mid + 1, high, comp);  
  72.       }  
  73.    }  
  74.     
  75.    private <T> void merge(T[] list, T[]temp, int left, int right, int last, Comparator<T> comp) {  
  76.         int j = 0;   
  77.         int lowIndex = left;   
  78.         int mid = right - 1;   
  79.         int n = last - lowIndex + 1;   
  80.         while (left <= mid && right <= last){   
  81.             if (comp.compare(list[left], list[right]) <0) {   
  82.                 temp[j++] = list[left++];   
  83.             } else {   
  84.                 temp[j++] = list[right++];   
  85.             }   
  86.         }   
  87.         while (left <= mid) {   
  88.             temp[j++] = list[left++];   
  89.         }   
  90.         while (right <= last) {   
  91.             temp[j++] = list[right++];   
  92.         }   
  93.         for (j = 0; j < n; j++) {   
  94.             list[lowIndex + j] = temp[j];   
  95.         }   
  96.    }  
  97.    
  98. }  

 

QuickSorter.java

[java]  view plain  copy
  1. package com.jackfrued.util;  
  2.    
  3. import java.util.Comparator;  
  4.    
  5. /** 
  6.  * 快速排序 
  7.  * 快速排序是使用分治法(divide-and-conquer)依选定的枢轴 
  8.  * 将待排序序列划分成两个子序列,其中一个子序列的元素都小于枢轴, 
  9.  * 另一个子序列的元素都大于或等于枢轴,然后对子序列重复上面的方法, 
  10.  * 直到子序列中只有一个元素为止 
  11.  * @author Hao 
  12.  * 
  13.  */  
  14. public class QuickSorter implements Sorter {  
  15.    
  16.    @Override  
  17.    public <T extends Comparable<T>> void sort(T[] list) {  
  18.       quickSort(list, 0, list.length- 1);  
  19.    }  
  20.    
  21.    @Override  
  22.    public <T> void sort(T[] list, Comparator<T> comp) {  
  23.       quickSort(list, 0, list.length- 1, comp);  
  24.    }  
  25.    
  26.    private <T extends Comparable<T>> void quickSort(T[] list, int first, int last) {  
  27.       if (last > first) {  
  28.         int pivotIndex = partition(list, first, last);  
  29.         quickSort(list, first, pivotIndex - 1);  
  30.         quickSort(list, pivotIndex, last);  
  31.       }  
  32.    }  
  33.     
  34.    private <T> void quickSort(T[] list, int first, int last,Comparator<T> comp) {  
  35.       if (last > first) {  
  36.         int pivotIndex = partition(list, first, last, comp);  
  37.         quickSort(list, first, pivotIndex - 1, comp);  
  38.         quickSort(list, pivotIndex, last, comp);  
  39.       }  
  40.    }  
  41.    
  42.    private <T extends Comparable<T>> int partition(T[] list, int first, int last) {  
  43.       T pivot = list[first];  
  44.       int low = first + 1;  
  45.       int high = last;  
  46.    
  47.       while (high > low) {  
  48.         while (low <= high && list[low].compareTo(pivot) <= 0) {  
  49.            low++;  
  50.         }  
  51.         while (low <= high && list[high].compareTo(pivot) >= 0) {  
  52.            high--;  
  53.         }  
  54.         if (high > low) {  
  55.            T temp = list[high];  
  56.            list[high]= list[low];  
  57.            list[low]= temp;  
  58.         }  
  59.       }  
  60.    
  61.       while (high > first&& list[high].compareTo(pivot) >= 0) {  
  62.         high--;  
  63.       }  
  64.       if (pivot.compareTo(list[high])> 0) {  
  65.         list[first]= list[high];  
  66.         list[high]= pivot;  
  67.         return high;  
  68.       }  
  69.       else {  
  70.         return low;  
  71.       }  
  72.    }  
  73.    
  74.    private <T> int partition(T[] list, int first, int last, Comparator<T> comp) {  
  75.       T pivot = list[first];  
  76.       int low = first + 1;  
  77.       int high = last;  
  78.    
  79.       while (high > low) {  
  80.         while (low <= high&& comp.compare(list[low], pivot) <= 0) {  
  81.            low++;  
  82.         }  
  83.         while (low <= high&& comp.compare(list[high], pivot) >= 0) {  
  84.            high--;  
  85.         }  
  86.         if (high > low) {  
  87.            T temp = list[high];  
  88.            list[high] = list[low];  
  89.            list[low]= temp;  
  90.         }  
  91.       }  
  92.    
  93.       while (high > first&& comp.compare(list[high], pivot) >= 0) {  
  94.         high--;  
  95.       }  
  96.       if (comp.compare(pivot,list[high]) > 0) {  
  97.         list[first]= list[high];  
  98.         list[high]= pivot;  
  99.         return high;  
  100.       }  
  101.       else {  
  102.         return low;  
  103.       }  
  104.    }  
  105.     
  106. }  

 

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

答:折半搜索,也称二分查找算法、二分搜索,是一种在有序数组中查找某一特定元素的搜索算法。搜素过程从数组的中间元素开始,如果中间元素正好是要查找的元素,则搜素过程结束;如果某一特定元素大于或者小于中间元素,则在数组大于或小于中间元素的那一半中查找,而且跟开始一样从中间元素开始比较。如果在某一步骤数组为空,则代表找不到。这种搜索算法每一次比较都使搜索范围缩小一半。

[java]  view plain  copy
  1. package com.jackfrued.util;  
  2.    
  3. import java.util.Comparator;  
  4.    
  5. public class MyUtil {  
  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>> int binarySearch(T[] x, int low, int high, 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,l ow, 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 plain  copy
  1. import java.io.FileReader;  
  2.    
  3. public class WordCounting {  
  4.    
  5.    public static void main(String[] args) {  
  6.      try(FileReader fr = new FileReader("a.txt")) {  
  7.         int counter = 0;  
  8.         boolean state = false;  
  9.         int currentChar;  
  10.         while((currentChar= fr.read()) != -1) {  
  11.           if(currentChar== ' ' || currentChar == '\n'  
  12.              || currentChar == '\t' || currentChar == '\r') {  
  13.              state = false;  
  14.           }  
  15.           else if(!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 plain  copy
  1. import java.util.Scanner;  
  2.    
  3. public class DayCounting {  
  4.    
  5.    public static void main(String[] args) {  
  6.       int[][] data = {  
  7.            {31,2831303130313130313031},  
  8.            {31,2931303130313130313031}  
  9.       };  
  10.       Scanner sc = 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 = data[(year % 4 == 0 && year % 100 != 0 || year % 400 == 0)?1 : 0];  
  16.       int sum = 0;  
  17.       for(int i = 0; i < month -1; i++) {  
  18.         sum += daysOfMonth[i];  
  19.       }  
  20.       sum += date;  
  21.       System.out.println(sum);  
  22.       sc.close();  
  23.    }  
  24. }  

 

141、约瑟夫环:15个基督教徒和15个非教徒在海上遇险,必须将其中一半的人投入海中,其余的人才能幸免于难,于是30个人围成一圈,从某一个人开始从1报数,报到9的人就扔进大海,他后面的人继续从1开始报数,重复上面的规则,直到剩下15个人为止。结果由于上帝的保佑,15个基督教徒最后都幸免于难,问原来这些人是怎么排列的,哪些位置是基督教徒,哪些位置是非教徒。

答:

[java]  view plain  copy
  1. public class Josephu {  
  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 plain  copy
  1. public class PalindromicPrimeNumber {  
  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 plain  copy
  1. public class FullPermutation {  
  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 plain  copy
  1. public class MaxSum {  
  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 plain  copy
  1. public class StringReverse {  
  2.    
  3.    public static String reverse(String originStr) {  
  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 plain  copy
  1. public class DecomposeInteger {  
  2.    
  3.    private static List<Integer> list = newArrayList<Integer>();  
  4.     
  5.    public static void main(String[] args) {  
  6.        System.out.print("请输入一个数: ");  
  7.        Scanner sc = 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 plain  copy
  1. public class GoSteps {  
  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.    public static void main(String[] args) {   
  16.         System.out.println(countWays(5));   // 13    
  17.    }   
  18. }  

 

148、写一个算法判断一个英文单词的所有字母是否全都不同(不区分大小写)。

答:

[java]  view plain  copy
  1. public class AllNotTheSame {  
  2.    
  3.    public static boolean judge(String str) {  
  4.       String temp = 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 plain  copy
  1. import java.util.Arrays;  
  2.    
  3. public class RemoveDuplication {  
  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.    public static void main(String[] args) {   
  21.         int[] a = {11223};   
  22.         a = removeDuplicates(a);   
  23.         System.out.println(Arrays.toString(a));   
  24.    }   
  25. }  

 

150、给一个数组,其中有一个重复元素占半数以上,找出这个元素。

答:

[java]  view plain  copy
  1. public class FindMost {  
  2.    
  3.    public static <T> T find(T[] x){  
  4.       T temp = 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. }  
  27.    
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值