数组中重复的数字

题目描述

在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。

解题思路:如果你想用map的方式来查找第一个重复数字,这种想法是ok的,但是这样会付出o(n)的空间复杂度。我这主要介绍一种不需要额外空间的做法,但是会改变数组内部结构。从数组的特点来看,这里的数字都是在0~n-1之间的,而数组长度就是n;那么假设这个数字中没有重复的数字,那么数组中的数字就是0~n-1每个数字出现一次,而且若对这个数组排序,你会发现第i位山的数字正好是数组第i个位置上的值即i==numbers[i];根据以上分析,我们从最终结果入手,我们要重新对这个数组进行排序,根据数组中数字的特点我们可以按一下方式进行排序:从头到尾依次扫描数组中的每一个数字,当扫描到下标为i的数字时,首先比较这个数字m是不是等于i,如果是,那就扫描下一个数字;如果不是,再拿他和第m个数字进行比较,如果他和第m个数字相等,那就找到重复数字,如果不相等,就将交换第i个数字和第m个数字,知道第i为上的数字等于i才开始扫描下一个数字。

代码如下:

public class Solution {
    // Parameters:
    //    numbers:     an array of integers
    //    length:      the length of array numbers
    //    duplication: (Output) the duplicated number in the array number,length of duplication array is 1,so using duplication[0] = ? in implementation;
    //                  Here duplication like pointor in C/C++, duplication[0] equal *duplication in C/C++
    //    这里要特别注意~返回任意重复的一个,赋值duplication[0]
    // Return value:       true if the input is valid, and there are some duplications in the array number
    //                     otherwise false
    public boolean duplicate(int numbers[],int length,int [] duplication) {
        boolean result = false;
    	for(int i = 0; i < length; i++) {
            while (i != numbers[i]) {
                if (numbers[numbers[i]] == numbers[i]) {
                    duplication[0] = numbers[i];
                    return true;
                } else {
                    swap(numbers,i,numbers[i]);
                }
            }
        }
        return result;
    }
    
    public void swap(int[] numbers, int index1, int index2) {
        int temp = numbers[index1];
        numbers[index1] = numbers[index2];
        numbers[index2] = temp;
    }
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值