12.LeetCode:Intersection of Two Arrays

小咪咪 2022-02-28 14:30 210阅读 0赞

题目:

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2NsNzIzNDAx_size_16_color_FFFFFF_t_70

使用集合:

  1. public class IntersectionOfArraySolution {
  2. public int[] intersection(int[] nums1, int[] nums2) {
  3. TreeSet<Integer> set = new TreeSet<>();
  4. for (int num:nums1) {
  5. set.add(num);
  6. }
  7. ArrayList<Integer> list = new ArrayList<>();
  8. for (int num:nums2) {
  9. if(set.contains(num)){
  10. list.add(num);
  11. //num2可能有重复的元素,如果不移除set的num,必然下次又匹配了
  12. set.remove(num);
  13. }
  14. }
  15. int[] res = new int[list.size()];
  16. for (int i=0;i<list.size();i++){
  17. res[i]=list.get(i);
  18. }
  19. return res;
  20. }
  21. }

发表评论

表情:
评论列表 (有 0 条评论,210人围观)

还没有评论,来说两句吧...

相关阅读

    相关 LeetCode:Median of Two Sorted Arrays

    第四题是找两个已经排序的数组的中位数,其实就是寻找两个排序数组的第k个数。寻找第k个数就需要把k均分到两个数组,可以用到结论如果a\[k/2-1\]小雨b\[k/2-1\],那