力扣算法——数组中重复的数据

442.数组中重复的数据

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

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

示例 1:

输入:nums = [4,3,2,7,8,2,3,1]
输出:[2,3]
示例 2:

输入:nums = [1,1,2]
输出:[1]
示例 3:

输入:nums = [1]
输出:[]

//没看题的遍历,时间长主要是因为进行了排序
class Solution {
    public List<Integer> findDuplicates(int[] nums) {
    	//讲数组进行从小到大排序,使重复数据聚集一起
        Arrays.sort(nums);
        List<Integer> list = new ArrayList<Integer>();
        for(int i=0;i<nums.length-1;i++){
        	//不相等时就跳过
            if(nums[i]!=nums[i+1]){
                continue;
            }
            //相等时但已经包含就跳过
            if(list.contains(nums[i])){
                if((i+2)==nums.length){
                    break;
                }else{
                    i=i+2;
                }
            }
            list.add(nums[i]);
        }
        return list;
    }
}


//作者:stormsunshine
//链接:https://leetcode-cn.com/problems/find-all-duplicates-in-an-array/solution/by-stormsunshine-ojmz/
//来源:力扣(LeetCode)
//著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
//题解
//思想:因为数组数值范围必须小于数组的长度,数组遍历是0到n-1的
//所以以数组数值-1为下标,如果两数相同,数组数值-1会在同一下标,所以只要过一数值时打上标记
//这个题解就很好的运用了相反数来做标记
class Solution {
    public List<Integer> findDuplicates(int[] nums) {
        List<Integer> duplicates = new ArrayList<Integer>();
        int n = nums.length;
        for (int i = 0; i < n; i++) {
            int num = nums[i];
            int index = Math.abs(num) - 1;
            if (nums[index] > 0) {
                nums[index] = -nums[index];
            } else {
                duplicates.add(index + 1);
            }
        }
        return duplicates;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值