码迷,mamicode.com
首页 > 编程语言 > 详细

51、数组中重复的数

时间:2017-07-18 23:15:32      阅读:291      评论:0      收藏:0      [点我收藏+]

标签:数字   alt   page   param   ash   using   输入   .com   img   

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

https://www.nowcoder.com/practice/623a5ac0ea5b4e5f95552655361ae0a8?tpId=13&tqId=11203&tPage=3&rp=2&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking

思路:

 把数值放到对应的下标下,若对应的下标的元素和该值相等,出现重复。

注意:检查数组的值在0-n-1内

技术分享
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) {
        //way1.排序然后遍历时间O(nlogn)
        //way2.hashmap,o(n)的时间,o(n)的空间
        //way3.遍历数组和当前下标比较,并交换放到对于的下标下,直到发现重复的数。o(n)的时间,o(1)的空间
        if (numbers == null || numbers.length == 0) {
            return false;
        }
        for (int i = 0; i < numbers.length; i++) {
            //数字都在0到n-1的范围内
            if (numbers[i] < 0 || numbers[i] >= numbers.length ) {
                return false;
            }
        }
        for (int i = 0; i < numbers.length; i++) {
            //如果当前值和下标相等,就下一个
            if (numbers[i] == i) {
                continue;
            }
            //当前值和下标不等,且发现,当前值和对于下标的值相等,发现重复的数
            if (numbers[i] == numbers[numbers[i]]){
                duplication[0] = numbers[i];
                return true;
            }
            //将当前值放到对应的下标位置
            int temp = numbers[i];
            numbers[i] = numbers[temp];
            numbers[temp] = temp;
        }
        return false;
    
    }
}
View Code

 

测试:没有重复的元素;重复的元素有多个;重复的元素是最大或最小;数组元素不在0-n-1

51、数组中重复的数

标签:数字   alt   page   param   ash   using   输入   .com   img   

原文地址:http://www.cnblogs.com/lingli-meng/p/7203215.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!