剑指Offer 数组中重复的数字

    xiaoxiao2022-07-02  97

     第一个双重循环用来查找重复数字,并改变其对应的标志;

    第二个循环用来查找第一个标志为重复的数字。

    class Solution { public: // Parameters: // numbers: an array of integers // length: the length of array numbers // duplication: (Output) the duplicated number in the array number // Return value: true if the input is valid, and there are some duplications in the array number // otherwise false bool duplicate(int numbers[], int length, int* duplication) { if(length <= 1) return false; int flag[length]; for(int i = 0; i < length; i++){ flag[i] = 0; //0表示未重复的,1表示存在重复的数字 for(int j = i+1; j < length; j++) //遍历寻找重复的数字 if(numbers[i] == numbers[j]){ //存在重复 flag[i] = 1; //标志为1 flag[j] = 1; //标志为1 } } for(int i = 0; i < length; i++){ //遍历,将碰到的第一个标志为1的重复数字输出 if(flag[i] == 1){ *duplication = numbers[i]; return true; } } return false; } };

     

    最新回复(0)