zoukankan      html  css  js  c++  java
  • 剑指offer-数组中重复的数字

     

    题目描述

     
    在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。
     

    解题思路

    首先想到可用一个hash数组来记录0~n-1个数字出现的次数,这种解法的时间复杂度为O(n),空间复杂度为O(n)。考虑一种空间复杂度为O(1)的解法,因为该数组中所有数字均在0~n-1之间,如果按照下标分配数字,若无重复数字,则每个数字均对应其所在位置的下标。因此可以从第一个数字开始,检查该数字是否和下标相等,若不等就和该数字作为下标位置的数字交换,这样就把一个数字放到了它对应的位置。接着检查交换后的数字是否和下标相等,若不等重复上述操作。这样遍历并交换下去,直到发现一个数字与它作为下标位置上的数字相等,就发现了一个重复数字。这种解法每次交换至少把一个数字交换到对应位置上去,所以时间复杂度为O(n)

    代码

     1 class Solution {
     2 public:
     3     // Parameters:
     4     //        numbers:     an array of integers
     5     //        length:      the length of array numbers
     6     //        duplication: (Output) the duplicated number in the array number
     7     // Return value:       true if the input is valid, and there are some duplications in the array number
     8     //                     otherwise false
     9     bool duplicate(int numbers[], int length, int* duplication) {
    10         if(length <= 0||numbers == NULL)
    11             return false;
    12         for(int i=0;i<length;i++){
    13             while(numbers[i]!=i){
    14                 if(numbers[i]==numbers[numbers[i]]){
    15                     *duplication=numbers[i];
    16                     return true;
    17                 }
    18                 else
    19                     swap(numbers[i],numbers[numbers[i]]);
    20             }
    21         }
    22         return false;
    23     }
    24 };
  • 相关阅读:
    值得学习的东西
    【单调队列】转载
    dom基础3 — 简易版template.js
    js基础6 — 数组对象
    js基础6 — 字符串基本操作
    js基础5 — 将十六进制颜色转为rgba()
    js基础4 — 数组操作
    placeholer属性修改
    clipboard.js实现复制到剪切板
    JS 获取指定日期在当年的第几周
  • 原文地址:https://www.cnblogs.com/wmx24/p/8880497.html
Copyright © 2011-2022 走看看