力扣442.数组中重复的数据(java语言HashMap法,排序法)

题目描述:

给你一个长度为 n 的整数数组 nums ,其中 nums 的所有整数都在范围 [1, n] 内,且每个整数出现 一次 或 两次 。请你找出所有出现 两次 的整数,并以数组形式返回。

你必须设计并实现一个时间复杂度为 O(n) 且仅使用常量额外空间的算法解决此问题。

在这里插入图片描述

解题思路:

思路1:HashMap

我们先创建一个ArrayList集合和和HashMap集合,将数组中的元素作为键,索引作为值依次存入HashMap中,若已经存在与集合中则将该元素添加到ArrayList集合中。

代码
class Solution {
	//HashMap
	//Time Complexity: O(N)
	//Space Complexit: O(M) M为重复元素的个数
	public List<Integer> findDuplicates(int[] nums) {
		Map<Integer, Integer> map = new HashMap<>();
		List<Integer> res = new ArrayList<>();
		//若nums长度小于等于1,则直接返回空数组
		if (nums.length <= 1) {
			return new ArrayList<>();
		}
		for (int i = 0; i < nums.length; i++) {
			if (map.containsKey(nums[i])) {
				res.add(nums[i]);
			} else {
				map.put(nums[i],i);
			}
		}
		return res;
	}
}

思路二:排序法

由于题目中给的元素范围是1-n,所以若我们对元素升序排序后,重复的元素就会相邻,此时我们再遍历数组判断若相邻的元素相等则将其添加到事先创建的ArrayList集合中

代码:
class Solution {
	//Sorts
	//Time Complexity: O(NlogN)
	//Space Complexity: O(M) M为重复元素的个数
	public static List<Integer> findDuplicates(int[] nums) {
		//对原数组升序排序
		Arrays.sort(nums);
		List<Integer> res = new ArrayList<>();
		if (nums.length <= 1) {
			return new ArrayList<>();
		}
		for (int i = 1; i < nums.length; i++) {
			if (nums[i] == nums[i-1]) {
				res.add(nums[i]);
			}
		}
		return res;
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值