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

    题目描述

    在一个长度为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;
    
        }
    }
        
  • 相关阅读:
    数字相加
    大道至简第一章读后感 Java伪代码形式
    大道至简读后感
    listview解决滑动条目的时候背景变为黑色的问题
    安卓获取线程id
    安卓无法生成R文件原因
    eclipse安卓引入库项目的正确方法
    07-09 07:28:38.350: E/AndroidRuntime(1437): Caused by: java.lang.ClassNotFoundException: Didn't find class "com.example.googleplay.ui.activity.MainActivity" on path: DexPathList[[zip file "/data/app/c
    ActionBar更改背景颜色(主题)
    dip2px
  • 原文地址:https://www.cnblogs.com/tobemaster/p/5926673.html
Copyright © 2011-2022 走看看