• 数组中重复的数字


    思路:

    以数组{2,3,1,0,2,5,3}为例来分析找重复数字的步骤。

    第0个数字是2,与下标不相等,把它和下标为2的数字交换,得到:{1,3,2,0,2,5,3};

    第0个数字是1,仍与下标不相等,把它和下标为1的数字交换,得到:{3,1,2,0,2,5,3};

    第0个数字是3,仍与下标不相等,把它和下标为3的数字交换,得到:{0,1,2,3,2,5,3};

    第0个数字是0,与下标相等,继续下一位;

    第1位和1相等,继续下一位;

    第2位和2相等,继续下一位;

    第3位和3相等,继续;

    第4位是2,与下标不相等,要将它和第二位数字交换,但是此时的第二位数字也是2,出现重复的数字了,返回函数,找到重复的数字了。

     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(numbers==nullptr || length<=0) return false;
    11         for(int i=0;i<length;i++){
    12             if(numbers[i]>length-1) return false;
    13         }
    14         for(int i=0;i<length;i++){
    15             while(numbers[i]!=i){
    16                 if(numbers[i]==numbers[numbers[i]]){
    17                     *duplication = numbers[i];
    18                     return true;
    19                 }
    20                 //交换mubers[i] 和 numbers[numbers[i]]
    21                 int temp=numbers[i];
    22                 numbers[i]=numbers[temp];
    23                 numbers[temp] = temp;
    24             }
    25         }
    26         return false;
    27     }
    28 };
  • 相关阅读:
    短连接生成
    google 定位 标记 地址解码 逆解码
    Laravel 文件上传
    Laravel
    对接航信开票-在线二维码开票
    win 下 composer 安装
    对接美团外卖开放平台
    IOS 弹框在微信中导致输入框等失焦 偏移问题解决
    微信公众号-高德地图实例
    对接百度地图API 实现地址转经纬度
  • 原文地址:https://www.cnblogs.com/pacino12134/p/11238006.html
Copyright © 2020-2023  润新知