How to find a unique array of repeating elements?

Creative Commons License Copyright: Attribution, allow others to create paper-based, and must distribute paper (based on the original license agreement with the same license Creative Commons )

(Array) Title:

    Numbers 1-1000 in the array contains 1001 elements, where there is only one element value is repeated, the other figures are only occur once. Design an algorithm to find duplicate elements speak out, it requires that each array element can only be accessed once. If you do not use an auxiliary storage space, the ability to design an algorithm?

analysis:

      First time seeing this problem, pay special attention to several conditions:

             1. Each array element can only be accessed once. (If you can access multiple times, it can slowly traversed over, but the time complexity would be increased)

             2. Do not use an auxiliary storage space (if you can use this auxiliary space problem, it becomes very easy)

             3. The array element (array number 1 to 1000 in 1001 contains the elements), so when the test method to be special attention

            By way of XOR, to a large extent solved the problem, not exclusive or concepts introduced a lot, can own Baidu. Specific details, to see the code.

Code:

    /**
     *
     * @param arr:
     * 数组
     * @return
     * 重复的元素
     */
    public static int findDup(int[] arr) {
        if (arr==null) return  -1;//如果if条件判断,只有一条语句,可以省略{}

        //声明空间,减少变量的声明
        int len=arr.length;
        int result=0;
        int i;

        //将数组中的所有异或运算
        for (i=0;i<len;i++){
            result^=arr[i];
        }
        //因为从数字1到1000,所以我在这里借助1:1000的数字去和数组的元素异或运算
        for (i=1;i<len;i++){
            result^=i;
        }
        //返回重复元素的值
        return result;
    }

 

Guess you like

Origin blog.csdn.net/longyanchen/article/details/92968405