Prove safety offer-- repeated digital array (C ++)

Description Title: In an array of length n, where all numbers are in the range 0 to n-1. Some digital array is duplicated, but do not know how many numbers are repetitive and do not know each number is repeated several times, find duplicate any of the array of numbers.
**

(Time complexity of O (n), the spatial complexity is O (1)

**

Just saw this topic when the first thought is to first array sorted, then you can get out before and after results. But this way, then, the time complexity will be relatively large, and later saw to explain, but also do not understand the beginning, after some pondering understand.

Ideas: this is called an array of numbers, first of all, this is a disordered array, but all the elements are in the range [0, n-1]
In other words, if the array is ordered , then the i-th position the number should be equal to i, i.e. numbers [I] = I . But if Numbers [i] i is not equal to it, such as the following FIGS, divided into two cases:


So, this is actually a sort, but different from the usual sort, but looking for repeat ordering digital process, then attach the code.

class Solution {
public:
      Solution() {
 }
public:
      bool duplicate(vector<int> numbers,int *duplication) {
           if (numbers.size() <= 0) {
               return false;
           }
      for (int i = 0; i < numbers.size(); i++) {
           if (numbers[i] == i) {
               continue;
           }
           else if (numbers[i] != i) {
                if (numbers[i] == numbers[numbers[i]]) {
                    //重复了
                   *duplication = numbers[i];   //获取重复的数字
                    return true;
           }
                if (numbers[i] != numbers[numbers[i]]) {
                    int temp = numbers[i];        //交换位置
                    numbers[i] = numbers[numbers[i]];
                    numbers[numbers[i]] = temp;
                   }
         }
  }
         return false;   //没有重复的数字
  }
 };

**测试:**
int main() {
    vector<int> numbers;
    for (int i = 0; i < 10; i++) {
         numbers.push_back(i);
    }
    numbers.push_back(6);    
    numbers.push_back(3);
    Solution obj;
    int duplication;
    if (obj.duplicate(numbers, &duplication)) {
        cout << "重复的数字:  " << duplication << endl;
    }
    else {
       cout << "没有重复的数字. " << endl;
    }
    system("pause");
    return 0;
 }

Here Insert Picture Description

Released five original articles · won praise 1 · views 304

Guess you like

Origin blog.csdn.net/PPprogrammer/article/details/104032840