• 数组中重复的数字


    题目描述

    在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是重复的数字2或者3。
     
    正常思路:用一个bit类型的数组,   长度为n的数组,假如遍历到了3,那就把arr[3]设置为1,下一次又找到3了,看arr[3]为1.说明3出现过了 ,没有出现过就arr[2]设置为1
    这个时间复杂度为O(N)空间复杂度为O(N)。     可以使用本身的数组,不申请辅助空间,这样时间复杂度为n,空间复杂度为1.
    思路:把从前到后的每一个数当做是数组的索引来用,通过这个索引找到那个位置,把那个位置上的数字加上n。从前往后遍历的过程中找索引的时候,遇到比n大的数字,就把他减去n,当做索引(数组里的数字不变,只是用数组里的数字减去n当做索引来找数组中的位置),在通过索引找数时,如果发现找到的这位已经是大于n的了,那说明之前通过同样的索引已经找到过他了,又因为索引是从数组中找的,那么肯定数组中一定有两个相同的,那就是这个索引。
     
    时间复杂度O(N),空间复杂度O(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) {
    
            for(int i=0;i<length;i++){
                int index=numbers[i];
                if(index>=length){
                   index-=length;
                }
                if(numbers[index]>length){
                    duplication[0]=index;
                    return true;
                }else{
                    numbers[index]+=length;
                }
            }
            duplication[0]=-1;
            return false;
    
        }
    }
        
  • 相关阅读:
    Blazor使用Chrome远程调试
    Blazor登录Ids4
    Jenkins + Coding 构建 Docker Image 并自动上传至Docker Registry
    EFK 数据生命周期
    EFK (Elasticsearch + Fluentd + Kibana) 日志分析系统
    通过Nginx代理Grafana,并通过域名访问
    Prometheus搜集mysql和nginx log指标
    java 线程相关(4)
    java 并发相关(5)
    java 线程相关(3)
  • 原文地址:https://www.cnblogs.com/tobemaster/p/5926673.html
Copyright © 2020-2023  润新知