LeetCode 217. 存在重复元素

作者: TheKey_ | 来源:发表于2019-08-22 20:42 被阅读3次

217. 存在重复元素

给定两个数组,编写一个函数来计算它们的交集。

示例1:
输入: nums1 = [1,2,2,1], nums2 = [2,2]
输出: [2]
示例2:
输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出: [9,4]
说明:
  • 输出结果中的每个元素一定是唯一的。
  • 我们可以不考虑输出结果的顺序。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/intersection-of-two-arrays/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


  • 1. 排序法

思路:

  1. 首先对数组进行排序
  2. 遍历数组,判断数组当前元素的值和后一个值是否相等,如果相等,那么肯定存在重复元素,否则不存在
public static boolean containsDuplicate(int[] nums) {
        Arrays.sort(nums);
        for (int i = 0; i < nums.length - 1; i++) {
            if (nums[i] == nums[i + 1]) return true;
        }
        return false;
    }

复杂度分析:

  • 时间复杂度:O(n log(n)), 主要取决于数组排序

  • 空间复杂度:O(1), 只需要常数级别的空间复杂度

  • 2. set集合法

思路:

  1. 创建一个set集合
  2. 遍历数组,判断set中是否包含该元素,如果包含,则return true, 否则将元素添加到 set 中
public static boolean containsDuplicate(int[] nums) {
        Set<Integer> set = new HashSet<>();
        for (int num : nums) {
            if (set.contains(num)) return true;
            else set.add(num);
        }
        return false;
    }

复杂度分析:

  • 时间复杂度:O(n), 在遍历数组 nums 的过程中,需要判断set中是否包含(由于使用的是HashSet, 所以插入和查找操作复杂度均为 O(1)),总的时间复杂度为O(n);

  • 空间复杂度:O(n), 最坏情况下需要创建容量为 n 为集合

  • 测试用例

 public static void main(String[] args) {
         int[] nums = {1,1,1,3,3,4,3,2,4,2};
         System.out.println(Arrays.toString(nums));
         System.out.println(containsDuplicate2(nums));
    }
  • 结果

[1, 1, 1, 3, 3, 4, 3, 2, 4, 2]
true

  • 源码

  • 我会每天更新新的算法,并尽可能尝试不同解法,如果发现问题请指正
  • Github

相关文章

网友评论

    本文标题:LeetCode 217. 存在重复元素

    本文链接:https://www.haomeiwen.com/subject/ejgosctx.html