題目:給定兩個有序數組,需要找出兩個數組中的相同元素?
笨拙的解法,就是兩層for循環嵌套,時間復雜度為 N 方。
當時回答的解答,兩個下標分別指向數組的頭部,比如,i 指向數組 a 的頭部,j 指向數組 b 的頭部,那么比較 a[i] 和 b[j] ,如果 a[i] 較大,移動 j,如果 b[j] 較大,那么 移動 i,如果相等,那么 i 和 j 往后挪動,采用這種方式,只需要一次遍歷即可,代碼如下:
public class FindCommon { public static List<Integer> getCommons(int[] a , int[] b){ if( a.length <= 0 || b.length <= 0 ){//如果任何一個數組為空,那么就沒有相同元素,邊界判斷 return null; } List commons = new ArrayList<>(); int i = 0,j=0; for (;i<a.length;i++){ if( j >= b.length){ break; } //如果 a[i] 較大,那么就移動 j(前提:兩個數組都是有序數組) while ( j < b.length-1 && a[i] > b[j]){ j++; } if(a[i] == b[j]){ commons.add(a[i]); if( j < b.length ){ j++; } } } return commons; } public static void main(String[] args) { int a[] = {1,1,1,1,3,5,6,8,9}; int b[] = {1,1,3,5,7,10,12}; List<Integer> result = getCommons(b,a); for (int i : result){ System.out.print(i+","); } } }
運行結果如下:
細心的童鞋,可能會發現,當 a[i] > a[j] 的時候,我多加了一個判斷: j < b.length - 1 ,為什么呢?是因為,如果是 j < b.length 時,這種情況下,j 已經到達了 b[] 的末尾,然而在末尾的時候,做了j++的運算,在下邊的判斷 a[i] == b[j] 的地方就會發生下標越界的情況,希望大家來糾錯!