数组有N+M个数字, 数字的范围为1 ... N, 打印重复的元素, 要求O(M + N), 空间复杂度O(1).
利用数组存储,如果重复了在对应位置设置为-1,逻辑上考虑清楚,代码尽量清晰
#include <iostream> using namespace std; //数组有N+M个数字, 数字的范围为1 ... N, 打印重复的元素, 要求O(M + N), 空间复杂度O(1)。 void PrintRepeatedNum(int arr[], int n) { for (int pos = 0; pos < n; ++pos) { if (arr[pos] == -1) continue; while (arr[pos] != pos + 1) { int swap_pos = arr[pos] - 1; if (arr[swap_pos] == -1) break; if (arr[swap_pos] == swap_pos + 1) { arr[swap_pos] = -1; cout << swap_pos + 1 << endl; break; } std::swap(arr[pos], arr[swap_pos]); } } } int main() { int arr[] = {8,5, 7, 6, 4, 2, 6, 8, 9, 3, 1, 6, 4, 2, 1, 7}; PrintRepeatedNum(arr, sizeof(arr)/4); return 1; }
Passion, patience, perseverance, keep it and move on.

浙公网安备 33010602011771号