zoukankan      html  css  js  c++  java
  • 数组中重复的数字

    时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M

    题目描述

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

    思路:

    • 依旧可以采用hash的方式对所有元素计数,将第一个hash表中数据超过1的输出
    class Solution {
    public:
        // Parameters:
        //        numbers:     an array of integers
        //        length:      the length of array numbers
        //        duplication: (Output) the duplicated number in the array number
        // Return value:       true if the input is valid, and there are some duplications in the array number
        //                     otherwise false
        bool duplicate(int numbers[], int length, int* duplication) {
            if(numbers == NULL || length < 0)
                return false;
            map<int,int> hash_map;
            for(int i =0;i < length;i++)
            {
                hash_map[numbers[i]] ++ ;
            }
            for(int i = 0;i < length;i++)
            {
                if(hash_map[numbers[i]]>1)
                {
                    *duplication = numbers[i];
                    return true;
                }
            }
            return false;
        }
    };
    
    • 另一种方法非常巧妙,不需要额外空间来储存数据,由于题目中对数组中的数字的范围保证在0~n-1之间,这也就是一个大的前提。当一个数字被访问过之后,可在以该元素为下标所对应的数据上加n,之后在遇到相同的数字时,由于以该元素下标所对应的数据已经大于或等于n,此时,就已经找到了该元素

    class Solution {
    public:
        // Parameters:
        //        numbers:     an array of integers
        //        length:      the length of array numbers
        //        duplication: (Output) the duplicated number in the array number
        // Return value:       true if the input is valid, and there are some duplications in the array number
        //                     otherwise false
        bool duplicate(int numbers[], int length, int* duplication) {
            if(numbers == NULL||length < 0)
                return false;
             
            for(int i = 0;i < length;i++)
            {
                int index = numbers[i];
                if(index >= length)
                {
                    index -= length;
                }
                if(numbers[index] >= length)
                {
                    *duplication= index;
                    return true;
                }
                numbers[index] = numbers[index] + length;
                 
            }
            return false;
        }
    };
    
  • 相关阅读:
    内存泄露检测工具之DMalloc
    五年后你在何方
    程序员技术练级攻略
    Windows编程革命简史
    su的时候密码认证失败的解决方法
    ruby 元编程 meta programming
    内存对齐分配策略(含位域模式)
    Ruby 之 Block, Proc, Lambda 联系区别,转载
    c++异常处理机制示例及讲解
    ruby 常见问题集 1 不断更新中
  • 原文地址:https://www.cnblogs.com/whiteBear/p/12650051.html
Copyright © 2011-2022 走看看