zoukankan      html  css  js  c++  java
  • [leetcode] 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-n之间,我们利用二分查找方法,初始化left = 1, right = n, 不防假设重复数字为mid = (left + right)/2.然后遍历数组,计算小于等于mid的元素个数num,若num > mid,则只需在left和mid-1之间查找重复的数,否则在mid+1和right之间查找重复的数。当不满足循环条件left <= right时,整数left即为要查找的重复的数。

    Java代码如下:

        public int findDuplicate(int[] nums) {
            int left = 1;
            int right = nums.length - 1;
            while (left <= right) {
                int mid = (left + right)/2;
                int num = countNum(nums, mid);
                if (num > mid) {
                    right = mid - 1;
                } else {
                    left = mid + 1;
                }
            }
            return left;
        }
        public int countNum(int[] nums, int target) {
            int sum =0;
            for (int i = 0; i < nums.length; i++) {
                if (nums[i] <= target) {
                    sum++;
                }
            }
            return sum;
        }
  • 相关阅读:
    List的Select 和Select().tolist()
    lambda中FirstOrDefault和First
    EF时,数据库字段和实体类不一致问题
    用户变量问题
    实验十二:字符串和结构
    实验十一:指针(2)
    实验十:指针(1)
    实验九:二维数组和字符数组的应用
    实验八:一维数组的应用
    实验七:函数及数组(1)
  • 原文地址:https://www.cnblogs.com/lasclocker/p/4929873.html
Copyright © 2011-2022 走看看