• 数组中重复的数字


    时间限制: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;
        }
    };
    
  • 相关阅读:
    chrome扩展程序开发之在目标页面运行自己的JS
    微信JSSDK接口,previewImage
    js加减乘除丢失精度
    java jdbc/ojdbc 链接oracle的三种方式
    Navicat 提示Cannot create oci environment 解决方案
    jquery ajax 回调函数
    时间日期标识符
    SSIS从理论到实战,再到应用
    Business Intelligence——SSIS项目从创建到部署的简单总结(二)
    Business Intelligence——SSIS项目从创建到部署的简单总结(一)
  • 原文地址:https://www.cnblogs.com/whiteBear/p/12650051.html
Copyright © 2020-2023  润新知