zoukankan      html  css  js  c++  java
  • 数组中重复的数字

    题目描述

    在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。
    #include <iostream>
    #include <cstring>  //memset()
    #include <cstdlib>  // calloc
    using namespace std;
    // 思路 对数组进行遍历,将数组的值作为另一个数组得下标,
    //该下标对应的值加1,并赋值给一个变量
    //当这个变量的值大于1时就是要的结果
    class Solution {
    public:
    
        bool duplicate(int numbers[], int length, int* duplication) {
    
            if (length <= 0 || numbers == NULL)
                return false;
    //       int arr2[length+1];
    //       for(int i = 0; i < length+1; i++)
    //            arr2[i] = 0;
           int *arr2 = (int *)calloc(length, sizeof(int));
           int temp = 0;
           for(int i = 0; i < length; i++)
           {
               arr2[numbers[i]]++;
               temp = arr2[numbers[i]];
               if (temp > 1)
               {
                   *duplication = numbers[i];
                   break;
               }
           }
           if (temp > 1)
            return true;
           else
            return false;
        }
    };
    int main(void)
    {
        Solution s;
        int length = 5;
        int duplication;
        int numbers[length] = {2,4,2,1,4};
        bool falg = s.duplicate(numbers,length, &duplication);
        cout << duplication;
    
        return 0;
    }
  • 相关阅读:
    Docker简介
    分类技术
    龙果支付系统
    [徐培成系列实战课程]docker篇
    高手速成android开源项目【developer篇】
    高手速成android开源项目【项目篇】
    高手速成android开源项目【tool篇】
    高手速成android开源项目【View篇】
    JAVA代理分析
    程序员的2013回顾及2014钱途
  • 原文地址:https://www.cnblogs.com/xiaokang01/p/12380223.html
Copyright © 2011-2022 走看看