`

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.

给定一个长度为n + 1的数组nums[],里面的元素nums[i]都在1到n之间,只有一个重复元素,让我们找到这个元素,空间复杂度为O(1),时间复杂度不多于O(n^2)。我们可以将数组排序,然后通过二分法找到重复的元素,排序之后,如果中间的元素的值小于或等于中间元素的下标,即nums[m] <= m, 说明重复的元素肯定在m的左边(因为元素的值是从1开始,如果左边没有重复元素,所以中间元素的值肯定会大于中间元素的下标。),让右指针变为m - 1; 否则让左指针变为m+1。这样时间复杂度为O(nlogn)。代码如下:
public class Solution {
    public int findDuplicate(int[] nums) {
        Arrays.sort(nums);
        int l = 0; 
        int r = nums.length - 1;
        while(l < r) {
            int m = l + (r - l) / 2;
            if(nums[m] <= m) {
                r = m - 1;
            } else {
                l = m + 1;
            }
        }
        return nums[l];
    }
}


还有一个很巧妙的方法,只需要O(n)的时间复杂度。我们从第一个元素开始,如果nums[nums[i]]大于0,就把nums[nums[i]]设定为负数,因为只有一个元素重复,当我们往后处理,遇到nums[nums[i]]小于0,说明我们之前访问过这个元素,因此当前元素的值为重复的元素。代码如下:
public class Solution {
    public int findDuplicate(int[] nums) {
        int result = 0;
        for(int i = 0; i < nums.length; i++) {
            if(nums[Math.abs(nums[i])] > 0) {
                nums[Math.abs(nums[i])] = - nums[Math.abs(nums[i])];
            } else {
                result = Math.abs(nums[i]);
            }
        }
        return result;
    }
}
0
3
分享到:
评论

相关推荐

    lrucacheleetcode-LeetCode:复制和思考

    lru cache leetcode LeetCode copy ...Duplicate Number 指针 快慢指针,链表循环 20200529 198. House Robber 动态规划 如何确定子问题 20200525 20200525 20200525 20200525 20200525 20200525 $1 234

    LeetCode最全代码

    389 | [Find the Difference](https://leetcode.com/problems/find-the-difference/) | [C++](./C++/find-the-difference.cpp) [Python](./Python/find-the-difference.py) | _O(n)_ | _O(1)_ | Easy | | ...

    leetcode:LeetCode Top 100 Liked Questions | Top Interview Questions | LeetCode 用户最喜欢的100题 | 面试最容易被问到的题

    Find the Duplicate Number * 题意:n+1个数属于[1~n],找出重复的那个数 * 难度:Medium * 分类:Array, Two Pointers, Binary Search * 思路:如果nums[i]不在对应位置,则和对应位置交换。如果对应位置上也...

    leetcode338-books:图书

    Find the Duplicate Number * 题意:n+1个数属于[1~n],找出重复的那个数 * 难度:Medium * 分类:Array, Two Pointers, Binary Search * 思路:如果nums[i]不在对应位置,则和对应位置交换。如果对应位置上也为该数...

    Duplicate Email Remover 2.7

    Duplicate Email Remover (Add-... - Don't forget to provide the product registration number: this will allow faster processing of your request. You can contact the technical support service online at ...

    计算机网络第六版答案

    27. Creation of a botnet requires an attacker to find vulnerability in some application or system (e.g. exploiting the buffer overflow vulnerability that might exist in an application). After finding ...

    微软内部资料-SQL性能优化5

    However, if we are searching for multiple rows, such as duplicate values, or keys in a range, anything more than a small number of rows will make the nonclustered index search very inefficient. ...

    a project model for the FreeBSD Project.7z

    Because some committers work on different parts, the total number in the committers section of the triangle is higher than in the above triangle. The kernel is the main building block of FreeBSD. ...

    BobBuilder_app

    So a look-up for a key just compares the first keys in the page list to find the page required and gets the key from the page's dictionary. MGIndex is O(log M)+O(1), M being N / PageItemCount ...

    Monarch Butterfly Optimization

    This is used by each optimization method to compute the average cost of the population and to count the number of legal (feasible) individuals. This code is the same as Dan Simon. The original one are...

    VclZip pro v3.10.1

    - Improved memory performance when working with archives containing extremely high number of compressed files. ==================== Version 3.06 Build 2 Made Delphi 2005 compatible Other assorted ...

    acpi控制笔记本风扇转速

    Added the AcpiGpeCount global that tracks the number of processed GPEs, to be used for debugging systems with a large number of ACPI interrupts. Implemented support for the "DMAR" ACPI table (DMA ...

    Delphi7.1 Update

    * When multiple indexes are included with the data from a provider, the IndexDef entries in the TClientDataset will show duplicate ‘Fields‘ and ‘DescFields‘ values (Quality Central 7543)....

    php.ini-development

    The number of significant digits displayed in floating point numbers. ; http://php.net/precision precision = 14 ; Output buffering is a mechanism for controlling how much output data ; (excluding ...

    cpp-算法精粹

    Find Minimum in Rotated Sorted Array II Median of Two Sorted Arrays H-Index II 暴力枚举法 Subsets Subsets II Permutations Permutations II Combinations Letter Combinations of a Phone Number 广度优先...

    leetcode2-DSA-problems-solutions:DSA-问题-解决方案

    (Find_The_Duplicate_Number) 在不使用额外空间或排序算法的情况下对 0 的 1 的 2 的数组进行排序 (Sort_Colors) 重复和缺失号码 (Repeat_And_Missing_Number) 在没有额外空间的情况下合并两个已排序的数组 (Merge_...

    ICS delphixe10源码版

    The latest versions of ICS can be downloaded from the ICS Wiki web site: http://wiki.overbyte.be/wiki/index.php/ICS_Download ICS V5 and V6 are archive releases no longer updated, last supported ...

    997leetcodec-myleetcode:我的leetcode解决方案

    287-find-the-duplicate-number.c 和弗洛伊德的龟兔赛跑(循环检测)算法。 (完毕) 使用哈希表更新 496-next-greater-element-ic。 (完毕) 使用优化算法更新 798-smallest-rotation-with-highest-score.c。 ...

    javalruleetcode-shy:害羞的

    number in array given a sorted array, rotated at a pivot, find the maximum element what is encapsulation(封装) 大部分时间在问general behavior question。 比如要是组里有人不工作怎么办, 工作如果没法在...

    FastReport.v4.15 for.Delphi.BCB.Full.Source企业版含ClientServer中文修正版支持D4-XE5

    + improved number formats processing in the BIFF export + added property DataOnly to exports + added property TfrxODFExport.SingleSheet + added property TfrxSimpleTextExport.DeleteEmptyColumns + added...

Global site tag (gtag.js) - Google Analytics