面試中,經常會問到算法問題,比如如何合並兩個有序的整型有序數組,使之變成一個有序數組。
我的代碼如下:
1 package com.company.algorithm; 2 3 import java.util.Arrays; 4 5 /** 6 * 合並兩個有序數組 7 */ 8 public class MergeSortedArray { 9 public static void main(String[] args) { 10 int[] a = {0, 3, 4, 6, 9, 12}; 11 int[] b = {1, 2, 5, 7, 8, 10, 11}; 12 int[] c = marge(a, b); 13 System.out.println(Arrays.toString(c)); 14 } 15 16 /** 17 * 合並連個有序數組 18 * 算法: 19 * 1. 設置兩個指針i,j,分別指向a數組和b數組,一個執行合並后數組的指針index; 20 * 2. 比較指針i,j指向的值,小的值存入指針index指向的結果數組中,當有一個指針(i或j)先到達數組末尾時,比較結束; 21 * 3. 將指針(i或j)沒有到達數組末尾的數組復制到指針index指向的結果數組中 22 * @param a 23 * @param b 24 * @return 25 */ 26 private static int[] marge(int[] a, int[] b) { 27 int[] c = new int[a.length + b.length]; 28 int i = 0, j = 0; 29 int index = 0; 30 //比較指針i,j指向的值,小的值存入指針index指向的結果數組中,當有一個指針(i或j)先到達數組末尾時,比較結束; 31 while (i < a.length && j < b.length) { 32 if (a[i] < b[j]) { 33 c[index++] = a[i++]; 34 } else { 35 c[index++] = b[j++]; 36 } 37 } 38 int l; 39 //將指針(i或j)沒有到達數組末尾的數組復制到指針index指向的結果數組中 40 if (i < a.length) { 41 for (l = i; l < a.length; l++) { 42 c[index++] = a[l]; 43 } 44 } 45 //將指針(i或j)沒有到達數組末尾的數組復制到指針index指向的結果數組中 46 if (j < b.length) { 47 for (l = j; l < b.length; l++) { 48 c[index++] = b[l]; 49 } 50 } 51 return c; 52 } 53 }