
LeetCode 350 Intersection of Two Arrays II 题解
1.题目:
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].
题意:
返回两个数组的公共部分
2.解题思路:
感觉有点暴力
3.代码
[title] [] [url] [link text]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
|
public class { public int[] intersect(int[] nums1, int[] nums2) { Arrays.sort(nums1); Arrays.sort(nums2); ArrayList<Integer> ansArrayList = new ArrayList<Integer>(); int len1 = nums1.length; int len2 = nums2.length; int i = 0; int j = 0; for (; i < len1 && j < len2;) { if (nums1[i] == nums2[j]) { ansArrayList.add(nums1[i]); i++; j++;
} else if (nums1[i] > nums2[j]) { j++; } else { i++; } } int[] ans = new int[ansArrayList.size()]; for (int k = 0; k < ansArrayList.size(); k++) { ans[k] = ansArrayList.get(k); } return ans;
} }
|
4.一些总结:
近期评论