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;
    
        }
  • 相关阅读:
    workflow里xaml格式(备忘)
    Excel 读取
    自定义工作流活动的外观的两种方式(补充)
    用SQLite,Enterprise的报错
    WF 4.0
    升级 90天 vs2008 在win2008下。
    NUnitLite web下的用法
    screen常用方法 Lei
    中文摘要的写法 Lei
    bootstrap, boosting, bagging 几种方法的联系 Lei
  • 原文地址:https://www.cnblogs.com/WakingShaw/p/12051238.html
Copyright © 2011-2022 走看看