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;
        }
    };
    
  • 相关阅读:
    C# 还原SQL数据库(非存储过程方式)
    C# 无边框窗体移动代码
    SQL 2008 R2 数据库镜像操作
    序列号
    Oracle VM VirtualBox 随系统自动启动虚拟机的方法
    SQL每个用户最后的一条记录
    JS判断是否在微信浏览器打开
    使用device.js检测设备并实现不同设备展示不同网页
    check单选框多个全选与取消全选
    判断滚动是否到达底部
  • 原文地址:https://www.cnblogs.com/whiteBear/p/12650051.html
Copyright © 2011-2022 走看看