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;
        }
  • 相关阅读:
    @ExceptionHandler
    使用Vue.extend实现iview Upload在单文件上传时,拖拽多个文件给出错误提示
    spring 常用的注入方式
    SpringMVC框架
    Redis
    事务的隔离性以及隔离级别
    Qt的获取和安装
    C++ 指针delete 及 指针delete后赋值为NULL
    图形流水线
    freeglut的安装步骤
  • 原文地址:https://www.cnblogs.com/lasclocker/p/4929873.html
Copyright © 2011-2022 走看看