Donghua University computer problem-remove the same element in the array

Donghua University computer problem-remove the same element in the array

Topic description:
In an increasing ordered array, there are elements with the same value. The function of the program is to remove the elements with the same value, so that there are no duplicate elements in the array. For example (7, 10, 10, 21, 30, 42, 42, 42, 51) becomes (7, 10, 21, 30, 42, 51).

Method 1:
First determine that the array is increasing and ordered. Then only need to compare two adjacent elements. The idea of ​​direct insertion sort can be used here. If an inserted element exists in the array, it is not inserted. Using the idea of ​​direct sorting, its time complexity is o (n ^ 2) and space complexity is o (1).

#include<iostream>
using namespace std;
void sort(int num[], int n) {
	int temp;
	for (int i = 0;i < n - 1;i++) {
		for (int j = 0;j < n - i - 1;j++) {
			if (num[j] > num[j + 1]) {
				temp = num[j];
				num[j] = num[j + 1];
				num[j + 1] = temp;
			}
		}
	}
}
void deletSame(int num[], int n) {
	sort(num, n);
	int i, j;
	for (i = 0, j = 1;j < n;j++) {
		if (num[i] != num[j]) {
			num[++i] = num[j];
		}
	}
	for (int k = 0;k < (i + 1);k++)
		cout << num[k] << " ";
}
int main() {
	int n;
	cout << "输入数字个数:";
	cin >> n;
	int* num = new int[n];
	cout << "输入数组:";
	for (int i = 0;i < n;i++)
		cin >> num[i];
	deletSame(num, n);
	return 0;
}

Running test results:
Insert picture description here
Method 2:
Another way of thinking is to design an auxiliary array, design two pointers i and j to point to the original array and the auxiliary array, and compare the value in the original array and the value in the auxiliary array i ++, otherwise insert the data into the auxiliary array, the two pointers move back at the same time until the original array is traversed. Using the method of adding an auxiliary array, the time complexity is o (n) and the space complexity is o (n).

#include<iostream>
using namespace std;
void sort(int num[], int n) {
	int temp;
	for (int i = 0;i < n - 1;i++) {
		for (int j = 0;j < n - i - 1;j++) {
			if (num[j] > num[j + 1]) {
				temp = num[j];
				num[j] = num[j + 1];
				num[j + 1] = temp;
			}
		}
	}
}
void deletSame(int num[], int n) {
	sort(num, n);
	int i, j;
	int* fuzhu = new int[n];
	fuzhu[0] = num[0];
	for (i = 1, j = 0;i < n;i++) {
		if (num[i] != fuzhu[j]) {
			j++;
			fuzhu[j] = num[i];
		}
	}
	for (int k = 0;k <= j;k++)
		cout << fuzhu[k] << " ";
}
int main() {
	int n;
	cout << "输入数字个数:";
	cin >> n;
	int* num = new int[n];
	cout << "输入数组:";
	for (int i = 0;i < n;i++)
		cin >> num[i];
	deletSame(num, n);
	return 0;
}

Running test results:
Insert picture description here

Published 54 original articles · Liked 54 · Visits 3073

Guess you like

Origin blog.csdn.net/weixin_45295612/article/details/105407735