数组中的重复数字

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:
1. You must not modify the array (assume the array is read only).
2. You must use only constant, O(1) extra space.
3. Your runtime complexity should be less than O(n2).
4. There is only one duplicate number in the array, but it could be repeated more than once.
利用鸽巢原理(n个鸽子放到n-1个笼子中一定有一个笼子里面有两个鸽子),使用二分查找找到重复的数字,1~n范围的数,首先找到中位数mid,然后遍历数组看看数组中有多少个小于等于mid的数count,如果count > mid说明重复数在1~mid中,否则在mid+1~n中。

public class Solution {
    public int findDuplicate(int[] nums) {
        int left = 1, right = nums.length;
        int mid = left + (right-left)/2;
        while(left < right ){
            int count = 0;
            for(int i = 0; i < nums.length; i++){
                if(mid >= nums[i])   count++;
            }
            if(count > mid) right = mid;
            else left = mid + 1;
            mid = left + (right - left)/2;
        }
        return left;
    }
}

Leetcode 442. Find All Duplicates in an Array 找出数组中的所有重复数字(剑指offer 51)
Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements that appear twice in this array.
Could you do it without extra space and in O(n) runtime?
Example:
Input:
[4,3,2,7,8,2,3,1]

Output:
[2,3]
遍历数组,出现了什么数就改变以这个数当做index的位置的值(是负数就已经存在了,是正数就设成负数)

public class Solution {
    public List<Integer> findDuplicates(int[] nums) {
        List<Integer> res = new ArrayList<Integer>();
        for(int i = 0; i < nums.length; i++){
            int index = Math.abs(nums[i]) - 1; 
            if(nums[index] > 0) nums[index] = -nums[index];
            else if(nums[index] < 0) res.add(index + 1);
        }
        return res;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值