zoukankan      html  css  js  c++  java
  • 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.

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/find-the-duplicate-number
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    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.

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/find-the-duplicate-number
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    我个人是觉得,这道题很容易忽略最后一个条件,所以以为1~n+1中的每个数都至少出现一次。所以,一开始的思路就是,求和,差值自然就是重复的数。然而现实很骨感,弄了挺久才发下自己没过的原因居然是看漏了条件。。。

    废话少说,题目中要求找出重复的数,并没有要求求出重复的下标,因此我的思路是把数组排序,那么重复的自然是相邻的。可以设两个游标,当当前对比的两个相邻的数不相等时,两个游标同时右移,直到找到重复的数,就返回该数。

    代码如下:

    public int findDuplicate(int[] nums) {
            Arrays.sort(nums);
            int length = nums.length;
            int start = 0;
            for(int i = 1; i < length; i = start+1)
            {
                if(nums[i] == nums[start])
                {
                    return nums[i];
                }
                else
                {
                    start++;
                }
            }
            return -1;
    
        }
  • 相关阅读:
    VMware 11安装Mac OS X 10.10 (转载)
    ios]企业开发者账号申请
    SQL SERVER sa无法登陆的问题
    接触Ubuntu的第一周大致总结
    疯狂VirtualBox实战讲学录 以及 virtualbox完全学习手册 之我见
    必须使用角色管理工具 安装或配置microsoft.net framework 3.5
    02_brk/sbrk
    How to install qt5.9
    026_pickle
    024_iterator
  • 原文地址:https://www.cnblogs.com/WakingShaw/p/12051238.html
Copyright © 2011-2022 走看看