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

    题目描述

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

    解题思路

    数组大小是n,且数组中的数字是[0,n-1]范围的,那么如果所有数字都不同的话,每个数字能放自己对应的位置,比如0,存放在数组第0个位置。所以每次只要调整数字到正确的位置即可,如果调整位置上已经是正确的数字,说明该数字已经重复了,输出该数即可。

    实现

    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) {
            if (numbers == null || numbers.length <=0 ||
                    numbers.length != length || duplication == null || duplication.length <= 0)
                return false;
    
            int index = 0;
            while (index < length){
                if (numbers[index] != index){
                    //调整位置
                    int t = numbers[index];
                    if (numbers[t] != t){
                        numbers[index] = numbers[t];
                        numbers[t] = t;
                    }else {
                        //重复
                        duplication[0] = t;
                        return true;
                    }
                }else {
                    index ++;
                }
            }
            return false;
        }
    }
    
  • 相关阅读:
    BBS
    BBS
    BBS
    BBS
    6.1
    Django
    Django
    tomcat——启动项目报错:java.lang.IllegalStateException
    Java——java.lang.NullPointerException
    Java——反射三种方式的效率对比
  • 原文地址:https://www.cnblogs.com/ggmfengyangdi/p/5809524.html
Copyright © 2011-2022 走看看