Find the Duplicate Number

来源:互联网 发布:风险矩阵应用 编辑:程序博客网 时间:2024/06/05 04:58

leetcode 287. Find the Duplicate Number


问题描述

Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.

Note:

You must not modify the array (assume the array is read only).You must use only constant, O(1) extra space.Your runtime complexity should be less than O(n2).There is only one duplicate number in the array, but it could be repeated more than once.

七月算法思路

可以利用二进制数字可以散列的思想,找出这个数就需要和如果没有这个数的情况做出比较,可以通过二进制判断其每一位是否为1,时间复杂度是nlogn.

//发现数组中相同的元素,既然数组中的书都在1...n-1之间    public int findDuplicate(int []nums) {        int n = nums.length - 1;        int dup = 0;        for (int i = 0;(n >> i) != 0;i++) {            int indeed = 0;            //实际中每一位的大小            for (int j = 0;j <= n;j++) {                if (((nums[j] >> i) & 1) == 1) {                    indeed++;                }            }            //每一位本应该的大小            int should = 0;            for (int j = 1;j <= n;j++) {                if (((j >> i) & 1) == 1) {                    should++;                }            }            if (indeed > should) {                dup |= (1 << i);            }        }        return dup;    }*/

但这种方法毕竟不是很容易想到,我们在搜索的时候是不是可以想象二分搜索,当然这个时候就不会要求其数组有序了。

public int findDuplicate(int []nums) {        //利用二分查找的思想        int left = 0;        int right = nums.length - 1;        while (left < right) {            int mid = (left + right) >> 1;            int count = 0;            for (int i = left;i <= mid;i++) {                if (nums[i] >= left && nums[i] <= mid) {                    count++;                }                if (count > (mid - left + 1)) {                    right = mid;                } else {                    left = mid + 1;                }            }        }        return nums[left];    }

从这个问题中我们可以看到如何找出数组元素的重复数,不过如果其数范围不在这个区间内,可以先做一下映射,java中map可以帮助我们找到这一点,不过我想让我们的map根据value值找到其key值好像也不是那么的简单,感兴趣的人可以教教我。我是根据value做了个map的映射。

public int findDuplicate(int []nums) {        Map<Integer,Integer> map = new HashMap<Integer, Integer>();        Map<Integer, Integer> mapValue = new HashMap<Integer,Integer>();        mapNumber(nums,map,mapValue);        //利用二分查找的思想        int left = 1;        int right = nums.length - 1;        while (left < right) {            int mid = (left + right) >> 1;            int count = 0;            for (int i = 0;i < nums.length;i++) {                if (nums[i] >= left && nums[i] <= mid) {                    count++;                }            }            if (count > (mid - left + 1)) {                right = mid;            } else {                left = mid + 1;            }        }//      return left;        return mapValue.get(left);    }
0 0
原创粉丝点击