• 剑指offer 数组中重复的数


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

    思路:1、暴力法:直接遍历一遍,使用哈希map存储元素,然后找到第一个value值大于1的元素。

    2、非常巧妙的方法,剑指offer书上。

    1、判断输入数组有无元素非法

    2、从头扫到尾,只要当前元素值与下标不同,就做一次判断,numbers[i]与numbers[numbers[i]],相等就认为找到了重复元素,返回true,否则就交换两者,继续循环。直到最后还没找到认为没找到重复元素,返回false 数组中的元素最多只能交换2次就能有序,所以时间复杂度是常数空间复杂度。

    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 == nullptr){
                return false;
            }
            for(int i = 0;i < length;++i){
                while(numbers[i] != i){
                    if(numbers[i] == numbers[numbers[i]]){
                        * duplication = numbers[i];
                        return true;
                    }
                    swap(numbers[i],numbers[numbers[i]]);
                }
            }
            return false;
        }
    };
  • 相关阅读:
    大话设计模式--第六章 装饰模式
    大话设计模式--第五章 依赖倒置原则
    Linux—文件管理
    Linux—系统管理
    Mysql—添加用户并授权
    Linux—文件权限管理(chmod、chown、chgrp)
    Linux—管理用户、用户组及权限
    Mysql—修改用户密码(重置密码)
    Linux—编译安装详解
    Python—实现sftp客户端(连接远程服务器)
  • 原文地址:https://www.cnblogs.com/dingxiaoqiang/p/7505217.html
Copyright © 2020-2023  润新知