LeetCode日记 442.数组中重复的数据

给定一个整数数组 a,其中1 ≤ a[i] ≤ n (n为数组长度), 其中有些元素出现两次而其他元素出现一次。

找到所有出现两次的元素。

你可以不用到任何额外空间并在O(n)时间复杂度内解决这个问题吗?

示例:

输入:
[4,3,2,7,8,2,3,1]

输出:
[2,3]

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

  • 思路:遍历一次数组,每次读取num[i]的值,取| nums[i] |-1作为索index,若index对应元素>0,则表示其没被修改过,那么就将它取反(取反的目的有两点,一是为了标记index+1这个数出现过了,二是保存index对应的原数据,下一次我们要是在此使用该数据时取其绝对值就能获取到原数据了)。若index对应元素<0则表示该数据出现过了,是重复的,将index+1添加到结果集
class Solution {
    public List<Integer> findDuplicates(int[] nums) {
        List<Integer> res = new ArrayList();
        int len = nums.length;
        for(int i = 0;i < len;i++){
            int index = Math.abs(nums[i])-1;            
            if(nums[index]>0){
                nums[index] = -nums[index];
            }else if(nums[index]<0){
                res.add(index+1);
            }
           
        }
        return res;
    }
}

法2:原地哈希法:

class Solution {

      public void swap(int[] arr,int i,int j){
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    public List<Integer> findDuplicates(int[] nums) {
        List<Integer> res = new ArrayList();
         for(int i = 0;i < nums.length; i++){
        //如果没有放到正确的位置上,就交换。
            while(nums[nums[i]-1]!=nums[i]){
                swap(nums,nums[i]-1,i);
            }                   
        }
        //只出现一次的数字,肯定已经放到正确的位置上了。出现了两次以上的数字肯定有一个没放到正确的位置上
        for(int i = 0;i < nums.length;i++){
            if(nums[i]!=i+1){
                res.add(nums[i]);
            }
        }
        return res;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值