1.编写一个函数,该函数的功能是删除一维数组中所有相同的数,使之只剩一个。数组中的数已按由小到大的顺序排列,函数返回删除后数组中数据的个数。
时间: 2023-04-18 21:01:30 浏览: 114
可以使用双指针法,定义两个指针i和j,初始值都为,表示第一个元素。然后从第二个元素开始遍历数组,如果当前元素与前一个元素相同,则j指针不动,i指针继续向前移动,直到找到一个不同的元素,将这个元素复制到j+1的位置,然后j指针向前移动一位,i指针继续向前移动,重复上述过程,直到遍历完整个数组。
具体实现如下:
int removeDuplicates(int* nums, int numsSize) {
if (numsSize == ) return ;
int i = , j = ;
while (i < numsSize) {
if (nums[i] == nums[j]) {
i++;
} else {
nums[++j] = nums[i++];
}
}
return j + 1;
}
其中,numsSize表示数组的长度,nums是指向数组的指针。函数返回删除后数组中数据的个数,即j+1。
相关问题
1. 请编写函数fiun, 函数的功能是:删去一维数组中所有相同的数,使之只剩一个。函数返回删除后数组中数据的个数。主函数中输出删除前后数组中所有的元素。
```c++
#include <iostream>
#include <unordered_set>
// 定义函数 fiun 清除数组中重复的元素并返回剩余元素的数量
int removeDuplicates(int arr[], int n) {
std::unordered_set<int> uniqueSet;
int count = 0;
// 遍历数组,将每个元素添加到集合中,如果元素已存在则跳过
for (int i = 0; i < n; ++i) {
if (uniqueSet.find(arr[i]) == uniqueSet.end()) {
uniqueSet.insert(arr[i]);
count++;
}
}
return count;
}
// 主函数展示删除前后的数组内容
void displayArray(int* arr, int nBefore, int* newArr, int nAfter) {
std::cout << "Original array with duplicates: ";
for (int i = 0; i < nBefore; ++i) {
std::cout << arr[i] << " ";
}
std::cout << "\n";
std::cout << "Array after removing duplicates: ";
for (int i = 0; i < nAfter; ++i) {
std::cout << newArr[i] << " ";
}
std::cout << "\n";
}
int main() {
int arr[] = {1, 2, 2, 3, 4, 4, 5};
int nBefore = sizeof(arr) / sizeof(arr[0]);
int* newArr = new int[removeDuplicates(arr, nBefore)];
int nAfter = sizeof(newArr) / sizeof(newArr[0]);
displayArray(arr, nBefore, newArr, nAfter);
delete[] newArr; // 释放新数组内存
return 0;
}
```
这个程序首先创建了一个函数 `removeDuplicates`,它使用了 C++ 的 `std::unordered_set` 来存储数组中唯一的元素。接着,在 `main` 函数中,我们分配一个新的数组 `newArr` 存储经过处理后的结果,并显示原始数组和去重后的新数组。
注意:此代码中的 `new[]` 和 `delete[]` 是 C++ 中动态内存分配的典型用法,用于处理需要预先确定大小的情况。在实际应用中,记得处理好内存管理,避免内存泄漏。
请编写一个函数函数的功能是删去一维数组中所有相同的数,是指只剩一个数组中的数一按由大到小的顺序排序函数返回删除后数组中的数据的个数,C语言
在C语言中,你可以使用这样的函数来实现这个功能。首先,我们需要遍历数组,找到所有的不重复元素,并记录它们的下标。然后,我们可以按照数组中元素的大小进行排序,最后只保留最大值。以下是实现该功能的一个示例函数:
```c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <time.h> // 用于生成随机数组
// 函数声明
int uniqueAndSort(int arr[], int n);
void swap(int *a, int *b);
// 主函数
int main() {
srand(time(0));
int arr[] = {5, 2, 8, 2, 9, 5, 6, 3, 8};
int n = sizeof(arr) / sizeof(arr[0]);
int uniqueCount = uniqueAndSort(arr, n);
for (int i = 0; i < uniqueCount; i++) {
printf("%d ", arr[i]);
}
return 0;
}
// 删除并排序函数
int uniqueAndSort(int arr[], int n) {
int count = 0; // 记录唯一元素的数量
bool visited[n]; // 标记是否已访问过
// 遍历数组,找出唯一元素及其索引
for (int i = 0; i < n; i++) {
if (!visited[i]) {
visited[i] = true;
count++;
// 将未访问的元素移到新数组末尾
for (int j = n - 1; j >= i; j--) {
if (visited[j]) {
swap(&arr[count], &arr[j]);
}
}
}
}
// 对唯一元素降序排序
qsort(arr, count, sizeof(int), compareDescending);
return count;
}
// 比较函数,用于qsort降序排列
int compareDescending(const void *a, const void *b) {
return (*(const int*) b - *(const int*) a);
}
// 交换两个整数的值
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
阅读全文
相关推荐














