题目三:数组中重复的数字

题目一:数组中重复的数字

分析

题目一:数组中重复的数字

代码

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){
            duplication[0]=-1;
            return false;
        }
        for(int i=0;i<numbers.length;i++){
            while (numbers[i]!=i){
                int index = numbers[i];
                if(numbers[index]==index){
                    duplication[0]=index;
                    return true;
                }
                int temp=numbers[index];
                numbers[index]=index;
                numbers[i]=temp;
            }
        }
        duplication[0]=-1;
        return false;
    }
}

题目二:不修改数组找出重复的数字

在一个长度为n+1的数组里的所有数字都在1~n的范围内,所以数组中至少有一个数字是重复的。请找出数组中任意一个重复的数字,但是不能修改输入的数组。例如,如果输入长度为8的数组{2,3,5,4,3,2,6,7},那么对应的输出是重复的数字2或者3。

代码

public class Problem {
    final Integer integer = 123;
    final String str = "123";
    public static void main(String[] args) {
        Problem p=new Problem();
        System.out.println(p.getDuplication(new int[]{2,3,5,4,3,2,6,7}));
    }
    public int getDuplication(int[] arr) {
        if(arr==null||arr.length<=0){
            return 0;
        }
        int start = 1;
        int end = arr.length-1;
        while(end >= start) {
            int middle = (end+start)>>1;
            int count = countRange(arr,start,middle);
            if(end == start) {
                if(count > 1)
                    return start;
                else
                    break;
            }
            if(count > (middle-start+1)){//说明(start,middle)这个区间有重复的数
                end = middle;
            }
            else{////说明(middle+1,end)这个区间有重复的数
                start=middle+1;
            }
        }
        return -1;
    }

    private int countRange(int[] array, int low, int high) {
        int count = 0;
        for(int i = 0;i < array.length;i++)
        {
            if(array[i] >= low && array[i] <= high)
                ++count;
        }
        return count;
    }
}
posted @ 2018-04-09 22:03  baixiaoshuai  阅读(130)  评论(0编辑  收藏  举报