2020年5月2日 星期六

[LeetCode] 350. Intersection of Two Arrays II 解題思路 (Easy)



這題需要判斷兩個陣列共通的數字有哪些,返回一個結果陣列。




LeetCode 題目連結

 

https://leetcode.com/problems/intersection-of-two-arrays-ii/

 

題目

Given two arrays, write a function to compute their intersection.
Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]
Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [4,9]
Note:
  • Each element in the result should appear as many times as it shows in both arrays.
  • The result can be in any order.

Accept 作法


這題利用 HashSet 去判斷重複的部分。


Runtime: 9 ms
Memory: 39.7 MB

Java 程式碼

  1. class Solution {
  2. public int[] intersect(int[] nums1, int[] nums2) {
  3. ArrayList<Integer> list = new ArrayList<Integer>();
  4. HashSet<Integer> map =new HashSet<Integer>();
  5. for(int i = 0;i<nums1.length;i++){
  6. for(int j = 0;j<nums2.length;j++){
  7. if(nums1[i] == nums2[j] && !map.contains(j)){
  8. list.add(nums1[i]);
  9. map.add(j);
  10. break;
  11. }
  12. }
  13. }
  14. int[] resultArray = new int[list.size()];
  15. for(int i = 0;i<resultArray.length;i++){
  16. resultArray[i] = list.get(i);
  17. }
  18. return resultArray;
  19. }
  20. }

再來第二種解法是 Two Pointer 的解法。

Java 程式碼

  1. class Solution {
  2. public int[] intersect(int[] nums1, int[] nums2) {
  3. ArrayList<Integer> list = new ArrayList<Integer>();
  4. int cursor = 0;
  5. int cursor2 = 0;
  6. Arrays.sort(nums1);
  7. Arrays.sort(nums2);
  8. while(cursor < nums1.length && cursor2 < nums2.length){
  9. if(nums1[cursor] == nums2[cursor2]){
  10. list.add(nums1[cursor]);
  11. cursor ++;
  12. cursor2 ++;
  13. }else if(nums1[cursor] > nums2[cursor2]){
  14. cursor2 ++;
  15. }else if(nums1[cursor] < nums2[cursor2]){
  16. cursor ++;
  17. }
  18. }
  19. int[] resultArray = new int[list.size()];
  20. for(int i = 0;i<resultArray.length;i++){
  21. resultArray[i] = list.get(i);
  22. }
  23. return resultArray;
  24. }
  25. }

 

更多 LeetCode 相關資源

 

複習程式面試書籍


除了 LeetCode 練習外,我也入手了這本,題庫來自真正的面試,並非摘自教科書。它們反映出頂尖公司真正會出的題目,你可以藉此做好充分準備
需要的話可以看看,寫得很仔細。

書名:提升程式設計師的面試力:189道面試題目與解答



相關 LeetCode文章一律會放在 程式解題 標籤分類,歡迎持續追蹤。

沒有留言:

張貼留言