G面经prepare: Set Intersection Set Difference
生活随笔
收集整理的這篇文章主要介紹了
G面经prepare: Set Intersection Set Difference
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
求兩個sorted數(shù)組的intersection e.g. [1,2,3,4,5],[2,4,6] 結(jié)果是[2,4]
difference
類似merge, 分小于等于大于三種情況,然后時間O(m+n), 空間O(1)
1 package ShortestSubsequenceIncluding; 2 import java.util.*; 3 4 public class Solution2 { 5 public ArrayList<Integer> setInters(int[] arr1, int[] arr2) { 6 int i1=0, i2=0; 7 ArrayList<Integer> res = new ArrayList<Integer>(); 8 while (i1<arr1.length && i2<arr2.length) { 9 if (arr1[i1] < arr2[i2]) i1++; 10 else if (arr1[i1] > arr2[i2]) i2++; 11 else { 12 res.add(arr1[i1]); 13 i1++; 14 i2++; 15 } 16 } 17 return res; 18 } 19 20 public ArrayList<Integer> setDiff(int[] arr1, int[] arr2) { 21 int i1=0, i2=0; 22 ArrayList<Integer> res = new ArrayList<Integer>(); 23 while (i1<arr1.length && i2<arr2.length) { 24 if (arr1[i1] < arr2[i2]) { 25 res.add(arr1[i1]); 26 i1++; 27 } 28 else if (arr1[i1] > arr2[i2]) { 29 i2++; 30 } 31 else { 32 i1++; 33 i2++; 34 } 35 } 36 while (i1 < arr1.length) { 37 res.add(arr1[i1]); 38 i1++; 39 } 40 return res; 41 } 42 43 44 /** 45 * @param args 46 */ 47 public static void main(String[] args) { 48 // TODO Auto-generated method stub 49 Solution2 sol = new Solution2(); 50 ArrayList<Integer> res1 = sol.setInters(new int[]{1,2,3,4,4,5}, new int[]{2,4,4,6}); 51 ArrayList<Integer> res2 = sol.setDiff(new int[]{2,3,4,4,4,5}, new int[]{1,2,4,4,6}); 52 System.out.println(res2); 53 54 } 55 56 }如果是無序的兩個array,則Build兩個hashMap, 遍歷第一個map的keySet, O(m+n)time, O(m+n)space
轉(zhuǎn)載于:https://www.cnblogs.com/EdwardLiu/p/5144654.html
總結(jié)
以上是生活随笔為你收集整理的G面经prepare: Set Intersection Set Difference的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [读书笔记]C#学习笔记三: C#类型详
- 下一篇: BSEG和BSIS、BSAS、BSID、