当前位置:   article > 正文

LeetCode 5268. 找出两数组的不同_public list> finddifference(int[] nu

public list> finddifference(int[] nums1, int[] nums2)怎么调用

题目链接:

力扣icon-default.png?t=M276https://leetcode-cn.com/problems/find-the-difference-of-two-arrays/

【分析】用两个HashSet去重,然后分别遍历,可以以O(1)的复杂度查找在不在另一个集合中。

  1. class Solution {
  2. public List<List<Integer>> findDifference(int[] nums1, int[] nums2) {
  3. List<List<Integer>> ans = new ArrayList<>();
  4. int i, n;
  5. for(i = 0; i < 2; i++) ans.add(new ArrayList<>());
  6. Set<Integer> s = new HashSet<>();
  7. Set<Integer> t = new HashSet<>();
  8. for(Integer it: nums1) s.add(it);
  9. for(Integer it: nums2) t.add(it);
  10. for(Integer it: s){
  11. if(!t.contains(it)) ans.get(0).add(it);
  12. }
  13. for(Integer it: t){
  14. if(!s.contains(it)) ans.get(1).add(it);
  15. }
  16. return ans;
  17. }
  18. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/50337
推荐阅读
相关标签
  

闽ICP备14008679号