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

    题目描述
    在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。
     
    解题思路:从头开始遍历数组,例如2 3 1 0 2 5 3
    遍历到2 i != a[i] 交换i和a[i]位置的数字 变为 1 3 2 0 2 5 3
    1 交换变为 3 1 2 0 2 5 3
    3 交换变为 0 1 2 3 2 5 3
    一直遍历直到 2  2 == a[a[2]] 存入2 返回true
    全部遍历完返回false
     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)
    11             return false;
    12         for(int i=0;i<length;i++)
    13         {
    14             if(numbers[i] <0 || numbers[i]>length-1)
    15             {
    16                 return false;
    17             }
    18         }
    19         for(int i=0;i<length;i++)
    20         {
    21             while(numbers[i] != i)
    22             {
    23                 if(numbers[i] == numbers[numbers[i]])
    24                 {
    25                     *duplication = numbers[i];
    26                     return true;
    27                 }
    28                 //交换
    29                 int temp = numbers[i];
    30                 numbers[i] = numbers[temp];
    31                 numbers[temp] = temp;
    32             }
    33         }
    34         return false;
    35     }
    36 };
  • 相关阅读:
    3.3测试复盘
    计算机网络-运输层面试题整理
    3.2专项测试复盘
    2.27专项测试复盘
    2.26排序专项测试复盘
    2.25专项测试复盘
    前端基础笔记1
    2.24专项测试复盘
    2.23专项测试复盘
    更新pip报错AttributeError: 'NoneType' object has no attribute 'bytes'
  • 原文地址:https://www.cnblogs.com/qqky/p/7084602.html
Copyright © 2011-2022 走看看